Archilyzer · Source

archilyzer

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

commit a583597c48a719f1f47e70051392c5753a6eed27
parent 8ef019cc2020d081a10b13bd42dd423ee3a8d0e4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:50:19 -0500

Merge main into lane/network-exits

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

Diffstat:
MCOMMANDS.md | 40++++++++++++++++++++++++++++++----------
MENVIRONMENT.md | 5+++--
MOPERATING.md | 214++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
MSETTINGS.md | 6+++++-
Mcommon/bin/_cli.ts | 9+++++++++
Mcommon/bin/migrate-media-tier.test.ts | 23+++++++++++++++++++++++
Mcommon/bin/migrate-media-tier.ts | 26+++++++++++++++++++++++++-
Mcommon/controller/adoptLocalMediaReference.ts | 15++++++++++++++-
Mcommon/controller/archiveOrgDownload.ts | 4+++-
Mcommon/controller/buildIndex.test.ts | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/buildIndex.ts | 64+++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/controller/buildStats.ts | 4+++-
Mcommon/controller/capturePosts.ts | 34++++++++++++++++++++++++++--------
Mcommon/controller/channelSnapshot.test.ts | 34++++++++++++++++++++++++++++++++++
Mcommon/controller/channelSnapshot.ts | 4+++-
Mcommon/controller/checkKeptDeleted.ts | 11++++++++++-
Mcommon/controller/checkPostAvailability.ts | 3+++
Mcommon/controller/cleanAudioFromTranscribed.ts | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/cleanAudioJob.ts | 37+++++++++++++++++++++++++++++++++----
Mcommon/controller/cleanUnchecked.test.ts | 4++++
Acommon/controller/compressText.captions.test.ts | 397+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/compressText.ts | 643+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mcommon/controller/copies.test.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/copiesLane.ts | 44+++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/copiesScan.ts | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/controller/duplicateShorts.ts | 4+++-
Mcommon/controller/fetchOlderPosts.test.ts | 5++---
Mcommon/controller/fetchPosts.test.ts | 34+++++++++++++++++++++++++++++++---
Mcommon/controller/fetchPosts.ts | 12++++++++++++
Mcommon/controller/fetchWindows.test.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 48+++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/findClips.ts | 6+++++-
Mcommon/controller/importMedia.ts | 17+++++++++++++----
Mcommon/controller/keepVideosMatching.test.ts | 5++++-
Mcommon/controller/keepVideosMatching.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mcommon/controller/livePreclip.ts | 6++++--
Acommon/controller/markProvenance.test.ts | 648+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/marksBackfill.ts | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/normalizeTranscript.ts | 29++++++++++++++++++++++-------
Mcommon/controller/operationBatch.ts | 17+++++++++++++----
Mcommon/controller/pruneSavedVideos.test.ts | 2+-
Mcommon/controller/purgeSupersededAutoSubs.ts | 27++++++++++++++++++++++++---
Mcommon/controller/readXTrending.test.ts | 3++-
Mcommon/controller/readXTrending.ts | 31+++++++++++++++++++++++++++----
Mcommon/controller/reconcileVideoDirs.test.ts | 15+++++++++++++++
Mcommon/controller/recordLive.ts | 9+++++++--
Mcommon/controller/reportRefresh.ts | 15++++++++++++---
Acommon/controller/storedText.captions.test.ts | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/storedText.delete.test.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Acommon/controller/storedText.unreadable.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/verifyBeforeClean.ts | 19++++++++++++++-----
Mcommon/controller/xRun.test.ts | 5+++++
Mcommon/controller/xRun.ts | 15+++++++++------
Mcommon/controller/xTrendingWatch.ts | 16+++++++++++++++-
Mcommon/jobs/downloadBackoff.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobMeta.ts | 15+++++++++++++++
Mcommon/jobs/networkGuard.ts | 272++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/jobs/pacingGuard.test.ts | 177++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mcommon/jobs/platformBackoff.ts | 34++++++++++++++++++++++++++++++++--
Mcommon/jobs/queueGap.test.ts | 30+++++++++++++++++++++++-------
Mcommon/jobs/queueGap.ts | 151++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 6++++++
Mcommon/jobs/streamCommand.ts | 30++++++++++++++++++++++++++++++
Mcommon/jobs/unitOutcome.ts | 12++++++++++++
Mcommon/jobs/xJobCap.test.ts | 34+++++++++++++++++-----------------
Mcommon/jobs/xJobCap.ts | 7+++++++
Acommon/jobs/xSitting.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/xSittings.test.ts | 681+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability-server.ts | 4++++
Mcommon/lib/captionTracks-server.ts | 19+++++++++++++------
Mcommon/lib/cleanAudioConfirm.ts | 50++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/clipWindow-server.ts | 14++++++++++++++
Mcommon/lib/clipWindow.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/cookieStatus.ts | 17++++++++++++++++-
Acommon/lib/copies/dating.test.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/copies/dating.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/copies/file.ts | 21++++++++++++++++++++-
Mcommon/lib/copies/match.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/copies/match.ts | 126++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/doNotClean-server.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/doNotClean.ts | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/doNotCleanGate.test.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/downloadOutcome-server.ts | 20+++++++++++++++++++-
Mcommon/lib/envVars.ts | 5+++--
Mcommon/lib/evidenceClip.mjs | 107++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/jobContext.ts | 23+++++++++++++++++++++++
Mcommon/lib/operationUnit.test.ts | 1+
Mcommon/lib/pendingKeep-server.ts | 27+++++++++++++++++++++++----
Acommon/lib/recordingEnd.mjs | 316+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoWindow-server.test.ts | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/savedVideoWindow-server.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/settingsSchema.ts | 24+++++++++++++++++++++++-
Mcommon/lib/sidecar-server.test.ts | 2+-
Acommon/lib/storedText-read.d.mts | 14++++++++++++++
Acommon/lib/storedText-read.mjs | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/storedText-read.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/storedText-server.ts | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/storedText-write-server.ts | 338+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/storedText.compress.test.ts | 11+++++++++--
Mcommon/lib/storedText.grep.test.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/storedText.test.ts | 38++++++++++++++++++++++++++++++++------
Mcommon/lib/storedText.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/subtitleProvenance.ts | 30+++++++++---------------------
Mcommon/lib/transcriptPin-server.ts | 14++++++++++++++
Mcommon/lib/videoStatus.ts | 29++++++++++++++++++++++-------
Mcommon/lib/xJobRule.test.ts | 79++++++++++++++++++++++++++++++-------------------------------------------------
Mcommon/lib/xJobRule.ts | 43++++++++++++++++++-------------------------
Acommon/lib/xSitting.ts | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/zstdSupport.d.mts | 4++++
Acommon/lib/zstdSupport.mjs | 29+++++++++++++++++++++++++++++
Mcommon/package.json | 3+++
Mcommon/publish/composeReports.ts | 22++++++++++++++--------
Mcommon/social/fakeXProfileBrowser.test.ts | 4++--
Mcommon/social/fetchers.ts | 5+++++
Mcommon/social/headedDisplay.test.ts | 2+-
Mcommon/social/postCapture.ts | 12++++++++++++
Acommon/social/xAccountState.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xArticleCapture.test.ts | 12++++++++++++
Mcommon/social/xArticleCapture.ts | 19+++++++++++++++++--
Mcommon/social/xAvatarCapture.ts | 10++++++++++
Mcommon/social/xCookieSource.ts | 17+++++++++++++++++
Mcommon/social/xGalleryDlFetcher.test.ts | 19+++++++++++++++----
Mcommon/social/xGalleryDlFetcher.ts | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/social/xPlaywrightFetcher.ts | 21+++++++++++++++++++++
Mcommon/social/xPostCapture.test.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xPostCapture.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xSessionBroker.test.ts | 43+++++++++++++++++++++++++++++++++++++++++--
Mcommon/social/xSessionBroker.ts | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Acommon/ytdlp/captionsRefetch.test.ts | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 58+++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/ytdlp/runYtdlp.ts | 32++++++++++++++++++++++++--------
Mcommon/ytdlp/savedAlternates.test.ts | 4++--
Meditor/CHANGELOG.md | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts | 33+++++++++++++++++++++++++++++++++
Meditor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Aeditor/app/api/ops/_markProvenance.test.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/cleanup/route.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++------
Meditor/app/api/ops/compress-text/route.test.ts | 26+++++++++++++++++++++++++-
Meditor/app/api/ops/compress-text/route.ts | 36+++++++++++++++++++++++++-----------
Meditor/app/api/ops/do-not-clean/route.ts | 15+++++++++++----
Meditor/app/api/ops/keep-videos/route.ts | 2++
Aeditor/app/api/ops/marks-backfill/route.ts | 30++++++++++++++++++++++++++++++
Aeditor/app/api/ops/marks/route.ts | 25+++++++++++++++++++++++++
Aeditor/app/api/ops/x-session/route.test.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/x-session/route.ts | 37+++++++++++++++++++++++++++++++++++--
Meditor/app/channels/[slug]/components/KeepMatchingControl.tsx | 22+++++++++++++++++++---
Meditor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx | 36++++++++++++++++++++++++++++++------
Meditor/app/channels/[slug]/incompleteTranscriptActions.ts | 7+++++--
Aeditor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts | 35+++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/lib/fixIncompleteTranscript.ts | 19+++++++++++++------
Meditor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx | 21+++++++++++++++------
Meditor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Meditor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx | 9++++++---
Meditor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts | 18++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 21+++++++++++++++------
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 58+++++++++++++++++++++++++++++++++++++++++++++++++---------
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 17++++++++++++++++-
Meditor/app/channels/[slug]/videos/page.tsx | 3++-
Meditor/app/channels/[slug]/whisperActions.ts | 18+++++++++++++++---
Meditor/app/channels/actions.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/cookies/CookiesBoard.tsx | 119++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/cookies/actions.ts | 36++++++++++++++++++++++++++++++++++++
Aeditor/app/instrumentation.test.ts | 35+++++++++++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 5+++++
Meditor/app/lib/cookieControls.ts | 2++
Meditor/app/lib/cookieControlsTypes.ts | 2++
Meditor/app/lib/cookieStatus.ts | 15++++++++++++++-
Aeditor/app/lib/xPacing.ts | 18++++++++++++++++++
Meditor/app/review/components/XRunConsole.tsx | 12+++++++-----
Meditor/app/settings/components/SettingsForm.tsx | 6++++--
Meditor/app/settings/components/XSessionSection.tsx | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/settings/page.tsx | 2++
Meditor/app/settings/xSessionActions.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/storage/compressTextActions.ts | 17+++++++++++++++--
Meditor/e2e/servers.ts | 5+++++
Meditor/instrumentation.ts | 29++++++++++++++++++++++++-----
Meditor/playwright.config.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mscripts/archilyzer-ops.test.mjs | 16++++++++++++++++
Mumtool/bin/umtool.mjs | 25+++++++++++++++++++++++--
Mumtool/docs/knobs.md | 6++++++
Mumtool/docs/report-video.md | 19+++++++++++++++++++
Mumtool/lib/ingredients/stages.mjs | 6++++--
Mumtool/lib/report/cutPoints.mjs | 7++++---
Mumtool/lib/report/fetchCli.mjs | 6++++++
Mumtool/lib/report/fetchWindows.mjs | 8++++++++
Mumtool/lib/report/fetchWindows.test.mjs | 34++++++++++++++++++++++++++++++++++
Aumtool/lib/report/recordingEndNote.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/recordingEndNote.test.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/timelineCli.mjs | 19+++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 40+++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/clip-words.mjs | 4+++-
Mumtool/report-to-video/cues.mjs | 15++++++++++-----
Mumtool/report-to-video/cues.test.mjs | 41+++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/snap.mjs | 24++++++++++++++++++------
Mumtool/report-to-video/snap.test.mjs | 19+++++++++++++++++++
Mumtool/report-to-video/sources.test.mjs | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
197 files changed, 11329 insertions(+), 948 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -161,7 +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": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | | `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | | `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | | -| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?, "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). | | +| `compress-text` | compress-text stores big text files compressed (zstd, level 9): the raw live-chat replays (transcript.live\_chat.json -&gt; .zst, kind live-chat, the default) and the caption tracks (every transcript.&lt;lang&gt;.vtt -&gt; .zst, on the corpus disk: "kinds": \["captions"\], only when named). Read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat", "captions"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. A caption's dry run also counts the en / en-orig pairs of equal size (compressed each as it is, never deduped). 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, both kept and listed once (recorded per channel; not visited again until a form changes): nothing removes a stored copy because a different one arrived. 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 and kind the files, their bytes, the stored ones, the estimate after (about 5 % for a chat, 20 % for a caption: estimates) 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 file of the kinds 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 or caption (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}'` | @@ -200,15 +200,17 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `network` | network writes the named network exits (settings.network) through their one writer, as /settings → Network exits: {"upsertExit": {"id", "label"?, "proxy"?: "socks5h://host:port", "credentials"?: true\|false, "enabled"?}}, {"removeExit": "&lt;id&gt;"} (also out of every policy), {"exits": \[...\]} (the whole list, stored form {id, label, scheme, host, port, credentials, enabled}), {"platforms": {"&lt;platform&gt;": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "&lt;url&gt;" \| ""}, {"credentialsFile": "&lt;path&gt;"}, {"startupProbe": true\|false}. CREDENTIALS ARE NEVER A SETTING: a proxy URL with user:password in it is refused; give the exit "credentials": true and put NETWORK\_EXIT\_&lt;ID&gt;=user:password (percent-encoded) in the mode-600 file network.credentialsFile names (default ~/.config/archilyzer/network-exits.env), or in the environment. THE TRIAL routes only rumble and twitch LISTINGS: any other platform or request kind, and any cookie jar given an exit, is refused whole, every problem named. A channel's exit is a stable hash of its slug over the enabled exits, recorded on its first listing; a recorded exit that is disabled or removed FAILS that channel's listings until network-exit moves it, and a policy whose exits are all disabled fails every listing ("direct" only when the policy names it). One job keeps one exit for every page. Once any policy exists no child process inherits a proxy variable, and NETWORK\_EXIT\_\* never reaches a child. A listing that carries a login (cookies, a header, a token, a config file) goes direct; a 429 or bot check rests that exit (its channels wait); a proxy that does not answer, unreadable settings, missing credentials, or a yt-dlp output that does not show the proxy fail the listing — never a fallback to direct. Not a disguise: no fingerprint or user-agent changes, and a login never moves. get network \[--probe\] reports each exit (no secret in it), the rests, the channels per exit and the 1- and 7-day counts; --probe asks each proxy to answer (and fetches network.echoUrl through it only when set). The startup probe only connects to each proxy (startupProbe: false turns it off). | `pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'`<br>`pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}'`<br>`pnpm ops network --json '{"startupProbe":false}'` | | `network-exit` | network-exit reassigns one channel's exit: {"slug", "exit"} (an enabled exit of its platform's policy, or "direct"). The only way a channel moves besides its exit being removed or disabled. | `pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}'` | -| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | +| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. x-session marks the X account's state by hand: {"accountState": "suspended" \| "ok", "note"?}. While it is suspended, check-post- availability and capture-posts with screenshots on X (the jobs that record a post as deleted or unavailable) are refused, because a suspended account's answers are thinned; every other X job logs it. get x-session and /cookies show it as the account's alert. Nothing is asked of X. Answers {account: {state, note?, at, by}}. {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the one way X's 15-minute stop after a rate limit or a bot check ends early (a clean answer or clear-platform-hold never ends it). Without "confirm" it clears nothing and answers 409 with what it risks; each clear is logged in .jobs/x-stop-cleared.jsonl. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | +| `x-session` | — | `pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}'`<br>`pnpm ops x-session --json '{"accountState":"ok"}'`<br>`pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}'` | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | | `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:&lt;slug&gt;:&lt;id&gt;), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. 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.) | | +| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true, "note"?}; "keep": false removes it. (keep-videos is the bulk form.) On a mark another writer set (the availability check, an import, a live recording) "keep": true MAKES IT YOURS (the video page's "Make it mine"): {outcome: "taken-over"}; a "note" is written on it, and on a mark already yours. keep-videos takes such marks over too. | | | `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. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call, its counts answered ({jobId, plan}) and logged, and the job removes at most those videos' audio. It never touches a saved video. With the channel's cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked with no count (so do job retry and retry-failed of a clean). A checked clean the source rate-limits ends deferred and schedules a retry off the queue after at least 15 min (twice at most), then gives up; `job cancel <the deferred job id>` cancels the retry. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` | +| `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. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call, its counts answered ({jobId, plan}) and logged, and the job removes at most those videos' audio. It never touches a saved video. With the channel's cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked with no count (so do job retry and retry-failed of a clean). "includeSourceGone": true (with "unchecked" only; off by default, never implied by the channel key, never replayed) also removes the audio of videos kept ONLY because the source was gone: a mark by the availability check (inferred ones included) that nothing else holds. The plan counts that group apart, {plan: {sourceGone: {ids, videos, files, bytes, inferred: {ids, videos, files, bytes}}}}; the marks stay and record the removal. A mark a person, an import or a live recording set, or one from before marks said who set them, is never reached. The reply and the job's log state that group's counts; "expectSourceGone": &lt;the dry run's plan.sourceGone.videos&gt; refuses (409) a count that changed. A checked clean the source rate-limits ends deferred and schedules a retry off the queue after at least 15 min (twice at most), then gives up; `job cancel <the deferred job id>` cancels the retry. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait` | +| `marks-backfill` | marks-backfill relabels a channel's old do-not-clean marks (no "by") as set by the availability check, "inferred": true, only where the records prove it: availability.json says a check found the video gone within a minute of the mark, and a clean job of the channel running then names the pin in its log. Never from the note. {"slug", "dryRun"?: true} — a dry run unless "dryRun": false; answers {marks, labelled, relabelled: \[{id, setAt, evidence}\], notProven: \[{id, setAt, reason}\], oldestCleanJobAt}. The proof is one-sided: observed by the check, then pinned within the minute, inside the job's run. {"slug", "undo": true, "dryRun"?: true} returns every INFERRED label to unlabelled (the operator's): {unlabelled: \[{id, setAt, evidence}\], changedSince}. | `pnpm ops marks-backfill --json '{"slug":"x"}'` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | | `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -&gt; {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` | @@ -238,7 +240,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | | `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -&gt; {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.&lt;profile&gt;.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` | | `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -&gt; {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/&lt;slug&gt;.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` | -| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -&gt; {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their recorded dates are at most dateWindowDays apart. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/&lt;group&gt;.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals}. | | +| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -&gt; {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their dates are at most dateWindowDays apart. A video is dated by the best evidence it has: its channel's recordedDate rule, else a live stream's own day, else (no rule set) a date the channel's titles carry in a shape the scan recognises, else its upload day. On a channel with no rule, a video with only an upload day (on a re-upload channel, the copy's day) or none, and no candidate by date, is looked for by runtime instead: its 8 nearest agreeing runtimes on the other channels, at most 2,000 such pairs a scan, decided by their words only (no words, no pair). The result's advice says what the scan could not date well, with the exact channel-config patch that sets a channel's rule. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/&lt;group&gt;.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals, dating, advice?}. | | | `copies-release` | copies-release releases copies to their lanes: {"group", "video": "&lt;channel&gt;/&lt;dir&gt;" \| "videos": \[...\], "undo"?, "note"?, "by"?} -&gt; {group, action, undo, applied, unknown, skipped, now}. A released video is queued by its lanes as if it had no source group, whether it was held or skipped; undo takes the release back. A video may be named by its dir or its id (a Rumble video's differ); one the scan does not list is reported in unknown and not stored. by is "operator" or "agent" (the default), the caller's word, recorded with the time and the note in transcripts/copies/&lt;group&gt;.decisions.json, which the scan never touches. | | | `copies-confirm` | copies-confirm confirms metadata-only pairs as the same recording: {"group", "pair": "&lt;channel&gt;/&lt;dir&gt;\|&lt;channel&gt;/&lt;dir&gt;" \| "pairs": \[...\], "undo"?, "note"?, "by"?} -&gt; {group, action, undo, applied, unknown, skipped, now}. A confirmed pair acts as one confirmed by text: the copy is skipped once the other copy's work is done. Only a metadata-only pair takes it; a part-of or overlapping one is skipped with the reason. get copies lists the metadata pairs in their wait, with titles, dates and runtimes, for confirming in bulk. Recorded with who and when, as copies-release. | | | `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. | | @@ -272,6 +274,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get saved-alternates [<slug>] pnpm ops get compaction-review [<slug>] pnpm ops get kept-originals [<slug>] + pnpm ops get marks <slug> pnpm ops get services pnpm ops get x-session [<slug>] pnpm ops get cookies [fresh] @@ -343,6 +346,11 @@ get compaction-review [<slug>] lists every compacted saved video and what availability and why, the original's entry, sizes, checks, the re-check, "watch" (both files and an smplayer command that plays them) and any "leftover" of an interrupted drop. +get marks <slug> lists the channel's do-not-clean marks and who set each + one and when, as the video page says it ("setBy": "availability check, + 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live + recording, …"), with "mine" and "sourceGone" (the marks Clean without + checking's opt-in can reach). `do-not-clean {"keep": true}` makes one yours. get kept-originals [<slug>] lists every saved video that keeps an original ("keptAs": "original") or a former original ("former-original") beside its active copy, or has a drop in flight (pendingDrops: a file the pointer @@ -372,15 +380,27 @@ get x-session [<slug>] is the X login an X job would use and whether one "browser": cookiesFromBrowser, whose age cannot be read), hasCookies, looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up, - allowed, and reason (the refusal an X job would get); and X's JOB CAP: - cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} - - at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON + allowed, reason (the refusal an X job would get) and refusedBy (alert, + jar, cap, sitting, cooldown or suspended); X's JOB CAP: + cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} - + at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON THIS MACHINE: one count over every kind of X job, whatever the login source, cookie spec or channel. A job past it is refused when queued, with the time the next may start; one that meets it when its queue - starts it ends done, deferred (not failed). A library's media-only - capture is not counted. The numbers are constants of the code + starts it ends done, deferred (not failed). Every X job counts, a + library's media-only capture too. The numbers are constants of the code (common/lib/xJobRule.ts): no setting, option or queue raises them. + X's SITTING: sitting {began, kind, used, left, limit} - a cookie + refresh begins a sitting of at most social.x.sittingJobs X job starts + (default 4, 1-6 in the code), of ONE kind fixed by its first job: + timelines (account fetches, captures, availability checks, an import) + or browse (trending reads, X search walks, a library's captures). A + start past it, or of the other kind, is refused (at its start: done, + deferred); a new Refresh on /cookies starts the next. account {state, + since?, note?, alert?} is the operator's mark (x-session, below); + cooldown {until} is X's 15-minute stop after a rate limit or a bot check + met by any reader (gallery-dl, yt-dlp, the profile's pages), which + refuses every X job and Refresh/Connect. <slug> names a channel whose own cookiesFromBrowser may decide the source. Nothing is asked of X: a refresh is Refresh cookies / Connect X account on diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -263,8 +263,9 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AVAILABILITY_PROBE_GAP_MS` | the real gap (3 s, stretched by `pacing.jitter`) | The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once. | common/controller/checkAvailability.ts | | `E2E_PACING_JITTER` | `pacing.jitter` from settings.json (0.25) | Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts). | common/lib/jitter.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | -| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | -| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | +| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | +| `E2E_X_SITTINGS` | unset (X's sittings apply) | `off` leaves X jobs out of X's SITTINGS (at most `social.x.sittingJobs` X job starts per cookie refresh, of one kind each; common/lib/xSitting.ts) — inert unless `E2E_TEST_ROUTES=1`. The editor's e2e server sets it: its fake X jobs run many to one corpus with no refresh between them. X's job cap is not touched. | common/jobs/networkGuard.ts | +| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | | `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts | | `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -596,11 +596,64 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait did not continue from its place: it stops at once with a sentence and keeps the place. If a place is lost, `fetch-posts {"older": true}` walks down from the oldest archived post. - **Pacing is enforced, not advised** (plans/pacing-guard.md). Every job that asks a platform waits its - platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, X 300 s, - forums and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X - jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)`). Thirteen fetches queued in one loop run five - minutes apart and stop at the first challenge. A queue override of `""` (immediate) is refused for any - such job. + platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: Instagram 600 s, forums + and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so. **X's gap is + drawn per job**, uniform in `social.x.gapMinMinutes`-`gapMaxMinutes` (5-12 min; never below 5, an explicit + `pacing.jobGapSeconds.twitter` above 5 min raises the minimum, and the range is always at least 3 minutes wide, + so no setting makes it a fixed beat): `waiting 8m41s (a 9m02s gap drawn from 5-12 + min): X jobs are spaced 5-12 min apart, drawn per job`. A queue override of `""` (immediate) is refused for + any such job. +- **X in small, uneven sittings** (21 Nov 2026, after the account's suspension: one sitting of a trending read + and 12 timeline fetches, each 5-6 minutes after the last). A **sitting** begins at a cookie refresh (Refresh + cookies or Connect X account on /cookies) and admits at most `social.x.sittingJobs` X job starts — 4 by + default, bounded 1-6 in the code — counted as X's job cap counts them (each channel of an X run is one; a + library's media-only capture too). A sitting is **one kind**, fixed by its first job: **timelines** + (account post fetches in any mode, an X run's channels, Sync, captures of an account's posts, availability + checks, an import of one X post, X video windows) or **browse** (trending reads, an X search channel's walk, a + trending library's captures). A job past the sitting, or of the other kind, is refused when it is queued + (`This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at 14:02 UTC …`), or ends + `done`, deferred, when its queue reaches it; nothing retries it. **A new Refresh starts the next sitting** — + and only a refresh does: the jar's refresh time is the broker's own stamp (`.x-session/refreshed.json`), not + the jar file's time, which gallery-dl used to rewrite after every run (gallery-dl now runs with + `cookies-update` off). The sitting is kept in `.x-session/sitting.json` (a restart keeps it; deleted, it is + counted again from the job records and X's job count; unreadable, no X job starts). `pnpm ops get x-session` + shows `sitting {began, kind, used, left, limit}`, and /cookies shows it on X's row with the jobs left. An X run + stops at the sitting's end like at a stale jar, and Resume after a Refresh takes the rest; the scheduler + queues no more X syncs than the sitting has left; a trending watch waits for the next Refresh. +- **The X account's state, marked by hand.** `pnpm ops x-session --json '{"accountState":"suspended","note":"…"}'` + (or **Mark suspended** on /cookies) records that the account X answers as is suspended (read-only). While it + is: `check-post-availability`, the video checks (`check-availability`, `quick-availability-check`, + `check-maybe-missing`, `check-kept-deleted`) on X, and `capture-posts` unless both its screenshots and its + articles are off are refused; and inside every X job nothing is written as gone from X's answer — a capture + record's "deleted"/"unavailable" becomes an error owed again, a video download's "deleted"/"private" class is + dropped from its outcome and its availability history, the post availability sidecar keeps only "available" — + even if the mark is made while the job runs. Every other X job's log says the account is marked suspended. + `{"accountState":"ok"}` (Mark ok) lifts it. Nothing detects a suspension by itself: neither the fetchers nor + gallery-dl see an explicit signal of OUR account's suspension in X's answers. +- **A rate limit or a bot check from X stops every X job for 15 minutes — one rule, one place** + (`recordXStop`, common/jobs/downloadBackoff.ts). Whoever met it records the same stop at once: gallery-dl on a + timeline, a search walk or a post's media (its rate-limit or challenge line), yt-dlp on an X address (never X's + old 60-second backoff), the profile's pages (a trending read's 429 or 403, a capture's "Something went wrong" / + "rate limit exceeded"), the media CDN, the auto-download lane. gallery-dl no longer waits a 429 out: it runs + with `ratelimit=abort`, so the run ends at its last page, keeps what it read and its place, and **the job ends + `done`, deferred** ("X answered a rate limit (gallery-dl) at 14:02 UTC: this job stopped there …"). The guard + then refuses every X job of any kind until it ends (`X answered a rate limit (429) a short while ago: no X job + starts before …`), and **Refresh cookies and Connect X account are refused too** (they load x.com), with the + time it ends. A stop file that cannot be read refuses as well. `get x-session` shows `cooldown {until}`; + nothing ends it early — not a clean answer from another reader, not Clear hold — but the operator's + **Clear the X stop** (/cookies, or `pnpm ops x-session --json '{"clearStop":true,"confirm":true}'`), which says + what it risks first and is logged in `.jobs/x-stop-cleared.jsonl`. Inside a capture, a refusal met by any of + its readers (an avatar's or an article image's 429, three pages in a row that would not render) records the + stop and ends the loop at once. A capture takes at most `social.x.maxPostsPerJob` posts (the rest are owed, + `owed`); a trending read's posts over its tabs stay within the same setting. +- **The Playwright fallback fetcher (`postFetcher: "x-playwright"`) is refused**: it cannot tell X's refusals. + A channel on it is refused in every mode, with the sentence naming the switch to `x-gallery-dl`. +- **What one X job may read.** A walk of an account's timeline (sync new, Resume backfill, `full`, `older`) or of + an X search reads at most `social.x.maxPostsPerJob` posts (300; 20-400 in the code), then saves its place and + ends; the next sitting continues it. +- **Clear session (Forget session) forgets the login only**: the profile, the jar and its refresh stamp. The + suspended mark, the sitting and X's job count stay (they describe the account); Mark ok and a new Refresh are + their own acts. - **Only the editor's jobs ask X.** `pnpm archilyzer posts fetch --slug <x-channel>` is refused, in every mode (plain, `--backfill`, `--full`, `--older`, an X search channel) and for every X fetcher, and names `pnpm ops fetch-posts`: run directly it had no queue, no gap, no fresh-jar rule, no X alert and no cooldown. It still @@ -622,16 +675,14 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait by the time it runs fails ("the saved copy no longer covers this window; ask again and it runs on X's queue") and asks X nothing. `fetch-copies` refuses a copy whose address is X's. A `t.co` short link is X's. `record-live` of an X channel is refused (a recording would hold X's queue for hours), and so is `redownload-incomplete-bucket` on one (the transcription queue). -- **X's job cap: 12 in any 60 minutes, 150 in any 24 hours, on this machine.** ONE count over every kind of X +- **X's job cap: 6 in any 60 minutes, 150 in any 24 hours, on this machine.** ONE count over every kind of X job together (each channel of an X run is one), whatever the login source, cookie spec or channel. A job past it is refused when it is queued, with the time the next may start; nothing queues behind it. **A job that meets it when its queue starts it ends `done`, deferred** (`[deferred] …` in its log, `deferred` on the job): it did not run, it is not a failed sync, and nothing queues it again before that time. The scheduler skips X channels while it is reached and a trending watch waits, as for a cooldown. `pnpm ops get x-session` shows the count - (`cap`). **What counts:** a job that can ask x.com with the login or X's cookies — every X job but a trending - library's media-only capture (screenshots, articles, avatars and context off, not a keep capture), which takes - files from X's media hosts with no cookie and no page: it runs on X's queue under X's gap, cooldown and the - watch's jar rule, and the cap neither counts nor holds it. **The two numbers are constants of the code** + (`cap`). **What counts:** every X job, a trending library's media-only capture included (it asks X's media + hosts; 21 Nov 2026 ruling): it is in the cap, the sitting and the gap like any other. **The two numbers are constants of the code** (`common/lib/xJobRule.ts`): no setting, channel option, environment variable, flag or queue raises them, and changing them is a code change. The count is kept in `transcripts/.x-session/job-starts.json`; if that file cannot be read no X job starts until it is repaired. If it is gone, the last 24 hours are counted again from @@ -641,10 +692,9 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait say since when in `.jobs/x-records-kept.json`; until that is a day old, a lost count is refused, at most for a day (a date in that file after now is no proof: said again at now). A start stamped in the future (a clock set back) counts until the clock has passed it by the window. The scheduler queues no more X syncs than the cap has - starts left (less the X jobs already waiting); the others wait for a later tick. X's own gap (5 minutes) already means 12 jobs an hour, so - the hourly cap bites only if that gap is lowered; the daily cap bites sooner: an X run over more than 150 - channels, more than 150 X channels on a daily sync, or two topics watched at 30 minutes (a tick is a read and - usually a capture: about 96 jobs a day per topic) each reach it. + starts left (less the X jobs already waiting); the others wait for a later tick. At 6 an hour the hourly cap + bites at X's floor gap (5 minutes) and implies the daily one (6 × 24 = 144 < 150), which stays as a second, + independent bound. In practice the sitting (4 per refresh) is reached first. - **X only on a fresh jar.** With the connected profile as the login source, a job aimed at X is refused — at enqueue and again when its queue reaches it — unless the cookies were refreshed within `social.x.maxCookieAgeMinutes` (60; 0 = off): `X cookies were last refreshed 16 days ago (limit 60 min): @@ -851,8 +901,8 @@ pnpm ops watch-trending --json '{"slug":"trending","topic":"kettle-festival","o store, the transcript archives read `data/`, and the source mirror publishes this code repo, not the corpus. Nothing in Archilyzer commits or pushes the corpus repo; a backup you run yourself over `transcripts/` is yours to point away from `trending/reads/`. -- **One page is one job on X's queue** (`read-x-trending`): the fresh-jar rule, the X alert and X's 5-minute job - gap apply as to every X job. The page is opened in the connected X profile's browser (headless; `"headed": true` +- **One page is one job on X's queue** (`read-x-trending`): the fresh-jar rule, the X alert, X's drawn 5-12 minute job + gap and X's sitting (a read is a browse job) apply as to every X job. The page is opened in the connected X profile's browser (headless; `"headed": true` opens a window on the editor's desktop), and what the page itself fetches is kept: every GraphQL JSON answer, raw, in `channels/<slug>/trending/reads/<readId>/responses.jsonl`, a screenshot (`page.png`) and the read's record (`read.json`: operation names and sizes only). No request is built and no header is stored. That directory is @@ -1181,6 +1231,12 @@ pnpm ops diarize --json '{"slug":"example"}' --wait # one channe pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true,"dryRun":true}' # what it would remove pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true}' --wait # Clean without checking pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":true}' # always, for this channel +pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait # and audio kept only because the source was gone +pnpm ops marks-backfill --json '{"slug":"example"}' # which old marks the records prove (dry run) +pnpm ops marks-backfill --json '{"slug":"example","dryRun":false}' # relabel them +pnpm ops marks-backfill --json '{"slug":"example","undo":true}' # which inferred labels an undo returns (dry run) +pnpm ops get marks example # who set each mark, and when +pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":true}' # make a machine-set mark yours ``` - **Clean audio checks first**: before deleting a transcribed video's audio it asks the source whether the video is @@ -1214,8 +1270,46 @@ pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":tr new channel never starts with it. Clean after capture still holds a URL-less channel (`cleanAfterCaptureUnverified`) and a whole-recording one (`diarization.cleanWholeRecordingAudio`) — those holds are not the availability check. Audio an earlier checked clean pinned as "deleted from source (pre-clean check)" - stays do-not-clean: unpin it on the video page (or `pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":false}'`) to let - it go. + stays do-not-clean: let it go with the opt-in below, or unpin it on the video page (or `pnpm ops do-not-clean + --json '{"slug":"example","id":"<id>","keep":false}'`). +- **Who set a do-not-clean mark** is in the mark (`data/<id>/do-not-clean.json`): `by` is `availability-check` (the + checked clean's gate, clean after capture, the keep-latest window's deletion check), `live-recording` + (`record-live`), `import` (`import-media`) or `operator` (the video page's toggle, `do-not-clean`, `keep-videos`, + and a keep asked for before the video landed); `via` says which, `surface` where a person asked (`button` or + `ops`) and `jobId` the job that wrote it. A machine never replaces a mark that is there. **Any keep by a person + makes a mark set by another writer theirs** (`by: "operator"`, with its via, surface and the note given, else the + mark's own note; `takenOver` records who had set it): keep-videos by pattern or by ids, a keep asked for before + the video landed, the video page's toggle and **Make it mine**, `do-not-clean {"keep": true}`, and writing a note + on it. "Already kept" is said only of a mark that is already a person's (a note given is still written on it). + A mark from before this has no `by` and is treated as the operator's. **Every surface says who set it and when**: + the video page ("Do not clean: on (availability check, 3 Nov; the source was gone)" or "(you, 20 Nov)"), the + Keep matching control's lists, keep-videos' answer (`keptBy`, `takenOver`) and `pnpm ops get marks <slug>` + (`setBy`, `mine`, `sourceGone`). +- **"Also remove audio kept only because the source was gone"** — a checkbox on Clean without checking's + confirmation, off by default, and `"includeSourceGone": true` with `"unchecked": true` over ops. Never implied by + `cleanAudioWithoutChecking`, never on Clean audio, never carried by a Retry or a restart. It reaches ONLY marks + with `by: "availability-check"` (inferred ones included) that nothing else holds (the keep-latest window, the + speaker holds); a mark set by a person, an import, a live recording, or one with no `by`, is never reached. The + plan always counts that group apart (`plan.sourceGone`: ids, videos, files, bytes, and `inferred` the same), and + the ticked confirmation gives it its own line: "Also removed, kept only because the source was gone: N audio files + (X) from M videos the availability check marked do not clean. Their marks stay." — with the inferred part named + after it. The job carries those ids; each removal happens under the mark's lock, after re-reading it there, and + its record is written before the lock is released — a person's keep is either first (nothing removed) or after. + Over ops the reply answers the group's counts and the job's log states them before anything is removed; + `"expectSourceGone": <the dry run's plan.sourceGone.videos>` refuses (409) a count that changed since. The mark + stays (the video is still gone, so every other cleaner and the saved-video prune keep it) and gains + `audioRemoved: [{at, jobId, files, bytes, why}]`. +- **`marks-backfill`** relabels an OLD mark (no `by`) as `by: "availability-check", inferred: true` only when the + records prove it, never from its note: `availability.json` says a **check** found the video gone at most a minute + **before** the mark's `setAt` (one-sided: the gate pins only after the check has recorded what it saw, on the + same clock), AND a finished Clean audio job of the channel (or its rate-limit retry) that started at or before + `setAt` and ended at or after it has the line `Pinned <id> as do-not-clean (<that state>)` in its log. A dry run unless `"dryRun": false`; it lists + every mark it would relabel with that evidence, and every other with why not (`notProven`, and + `oldestCleanJobAt` — job logs are pruned by retention). What it cannot prove: a pin made on a **cached** verdict + (the check ran days before the clean), any mark older than the oldest job log kept, a mark whose availability + record a later recheck moved, and every keep-latest-check or clean-after-capture pin (not a clean job's). Those + stay the operator's; unpin them by hand. `{"undo": true}` (a dry run unless `"dryRun": false`, the same listing) + returns every **inferred** label to unlabelled — the operator's again; setAt, note and audioRemoved stay. - **A checked clean the source rate-limits** (HTTP 429 on the channel listing or on a confirmation probe) deletes nothing it could not verify and ends **deferred** on /jobs, with its counts. **The 429 counts toward the platform's pace and hold**: a rate-limited listing records the platform's cooldown as Sync does @@ -1448,6 +1542,37 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md" - `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not hold, one paced job per platform; a re-run resumes. It stays at 720: a site's evidence clip is cut inside 1280×720 from the plain `<from>-<to>.mp4` window. +- **A window that runs past the end of a saved recording is cut from it, clamped at the end.** This is the last clip + of a recording plus its pad. The rule is in `common/lib/recordingEnd.mjs` and applies to `fetch-windows`, + fetch-window, `fetch_clip`, live-clip and the umtool build. + - The window must START inside the saved container and the recording must be KNOWN WHOLE. Known whole means a + known length is at most 2 s longer than the container's end, compared on one clock: the container's end on the + cue clock, which is its length less the time map's offset at the end. yt-dlp's duration is whole seconds, and + the muxer rounds the last frame. + - The known length is the record's `duration` (metadata.info.json). It is not trusted while the record says + `is_live`, `is_upcoming` or `post_live`. + - Else it is a landed live recording's stream length, and only the ended stream's OWN duration counts + (`coverage.basis: "duration"`, `covers`, from the start, with no live-edge fallback, no missing stream and no + failure on the record). The recorder's clock measures the recorder: a recorder that died mid-stream measures + itself whole. + - The cut ends where BOTH streams have data: the shorter of the picture's and the sound's ends, measured once per + container from its last packets. So the window passes the sync check. The end is two decimals rounded down, on + the cue clock through the recording's time map. + - The file is named for what it holds (`clips/<from>-<cutTo>.mp4`). Its sidecar records `clamp: {askedTo, cutTo, + recordingEnd, why, container: {file, bytes}, knownSeconds}`. Nothing is fetched. + - A window carrying the clamp holds any later span that starts inside it, so the same padded ask is a cache hit. + The answer lists the item under `"atRecordingEnd"`, and `umtool fetch --dry-run` prints `at end <clip>: + saved-video, clamped at the recording's end (asked to X, cut to Y)`. + - **A clamp is re-checked on every lookup** against the saved-video pointer (file and bytes) and the known length + (within 0.5 s). These are JSON reads, never a probe. + - When the container is another or a longer file, or the known end has moved, the window answers only its own + seconds. `fetch-windows` retires it, as it retires a window cut on another clock (listed under `retired`), and + asks the span again. + - Still `not-covering`, as before: a window that starts at or after the end; a container shorter than the known + length by more than 2 s, which is a partial recording; and a recording whose length is not known. The reason is + given (a whole-recording platform's item fails with it). + - So do not shorten a last clip to avoid a network fetch. Keep its whole end (`umtool window <p> <clip> --end E`), + then `umtool fetch <p> --dry-run`. - A window asked taller than 720 (`"maxHeight"` on `fetch-windows`, fetch-window, `fetch_clip`; umtool sends it only for a project with `render.tallWindows` on) is its own file beside the 720 one: `clips/<from>-<to>.h<tier>.mp4`, with its own sidecar. The 720 window is never replaced, retired or re-fetched for this. An ask with no `maxHeight` @@ -1833,6 +1958,52 @@ pnpm ops compress-text --json '{"restore":true}' --wait # the roll see the chat; with different content, the other is what readers read). - **By hand:** `zstdcat transcript.live_chat.json.zst` reads one. +### Compress the caption tracks + +```sh +pnpm ops compress-text --json '{"kinds":["captions"],"dryRun":true}' # per channel: caption files, bytes, ~20 % after, equal-size en/en-orig pairs, free space +pnpm ops compress-text --json '{"kinds":["captions"],"slugs":["example"],"limit":20}' --wait # a first batch +pnpm ops compress-text --json '{"kinds":["captions"],"verify":true}' --wait # decode every stored caption; writes nothing +pnpm ops compress-text --json '{"kinds":["captions"]}' --wait # the rest; a re-run continues +pnpm ops compress-text --json '{"kinds":["captions"],"restore":true}' --wait # the rollback for captions +``` + +- **What it does.** Every caption track, `transcript.<lang>.vtt` (`en`, `en-orig`, regional, translated, foreign), is + stored as `transcript.<lang>.vtt.zst` beside where it was: about 20 % of its size. Captions are text on the CORPUS + disk (real files in `data/<id>/`, never tiered), so this is what frees that disk. Only when named: `kinds` defaults + to the live chat alone; `["live-chat","captions"]` does both, the chat first. +- **Every reader reads either form** with the same times: the index (it sees no change), normalize, the snapshot's + buckets, the provenance sniff (it decodes the head), compose, the remote worker's inputs (sent plain), umtool's cue + source. A stored track is "on disk" to every skip: no audio is downloaded or transcribed because of it, and + Download missing subs (which fetches only what is missing) leaves it out of `--sub-langs`. +- **A re-download fetches a stored track again, as it always did** (the video page's Download, the retry bucket, + `full: true`, Persist source video): YouTube's captions are asked again and the new file replaces the old one. + Per track, the job log says which: the same content keeps the stored form (the new copy is dropped; nothing + moves, the index sees nothing); new content with cues becomes the track, and the stored one is removed only once + the new file is whole; nothing fetched (a video that is gone), a `.part`, or an empty or cue-less file leaves the + stored track untouched. +- **The same rules as the chat**: one file at a time, verified, the original removed last; the quiet period, the + `.part` and recording refusals, the per-directory lock, person-started only, one job per channel. +- **Two forms with different content are refused and both kept, and listed** ("refused — both-differ"): a plain + caption a re-fetch, a forced re-download or "Set as transcript" landed beside an older stored one. The plain one + is what readers read. Nothing removes a stored caption because a different one arrived: a video deleted on its + platform cannot give its captions again. Settle a pair on the video's files card. A refused pair is recorded in + the channel's `.stored-text-differs.json` (both forms' inode, size and mtime): later runs do not visit it again, + and the dry run lists it once as "waiting for a person" until either form changes. +- **A stopped run never brings a deleted caption back.** Every deleter (the files card, the purge, the + clear-transcript fix, deleting the video) removes a stopped run's set-aside original with the forms; a set-aside + found with no stored form beside it is not adopted but listed ("retired-kept"). +- **A Node without zstd refuses to start** (the editor, every `archilyzer` CLI, umtool and its bare-node + readers), naming the Node needed (>= 22.15): it never runs with stored files unreadable. A stored file that does + not decode is an error, never "no text": the index keeps the record as the last build held it and says so + ("UNREADABLE STORED TEXT"), and `verify` lists it. +- **The en / en-orig pairs** of equal size (on samples, byte-identical) are compressed each as it is; the dry run + counts them (`pairsEqualSize`) for a person deciding whether to dedupe — nothing here dedupes. +- **The tier migration's reclaim** takes a platter copy of a caption whose twin on the corpus disk is stored only + when the stored form decodes to exactly its bytes; otherwise it keeps and reports it. +- **Deleting a caption**: the files card (only the file named goes), the auto-caption purge and the clear-transcript + fix (both forms; the purge keeps both when they differ). By hand: `zstdcat transcript.en.vtt.zst`. + #### 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 @@ -1844,8 +2015,15 @@ first, then revert or run the older code**: 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 +pnpm ops compress-text --json '{"kinds":["captions"],"restore":true,"dryRun":true}' # the same for captions: +pnpm ops compress-text --json '{"kinds":["captions"],"restore":true}' --wait # an older checkout sees a stored caption as no transcript at all ``` +For captions an older checkout is worse than for the chat: a video whose only captions are stored reads as having no +transcript, so its download lane fetches the captions again and the no-subs fallback downloads the audio and +transcribes it. Restore the captions first: they take their plain size again on the corpus disk (about 5 times the +stored size; the dry run says how much). + 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 diff --git a/SETTINGS.md b/SETTINGS.md @@ -181,7 +181,7 @@ Default: `"when-required"` ## `social` -Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. +Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. #### `social` @@ -198,6 +198,10 @@ Per-platform settings of the social posts: X's three, all chosen in the X accoun | `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. | | `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. | | `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /cookies, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. | +| `sittingJobs` | absent | X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` (trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code (common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts. | +| `gapMinMinutes` | absent | THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and `gapMaxMinutes`, after the previous X job ended, and logged ("waiting 8m41s (a 9m02s gap drawn from 5-12 min)"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises it. ABSENT: 5. At most 120. common/jobs/queueGap.ts. | +| `gapMaxMinutes` | absent | THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never less than the minimum plus 3 (a range of one value is a fixed beat; the spread is in the code). ABSENT: 12. At most 120. | +| `maxPostsPerJob` | absent | WHAT ONE X JOB MAY READ: a walk of an account's timeline (sync new, Resume backfill, a full or older walk) or of an X search reads at most this many posts, then saves its place and ends; the next sitting continues it. A lower `limit` on the job still applies. ABSENT: 300. Bounded 20-400 in the code (common/lib/xSitting.ts). | #### `social.xenforo` diff --git a/common/bin/_cli.ts b/common/bin/_cli.ts @@ -7,6 +7,8 @@ import { realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { parseArgv, type FlagValue } from "./_parseFlags"; +import path from "node:path"; +import { zstdSupportProblem } from "../lib/zstdSupport.mjs"; // A flag a command accepts. "boolean" never takes a value (`--nodata`), // "string" always needs one (`--preview <branch>`). @@ -201,6 +203,13 @@ export function runIfEntryPoint( main: () => Promise<number | void>, ): void { if (!isEntryPoint(metaUrl)) return; + // Every CLI may read the corpus, where captions and chats may be stored as + // `.zst`: on a Node without zstd it refuses to start (REVIEW-1 F3). + const zstd = zstdSupportProblem(); + if (zstd) { + console.error(`${path.basename(fileURLToPath(metaUrl))} refuses to start: ${zstd}`); + process.exit(1); + } main().then( (code) => { if (typeof code === "number") process.exitCode = code; diff --git a/common/bin/migrate-media-tier.test.ts b/common/bin/migrate-media-tier.test.ts @@ -410,6 +410,29 @@ test("--reclaim keeps a platter copy whose twin on the corpus disk is gone or di assert.ok(lines.some((l) => /kept 2 entries on the drive with no same-size copy/.test(l))); }); +test("--reclaim takes a platter caption whose twin was since COMPRESSED — only when the stored form holds its very bytes", async () => { + // Lane text-compress-captions: a caption brought home and then compressed + // is `transcript.en.vtt.zst` on the corpus disk. Its platter copy is taken + // when the stored form decodes to exactly its bytes; a stored form of OTHER + // content (or one that does not decode) keeps the copy, reported. + resetCorpus(); + seedLegacy(); + writeFileSync(path.join(oldTree(SLUG), "v3", "transcript.en.vtt"), VTT); + await run(); + const { storeFixture } = await import("../testing/storedTextFixture"); + const data = (id: string) => path.join(channelDir(), "data", id); + await storeFixture(data("v1"), "transcript.en.vtt"); + // v3: since the migration, the track was re-written with other words of + // the same size, then compressed — the stored form is not the platter copy. + writeFileSync(path.join(data("v3"), "transcript.en.vtt"), VTT.replace(/[a-z]/, "Z")); + await storeFixture(data("v3"), "transcript.en.vtt"); + const res = await run({ reclaim: true }); + assert.equal(res.exitCode, 0, res.channels[0].detail); + assert.deepEqual(res.channels[0].reclaimKept?.sort(), ["v3/transcript.en.vtt"]); + assert.throws(() => lstatSync(path.join(mediaTarget(), "v1", "transcript.en.vtt")), "its stored twin holds it: taken"); + assert.ok(lstatSync(path.join(mediaTarget(), "v3", "transcript.en.vtt")).isFile(), "a stored twin of other content: kept"); +}); + test("a reclaim killed after its deletes resumes from its marker and ends clean", async () => { resetCorpus(); seedLegacy(); diff --git a/common/bin/migrate-media-tier.ts b/common/bin/migrate-media-tier.ts @@ -68,6 +68,7 @@ import { lutimes, mkdir, readdir, + readFile, readlink, rename, rm, @@ -83,6 +84,8 @@ import type { SiteSettings } from "../lib/settings"; import { formatBytes } from "../lib/format"; import { getFreeBytes } from "../lib/diskSpace"; import { classifyEntry, CLIPS_DIR, isTierable } from "../lib/mediaTier"; +import { STORED_TEXT_SUFFIX, isStoredTextName } from "../lib/storedText"; +import { decodeStoredBytes } from "../lib/storedText-server"; import { channelMediaLink, relocatedMediaDir, @@ -935,7 +938,12 @@ async function reclaimTree( try { twin = await lstat(path.join(ssd, rel)); } catch { - return false; + // A TWIN IN ITS STORED FORM (lib/storedText.ts): a caption brought home + // and since compressed is `<name>.zst` on the corpus disk. It is the + // twin only when it decodes whole (checksum, length) to exactly the + // platter copy's bytes — never by size alone, so a reclaim run after a + // compress-text run removes no copy the stored form does not hold. + return st.isFile() && isStoredTextName(path.basename(rel)) && (await storedTwinHolds(path.join(ssd, rel), path.join(mediaDir, rel))); } if (st.isDirectory()) return twin.isDirectory(); return !twin.isDirectory() && twin.size === st.size; @@ -979,6 +987,22 @@ async function reclaimTree( return { reclaimedFiles: files, reclaimedBytes: bytes, reclaimKept: kept }; } +// Does `<plain>.zst` beside `plain` (a real file) hold exactly `copy`'s bytes? +async function storedTwinHolds(plain: string, copy: string): Promise<boolean> { + const stored = `${plain}${STORED_TEXT_SUFFIX}`; + try { + const z = await lstat(stored); + if (!z.isFile()) return false; + const [decoded, bytes] = await Promise.all([ + readFile(stored).then((b) => decodeStoredBytes(b, stored)), + readFile(copy), + ]); + return decoded.equals(bytes); + } catch { + return false; + } +} + // --reclaim on a channel already on the media tier: only one this tool // migrated (its reclaim note stands), whose media drive answers and whose // `data/` is a real directory. diff --git a/common/controller/adoptLocalMediaReference.ts b/common/controller/adoptLocalMediaReference.ts @@ -11,6 +11,8 @@ import { openExternalMedia } from "../lib/externalMediaResolver-server"; import { localMediaFingerprint } from "../lib/localMediaScan"; import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference } from "../lib/localMedia"; import { writeExternalMediaReference } from "../lib/externalMedia-server"; +import { storedNameOf } from "../lib/storedText"; +import { decodeStoredBytes } from "../lib/storedText-server"; type Selection = { sourceToken: string; media: string; fingerprint: string }; export type LocalMediaAdoptionResult = { status: "ready" | "attached" | "already-linked" | "conflict"; stagingCleanupFailed?: boolean }; @@ -34,6 +36,17 @@ async function bytes(root: string, name: string, afterRead?: () => Promise<void> } finally { await h.close(); } } +// A caption's exact bytes in either form (lib/storedText.ts): the plain file +// by `bytes`, else its stored `.zst` by `bytes` (the same no-follow, bounded, +// unchanged read), decoded — the frame's checksum and length checked. The +// decoded bytes are the plain file's exactly. +async function captionBytes(root: string, name: string): Promise<Buffer> { + if (await lstat(path.join(root, name)).then(() => true, () => false)) return bytes(root, name); + const stored = storedNameOf(name); + if (!(await lstat(path.join(root, stored)).then(() => true, () => false))) return bytes(root, name); + return decodeStoredBytes(await bytes(root, stored), path.join(root, stored)); +} + // Separate from import: occupied records are NEVER silently merged by scanning. // This explicit operation requires exact existing metadata/transcript matches. // It publishes only a new sidecar and never changes/removes prototype links. @@ -68,7 +81,7 @@ export async function adoptLocalMediaReference(paths: Paths, slug: string, }); const channel=path.join(paths.channelsDir,slug), data=path.join(channel,"data"), record=path.join(data,row.directoryId); for(const dir of [channel,data,record]) { const s=await lstat(dir); if(!s.isDirectory() || s.isSymbolicLink()) throw new Error("Expected real archive directories"); } - const metadata=await bytes(record,"metadata.info.json"), transcript=await bytes(record,"transcript.en.vtt"); + const metadata=await bytes(record,"metadata.info.json"), transcript=await captionBytes(record,"transcript.en.vtt"); if(!metadata.equals(source.metadata) || !transcript.equals(source.transcript)) throw new Error("Existing metadata or transcript differs; manual review required"); // Repeat the configuration/relocation guards after the source reads too. const after=await previewLocalMedia(paths,slug); diff --git a/common/controller/archiveOrgDownload.ts b/common/controller/archiveOrgDownload.ts @@ -48,6 +48,7 @@ import path from "node:path"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { appendFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import { readdirLogical } from "../lib/storedText-server"; import type { ManagedDownloadOpts } from "../ytdlp/downloadOneManaged"; import type { AudioFormat } from "../lib/channelConfig"; import type { @@ -165,8 +166,9 @@ function extOf(name: string): string { return m ? m[1].toLowerCase() : ""; } +// LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript. async function hasTranscriptOnDisk(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = await readdirLogical(videoDir); return entries.some((e) => { if (e === "transcript.json") return true; const m = /^transcript\.([^.]+)\.(?:vtt|json|json3|srv1|srv2|srv3)$/.exec(e); diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -969,6 +969,152 @@ test("(t) lane text-compress: THE COMPRESSOR itself, over a real and a tiered ch assert.deepEqual(mtimesOf(), before); }); +test("(u) lane text-compress-captions: every caption track compressed — the index sees NO change, and reads the same cues, alternates and subs", async () => { + resetCorpus(); + seedVideo("c1", CHANNEL, { subs: true }); + seedVideo("c2"); + // c1 carries an en-orig whose words differ from en (an alternate track), a + // German sub track, and sub-millisecond times a `Date` would lose. + const ORIG = VTT.replace("First", "Original").replace("Second", "Spoken"); + writeFileSync(path.join(videoDir("c1"), "transcript.en-orig.vtt"), ORIG); + const { utimesSync } = await import("node:fs"); + for (const [n, t] of [["transcript.en.vtt", 1763700000.123457], ["transcript.en-orig.vtt", 1763700002.000003], ["transcript.de.vtt", 1763700003.5]] as const) { + utimesSync(path.join(videoDir("c1"), n), t, t + 0.000001); + } + const all = () => + withIndex((db) => ({ + mtimes: [...db("mtimes").getRange()].map(({ key, value }) => [key, value]), + cues: [...db("cues").getRange()].map(({ key, value }) => [key, value]), + subs: [...db("subs").getRange()].map(({ key, value }) => [key, value]), + alts: [...db("alts").getRange()].map(({ key, value }) => [key, value]), + })); + await runIndex(); + const before = all(); + assert.ok(before.alts.length > 0, "the fixture has an alternate track"); + assert.ok(before.subs.length > 0, "the fixture has a sub track"); + assert.ok(before.cues.length >= 2); + + // THE COMPRESSOR over every caption of both videos (c2 through the fixture + // helper, the way a run killed after its rename leaves it). + const { compressStoredText } = await import("../lib/storedText-write-server"); + for (const n of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.de.vtt"]) { + const out = await compressStoredText(videoDir("c1"), n, { reserveBytes: 0 }); + assert.equal(out.status, "compressed", `${n}: ${JSON.stringify(out)}`); + } + const { storeFixture } = await import("../testing/storedTextFixture"); + await storeFixture(videoDir("c2"), "transcript.en.vtt"); + assert.deepEqual(readdirSync(videoDir("c1")).filter((n) => n.endsWith(".vtt")), [], "no plain caption is left"); + + 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(all(), before, "the same mtimes, cues, subs and alternates"); + + // A change elsewhere re-reads both records: everything comes from the stored forms. + seedVideo("c1", CHANNEL, { title: "Retitled" }); + seedVideo("c2", CHANNEL, { title: "Retitled" }); + // seedVideo wrote a plain en.vtt again (the same bytes): what a re-fetch + // would leave beside the stored one — plain is read, and is the same. + rmSync(path.join(videoDir("c1"), "transcript.en.vtt")); + rmSync(path.join(videoDir("c1"), "transcript.de.vtt"), { force: true }); + rmSync(path.join(videoDir("c2"), "transcript.en.vtt")); + const reread = await runIndex(); + assert.equal(reread.res.changed, 2, reread.log.join("\n")); + const now = all(); + assert.deepEqual(now.cues, before.cues, "the cues are read from the stored captions"); + assert.deepEqual(now.subs, before.subs, "the German track is read from its stored form"); + assert.deepEqual(now.alts, before.alts, "the alternate is read from the stored en-orig"); +}); + +test("(v) lane text-compress-captions: THE MIGRATION (compress-text, kinds captions) — the real index sees no change", async () => { + resetCorpus(); + seedVideo("c1", CHANNEL, { subs: true }); + seedVideo("c2"); + writeFileSync(path.join(videoDir("c1"), "transcript.en-orig.vtt"), VTT.replace("First", "Original")); + const { utimesSync } = await import("node:fs"); + for (const id of ["c1", "c2"]) { + for (const n of readdirSync(videoDir(id)).filter((x) => x.endsWith(".vtt"))) { + utimesSync(path.join(videoDir(id), n), 1763700000.5, 1763700000.000003); + } + } + const all = () => + withIndex((db) => ({ + mtimes: [...db("mtimes").getRange()].map(({ key, value }) => [key, value]), + cues: [...db("cues").getRange()].map(({ key, value }) => [key, value]), + subs: [...db("subs").getRange()].map(({ key, value }) => [key, value]), + alts: [...db("alts").getRange()].map(({ key, value }) => [key, value]), + })); + await runIndex(); + const before = all(); + const { compressText } = await import("./compressText"); + const r = await compressText({ paths, slugs: [CHANNEL], kinds: ["captions"], quietMs: 0, compressOpts: { reserveBytes: 0 }, onLog: () => {} }); + assert.equal(r.channels[0].compressed, 4, JSON.stringify(r.channels[0])); + const after = await runIndex(); + assert.equal(after.res.changed, 0, after.log.join("\n")); + assert.deepEqual(all(), before); +}); + +test("(w) REVIEW-1 F3: a stored caption that does not decode — the record keeps what the last build held, is said, and is read again", async () => { + resetCorpus(); + seedVideo("c1", CHANNEL, { subs: true }); + const { storeFixture } = await import("../testing/storedTextFixture"); + await storeFixture(videoDir("c1"), "transcript.en.vtt"); + await storeFixture(videoDir("c1"), "transcript.de.vtt"); + const all = () => + withIndex((db) => ({ + mtimes: [...db("mtimes").getRange()].map(({ key, value }) => [key, value]), + cues: [...db("cues").getRange()].map(({ key, value }) => [key, value]), + subs: [...db("subs").getRange()].map(({ key, value }) => [key, value]), + sums: [...db("sums").getRange()].map(({ key, value }) => [key, value]), + })); + await runIndex(); + const before = all(); + assert.ok(before.cues.length === 1 && (before.cues[0][1] as unknown[]).length > 0, "the stored caption was read"); + // The frame goes bad (a disk error) and the record changes (retitled). + const good = readFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst")); + writeFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst"), Buffer.concat([good.subarray(0, 12), Buffer.alloc(good.length - 12, 7)])); + seedVideo("c1", CHANNEL, { title: "Retitled" }); + rmSync(path.join(videoDir("c1"), "transcript.en.vtt")); + const bad = await runIndex(); + assert.ok(bad.log.some((l) => /^Unreadable stored text in test-channel\/c1: .*transcript\.en\.vtt\.zst/.test(l)), bad.log.join("\n")); + assert.ok(bad.log.some((l) => /^UNREADABLE STORED TEXT: 1 file\(s\)/.test(l)), bad.log.join("\n")); + const kept = all(); + assert.deepEqual(kept.cues, before.cues, "never written with no cues"); + assert.deepEqual(kept.sums, before.sums, "the record is the last build's"); + assert.deepEqual(kept.mtimes, before.mtimes, "not marked read: the next build tries again"); + // Fixed (restored from a good copy): read, the retitle lands. + writeFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst"), good); + const fixed = await runIndex(); + assert.equal(fixed.res.changed, 1, fixed.log.join("\n")); + assert.deepEqual(all().cues, before.cues); +}); + +test("(x) REVIEW-2 N5: an unreadable stored SUB track keeps its earlier cues AND is read again, and said, on every build", async () => { + resetCorpus(); + seedVideo("c1", CHANNEL, { subs: true }); + const { storeFixture } = await import("../testing/storedTextFixture"); + await storeFixture(videoDir("c1"), "transcript.de.vtt"); + const subsOf = () => withIndex((db) => [...db("subs").getRange()].map(({ key, value }) => [key, value])); + const subsMs = () => withIndex((db) => [...db("mtimes").getRange()].map(({ value }) => (value as { subsMs: number | null }).subsMs)); + await runIndex(); + const before = subsOf(); + assert.equal(before.length, 1, "the German track was read"); + const good = readFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst")); + writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), Buffer.concat([good.subarray(0, 12), Buffer.alloc(good.length - 12, 7)])); + seedVideo("c1", CHANNEL, { title: "Retitled" }); + for (let build = 1; build <= 2; build++) { + const r = await runIndex(); + assert.ok(r.log.some((l) => /^UNREADABLE STORED TEXT: 1 file\(s\).*transcript\.de\.vtt/.test(l)), `build ${build}: ${r.log.join("\n")}`); + assert.deepEqual(subsOf(), before, `build ${build}: the earlier cues are kept`); + assert.deepEqual(subsMs(), [null], `build ${build}: not pinned as read`); + } + writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), good); + const fixed = await runIndex(); + assert.ok(!fixed.log.some((l) => /UNREADABLE/.test(l))); + assert.notDeepEqual(subsMs(), [null]); +}); + 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 @@ -100,7 +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 { isStoredTextReadError, readStoredText, statStoredText } from "../lib/storedText-server"; import { onDrive } from "../lib/storageHealth"; import { HELD_WAYS_OUT, @@ -575,7 +575,10 @@ async function scanSource( : [picked.filename, ...captionInputs(files.entries)]; for (const name of inputs) { try { - const ms = (await stat(path.join(fullVideoDir, name))).mtimeMs; + // Either form (lib/storedText.ts): a caption stored compressed + // carries the plain file's mtime exactly, so the same + // `transcriptMs` — a compression re-ingests nothing. + const ms = (await statStoredText(fullVideoDir, name)).stats.mtimeMs; if (transcriptMs === null || ms > transcriptMs) transcriptMs = ms; } catch { // ignore @@ -1120,6 +1123,9 @@ export async function buildIndex({ const toProcess = [...added, ...changed]; let processed = 0; + // Stored files (captions, chats) that are there and do not decode, this + // build: each logged with its path, counted below (REVIEW-1 F3). + const unreadableStored: string[] = []; const BATCH = 200; for (let i = 0; i < toProcess.length; i += BATCH) { const slice = toProcess.slice(i, i + BATCH); @@ -1168,7 +1174,11 @@ export async function buildIndex({ ? // The caption-track rule (lib/videoStatus.ts). (await readEnglishVttCues(videoFullDir))?.cues : parseTranscriptJson(await readFile(s.transcriptPath, "utf8")); - } catch { + } catch (err) { + // A stored caption that does not decode is an ERROR: the + // record is not written (the last build's stays, and the next + // build retries) — never written with no cues (REVIEW-1 F3). + if (isStoredTextReadError(err)) throw err; cueList = undefined; } } @@ -1221,6 +1231,16 @@ export async function buildIndex({ summary.id, ]; + // The other English tracks, where their words differ from the + // primary's (lib/captionTracks.ts). Only a record that can hold one + // reads anything. Read BEFORE anything of the record is written: a + // stored track that does not decode throws, and the record is then + // left exactly as the last build held it (REVIEW-1 F3). + const trackFields: TrackFields = + canHoldAltTracks(s) && s.transcriptKind + ? await readTrackFields(videoFullDir, s.transcriptKind, cueList) + : {}; + const pk: PathKey = [s.channelSlug, s.videoDir]; const prev = mtimes.get(pk); // What the last build held for this video's captions, for the @@ -1245,13 +1265,6 @@ export async function buildIndex({ if (cueList) cues.put(indexKey, cueList); else cues.remove(indexKey); - // The other English tracks, where their words differ from the - // primary's (lib/captionTracks.ts). Only a record that can hold one - // reads anything. - const trackFields: TrackFields = - canHoldAltTracks(s) && s.transcriptKind - ? await readTrackFields(videoFullDir, s.transcriptKind, cueList) - : {}; if (trackFields.altTracks) { alts.put(indexKey, trackFields); altTrackRecords++; @@ -1338,7 +1351,19 @@ export async function buildIndex({ if (trackCues.length > 0) { parsedSubs.push({ track: t.track, cues: trackCues }); } - } catch { + } catch (err) { + // A STORED sub track that does not decode: the cues the last + // build held are kept, and with none to keep the record is + // written with no sub-track time, so the next build retries — + // the tiered chat's rule (REVIEW-1 F3). + if (isStoredTextReadError(err)) { + unreadableStored.push(`${s.channelSlug}/${s.videoDir}/${t.filename}: ${(err as Error).message}`); + const kept = prevSubs?.find((x) => x.track === t.track); + if (kept) parsedSubs.push(kept); + // Retried on EVERY later build, kept cues or not — never + // pinned as read (REVIEW-2 N5): `subsMs` is stored null. + retrySubs = true; + } // Skip unreadable / malformed sub tracks; the rest of the // video's data is still useful. } @@ -1453,6 +1478,14 @@ export async function buildIndex({ cueFingerprint: cueFingerprint(cueList), }); } catch (err) { + if (isStoredTextReadError(err)) { + unreadableStored.push(`${s.channelSlug}/${s.videoDir}: ${(err as Error).message}`); + log( + `Unreadable stored text in ${s.channelSlug}/${s.videoDir}: ${(err as Error).message} — ` + + `the record is kept as the last build held it, and read again next build`, + ); + return; + } log(`Failed to process ${s.channelSlug}/${s.videoDir}: ${String(err)}`); } }), @@ -1463,6 +1496,15 @@ export async function buildIndex({ } } + if (unreadableStored.length > 0) { + log( + `UNREADABLE STORED TEXT: ${unreadableStored.length} file(s) that do not decode — not read as empty; ` + + `their records keep what the last build held: ${unreadableStored.slice(0, 20).join("; ")}` + + `${unreadableStored.length > 20 ? `; … ${unreadableStored.length - 20} more` : ""}. ` + + `\`pnpm ops compress-text --json '{"kinds":["captions"],"verify":true}'\` lists them.`, + ); + } + // What the caption-track pass changed, per channel (CAPTION_TRACK_KEY). for (const [slug, r] of [...captionReport].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { log( diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -72,6 +72,7 @@ import { heldReason, } from "../lib/channelMediaHold"; import { getSettings } from "../lib/settings"; +import { storedTextMtimeMs } from "../lib/storedText-server"; import type { Paths } from "../lib/paths"; import { channelsOnlyOnUnlistedSites, @@ -271,7 +272,8 @@ async function resolveAcquisitionDates( if (transcribedDate === null) { const picked = pickIndexTranscript(await readVideoFiles(videoDir)); const mtime = - (picked ? await fileMtimeMs(path.join(videoDir, picked.filename)) : null) ?? + // Either form (lib/storedText.ts): a stored caption carries its mtime. + (picked ? await storedTextMtimeMs(videoDir, picked.filename) : null) ?? (await fileMtimeMs(path.join(videoDir, CUES_JSON_FILENAME))); transcribedDate = (mtime != null ? ymdFromMs(mtime) : null) ?? downloadedDate; } diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -33,6 +33,8 @@ // shows), writing the context into the record and nothing about availability. import { xJobContextRefusal } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; @@ -44,7 +46,7 @@ import { xTrendingPostsRoot, } from "../lib/xTrending/store"; import { ensureXTrendingMediaIgnore } from "../lib/xTrending/mediaStore"; -import { platformCooldownRemainingMs, recordPlatformCooldown } from "../jobs/downloadBackoff"; +import { platformCooldownRemainingMs, recordXStop } from "../jobs/downloadBackoff"; import type { ChromiumLike } from "../social/playwrightRuntime"; import { createLibraryMediaDownloader, @@ -53,7 +55,6 @@ import { type MediaFetch, } from "../social/xTrendingMedia"; import { mediaSourcesInCapture, readCaptureLines, type TrendingMediaSource } from "../social/xTrendingParse"; -import { X_RATE_LIMIT_HOLD_MS } from "./readXTrending"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; import type { Post, PostAvailability } from "../lib/posts"; @@ -167,6 +168,9 @@ export type CapturePostsResult = { avatars?: XAvatarRunSummary; // X: what the run read of the posts' context, when it read any. context?: XContextRunSummary; + // X: the ids past the per-job ceiling (social.x.maxPostsPerJob), not + // captured by this job and left for a later one (review 2 G3). + owed?: string[]; }; // Why this fetcher cannot capture posts, or null when it can. Shared with the @@ -263,7 +267,8 @@ export async function capturePosts( const log = (line: string) => onLog?.(line); const fail = (error: string): CapturePostsResult => ({ ok: false, outcomes: [], error }); const channelDir = path.join(paths.channelsDir, slug); - const ids = [...new Set(opts.ids)]; + let ids = [...new Set(opts.ids)]; + let owed: string[] = []; if (nothingToCapture(opts)) return fail(NOTHING_TO_CAPTURE); if (ids.length === 0) return fail("No post ids to capture."); @@ -300,6 +305,17 @@ export async function capturePosts( if (fetcher.platform === "twitter") { const refusal = xJobContextRefusal(`A capture of ${opts.slug}'s posts`, `pnpm ops capture-posts --json '{"slug":"${opts.slug}","ids":[…]}' --wait`); if (refusal) return fail(refusal); + // WHAT ONE X JOB MAY TAKE (review 2 G3): the first posts up to the + // ceiling; the rest are owed to a later job (`owed`). + const cap = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined); + if (ids.length > cap) { + owed = ids.slice(cap); + ids = ids.slice(0, cap); + log( + `This X capture takes the first ${cap} of ${cap + owed.length} posts (social.x.maxPostsPerJob); ` + + `the other ${owed.length} are left for a later job, from ${owed[0]}.`, + ); + } } const avatarsOnly = opts.avatarsOnly === true; if (avatarsOnly) { @@ -466,11 +482,13 @@ export async function capturePosts( return { ok: true, outcomes: [], ...avatars }; } - // What the pages said about each post, folded into the sidecar. - const observations = new Map<string, PostAvailability>(); + // What the pages said about each post, folded into the sidecar — never a + // suspended X account's "deleted" (social/xAccountState.ts). + let observations = new Map<string, PostAvailability>(); for (const o of result.outcomes) { if (o.availability) observations.set(o.id, o.availability); } + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); if (observations.size > 0) { const { map, newlyDeleted, changed } = mergePostAvailability( await readPostAvailability(channelRoot), @@ -509,9 +527,9 @@ export async function capturePosts( const stoppedByOperator = (opts.signal ?? controller.signal).aborted || Boolean(opts.drain?.aborted); if (result.stoppedEarly && !stoppedByOperator) { - return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars }; + return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly, ...avatars, ...(owed.length ? { owed } : {}) }; } - return { ok: true, outcomes: result.outcomes, ...avatars }; + return { ok: true, outcomes: result.outcomes, ...avatars, ...(owed.length ? { owed } : {}) }; } const waitFor = (ms: number, signal: AbortSignal) => @@ -577,7 +595,7 @@ async function libraryMediaDownloader( pauseMs: () => libraryMediaPauseMs(), pause: waitFor, cooldownMs: () => platformCooldownRemainingMs(X, paths), - noteRateLimit: () => recordPlatformCooldown(X, X_RATE_LIMIT_HOLD_MS, paths), + noteRateLimit: () => recordXStop("a rate limit (429) from its media CDN", paths), ...asked?.deps, }, }); diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -658,6 +658,40 @@ test("a chat-only livestream whose chat is STORED compressed is still a corpus m } }); +test("videos whose captions are STORED compressed read exactly as before: downloaded, transcribed, ASR-only (lane text-compress-captions)", async () => { + // Missed, an ASR-only video would leave the replace lane's bucket, and a + // captioned one would read undownloaded — the download lane fetching it + // again. The byte walk counts the stored file as text, under its own name. + const ASR = + "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + + "Second<00:01:10.000><c> caption</c>\n"; + const { dir, paths, channelDir } = await filteredChannel({ listed: ["aaaa0000001", "bbbb0000002"] }); + try { + for (const id of ["aaaa0000001", "bbbb0000002"]) { + const videoDir = path.join(channelDir, "data", id); + await mkdir(videoDir, { recursive: true }); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id, title: `Synthetic ${id}` })); + await writeFile(path.join(videoDir, "transcript.en.vtt"), ASR); + } + const plain = await generateChannelSnapshot(paths, "alpha"); + const { storeFixture } = await import("../testing/storedTextFixture"); + for (const id of ["aaaa0000001", "bbbb0000002"]) { + await storeFixture(path.join(channelDir, "data", id), "transcript.en.vtt"); + } + const stored = await generateChannelSnapshot(paths, "alpha"); + assert.deepEqual(stored.buckets.autoSubsOnly, ["aaaa0000001", "bbbb0000002"]); + assert.deepEqual(stored.buckets.autoSubsOnly, plain.buckets.autoSubsOnly); + assert.deepEqual(stored.undownloadedIds, plain.undownloadedIds); + assert.deepEqual(stored.undownloadedIds, []); + assert.equal(stored.totals.downloaded, plain.totals.downloaded); + assert.equal(stored.totals.transcribed, plain.totals.transcribed); + assert.equal(stored.totals.transcribed, 2); + } 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 @@ -1046,7 +1046,9 @@ export async function generateChannelSnapshot( let textBytes = 0; let clipsBytes = 0; const linked: string[] = []; - for (const name of files.entries) { + // PHYSICAL: a stored `.zst` is a file of its own size (text unless + // its name is tierable — lib/mediaTier.ts). + for (const name of files.physicalEntries) { try { const st = await lstat(path.join(dir, name)); if (st.isSymbolicLink()) { diff --git a/common/controller/checkKeptDeleted.ts b/common/controller/checkKeptDeleted.ts @@ -20,6 +20,8 @@ export type CheckKeptDeletedOptions = { onLog?: (msg: string) => void; signal?: AbortSignal; concurrency?: number; + // The job this check runs in, recorded on every mark it writes. + jobId?: string; }; export type CheckKeptDeletedResult = { @@ -37,6 +39,7 @@ export async function checkKeptDeleted({ onLog, signal, concurrency, + jobId, }: CheckKeptDeletedOptions): Promise<CheckKeptDeletedResult> { const log = onLog ?? ((m: string) => console.log(m)); const config = await readChannelConfig(paths, channelSlug); @@ -78,7 +81,13 @@ export async function checkKeptDeleted({ const already = await loadDoNotClean(videoDir); if (already) continue; const note = `deleted from source (keep-latest): ${availability}`; - await setDoNotClean(videoDir, true, note); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "kept-deleted-check", + ...(jobId ? { jobId } : {}), + note, + }); + if (!wrote) continue; pinned++; log(`Pinned ${id} as do-not-clean (${availability}).`); } diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts @@ -18,6 +18,7 @@ // posts never looked at, `all` re-checks everything. import { xJobContextRefusal } from "../lib/xJobRule"; +import { keepVerdictsTrustedWhileSuspended } from "../social/xAccountState"; import path from "node:path"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; @@ -217,6 +218,8 @@ export async function checkPostAvailability( return { ok: false, ...empty, error: message }; } + // A suspended X account's "deleted" is not believed (social/xAccountState.ts). + if (fetcher.platform === "twitter") observations = await keepVerdictsTrustedWhileSuspended(paths, observations, log); const checkedAt = new Date().toISOString(); const { map, newlyDeleted, changed } = mergePostAvailability( availability, diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -3,7 +3,8 @@ import { isPermanentlyGone } from "../lib/availability"; import { detectPlatform } from "../lib/platform"; import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings"; import { resolveEffectiveAvailability } from "../lib/availability-server"; -import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import { loadDoNotClean, removeUnderSourceGoneMark, setDoNotClean } from "../lib/doNotClean-server"; +import { isSourceGoneMark } from "../lib/doNotClean"; import { readAvailabilityVerdict, requestAvailabilityCheck, @@ -52,6 +53,19 @@ export type CleanAudioOptions = { // plan". Absent = discover at start (the checked clean, a channel-key clean // nobody confirmed). onlyIds?: readonly string[]; + // ALSO REMOVE AUDIO KEPT ONLY BECAUSE THE SOURCE WAS GONE (lane + // mark-provenance): the ids of the plan's `sourceGone` group a person + // confirmed with that explicit opt-in. Honoured ONLY by a "button" unchecked + // sweep (a person confirmed the count); ignored, and said so, anywhere else. + // A video in it loses its audio only when its mark STILL says by + // "availability-check" (inferred included) and it passes every other gate; + // a mark by anything else — a person, an import, a live recording, or a mark + // from before marks said who set them — is never reached. The mark stays, + // and records when and why the audio went. + sourceGone?: readonly string[]; + // The job running the sweep: recorded on every mark the gate writes and on + // every audioRemoved entry. + jobId?: string; // Test seam for the availability probes (verifyBeforeClean). probes?: VerifyProbes; // Test seam for the media guard asked immediately before anything is @@ -106,6 +120,10 @@ export type CleanAudioResult = { // since the plan was made), skipped. notInPlan?: number; planNoLongerEligible?: number; + // The opt-in's group, when it was confirmed: audio removed from videos kept + // only because the source was gone (their marks stay). Counted inside + // cleanedDirs / removedFiles / bytesFreed too. + sourceGoneRemoved?: { videos: number; files: number; bytes: number; inferredVideos: number }; // Set when the availability gate stopped short — the source rate-limited it // (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could // not verify (verifyBeforeClean's CleanVerdicts.stopped). @@ -129,6 +147,10 @@ export type AudioCleanGate = | "no-audio" | "keep-latest" | "do-not-clean" + // Only when the caller asks (ctx.sourceGone, the opt-in's discover): a + // video whose mark says by "availability-check" and that passes every gate + // after the mark. It stays protected unless a person confirmed the opt-in. + | "source-gone" | "awaiting-diarization" | "awaiting-voiceprint" // cleanAudioForVideo only: the channel's media drive is not answering. The @@ -153,14 +175,27 @@ export type AudioCleanGate = export async function audioCleanGate( videoDir: string, id: string, - ctx: { keptIds: Set<string>; diarization: DiarizationSettings }, -): Promise<{ gate: AudioCleanGate; audioFiles: string[] }> { + ctx: { keptIds: Set<string>; diarization: DiarizationSettings; sourceGone?: boolean }, +): Promise<{ gate: AudioCleanGate; audioFiles: string[]; inferred?: boolean }> { const entries = await readdir(videoDir).catch(() => [] as string[]); if (!entries.includes("transcript.json")) return { gate: "no-transcript", audioFiles: [] }; const audioFiles = audioFilesToRemove(entries); if (audioFiles.length === 0) return { gate: "no-audio", audioFiles }; if (ctx.keptIds.has(id)) return { gate: "keep-latest", audioFiles }; - if (await isDoNotClean(videoDir)) return { gate: "do-not-clean", audioFiles }; + // THE MARK. Without ctx.sourceGone (every caller but the opt-in's discover) + // any mark protects, as it always has. With it, a mark the availability + // check wrote goes on through the gates below; every other mark protects. + let sourceGone: { inferred: boolean } | null = null; + if (ctx.sourceGone) { + const mark = await loadDoNotClean(videoDir); + if (mark && !isSourceGoneMark(mark)) return { gate: "do-not-clean", audioFiles }; + if (mark) sourceGone = { inferred: mark.inferred === true }; + } else if (await isDoNotClean(videoDir)) { + return { gate: "do-not-clean", audioFiles }; + } + // A source-gone video held by a gate below stays "do-not-clean": its mark + // keeps it first. + const held = (gate: AudioCleanGate) => ({ gate: sourceGone ? ("do-not-clean" as const) : gate, audioFiles }); // While diarization is enabled, a transcribed video that still has audio but // no diarization.json is NOT cleanable yet — its diarize job hasn't run. // @@ -174,19 +209,22 @@ export async function audioCleanGate( const record = entries.includes("diarization.json") ? await loadDiarization(videoDir) : null; - if (!record) return { gate: "awaiting-diarization", audioFiles }; + if (!record) return held("awaiting-diarization"); // The voice fingerprint is the part of a diarization that cannot be made // again without the audio, so it is waited for too. if (ctx.diarization.requireVoiceprints && !hasVoiceprints(record)) { - return { gate: "awaiting-voiceprint", audioFiles }; + return held("awaiting-voiceprint"); } } + if (sourceGone) return { gate: "source-gone", audioFiles, inferred: sourceGone.inferred }; return { gate: "candidate", audioFiles }; } const SKIP_LOG: Partial<Record<AudioCleanGate, string>> = { "keep-latest": "in keep-latest window", "do-not-clean": "marked do not clean", + // Unreleased, it reads exactly as any other mark does. + "source-gone": "marked do not clean", "awaiting-diarization": "awaiting diarization", "awaiting-voiceprint": "awaiting voice fingerprint", }; @@ -216,6 +254,8 @@ export async function cleanAudioFromTranscribed({ verifyAvailability, unchecked, onlyIds, + sourceGone: sourceGoneAsked, + jobId, probes, assertReachable = assertChannelMediaReachable, onLog, @@ -246,12 +286,40 @@ export async function cleanAudioFromTranscribed({ let removedFiles = 0; let bytesFreed = 0; + // --- The opt-in: only a person-confirmed unchecked clean ----------------- + // ("button"). A checked sweep, a channel-key sweep and a retry never release + // a mark, whatever their spec carries. + const releaseSourceGone = unchecked === "button" && sourceGoneAsked !== undefined; + if (sourceGoneAsked !== undefined && !releaseSourceGone) { + log("Audio kept only because the source was gone is NOT removed: only a confirmed Clean without checking can opt in to that."); + } + // --- Discover ------------------------------------------------------------- - const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal }); + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal, sourceGone: releaseSourceGone }); let candidates = found.candidates; let protectedCount = found.protectedCount; const { awaitingDiarization, awaitingVoiceprint } = found; + // The opt-in's group: the confirmed ids still marked by the availability + // check now; every other source-gone video stays protected, as before. + let released: SourceGoneCandidate[] = []; + if (releaseSourceGone) { + const asked = new Set(sourceGoneAsked); + released = found.sourceGone.filter((c) => asked.has(c.id)); + for (const c of found.sourceGone) { + if (!asked.has(c.id)) { + log(`Skipped ${c.id} (${SKIP_LOG["source-gone"]})`); + protectedCount++; + } + } + const gone = asked.size - released.length; + log( + `Also remove audio kept only because the source was gone (confirmed): ${asked.size} video(s) asked, ${released.length} still marked by the availability check` + + (gone > 0 ? `; ${gone} no longer (re-marked by a person, unmarked, or held since) and kept` : "") + + ". Their marks stay.", + ); + } + // --- The confirmed plan: never more than a person was shown --------------- let notInPlan: number | undefined; let planNoLongerEligible: number | undefined; @@ -284,6 +352,7 @@ export async function cleanAudioFromTranscribed({ candidateIds: candidates.map((c) => c.id), onLog: log, signal, + ...(jobId ? { jobId } : {}), ...(probes ? { probes } : {}), }); excluded = excludedIds(verdicts); @@ -300,7 +369,7 @@ export async function cleanAudioFromTranscribed({ // listing can take minutes. A drive that went away or a relocation that // started since (its marker) stops the sweep here, removing nothing: a // removed tier link on an absent drive strands its bytes there. - if (candidates.some((c) => !excluded.has(c.id)) && !signal?.aborted) { + if ((candidates.some((c) => !excluded.has(c.id)) || released.length > 0) && !signal?.aborted) { await assertReachable(paths, channelSlug); } for (const candidate of candidates) { @@ -311,6 +380,53 @@ export async function cleanAudioFromTranscribed({ bytesFreed += out.bytes; cleanedDirs++; } + let sourceGoneRemoved: CleanAudioResult["sourceGoneRemoved"]; + if (releaseSourceGone) { + sourceGoneRemoved = { videos: 0, files: 0, bytes: 0, inferredVideos: 0 }; + for (const c of released) { + if (signal?.aborted) break; + // UNDER THE MARK'S LOCK (review F3): the mark is re-checked after the + // lock is taken and the removal and its record happen before it is + // released, so a person who re-marks the video — before or meanwhile — + // is either first (theirs: nothing removed) or after (the audio is gone + // and recorded on the mark they then take over). + let removed = 0; + const done = await removeUnderSourceGoneMark( + c.videoDir, + async () => { + const r = await removeCandidateAudio(c, log); + removed = r.removed; + return { files: c.audioFiles, bytes: r.bytes }; + }, + { + at: new Date().toISOString(), + ...(jobId ? { jobId } : {}), + why: + "Clean without checking, with \"also remove audio kept only because the source was gone\" confirmed: the mark was set by the availability check" + + (c.inferred ? " (inferred from the records by marks-backfill)" : "") + + "; the mark stays.", + }, + ); + if (!done) { + log(`Skipped ${c.id} (marked do not clean — no longer by the availability check)`); + protectedCount++; + continue; + } + const out = { removed, bytes: done.bytes }; + log( + done.recorded + ? `Removed the audio of ${c.id}, kept only because the source was gone${c.inferred ? " (mark inferred)" : ""}; its mark stays.` + : `Removed the audio of ${c.id}, but its mark could not record it: this log is the record.`, + ); + removedFiles += out.removed; + bytesFreed += out.bytes; + cleanedDirs++; + sourceGoneRemoved.videos++; + sourceGoneRemoved.files += out.removed; + sourceGoneRemoved.bytes += out.bytes; + if (c.inferred) sourceGoneRemoved.inferredVideos++; + } + } const skipped = protectedCount + pinned + unverified + awaitingDiarization + awaitingVoiceprint; @@ -367,10 +483,13 @@ export async function cleanAudioFromTranscribed({ prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}), + ...(sourceGoneRemoved ? { sourceGoneRemoved } : {}), ...(stopped ? { stopped } : {}), }; } +type SourceGoneCandidate = CleanCandidate & { inferred: boolean }; + // THE DISCOVER PASS of the channel sweep, shared with the dry plan below so // the two can never disagree about what a clean would remove. Nothing is // deleted here. Protected videos are filtered out, so the availability gate @@ -382,6 +501,7 @@ async function discoverAudioCandidates({ dirs, log, signal, + sourceGone = false, }: { paths: Paths; channelSlug: string; @@ -389,8 +509,13 @@ async function discoverAudioCandidates({ dirs: string[]; log: (m: string) => void; signal?: AbortSignal; + // Tell apart the marks the availability check wrote (the opt-in's group, + // returned in `sourceGone`, NOT counted in protectedCount — the caller + // decides). Off: every mark is "do-not-clean", as always. + sourceGone?: boolean; }): Promise<{ candidates: CleanCandidate[]; + sourceGone: SourceGoneCandidate[]; protectedCount: number; awaitingDiarization: number; awaitingVoiceprint: number; @@ -408,18 +533,23 @@ async function discoverAudioCandidates({ let awaitingDiarization = 0; let awaitingVoiceprint = 0; const candidates: CleanCandidate[] = []; + const goneGroup: SourceGoneCandidate[] = []; for (const id of dirs) { if (signal?.aborted) break; const videoDir = path.join(dataDir, id); - const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); + const { gate, audioFiles, inferred } = await audioCleanGate(videoDir, id, { keptIds, diarization, sourceGone }); if (gate === "no-transcript" || gate === "no-audio") continue; + if (gate === "source-gone") { + goneGroup.push({ id, videoDir, audioFiles, inferred: inferred === true }); + continue; + } if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; else if (gate === "awaiting-diarization") awaitingDiarization++; else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; else candidates.push({ id, videoDir, audioFiles }); } - return { candidates, protectedCount, awaitingDiarization, awaitingVoiceprint }; + return { candidates, sourceGone: goneGroup, protectedCount, awaitingDiarization, awaitingVoiceprint }; } export type AudioCleanPlan = { @@ -433,9 +563,25 @@ export type AudioCleanPlan = { files: number; bytes: number; // What it would keep: do-not-clean or keep-latest, and the two speaker holds. + // `protected` INCLUDES the sourceGone group (kept unless the opt-in is + // confirmed). protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + // THE OPT-IN'S GROUP (lane mark-provenance): videos kept ONLY because the + // availability check found the source gone (their mark says by + // "availability-check") and held by nothing else. What "also remove audio + // kept only because the source was gone" would remove; `inferred` is the + // part whose marks the backfill relabelled from the records. + sourceGone: SourceGonePlan; +}; + +export type SourceGonePlan = { + ids: string[]; + videos: number; + files: number; + bytes: number; + inferred: { ids: string[]; videos: number; files: number; bytes: number }; }; // THE DRY PLAN of a clean without checking — the confirmation's numbers and @@ -455,24 +601,28 @@ export async function planAudioClean({ await assertChannelMediaReachable(paths, channelSlug); const dataDir = path.join(paths.channelsDir, channelSlug, "data"); const dirs = (await pathExists(dataDir)) ? await readdir(dataDir) : []; - const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal }); - let files = 0; - let bytes = 0; - for (const c of found.candidates) { - for (const f of c.audioFiles) { - files++; - bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal, sourceGone: true }); + const count = async (group: readonly CleanCandidate[]) => { + let files = 0; + let bytes = 0; + for (const c of group) { + for (const f of c.audioFiles) { + files++; + bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + } } - } + return { ids: group.map((c) => c.id), videos: group.length, files, bytes }; + }; + const main = await count(found.candidates); + const gone = await count(found.sourceGone); + const inferred = await count(found.sourceGone.filter((c) => c.inferred)); return { inspected: dirs.length, - ids: found.candidates.map((c) => c.id), - videos: found.candidates.length, - files, - bytes, - protected: found.protectedCount, + ...main, + protected: found.protectedCount + found.sourceGone.length, awaitingDiarization: found.awaitingDiarization, awaitingVoiceprint: found.awaitingVoiceprint, + sourceGone: { ...gone, inferred }, }; } @@ -581,8 +731,12 @@ export async function cleanAudioForVideo({ const cached = await resolveEffectiveAvailability(videoDir); if (isPermanentlyGone(cached)) { if (!(await loadDoNotClean(videoDir))) { - await setDoNotClean(videoDir, true, `deleted from source (pre-clean check): ${cached}`); - log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "clean-after-capture", + note: `deleted from source (pre-clean check): ${cached}`, + }); + if (wrote) log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`); } return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 }; } diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts @@ -86,19 +86,26 @@ export function uncheckedReasonFor(config: ChannelConfig | null | undefined): Un // a person confirmed one, else discovered at start; the key is re-read // when the job starts (runCleanAudioJob); // - otherwise the checked clean (bounded by a plan when one was confirmed). +// - `sourceGone` (the opt-in "also remove audio kept only because the source +// was gone", lane mark-provenance) rides ONLY on an explicit "button" +// request: never implied by the channel key, never on a checked clean. export type CleanAudioRequest = { kind: "clean-audio-transcribed" | "clean-audio-unchecked"; unchecked?: UncheckedReason; plan?: string[]; + sourceGone?: string[]; }; export function cleanAudioRequestFor( config: ChannelConfig | null | undefined, - opts: { explicit?: "button"; plan?: readonly string[] } = {}, + opts: { explicit?: "button"; plan?: readonly string[]; sourceGone?: readonly string[] } = {}, ): CleanAudioRequest { const plan = opts.plan ? [...opts.plan] : undefined; const reason: UncheckedReason | undefined = opts.explicit ?? uncheckedReasonFor(config); - if (reason) return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}) }; + if (reason) { + const sourceGone = opts.explicit === "button" && opts.sourceGone ? [...opts.sourceGone] : undefined; + return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}), ...(sourceGone ? { sourceGone } : {}) }; + } return { kind: "clean-audio-transcribed", ...(plan ? { plan } : {}) }; } @@ -108,6 +115,13 @@ export function planFromParams(p: Record<string, unknown> | undefined): string[] return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; } +// A spec's carried source-gone ids (the opt-in), or undefined. Read only by the +// job that carries them — no replay passes them on (below). +export function sourceGoneFromParams(p: Record<string, unknown> | undefined): string[] | undefined { + const v = p?.sourceGone; + return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; +} + // HOW A CLEAN JOB IS REPLAYED — by every replay path alike: a /jobs Retry, // Retry all failed, `pnpm ops job retry`, and the boot's re-queue of a job a // restart caught queued (all four go through the editor's runJobSpec). Operator @@ -127,6 +141,9 @@ export function planFromParams(p: Record<string, unknown> | undefined): string[] // plan lost; confirm again". On a key-OFF channel it is REFUSED: it would // be an unchecked run nobody asked for now; // - anything else is refused. +// THE OPT-IN IS NEVER REPLAYED (lane mark-provenance): a replay carries the +// plan only, so audio kept because the source was gone is removed only by the +// run a person confirmed it for. export type CleanReplay = | { ok: true; call: "clean" | "unchecked"; plan?: string[] } | { ok: false; error: string; info?: boolean }; @@ -183,13 +200,20 @@ export type CleanPlanCountsLog = { protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + // The opt-in's group as counted, when it was confirmed. + sourceGone?: { videos: number; files: number; bytes: number; inferred: { videos: number; files: number; bytes: number } }; }; export function planCountsLine(c: CleanPlanCountsLog): string { + const g = c.sourceGone; return ( `Plan counted when this clean was asked for: ${c.files} audio file(s) (${c.bytes} bytes) from ${c.videos} video(s); ` + - `kept: ${c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + - `${c.awaitingVoiceprint} awaiting voice fingerprint.` + `kept: ${g ? c.protected - g.videos : c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + + `${c.awaitingVoiceprint} awaiting voice fingerprint.` + + (g + ? ` Also, kept only because the source was gone: ${g.files} audio file(s) (${g.bytes} bytes) from ${g.videos} video(s)` + + ` (${g.inferred.videos} of them with marks inferred from the records: ${g.inferred.files} file(s), ${g.inferred.bytes} bytes).` + : "") ); } @@ -204,6 +228,7 @@ export async function runCleanAudioJob({ unchecked, plan, planCounts, + sourceGone, retry, onLog, signal, @@ -220,6 +245,8 @@ export async function runCleanAudioJob({ plan?: readonly string[]; // The plan's counts, logged before anything is removed (an ops call). planCounts?: CleanPlanCountsLog; + // The opt-in's confirmed ids: honoured only while the job runs as "button". + sourceGone?: readonly string[]; retry?: CleanRetry; onLog: (m: string) => void; signal?: AbortSignal; @@ -265,6 +292,8 @@ export async function runCleanAudioJob({ signal, ...(mode ? { unchecked: mode } : {}), ...(plan ? { onlyIds: plan } : {}), + ...(sourceGone ? { sourceGone } : {}), + jobId, ...(deps.probes ? { probes: deps.probes } : {}), ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}), }); diff --git a/common/controller/cleanUnchecked.test.ts b/common/controller/cleanUnchecked.test.ts @@ -176,6 +176,10 @@ test("the dry plan counts exactly what the unchecked clean removes, and asks not protected: 1, awaitingDiarization: 1, awaitingVoiceprint: 1, + // The pinned video's mark carries the gate's note but no `by` (written + // before marks said who set them): the operator's, never in the opt-in's + // group (lane mark-provenance). + sourceGone: { ids: [], videos: 0, files: 0, bytes: 0, inferred: { ids: [], videos: 0, files: 0, bytes: 0 } }, }); // Nothing was deleted by the plan. assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); diff --git a/common/controller/compressText.captions.test.ts b/common/controller/compressText.captions.test.ts @@ -0,0 +1,397 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { rmSync } from "node:fs"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compressText.captions.test.ts +// +// THE MIGRATION OVER CAPTIONS (lane text-compress-captions, slice 5): +// `compress-text {kinds: ["captions"]}` over a temp corpus — a dry run that +// touches nothing and counts the equal-size en / en-orig pairs, a real run, +// its limit, the refusals (two forms of different content listed and both +// kept, a recent file, a `.part`, a recording), every kill point finished by +// the job, the check, and the restore. The live chat is left alone unless it +// is asked for, and captions unless they are. Synthetic names only. + +const ROOT = await mkdtemp(path.join(tmpdir(), "compress-captions-")); +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 } = await import("./compressText"); +const { readStoredText } = await import("../lib/storedText-server"); +const { CompressKill } = await import("../lib/storedText-write-server"); + +const paths = getPaths(); +const CAPTIONS = ["captions"] as const; +const vtt = (seed: string, cues: number) => + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + Array.from({ length: cues }, (_, i) => { + const s = String(i).padStart(2, "0"); + return `00:00:${s}.000 --> 00:00:${s}.900 align:start position:0%\n${seed} ${i} ${createHash("md5").update(seed + i).digest("hex")}\n`; + }).join("\n"); +const CHAT = "transcript.live_chat.json"; +const OLD = 1_700_000_000; + +type Videos = Record<string, Record<string, string>>; + +async function channel(slug: string, videos: Videos): 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}` })); + for (const [id, files] 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 })); + for (const [name, text] of Object.entries(files)) { + await writeFile(path.join(dir, name), text); + // Old enough for the quiet period; sub-millisecond times. + await utimes(path.join(dir, name), OLD, OLD + 0.123457); + } + } +} + +const dirOf = (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id); +const names = async (slug: string, id: string) => (await readdir(dirOf(slug, id))).sort(); +const leftovers = async (slug: string, id: string) => (await readdir(dirOf(slug, id))).filter((e) => e.startsWith(".")); + +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 PAIR = vtt("pair", 40); +const A: Videos = { + a1: { "transcript.en.vtt": PAIR, "transcript.en-orig.vtt": PAIR, "transcript.es.vtt": vtt("es", 30) }, + a2: { "transcript.en.vtt": vtt("served", 20), "transcript.en-orig.vtt": vtt("spoken", 25), [CHAT]: '{"replayChatItemAction":{}}\n'.repeat(50) }, +}; +await channel("alpha", A); + +test("a dry run over captions: per channel and kind, ~20 %, the equal-size pairs — and touches NOTHING", async () => { + const before = await tree(ROOT); + const lines: string[] = []; + const r = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, dryRun: true, onLog: (l) => lines.push(l) }); + assert.deepEqual(await tree(ROOT), before, "not one entry changed, not one mtime"); + assert.deepEqual(r.kinds, ["captions"]); + const alpha = r.channels[0]; + const c = alpha.byKind!.captions!; + assert.equal(c.plainFiles, 5); + const bytes = Object.values(A).flatMap((v) => Object.entries(v)).filter(([n]) => n.endsWith(".vtt")).reduce((a, [, t]) => a + t.length, 0); + assert.equal(c.plainBytes, bytes); + assert.equal(c.estimateAfterBytes, Math.round(bytes * 0.2)); + assert.equal(c.pairsEqualSize, 1, "a1's pair; a2's differ in size"); + assert.equal(c.pairsEqualSizeBytes, PAIR.length); + assert.equal(alpha.byKind!["live-chat"], undefined, "the chat is not asked"); + assert.equal(alpha.plainFiles, 5, "the channel's totals are the kinds asked"); + assert.match(lines.join(""), /caption file\(s\).*estimate, 20 %.*en \/ en-orig pairs of equal size: 1/); + assert.match(lines.join(""), /Nothing was written/); + // And with no kinds: the live chat alone, as before captions were a kind. + const chatOnly = await compressText({ paths, slugs: ["alpha"], dryRun: true, onLog: () => {} }); + assert.deepEqual(chatOnly.kinds, ["live-chat"]); + assert.equal(chatOnly.channels[0].plainFiles, 1); +}); + +test("a real run: every caption compressed, read back the same, with the same times; the chat untouched; a limit; a re-run", async () => { + const mt = async (id: string, n: string) => (await stat(path.join(dirOf("alpha", id), n))).mtimeMs; + const times: Record<string, number> = {}; + for (const [id, files] of Object.entries(A)) for (const n of Object.keys(files)) times[`${id}/${n}`] = await mt(id, n); + const first = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, limit: 2, onLog: () => {} }); + assert.equal(first.stopped, "limit"); + assert.equal(first.channels[0].compressed, 2); + const rest = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.equal(rest.channels[0].compressed, 3); + assert.equal(rest.channels[0].already, 2); + for (const [id, files] of Object.entries(A)) { + for (const [n, text] of Object.entries(files)) { + if (n === CHAT) continue; + assert.equal(await readStoredText(dirOf("alpha", id), n, "utf8"), text, `${id}/${n}`); + assert.equal(await mt(id, `${n}.zst`), times[`${id}/${n}`], `${id}/${n}: the same mtimeMs`); + } + } + assert.deepEqual(await names("alpha", "a1"), ["metadata.info.json", "transcript.en-orig.vtt.zst", "transcript.en.vtt.zst", "transcript.es.vtt.zst"]); + assert.ok((await names("alpha", "a2")).includes(CHAT), "the chat is not a caption: left as it was"); + const again = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.equal(again.channels[0].compressed, 0); + const check = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, verify: true, onLog: () => {} }); + assert.equal(check.channels[0].verified, 5); + assert.deepEqual(check.channels[0].problems, []); +}); + +test("two forms of DIFFERENT content: refused, both kept, and listed — nothing removes a stored copy because another arrived", async () => { + await channel("beta", { b1: { "transcript.en.vtt": vtt("old", 20) } }); + await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + // A re-fetch (or Set as transcript) lands a new plain file beside it. + await writeFile(path.join(dirOf("beta", "b1"), "transcript.en.vtt"), vtt("new", 21)); + await utimes(path.join(dirOf("beta", "b1"), "transcript.en.vtt"), OLD, OLD); + const lines: string[] = []; + const r = await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) }); + const c = r.channels[0].byKind!.captions!; + assert.equal(c.compressed, 0); + assert.deepEqual(c.refused?.map((x) => [x.id, x.name, x.reason]), [["b1", "transcript.en.vtt", "both-differ"]]); + assert.match(lines.join(""), /b1\/transcript\.en\.vtt: refused — both-differ.*both files are kept/); + assert.match(lines.join(""), /1 refused with both forms kept/); + assert.deepEqual(await names("beta", "b1"), ["metadata.info.json", "transcript.en.vtt", "transcript.en.vtt.zst"]); + assert.equal(await readStoredText(dirOf("beta", "b1"), "transcript.en.vtt", "utf8"), vtt("new", 21), "plain is the truth"); + const check = await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, verify: true, onLog: () => {} }); + assert.deepEqual(check.channels[0].problems?.map((p) => p.status), ["differs"]); +}); + +test("left alone and counted: a recent file, a `.part` beside it, a video recording", async () => { + await channel("gamma", { + g1: { "transcript.en.vtt": vtt("recent", 10) }, + g2: { "transcript.en.vtt": vtt("partial", 10), "transcript.es.vtt.part": "half" }, + g3: { "transcript.en.vtt": vtt("live", 10), "live-recording.json": JSON.stringify({ status: "recording" }) }, + g4: { "transcript.en.vtt": vtt("refetch", 10), "transcript.en.vtt.part": "a download of the same track" }, + }); + // The quiet period asks the later of mtime and ctime: every file here was + // just made (ctime now), so the run's clock is 20 minutes on, and g1's + // mtime 15 minutes on — written 5 minutes before the run, by its clock. + const t0 = Date.now(); + await utimes(path.join(dirOf("gamma", "g1"), "transcript.en.vtt"), (t0 + 15 * 60_000) / 1000, (t0 + 15 * 60_000) / 1000); + const r = await compressText({ paths, slugs: ["gamma"], kinds: CAPTIONS, now: () => t0 + 20 * 60_000, onLog: () => {} }); + const c = r.channels[0].byKind!.captions!; + assert.equal(c.compressed, 1, "g2's en track only"); + assert.deepEqual(c.skipped, { recent: 1, recording: 1, partial: 1 }); + // The `.part` is of another track: the en track itself is not partial, and + // the es one has no plain form (only its partial): nothing to compress. + assert.equal((await names("gamma", "g2")).includes("transcript.en.vtt.zst"), true); + for (const id of ["g1", "g3", "g4"]) assert.equal((await names("gamma", id)).includes("transcript.en.vtt"), true, id); +}); + +const killAt = (point: string) => (p: string) => { + if (p === point) throw new CompressKill(p as never); +}; + +test("every kill point, then a job run: a whole copy at each point, and the job finishes it", async () => { + const points = ["compressing", "written", "verified", "placed", "retired"] as const; + // One channel per point: a run over a channel would first finish a video an + // earlier point left, and stop there. + for (const p of points) { + const slug = `delta-${p}`; + await channel(slug, { k1: { "transcript.en-orig.vtt": vtt(p, 30) } }); + await assert.rejects( + compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_990, crashAt: killAt(p) } }), + CompressKill, + p, + ); + // A whole copy, readable, whatever was left. + assert.equal(await readStoredText(dirOf(slug, "k1"), "transcript.en-orig.vtt", "utf8"), vtt(p, 30), `${p}: read back`); + if (p === "retired") { + assert.ok(!(await names(slug, "k1")).includes("transcript.en-orig.vtt"), "retired: the plain name is absent"); + assert.equal((await leftovers(slug, "k1")).length, 1, "the set-aside original"); + } + // The job's survey sees the file as work, whatever the point. + const plan = await compressText({ paths, slugs: [slug], kinds: CAPTIONS, dryRun: true, onLog: () => {} }); + assert.equal(plan.channels[0].pending, 1, `${p}: work for the job`); + const r = await compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.deepEqual(r.channels[0].failed, [], p); + assert.deepEqual(await leftovers(slug, "k1"), [], `${p}: no leftover`); + assert.deepEqual(await names(slug, "k1"), ["metadata.info.json", "transcript.en-orig.vtt.zst"], p); + assert.equal(await readStoredText(dirOf(slug, "k1"), "transcript.en-orig.vtt", "utf8"), vtt(p, 30), p); + } +}); + +test("restore over captions: the dry run is exact and touches nothing; a restore, killed, re-run — the plain files with their times", async () => { + await channel("eta", { h1: { "transcript.en.vtt": vtt("h1", 30), "transcript.de.vtt": vtt("de", 12) } }); + const before: Record<string, number> = {}; + for (const n of ["transcript.en.vtt", "transcript.de.vtt"]) before[n] = (await stat(path.join(dirOf("eta", "h1"), n))).mtimeMs; + await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + const tr = await tree(dirOf("eta", "h1")); + const plan = await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, dryRun: true, onLog: () => {} }); + assert.deepEqual(await tree(dirOf("eta", "h1")), tr); + assert.equal(plan.channels[0].estimateAfterBytes, vtt("h1", 30).length + vtt("de", 12).length); + await assert.rejects( + compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, onLog: () => {}, compressOpts: { pid: 999_999_991, crashAt: killAt("restore-placed") } }), + CompressKill, + ); + const r = await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, onLog: () => {} }); + assert.ok((r.channels[0].restored ?? 0) >= 1); + assert.deepEqual(await names("eta", "h1"), ["metadata.info.json", "transcript.de.vtt", "transcript.en.vtt"]); + for (const n of ["transcript.en.vtt", "transcript.de.vtt"]) { + assert.equal((await stat(path.join(dirOf("eta", "h1"), n))).mtimeMs, before[n], `${n}: the index key`); + } + assert.equal(await readFile(path.join(dirOf("eta", "h1"), "transcript.en.vtt"), "utf8"), vtt("h1", 30)); +}); + +test("both kinds: the live chat first, then the captions — each counted under its own kind", async () => { + await channel("theta", { t1: { "transcript.en.vtt": vtt("t1", 10), [CHAT]: '{"replayChatItemAction":{}}\n'.repeat(80) } }); + const lines: string[] = []; + const r = await compressText({ paths, slugs: ["theta"], kinds: ["captions", "live-chat"], quietMs: 0, onLog: (l) => lines.push(l) }); + assert.deepEqual(r.kinds, ["live-chat", "captions"], "the walk's order whatever was asked"); + assert.equal(r.channels[0].byKind!["live-chat"]!.compressed, 1); + assert.equal(r.channels[0].byKind!.captions!.compressed, 1); + assert.equal(r.channels[0].compressed, 2); + const text = lines.join(""); + assert.ok(text.indexOf("[live-chat]") < text.indexOf("[captions]"), text); + assert.deepEqual(await names("theta", "t1"), ["metadata.info.json", "transcript.en.vtt.zst", `${CHAT}.zst`]); +}); + +test("a caption that is a link into media/ (none on this corpus: the classifier never tiers one) is handled like a tiered chat", async () => { + const { symlink } = await import("node:fs/promises"); + await channel("iota", { i1: {} }); + const channelDir = path.join(paths.channelsDir, "iota"); + await mkdir(path.join(channelDir, "media", "i1"), { recursive: true }); + await writeFile(path.join(channelDir, "media", "i1", "transcript.en.vtt"), vtt("linked", 15)); + await symlink(path.join("..", "..", "media", "i1", "transcript.en.vtt"), path.join(dirOf("iota", "i1"), "transcript.en.vtt")); + const r = await compressText({ paths, slugs: ["iota"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.equal(r.channels[0].compressed, 1); + // The stored bytes beside the original's, on the same drive, with a link of their own. + assert.deepEqual(await readdir(path.join(channelDir, "media", "i1")), ["transcript.en.vtt.zst"]); + assert.equal(await readlink(path.join(dirOf("iota", "i1"), "transcript.en.vtt.zst")), path.join("..", "..", "media", "i1", "transcript.en.vtt.zst")); + assert.equal(await readStoredText(dirOf("iota", "i1"), "transcript.en.vtt", "utf8"), vtt("linked", 15)); +}); + +// REVIEW-1 F2: A DELETED CAPTION NEVER COMES BACK FROM A STOPPED RUN'S +// SET-ASIDE. A run killed at "retired" leaves the stored form and +// `.transcript.en.vtt.retire-<pid>-<token>` (the whole original). Every +// deleter removes the set-aside with the forms; and a set-aside found with NO +// stored form beside it (a deletion some other way) is not adopted: kept, +// listed for a person. +test("killed at retired, then the caption deleted by each deleter: the next captions run leaves it deleted", async () => { + const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs"); + const { removeStoredText, removeStoredTextForm } = await import("../lib/storedText-write-server"); + const ASR = + "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + + "Second<00:01:10.000><c> caption</c>\n"; + const deleters: Record<string, (dir: string, slug: string) => Promise<unknown>> = { + purge: (_dir, slug) => purgeSupersededAutoSubs({ channelSlug: slug, paths, onLog: () => {} }), + "removeStoredText (the clear-transcript fix)": (dir) => removeStoredText(dir, "transcript.en.vtt"), + "the files card (the stored form)": (dir) => removeStoredTextForm(dir, "transcript.en.vtt.zst"), + }; + let n = 0; + for (const [who, del] of Object.entries(deleters)) { + const slug = `kappa-${n++}`; + await channel(slug, { k1: { "transcript.en.vtt": ASR, "transcript.json": JSON.stringify({ transcription: [{ text: "ours" }] }) } }); + await assert.rejects( + compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_989, crashAt: killAt("retired") } }), + CompressKill, + ); + assert.equal((await leftovers(slug, "k1")).length, 1, `${who}: the set-aside is there`); + await del(dirOf(slug, "k1"), slug); + assert.deepEqual(await leftovers(slug, "k1"), [], `${who}: the deleter took the set-aside too`); + await compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.deepEqual( + (await names(slug, "k1")).filter((f) => f.includes(".vtt")), + [], + `${who}: still deleted, in every form`, + ); + } +}); + +test("a set-aside with no stored form beside it (deleted some other way) is NOT adopted: kept, listed for a person", async () => { + await channel("lambda", { l1: { "transcript.en.vtt": vtt("l1", 20) } }); + await assert.rejects( + compressText({ paths, slugs: ["lambda"], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_988, crashAt: killAt("retired") } }), + CompressKill, + ); + // Deleted by hand: the stored form only (the set-aside left). + await rm(path.join(dirOf("lambda", "l1"), "transcript.en.vtt.zst")); + const lines: string[] = []; + const r = await compressText({ paths, slugs: ["lambda"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) }); + const c = r.channels[0].byKind!.captions!; + assert.deepEqual(c.refused?.map((x) => [x.name, x.reason]), [["transcript.en.vtt", "retired-kept"]]); + assert.match(lines.join(""), /not adopted \(no stored form\)/); + assert.equal((await names("lambda", "l1")).includes("transcript.en.vtt"), false, "not brought back"); + assert.equal((await leftovers("lambda", "l1")).length, 1, "kept for a person"); +}); + +// REVIEW-1 N2: a pair refused once is recorded — the next run's survey counts +// it as waiting for a person (listed once by the dry run), not as work, and +// it is work again as soon as either form changes. +test("both forms differ: refused ONCE and recorded; later runs list it as waiting, not work, until a form changes", async () => { + await channel("mu", { m1: { "transcript.en.vtt": vtt("old", 20) } }); + await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + await writeFile(path.join(dirOf("mu", "m1"), "transcript.en.vtt"), vtt("new", 21)); + await utimes(path.join(dirOf("mu", "m1"), "transcript.en.vtt"), OLD, OLD); + const first = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.equal(first.channels[0].byKind!.captions!.refused?.length, 1); + const plan = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, dryRun: true, onLog: () => {} }); + assert.equal(plan.channels[0].pending, 0, "not work: the job is not started for it"); + assert.deepEqual(plan.channels[0].byKind!.captions!.differs, [{ id: "m1", name: "transcript.en.vtt" }]); + assert.match(plan.lines.join("\n"), /both forms differ, waiting for a person \(settle on the files card\): 1 — m1\/transcript\.en\.vtt/); + const lines: string[] = []; + const again = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) }); + assert.equal(again.channels[0].byKind!.captions!.refused?.length, 0, "not refused again"); + assert.match(lines.join(""), /1 with both forms differing still wait for a person/); + // A person settles it (the older stored copy deleted): work again — compressed. + await rm(path.join(dirOf("mu", "m1"), "transcript.en.vtt.zst")); + const settled = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + assert.equal(settled.channels[0].compressed, 1); + assert.equal(await readStoredText(dirOf("mu", "m1"), "transcript.en.vtt", "utf8"), vtt("new", 21)); +}); + +// REVIEW-2 N3: the original removed OUTSIDE the lock between the compressor's +// last look and its set-aside — yt-dlp's own overwrite deletes the plain +// caption and fetches after. The verified stored copy is KEPT: if the fetch +// fails it is the caption. +test("the original vanishes just before its set-aside (yt-dlp's overwrite): the verified stored copy is kept", async () => { + await channel("nu", { n1: { "transcript.en.vtt": vtt("n1", 20) } }); + const plain = path.join(dirOf("nu", "n1"), "transcript.en.vtt"); + const lines: string[] = []; + const r = await compressText({ + paths, + slugs: ["nu"], + kinds: CAPTIONS, + quietMs: 0, + onLog: (l) => lines.push(l), + compressOpts: { + crashAt: (p) => { + if (p === "placed") rmSync(plain); + }, + }, + }); + assert.equal(r.channels[0].byKind!.captions!.changed, 1); + assert.deepEqual(await names("nu", "n1"), ["metadata.info.json", "transcript.en.vtt.zst"]); + assert.equal(await readStoredText(dirOf("nu", "n1"), "transcript.en.vtt", "utf8"), vtt("n1", 20)); + assert.match(lines.join(""), /was removed while it was being compressed: the verified stored copy is kept/); +}); + +// REVIEW-2 N2: a deleter that cannot make the file's lock (a full disk, a +// read-only dir) REFUSES, removes nothing, throws nothing, leaves no temp. +test("a deleter that cannot make its lock refuses: nothing removed, no throw, no lock temp left", async () => { + const { chmod } = await import("node:fs/promises"); + const { removeStoredText, removeStoredTextForm } = await import("../lib/storedText-write-server"); + const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs"); + const ASR = + "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" + + "Second<00:01:10.000><c> caption</c>\n"; + await channel("xi", { x1: { "transcript.en.vtt": ASR, "transcript.json": JSON.stringify({ transcription: [{ text: "ours" }] }) } }); + await compressText({ paths, slugs: ["xi"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} }); + const d = dirOf("xi", "x1"); + const before = await names("xi", "x1"); + await chmod(d, 0o555); + try { + const a = await removeStoredText(d, "transcript.en.vtt"); + assert.ok("refused" in a && /not deleted: the stored-text lock cannot be made/.test(a.refused), JSON.stringify(a)); + const b = await removeStoredTextForm(d, "transcript.en.vtt.zst"); + assert.ok(typeof b === "object" && "refused" in b, JSON.stringify(b)); + const logs: string[] = []; + const p = await purgeSupersededAutoSubs({ channelSlug: "xi", paths, onLog: (m) => logs.push(m) }); + assert.equal(p.removedFiles, 0); + assert.match(logs.join("\n"), /Kept x1\/transcript\.en\.vtt — transcript\.en\.vtt not deleted/); + } finally { + await chmod(d, 0o755); + } + assert.deepEqual(await names("xi", "x1"), before, "nothing removed, no lock temp left"); +}); diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts @@ -1,9 +1,18 @@ -// 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 +// COMPRESS TEXT — the migration that puts existing big text files into their +// stored form (lib/storedText.ts), 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. +// then the original removed through removeMediaFile). `pnpm ops compress-text` +// posts it. Two KINDS: +// +// live-chat the raw live-chat replay, `transcript.live_chat.json` → `.zst` +// (lane text-compress, slice 2) — mostly on the media drive; +// captions every caption track, `transcript.<lang>.vtt` → `.zst` (lane +// text-compress-captions, slice 5) — on the CORPUS disk, real +// files in `data/<id>/` (the classifier never tiers one; a link, +// if one were there, is handled as the chat's are). +// +// `kinds` defaults to the live chat alone: captions are compressed only when a +// person names them. Both named: the live chat first, then the captions. // // SAFE BY CONSTRUCTION, RESUMABLE BY RE-WALKING. Every file is "already", // "compressed", skipped with a reason, or repaired by the compressor's crash @@ -16,36 +25,48 @@ // 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. +// `dryRun` WRITES NOTHING AND READS NO CONTENT: per channel and per kind, 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. For captions it also counts the en / en-orig PAIRS OF EQUAL +// SIZE (by the logical size): each is compressed as it is — never deduped — +// and the count says how much of the caption bytes are the pair twice. // `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. +// THE WALK VISITS EVERY FILE A RUN MAY HAVE TO FINISH: one whose plain form is +// there (a dangling tier link too — an interrupted removal), or whose stored +// form is (the restore), or a stopped run's leftover for it (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). +// TWO FORMS WITH DIFFERENT CONTENT — a plain caption a re-fetch or "Set as +// transcript" landed beside an older stored one — ARE REFUSED AND BOTH KEPT, +// and listed (`both-differ`, with the file): nothing removes a stored copy +// because a different one arrived. A video deleted on its platform cannot give +// its captions again. +// +// `restore: true` IS THE ROLLBACK: every stored file of the named kinds 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 { LIVE_CHAT_FILENAME, ORIG_VTT_FILENAME, VTT_FILENAME } from "../lib/videoStatus"; +import { isStoredCaptionName, logicalEntries, storedFormsIn, storedNameOf } from "../lib/storedText"; import { isKeptChatCapture } from "../lib/mediaTier"; import { frameContentSize } from "../lib/storedText-server"; import { compressStoredText, hasStoredTextLeftover, + bothDifferRecorded, + readStoredTextDiffers, restoreStoredText, + storedTextLeftoverNames, verifyStoredText, type CompressOutcome, type CompressSkipReason, @@ -55,12 +76,21 @@ 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 const COMPRESS_TEXT_KINDS = ["live-chat", "captions"] as const; export type CompressTextKind = (typeof COMPRESS_TEXT_KINDS)[number]; +export const DEFAULT_COMPRESS_TEXT_KINDS: readonly CompressTextKind[] = ["live-chat"]; + +export function isCompressTextKind(k: unknown): k is CompressTextKind { + return typeof k === "string" && (COMPRESS_TEXT_KINDS as readonly string[]).includes(k); +} -// 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. +// Measured on samples (lane text-compress design §1): a raw chat at level 9 +// is ~5 % of its size, a caption track ~20 %. Estimates, and every line that +// uses one says so. export const CHAT_RATIO_ESTIMATE = 0.05; +export const CAPTION_RATIO_ESTIMATE = 0.2; +const RATIO: Record<CompressTextKind, number> = { "live-chat": CHAT_RATIO_ESTIMATE, captions: CAPTION_RATIO_ESTIMATE }; +const NOUN: Record<CompressTextKind, string> = { "live-chat": "raw chat(s)", captions: "caption file(s)" }; 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; @@ -69,6 +99,8 @@ export type CompressTextOptions = { paths: Paths; // Default: every channel. slugs?: string[]; + // Default: the live chat alone (DEFAULT_COMPRESS_TEXT_KINDS). + kinds?: readonly CompressTextKind[]; dryRun?: boolean; verify?: boolean; // The rollback: stored → plain (with `dryRun`: the plan). @@ -91,18 +123,52 @@ export type CompressTextOptions = { compressOpts?: Parameters<typeof compressStoredText>[2]; }; +// One kind's figures for one channel (the same fields as the channel line). +export type KindLine = { + plainFiles: number; + plainBytes: number; + storedFiles: number; + storedLogicalBytes: number; + storedBytes: number; + // The files 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). + pending: number; + // Both forms with different content, recorded and unchanged since: waiting + // for a person (the files card), not work — each listed once. + differs?: { id: string; name: string }[]; + // Captions only: dirs whose `transcript.en.vtt` and `transcript.en-orig.vtt` + // are both here, in either form, with the same LOGICAL size (on samples of + // this corpus every such pair was byte-identical). Compressed each as it + // is; the count is for a person deciding on a dedupe. + pairsEqualSize?: number; + pairsEqualSizeBytes?: number; + estimateAfterBytes?: number; + compressed?: number; + restored?: number; + bytesBefore?: number; + bytesAfter?: number; + already?: number; + changed?: number; + skipped?: Partial<Record<CompressSkipReason, number>>; + failed?: { id: string; name: string; error: string }[]; + // Files left with BOTH forms of different content (or a stored form that + // does not decode): kept, both, for a person — listed. + refused?: { id: string; name: string; reason: CompressSkipReason; detail?: string }[]; + verified?: number; + problems?: { id: string; name: string; status: string; detail?: string }[]; +}; + export type ChannelLine = { slug: string; // Why the channel was not walked, when it was not. refused?: string; + // The totals over the kinds asked (with the live chat alone, exactly its + // figures, as before captions were a kind). 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 @@ -112,7 +178,7 @@ export type ChannelLine = { // 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. + // Dry run only: free space now on the disk(s) holding this channel's files. free?: { corpus?: number; media?: number }; // A real run. compressed?: number; @@ -121,26 +187,30 @@ export type ChannelLine = { already?: number; changed?: number; skipped?: Partial<Record<CompressSkipReason, number>>; - failed?: { id: string; error: string }[]; + failed?: { id: string; error: string; name?: string }[]; // A restore. restored?: number; // Verify. verified?: number; - problems?: { id: string; status: string; detail?: string }[]; + problems?: { id: string; status: string; detail?: string; name?: string }[]; + // Per kind asked. + byKind?: Partial<Record<CompressTextKind, KindLine>>; }; export type CompressTextResult = { dryRun: boolean; verify: boolean; restore: boolean; + kinds: CompressTextKind[]; 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 +// A file 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 }; +type Candidate = { id: string; videoDir: string; name: string; size: number }; +type Stored = { id: string; videoDir: string; name: string; bytes: number; logical: number }; function fmtBytes(n: number): string { if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`; @@ -192,67 +262,135 @@ async function storedLogicalSize(file: string): Promise<number | 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<{ +// The declared names of one kind in one dir's PHYSICAL listing: either form, +// or a stopped run's leftover for it. +function namesOfKind(kind: CompressTextKind, entries: readonly string[]): string[] { + if (kind === "live-chat") return [LIVE_CHAT_FILENAME]; + const names = new Set(logicalEntries(entries).filter(isStoredCaptionName)); + for (const n of storedTextLeftoverNames(entries)) if (isStoredCaptionName(n)) names.add(n); + return [...names].sort(); +} + +type KindSurvey = { plain: Candidate[]; - stored: { id: string; videoDir: string; bytes: number; logical: number }[]; - // Every dir a compress run visits: the plain form, present at all (a + stored: Stored[]; + // Every file 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. + // Every file a restore visits: the stored form, or a leftover. restoreWork: Candidate[]; - kept: { files: number; bytes: number }; -}> { + // Both forms present and recorded as differing, unchanged since: waiting + // for a person — never work (REVIEW-1 N2). + differs: Candidate[]; + pairsEqualSize: number; + pairsEqualSizeBytes: number; +}; + +// One channel's files of the kinds asked, by what is on disk. Sizes are +// `stat`s (through a tier link, under the drive's watchdog); no content is +// read beyond a stored file's 18-byte frame header. +async function surveyChannel( + channelDir: string, + drive: string | undefined, + kinds: readonly CompressTextKind[], +): Promise<{ byKind: Partial<Record<CompressTextKind, KindSurvey>>; 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 byKind: Partial<Record<CompressTextKind, KindSurvey>> = {}; + for (const k of kinds) { + byKind[k] = { plain: [], stored: [], work: [], restoreWork: [], differs: [], pairsEqualSize: 0, pairsEqualSizeBytes: 0 }; + } const kept = { files: 0, bytes: 0 }; - const sizeOf = (p: string) => + const differs = await readStoredTextDiffers(channelDir); + const sizeOfMedia = (p: string) => (drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null); + const logicalOfMedia = (p: string) => (drive ? onDrive(drive, () => storedLogicalSize(p)) : storedLogicalSize(p)).catch(() => 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 (kinds.includes("live-chat")) { + for (const k of entries.filter(isKeptChatCapture)) { + kept.files += 1; + kept.bytes += (await sizeOfMedia(path.join(videoDir, k))) ?? 0; + } } - 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 }); + for (const kind of kinds) { + const s = byKind[kind]!; + // Captions are on the corpus disk (never tiered): stat them directly, + // never under the media drive's watchdog (REVIEW-1 N4). + const sizeOf = kind === "live-chat" ? sizeOfMedia : (p: string) => stat(p).then((st) => st.size, () => null); + const logicalOf = kind === "live-chat" ? logicalOfMedia : (p: string) => storedLogicalSize(p); + const logicalSize: Record<string, number | null> = {}; + for (const name of namesOfKind(kind, entries)) { + const forms = storedFormsIn(entries, name); + const leftover = hasStoredTextLeftover(entries, name); + let size: number | null = null; + if (forms === "plain" || forms === "both") { + size = await sizeOf(path.join(videoDir, name)); + if (size !== null) s.plain.push({ id, videoDir, name, size }); + logicalSize[name] = size; + } + const waiting = forms === "both" && !leftover && (await bothDifferRecorded(differs, videoDir, name)); + if (waiting) s.differs.push({ id, videoDir, name, size: size ?? 0 }); + else if (forms === "plain" || forms === "both" || leftover) s.work.push({ id, videoDir, name, size: size ?? 0 }); + if (forms === "zst" || forms === "both" || leftover) s.restoreWork.push({ id, videoDir, name, size: 0 }); + if (forms === "zst" || forms === "both") { + const zp = path.join(videoDir, storedNameOf(name)); + const bytes = await sizeOf(zp); + const logical = bytes === null ? null : await logicalOf(zp); + if (bytes !== null) s.stored.push({ id, videoDir, name, bytes, logical: logical ?? 0 }); + // The plain form, when it is here, is the truth (lib/storedText.ts). + if (forms === "zst") logicalSize[name] = logical; + } + } + if (kind === "captions") { + const en = logicalSize[VTT_FILENAME]; + const orig = logicalSize[ORIG_VTT_FILENAME]; + if (typeof en === "number" && en === orig) { + s.pairsEqualSize += 1; + s.pairsEqualSizeBytes += en; + } + } } } // 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 }; + const bySize = (a: Candidate, b: Candidate) => + a.size - b.size || (a.id < b.id ? -1 : a.id > b.id ? 1 : a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + for (const s of Object.values(byKind)) { + s!.plain.sort(bySize); + s!.work.sort(bySize); + } + return { byKind, kept }; +} + +function emptyKindLine(s: KindSurvey, restore: boolean): KindLine { + return { + differs: s.differs.map((d) => ({ id: d.id, name: d.name })), + plainFiles: s.plain.length, + plainBytes: s.plain.reduce((a, c) => a + c.size, 0), + storedFiles: s.stored.length, + storedBytes: s.stored.reduce((a, c) => a + c.bytes, 0), + storedLogicalBytes: s.stored.reduce((a, c) => a + c.logical, 0), + pending: (restore ? s.restoreWork : s.work).length, + }; +} + +const sum = (lines: KindLine[], f: (l: KindLine) => number | undefined) => lines.reduce((a, l) => a + (f(l) ?? 0), 0); + +function mergeSkipped(into: Partial<Record<CompressSkipReason, number>>, from: Partial<Record<CompressSkipReason, number>> | undefined) { + for (const [r, n] of Object.entries(from ?? {})) { + into[r as CompressSkipReason] = (into[r as CompressSkipReason] ?? 0) + (n ?? 0); + } } 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; + // In the walk's order: the live chat first (the media drive), then captions. + const asked = opts.kinds && opts.kinds.length > 0 ? opts.kinds : DEFAULT_COMPRESS_TEXT_KINDS; + const kinds = COMPRESS_TEXT_KINDS.filter((k) => asked.includes(k)); const lines: string[] = []; const say = (line: string) => { lines.push(line); @@ -266,6 +404,7 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT // Files compressed (or restored) this run: what `limit` counts. let doneThisRun = 0; let stopped: CompressTextResult["stopped"]; + const label = (k: CompressTextKind) => (kinds.length > 1 ? ` [${k}]` : ""); for (const slug of slugs) { if (stopped) break; @@ -291,216 +430,262 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT 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 { byKind: survey, kept } = await surveyChannel(channelDir, drive, kinds); + if (kinds.includes("live-chat")) { + 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); + const kl: Partial<Record<CompressTextKind, KindLine>> = {}; + for (const k of kinds) kl[k] = emptyKindLine(survey[k]!, restore); + line.byKind = kl; + const all = kinds.map((k) => kl[k]!); + line.plainFiles = sum(all, (l) => l.plainFiles); + line.plainBytes = sum(all, (l) => l.plainBytes); + line.storedFiles = sum(all, (l) => l.storedFiles); + line.storedBytes = sum(all, (l) => l.storedBytes); + line.storedLogicalBytes = sum(all, (l) => l.storedLogicalBytes); + line.pending = sum(all, (l) => l.pending); + if (kinds.includes("captions")) { + kl.captions!.pairsEqualSize = survey.captions!.pairsEqualSize; + kl.captions!.pairsEqualSizeBytes = survey.captions!.pairsEqualSizeBytes; + } + const freeOf = (p: string) => statfs(p).then((f) => f.bavail * f.bsize, () => undefined); + const freeLine = async () => { 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; - } + }; + // Which disk a kind's files are on: the chat on the media drive when the + // channel has one, captions on the corpus disk (never tiered). + const freeText = (k: CompressTextKind) => + k === "live-chat" && drive + ? `free on the media drive ${fmtBytes(line.free?.media ?? 0)}` + : `free on the corpus disk ${fmtBytes(line.free?.corpus ?? 0)}`; + const differsText = (k: CompressTextKind) => { + const d = kl[k]!.differs ?? []; + return d.length + ? `; both forms differ, waiting for a person (settle on the files card): ${d.length} — ` + + `${d.slice(0, 10).map((x) => `${x.id}/${x.name}`).join(", ")}${d.length > 10 ? `, … ${d.length - 10} more` : ""}` + : ""; + }; + const pairsText = (k: CompressTextKind) => { + const c = kl[k]!; + return k === "captions" && c.pairsEqualSize + ? `; en / en-orig pairs of equal size: ${c.pairsEqualSize} (${fmtBytes(c.pairsEqualSizeBytes ?? 0)} each side — compressed each as it is, not deduped)` + : ""; + }; - 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`); - } + if (dryRun && restore) { + // Exact, from the frame headers: what the plain files will take again. + line.estimateAfterBytes = line.storedLogicalBytes; + await freeLine(); + for (const k of kinds) { + const c = kl[k]!; + c.estimateAfterBytes = c.storedLogicalBytes; + if (c.storedFiles + (k === "live-chat" ? kept.files : 0) > 0) { + say( + `${slug}${label(k)}: ${c.storedFiles} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ` + + `${fmtBytes(c.storedBytes)} → ${fmtBytes(c.storedLogicalBytes)} as plain files; ${freeText(k)}` + + `${k === "live-chat" ? keptText : ""}`, + ); } } - 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}`, - ); + await freeLine(); + for (const k of kinds) { + const c = kl[k]!; + c.estimateAfterBytes = Math.round(c.plainBytes * RATIO[k]); + if (c.plainFiles + c.storedFiles + (c.differs?.length ?? 0) + (k === "live-chat" ? kept.files : 0) > 0) { + say( + `${slug}${label(k)}: ${c.plainFiles} ${NOUN[k]}, ${fmtBytes(c.plainBytes)} → ~${fmtBytes(c.estimateAfterBytes)} ` + + `(estimate, ${Math.round(RATIO[k] * 100)} %); already stored ${c.storedFiles} ` + + `(${fmtBytes(c.storedBytes)} holding ${fmtBytes(c.storedLogicalBytes)}); ${freeText(k)}` + + `${pairsText(k)}${differsText(k)}${k === "live-chat" ? keptText : ""}`, + ); + } } + line.estimateAfterBytes = sum(all, (l) => l.estimateAfterBytes); 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}` : ""}`); + for (const k of kinds) { + const c = kl[k]!; + c.verified = 0; + c.problems = []; + for (const s of survey[k]!.stored) { + if (opts.signal?.aborted) { stopped = "cancelled"; break; } + if (opts.drainSignal?.aborted) { stopped = "drained"; break; } + const v = await verifyStoredText(s.videoDir, s.name, { throttle }); + if (v.status === "ok") { + c.verified += 1; + line.verified += 1; + } else { + const p = { id: s.id, name: s.name, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) }; + c.problems.push(p); + line.problems.push(p); + say(`${slug}/${s.id}/${s.name}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`); + } } + say(`${slug}${label(k)}: verified ${c.verified} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ${c.problems.length} problem(s)`); + if (stopped) break; } - say(`${slug}: verified ${line.verified} stored chat(s), ${line.problems.length} problem(s)`); continue; } - line.compressed = 0; + // ── a real run: compress, or restore ──────────────────────────────────── 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.already = 0; 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; } + if (restore) line.restored = 0; + else line.compressed = 0; + for (const k of kinds) { + const c = kl[k]!; + const s = survey[k]!; + c.bytesBefore = 0; + c.bytesAfter = 0; + c.changed = 0; + c.skipped = {}; + c.failed = []; + c.refused = []; + const work = restore ? s.restoreWork : s.work; + if (restore) { + c.restored = 0; + c.already = 0; + } else { + c.compressed = 0; + // A stored file with nothing to finish is "already"; one in `work` + // says so itself. + const inWork = new Set(work.map((w) => `${w.id}/${w.name}`)); + c.already = s.stored.filter((z) => !inWork.has(`${z.id}/${z.name}`)).length; } - 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, + for (const w 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; } + } + const runOpts = { + isBusy: opts.isBusy ? () => opts.isBusy!(slug, w.id) : undefined, throttle, ...(opts.signal ? { signal: opts.signal } : {}), - onLog: (l) => opts.onLog(`${l}\n`), + onLog: (l: string) => 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`); + }; + let out: CompressOutcome | RestoreOutcome; + try { + out = restore + ? await restoreStoredText(w.videoDir, w.name, runOpts) + : await compressStoredText(w.videoDir, w.name, { + quietMs: opts.quietMs ?? COMPRESS_QUIET_MS, + now, + ...runOpts, + }); + } catch (err) { + if ((err as Error).name === "CompressKill") throw err; + c.failed.push({ id: w.id, name: w.name, error: (err as Error).message }); + say( + `${slug}/${w.id}/${w.name}: failed — ${(err as Error).message} ` + + `(${restore ? "the stored file" : "the original"} is untouched)`, + ); + continue; + } + const where = k === "live-chat" ? `${slug}/${w.id}` : `${slug}/${w.id}/${w.name}`; + if (out.status === "compressed" || out.status === "restored") { + doneThisRun += 1; + if (out.status === "compressed") c.compressed! += 1; + else c.restored! += 1; + c.bytesBefore += out.before; + c.bytesAfter += out.after; + opts.onLog( + `${where}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${restore ? " (restored)" : ""}${out.tiered ? " (media tier)" : ""}\n`, + ); + } else if (out.status === "already") { + c.already += 1; + } else if (out.status === "changed") { + c.changed += 1; + } else if (out.status === "skipped") { + c.skipped[out.reason] = (c.skipped[out.reason] ?? 0) + 1; + if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") { + c.refused.push({ id: w.id, name: w.name, reason: out.reason, ...(out.detail ? { detail: out.detail } : {}) }); + say(`${where}: 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}`, - ); + // The channel's totals. + line.bytesBefore += c.bytesBefore; + line.bytesAfter += c.bytesAfter; + line.already += c.already; + line.changed += c.changed; + mergeSkipped(line.skipped, c.skipped); + line.failed.push(...c.failed); + if (restore) line.restored! += c.restored!; + else line.compressed! += c.compressed!; + const skippedText = Object.entries(c.skipped).map(([r, n]) => `${n} ${r}`).join(", "); + if (restore && work.length > 0) { + say( + `${slug}${label(k)}: restored ${c.restored} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` + + `already plain ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`, + ); + } else if (!restore && work.length + c.storedFiles > 0) { + say( + `${slug}${label(k)}: compressed ${c.compressed} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` + + `already ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`, + ); + } + if (stopped) break; } } + const kindsText = kinds.map((k) => NOUN[k]).join(" and "); + const storedNoun = kinds.map((k) => (k === "live-chat" ? "chat(s)" : "caption file(s)")).join(" and "); 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.`); + say(`Dry run (restore): ${n} stored ${storedNoun} → ${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` : ""}.`); + say(`Restored ${r} ${kindsText} 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 parts = kinds.map((k) => { + const n = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainFiles ?? 0), 0); + const b = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainBytes ?? 0), 0); + return `${n} ${NOUN[k]}, ${fmtBytes(b)} → ~${fmtBytes(Math.round(b * RATIO[k]))}`; + }); const kf = channels.reduce((a, c) => a + (c.keptCaptures ?? 0), 0); const kb = channels.reduce((a, c) => a + (c.keptCaptureBytes ?? 0), 0); + const pf = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSize ?? 0), 0); + const pb = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSizeBytes ?? 0), 0); say( - `Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate)` + + `Dry run: ${parts.join("; ")} (estimate)` + + `${pf ? `; en / en-orig pairs of equal size: ${pf} (${fmtBytes(pb)} each side), compressed each as it is` : ""}` + `${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` : ""}.`); + const refused = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.refused?.length ?? 0), 0), 0); + const waiting = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.differs?.length ?? 0), 0), 0); + say( + `Compressed ${c} ${kindsText}: ${fmtBytes(b)} → ${fmtBytes(f)}` + + `${refused ? `; ${refused} refused with both forms kept (listed above, and recorded: not work again until one changes)` : ""}` + + `${waiting ? `; ${waiting} with both forms differing still wait for a person (the dry run lists them)` : ""}` + + `${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`, + ); } - return { dryRun, verify, restore, channels, ...(stopped ? { stopped } : {}), lines }; + return { dryRun, verify, restore, kinds: [...kinds], channels, ...(stopped ? { stopped } : {}), lines }; } diff --git a/common/controller/copies.test.ts b/common/controller/copies.test.ts @@ -103,21 +103,40 @@ function vtt(lines: number, text: (i: number) => string, asr = false): string { return out; } -function channel(p: Paths, slug: string): void { +function channel(p: Paths, slug: string, extra: Record<string, unknown> = {}): void { mkdirSync(path.join(p.channelsDir, slug, "data"), { recursive: true }); - writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe" })); + writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe", ...extra })); } function video( p: Paths, slug: string, dir: string, - o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean | number; audio?: boolean; id?: string }, + o: { + date: string; + duration: number; + cues?: ReturnType<typeof cues>; + transcript?: boolean | number; + audio?: boolean; + id?: string; + title?: string; + // A finished live stream (yt-dlp's live_status "was_live"). + live?: boolean; + }, ): void { const d = path.join(p.channelsDir, slug, "data", dir); mkdirSync(d, { recursive: true }); const id = o.id ?? dir; - writeFileSync(path.join(d, "metadata.info.json"), JSON.stringify({ id, title: `Stream ${id}`, duration: o.duration, upload_date: o.date })); + writeFileSync( + path.join(d, "metadata.info.json"), + JSON.stringify({ + id, + title: o.title ?? `Stream ${id}`, + duration: o.duration, + upload_date: o.date, + ...(o.live ? { live_status: "was_live", was_live: true } : {}), + }), + ); if (o.cues) writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id, cues: o.cues })); // A real-length transcript by default: 20 words a minute of runtime. if (o.transcript) writeFileSync(path.join(d, "transcript.json"), whisperJson(typeof o.transcript === "number" ? o.transcript : Math.ceil((o.duration / 60) * 20))); @@ -262,6 +281,90 @@ test("a cancelled scan stops between pairs and writes nothing", async () => { assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"], "no copies file"); }); +// A RE-UPLOAD channel and a LIVE mirror of the same streams (the shape of the +// first real scan's fault): the re-uploads went up months after the streams and +// carry the stream's day only in their titles; the mirror's videos are the live +// streams themselves, dated by their own day. No recordedDate rule is set. +function reuploads(p: Paths, prefConfig: Record<string, unknown> = {}): void { + channel(p, "pref-chan", prefConfig); + channel(p, "mirror-chan"); + video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "2023-04-05 the long stream", cues: cues(1) }); + video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "2023 04 08 another stream" }); + video(p, "pref-chan", "p3", { date: "20260312", duration: 3000, title: "2023 Apr 20 a short one" }); + video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, title: "[Copy] stream", cues: cues(1, 45), audio: true }); + video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, title: "[Copy] stream", cues: cues(2), audio: true }); +} + +test("a re-upload channel dated only in its titles is paired with the live copies (fails against upload-date dating)", async () => { + const p = corpus(); + reuploads(p); + const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true }); + const f = out.file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.a.dateFrom, x.b.dateFrom]), + [ + ["pref-chan/p1|mirror-chan/m1", "confirmed", "title", "live"], + ["pref-chan/p2|mirror-chan/m2", "metadata", "title", "live"], + ], + ); + assert.deepEqual(f.pairs[0].a.date, "20230405", "the stream's day, not the upload's"); + assert.equal(f.dating?.["pref-chan"].detectedPattern !== undefined, true); + assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 0, live: 0, title: 3, upload: 0, none: 0 }); + assert.deepEqual(f.dating?.["mirror-chan"].byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 }); + // The scan SAYS the channel lacks its rule, with the exact patch to set it. + const advice = (f.advice ?? []).join("\n"); + assert.match(advice, /pref-chan: 3 of 3 videos are dated by a date their titles carry/); + const patch = /pnpm ops channel-config --json '(.*?)'/.exec(advice)?.[1]; + assert.ok(patch, advice); + const body = JSON.parse(patch!); + assert.equal(body.slug, "pref-chan"); + assert.equal(new RegExp(body.patch.recordedDateTitlePattern, "i").test("2023-04-05 the long stream"), true); + assert.doesNotMatch(advice, /mirror-chan/, "a live channel is dated by its streams: nothing to set"); +}); + +test("the channel's own recordedDate rule dates its videos first, and no advice asks for one", async () => { + const p = corpus(); + reuploads(p, { recordedDate: { titlePattern: "^(?<year>\\d{4})[- ](?<month>\\d{2})[- ](?<day>\\d{2})" } }); + const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.a.dateFrom]), + [ + ["pref-chan/p1|mirror-chan/m1", "confirmed", "rule"], + ["pref-chan/p2|mirror-chan/m2", "metadata", "rule"], + ], + ); + // p3's "2023 Apr 20" is not the rule's shape: the rule is the operator's word, + // so the scan does not guess past it — p3 keeps its upload date. + assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 2, live: 0, title: 0, upload: 1, none: 0 }); + assert.equal(f.dating?.["pref-chan"].detectedPattern, undefined); + assert.doesNotMatch((f.advice ?? []).join("\n"), /recordedDateTitlePattern/); + // A ruled channel is never searched by runtime: the scan is main's. + assert.equal(f.totals.runtime, undefined); +}); + +test("with no date to go by, a copy is found by runtime and words, never held on runtime alone, and the search is bounded", async () => { + const p = corpus(); + channel(p, "pref-chan"); + channel(p, "mirror-chan"); + // Re-uploads whose titles carry no date: their upload day is the copy's. + video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "Stream highlights", cues: cues(1) }); + video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "Another stream" }); + video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, cues: cues(1, 45), audio: true }); + video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, cues: cues(2), audio: true }); + video(p, "mirror-chan", "m3", { date: "20230409", duration: 7190, live: true, cues: cues(3), audio: true }); + const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; + assert.deepEqual( + f.pairs.map((x) => [x.key, x.link, x.evidence.via]), + [["pref-chan/p1|mirror-chan/m1", "confirmed", "runtime"]], + "p2 has no words: a runtime alone is no evidence, so no pair (and no hold)", + ); + assert.equal(f.totals.candidates, 0, "nothing was dated near anything"); + assert.deepEqual(f.totals.runtime, { searched: 1, candidates: 3, rejected: 2, capped: 0 }); + const advice = (f.advice ?? []).join("\n"); + assert.match(advice, /pref-chan: 2 of 2 videos have only an upload date/); + assert.match(advice, /no two members' videos are dated within 1 day/); +}); + async function lane(p: Paths, kind: "transcription" | "backfill" = "transcription") { resetCopiesLaneCacheForTest(); return computeLeafPending(kind, p, { state: emptyAutoQueueState() }); diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts @@ -30,6 +30,8 @@ import { isGroup, type AutoQueueKind, type AutoQueueNode, type AutoQueuePolicy } import { mapConcurrent } from "../lib/concurrency"; import { isTranscriptVtt, readVideoFiles, resolvePrimaryVtt, WHISPER_FILENAME } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; +import { isStoredTextName, logicalEntries, storedNameOf } from "../lib/storedText"; +import { isStoredTextReadError, readStoredText } from "../lib/storedText-server"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { operationsForLane } from "../lib/operations"; import { DIARIZATION_FILENAME } from "../lib/videoStatus"; @@ -74,13 +76,22 @@ export type CopiesLaneIo = { readFile: (p: string) => Promise<string>; readdir: (p: string) => Promise<string[]>; stat: (p: string) => Promise<{ mtimeMs: number; size: number }>; + // A caption's text in either form (lib/storedText.ts). A test's seam may + // leave it out: the plain file is read through `readFile` then. + readCaption?: (dir: string, name: string) => Promise<string>; }; const realIo: CopiesLaneIo = { readFile: (p) => readFile(p, "utf8"), readdir: (p) => readdir(p), stat: (p) => stat(p), + readCaption: (dir, name) => readStoredText(dir, name, "utf8"), }; let io: CopiesLaneIo = realIo; +// Stored captions this process found unreadable (REVIEW-1 F3): counted. +let unreadableStoredCaptions = 0; +export function unreadableStoredCaptionCount(): number { + return unreadableStoredCaptions; +} let revalidateMs = COPY_DONE_REVALIDATE_MS; // What the lanes need to know about a video of a group, beyond its pairs. @@ -224,7 +235,10 @@ type DoneRules = { // The files that decide a video's done state for the lane, with their sizes // and mtimes: equal signatures, equal answers. async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig: string; entries: string[] }> { - const entries = (await io.readdir(videoDir).catch(() => [] as string[])).sort(); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is listed under + // its plain name, and stamped by the form that is there. + const physical = await io.readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physical).sort(); const decisive = kind === "transcription" ? entries.filter((e) => e === WHISPER_FILENAME || isTranscriptVtt(e)) @@ -236,7 +250,11 @@ async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig e === ATTRIBUTION_FILENAME || e === AUDIO_INTEGRITY_FILENAME, ); - const stamps = await Promise.all(decisive.map((e) => stampOf(path.join(videoDir, e)))); + const stamps = await Promise.all( + decisive.map((e) => + stampOf(path.join(videoDir, physical.includes(e) || !isStoredTextName(e) ? e : storedNameOf(e))), + ), + ); // The Speakers states also turn on which other files are there (audio, a // container), so the backfill signature carries the whole listing. return { sig: JSON.stringify([kind === "backfill" ? entries : decisive, stamps]), entries }; @@ -268,9 +286,13 @@ async function transcriptDone(videoDir: string, entries: readonly string[], rule if (rules.replaceAutoSubs && (await resolveCaptionsProvenance(videoDir, entries)) === "asr") return false; try { let words = 0; - for (const cue of parseVtt(await io.readFile(path.join(videoDir, vtt)))) words += speechWords(cue.text); + const text = io.readCaption ? await io.readCaption(videoDir, vtt) : await io.readFile(path.join(videoDir, vtt)); + for (const cue of parseVtt(text)) words += speechWords(cue.text); return words >= min; - } catch { + } catch (err) { + // A stored caption that does not decode is not "no transcript" (REVIEW-1 + // F3): computeDone answers it. + if (isStoredTextReadError(err)) throw err; return false; } } @@ -307,12 +329,24 @@ async function computeDone( try { if (kind === "transcription") return await transcriptDone(path.join(paths.channelsDir, channel, "data", dir), entries, rules); if (kind === "backfill") return await speakersDone(paths, settings, channel, dir); - } catch { + } catch (err) { + // A STORED CAPTION THAT DOES NOT DECODE is an error, never "not done" + // (REVIEW-1 F3, captions lane): "not done" would send the lane to + // transcribe the video's copy over it. Counted as done (no work made + // from it), and said, with the path. + if (isStoredTextReadError(err)) { + unreadableStoredCaptions += 1; + console.warn(`[copies] ${key}: a stored caption cannot be read — ${(err as Error).message}; not counted as work`); + return true; + } // unreadable: not done } return false; } +// Exported for its test ONLY (controller/storedText.unreadable.test.ts). +export const __computeDoneForTest = computeDone; + /** * Whether each `<channel>/<dir>` has this lane's work done and readable. A copy * seen before answers from the cache at once; one never seen is read now. diff --git a/common/controller/copiesScan.ts b/common/controller/copiesScan.ts @@ -26,16 +26,18 @@ import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { isRealAudioFile } from "../lib/mediaFiles"; import { inspectChannelMedia } from "../lib/channelMedia"; import { isMediaHeld } from "../lib/channelMediaHold"; -import { contentDate } from "../lib/mirrors/match"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { readChannelConfig } from "./channels"; import { readChannelRecords } from "./mirrorScan"; import { classifyCandidate, copyCandidates, + COPY_RUNTIME_PER_VIDEO, cuesToWords, prepareCopyText, + runtimeCandidates, textEvidence, + wantsRuntimeSearch, type CopyRecord, type CopyText, type TextEvidence, @@ -55,6 +57,7 @@ import { } from "../lib/copies/file"; import { readCopiesDecisions, readCopiesFile, updateCopiesDecisions, writeCopiesFile } from "../lib/copies/file-server"; import { SOURCE_GROUP_ID_RE, type SourceGroup } from "../lib/copies/settings"; +import { dateChannel, datingAdvice, noCandidatesAdvice, type ChannelDating, type DatedChannel } from "../lib/copies/dating"; export const COPIES_SCAN_JOB_KIND = "copies-scan"; // One scan at a time, machine-wide: each reads thousands of cue files. @@ -117,7 +120,22 @@ export class CopiesScanCancelled extends Error { } function member(r: CopyRecord): CopyMember { - return { channel: r.channel, dir: r.dir, id: r.id, title: r.title, duration: r.duration, date: r.date }; + return { + channel: r.channel, + dir: r.dir, + id: r.id, + title: r.title, + duration: r.duration, + date: r.date, + ...(r.dateFrom !== undefined ? { dateFrom: r.dateFrom } : {}), + }; +} + +async function hasCuesFile(paths: Paths, r: CopyRecord): Promise<boolean> { + return stat(path.join(paths.channelsDir, r.channel, "data", r.dir, CUES_JSON_FILENAME)).then( + (s) => s.isFile() && s.size > 0, + () => false, + ); } export type CopiesScanOptions = { @@ -138,7 +156,7 @@ export type CopiesScanOutcome = { // The file's content without the per-run stamps, for "did anything change". function contentOf(f: CopiesFile): string { - return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals]); + return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals, f.dating ?? {}, f.advice ?? []]); } export async function runCopiesScan( @@ -169,27 +187,78 @@ export async function runCopiesScan( const missing: string[] = []; const records: CopyRecord[] = []; const videos: Record<string, number> = {}; + const datings = new Map<string, DatedChannel<{ title: string; uploadDate: string; recordedDate?: string; wasLive: boolean }>>(); let undated = 0; for (const slug of group.channels) { checkCancel(); - if (!(await readChannelConfig(paths, slug))) { + const config = await readChannelConfig(paths, slug); + if (!config) { missing.push(slug); continue; } const c = await readChannelRecords(paths, slug); videos[slug] = c.records.length; - for (const r of c.records) { - const date = contentDate(r); + // DATED BY THE BEST EVIDENCE EACH VIDEO HAS (lib/copies/dating.ts): the + // channel's rule, a live stream's own day, a date its titles carry, its upload. + const d = dateChannel(c.records, !!config.recordedDate); + datings.set(slug, d); + for (const { record: r, date, from } of d.dated) { if (!date) undated++; - records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date }); + records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date, dateFrom: from }); } - log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk)`); + const by = Object.entries(d.dating.byFrom) + .filter(([, n]) => n > 0) + .map(([k, n]) => `${n} by ${k === "none" ? "nothing (undated)" : k}`) + .join(", "); + log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk); dated ${by || "none"}`); } if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`); const candidates = copyCandidates(group, records); log(`${candidates.length} candidate pairs dated within ${group.dateWindowDays} day(s)`); + // THE RUNTIME SEARCH for videos whose date cannot pair them (only an upload + // day, or none) and that found no candidate by date: bounded, and decided by + // the words only (lib/copies/match.ts runtimeCandidates). + const pairedByDate = new Set<string>(); + for (const c of candidates) { + if (c.a.channel === c.b.channel) continue; + pairedByDate.add(`${c.a.channel}/${c.a.dir}`); + pairedByDate.add(`${c.b.channel}/${c.b.dir}`); + } + const ruled = new Set([...datings].filter(([, d]) => d.dating.ruleSet).map(([slug]) => slug)); + const textKnown = new Set<string>(); + if (wantsRuntimeSearch(records, ruled)) { + for (const r of records) { + await breathe(); + if (r.duration > 0 && (await hasCuesFile(paths, r))) textKnown.add(`${r.channel}/${r.dir}`); + } + } + const search = await runtimeCandidates(group, records, { + hasText: (r) => textKnown.has(`${r.channel}/${r.dir}`), + dated: pairedByDate, + ruled, + breathe, + }); + if (search.searched > 0 || search.capped > 0) { + log( + `${search.candidates.length} candidate pairs by runtime for ${search.searched} video(s) with no date to pair by` + + `${search.capped ? ` (${search.capped} more left unsearched: the scan's cap)` : ""}`, + ); + } + const runtimeSentence = + search.searched > 0 || search.capped > 0 + ? `Those with words were looked for by runtime instead (at most ${COPY_RUNTIME_PER_VIDEO} nearest each): ${search.searched} searched, ` + + `${search.candidates.length} compared${search.capped ? `, ${search.capped} left unsearched by the cap` : ""}.` + : null; + const advice: string[] = []; + for (const [slug, d] of datings) advice.push(...datingAdvice(slug, d, d.dating.byFrom.upload + d.dating.byFrom.none > 0 ? runtimeSentence : null)); + const crossDated = candidates.some((c) => c.a.channel !== c.b.channel); + if (!crossDated && datings.size >= 2 && records.length > 0) { + advice.push(noCandidatesAdvice(group.dateWindowDays, [...datings].map(([slug, d]) => ({ slug, span: d.dating.span })))); + } + for (const a of advice) log(`note: ${a}`); + // A small cache of words and their phrase index: candidates come grouped // by their `a` side, so each is built once per run of its candidates. const cache = new Map<string, CopyText | null>(); @@ -219,16 +288,22 @@ export async function runCopiesScan( overlaps: 0, rejected: 0, withinChannel: 0, + ...(search.searched > 0 || search.capped > 0 + ? { runtime: { searched: search.searched, candidates: search.candidates.length, rejected: 0, capped: search.capped } } + : {}), }; const pairs: CopyPairRecord[] = []; - for (const c of candidates) { + for (const c of [...candidates, ...search.candidates]) { await breathe(); const [wa, wb] = [await wordsOf(c.a), await wordsOf(c.b)]; const text: TextEvidence | null = wa && wb ? textEvidence(wa, wb) : null; const usable = text && text.verdict !== "no-text" ? text : null; const cls = classifyCandidate(c, usable); if (!cls) { - if (usable) totals.rejected++; + if (usable) { + if (c.via === "runtime") totals.runtime!.rejected++; + else totals.rejected++; + } continue; } const { link } = cls; @@ -246,6 +321,7 @@ export async function runCopiesScan( withinChannel, evidence: { kind: usable ? "text" : "metadata", + via: c.via ?? "date", dateDeltaDays: c.dateDeltaDays, durationOk: c.durationOk, ...(usable ? { text: usable } : {}), @@ -269,6 +345,8 @@ export async function runCopiesScan( }, pairs, totals, + dating: Object.fromEntries([...datings].map(([slug, d]) => [slug, d.dating])) as Record<string, ChannelDating>, + ...(advice.length > 0 ? { advice } : {}), }; log( `${totals.confirmed} confirmed by text and runtime, ${totals.metadata} metadata only, ${totals.partOf} part of ` + @@ -293,6 +371,8 @@ export function copiesScanSummary(out: CopiesScanOutcome, dryRun: boolean) { channels: f.channels, ...(f.missing ? { missing: f.missing } : {}), totals: f.totals, + ...(f.dating ? { dating: f.dating } : {}), + ...(f.advice ? { advice: f.advice } : {}), }; } @@ -544,6 +624,8 @@ export type CopiesGroupReport = { jobId?: string; totals: CopiesTotals; missing?: string[]; + // What the scan said about its own inputs (CopiesFile.advice). + advice?: string[]; }; // Cross-channel pairs by link (a metadata pair a person confirmed counts as // confirmed; a rejected pair counts nowhere but `rejected`); the pairs @@ -631,7 +713,7 @@ export async function copiesReport( key: p.key, a: p.a, b: p.b, - dateDeltaDays: p.evidence.dateDeltaDays, + dateDeltaDays: p.evidence.dateDeltaDays ?? 0, durationDifferenceSeconds: Math.round(Math.abs(p.a.duration - p.b.duration)), firstSeenAt: p.firstSeenAt, waitEnds: new Date(ends).toISOString(), @@ -676,6 +758,7 @@ export async function copiesReport( ...(file.jobId ? { jobId: file.jobId } : {}), totals: file.totals, ...(file.missing ? { missing: file.missing } : {}), + ...(file.advice ? { advice: file.advice } : {}), } : null, pairs, diff --git a/common/controller/duplicateShorts.ts b/common/controller/duplicateShorts.ts @@ -49,6 +49,7 @@ import { STATS_SCHEMA_VERSION } from "../lib/stats"; import type { Cue } from "../lib/vtt"; import { parseTranscriptJson } from "../lib/whisper"; import { readVideoFiles, pickIndexTranscript } from "../lib/videoStatus"; +import { readStoredText } from "../lib/storedText-server"; import { DEFAULT_ALIGNMENT_TOLERANCE_SECONDS, DEFAULT_CONTAINMENT_THRESHOLD, @@ -966,7 +967,8 @@ async function readRawCues( if (!picked) return null; let raw: string; try { - raw = await readFile(path.join(dir, picked.filename), "utf8"); + // Either form (lib/storedText.ts): a caption stored as `.zst` is read. + raw = await readStoredText(dir, picked.filename, "utf8"); } catch { return null; } diff --git a/common/controller/fetchOlderPosts.test.ts b/common/controller/fetchOlderPosts.test.ts @@ -502,7 +502,7 @@ test("with nothing archived but posts found this run, the year-of-empties rule s assert.match(older?.completeReason ?? "", /^4 windows of 3 months in a row held no posts, back to [\d-]+$/); }); -test("a drain mid-window stops the search at once and keeps the resume point inside the window", async () => { +test("X's rate limit mid-window stops the search at once (review 1 F2) and keeps the resume point inside the window", async () => { const slug = "older-drain-window"; const channelRoot = await makeChannel(slug); await seed(channelRoot, slug); @@ -528,15 +528,14 @@ test("a drain mid-window stops the search at once and keeps the resume point ins delete process.env.FAKE_MODE; } assert.equal(result.ok, true, log.join("\n")); - assert.equal(result.drained, true); assert.equal(result.complete, false); + assert.ok(log.some((l) => /X answered this search with a rate limit: the walk stops at/.test(l)), log.join("\n")); assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); const older = (await readPostFetchState(channelRoot))?.older; assert.deepEqual( { since: older?.since, until: older?.until, maxId: older?.maxId, lastError: older?.lastError }, { since: "2020-12-11", until: "2021-03-11", maxId: idOf(POST_DATES[0]), lastError: undefined }, ); - assert.ok(log.some((l) => /Drained; the next run resumes at 2020-12-11 – 2021-03-11 below/.test(l)), log.join("\n")); }); test("a drain during the pause between windows ends it at once, at the next window, before another search", async () => { diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -167,7 +167,8 @@ test("a cancelled first walk keeps what it read, and where it stopped as the BAC assert.equal(state?.backfill?.cursor, "1/AFTER-P2"); assert.equal(state?.cursor, undefined); assert.equal(state?.sync, undefined); - assert.ok(log.some((l) => /Cancelled; the next run resumes/.test(l)), log.join("\n")); + // X's rate limit ends the run itself now (review 1 F2: ratelimit=abort), before any cancel. + assert.ok(log.some((l) => /X answered this run with a rate limit: gallery-dl stopped at its last page/.test(l)), log.join("\n")); assert.ok(log.some((l) => /sync new — nothing archived yet, so this is the first full-history walk/.test(l)), log.join("\n")); const argv = await lastArgv(); assert.ok(argv.includes("output.jsonl=true")); @@ -422,7 +423,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/PAGES-P1")); }); -test("a drain while gallery-dl waits out a rate limit stops it at once, keeping the last page's cursor", async () => { +test("X's rate limit stops gallery-dl at once (review 1 F2: never waited out), keeping the last page's cursor", async () => { const slug = "fake-x-drain-wait"; const root = await makeChannel(slug); const drain = new AbortController(); @@ -439,7 +440,8 @@ test("a drain while gallery-dl waits out a rate limit stops it at once, keeping }, }); assert.equal(result.ok, true, log.join("\n")); - assert.equal(result.drained, true); + assert.equal(result.complete, false); + assert.ok(log.some((l) => /X answered this run with a rate limit: gallery-dl stopped at its last page/.test(l)), log.join("\n")); assert.equal(result.written, 6); // Not left asleep for its 60 s. assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); @@ -756,3 +758,29 @@ test("R2a: an availability check of an X channel outside the editor's job is ref const inside = await asEditorJob(() => checkPostAvailability({ paths, slug: SLUG })); assert.doesNotMatch(inside.error ?? "", /asks X, and X/); }); + +// LANE X-SITTINGS, review 2 G1: the Playwright fallback cannot tell X's +// refusals, so a channel on it is refused in every mode, before anything +// opens, with the sentence naming the switch; the fetcher refuses too. +test("x-playwright is refused in every mode, naming the postFetcher to switch to; nothing is asked of X", async () => { + const slug = "fake-x-playwright"; + const root = await makeChannel(slug); + const config = JSON.parse(await readFile(path.join(root, "config.json"), "utf8")); + await writeFile(path.join(root, "config.json"), JSON.stringify({ ...config, postFetcher: "x-playwright" })); + const before = (await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length; + for (const mode of [{}, { backfill: true }, { full: true }, { older: true }]) { + const log: string[] = []; + const { runInJobContext } = await import("../lib/jobContext"); + const ctx = { jobId: "g1", kind: "fetch-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + const r = await runInJobContext(ctx, async () => fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, onLog: (l) => log.push(l), ...mode })); + assert.equal(r.ok, false, JSON.stringify(mode)); + // Refused by fetchPosts itself, before any walk began. + assert.ok(!log.some((l) => /^Fetching (older )?posts/.test(l)), log.join("\n")); + assert.match(r.error ?? "", /^fake-x-playwright's post fetcher is x-playwright \(the Playwright fallback\), which cannot tell when X refuses or rate-limits it, so it is refused: set the channel's postFetcher to x-gallery-dl/); + } + assert.equal((await readFile(ARGS_LOG, "utf8").catch(() => "")).trim().split("\n").length, before, "no gallery-dl run"); + const { xPlaywrightFetcher } = await import("../social/xPlaywrightFetcher"); + const direct = await xPlaywrightFetcher.fetch({ accountUrl: "https://x.com/faketester", handle: "faketester", channelSlug: slug, seenIds: new Set() } as never); + assert.equal(direct.complete, false); + assert.match(direct.error ?? "", /is refused/); +}); diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -95,6 +95,8 @@ import { import { instagramJobGuard } from "../jobs/instagramGuard"; import { currentJobContext } from "../lib/jobContext"; import { xJobContextRefusal } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { X_PLAYWRIGHT_REFUSED, xPlaywrightRefused } from "../social/xPlaywrightFetcher"; import { INSTAGRAM_QUEUE_KEY, INSTAGRAM_QUEUE_REFUSAL, isInstagramPostsChannelConfig } from "../lib/instagram/channel"; import { detectPlatform } from "../lib/platform"; import { postsMediaDir } from "../social/postCapture"; @@ -414,6 +416,16 @@ export async function fetchPosts( // …and only on X's queue (added scope R2): asked where the job runs too. const queue = xJobContextRefusal(slug, X_FETCH_DOOR(slug)); if (queue) return { ok: false, written: 0, skipped: 0, complete: false, error: queue }; + // THE PLAYWRIGHT FALLBACK IS REFUSED (review 2 G1): it cannot tell X's + // refusals, so it would scroll past a 429 and call the walk complete. + if (fetcher.id === "x-playwright" && xPlaywrightRefused()) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_PLAYWRIGHT_REFUSED(slug) }; + } + // WHAT ONE X JOB MAY READ (review 1 F8; lib/xSitting.ts): every mode + // below — timeline, backfill, full, older, search — takes the limit. + const limit = xJobPostLimit(settings?.social?.x as { maxPostsPerJob?: number } | undefined, opts.limit); + if (limit !== opts.limit) log(`This X job reads at most ${limit} posts (social.x.maxPostsPerJob); then it saves its place and ends.`); + opts = { ...opts, limit }; } // AN X SEARCH CHANNEL (release 38): its query across accounts, walked in diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -961,3 +961,100 @@ test("review 3 M1/M2: off clips:saved-video an X window is fetched only by a job const on = await runInJobContext(jobCtx("platform:twitter"), async () => go(await corpus(), xItems().slice(0, 1), h)); assert.equal(on.fetched.length, 1, "on X's queue it is fetched"); }); + +// THE RECORDING'S END (lane window-end): the last clip of a saved recording +// known whole — its padded window ends past the container — is cut from the +// saved video, clamped at its end, through the real saved-video tier: no +// yt-dlp spawned, the clamp in the result, and the next run's same ask cached. +test("the recording's end: a window past a whole saved recording's end is cut clamped, nothing spawned, then cached", async () => { + const { execFileSync } = await import("node:child_process"); + const base = await corpus(); + const transcriptsDir = path.dirname(base.channelsDir); + const savedVideosDir = path.join(transcriptsDir, "saved-videos"); + const paths = { ...base, transcriptsDir, savedVideosDir, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths; + const videoDir = path.join(base.channelsDir, "c", "data", "last1"); + const storeDir = path.join(savedVideosDir, "c", "last1"); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + execFileSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=8", + "-f", "lavfi", "-i", "sine=frequency=440:duration=8", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", + path.join(storeDir, "source-media.mp4"), + ]); + await writeFile( + path.join(videoDir, "saved-video.json"), + JSON.stringify({ storedAt: "2026-11-21T00:00:00.000Z", dir: storeDir, file: "source-media.mp4", bytes: 1, keepReason: "pin" }), + ); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last1", duration: 8 })); + // The clip ends 1 s before the end (7 of 8), padded 3 s: the window is 1–10. + const ask = { ...item("last1", "/last1", 1, 10), clipId: "m#last", pad: 3 }; + const before = await spawns(); + const h = harness(); + const r = await go(paths, [ask], h); + assert.deepEqual(r.failed, []); + assert.deepEqual(r.fetched, [], "nothing fetched"); + assert.deepEqual(r.cut.map((i) => i.clipId), ["m#last"]); + assert.equal((await spawns()) - before, 0, "no yt-dlp spawned for footage on disk"); + assert.equal(r.atRecordingEnd?.length, 1); + const end = r.atRecordingEnd![0]; + assert.equal(end.askedTo, 10); + assert.ok(end.cutTo > 7.5 && end.cutTo <= 8.1, `cut to ${end.cutTo}`); + assert.match(end.why, /whole recording/); + const names = await readdir(path.join(videoDir, "clips")); + assert.ok(names.includes(`1.00-${end.cutTo.toFixed(2)}.mp4`), names.join(" ")); + const prov = parseClipProvenance(JSON.parse(await readFile(path.join(videoDir, "clips", `1.00-${end.cutTo.toFixed(2)}.json`), "utf8"))); + assert.equal(prov?.source, "saved-video"); + assert.equal(prov?.clamp?.askedTo, 10); + // The same padded ask again: answered from the clamped window, nothing cut or fetched. + const again = await go(paths, [ask], harness()); + assert.deepEqual(again.cached.map((i) => i.clipId), ["m#last"]); + assert.deepEqual(again.cut, []); + assert.equal((await spawns()) - before, 0); +}); + +// REVIEW 1, finding 2: a clamp re-checked on every run. Its known end moved, or +// its saved container replaced: the clamped window is retired (as a window cut +// on another clock is) and the span is cut or fetched again. +test("the recording's end: a clamp whose facts moved is retired, and the span asked again", async () => { + const { execFileSync } = await import("node:child_process"); + const base = await corpus(); + const transcriptsDir = path.dirname(base.channelsDir); + const savedVideosDir = path.join(transcriptsDir, "saved-videos"); + const paths = { ...base, transcriptsDir, savedVideosDir, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths; + const videoDir = path.join(base.channelsDir, "c", "data", "last2"); + const storeDir = path.join(savedVideosDir, "c", "last2"); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + execFileSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=8", + "-f", "lavfi", "-i", "sine=frequency=440:duration=8", + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", + path.join(storeDir, "source-media.mp4"), + ]); + const pointer = { storedAt: "2026-11-21T00:00:00.000Z", dir: storeDir, file: "source-media.mp4", bytes: 1, keepReason: "pin" }; + await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify(pointer)); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last2", duration: 8 })); + const ask = { ...item("last2", "/last2", 1, 10), clipId: "m#end", pad: 3 }; + const first = await go(paths, [ask], harness()); + assert.equal(first.atRecordingEnd?.length, 1); + const clamped = `1.00-${first.atRecordingEnd![0].cutTo.toFixed(2)}`; + + // The saved container replaced by a longer copy (another size): retired, cut again from the new one. + await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ ...pointer, bytes: 2 })); + const before = await spawns(); + const second = await go(paths, [ask], harness()); + assert.deepEqual(second.retired, [`c/last2/clips/${clamped}`]); + assert.deepEqual(second.cut.map((i) => i.clipId), ["m#end"], "cut again from the saved video"); + assert.equal((await spawns()) - before, 0); + + // The recording's known end moved past the container: retired, and the span is not the saved video's any more. + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: "last2", duration: 60 })); + const third = await go(paths, [ask], harness()); + assert.deepEqual(third.retired, [`c/last2/clips/${clamped}`]); + assert.deepEqual(third.cut, []); + assert.deepEqual(third.fetched.map((i) => i.clipId), ["m#end"], "the network, as for any span the saved video does not hold"); + assert.equal((await readdir(path.join(videoDir, "clips"))).some((n) => n.startsWith(`${clamped}.`)), false, "the clamped window is gone"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -314,9 +314,15 @@ export type FetchWindowsResult = { // (clips.windowMaxHeight) clamped it. lower?: { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string }[]; clampedFrom?: number; + // THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): of `cut`, the + // windows asked past the end of a saved recording known whole and cut to it — + // the end asked, the end cut (the window's name) and why. + atRecordingEnd?: FetchWindowsAtEnd[]; stopped?: FetchWindowsStop; }; +export type FetchWindowsAtEnd = { item: FetchWindowsItem; askedTo: number; cutTo: number; why: string }; + export type FetchWindowsProvenance = { requestedBy: string; manifest?: string; @@ -379,6 +385,10 @@ export type FetchWindowsDeps = { // cut made before the map): their seconds are another clock's. Returns the // retired `<from>-<to>` names. retireOffClock: (opts: { paths: Paths; slug: string; dirId: string; videoDir: string; clockId: string }) => Promise<string[]>; + // THE RECORDING'S END (lane window-end): remove the windows of a video whose + // clamp at the recording's end no longer holds (another or a longer saved + // container, the known length moved). Returns the retired `<from>-<to>` names. + retireStaleClamps: (opts: { paths: Paths; slug: string; dirId: string; videoDir: string }) => Promise<string[]>; // A window's picture height, for a tall ask over a window with none // recorded (probed once; the answer is written to its sidecar). probeHeight: (file: string, paths: Paths) => Promise<number | null>; @@ -410,6 +420,16 @@ async function retireOffClockWindows(o: { return off.map((w) => `${w.from.toFixed(2)}-${w.to.toFixed(2)}`); } +// The windows of a video clamped at a recording's end whose clamp no longer +// holds (clipWindow-server listClipWindows `clampStale`), evicted through the +// targeted eviction, as the windows cut on another clock are. +async function retireStaleClampWindows(o: { paths: Paths; slug: string; dirId: string; videoDir: string }): Promise<string[]> { + const stale = (await listClipWindows(o.videoDir, { tiers: true })).filter((w) => w.clampStale); + if (!stale.length) return []; + await evictClipWindows({ paths: o.paths, slug: o.slug, id: o.dirId, windows: stale.map((w) => ({ from: w.from, to: w.to })) }); + return stale.map((w) => `${w.from.toFixed(2)}-${w.to.toFixed(2)}`); +} + export type SaveWholeRecordingOpts = { paths: Paths; slug: string; @@ -532,6 +552,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = { signal: o.signal, }), retireOffClock: retireOffClockWindows, + retireStaleClamps: retireStaleClampWindows, probeHeight: (file, paths) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }), renderHeld: renderModeHeldNow, cutPlainFromTiered: cutPlainFromTieredWindow, @@ -817,9 +838,15 @@ export async function fetchWindows({ signal: fetchSignal, }); result.cut.push(item); + if (source.clamp) { + (result.atRecordingEnd ??= []).push({ item, askedTo: source.clamp.askedTo, cutTo: source.clamp.cutTo, why: source.clamp.why }); + } log( ` ✂ ${label}: cut from the saved video into clips/${cut.file}` + - (beside ? ` (${cut.height ?? "?"}p, beside clips/${beside}, which stays as it is)` : ""), + (beside ? ` (${cut.height ?? "?"}p, beside clips/${beside}, which stays as it is)` : "") + + (source.clamp + ? ` — clamped at the recording's end (asked to ${source.clamp.askedTo.toFixed(2)}, cut to ${source.clamp.cutTo.toFixed(2)}): ${source.clamp.why}` + : ""), ); } catch (e) { fail(item, "cut-failed", (e as Error).message); @@ -886,6 +913,21 @@ export async function fetchWindows({ const clockWanted = wholeRecordingFor(settings, channelConfigPlatform(config) ?? "", item, wholeRecording); const clock = clockWanted ? await clockOf(item, label, videoDir, dirId) : null; + // A window clamped at the recording's end whose facts moved (another or a + // longer saved container, the known end moved) is retired first, as a + // window on another clock is, and the span is cut or fetched again below. + const staleClamps = await deps.retireStaleClamps({ paths, slug: item.slug, dirId, videoDir }).catch((e: unknown) => { + log(` ${label}: retiring the windows whose clamp at the recording's end no longer holds failed: ${(e as Error).message}`); + return [] as string[]; + }); + if (staleClamps.length) { + for (const n of staleClamps) (result.retired ??= []).push(`${item.slug}/${dirId}/clips/${n}`); + log( + ` ⏱ ${item.slug}/${dirId}: ${staleClamps.length} window(s) clamped at the recording's end retired — the saved video ` + + `or the recording's known length changed since: ${staleClamps.join(", ")}`, + ); + } + // THE CACHE FIRST, here rather than only inside fetchWindowManaged, so a // cached window owes no pause and is not counted as a network attempt — // and IN SYNC (the header): a desynced held window is set aside here, and @@ -1090,7 +1132,7 @@ export async function fetchWindows({ fail( item, "cut-failed", - `the saved recording ends at ${saved.durationSec.toFixed(2)} s, before this window does`, + saved.why ?? `the saved recording ends at ${saved.durationSec.toFixed(2)} s, before this window does`, ); done += 1; progress(); @@ -1256,7 +1298,7 @@ export async function fetchWindows({ fail( item, "cut-failed", - `the saved recording ends at ${after.durationSec.toFixed(2)} s, before this window does`, + after.why ?? `the saved recording ends at ${after.durationSec.toFixed(2)} s, before this window does`, ); } else { fail(item, "cut-failed", "the download reported success, but no saved video is on record"); diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts @@ -63,6 +63,7 @@ import { getSettings } from "../lib/settings"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; +import { logicalEntries } from "../lib/storedText"; import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server"; import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations"; import { isGateHeld } from "../lib/pauseGates"; @@ -201,7 +202,10 @@ export async function inspectFindClips( const audio = pickPreferredAudio(entries.filter(isRealAudioFile)); let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null; if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null); - const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null); + // LOGICAL for the transcript (lib/storedText.ts): a stored caption counts. + const transcript = entries.includes(WHISPER_FILENAME) + ? WHISPER_FILENAME + : (englishVttsByPreference(logicalEntries(entries))[0] ?? null); const words = await loadWordTimings(videoDir).catch(() => null); return { saved: pointer !== null || container !== null, diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts @@ -142,6 +142,8 @@ export type ImportMediaJobOpts = { // queues the transcribe-one job (held by any pause, as every one is). requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise<void>; + // The job running it, recorded on the do-not-clean mark it sets. + jobId?: string; deps?: { refresh?: RefreshRunner; land?: LandMediaDeps; @@ -281,10 +283,17 @@ export async function importMediaRun( } if (req.doNotClean) { - if (!req.dryRun) await setDoNotClean(videoDir, true, req.note); + if (!req.dryRun) { + await setDoNotClean(videoDir, true, { + by: "import", + via: "import-media", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }); + } say(`${req.dryRun ? "Would mark" : "Marked"} "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } - if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog); + if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog, opts.jobId); let transcribeJob: string | undefined; if (!req.dryRun && landed.audio !== "skipped") { @@ -358,8 +367,8 @@ export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<Strea paths, channelSlug: req.slug, videoId: target.id, - fn: async (onLog, signal) => { - await importMediaRun({ ...opts, target, onLog, signal }); + fn: async (onLog, signal, _progress, ctx) => { + await importMediaRun({ ...opts, target, onLog, signal, jobId: ctx.jobId }); await opts.afterRun?.(); }, }); diff --git a/common/controller/keepVideosMatching.test.ts b/common/controller/keepVideosMatching.test.ts @@ -106,7 +106,7 @@ test("an already-kept video is counted and not rewritten", async () => { { dirs: { aaaaaaaaaaa: ["TheQuartering live", ""] } }, async (paths, channelDir) => { const dir = dirOf(channelDir, "aaaaaaaaaaa"); - await setDoNotClean(dir, true, "by hand"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "by hand" }); const markerFile = path.join(dir, "do-not-clean.json"); const before = (await stat(markerFile)).mtimeMs; await new Promise((r) => setTimeout(r, 20)); @@ -123,7 +123,10 @@ test("an already-kept video is counted and not rewritten", async () => { downloaded: true, alreadyKept: true, marked: false, + // Who had set it, in the page's words (lane mark-provenance review F2). + keptBy: r.matched[0].keptBy, }); + assert.match(String(r.matched[0].keptBy), /^you, /); assert.equal((await stat(markerFile)).mtimeMs, before); assert.equal((await loadDoNotClean(dir))?.note, "by hand"); }, diff --git a/common/controller/keepVideosMatching.ts b/common/controller/keepVideosMatching.ts @@ -2,7 +2,9 @@ import path from "node:path"; import { readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { assertChannelMediaReachable } from "../lib/channelMedia"; -import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import { keepByPerson } from "../lib/doNotClean-server"; +import { describeDoNotCleanMark } from "../lib/doNotClean"; +import type { DoNotCleanSurface } from "../lib/doNotClean"; import { addPendingKeep, loadPendingKeep, type PendingKeepEntry } from "../lib/pendingKeep-server"; import { classifyAgainstFilter, @@ -71,6 +73,9 @@ export type KeepVideosOptions = { fields?: readonly KeepVideosField[]; note?: string; dryRun?: boolean; + // Where the person asked: recorded on every mark (default "ops" — the only + // caller today is `pnpm ops keep-videos`). + surface?: DoNotCleanSurface; }; export type KeepVideosMatch = { @@ -78,10 +83,20 @@ export type KeepVideosMatch = { title: string; // Has a data/<id>/ dir — the only kind that can carry the marker. downloaded: boolean; - // Already carried a marker before this call; left untouched. + // Already carried a PERSON's marker before this call (by "operator", or one + // from before marks said who set them); left untouched unless a note was + // given. alreadyKept: boolean; // This call wrote the marker (always false on a dry run). marked: boolean; + // The marker another writer set (the availability check, an import, a live + // recording) was taken over: it is the operator's now (would be, on a dry + // run). Counted in `marked` too when written. + takenOver?: boolean; + // Who had set the marker there before this call, and when + // (describeDoNotCleanMark): "availability check, 3 Nov; the source was + // gone", "you, 20 Nov". Absent when there was none. + keptBy?: string; }; export type KeepVideosResult = { @@ -92,6 +107,9 @@ export type KeepVideosResult = { matched: KeepVideosMatch[]; marked: number; alreadyKept: number; + // Of `marked` (would be, on a dry run): marks another writer set, now the + // operator's. + takenOver: number; // Matched ids with no data/<id>/ — download them, then re-run. notDownloaded: string[]; // Ids in playlist / roster.json with neither a dir nor a scan entry: the @@ -180,9 +198,11 @@ export async function keepVideosMatching( const notDownloaded: string[] = []; let marked = 0; let alreadyKept = 0; + let takenOver = 0; let noMetadata = 0; let considered = 0; - const note = opts.note?.trim() || `keep-videos: matched /${pattern}/i`; + const given = opts.note?.trim() || undefined; + const note = given ?? `keep-videos: matched /${pattern}/i`; for (const id of ids) { const downloaded = dirs.has(id); @@ -213,19 +233,23 @@ export async function keepVideosMatching( matched.push({ id, title, downloaded, alreadyKept: false, marked: false }); continue; } - const kept = await isDoNotClean(videoDir); - if (kept) { - alreadyKept++; - } else if (!dryRun) { - await setDoNotClean(videoDir, true, note); - marked++; - } + const { outcome, before } = await keepByPerson( + videoDir, + { via: "keep-videos-match", surface: opts.surface ?? "ops", ...(given ? { note: given } : {}) }, + { dryRun, defaultNote: note }, + ); + const kept = outcome === "already-kept"; + if (kept) alreadyKept++; + else if (!dryRun) marked++; + if (outcome === "taken-over") takenOver++; matched.push({ id, title, downloaded, alreadyKept: kept, marked: !kept && !dryRun, + ...(outcome === "taken-over" ? { takenOver: true } : {}), + ...(before ? { keptBy: describeDoNotCleanMark(before).text } : {}), }); } @@ -241,6 +265,7 @@ export async function keepVideosMatching( matched, marked, alreadyKept, + takenOver, notDownloaded, unscanned, noMetadata, @@ -254,8 +279,14 @@ export type KeepVideosByIdsResult = { ids: string[]; // Held, marked by this call (would be, on a dry run). marked: string[]; - // Held and already marked. + // Held and already marked by a person. alreadyKept: string[]; + // Of `marked`: held with a mark another writer set (the availability check, + // an import, a live recording), now the operator's (would be, on a dry run). + takenOver: string[]; + // Who had set each held id's marker before this call, and when + // (describeDoNotCleanMark), for every id that had one. + keptBy: Record<string, string>; // Not held: recorded as pending by this call (would be, on a dry run). The // marker is set when the record is first written (lib/pendingKeep-server.ts). pending: string[]; @@ -273,6 +304,9 @@ export async function keepVideosByIds(opts: { ids: readonly string[]; note?: string; dryRun?: boolean; + // Where the person asked (the Keep matching control's button, or pnpm ops), + // recorded on each mark and on each pending entry. + surface?: DoNotCleanSurface; }): Promise<KeepVideosByIdsResult> { const { paths, channelSlug } = opts; const dryRun = opts.dryRun === true; @@ -287,23 +321,30 @@ export async function keepVideosByIds(opts: { const config = await readChannelConfig(paths, channelSlug); await assertChannelMediaReachable(paths, channelSlug, config); const held = new Set(await listChannelVideoIds(paths, channelSlug)); - const note = opts.note?.trim() || "keep-videos: by id"; - const result: KeepVideosByIdsResult = { ids, marked: [], alreadyKept: [], pending: [], pendingAll: [], dryRun }; + const given = opts.note?.trim() || undefined; + const note = given ?? "keep-videos: by id"; + const result: KeepVideosByIdsResult = { ids, marked: [], alreadyKept: [], takenOver: [], keptBy: {}, pending: [], pendingAll: [], dryRun }; for (const id of ids) { if (!held.has(id)) { result.pending.push(id); continue; } const videoDir = path.join(paths.channelsDir, channelSlug, "data", id); - if (await isDoNotClean(videoDir)) result.alreadyKept.push(id); + const { outcome, before } = await keepByPerson( + videoDir, + { via: "keep-videos-ids", ...(opts.surface ? { surface: opts.surface } : {}), ...(given ? { note: given } : {}) }, + { dryRun, defaultNote: note }, + ); + if (before) result.keptBy[id] = describeDoNotCleanMark(before).text; + if (outcome === "already-kept") result.alreadyKept.push(id); else { - if (!dryRun) await setDoNotClean(videoDir, true, note); result.marked.push(id); + if (outcome === "taken-over") result.takenOver.push(id); } } result.pendingAll = !dryRun && result.pending.length - ? await addPendingKeep(paths, channelSlug, result.pending, note) + ? await addPendingKeep(paths, channelSlug, result.pending, note, new Date(), opts.surface) : await loadPendingKeep(paths, channelSlug); return result; } diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts @@ -39,7 +39,7 @@ // machine. import path from "node:path"; -import { mkdir, readdir, rm } from "node:fs/promises"; +import { mkdir, rm } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { getSettings } from "../lib/settings"; @@ -51,6 +51,7 @@ import { savedVideoDir } from "../lib/savedVideo"; import { loadSavedVideo } from "../lib/savedVideo-server"; import { savedVideoPath } from "../lib/savedVideo"; import { englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; +import { readdirLogical } from "../lib/storedText-server"; import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl"; import { getWorkerToken } from "../lib/workerToken"; import { @@ -290,7 +291,8 @@ export function umtoolMiner(umtool: string, token: string, doFetch: typeof fetch } export async function hasCorpusTranscript(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript. + const entries = await readdirLogical(videoDir); return entries.includes(WHISPER_FILENAME) || englishVttsByPreference(entries).length > 0; } diff --git a/common/controller/markProvenance.test.ts b/common/controller/markProvenance.test.ts @@ -0,0 +1,648 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { DoNotCleanRecord } from "../lib/doNotClean"; +import { + loadDoNotClean, + recordDoNotCleanAudioRemoved, + relabelDoNotCleanInferred, + setDoNotClean, +} from "../lib/doNotClean-server"; +import { addPendingKeep, applyPendingKeep } from "../lib/pendingKeep-server"; +import { cleanConfirmationText, sourceGoneOptInLabel } from "../lib/cleanAudioConfirm"; +import { cleanAudioForVideo, cleanAudioFromTranscribed, planAudioClean } from "./cleanAudioFromTranscribed"; +import { cleanAudioRequestFor, planCountsLine, replayCleanSpec, runCleanAudioJob } from "./cleanAudioJob"; +import { verifyBeforeClean, type VerifyProbes } from "./verifyBeforeClean"; +import { checkKeptDeleted } from "./checkKeptDeleted"; +import { keepVideosByIds, keepVideosMatching } from "./keepVideosMatching"; +import { backfillMarkProvenance, MARK_PROOF_WINDOW_MS } from "./marksBackfill"; +import type { CheckRequestDeps } from "./availabilityVerdict"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/markProvenance.test.ts +// +// LANE MARK-PROVENANCE. Who set a do-not-clean mark, recorded by every writer; +// the backfill that relabels an old mark only on proof from other records; and +// the unchecked clean's explicit opt-in that removes audio kept ONLY because +// the source was gone — never reaching a mark anything else set. Temp corpus, +// temp settings, synthetic ids; every probe a stub. + +const ROOT = await mkdtemp(path.join(tmpdir(), "mark-provenance-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true, diarization: { enabled: false } })); + +const exists = (f: string) => access(f).then(() => true, () => false); +const mark = async (dir: string) => (await loadDoNotClean(dir)) as DoNotCleanRecord; + +const NO_CHECK: CheckRequestDeps = { + start: async () => { + throw new Error("a test asked for a real availability check"); + }, + platformRefusal: async () => null, + serviceAlert: async () => null, +}; + +const THROWING: VerifyProbes = { + quick: async () => { + throw new Error("the source was asked"); + }, + full: async () => { + throw new Error("the source was asked"); + }, + recordBackoff: async () => {}, +}; + +let n = 0; +async function corpus(config: Record<string, unknown> = {}) { + const dir = path.join(ROOT, `c${n++}`); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + jobsDir: path.join(dir, ".jobs"), + savedVideosDir: path.join(dir, "saved"), + ytdlpBin: path.join(dir, "no-such-ytdlp"), + } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await mkdir(paths.jobsDir, { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...config }), + ); + const video = async ( + id: string, + o: { transcript?: boolean; audio?: number; mark?: Record<string, unknown>; availability?: Record<string, unknown>; uploadDate?: string } = {}, + ) => { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + if (o.uploadDate) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: id, upload_date: o.uploadDate })); + if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}"); + if (o.audio !== 0) await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.audio ?? 1000)); + if (o.mark) await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify(o.mark)); + if (o.availability) await writeFile(path.join(v, "availability.json"), JSON.stringify(o.availability)); + return v; + }; + const job = async (id: string, meta: Record<string, unknown>, log: string) => { + await writeFile(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, queueKey: "channel:ch", status: "done", queuedAt: 0, ...meta })); + await writeFile(path.join(paths.jobsDir, `${id}.log`), log); + }; + return { paths, video, job }; +} + +// --- The one writer --------------------------------------------------------- + +test("the writer: a mark needs its writer; availability-check never replaces a mark; a person's replaces and keeps what was removed", async () => { + const { video } = await corpus(); + const v = await video("w1"); + await assert.rejects( + // @ts-expect-error — no provenance: refused by the type and at run time. + setDoNotClean(v, true), + /needs its writer/, + ); + assert.equal(await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button", note: "mine" }), true); + assert.equal(await setDoNotClean(v, true, { by: "availability-check", via: "pre-clean-check", note: "gone" }), false); + assert.deepEqual({ ...(await mark(v)), setAt: "x" }, { setAt: "x", note: "mine", by: "operator", via: "toggle", surface: "button" }); + + const g = await video("w2"); + assert.equal(await setDoNotClean(g, true, { by: "availability-check", via: "pre-clean-check", jobId: "J1" }), true); + assert.equal(await recordDoNotCleanAudioRemoved(g, { at: "t", files: ["audio.mp3"], bytes: 5, why: "w" }), true); + await setDoNotClean(g, true, { by: "live-recording", via: "record-live", jobId: "J2" }); + const after = await mark(g); + assert.equal(after.by, "live-recording"); + assert.equal(after.jobId, "J2"); + assert.equal(after.audioRemoved?.length, 1, "the removal stays on record"); + // An annotation reaches only a mark by the availability check. + assert.equal(await recordDoNotCleanAudioRemoved(g, { at: "t", files: [], bytes: 0, why: "w" }), false); + // An unknown `by` reads as the operator's. + await writeFile(path.join(g, "do-not-clean.json"), JSON.stringify({ setAt: "s", by: "robot" })); + assert.equal((await mark(g)).by, undefined); +}); + +// --- Every writer's `by` ---------------------------------------------------- + +test("verifyBeforeClean: tier A and tier C pins say availability-check / pre-clean-check with the job", async () => { + const { paths, video } = await corpus(); + const cached = await video("cachedgone", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "private" } }); + const suspect = await video("suspect"); + const probes: VerifyProbes = { + quick: async () => ({ knownCount: 2, freshCount: 1, maybeMissingCount: 1, ids: ["suspect"] }), + full: (async () => { + await writeFile(path.join(suspect, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), checkedBy: "check", availability: "deleted" })); + return { attempted: 1, checked: 1, skipped: 0, byStatus: {}, blocked: false, probedIds: ["suspect"] }; + }) as unknown as VerifyProbes["full"], + }; + const v = await verifyBeforeClean({ channelSlug: "ch", paths, candidateIds: ["cachedgone", "suspect"], probes, jobId: "JOB-A", onLog: () => {} }); + assert.deepEqual([...v.pinned.keys()].sort(), ["cachedgone", "suspect"]); + for (const dir of [cached, suspect]) { + const m = await mark(dir); + assert.equal(m.by, "availability-check"); + assert.equal(m.via, "pre-clean-check"); + assert.equal(m.jobId, "JOB-A"); + } +}); + +test("clean after capture pins as availability-check / clean-after-capture; the keep-latest check as kept-deleted-check", async () => { + const { paths, video } = await corpus({ keepLatest: 1 }); + const v = await video("capgone", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "deleted" }, uploadDate: "20260101" }); + // In the keep-latest window: the kept-deleted check pins it. + const k = await checkKeptDeleted({ channelSlug: "ch", paths, onLog: () => {}, jobId: "JOB-K" }); + assert.equal(k.pinned, 1); + assert.deepEqual({ by: (await mark(v)).by, via: (await mark(v)).via, jobId: (await mark(v)).jobId }, { by: "availability-check", via: "kept-deleted-check", jobId: "JOB-K" }); + + const c2 = await corpus(); + const w = await c2.video("capgone2", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "deleted" } }); + const r = await cleanAudioForVideo({ channelSlug: "ch", paths: c2.paths, videoId: "capgone2", onLog: () => {}, checkDeps: NO_CHECK }); + assert.equal(r.outcome, "pinned"); + assert.equal((await mark(w)).by, "availability-check"); + assert.equal((await mark(w)).via, "clean-after-capture"); +}); + +test("keep-videos (by pattern, by ids, pending) and its surfaces say operator", async () => { + const { paths, video } = await corpus(); + const a = await video("kmatch", { uploadDate: "20260101" }); + await writeFile(path.join(a, "metadata.info.json"), JSON.stringify({ id: "kmatch", title: "keep me", description: "" })); + await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me" }); + assert.deepEqual({ by: (await mark(a)).by, via: (await mark(a)).via, surface: (await mark(a)).surface }, { by: "operator", via: "keep-videos-match", surface: "ops" }); + + const b = await video("kids"); + const r = await keepVideosByIds({ paths, channelSlug: "ch", ids: ["kids", "notyet"], surface: "button" }); + assert.deepEqual(r.pending, ["notyet"]); + assert.deepEqual({ by: (await mark(b)).by, via: (await mark(b)).via, surface: (await mark(b)).surface }, { by: "operator", via: "keep-videos-ids", surface: "button" }); + + // The pending one lands later (an import's job): operator / pending-keep, the surface carried. + const c = await video("notyet"); + assert.equal(await applyPendingKeep(paths, "ch", "notyet", undefined, "JOB-LAND"), true); + assert.deepEqual( + { by: (await mark(c)).by, via: (await mark(c)).via, surface: (await mark(c)).surface, jobId: (await mark(c)).jobId }, + { by: "operator", via: "pending-keep", surface: "button", jobId: "JOB-LAND" }, + ); + // An entry from before surfaces were recorded: no surface, still operator. + await addPendingKeep(paths, "ch", ["old"], "n"); + const d = await video("old"); + await applyPendingKeep(paths, "ch", "old"); + assert.equal((await mark(d)).by, "operator"); + assert.equal((await mark(d)).surface, undefined); +}); + +// --- The gate: one writer --------------------------------------------------- + +test("the opt-in plan: only marks by the availability check are in the group, inferred counted apart; legacy, operator, import, live never", async () => { + const { paths, video } = await corpus(); + await video("plain", { audio: 100 }); + await video("gone", { audio: 200, mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + await video("goneinf", { audio: 300, mark: { setAt: "s", by: "availability-check", via: "pre-clean-check", inferred: true } }); + await video("legacy", { audio: 400, mark: { setAt: "s", note: "deleted from source (pre-clean check): deleted" } }); + await video("person", { audio: 500, mark: { setAt: "s", by: "operator", via: "toggle", surface: "button" } }); + await video("imp", { audio: 600, mark: { setAt: "s", by: "import", via: "import-media" } }); + await video("live", { audio: 700, mark: { setAt: "s", by: "live-recording", via: "record-live" } }); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan.ids, ["plain"]); + assert.equal(plan.protected, 6, "every mark is kept without the opt-in"); + assert.deepEqual(plan.sourceGone, { + ids: ["gone", "goneinf"], + videos: 2, + files: 2, + bytes: 500, + inferred: { ids: ["goneinf"], videos: 1, files: 1, bytes: 300 }, + }); + + const off = cleanConfirmationText(plan); + assert.equal(off.sourceGone, null); + assert.equal(off.button, "Remove 1 file without checking"); + assert.match(off.kept, /^Kept: 6 marked do not clean or in the keep-latest window \(2 of them only because the source was gone\), /); + assert.equal(sourceGoneOptInLabel(plan.sourceGone), "Also remove audio kept only because the source was gone (2 videos, 2 files, 500 B)"); + const on = cleanConfirmationText(plan, { includeSourceGone: true }); + assert.equal( + on.sourceGone, + "Also removed, kept only because the source was gone: 2 audio files (500 B) from 2 videos the availability check marked do not clean. Their marks stay. " + + "Of these, 1 video (1 file, 300 B) carry marks inferred from the records (marks-backfill), not written by the check itself.", + ); + assert.equal(on.button, "Remove 3 files without checking"); + assert.equal(on.files, 3); + assert.match(on.kept, /^Kept: 4 marked do not clean/); + assert.match(on.kept, /A mark set by a person, an import or a live recording is never touched\.$/); +}); + +test("the opt-in run: removes only the confirmed source-gone group, the marks stay and record it; nothing else is reachable", async () => { + const { paths, video } = await corpus(); + const plain = await video("plain"); + const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const goneinf = await video("goneinf", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check", inferred: true } }); + const notAsked = await video("notasked", { mark: { setAt: "s", by: "availability-check", via: "kept-deleted-check" } }); + const legacy = await video("legacy", { mark: { setAt: "s", note: "deleted from source (pre-clean check): deleted" } }); + const person = await video("person", { mark: { setAt: "s", by: "operator", via: "toggle" } }); + const imp = await video("imp", { mark: { setAt: "s", by: "import", via: "import-media" } }); + const live = await video("live", { mark: { setAt: "s", by: "live-recording", via: "record-live" } }); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + unchecked: "button", + onlyIds: ["plain"], + // A caller that names other kinds of marks too reaches none of them. + sourceGone: ["gone", "goneinf", "legacy", "person", "imp", "live"], + jobId: "JOB-U", + probes: THROWING, + onLog: (m) => logs.push(m), + }); + for (const d of [plain, gone, goneinf]) assert.equal(await exists(path.join(d, "audio.mp3")), false); + for (const d of [notAsked, legacy, person, imp, live]) assert.equal(await exists(path.join(d, "audio.mp3")), true, d); + for (const d of [gone, goneinf]) { + const m = await mark(d); + assert.equal(m.by, "availability-check", "the mark stays"); + assert.equal(m.audioRemoved?.length, 1); + assert.equal(m.audioRemoved![0].jobId, "JOB-U"); + assert.deepEqual(m.audioRemoved![0].files, ["audio.mp3"]); + assert.match(m.audioRemoved![0].why, /also remove audio kept only because the source was gone/); + } + assert.match((await mark(goneinf)).audioRemoved![0].why, /inferred from the records/); + assert.deepEqual(r.sourceGoneRemoved, { videos: 2, files: 2, bytes: 2000, inferredVideos: 1 }); + assert.equal(r.cleanedDirs, 3); + assert.ok(logs.some((l) => l.startsWith("Also remove audio kept only because the source was gone (confirmed): 6 video(s) asked, 2 still marked")), logs.join("\n")); +}); + +test("the opt-in is honoured only by a confirmed unchecked clean: not checked, not the channel key, not without it", async () => { + for (const mode of [undefined, "channel-setting"] as const) { + const { paths, video } = await corpus(); + const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const probes: VerifyProbes = { quick: async () => ({ knownCount: 1, freshCount: 1, maybeMissingCount: 0, ids: [] }) }; + const logs: string[] = []; + await cleanAudioFromTranscribed({ channelSlug: "ch", paths, ...(mode ? { unchecked: mode } : {}), sourceGone: ["gone"], probes, onLog: (m) => logs.push(m) }); + assert.equal(await exists(path.join(gone, "audio.mp3")), true, String(mode)); + assert.ok(logs.some((l) => l.startsWith("Audio kept only because the source was gone is NOT removed")), logs.join("\n")); + } + // A button clean without the opt-in: kept, and logged as any mark is. + const { paths, video } = await corpus(); + const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const logs: string[] = []; + await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], probes: THROWING, onLog: (m) => logs.push(m) }); + assert.equal(await exists(path.join(gone, "audio.mp3")), true); + assert.ok(logs.includes("Skipped gone (marked do not clean)"), logs.join("\n")); + // The request: only an explicit button carries it. + assert.equal(cleanAudioRequestFor({ cleanAudioWithoutChecking: true } as never, { sourceGone: ["gone"] }).sourceGone, undefined); + assert.deepEqual(cleanAudioRequestFor(null, { explicit: "button", plan: [], sourceGone: ["gone"] }).sourceGone, ["gone"]); +}); + +test("the opt-in: a mark a person set since the plan, or a speaker hold, keeps the audio", async () => { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ diarization: { enabled: true, segModel: "/m/s.onnx", embModel: "/m/e.onnx" } })); + try { + const { paths, video } = await corpus(); + const held = await video("held", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const remarked = await video("remarked", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + await writeFile( + path.join(remarked, "diarization.json"), + JSON.stringify({ + videoId: "remarked", + generatedAt: "2026-08-07T00:00:00.000Z", + speakers: 1, + turns: [{ start: 0, end: 4, speaker: 0 }], + engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, + voiceprints: [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }], + }), + ); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan.sourceGone.ids, ["remarked"], "awaiting diarization stays held under its mark"); + // A person re-marks it after the plan was counted. + await setDoNotClean(remarked, true, { by: "operator", via: "toggle", surface: "button" }); + await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["held", "remarked"], probes: THROWING, onLog: () => {} }); + assert.equal(await exists(path.join(held, "audio.mp3")), true); + assert.equal(await exists(path.join(remarked, "audio.mp3")), true); + assert.equal((await mark(remarked)).audioRemoved, undefined); + } finally { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ verifyAvailabilityBeforeClean: true, diarization: { enabled: false } })); + } +}); + +test("the opt-in: a person who re-marks the video after discover (just before removal) keeps its audio", async () => { + const { paths, video } = await corpus(); + const v = await video("race", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const logs: string[] = []; + await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + unchecked: "button", + onlyIds: [], + sourceGone: ["race"], + probes: THROWING, + // The media guard runs between discover and the removals: the person acts then. + assertReachable: async () => { + await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button" }); + }, + onLog: (m) => logs.push(m), + }); + assert.equal(await exists(path.join(v, "audio.mp3")), true); + assert.equal((await mark(v)).by, "operator"); + assert.ok(logs.includes("Skipped race (marked do not clean — no longer by the availability check)"), logs.join("\n")); +}); + +test("the job: a button job carries the opt-in into the sweep and logs its counts; a retry and a replay never carry it", async () => { + const { paths, video } = await corpus(); + const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); + const logs: string[] = []; + const counts = { files: 0, bytes: 0, videos: 0, protected: 1, awaitingDiarization: 0, awaitingVoiceprint: 0, sourceGone: { videos: 1, files: 1, bytes: 1000, inferred: { videos: 0, files: 0, bytes: 0 } } }; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "JOB-B", + unchecked: "button", + plan: [], + planCounts: counts, + sourceGone: ["gone"], + onLog: (m) => logs.push(m), + deps: { scheduleRetry: async () => ({ ok: false, error: "no" }), probes: THROWING }, + }); + assert.equal(out.end, "done"); + assert.equal(await exists(path.join(gone, "audio.mp3")), false); + assert.equal((await mark(gone)).audioRemoved?.[0].jobId, "JOB-B"); + assert.ok(logs.includes(planCountsLine(counts)), logs.join("\n")); + assert.match(planCountsLine(counts), /kept: 0 marked do not clean .* Also, kept only because the source was gone: 1 audio file\(s\) \(1000 bytes\) from 1 video\(s\) \(0 of them/); + + // Replay of a button job on a key-on channel: the plan only. + const calls: unknown[][] = []; + await replayCleanSpec( + { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a"], sourceGone: ["gone"] } }, + { + readConfig: async () => ({ cleanAudioWithoutChecking: true }) as never, + clean: async (...a) => calls.push(["clean", ...a]), + unchecked: async (...a) => calls.push(["unchecked", ...a]), + }, + ); + assert.deepEqual(calls, [["unchecked", "ch", undefined, ["a"]]]); +}); + +// --- The backfill ----------------------------------------------------------- + +const SET_AT = "2026-10-20T10:00:30.000Z"; +const T0 = Date.parse("2026-10-20T10:00:00.000Z"); + +async function provable(c: Awaited<ReturnType<typeof corpus>>, id = "pv") { + const v = await c.video(id, { + mark: { setAt: SET_AT, note: "anything at all" }, + availability: { + checkedAt: "2026-11-01T00:00:00.000Z", + checkedBy: "check", + availability: "deleted", + history: [ + { availability: "public", observedAt: "2026-01-01T00:00:00.000Z", source: "backfill" }, + { availability: "deleted", observedAt: "2026-10-20T10:00:10.000Z", source: "check" }, + ], + }, + }); + return v; +} + +test("backfill: relabels only on both proofs, dry run first, with its evidence; never from the note", async () => { + const c = await corpus(); + const v = await provable(c); + await c.job("J-CLEAN", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 120_000 }, `Verify before clean: …\nPinned pv as do-not-clean (deleted) — gone from source.\n`); + const dry = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch" }); + assert.equal(dry.dryRun, true); + assert.deepEqual(dry.relabelled, [ + { id: "pv", setAt: SET_AT, evidence: { availability: "deleted", observedAt: "2026-10-20T10:00:10.000Z", field: "history", jobId: "J-CLEAN", jobKind: "clean-audio-transcribed" } }, + ]); + assert.equal((await mark(v)).by, undefined, "a dry run writes nothing"); + const real = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false, now: new Date("2026-11-21T00:00:00.000Z") }); + assert.equal(real.relabelled.length, 1); + const m = await mark(v); + assert.deepEqual(m, { + setAt: SET_AT, + note: "anything at all", + by: "availability-check", + via: "pre-clean-check", + inferred: true, + inferredAt: "2026-11-21T00:00:00.000Z", + evidence: real.relabelled[0].evidence, + }); + // Labelled now: a second run leaves it. + const again = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); + assert.deepEqual([again.labelled, again.relabelled.length], [1, 0]); +}); + +test("backfill refuses: note only, a check far from the mark, no job, a job of another kind or channel or time, a line for another id", async () => { + const c = await corpus(); + // The gate's own note text, and nothing else: not proof. + await c.video("noteonly", { mark: { setAt: SET_AT, note: "deleted from source (pre-clean check): deleted" } }); + // A tier-A pin: the check ran weeks before the mark. + await c.video("cached", { + mark: { setAt: SET_AT, note: "deleted from source (pre-clean check): deleted" }, + availability: { checkedAt: "2026-09-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [{ availability: "deleted", observedAt: "2026-09-01T00:00:00.000Z", source: "check" }] }, + }); + // A record that never said gone. + await c.video("public", { mark: { setAt: SET_AT }, availability: { checkedAt: SET_AT, checkedBy: "check", availability: "public" } }); + // Gone within the minute, but by a backfill, not a check. + await c.video("assumed", { mark: { setAt: SET_AT }, availability: { checkedAt: SET_AT, checkedBy: "backfill", availability: "deleted", history: [{ availability: "deleted", observedAt: SET_AT, source: "backfill" }] } }); + // Both halves would hold, but the only job naming it is the keep-latest check, another channel's clean, or one not running then. + await provable(c, "wrongjob"); + await c.job("J-KEPT", { kind: "check-kept-deleted", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned wrongjob as do-not-clean (deleted).\n"); + await c.job("J-OTHER", { kind: "clean-audio-transcribed", channelSlug: "other", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); + await c.job("J-LATE", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0 + 10 * 60_000, endedAt: T0 + 11 * 60_000 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); + await c.job("J-RUNNING", { kind: "clean-audio-transcribed", channelSlug: "ch", status: "running", startedAt: T0 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); + // A clean job running then, whose line names a longer id / another availability. + await provable(c, "idx"); + await c.job("J-PREFIX", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned aidx as do-not-clean (deleted) — gone from source.\nPinned idx as do-not-clean (private) — gone from source.\n"); + + const r = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); + assert.deepEqual(r.relabelled, []); + assert.deepEqual( + Object.fromEntries(r.notProven.map((x) => [x.id, x.reason])), + { + assumed: "no-check-within-a-minute", + cached: "no-check-within-a-minute", + idx: "no-clean-job-naming-it", + noteonly: "no-availability-record", + public: "not-gone", + wrongjob: "no-clean-job-naming-it", + }, + ); + for (const id of ["noteonly", "cached", "public", "assumed", "wrongjob", "idx"]) { + assert.equal((await mark(path.join(c.paths.channelsDir, "ch", "data", id))).by, undefined, id); + } + assert.equal(r.oldestCleanJobAt, new Date(T0).toISOString()); + assert.equal(MARK_PROOF_WINDOW_MS, 60_000); +}); + +test("backfill's relabel refuses a mark that changed since it was judged", async () => { + const c = await corpus(); + const v = await provable(c); + const evidence = { availability: "deleted", observedAt: SET_AT, field: "history" as const, jobId: "J", jobKind: "clean-audio-transcribed" }; + assert.equal(await relabelDoNotCleanInferred(v, { setAt: "2026-01-01T00:00:00.000Z" }, evidence), false, "another setAt"); + await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "ops" }); + assert.equal(await relabelDoNotCleanInferred(v, { setAt: (await mark(v)).setAt }, evidence), false, "labelled since"); + assert.equal((await mark(v)).by, "operator"); +}); + +test("an inferred mark joins the opt-in group, counted apart", async () => { + const c = await corpus(); + await provable(c); + await c.job("J-CLEAN", { kind: "clean-audio-retry", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned pv as do-not-clean (deleted) — gone from source.\n"); + assert.deepEqual((await planAudioClean({ channelSlug: "ch", paths: c.paths })).sourceGone.ids, [], "not before the relabel"); + await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); + const plan = await planAudioClean({ channelSlug: "ch", paths: c.paths }); + assert.deepEqual(plan.sourceGone.inferred.ids, ["pv"]); + const raw = JSON.parse(await readFile(path.join(c.paths.channelsDir, "ch", "data", "pv", "do-not-clean.json"), "utf8")); + assert.equal(raw.evidence.jobKind, "clean-audio-retry"); +}); + +// --- Review 1 --------------------------------------------------------------- +// New symbols are imported inside each test, so each fails on its own before +// the fix (the run of these against the pre-fix code is the RED one). + +const MACHINE = { setAt: "2026-11-03T08:00:00.000Z", note: "deleted from source (pre-clean check): deleted", by: "availability-check", via: "pre-clean-check" }; + +async function optInGroup(paths: Paths) { + return (await planAudioClean({ channelSlug: "ch", paths })).sourceGone.ids; +} + +test("F1: keep-videos by ids on a machine-set mark makes it the operator's, with the note; the opt-in then never reaches it", async () => { + const { paths, video } = await corpus(); + const v = await video("mach", { mark: MACHINE }); + const mine = await video("mine", { mark: { setAt: "2026-11-01T00:00:00.000Z", by: "operator", via: "toggle", note: "mine" } }); + assert.deepEqual(await optInGroup(paths), ["mach"]); + const r = await keepVideosByIds({ paths, channelSlug: "ch", ids: ["mach", "mine"], note: "the only copy, keep", surface: "ops" }); + assert.deepEqual(r.marked, ["mach"]); + assert.deepEqual((r as unknown as { takenOver: string[] }).takenOver, ["mach"]); + assert.deepEqual(r.alreadyKept, ["mine"], "already kept only for a mark already the operator's"); + const m = await mark(v); + assert.deepEqual([m.by, m.via, m.surface, m.note], ["operator", "keep-videos-ids", "ops", "the only copy, keep"]); + assert.equal((m as { takenOver?: { by?: string } }).takenOver?.by, "availability-check"); + assert.equal((await mark(mine)).note, "the only copy, keep", "a note given is written on the person's own mark"); + assert.deepEqual(await optInGroup(paths), [], "the opt-in never reaches it now"); + const logs: string[] = []; + await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["mach"], probes: THROWING, onLog: (l) => logs.push(l) }); + assert.equal(await exists(path.join(v, "audio.mp3")), true); +}); + +test("F1: keep-videos by pattern takes over a machine-set mark (and a dry run only says it would)", async () => { + const { paths, video } = await corpus(); + const v = await video("pat", { mark: { ...MACHINE, by: "import", via: "import-media" } }); + await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: "pat", title: "keep me", description: "" })); + const dry = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me", dryRun: true }); + assert.equal((dry as unknown as { takenOver: number }).takenOver, 1); + assert.equal((await mark(v)).by, "import", "a dry run writes nothing"); + const r = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me" }); + assert.deepEqual([r.marked, r.alreadyKept], [1, 0]); + assert.match(String((r.matched[0] as { keptBy?: string }).keptBy), /^import, 3 Nov/); + const m = await mark(v); + assert.deepEqual([m.by, m.via, m.note], ["operator", "keep-videos-match", MACHINE.note], "no note given: the mark's own stays"); +}); + +test("F1: a pending keep landing on a machine-set mark takes it over", async () => { + const { paths, video } = await corpus(); + await addPendingKeep(paths, "ch", ["later"], "asked first", new Date(), "button"); + const v = await video("later", { mark: { ...MACHINE, via: "kept-deleted-check" } }); + assert.equal(await applyPendingKeep(paths, "ch", "later", undefined, "JOB-L"), true); + const m = await mark(v); + assert.deepEqual([m.by, m.via, m.surface, m.note, m.jobId], ["operator", "pending-keep", "button", "asked first", "JOB-L"]); + assert.deepEqual(await optInGroup(paths), []); +}); + +test("F1: the toggle, Make it mine and a note — keepByPerson takes a machine mark over; a person's stays unless given a note", async () => { + const { keepByPerson } = (await import("../lib/doNotClean-server")) as unknown as { + keepByPerson: (d: string, m: Record<string, unknown>, o?: Record<string, unknown>) => Promise<{ outcome: string }>; + }; + const { paths, video } = await corpus(); + const v = await video("tg", { mark: MACHINE }); + assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "taken-over"); + const m = await mark(v); + assert.deepEqual([m.by, m.via, m.note], ["operator", "toggle", MACHINE.note]); + const setAt = m.setAt; + assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "already-kept"); + assert.equal((await mark(v)).setAt, setAt, "nothing rewritten"); + assert.equal((await keepByPerson(v, { via: "toggle", surface: "ops", note: "edited" })).outcome, "already-kept"); + assert.equal((await mark(v)).note, "edited"); + // A note written on a machine mark takes it over. + const n2 = await video("nt", { mark: MACHINE }); + await keepByPerson(n2, { via: "toggle", surface: "button", note: "mine now" }); + assert.deepEqual([(await mark(n2)).by, (await mark(n2)).note], ["operator", "mine now"]); + assert.deepEqual(await optInGroup(paths), []); +}); + +test("F2: who set a mark and when, in the page's words", async () => { + const { describeDoNotCleanMark } = (await import("../lib/doNotClean")) as unknown as { + describeDoNotCleanMark: (m: Record<string, unknown>, now?: Date) => { text: string; mine: boolean; sourceGone: boolean }; + }; + const now = new Date("2026-11-21T00:00:00.000Z"); + const d = (m: Record<string, unknown>) => describeDoNotCleanMark(m, now); + assert.deepEqual(d(MACHINE), { who: "availability check", day: "3 Nov", text: "availability check, 3 Nov; the source was gone", mine: false, sourceGone: true }); + assert.equal(d({ setAt: "2026-11-20T09:00:00.000Z", by: "operator", via: "toggle" }).text, "you, 20 Nov"); + assert.equal(d({ ...MACHINE, inferred: true }).text, "availability check (inferred from the records), 3 Nov; the source was gone"); + assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "import", via: "import-media" }).text, "import, 3 Nov"); + assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "live-recording", via: "record-live" }).text, "live recording, 3 Nov"); + assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).text, "you, 11 Sep 2025 (set before marks said who set them)"); + assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).mine, true); +}); + +test("F3: a person's re-mark that takes the mark's lock first (not yet written when the sweep re-reads) keeps the audio", async () => { + const { paths, video } = await corpus(); + const v = await video("lockrace", { mark: MACHINE }); + const logs: string[] = []; + let person: Promise<unknown> | undefined; + await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + unchecked: "button", + onlyIds: [], + sourceGone: ["lockrace"], + probes: THROWING, + // Just before the removals the person presses Make it mine; the sweep + // does not wait for the write to land. + assertReachable: async () => { + person = setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button" }); + }, + onLog: (m) => logs.push(m), + }); + await person; + assert.equal(await exists(path.join(v, "audio.mp3")), true, "the audio stays"); + assert.equal((await mark(v)).by, "operator"); + assert.equal((await mark(v)).audioRemoved, undefined); +}); + +test("F4: the job states the source-gone group's counts before it removes anything", async () => { + const { paths, video } = await corpus(); + await video("g4", { mark: MACHINE }); + const logs: string[] = []; + const counts = { files: 0, bytes: 0, videos: 0, protected: 1, awaitingDiarization: 0, awaitingVoiceprint: 0, sourceGone: { videos: 1, files: 1, bytes: 1000, inferred: { videos: 0, files: 0, bytes: 0 } } }; + await runCleanAudioJob({ + channelSlug: "ch", paths, jobId: "J4", unchecked: "button", plan: [], planCounts: counts, sourceGone: ["g4"], + onLog: (m) => logs.push(m), + deps: { scheduleRetry: async () => ({ ok: false, error: "no" }), probes: THROWING }, + }); + const said = logs.findIndex((l) => l.includes("Also, kept only because the source was gone: 1 audio file(s) (1000 bytes) from 1 video(s)")); + const removed = logs.findIndex((l) => l.startsWith("Removed ")); + assert.ok(said >= 0 && removed > said, logs.join("\n")); +}); + +test("F5: the proof is one-sided — an observation AFTER the mark, or a job that started after it, is not proof", async () => { + const c = await corpus(); + await c.video("after", { + mark: { setAt: SET_AT }, + availability: { checkedAt: "2026-11-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [{ availability: "deleted", observedAt: "2026-10-20T10:00:50.000Z", source: "check" }] }, + }); + await provable(c, "jobafter"); + await c.job("J-AFTER", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: Date.parse(SET_AT) + 20_000, endedAt: Date.parse(SET_AT) + 90_000 }, + "Pinned after as do-not-clean (deleted) — gone from source.\nPinned jobafter as do-not-clean (deleted) — gone from source.\n"); + const r = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch" }); + assert.deepEqual(r.relabelled, []); + assert.deepEqual(Object.fromEntries(r.notProven.map((x) => [x.id, x.reason])), { after: "no-check-within-a-minute", jobafter: "no-clean-job-naming-it" }); +}); + +test("F5: undo returns every inferred label to unlabelled — dry run first, the same listing — and nothing else", async () => { + const { undoMarkProvenanceBackfill } = (await import("./marksBackfill")) as unknown as { + undoMarkProvenanceBackfill: (o: Record<string, unknown>) => Promise<{ dryRun: boolean; unlabelled: { id: string; evidence: unknown }[]; changedSince: string[] }>; + }; + const c = await corpus(); + const v = await provable(c); + await c.job("J-CLEAN", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 120_000 }, "Pinned pv as do-not-clean (deleted) — gone from source.\n"); + await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); + const machine = await c.video("machine", { mark: MACHINE }); + const dry = await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch" }); + assert.equal(dry.dryRun, true); + assert.deepEqual(dry.unlabelled.map((x) => x.id), ["pv"]); + assert.equal((await mark(v)).inferred, true, "a dry run writes nothing"); + await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch", dryRun: false }); + assert.deepEqual(await mark(v), { setAt: SET_AT, note: "anything at all" }); + assert.equal((await mark(machine)).by, "availability-check", "a mark the check itself wrote is not touched"); +}); diff --git a/common/controller/marksBackfill.ts b/common/controller/marksBackfill.ts @@ -0,0 +1,226 @@ +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { isPermanentlyGone } from "../lib/availability"; +import { loadAvailability } from "../lib/availability-server"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import type { DoNotCleanEvidence } from "../lib/doNotClean"; +import { loadDoNotClean, relabelDoNotCleanInferred, unlabelDoNotCleanInferred } from "../lib/doNotClean-server"; +import { readJobMeta, type JobMeta } from "../jobs/jobMeta"; + +// MARKS-BACKFILL (lane mark-provenance): relabel an OLD do-not-clean mark — one +// written before marks said who set them, so the operator's by rule — as set +// by the availability check, `inferred: true`, ONLY when other records prove +// it. Never from the mark's free-text note, which a person can write too. +// +// THE PROOF, both halves required: +// 1. availability.json says the CHECK found the video gone (deleted / +// private / members-only) AT MOST A MINUTE BEFORE the mark's setAt: a +// history entry by source "check", or the record's top level (checkedAt, +// checkedBy "check"). ONE-SIDED (review F5): the gate pins only after the +// check has written what it saw (tier C: runAvailabilityCheck records, +// then verifyBeforeClean reads it and pins), on the same clock, so the +// observation can never come after the pin. An observation after setAt +// is some other check, not the one that set this mark. +// 2. A FINISHED clean job of the video's channel (clean-audio-transcribed or +// clean-audio-retry — the only jobs whose gate pins), whose start is at or +// before setAt and whose end at or after it — the pin is written inside +// the job's run, between the two times its record holds — and whose log +// names the pin: the gate's own line `Pinned <id> as do-not-clean (<that +// availability>)`. +// What it cannot prove, it leaves the operator's and says why. Its limits: +// tier A of the gate pins on a CACHED verdict (the check ran days or weeks +// before), so (1) fails for those; a job record is gone once retention prunes +// it, so (2) fails for any mark older than the oldest record; a later recheck +// moves checkedAt, and a same-state recheck adds no history entry. +// +// Dry run by default. A real run writes each relabel through the one writer +// (relabelDoNotCleanInferred), which refuses a mark that changed since it was +// judged (a person re-set it, or a writer labelled it). + +export const MARK_PROOF_WINDOW_MS = 60_000; +const CLEAN_JOB_KINDS = new Set(["clean-audio-transcribed", "clean-audio-retry"]); + +export type MarkNotProvenReason = + | "no-availability-record" + | "not-gone" + | "no-check-within-a-minute" + | "no-clean-job-naming-it" + | "changed-since"; + +export type MarkBackfillResult = { + slug: string; + dryRun: boolean; + // Marks on the channel, and those already saying who set them. + marks: number; + labelled: number; + // Relabelled (would be, on a dry run), each with its evidence. + relabelled: { id: string; setAt: string; evidence: DoNotCleanEvidence }[]; + // Left the operator's, each with the first half of the proof it failed. + notProven: { id: string; setAt: string; reason: MarkNotProvenReason }[]; + // What the job records reach back to: the oldest clean job on record (null: + // none), so "no clean job naming it" can be read against it. + oldestCleanJobAt: string | null; +}; + +// THE UNDO (marks-backfill {"undo": true}): every INFERRED label of the +// channel returns to unlabelled — the operator's, as before the backfill. +// Only marks with `inferred: true` are touched; setAt, note and audioRemoved +// stay. A dry run unless `dryRun` is false; the same listing, with each +// label's evidence. +export type MarkUndoResult = { + slug: string; + dryRun: boolean; + undo: true; + marks: number; + unlabelled: { id: string; setAt: string; evidence: DoNotCleanEvidence | null }[]; + // Changed between the listing and the write (a person or a writer set it since). + changedSince: string[]; +}; + +export async function undoMarkProvenanceBackfill({ + paths, + channelSlug, + dryRun = true, +}: { + paths: Paths; + channelSlug: string; + dryRun?: boolean; +}): Promise<MarkUndoResult> { + await assertChannelTextReadable(paths, channelSlug); + const dataDir = path.join(paths.channelsDir, channelSlug, "data"); + const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); + const out: MarkUndoResult = { slug: channelSlug, dryRun, undo: true, marks: 0, unlabelled: [], changedSince: [] }; + for (const id of ids) { + const videoDir = path.join(dataDir, id); + const mark = await loadDoNotClean(videoDir); + if (!mark) continue; + out.marks++; + if (mark.inferred !== true || mark.by !== "availability-check") continue; + if (!dryRun && !(await unlabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }))) { + out.changedSince.push(id); + continue; + } + out.unlabelled.push({ id, setAt: mark.setAt, evidence: mark.evidence ?? null }); + } + return out; +} + +export const NOT_PROVEN_SENTENCE: Record<MarkNotProvenReason, string> = { + "no-availability-record": "no availability.json", + "not-gone": "availability.json does not say gone", + "no-check-within-a-minute": "no check found it gone within a minute of the mark", + "no-clean-job-naming-it": "no clean job on record, running then, names the pin", + "changed-since": "the mark changed while this ran", +}; + +type CleanJob = { meta: JobMeta; log: string | null }; + +async function loadCleanJobs(paths: Paths, slug: string): Promise<CleanJob[]> { + const names = await readdir(paths.jobsDir).catch(() => [] as string[]); + const out: CleanJob[] = []; + for (const n of names) { + if (!n.endsWith(".meta.json")) continue; + const meta = await readJobMeta(paths, n.slice(0, -".meta.json".length)); + if (!meta || !CLEAN_JOB_KINDS.has(meta.kind)) continue; + if ((meta.channelSlug ?? meta.spec?.slug) !== slug) continue; + // Running or queued: no end to bound it by. + if (typeof meta.startedAt !== "number" || typeof meta.endedAt !== "number") continue; + out.push({ meta, log: null }); + } + return out; +} + +async function logOf(paths: Paths, job: CleanJob): Promise<string> { + if (job.log === null) { + job.log = await readFile(path.join(paths.jobsDir, `${job.meta.id}.log`), "utf8").catch(() => ""); + } + return job.log; +} + +export async function backfillMarkProvenance({ + paths, + channelSlug, + dryRun = true, + now = new Date(), +}: { + paths: Paths; + channelSlug: string; + dryRun?: boolean; + now?: Date; +}): Promise<MarkBackfillResult> { + await assertChannelTextReadable(paths, channelSlug); + const dataDir = path.join(paths.channelsDir, channelSlug, "data"); + const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); + const jobs = await loadCleanJobs(paths, channelSlug); + const oldest = jobs.reduce((m, j) => Math.min(m, j.meta.startedAt!), Infinity); + const result: MarkBackfillResult = { + slug: channelSlug, + dryRun, + marks: 0, + labelled: 0, + relabelled: [], + notProven: [], + oldestCleanJobAt: Number.isFinite(oldest) ? new Date(oldest).toISOString() : null, + }; + + for (const id of ids) { + const videoDir = path.join(dataDir, id); + const mark = await loadDoNotClean(videoDir); + if (!mark) continue; + result.marks++; + if (mark.by !== undefined) { + result.labelled++; + continue; + } + const setAt = Date.parse(mark.setAt); + const fail = (reason: MarkNotProvenReason) => result.notProven.push({ id, setAt: mark.setAt, reason }); + // (1) The availability record. + const av = await loadAvailability(videoDir); + if (!av) { + fail("no-availability-record"); + continue; + } + // One-sided: observed, then pinned within the minute. + const near = (iso: string) => { + const lead = setAt - Date.parse(iso); + return Number.isFinite(lead) && lead >= 0 && lead <= MARK_PROOF_WINDOW_MS; + }; + const seen: { availability: string; observedAt: string; field: "history" | "checkedAt" }[] = []; + for (const h of av.history ?? []) { + if (h.source === "check" && isPermanentlyGone(h.availability) && near(h.observedAt)) { + seen.push({ availability: h.availability, observedAt: h.observedAt, field: "history" }); + } + } + if (av.checkedBy === "check" && isPermanentlyGone(av.availability) && near(av.checkedAt)) { + seen.push({ availability: av.availability, observedAt: av.checkedAt, field: "checkedAt" }); + } + if (seen.length === 0) { + const everGone = isPermanentlyGone(av.availability) || (av.history ?? []).some((h) => isPermanentlyGone(h.availability)); + fail(everGone ? "no-check-within-a-minute" : "not-gone"); + continue; + } + // (2) A clean job running then, whose log names this pin. + let evidence: DoNotCleanEvidence | null = null; + for (const job of jobs) { + const { startedAt, endedAt } = job.meta; + if (setAt < startedAt! || setAt > endedAt!) continue; + const log = await logOf(paths, job); + const obs = seen.find((o) => log.includes(`Pinned ${id} as do-not-clean (${o.availability})`)); + if (obs) { + evidence = { ...obs, jobId: job.meta.id, jobKind: job.meta.kind }; + break; + } + } + if (!evidence) { + fail("no-clean-job-naming-it"); + continue; + } + if (!dryRun && !(await relabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }, evidence, now))) { + fail("changed-since"); + continue; + } + result.relabelled.push({ id, setAt: mark.setAt, evidence }); + } + return result; +} diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts @@ -4,7 +4,13 @@ // shape that buildIndex would emit, plus a `source` marker. import path from "node:path"; -import { open, readdir, readFile, stat } from "node:fs/promises"; +import { open, readFile, stat } from "node:fs/promises"; +import { + readStoredTextHead, + readdirLogical, + storedTextLogicalSize, + storedTextMtimeMs, +} from "../lib/storedText-server"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { hasWordTiming, type Cue } from "../lib/vtt"; import { @@ -300,14 +306,17 @@ export async function isCuesJsonFresh( ): Promise<{ fresh: boolean; reason: CuesFreshReason; cuesPath: string }> { const cuesPath = path.join(videoDir, CUES_JSON_FILENAME); const metaPath = path.join(videoDir, META_FILENAME); - const entries = await readdir(videoDir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is an input under + // its plain name, and its mtime is the plain file's (the stored form carries + // it exactly), so a compression moves no cues.json to stale. + const entries = await readdirLogical(videoDir); const whisperPath = path.join(videoDir, WHISPER_FILENAME); const inputs = captionInputs(entries); const [cuesMs, metaMs, whisperMs, ...inputMs] = await Promise.all([ mtimeMs(cuesPath), mtimeMs(metaPath), mtimeMs(whisperPath), - ...inputs.map((n) => mtimeMs(path.join(videoDir, n))), + ...inputs.map((n) => storedTextMtimeMs(videoDir, n)), ]); const vttMs = inputMs.reduce<number | null>( (max, ms) => (ms !== null && (max === null || ms > max) ? ms : max), @@ -383,18 +392,24 @@ async function followsCaptionTrackRule( const vtts = englishVttsByPreference(entries); if (vtts.length === 0) return true; try { - if (vtts.length === 1 && hasWordTiming(await readHead(path.join(videoDir, vtts[0])))) { + // The DECODED head of a stored track (lib/storedText-server.ts). + if ( + vtts.length === 1 && + hasWordTiming((await readStoredTextHead(videoDir, vtts[0], HEAD_BYTES)).toString("utf8")) + ) { return true; } const m = (await readHead(cuesPath)).match(/"captionTrackRule"\s*:\s*(\d+)/); if (m !== null && Number(m[1]) === CAPTION_TRACK_RULE_VERSION) return true; if (/"cues"\s*:\s*\[\s*\]\s*\}\s*$/.test(await readTail(cuesPath))) return false; if (!entries.includes(VTT_FILENAME) || !entries.includes(ORIG_VTT_FILENAME)) return true; + // LOGICAL sizes: a stored track's is its frame header's content size — + // never the compressed size, which differs between the two forms. const [en, orig] = await Promise.all([ - stat(path.join(videoDir, VTT_FILENAME)), - stat(path.join(videoDir, ORIG_VTT_FILENAME)), + storedTextLogicalSize(videoDir, VTT_FILENAME), + storedTextLogicalSize(videoDir, ORIG_VTT_FILENAME), ]); - return en.size === orig.size; + return en === orig; } catch { return false; } diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts @@ -34,7 +34,7 @@ // share. Nothing new. import path from "node:path"; -import { open, readFile, readdir } from "node:fs/promises"; +import { open, readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { getSettings, type SiteSettings } from "../lib/settings"; import { isGateHeld } from "../lib/pauseGates"; @@ -49,6 +49,17 @@ import { runPool } from "../jobs/concurrentRunner"; import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus"; +import { readStoredText } from "../lib/storedText-server"; + +// A remote unit's inputs, as the worker receives them: each under its LOGICAL +// name with its PLAIN bytes (lib/storedText.ts) — a caption stored as `.zst` +// is decoded here, so the worker protocol and an older worker see exactly what +// they always did. Exported for its test. +export async function readUnitInputFiles(videoDir: string, names: readonly string[]): Promise<Record<string, Buffer>> { + const files: Record<string, Buffer> = {}; + for (const name of names) files[name] = await readStoredText(videoDir, name); + return files; +} import { DIARIZATION_OPERATION_ID, DIGEST_OPERATION_ID, @@ -1311,9 +1322,7 @@ async function runViaTaggedRemote( checkUntranscribable: true, }); const files: Record<string, Buffer> = {}; - for (const name of unit.op.inputs(listing)) { - files[name] = await readFile(path.join(videoDir, name)); - } + Object.assign(files, await readUnitInputFiles(videoDir, unit.op.inputs(listing))); // The channel context is injected because a scratch corpus has no // digest-context.md to read. Read per channel, memoized by the same map // the targets use. diff --git a/common/controller/pruneSavedVideos.test.ts b/common/controller/pruneSavedVideos.test.ts @@ -91,7 +91,7 @@ test("never evicts override or pinned containers, even out of window", async () await setDoNotClean( path.join(paths.channelsDir, "ch", "data", "deleted"), true, - "deleted from source", + { by: "availability-check", via: "pre-clean-check", note: "deleted from source" }, ); const res = await pruneSavedVideos({ channelSlug: "ch", paths }); diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts @@ -1,4 +1,5 @@ -import { removeStoredText } from "../lib/storedText-write-server"; +import { removeStoredText, verifyStoredText } from "../lib/storedText-write-server"; +import { logicalEntries, storedFormsIn } from "../lib/storedText"; import path from "node:path"; import fs from "fs-extra"; import type { Paths } from "../lib/paths"; @@ -70,7 +71,10 @@ export async function purgeSupersededAutoSubs({ for (const id of dirs) { if (signal?.aborted) break; const videoDir = path.join(dataDir, id); - const entries = await readdir(videoDir).catch(() => [] as string[]); + // PHYSICAL, then LOGICAL (lib/storedText.ts): a track stored as `.zst` is + // a track here under its plain name — and is purged in both forms. + const physical = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physical); // No transcript of our own yet — nothing has been superseded, so the VTT is // still this video's only transcript. Never touch it. if (!entries.includes(WHISPER_FILENAME)) continue; @@ -89,9 +93,26 @@ export async function purgeSupersededAutoSubs({ skipped++; continue; } + // BOTH FORMS WITH DIFFERENT CONTENT: the sniff read the plain one, and + // the stored one is another capture this purge has not looked at (it + // may be the manual one) — kept, both, for a person. + if (storedFormsIn(physical, name) === "both") { + const v = await verifyStoredText(videoDir, name); + if (v.status !== "ok") { + log(`Kept ${id}/${name} (its plain and stored forms differ: ${v.status} — settle it on the files card)`); + skipped++; + continue; + } + } // Both forms (lib/storedText-write-server.ts): a stored copy left behind // would bring the captions back. Each through removeMediaFile. - await removeStoredText(videoDir, name); + const out = await removeStoredText(videoDir, name); + if ("refused" in out) { + // Nothing was removed (a full disk, or a run holding the file). + log(`Kept ${id}/${name} — ${out.refused}`); + skipped++; + continue; + } log(`Removed ${id}/${name}`); removedFiles++; removedHere++; diff --git a/common/controller/readXTrending.test.ts b/common/controller/readXTrending.test.ts @@ -391,7 +391,8 @@ test("a 403 fails with its own sentence, keeps what was read, and raises no logi assert.match(result.sentence, /3 posts read before it were kept \(3 new\)\./); assert.match(result.sentence, /not taken for a lost login and no alert was raised/); assert.deepEqual(notes, []); - assert.equal(limited, 0); + // A 403 is X's bot check as often as not: the same 15-minute X stop as a 429 (review 1 F1). + assert.equal(limited, 1); assert.equal((await readXTrendingPosts(root(paths))).length, 3); }); diff --git a/common/controller/readXTrending.ts b/common/controller/readXTrending.ts @@ -39,7 +39,7 @@ import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { heldPlatformRefusal, platformCooldownRemainingMs, - recordPlatformCooldown, + recordXStop, } from "../jobs/downloadBackoff"; import { isXTrendingChannel, @@ -101,7 +101,24 @@ export const READ_X_TRENDING_RESULT_MARKER = "@@read-x-trending "; // rate-limit window. Written as the `twitter` platform cooldown // (jobs/downloadBackoff.ts recordPlatformCooldown — the cooldown import-post // already respects), read by this job's enqueue and start. -export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; +export { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; +import { xJobPostLimit } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; + +// WHAT ONE READ MAY TAKE (review 2 G3): its posts over all its tabs stay +// within social.x.maxPostsPerJob (default 300; the code's ceiling bounds it). +export function xTrendingPostsPerTab(asked: number, tabs: number, x: { maxPostsPerJob?: number } | undefined): number { + return Math.max(1, Math.min(asked, Math.floor(xJobPostLimit(x) / Math.max(1, tabs)))); +} + +function xPostsSettingNow(): { maxPostsPerJob?: number } | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; const X_PLATFORM = "twitter"; const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); @@ -282,7 +299,9 @@ export async function planReadXTrending( slug: ask.slug, channelRoot, ref, - limits: limits.limits, + // WHAT ONE X JOB MAY READ (review 1 F8): the read's posts over all its + // tabs stay within X's per-job ceiling (lib/xSitting.ts). + limits: { ...limits.limits, posts: xTrendingPostsPerTab(limits.limits.posts, tabs.tabs.length, xPostsSettingNow()) }, ...(topic ? { topic } : {}), probe: ask.probe === true, headed: ask.headed === true, @@ -727,9 +746,13 @@ export async function runXTrendingRead(o: { // cannot send the next read straight back to X. let limitedUntil: number | undefined; if (page.stop === "rate-limit") { - limitedUntil = await (deps.noteRateLimit ?? (() => recordPlatformCooldown(X_PLATFORM, X_RATE_LIMIT_HOLD_MS, paths, now())))().catch( + limitedUntil = await (deps.noteRateLimit ?? (() => recordXStop("a rate limit (429) to a trending read", paths, now())))().catch( () => now() + X_RATE_LIMIT_HOLD_MS, ); + } else if (page.stop === "forbidden") { + // A refusal (403) is X's bot check as often as not: the same X stop + // (review 1 F1). + await (deps.noteRateLimit ?? (() => recordXStop("a refusal (403) to a trending read", paths, now())))().catch(() => 0); } const untilText = limitedUntil === undefined ? "" : `${hhmm(limitedUntil)} UTC (${Math.ceil((limitedUntil - now()) / 60_000)} min)`; diff --git a/common/controller/reconcileVideoDirs.test.ts b/common/controller/reconcileVideoDirs.test.ts @@ -193,6 +193,21 @@ test("a stored chat and a plain chat collide by their LOGICAL name; the loser is ); }); +test("a stored caption and a plain caption collide by their LOGICAL name too (lane text-compress-captions)", async (t) => { + const channelDir = await makeChannel(); + t.after(() => rm(channelDir, { recursive: true, force: true })); + await writeStrayDir(channelDir, "canonical01", { "transcript.en.vtt.zst": "destination stored caption" }); + await writeStrayDir(channelDir, "v-canonical01", { "transcript.en.vtt": "source plain caption" }); + 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.en.vtt", "transcript.en.vtt.zst.dup-v-canonical01"]); + assert.equal( + await readFile(path.join(dst, "transcript.en.vtt.zst.dup-v-canonical01"), "utf8"), + "destination stored caption", + ); +}); + 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 })); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -1592,10 +1592,15 @@ async function recordLiveRunInner( // 4. Keep it, and hand it on. if (req.doNotClean) { - await setDoNotClean(videoDir, true, req.note); + await setDoNotClean(videoDir, true, { + by: "live-recording", + via: "record-live", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }); say(`Marked "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } - await applyPendingKeep(paths, req.slug, id, onLog); + await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId); const facts = await (deps.handoff ?? readHandoffFacts)({ slug: req.slug, channelConfig: opts.channelConfig, diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -22,7 +22,7 @@ // (current.json), else the newest done iteration that carries a report. import { modelLogged } from "./jobModelLog"; -import { access, readdir, readFile } from "node:fs/promises"; +import { access, readFile } from "node:fs/promises"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; @@ -40,6 +40,7 @@ import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { detectPlatform } from "../lib/detectPlatform.mjs"; import { WHISPER_FILENAME, englishVttsByPreference } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; +import { isStoredTextReadError, readStoredText, readdirLogical } from "../lib/storedText-server"; import { parseTranscriptJson } from "../lib/whisper"; import { isCuesJsonFresh, readNormalizedTranscript } from "./normalizeTranscript"; import { diskPostChannelOf } from "../lib/report/convert-server"; @@ -501,7 +502,8 @@ async function runRefreshJob( export async function diskRecordOf(channelsDir: string, slug: string, id: string): Promise<RecordRead | null> { const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null); if (!dir) return null; - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a stored caption is a track under its name. + const entries = await readdirLogical(dir); if (!entries.length) return null; const tracks: { name: string; cues: { start: number; end: number; text: string }[] }[] = []; const fresh = await isCuesJsonFresh(dir).catch(() => ({ fresh: false as const })); @@ -514,7 +516,14 @@ export async function diskRecordOf(channelsDir: string, slug: string, id: string if (w.length) tracks.push({ name: WHISPER_FILENAME, cues: w }); } for (const name of englishVttsByPreference(entries)) { - const v = await readFile(path.join(dir, name), "utf8").then((t) => parseVtt(t), () => []); + // A stored track that does not decode is an error, never "no cues" (REVIEW-1 F3). + const v = await readStoredText(dir, name, "utf8").then( + (t) => parseVtt(t), + (err: unknown) => { + if (isStoredTextReadError(err)) throw err; + return []; + }, + ); if (v.length) tracks.push({ name, cues: v }); } const state = stateFromAvailability(await resolveEffectiveAvailability(dir).catch(() => null)); diff --git a/common/controller/storedText.captions.test.ts b/common/controller/storedText.captions.test.ts @@ -0,0 +1,244 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, utimes, 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.captions.test.ts +// +// THE CAPTIONS ARE STILL FOUND BY EVERY READER AFTER THEY ARE COMPRESSED (lane +// text-compress-captions, slice 4). Each case builds a video dir whose caption +// tracks are `transcript.<lang>.vtt.zst` only and asks a reader of each class +// what it sees: the listing (readVideoFiles), the cue read, the freshness +// stat, the head sniff (provenance, word timing), the logical size, the +// yt-dlp skip-if-exists checks (a miss there is a re-fetch, or an audio +// download and a transcription), the cited record, the remote worker's +// inputs. Before this slice each read a stored track as ABSENT — or, for a +// head sniff, read zstd bytes and answered WRONG. Temp corpus, no network, +// no yt-dlp. Synthetic names only. + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-captions-")); +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 { readVideoFiles, readEnglishVttCues, pickIndexTranscript } = await import("../lib/videoStatus"); +const { normalizeTranscript, isCuesJsonFresh } = await import("./normalizeTranscript"); +const { readVttProvenance, resolveCaptionsProvenance, isAutoSubsOnly } = await import("../lib/subtitleProvenance"); +const { readVideoTracks } = await import("../lib/captionTracks-server"); +const { destinationExists, subLangsForVideo } = await import("../ytdlp/runYtdlp"); +const { youtubeHandlingArgs, __hasAnyTranscriptOnDiskForTest } = await import("../ytdlp/downloadOneManaged"); +const { readCitedRecord } = await import("../publish/composeReports"); +const { diskRecordOf } = await import("./reportRefresh"); +const { hasCorpusTranscript } = await import("./livePreclip"); +const { readUnitInputFiles } = await import("./operationBatch"); +const { storeFixture } = await import("../testing/storedTextFixture"); + +const paths = getPaths(); +const SLUG = "synth-captions"; +const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/videos", name: "Synth" } as ChannelConfig; +const channelDir = path.join(CORPUS, "channels", SLUG); +const dataDir = path.join(channelDir, "data"); + +// YouTube's rolling ASR shape (align + inline word timing) and a human track. +const ASR = + "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"; +const MANUAL = + "WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nA human wrote this line.\n\n" + + "00:00:04.000 --> 00:00:09.000\nAnd this one, with care.\n\n00:00:09.000 --> 00:00:12.000\nThe end.\n"; +const ORIG = ASR.replace("First", "Original").replace("Second", "Spoken"); + +async function video(id: string, tracks: Record<string, string>, extra: Record<string, string> = {}): Promise<string> { + const dir = path.join(dataDir, 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 ${id}`, + upload_date: "20260101", + duration: 120, + webpage_url: `https://www.youtube.com/watch?v=${id}`, + extractor_key: "Youtube", + }), + ); + for (const [name, body] of Object.entries({ ...tracks, ...extra })) await writeFile(path.join(dir, name), body); + // Sub-millisecond times: a `Date` round trip would lose them. + for (const name of Object.keys(tracks)) await utimes(path.join(dir, name), 1763700000.123457, 1763700000.987653); + return dir; +} + +async function storeAll(dir: string): Promise<void> { + for (const n of await readdir(dir)) if (/^transcript\.[^.]+\.vtt$/.test(n)) await storeFixture(dir, n); + assert.equal((await readdir(dir)).some((n) => n.endsWith(".vtt")), false, "only stored captions are left"); +} + +test("the listing: readVideoFiles is LOGICAL — a stored track is listed, primary and all", async () => { + const dir = await video("list1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG, "transcript.es.vtt": MANUAL }); + const before = await readVideoFiles(dir); + await storeAll(dir); + const after = await readVideoFiles(dir); + assert.equal(after.hasYtVtt, true); + assert.equal(after.ytVttFile, "transcript.en-orig.vtt"); + assert.equal(after.hasNonCanonicalVtt, before.hasNonCanonicalVtt); + assert.deepEqual([...after.entries].sort(), [...before.entries].sort(), "the same logical names"); + assert.ok(after.physicalEntries.includes("transcript.en.vtt.zst")); + assert.deepEqual(pickIndexTranscript(after), pickIndexTranscript(before)); +}); + +test("the cue read: readEnglishVttCues reads the stored tracks, under their plain names", async () => { + const dir = await video("cues1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readEnglishVttCues(dir); + await storeAll(dir); + assert.deepEqual(await readEnglishVttCues(dir), before); + // Given the caller's raw readdir, too. + assert.deepEqual(await readEnglishVttCues(dir, await readdir(dir)), before); + assert.equal(before?.filename, "transcript.en-orig.vtt"); +}); + +test("normalize: a cues.json made before compression stays FRESH, and a forced one writes the same cues", async () => { + const dir = await video("norm1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "wrote"); + const made = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8")); + await storeAll(dir); + assert.deepEqual(await isCuesJsonFresh(dir), { fresh: true, reason: "fresh", cuesPath: path.join(dir, "transcript.cues.json") }); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "fresh"); + assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {}, force: true })).status, "wrote"); + const again = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8")); + assert.deepEqual(again.cues, made.cues); + assert.equal(again.vttFile, "transcript.en-orig.vtt", "the record names the LOGICAL track"); +}); + +test("normalize: the caption-track rule's head and size checks read the stored tracks as the plain ones", async () => { + // An unversioned cues.json (made before the rule had a version) with cues, + // en and en-orig of DIFFERENT content: stale — it was read from en, and + // en-orig is read now. Stored, the sizes compared must be the logical ones. + const dir = await video("rule1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG + "\n" }); + await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} }); + const cuesPath = path.join(dir, "transcript.cues.json"); + const rec = JSON.parse(await readFile(cuesPath, "utf8")); + delete rec.captionTrackRule; + await writeFile(cuesPath, JSON.stringify(rec)); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "plain: stale"); + await storeFixture(dir, "transcript.en.vtt"); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "en stored, en-orig plain: still stale"); + await storeFixture(dir, "transcript.en-orig.vtt"); + assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "both stored: still stale"); + + // A lone word-timed track with an empty unversioned cues.json: FRESH (its + // parse did not change) — read from the DECODED head. + const lone = await video("rule2", { "transcript.en.vtt": ASR }); + await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ title: "x", cues: [] })); + assert.equal((await isCuesJsonFresh(lone)).fresh, true, "plain"); + await storeFixture(lone, "transcript.en.vtt"); + assert.equal((await isCuesJsonFresh(lone)).fresh, true, "stored: the head is decoded"); +}); + +test("the head sniff: provenance reads the DECODED head — ASR stays ASR, manual stays manual", async () => { + const dir = await video("prov1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ASR, "transcript.es.vtt": MANUAL }); + await storeAll(dir); + assert.equal(await readVttProvenance(dir, "transcript.en.vtt"), "asr"); + assert.equal(await readVttProvenance(dir, "transcript.es.vtt"), "manual"); + assert.equal(await resolveCaptionsProvenance(dir, await readdir(dir)), "asr"); + const files = await readVideoFiles(dir); + assert.equal(await isAutoSubsOnly(dir, files), true, "the replace lane still sees an ASR-only video"); + const human = await video("prov2", { "transcript.en.vtt": MANUAL }); + await storeAll(human); + assert.equal(await resolveCaptionsProvenance(human, await readdir(human)), "manual", "a human track is never scheduled for replacement"); +}); + +test("the alternate tracks: readVideoTracks reads stored tracks", async () => { + const dir = await video("alts1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readVideoTracks(dir); + await storeAll(dir); + assert.deepEqual(await readVideoTracks(dir), before); + assert.equal(before?.tracks.length, 2); +}); + +test("destinationExists: a stored transcript.en.vtt is the destination — the URL is NOT fetched again", async () => { + await video("dest1", { "transcript.en.vtt": ASR }); + await storeAll(path.join(dataDir, "dest1")); + assert.equal(await destinationExists(dataDir, "dest1", "youtube"), true); + // The replace-auto-captions run still sees it as ASR (the decoded sniff). + assert.equal(await destinationExists(dataDir, "dest1", "youtube", { replaceAutoSubs: true }), false); + await video("dest2", { "transcript.en.vtt": MANUAL }); + await storeAll(path.join(dataDir, "dest2")); + assert.equal(await destinationExists(dataDir, "dest2", "youtube", { replaceAutoSubs: true }), true, "a human track suppresses it"); +}); + +test("hasAnyTranscriptOnDisk: a stored caption is a transcript — no audio download, no transcription", async () => { + for (const name of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.es.vtt"]) { + const dir = await video(`any-${name.split(".")[1]}`, { [name]: ASR }); + await storeAll(dir); + assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), true, name); + } + // The control: a stored chat alone is not a transcript. + const chat = await video("any-chat", {}, { "transcript.live_chat.json": "{}\n" }); + await storeFixture(chat, "transcript.live_chat.json"); + assert.equal(await __hasAnyTranscriptOnDiskForTest(chat), false); +}); + +test("the missing-subs pass leaves every stored track out of --sub-langs (under --no-overwrites main skipped a present one)", async () => { + const dir = await video("subs1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + await storeFixture(dir, "transcript.en.vtt"); + await storeFixture(dir, "transcript.en-orig.vtt"); + const entries = await readdir(dir); + assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*,live_chat,-en,-en-orig"); + // Both forms (the plain is there): yt-dlp's own skip sees it — unchanged. + assert.equal(subLangsForVideo(["transcript.en.vtt", "transcript.en.vtt.zst"], "en.*"), "en.*"); + // A stored chat and a stored caption: the chat left out as for a `later` + // channel, the caption excluded by code. + assert.equal(subLangsForVideo(["transcript.live_chat.json.zst", "transcript.en.vtt.zst"], "en.*,live_chat"), "en.*,-en"); + const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1]; + // The managed download fetches a stored caption AGAIN (main's re-download + // rule, REVIEW-1 F1): no exclusion there; the pass is settled afterwards + // (ytdlp/captionsRefetch.test.ts). Only the stored chat is left out. + assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat"); + assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*"); +}); + +test("the cited record (compose, report refresh) reads stored tracks — cues and every English track", async () => { + const dir = await video("cite1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG }); + const before = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1"); + const beforeDisk = await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1"); + await storeAll(dir); + const after = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1"); + assert.deepEqual(after?.cues, before?.cues); + assert.deepEqual(after?.tracks, before?.tracks); + assert.equal(after?.tracks.length, 2); + assert.deepEqual(await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1"), beforeDisk); +}); + +test("the live pre-clip's transcript check sees a stored caption", async () => { + const dir = await video("pre1", { "transcript.en.vtt": ASR }); + await storeAll(dir); + assert.equal(await hasCorpusTranscript(dir), true); +}); + +test("the remote worker's inputs: the PLAIN bytes under the logical name", async () => { + const dir = await video("worker1", { "transcript.en-orig.vtt": ORIG }); + await storeAll(dir); + const files = await readUnitInputFiles(dir, ["metadata.info.json", "transcript.en-orig.vtt"]); + assert.deepEqual(Object.keys(files), ["metadata.info.json", "transcript.en-orig.vtt"]); + assert.equal(files["transcript.en-orig.vtt"].toString("utf8"), ORIG); +}); + +test("with no caption in either form, every check says so (the control)", async () => { + const dir = await video("none1", {}); + assert.equal(await destinationExists(dataDir, "none1", "youtube"), false); + assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), false); + assert.equal((await readVideoFiles(dir)).hasYtVtt, false); + assert.equal(await readEnglishVttCues(dir), null); + assert.equal(paths.channelsDir, path.join(CORPUS, "channels")); +}); diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts @@ -68,8 +68,9 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too", 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"); + // Both forms of the same track (a compression that stopped before the + // original went): purged in both. + await storeFixture(d, "transcript.en.vtt", { keepPlain: true }); const r = await purgeSupersededAutoSubs({ channelSlug: "p", paths: { channelsDir: path.join(ROOT, "channels") } as never, @@ -79,6 +80,48 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too", assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]); }); +test("the purge KEEPS both forms when they differ (or the stored one does not decode): it sniffed only the plain one", async () => { + // (Changed in lane text-compress-captions: slice 1 removed a stored sibling + // whatever it held. A stored copy with other content is another capture — + // it may be the manual track — and nothing removes a stored caption + // because a different one arrived.) + for (const [id, stored] of [["v4", "differs"], ["v5", "corrupt"]] as const) { + const d = await videoDir("p", id); + await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] })); + if (stored === "differs") { + await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nA human track.\n"); + await storeFixture(d, "transcript.en.vtt"); + } else { + await writeFile(path.join(d, "transcript.en.vtt.zst"), "not a zstd frame"); + } + await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT); + const r = await purgeSupersededAutoSubs({ + channelSlug: "p", + ids: [id], + paths: { channelsDir: path.join(ROOT, "channels") } as never, + onLog: () => {}, + }); + assert.equal(r.removedFiles, 0, stored); + assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt", "transcript.en.vtt.zst", "transcript.json"], stored); + } +}); + +test("the purge finds a superseded ASR track stored ONLY compressed, and removes it", async () => { + const d = await videoDir("p", "v6"); + await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] })); + await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT); + await storeFixture(d, "transcript.en.vtt"); + assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt.zst", "transcript.json"]); + const r = await purgeSupersededAutoSubs({ + channelSlug: "p", + ids: ["v6"], + paths: { channelsDir: path.join(ROOT, "channels") } as never, + onLog: () => {}, + }); + assert.equal(r.removedFiles, 1, "the decoded head sniffs as ASR"); + assert.deepEqual(await readdir(d), ["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 @@ -157,3 +200,26 @@ test("delete one named form through tier links: the named form's bytes go, the o assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "unreadable" } }); assert.equal(await readStoredText(e, CHAT, "utf8"), "ONLY COPY\n"); }); + +// REVIEW-1 N1 (captions lane): "Set as transcript" over a stored `en` writes +// the pick as a plain transcript.en.vtt beside it and pins it. Deleting the +// plain pick must not leave the pin ranking YouTube's stored `en` first. +test("the files card: the plain pick deleted beside a stored en of other content takes the pin with it", async () => { + const d = await videoDir("pin", "v1"); + await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nyoutube's en\n"); + await storeFixture(d, "transcript.en.vtt"); + await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nthe picked track\n"); + await writeFile(path.join(d, "transcript-pin.json"), JSON.stringify({ from: "transcript.en-US.vtt", pinnedAt: "2026-11-21T00:00:00.000Z" })); + const out = await removeStoredTextForm(d, "transcript.en.vtt"); + assert.notEqual(out, "busy"); + assert.equal((out as { unpinned?: boolean }).unpinned, true); + assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt.zst"]); + // The same content beside it: nothing was picked over it — the pin stays. + const e = await videoDir("pin", "v2"); + await writeFile(path.join(e, "transcript.en.vtt"), "WEBVTT\n\nsame\n"); + await storeFixture(e, "transcript.en.vtt", { keepPlain: true }); + await writeFile(path.join(e, "transcript-pin.json"), JSON.stringify({ from: "transcript.en.vtt", pinnedAt: "x" })); + const same = await removeStoredTextForm(e, "transcript.en.vtt"); + assert.equal((same as { unpinned?: boolean }).unpinned, undefined); + assert.ok((await readdir(e)).includes("transcript-pin.json")); +}); diff --git a/common/controller/storedText.unreadable.test.ts b/common/controller/storedText.unreadable.test.ts @@ -0,0 +1,114 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, 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 controller/storedText.unreadable.test.ts +// +// REVIEW-1 F3 (captions lane): A STORED FILE THAT CANNOT BE READ IS AN ERROR +// THAT SURFACES, NEVER "NO TEXT". On a Node without zstd every process refuses +// to start, naming the Node it needs; and a stored caption whose frame does +// not decode is thrown past the readers that skip a missing track — the copies +// lane does not read it as "not done". (The index's side is buildIndex.test.ts +// (w).) Temp dirs, synthetic names. + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-unreadable-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); +const COMMON = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +const { zstdSupportProblem, assertZstdSupport } = await import("../lib/zstdSupport.mjs"); +const { readEnglishVttCues } = await import("../lib/videoStatus"); +const { readVideoTracks } = await import("../lib/captionTracks-server"); +const { isStoredTextReadError } = await import("../lib/storedText-server"); +const { __computeDoneForTest, unreadableStoredCaptionCount } = await import("./copiesLane"); + +const VTT = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\none two three four\n"; + +test("no zstd in this Node: the problem names the Node it needs; asked to assert, it refuses", () => { + assert.equal(zstdSupportProblem(), null, "this Node has it"); + const old = {}; + const p = zstdSupportProblem(old, "v22.11.0"); + assert.match(String(p), /needs node:zlib zstd — Node >= 22\.15 \(this is v22\.11\.0\)/); + assert.throws(() => assertZstdSupport("the editor", old, "v22.11.0"), /the editor refuses to start: .*Node >= 22\.15/); +}); + +test("a bare-node reader of stored text, and a common/bin CLI, refuse to start on a Node without zstd", async (t) => { + // A preload that takes zstd away, as an older Node would not have it (its + // own temp dir: made and removed by this test). + const own = await mkdtemp(path.join(tmpdir(), "no-zstd-")); + t.after(() => rm(own, { recursive: true, force: true })); + const NO_ZSTD = path.join(own, "no-zstd.mjs"); + await writeFile( + NO_ZSTD, + 'import zlib from "node:zlib";\nfor (const k of ["zstdDecompress", "createZstdCompress", "createZstdDecompress"]) delete zlib[k];\n', + ); + const reader = spawnSync(process.execPath, ["--import", NO_ZSTD, "-e", `await import(${JSON.stringify(path.join(COMMON, "lib", "storedText-read.mjs"))})`], { + encoding: "utf8", + input: "", + }); + assert.notEqual(reader.status, 0); + assert.match(reader.stderr, /refuses to start: stored text .*needs node:zlib zstd — Node >= 22\.15/); + // A CLI entry (runIfEntryPoint): a tiny entry point in the temp dir. + const entry = path.join(own, "cli-entry.ts"); + const cli = path.join(COMMON, "bin", "_cli.ts"); + await writeFile(entry, `import { runIfEntryPoint } from ${JSON.stringify(cli)};\nrunIfEntryPoint(import.meta.url, async () => { console.log("ran"); });\n`); + const tsx = path.join(COMMON, "node_modules", ".bin", "tsx"); + const run = spawnSync(tsx, [entry], { encoding: "utf8", cwd: own, env: { ...process.env, NODE_OPTIONS: `--import=${NO_ZSTD}` } }); + assert.notEqual(run.status, 0, run.stdout + run.stderr); + assert.doesNotMatch(run.stdout, /ran/); + assert.match(run.stderr, /cli-entry\.ts refuses to start: .*Node >= 22\.15/); + const ok = spawnSync(tsx, [entry], { encoding: "utf8", cwd: own, env: { ...process.env, NODE_OPTIONS: "" } }); + assert.equal(ok.status, 0, ok.stderr); + assert.match(ok.stdout, /ran/); +}); + +async function videoWithCorruptStored(id: string): Promise<string> { + const dir = path.join(ROOT, "channels", "synth", "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id })); + // A frame header claiming 64 bytes, then garbage: it does not decode. + await writeFile(path.join(dir, "transcript.en.vtt.zst"), Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x40, 1, 2, 3, 4, 5, 6])); + return dir; +} + +test("a stored caption that does not decode is THROWN by the caption readers, never skipped as no text", async () => { + const dir = await videoWithCorruptStored("bad1"); + await assert.rejects(readEnglishVttCues(dir), (e: unknown) => isStoredTextReadError(e)); + await assert.rejects(readVideoTracks(dir), (e: unknown) => isStoredTextReadError(e)); + // A readable fallback track does not hide it either: the corrupt one is + // the preferred one, and its words are unknown. + await writeFile(path.join(dir, "transcript.en-US.vtt"), VTT); + await assert.rejects(readEnglishVttCues(dir), (e: unknown) => isStoredTextReadError(e)); + // A MISSING track is still just missing. + const none = path.join(ROOT, "channels", "synth", "data", "none1"); + await mkdir(none, { recursive: true }); + assert.equal(await readEnglishVttCues(none), null); +}); + +test("the copies lane: an unreadable stored caption is not \"not done\" (it would send the lane to transcribe it)", async () => { + await videoWithCorruptStored("bad2"); + const paths = { channelsDir: path.join(ROOT, "channels") } as never; + const before = unreadableStoredCaptionCount(); + const warned: string[] = []; + const warn = console.warn; + console.warn = (m: string) => void warned.push(m); + try { + const done = await __computeDoneForTest( + "transcription", + paths, + {} as never, + "synth/bad2", + { facts: { duration: 10, captionsCountAsDone: true }, replaceAutoSubs: false }, + ["metadata.info.json", "transcript.en.vtt"], + ); + assert.equal(done, true); + } finally { + console.warn = warn; + } + assert.equal(unreadableStoredCaptionCount(), before + 1, "counted"); + assert.match(warned.join("\n"), /synth\/bad2: a stored caption cannot be read — .*transcript\.en\.vtt\.zst/); +}); diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -75,6 +75,8 @@ export type VerifyBeforeCleanOptions = { onLog?: (msg: string) => void; signal?: AbortSignal; probes?: VerifyProbes; + // The clean job this gate runs in, recorded on every mark it writes. + jobId?: string; }; function emptyVerdicts(): CleanVerdicts { @@ -97,6 +99,7 @@ export async function verifyBeforeClean({ onLog, signal, probes, + jobId, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -111,11 +114,17 @@ export async function verifyBeforeClean({ verdicts.alreadyGone.add(id); return; } - await setDoNotClean( - videoDir, - true, - `deleted from source (pre-clean check): ${availability}`, - ); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "pre-clean-check", + ...(jobId ? { jobId } : {}), + note: `deleted from source (pre-clean check): ${availability}`, + }); + // A mark that appeared between the read above and the write is kept. + if (!wrote) { + verdicts.alreadyGone.add(id); + return; + } verdicts.pinned.set(id, availability); log(`Pinned ${id} as do-not-clean (${availability}) — gone from source.`); }; diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts @@ -28,6 +28,11 @@ writeFileSync( const { getPaths } = await import("../lib/paths"); const xr = await import("./xRun"); +// X's gap is drawn in 5-12 min and has no off switch now (lane x-sittings: +// jobGapSeconds.twitter 0 no longer turns it off): a fake clock waits it out. +const { setQueueGapClock } = await import("../jobs/queueGap"); +let skew = 0; +setQueueGapClock({ now: () => Date.now() + skew, sleep: async (ms) => void (skew += ms) }); const { defaultChannelPriority } = await import("../lib/channelPriority"); const paths = getPaths(); diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -58,7 +58,7 @@ import { ulid } from "../jobs/ulid"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/networkGuard"; -import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap"; +import { noteQueueJobEnd, queueGapClock, waitForQueueGap, xQueueGapRange } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "../lib/sourcelessPosts"; @@ -802,8 +802,10 @@ export type XRunConsole = { run: XRunView | null; candidates: XRunCandidate[]; jar: XRunJar; - // X's queue gap between two channels (pacing.jobGapSeconds.twitter), seconds. + // X's queue gap between two channels, seconds: drawn per channel from + // [gapSeconds, gapMaxSeconds] (social.x.gapMinMinutes / gapMaxMinutes). gapSeconds: number; + gapMaxSeconds: number; maxPosts: number; }; @@ -833,11 +835,12 @@ export async function xRunConsole(paths: Paths, runId?: string): Promise<XRunCon listXRunCandidates(paths), xSessionReport({ paths }), ]); - let gapSeconds = 0; + let range = xQueueGapRange(undefined, undefined); try { - gapSeconds = queueGapFor(getSettings().pacing, "twitter").seconds; + const settings = getSettings(); + range = xQueueGapRange(settings.pacing, settings.social?.x); } catch { - gapSeconds = queueGapFor(undefined, "twitter").seconds; + /* the defaults */ } - return { run, candidates, jar: xRunJar(report), gapSeconds, maxPosts: X_RUN_MAX_POSTS }; + return { run, candidates, jar: xRunJar(report), gapSeconds: range.minSeconds, gapMaxSeconds: range.maxSeconds, maxPosts: X_RUN_MAX_POSTS }; } diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts @@ -142,7 +142,14 @@ function settingsCanBeRead(): boolean { // 60 minutes) — an age that cannot be read, or is negative (a clock set // back), refuses — and never when settings cannot be read. export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> { - const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now, ...(deps.counts === false ? { counts: false } : {}) }); + // A watch's job is a read or a library's capture: a browse job of X's sitting. + const report = await (deps.report ?? xSessionReport)({ + paths, + channelSlug: slug, + now, + sittingKind: "browse", + ...(deps.counts === false ? { counts: false } : {}), + }); if (!report.hasProfile) { return { reason: "no-profile", @@ -180,6 +187,13 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps if (deps.counts !== false && !report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) { return { reason: "cooldown", sentence: report.reason ?? "X's job cap is reached." }; } + // X'S SITTING (lib/xSitting.ts) used up or of the other kind, X cooling down + // after a 429, or the account marked suspended: the tick is skipped and the + // watch waits — the sitting's ends at the next Refresh, the cooldown's at + // its time. Not the jar's fault. + if (!report.allowed && (report.refusedBy === "sitting" || report.refusedBy === "cooldown" || report.refusedBy === "suspended")) { + return { reason: "cooldown", sentence: report.reason ?? "X is held." }; + } // Whatever else the guard would refuse a person's job for. if (!report.allowed) return { reason: "jar", sentence: report.reason ?? "X's cookie jar is past its limit." }; const held = await (deps.held ?? xTrendingHeld)(paths, now); diff --git a/common/jobs/downloadBackoff.ts b/common/jobs/downloadBackoff.ts @@ -42,6 +42,9 @@ import { settlePlatformClean, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; +import { applyXStop, clearXStopEntry, X_STOP_MS, X_STOP_PLATFORM } from "./platformBackoff"; +import { currentJobContext } from "../lib/jobContext"; +import { readFile } from "node:fs/promises"; // Milliseconds remaining in the platform's current cooldown window, or 0 if it // is not cooling down. Prefers the live shared object; else reads the file. @@ -106,6 +109,12 @@ export async function recordDownloadBackoff( failureClass: "rate_limit" | "network" = "rate_limit", pacing: PacingSettings | undefined = pacingSettings(), ): Promise<void> { + // X's rate limit (yt-dlp on an X address, any caller): the X stop, never + // the generic backoff (review 1 F1). + if (platform === X_STOP_PLATFORM && failureClass === "rate_limit") { + await recordXStop("a rate limit (yt-dlp)", paths); + return; + } await mutateDownloadState(paths, (state) => { const now = Date.now(); prunePlatformPacing(state.download, now); @@ -129,6 +138,8 @@ export async function recordPlatformCooldown( paths: Paths = getPaths(), now: number = Date.now(), ): Promise<number> { + // X's is the X stop, whatever length was asked for. + if (platform === X_STOP_PLATFORM) return recordXStop("a rate limit", paths, now); return mutateDownloadState(paths, (state) => { prunePlatformPacing(state.download, now); const prev = state.download.platformBackoff[platform]; @@ -269,3 +280,73 @@ export async function clearPlatformHold( return `Cleared by hand for ${platform}: ${parts.join(", ")}. The next failure starts from the bottom of the backoff.\n`; }); } + +// THE X STOP, RECORDED (lane x-sittings, review 1 F1/F2): every reader that +// meets X's rate limit or a bot check calls this, AT ONCE (not when its run +// ends). The guard then refuses every X job until it ends +// (jobs/networkGuard.ts); the job that met it is told through its context and +// ends DEFERRED, saying so (jobs/streamCommand.ts). `why` names the answer +// ("a rate limit (gallery-dl)"). Answers when the stop ends (ms). +export async function recordXStop(why: string, paths: Paths = getPaths(), now: number = Date.now()): Promise<number> { + // The job is told FIRST (review 2 G5): a write that fails still stops it. + const job = currentJobContext(); + if (job && (!job.xStop || job.xStop.until < now + X_STOP_MS)) job.xStop = { until: now + X_STOP_MS, why, at: now }; + const until = await mutateDownloadState(paths, (state) => { + prunePlatformPacing(state.download, now); + return applyXStop(state.download, now).until; + }); + if (job) { + if (job.xStop && job.xStop.until < until) job.xStop = { ...job.xStop, until }; + job.onLog(`X answered ${why}: X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes); this job stops here.`); + } + return until; +} + +// What is left of the X stop (ms), READ STRICTLY (review 1 F7): a state file +// that is there and cannot be parsed throws — the guard then refuses — where +// the lane's own reader takes it as empty. +export async function xStopRemainingMs(paths: Paths = getPaths(), now: number = Date.now()): Promise<number> { + const live = await liveAutoQueueState(paths); + let entry = live?.download.platformBackoff[X_STOP_PLATFORM]; + let text: string | null = null; + try { + text = await readFile(paths.autoQueueStateFile, "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err; + } + if (text !== null) { + const raw = JSON.parse(text) as { download?: { platformBackoff?: Record<string, { until?: unknown }> } }; + const onDisk = raw?.download?.platformBackoff?.[X_STOP_PLATFORM]?.until; + if (typeof onDisk === "number" && Number.isFinite(onDisk) && (!entry || onDisk > entry.until)) { + entry = { until: onDisk, fails: entry?.fails ?? 0 }; + } + } + return entry && entry.until > now ? entry.until - now : 0; +} + +// "CLEAR THE X STOP" (review 2 G4): the operator's named, logged act — the +// only way X's 15-minute stop ends before its time. Without `confirm` it +// removes nothing and answers what it would risk. Each clear is logged in +// `<jobsDir>/x-stop-cleared.jsonl` ({at, until, why, by, note?}). +export const X_STOP_CLEAR_RISK = + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for after it " + + "answered a rate limit or a bot check — asking again then is what gets an account limited or locked."; + +export async function clearXStop( + paths: Paths, + opts: { confirm: boolean; by: string; note?: string; now?: number }, +): Promise<{ ok: true; cleared: { until: number } | null; message: string } | { ok: false; confirmNeeded: true; message: string }> { + const now = opts.now ?? Date.now(); + if (!opts.confirm) return { ok: false, confirmNeeded: true, message: `${X_STOP_CLEAR_RISK} Confirm to clear it.` }; + const removed = await mutateDownloadState(paths, (state) => clearXStopEntry(state.download, now)); + if (!removed) return { ok: true, cleared: null, message: "No X stop was running; nothing was cleared." }; + const { appendFile, mkdir } = await import("node:fs/promises"); + const line = { at: new Date(now).toISOString(), until: new Date(removed.until).toISOString(), by: opts.by, ...(opts.note ? { note: opts.note } : {}) }; + await mkdir(paths.jobsDir, { recursive: true }); + await appendFile(`${paths.jobsDir}/x-stop-cleared.jsonl`, `${JSON.stringify(line)}\n`); + return { + ok: true, + cleared: { until: removed.until }, + message: `The X stop (until ${line.until.slice(11, 16)} UTC) was cleared by ${opts.by}; X jobs may start now. Logged in .jobs/x-stop-cleared.jsonl.`, + }; +} diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -50,6 +50,8 @@ export type JobMeta = { // can be rebuilt from the records (jobs/xJobCap.ts). Absent on metas from // before it. xStarts?: number[]; + // The X sittings those starts were counted in (JobRecord.xSittings). + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // The job ended deferred by X's job cap (JobRecord.deferred). deferred?: { until: number; sentence: string }; }; @@ -83,6 +85,7 @@ export async function writeJobMeta( ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), ...(record.queueKey === X_QUEUE_KEY ? { xStarts: [...(record.xStarts ?? [])] } : {}), + ...(record.xSittings?.length ? { xSittings: record.xSittings.map((x) => ({ ...x })) } : {}), ...(record.deferred ? { deferred: { ...record.deferred } } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); @@ -116,6 +119,18 @@ export async function readJobMeta( if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; if (m.xStarts !== undefined && !(Array.isArray(m.xStarts) && m.xStarts.every((t) => typeof t === "number" && Number.isFinite(t)))) delete meta.xStarts; + if ( + m.xSittings !== undefined && + !( + Array.isArray(m.xSittings) && + m.xSittings.every((x) => { + const r = x as { began?: unknown; kind?: unknown; at?: unknown } | null; + return !!r && (r.began === null || typeof r.began === "string") && (r.kind === "timelines" || r.kind === "browse") && typeof r.at === "number" && Number.isFinite(r.at); + }) + ) + ) { + delete meta.xSittings; + } const d = m.deferred as { until?: unknown; sentence?: unknown } | undefined; if (d !== undefined && !(d && typeof d === "object" && typeof d.until === "number" && typeof d.sentence === "string")) delete meta.deferred; if ( diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -19,6 +19,14 @@ // the "browser" source the age cannot be read: the job logs that and // proceeds. // +// 4. X IN SITTINGS (lane x-sittings, lib/xSitting.ts, jobs/xSitting.ts): a +// cookie refresh admits at most `social.x.sittingJobs` X job starts (4; +// 1-6 in the code), of ONE kind (timelines or browse, fixed by the +// first); X cooling down after a 429 refuses every X job; and an +// account the operator marked suspended refuses the jobs that record +// posts as deleted (social/xAccountState.ts). All in xSessionReport, the +// one computation behind the refusal and `get x-session`. +// // Operator, 2026-10-23: "only start X downloads with a recent cookie refresh", // "be very careful not to do that thing on any sort of site", "This should be // enforced in Archilyzer, not just an AI standing rule". @@ -50,6 +58,17 @@ import { jobKindLabel, kindIsNetwork } from "./jobKinds"; import { xJobAsksX, xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { recordXJobStart, xJobCapStatus } from "./xJobCap"; +import { recordXSittingStart, xSittingLook } from "./xSitting"; +import { + xSittingJobs, + xSittingKindOf, + xSuspendedRefuses, + xSuspendedSentence, + type XSittingKind, +} from "../lib/xSitting"; +import { readXAccountState, xAccountAlertLine } from "../social/xAccountState"; +import { heldPlatformRefusal, xStopRemainingMs } from "./downloadBackoff"; +import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import { writeJobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; import { getRegistry } from "./registry"; @@ -214,6 +233,8 @@ export function xJarVerdict(input: { // server sets 0, so its fake X fetches need no jar); a limit a spec writes into // settings.json still applies. Unset everywhere but the e2e test server. function e2eDefaultMaxAge(): number | undefined { + // Only on the test server (review 1 F6: jobs/queueGap.ts e2eHooksOn). + if (process.env.E2E_TEST_ROUTES !== "1") return undefined; const raw = process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; if (raw === undefined || raw === "") return undefined; const n = Number(raw); @@ -245,8 +266,8 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting // `capped`: the refusal is the job cap's (no cookie banner is raised for it), // with `nextAt`, when the next X job may start. export type XGuardResult = - | { ok: true; note?: string } - | { ok: false; message: string; alert: boolean; capped?: true; nextAt?: number }; + | { ok: true; note?: string; accountAlert?: string } + | { ok: false; message: string; alert: boolean; refusedBy?: XSessionReport["refusedBy"]; capped?: true; nextAt?: number }; // WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and // its verdict in one record, for `pnpm ops get x-session` (an agent asks it @@ -277,9 +298,32 @@ export type XSessionReport = { // cookie spec or channel (review 2 M1) — the caps (constants of the code), // and, when the cap is reached, when the next may start. cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true }; - // Would an X job start now? `reason` is the refusal it would get. + // X'S SITTING (lib/xSitting.ts, jobs/xSitting.ts): when it began (the + // jar's refresh; null: none on record), its kind (null: no job yet; + // "unknown": its record was lost), the starts it admitted and has left, + // and the limit (social.x.sittingJobs, 1-6). `unreadable`: the file cannot + // be read and no X job starts. + sitting: { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + left: number; + limit: number; + // The kind of the job asked about, when one was. + asked?: XSittingKind; + unreadable?: true; + }; + // THE ACCOUNT'S STATE as the operator marked it (social/xAccountState.ts): + // "suspended" refuses the jobs that record deleted posts; `alert` is the + // line /cookies shows. + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X cooling down after a rate limit (429: 15 minutes), when it is: until when. + cooldown: { until: string } | null; + // Would an X job start now? `reason` is the refusal it would get, and + // `refusedBy` which rule gave it. allowed: boolean; reason: string | null; + refusedBy?: "alert" | "jar" | "cap" | "sitting" | "cooldown" | "suspended"; note?: string; }; @@ -288,9 +332,15 @@ export async function xSessionReport(opts: { channelSlug?: string; now?: number; // False: the job asked about does not count against X's job cap (ruling - // R-a: xJobCounts), so the cap does not refuse it. The count is reported - // all the same. + // R-a: xJobCounts), so the cap does not refuse it — nor does its sitting. + // The counts are reported all the same. counts?: boolean; + // The job asked about: its sitting kind (absent: only a used-up sitting + // refuses), and whether it records posts as deleted or unavailable (a + // suspended account refuses it). + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XSessionReport> { const now = opts.now ?? Date.now(); const status = await readXSessionStatus(opts.paths); @@ -316,10 +366,74 @@ export async function xSessionReport(opts: { ...(capStatus.nextAt !== undefined ? { nextAt: new Date(capStatus.nextAt).toISOString() } : {}), ...(capStatus.unreadable ? { unreadable: true as const } : {}), }; - // The cap refuses whatever else would let the job through. - const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T => - r.allowed && !capStatus.ok && opts.counts !== false ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r; + // X'S SITTING: the jar's refresh begins it; the limit is the setting, + // bounded 1-6 in the code. + const limit = xSittingJobs(settings?.social?.x); + const refreshedAt = status.cookiesUpdatedAt ?? null; + const sittingOff = e2eSittingsOff(); + const look = await xSittingLook(opts.paths, { refreshedAt, kind: opts.sittingKind ?? "timelines", limit }); + const sitting: XSessionReport["sitting"] = { + began: look.status.state.began, + kind: look.status.state.kind, + used: look.status.used, + left: look.status.left, + limit, + ...(opts.sittingKind ? { asked: opts.sittingKind } : {}), + ...(!look.status.readable ? { unreadable: true as const } : {}), + }; + // Without a kind asked, only a used-up (or unreadable) sitting refuses. + const sittingRefusal = + sittingOff || opts.counts === false || look.verdict.ok + ? null + : opts.sittingKind || look.verdict.why === "used-up" || !look.status.readable + ? look.verdict.sentence + : null; + // The account's state, as marked. + const acct = await readXAccountState(opts.paths); + const account: XSessionReport["account"] = acct + ? { + state: acct.state, + since: acct.at, + ...(acct.note ? { note: acct.note } : {}), + ...(acct.state === "suspended" ? { alert: xAccountAlertLine(acct) } : {}), + } + : { state: "ok" }; + const suspendedRefusal = + acct?.state === "suspended" && opts.recordsAvailability === true + ? xSuspendedSentence(opts.what ?? "This job", acct.at, acct.note) + : null; + // X'S COOLDOWN AFTER A 429 (15 minutes) and its hold refuse EVERY X job, + // whatever its kind (rule 6 of lane x-sittings: it used to be asked only by + // the trending read, its media and the capture). + const wallNow = opts.now ?? Date.now(); + // READ STRICTLY (review 1 F7): a stop that cannot be read refuses. + let coolingMs = 0; + let held: string | null = null; + let unreadableStop: string | null = null; + try { + coolingMs = await xStopRemainingMs(opts.paths, wallNow); + held = await heldPlatformRefusal("twitter", opts.what ?? "This X job", opts.paths, wallNow); + } catch (err) { + unreadableStop = + `X's rate-limit stop cannot be read (${opts.paths.autoQueueStateFile}: ${(err as Error).message}): no X job starts ` + + "while it cannot be told whether X answered a rate limit in the last 15 minutes. Repair or remove the file, then ask again."; + } + const cooldown = coolingMs > 0 ? { until: new Date(wallNow + coolingMs).toISOString() } : null; + const coolRefusal = unreadableStop ?? held ?? (coolingMs > 0 ? xRateLimitHoldSentence("X job", coolingMs, wallNow) : null); + // The cap, the sitting, the cooldown and the account refuse whatever else + // would let the job through. + const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T & { refusedBy?: XSessionReport["refusedBy"] } => { + if (!r.allowed) return r; + if (coolRefusal) return { ...r, allowed: false, reason: coolRefusal, refusedBy: "cooldown" }; + if (suspendedRefusal) return { ...r, allowed: false, reason: suspendedRefusal, refusedBy: "suspended" }; + if (!capStatus.ok && opts.counts !== false) return { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached.", refusedBy: "cap" }; + if (sittingRefusal) return { ...r, allowed: false, reason: sittingRefusal, refusedBy: "sitting" }; + return r; + }; const base = { + sitting, + account, + cooldown, cap, source: resolved.source, sourceChosen: resolved.chosen, @@ -345,6 +459,7 @@ export async function xSessionReport(opts: { ...base, alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line }, allowed: false, + refusedBy: "alert", reason: `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, @@ -355,24 +470,55 @@ export async function xSessionReport(opts: { const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) - : { ...base, alert: null, allowed: false, reason: verdict.message }; + : { ...base, alert: null, allowed: false, reason: verdict.message, refusedBy: "jar" }; +} + +// TEST-ONLY: E2E_X_SITTINGS=off on the e2e test server (with +// E2E_TEST_ROUTES=1, as it always runs) leaves its fake X jobs out of the +// sitting rule — they run many to a test corpus with no jar refresh between. +// Unset everywhere but the e2e test server; it does not touch X's job cap. +function e2eSittingsOff(): boolean { + return process.env.E2E_X_SITTINGS === "off" && process.env.E2E_TEST_ROUTES === "1"; } // Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count), // or null: for the scheduler, which then skips X's channels rather than // queue syncs that would each be refused. -export async function xCapHeldReason(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<string | null> { +export async function xCapHeldReason(paths: Paths, now?: number): Promise<string | null> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); - return status.ok ? null : (status.sentence ?? "X's job cap is reached."); + if (!status.ok) return status.sentence ?? "X's job cap is reached."; + // X's sitting, used up (or unreadable), holds them the same way. + const sitting = await xSittingHeld(paths); + return sitting?.sentence ?? null; +} + +// X's sitting as the scheduler reads it: what it has left, and its refusal +// when it has none (a look: nothing counted). +async function xSittingHeld(paths: Paths): Promise<{ left: number; sentence?: string } | null> { + if (e2eSittingsOff()) return null; + try { + const status = await readXSessionStatus(paths); + const limit = xSittingJobs(settingsNow()?.social?.x); + const look = await xSittingLook(paths, { refreshedAt: status.cookiesUpdatedAt ?? null, kind: "timelines", limit }); + // The scheduler queues syncs (timelines jobs): a browse sitting, or one + // used up or unreadable, has no room for them. + if (look.verdict.ok) return { left: look.status.left }; + return { left: 0, sentence: look.verdict.sentence }; + } catch { + return null; + } } // HOW MANY X JOBS MAY START NOW under X's job cap (0 when it is reached or // its count cannot be read): for the scheduler, which queues no more X syncs // than that (review 3 N9). A look: nothing is counted. -export async function xCapRoom(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<number> { +export async function xCapRoom(paths: Paths, now?: number): Promise<number> { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); if (!status.ok) return 0; - return Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + const cap = Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); + // No more than X's sitting has left, either. + const sitting = await xSittingHeld(paths); + return sitting ? Math.min(cap, sitting.left) : cap; } export async function xJobGuard(opts: { @@ -380,15 +526,25 @@ export async function xJobGuard(opts: { channelSlug?: string; now?: number; counts?: boolean; + sittingKind?: XSittingKind; + recordsAvailability?: boolean; + what?: string; }): Promise<XGuardResult> { const r = await xSessionReport(opts); - if (r.allowed) return { ok: true, ...(r.note ? { note: r.note } : {}) }; - const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason); - const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : undefined; + if (r.allowed) { + return { + ok: true, + ...(r.note ? { note: r.note } : {}), + ...(r.account.state === "suspended" ? { accountAlert: r.account.alert ?? "The X account is marked suspended." } : {}), + }; + } + const capped = r.refusedBy === "cap"; + const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : r.refusedBy === "cooldown" && r.cooldown ? Date.parse(r.cooldown.until) : undefined; return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, + ...(r.refusedBy ? { refusedBy: r.refusedBy } : {}), ...(capped ? { capped: true as const } : {}), ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}), }; @@ -397,13 +553,22 @@ export async function xJobGuard(opts: { // THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its // spec's params, and whether its channel is a trending library (read here, // never taken from the caller). -async function xJobPlanOf(opts: NetworkJobOpts): Promise<XJobPlan> { +type XGuardPlan = XJobPlan & { channel?: XJobPlan["channel"] & { search?: boolean } }; + +async function xJobPlanOf(opts: NetworkJobOpts): Promise<XGuardPlan> { const params = planParams(opts); - let channel: XJobPlan["channel"]; + let channel: XGuardPlan["channel"]; if (opts.channelSlug) { const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null); const config = read?.ok ? channelConfigSchema.parse(read.value) : null; - if (config) channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) }; + if (config) { + channel = { + library: isXTrendingChannel(config), + ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}), + // An X search channel: its fetch is the search walk (browse). + ...(config.xSearch ? { search: true } : {}), + }; + } } return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) }; } @@ -428,14 +593,30 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that // does not count is not refused by the cap either; everything else of X's // guard holds for it. - const counts = xJobCounts(await xJobPlanOf(opts)); - const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts }); + const plan = await xJobPlanOf(opts); + const counts = xJobCounts(plan); + // ITS SITTING KIND (lib/xSitting.ts): from its plan — its kind and its + // channel's config — never from a flag. An X run's own start (no channel) + // is no job of either kind: each channel is guarded with its slug. + const runStart = opts.kind === "x-run" && !opts.channelSlug; + const sittingKind = runStart ? undefined : xSittingKindOf(plan); + const what = `${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`; + const x = await xJobGuard({ + paths: opts.paths, + channelSlug: opts.channelSlug, + counts, + ...(sittingKind ? { sittingKind } : {}), + recordsAvailability: xSuspendedRefuses(plan), + what, + }); if (x.ok) { + const notes: string[] = x.note ? [x.note] : []; // THE START, COUNTED: checked and recorded in one step. An X run's own // start asks X nothing: each of its channels is a start (it is guarded, // with its slug, before each one). - if (counts && opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) { - const counted = await recordXJobStart(opts.paths, queueGapClock().now()); + if (counts && opts.countStart && opts.job && !runStart) { + const at = queueGapClock().now(); + const counted = await recordXJobStart(opts.paths, at); if (!counted.ok) { return { ok: false, @@ -443,23 +624,54 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}), }; } - // The start on the job's own record (and its sidecar), so a lost count - // is rebuilt from the records (jobs/xJobCap.ts). + // THE SITTING, COUNTED (lib/xSitting.ts): checked and recorded in one + // step under its own lock. Refused here only on a race (the look above + // passed): the cap's start stays counted — more rather than fewer. const record = getRegistry().get(opts.job.id); + let sat: { began: string | null; kind: XSittingKind } | null = null; + if (sittingKind && !e2eSittingsOff()) { + const refreshedAt = (await readXSessionStatus(opts.paths)).cookiesUpdatedAt ?? null; + const r = await recordXSittingStart(opts.paths, { + refreshedAt, + kind: sittingKind, + limit: xSittingJobs(settingsNow()?.social?.x), + jobKind: opts.kind, + at: counted.at ?? at, + jobId: opts.job.id, + ...(opts.channelSlug ? { channel: opts.channelSlug } : {}), + }); + if (!r.verdict.ok) { + if (record && counted.at !== undefined) { + (record.xStarts ??= []).push(counted.at); + await writeJobMeta(opts.paths, record); + } + return { ok: false, error: r.verdict.sentence, deferUntil: 0 }; + } + sat = { began: r.began, kind: sittingKind }; + notes.push( + `X sitting: ${r.verdict.used} of ${r.verdict.limit} started (${sittingKind}, ` + + `${r.began ? `since the refresh at ${r.began.slice(11, 16)} UTC` : "no refresh on record"}); ${r.verdict.left} left.`, + ); + } + // The start on the job's own record (and its sidecar), so a lost count + // — and a lost sitting — is rebuilt from the records. if (record && counted.at !== undefined) { (record.xStarts ??= []).push(counted.at); + if (sat) (record.xSittings ??= []).push({ ...sat, at: counted.at }); await writeJobMeta(opts.paths, record); } } + // A suspended account (marked by hand): every X job's log says so. + if (x.accountAlert) notes.push(`${x.accountAlert} What X answers it may be thinned.`); // The jar passed at a job's START: a jar-age banner from an earlier // refusal clears. (Not at enqueue — the start follows, and enqueue stays // as cheap as it was.) if (opts.job) await noteXJarFresh(opts.paths); - return { ok: true, notes: x.note ? [x.note] : [] }; + return { ok: true, notes }; } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); - } else if (!x.alert && !x.capped) { + } else if (!x.alert && x.refusedBy === "jar") { // The fresh-jar rule refused it: X's cookie banner says so on the // dashboard (kind jar-age), and a job refused at its start is offered for // "Re-run stopped jobs" once the jar is fresh. @@ -469,7 +681,11 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}), }); } - return { ok: false, error: x.message, ...(x.capped && x.nextAt !== undefined ? { deferUntil: x.nextAt } : {}) }; + // A cap, a cooldown or a sitting met AT A START ends the job deferred, not + // failed: nothing retries it (a sitting's until 0: until a Refresh). + const deferUntil = + (x.refusedBy === "cap" || x.refusedBy === "cooldown") && x.nextAt !== undefined ? x.nextAt : x.refusedBy === "sitting" ? 0 : undefined; + return { ok: false, error: x.message, ...(deferUntil !== undefined ? { deferUntil } : {}) }; } // Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -34,6 +34,11 @@ await writeFile( `#!/usr/bin/env node import { appendFileSync } from "node:fs"; appendFileSync(process.env.FAKE_RUNS, process.argv.slice(2).join(" ") + "\\n"); +if (process.env.FAKE_MODE === "ratelimit") { + // X's API answered 429: gallery-dl, told ratelimit=abort, stops at once. + process.stderr.write("[twitter][error] Rate limit exceeded\\n"); + process.exit(1); +} if (process.env.FAKE_MODE === "challenge") { // X answers after a moment, as it does: the loop has queued all 13 by then // (on a loaded machine an instant answer raced the loop's later enqueues). @@ -83,6 +88,7 @@ const { fetchPosts } = await import("../controller/fetchPosts"); const { getSettings } = await import("../lib/settings"); const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); await import("../social/xGalleryDlFetcher"); @@ -126,11 +132,24 @@ async function reset(): Promise<void> { clearQueueGaps(); await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); - await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + // X's queue gap: a known end long ago (a lost file is answered from the + // job records — review 1 F7 — whose clock is the wall's, not this test's). + await mkdir(paths.jobsDir, { recursive: true }); + await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); // X's job count (jobs/xJobCap.ts): each test starts from none. (Deleting // the file would not: it is rebuilt from the earlier tests' job records.) await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + // X's stop after a 429 or a bot check (jobs/downloadBackoff.ts): none. + { + const { readAutoQueueState, writeAutoQueueState } = await import("./autoQueueState"); + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + st.download.platformHolds = {}; + await writeAutoQueueState(paths, st); + } + // X's sitting (jobs/xSitting.ts): each test starts a fresh one. + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: null, kind: null, starts: [] })); } async function readLog(jobId: string): Promise<string> { @@ -152,7 +171,9 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); assert.deepEqual( ends.map((e) => e?.status), - ["failed", ...Array(12).fill("failed")], + // Job 1 met X's bot check: it records the X stop and ends deferred + // (review 1 F1/F2); jobs 2–13 are refused by the alert. + ["done", ...Array(12).fill("failed")], ); // gallery-dl ran ONCE: only job 1 asked X. assert.equal(await runCount(), 1); @@ -160,6 +181,7 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert const first = await readLog(ends[0]!.jobId); assert.match(first, /Cloudflare challenge/); assert.match(first, /challenge or a login wall/); + assert.match(first, /^\[deferred\] X answered a bot check \(gallery-dl\) at \d\d:\d\d UTC/m); const second = await readLog(ends[1]!.jobId); assert.match(second, /X answered with a challenge at \d\d:\d\d UTC .*its cookie alert is up, so no X job starts/); const state = await readServiceCookieState(paths); @@ -177,7 +199,7 @@ test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert } }); -test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter (300 s) apart", async () => { +test("13 X fetches queued in one loop: the sitting's 4 start 5-12 min apart (drawn), the other 9 end deferred unasked", async () => { await reset(); await writeJar(5 * 60_000); const starts = new Map<string, number>(); @@ -189,15 +211,21 @@ test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter } const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); assert.deepEqual(ends.map((e) => e?.status), Array(13).fill("done")); - assert.equal(await runCount(), 13); - const at = SLUGS.map((s) => starts.get(s)!); + // Only the sitting's four asked anything (lib/xSitting.ts: 4 per cookie refresh). + assert.equal(await runCount(), 4); + assert.deepEqual([...starts.keys()], SLUGS.slice(0, 4)); + for (const e of ends.slice(4)) { + assert.match(await readLog(e!.jobId), /\[deferred\] This X sitting is used up: 4 of 4 X jobs started/); + } + const at = SLUGS.slice(0, 4).map((s) => starts.get(s)!); for (let i = 1; i < at.length; i++) { - assert.ok(at[i] - at[i - 1] >= 300_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); + // The gap runs from the previous job's end (3 s after its start) and is drawn in 5-12 min. + const gap = at[i] - at[i - 1] - 3_000; + assert.ok(gap >= 300_000 && gap <= 720_000, `job ${i + 1} started ${gap / 1000}s after job ${i} ended`); } - // The waiting job's log says why it waited. + // The waiting job's log says why it waited, and what was drawn. const log2 = await readLog(ends[1]!.jobId); - // 5 min at least, stretched by up to pacing.jitter (lib/jitter.mjs). - assert.match(log2, /waiting [56]m\d\ds: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); + assert.match(log2, /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); // The end survives a restart: the file names the queue. const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(typeof file.ends["platform:twitter"], "number"); @@ -387,21 +415,21 @@ test("R2a: a job that asks X is refused on any queue but X's — at enqueue for assert.equal(await runCount(), before, "gallery-dl was never started"); }); -test("R2b: X's job cap — the 13th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { +test("R2b: X's job cap — the 7th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { await reset(); await writeJar(5 * 60_000); const before = await runCount(); - // Eleven starts on record, of whatever kinds; then one fetch through the funnel is the twelfth. - for (let i = 0; i < 11; i++) await recordXJobStart(paths, fakeNow); - const twelfth = await fetchJob(SLUGS[0], new Map()); - assert.equal(twelfth.ok, true, twelfth.ok ? "" : twelfth.error); - if (twelfth.ok) assert.equal((await twelfth.done).status, "done"); - assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); - // The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. + // Five starts on record, of whatever kinds; then one fetch through the funnel is the sixth. + for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); + const sixth = await fetchJob(SLUGS[0], new Map()); + assert.equal(sixth.ok, true, sixth.ok ? "" : sixth.error); + if (sixth.ok) assert.equal((await sixth.done).status, "done"); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); + // The seventh, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) { const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); assert.equal(res.ok, false, kind); - assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); + assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes \(the cap is 6\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); } assert.equal(await runCount(), before + 1); // The cap raises no cookie banner: it is not the jar's fault. @@ -409,7 +437,7 @@ test("R2b: X's job cap — the 13th X job in an hour is refused before it starts // get x-session: the count, the caps, and the refusal. const report = await xReport({ paths }); assert.equal(report.allowed, false); - assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true, nextAt: "string" }); + assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 6, perHour: 6, lastDay: 6, perDay: 150, reached: true, nextAt: "string" }); assert.match(report.reason ?? "", /^X's job cap is reached/); // An hour on, the oldest starts have left the window and X jobs start again. fakeNow += 61 * 60_000; @@ -441,11 +469,11 @@ test("R2b: the start is counted once, by the last guard before the work; a look assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); assert.equal(await count(), 2); // The cap fills while a job waits its turn: its start is refused, and the refused start is not counted. - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await guardNetworkJob({ ...opts, job, countStart: true }); assert.equal(late.ok, false); assert.match(late.ok ? "" : late.error, /^X's job cap is reached/); - assert.equal(await count(), 12); + assert.equal(await count(), 6); // A count that cannot be read refuses every X job, at enqueue and at the start. await writeFile(path.join(transcripts, ".x-session", "job-starts.json"), "{broken"); for (const g of [await guardNetworkJob(opts), await guardNetworkJob({ ...opts, job, countStart: true })]) { @@ -476,43 +504,46 @@ test("M1: ONE count for the machine — a flipped login source, a respelled cook await writeJar(5 * 60_000); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true }); + // One sitting of six (the most there is), so the cap is what fills here. + const SIX = { sittingJobs: 6 }; try { - // Three starts on the connected profile. - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 3); + await writeSettings({ cookieSource: "profile", ...SIX }); + // Two starts on the connected profile. + for (let i = 0; i < 2; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 2); // The login source flipped to the browser: the same count, not a fresh one. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }); - assert.equal((await xReport({ paths })).cap.lastHour, 3); - for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); - assert.equal(await count(), 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }); + assert.equal((await xReport({ paths })).cap.lastHour, 2); + assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); + assert.equal(await count(), 3); // The same browser spelled another way: still the same count. - await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: " firefox:default " }); - assert.equal((await xReport({ paths })).cap.lastHour, 6); + await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: " firefox:default " }); + assert.equal((await xReport({ paths })).cap.lastHour, 3); assert.equal((await start("capture-posts", SLUGS[1])).ok, true); // A channel with a cookie spec of its own: the same count. await channelSpec(SLUGS[2], "chromium"); - assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 7); + assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 4); assert.equal((await start("check-post-availability", SLUGS[2])).ok, true); - // An X run over channels of different specs: each channel one start, in the one count. + // An X run over a channel of another spec: each channel one start, in the one count. await channelSpec(SLUGS[3], "brave"); await channelSpec(SLUGS[4], "chromium:Profile 2"); - for (const slug of [SLUGS[3], SLUGS[4], SLUGS[5], SLUGS[6]]) assert.equal((await start("x-run", slug)).ok, true); - assert.equal(await count(), 12); - // The thirteenth is refused whatever it uses. + assert.equal((await start("x-run", SLUGS[3])).ok, true); + assert.equal(await count(), 6); + // The seventh is refused whatever it uses. for (const [x, top, slug] of [ - [{ cookieSource: "profile" }, {}, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], - [{ cookieSource: "browser" }, { cookiesFromBrowser: "safari" }, SLUGS[3]], + [{ cookieSource: "profile", ...SIX }, {}, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], + [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "safari" }, SLUGS[4]], ] as const) { await writeSettings(x, top); const refused = await start("fetch-posts", slug); assert.equal(refused.ok, false); - assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); } // get x-session names no login: the count is the machine's. const report = await xReport({ paths }); assert.equal("login" in report, false); - assert.deepEqual([report.cap.lastHour, report.cap.reached], [12, true]); + assert.deepEqual([report.cap.lastHour, report.cap.reached], [6, true]); } finally { await writeSettings({ cookieSource: "profile" }); for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined); @@ -520,7 +551,7 @@ test("M1: ONE count for the machine — a flipped login source, a respelled cook } }); -test("R-a: a trending library's media-only capture is not counted and not refused by the cap; its keep capture and a capture with shots are", async () => { +test("review 1 F8 (R-a reversed): a trending library's media-only capture IS an X job — counted, and refused by the cap like any other", async () => { await reset(); await writeJar(5 * 60_000); const lib = "x-trending-lib"; @@ -534,26 +565,14 @@ test("R-a: a trending library's media-only capture is not counted and not refuse guardNetworkJob({ kind: "capture-posts", queueKey: "platform:twitter", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params }, job: { id: "ra" }, ...(countStart ? { countStart: true } : {}) }); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; assert.equal((await capture(mediaOnly)).ok, true); - assert.equal(await count(), 0, "the media-only capture is not a start"); - assert.equal((await capture({ ...mediaOnly, keptMedia: true })).ok, true); - assert.equal((await capture({ ...mediaOnly, shots: true })).ok, true); - assert.equal(await count(), 2, "the keep capture and the capture with shots are"); - // The cap reached: the media-only capture still starts (it asks x.com nothing); the others are refused. - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); - assert.equal((await capture(mediaOnly, false)).ok, true); - assert.equal((await capture(mediaOnly)).ok, true); - for (const params of [{ ...mediaOnly, keptMedia: true }, { ...mediaOnly, shots: true }, { ...mediaOnly, articles: undefined }]) { + assert.equal(await count(), 1, "the media-only capture is a start"); + // The cap reached: it is refused like the others. + for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); + for (const params of [mediaOnly, { ...mediaOnly, shots: true }]) { const refused = await capture(params, false); assert.equal(refused.ok, false); assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached/); } - // It still meets the rest of X's guard: the queue, and the jar. - const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "manual", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params: mediaOnly } }); - assert.equal(moved.ok, false); - await writeJar(5 * 60 * 60_000); - const stale = await capture(mediaOnly, false); - assert.equal(stale.ok, false); - assert.doesNotMatch(stale.ok ? "" : stale.error, /job cap/); await rm(path.join(transcripts, "channels", lib), { recursive: true, force: true }); await reset(); }); @@ -568,8 +587,8 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate }); assert.equal(blocker.ok, true); for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20)); - // Ten more: eleven. The next passes its enqueue (a slot is left)… - for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow); + // Four more: five. The next passes its enqueue (a slot is left)… + for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await fetchJob(SLUGS[1], new Map()); assert.equal(late.ok, true, late.ok ? "" : late.error); // …and the cap fills while it waits behind the first. @@ -581,7 +600,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.equal(end.status, "done"); const record = getRegistry().get(late.jobId)!; assert.ok(record.deferred, "the record says it was deferred"); - assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt); assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m); assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m); @@ -589,7 +608,7 @@ test("R-b: a job that meets the cap AT ITS START ends deferred — done, not fai assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]); // Nothing was asked, no start was counted, and no cookie banner was raised. assert.equal(await runCount(), before); - assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12); + assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); // The first job's own record carries its start (the count can be rebuilt from it). assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1); @@ -690,3 +709,39 @@ test("review 3 M2/S5: a window job is X's by its URLs on any channel; a URL-less } await reset(); }); + +test("rule 6 / review 1 F2: on X's rate limit gallery-dl STOPS (abort); the stop is recorded the moment it is seen; the job ends deferred; every X job of any kind is then refused", async () => { + await reset(); + await writeJar(5 * 60_000); + process.env.FAKE_MODE = "ratelimit"; + let jobId = ""; + try { + const res = await fetchJob(SLUGS[0], new Map()); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (!res.ok) return; + jobId = res.jobId; + assert.equal((await res.done).status, "done"); + } finally { + delete process.env.FAKE_MODE; + } + const log = await readLog(jobId); + // Recorded at once: the stop line comes before the run's summary. + const stopAt = log.indexOf("X answered a rate limit (gallery-dl): X is left alone until"); + assert.ok(stopAt >= 0, log); + assert.ok(stopAt < log.indexOf("gallery-dl read "), "the stop is recorded when the line is seen, before the run ends"); + assert.match(log, /^\[deferred\] X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read/m); + const record = getRegistry().get(jobId)!; + assert.ok(record.deferred && record.deferred.until > Date.now() + 14 * 60_000); + // gallery-dl was told to abort on a rate limit, to read at most 300 posts, and not to write the jar back. + const argv = (await readFile(RUNS, "utf8")).trim().split("\n").at(-1) ?? ""; + assert.match(argv, /extractor\.twitter\.ratelimit=abort/); + assert.doesNotMatch(argv, /ratelimit=wait/); + assert.match(argv, /--post-range 1-300/); + assert.match(argv, /--cookies \S+cookies\.txt -o cookies-update=false/); + for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[2]], ["check-post-availability", SLUGS[3]], ["read-x-trending", undefined]] as const) { + const r = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); + assert.equal(r.ok, false, kind); + assert.match(r.ok ? "" : r.error, /^X answered a rate limit \(429\) a short while ago: no X job starts before/, kind); + } + await reset(); +}); diff --git a/common/jobs/platformBackoff.ts b/common/jobs/platformBackoff.ts @@ -12,6 +12,7 @@ import { jitterUp } from "../lib/jitter.mjs"; import { pacingJitter } from "../lib/jitter"; +import { X_RATE_LIMIT_HOLD_MS } from "../lib/xJobRule"; export type PlatformBackoffEntry = { // Epoch ms: downloads for this platform are paused until this instant. @@ -68,6 +69,22 @@ export function mergeBackoffEntry( return { until: Math.max(a.until, b.until), fails: Math.max(a.fails, b.fails) }; } +// THE X STOP (lane x-sittings, review 1 F1): ONE rule for every answer from +// X that is a rate limit or a bot check, whoever met it — gallery-dl, yt-dlp, +// the profile's pages, the CDN. X is left alone for X_RATE_LIMIT_HOLD_MS (15 +// minutes) from `now`; `until` only ever moves later. Never X's exponential +// backoff (60 s first), never a hold. Pure: the live runner's state and the +// file (jobs/downloadBackoff.ts recordXStop) are both changed through it. +export const X_STOP_PLATFORM = "twitter"; +export const X_STOP_MS = X_RATE_LIMIT_HOLD_MS; + +export function applyXStop(state: { platformBackoff: PlatformBackoffState }, now: number): PlatformBackoffEntry { + const prev = state.platformBackoff[X_STOP_PLATFORM]; + const next = mergeBackoffEntry(prev, { until: now + X_STOP_MS, fails: (prev?.fails ?? 0) + 1 }); + state.platformBackoff[X_STOP_PLATFORM] = next; + return next; +} + // True when the platform is currently in a cooldown window. export function isCoolingDown( state: PlatformBackoffState, @@ -78,14 +95,27 @@ export function isCoolingDown( return entry !== undefined && entry.until > now; } -// Clear a platform's backoff (called on a successful download). Mutates in place. +// Clear a platform's backoff (called on a successful download, and by Clear +// hold). Mutates in place. NEVER X'S STOP BEFORE ITS TIME (review 2 G4): a +// clean answer from any reader, or Clear hold, leaves an X stop that has not +// ended; only clearXStopEntry — the operator's "Clear the X stop" — removes it. export function clearBackoff( state: PlatformBackoffState, platform: string, + now: number = Date.now(), ): void { + if (platform === X_STOP_PLATFORM && (state[platform]?.until ?? 0) > now) return; delete state[platform]; } +// THE OPERATOR'S "CLEAR THE X STOP" (review 2 G4): the one removal of X's stop +// before its time. Answers what was removed (null: no stop was running). +export function clearXStopEntry(state: { platformBackoff: PlatformBackoffState }, now: number): PlatformBackoffEntry | null { + const entry = state.platformBackoff[X_STOP_PLATFORM]; + delete state.platformBackoff[X_STOP_PLATFORM]; + return entry && entry.until > now ? entry : null; +} + // Drop entries whose cooldown lapsed long enough ago that keeping their `fails` // count for escalation memory no longer matters. Mutates in place, keeping the // map bounded across a long-running server. We retain a lapsed entry for one @@ -434,7 +464,7 @@ export function settlePlatformClean( ): CleanEffect { const pacing = opts.pacing ?? PACING_DEFAULTS; const releasedHold = isPlatformHeld(state.platformHolds, platform); - clearBackoff(state.platformBackoff, platform); + clearBackoff(state.platformBackoff, platform, opts.now ?? Date.now()); delete state.platformHolds[platform]; const pace = state.platformPace[platform]; let decayed = false; diff --git a/common/jobs/queueGap.test.ts b/common/jobs/queueGap.test.ts @@ -18,6 +18,7 @@ import { queueGapWait, waitForQueueGap, waitText, + setXGapRandom, } from "./queueGap"; import { jobGapSecondsFor, sanitizePacing } from "../lib/settingsSchema"; @@ -49,13 +50,18 @@ test("the gap: the operator's per platform, else the built-in per platform, else assert.deepEqual(sanitizePacing({ jobGapSeconds: { twitter: 10 ** 9 } }).jobGapSeconds, { twitter: 86400 }); }); -test("E2E_JOB_GAP_SECONDS replaces the built-ins only; a set value still applies", () => { +test("E2E_JOB_GAP_SECONDS replaces the built-ins only, and only on the test server (E2E_TEST_ROUTES=1); a set value still applies", () => { process.env.E2E_JOB_GAP_SECONDS = "0"; try { + // An editor started normally ignores it (review 1 F6). + delete process.env.E2E_TEST_ROUTES; + assert.equal(queueGapFor(undefined, "twitter").seconds, 300); + process.env.E2E_TEST_ROUTES = "1"; assert.equal(queueGapFor(undefined, "twitter").seconds, 0); assert.equal(queueGapFor({ jobGapSeconds: { twitter: 3 } }, "twitter").seconds, 3); } finally { delete process.env.E2E_JOB_GAP_SECONDS; + delete process.env.E2E_TEST_ROUTES; } }); @@ -76,13 +82,23 @@ test("no end yet: no wait; an end: wait out the rest; the end is persisted and r delete process.env.E2E_JOB_GAP_SECONDS; const paths = await jobsDir(); const q = "platform:twitter"; - // jitter 0: the exact gap (the jittered one has its own test below). + // X's gap is drawn from a range, never one value (jobs/xSittings.test.ts): + // a 5-5 setting is widened to 5-8 min, and a seeded draw makes it exact here. const exact = { jobGapSeconds: {}, jitter: 0 }; - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 }), null); - await noteQueueJobEnd(paths, q, 1_000_000); - const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000 }); - assert.equal(w?.remainingMs, 252_000); - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_300_000 }), null); + const xGap = { gapMinMinutes: 5, gapMaxMinutes: 5 }; + setXGapRandom(0); + try { + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000, xGap }), null); + await noteQueueJobEnd(paths, q, 1_000_000); + const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000, xGap }); + assert.ok(w && w.drawn); + assert.deepEqual(w!.drawn!.range, { minSeconds: 300, maxSeconds: 480 }); + assert.equal(w!.remainingMs, w!.drawn!.seconds * 1000 - 48_000); + assert.match(queueGapLine(w!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-8 min\): X jobs are spaced 5-8 min apart, drawn per job/); + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 + 480_001, xGap }), null); + } finally { + setXGapRandom(null); + } const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(file.ends[q], 1_000_000); clearQueueGaps(); // the restart diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -15,6 +15,14 @@ // end: a job refused at its start (a stale X jar, a raised alert) asked // nothing, so the next one is not made to wait for it. // +// X'S GAP IS DRAWN, NOT FIXED (lane x-sittings, lib/xSitting.ts): a job on +// `platform:twitter` waits a gap drawn per job, uniform in +// `social.x.gapMinMinutes`-`gapMaxMinutes` (default 5-12 min, never below 5; +// an explicit `pacing.jobGapSeconds.twitter` above the minimum raises it), and +// says what was drawn ("waiting 8m41s (a 9m02s gap drawn from 5-12 min): …"). +// 12 fetches each 5-6 minutes after the last preceded the account's +// suspension; a fixed beat is what a script looks like. +// // The last end per queue is kept in memory and in `<jobsDir>/queue-gaps.json`, // so an editor restart is not a free pass (the scheduler's first tick after a // boot would otherwise ask X at once). @@ -25,6 +33,7 @@ // (sleepBetweenDownloadsSeconds + pace) and this one. import path from "node:path"; +import { readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { spanText, waitText } from "./queueGapText"; @@ -32,6 +41,9 @@ import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; import type { PacingSettingsBlock } from "../lib/settingsSchema"; import { jitterUpStable } from "../lib/jitter.mjs"; import { pacingJitter } from "../lib/jitter"; +import { randomInt } from "node:crypto"; +import { drawXGapSeconds, xGapRange, xGapRangeText, type XGapRange } from "../lib/xSitting"; +import { getSettings } from "../lib/settings"; export { spanText, waitText }; @@ -51,7 +63,15 @@ export function queueGapPlatform(queueKey: string): string | null { // sets 0, so its specs do not wait five minutes between two fake X fetches). // A gap a spec writes into settings.json still applies. Unset everywhere but // the e2e test server. +// THE TEST SERVER'S GATE (review 1 F6): every E2E_ hook here is honoured only +// beside E2E_TEST_ROUTES=1, as the e2e server always runs — never in an +// editor started normally, whatever else its environment carries. +export function e2eHooksOn(): boolean { + return process.env.E2E_TEST_ROUTES === "1"; +} + function builtInGaps(): Readonly<Record<string, number>> { + if (!e2eHooksOn()) return JOB_GAP_DEFAULT_SECONDS; const raw = process.env.E2E_JOB_GAP_SECONDS; if (raw === undefined || raw === "") return JOB_GAP_DEFAULT_SECONDS; const n = Number(raw); @@ -61,6 +81,86 @@ function builtInGaps(): Readonly<Record<string, number>> { export type QueueGap = { seconds: number; key: string }; +// TEST-ONLY, as above: the e2e server's E2E_JOB_GAP_SECONDS, which collapses +// X's drawn range to that one value too (0: no gap), else undefined. +function e2eGapSeconds(): number | undefined { + if (!e2eHooksOn()) return undefined; + const raw = process.env.E2E_JOB_GAP_SECONDS; + if (raw === undefined || raw === "") return undefined; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined; +} + +// ── X's gap: drawn per job (lane x-sittings, lib/xSitting.ts) ────────────── + +export type XGapSettings = { gapMinMinutes?: number; gapMaxMinutes?: number }; + +// The range X's gap is drawn from: `social.x.gapMinMinutes`-`gapMaxMinutes` +// (default 5-12 min, never below 5), an explicit pacing.jobGapSeconds.twitter +// raising the minimum. The e2e server's E2E_JOB_GAP_SECONDS collapses it. +export function xQueueGapRange( + pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, + x: XGapSettings | undefined, +): XGapRange { + const e2e = e2eGapSeconds(); + if (e2e !== undefined) return { minSeconds: e2e, maxSeconds: e2e }; + return xGapRange(x, pacing?.jobGapSeconds?.twitter); +} + +// THE DRAW: uniform in the range, from the system's random source — or, in a +// test, a seeded one (setXGapRandom). Drawn ONCE per wait: a wait is re-read +// after every sleep, and a fresh draw per read would end it at the shortest. +declare global { + // eslint-disable-next-line no-var + var __yttXGapRandom__: (() => number) | undefined; + // eslint-disable-next-line no-var + var __yttXGapDraws__: Map<string, number> | undefined; +} + +// TEST-ONLY: a seeded generator (mulberry32) for the draw; null restores the +// system's random source. +export function setXGapRandom(seed: number | null): void { + if (seed === null) { + globalThis.__yttXGapRandom__ = undefined; + return; + } + let a = seed >>> 0; + globalThis.__yttXGapRandom__ = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function xGapRandom(): number { + return globalThis.__yttXGapRandom__ ? globalThis.__yttXGapRandom__() : randomInt(0, 2 ** 32) / 2 ** 32; +} + +// The gap drawn for the wait after the end at `last` on `queueKey` (memoised: +// the same wait, re-read, keeps its draw; a range changed while it waits is +// drawn again, within the new range). +export function drawnXGapSeconds(queueKey: string, last: number, range: XGapRange): number { + const draws = (globalThis.__yttXGapDraws__ ??= new Map()); + const key = `${queueKey}@${last}@${range.minSeconds}-${range.maxSeconds}`; + let seconds = draws.get(key); + if (seconds === undefined) { + seconds = drawXGapSeconds(range, xGapRandom()); + if (draws.size > 256) draws.clear(); + draws.set(key, seconds); + } + return seconds; +} + +function xGapSettingsNow(): XGapSettings | undefined { + try { + return getSettings().social?.x; + } catch { + return undefined; + } +} + export function queueGapFor( pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, platform: string, @@ -169,6 +269,7 @@ export function noteQueueJobEnd( export function clearQueueGaps(): void { globalThis.__yttQueueGaps__?.clear(); + globalThis.__yttXGapDraws__?.clear(); } // ── the wait ─────────────────────────────────────────────────────────────── @@ -185,6 +286,8 @@ export type QueueGapWait = { until: number; remainingMs: number; reason: string; + // X's gap: the seconds drawn for this wait, and the range drawn from. + drawn?: { seconds: number; range: XGapRange }; }; // How long a network job on `queueKey` must still wait, or null for none. @@ -199,9 +302,31 @@ export async function queueGapWait(opts: { queueKey: string; pacing: (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; now: number; + // X's range settings (`social.x`); absent: read from settings. + xGap?: XGapSettings; }): Promise<QueueGapWait | null> { const platform = queueGapPlatform(opts.queueKey); if (!platform) return null; + // X'S GAP IS DRAWN PER JOB from its range (lane x-sittings), not stretched + // from a fixed beat: the draw is the unevenness, so no jitter is added. + if (platform === "twitter") { + const range = xQueueGapRange(opts.pacing, opts.xGap ?? xGapSettingsNow()); + if (range.maxSeconds <= 0) return null; + // NO END ON RECORD IS NOT "NO X JOB EVER RAN" (review 1 F7): a lost + // queue-gaps.json is answered from the job records — the latest start or + // end of a job on X's queue. Only a corpus with none waits nothing. + const last = (await lastQueueEnd(opts.paths, opts.queueKey)) ?? (await lastXJobFromRecords(opts.paths, opts.queueKey)); + if (last === undefined) return null; + const seconds = drawnXGapSeconds(opts.queueKey, last, range); + const until = last + seconds * 1000; + if (until <= opts.now) return null; + return { + until, + remainingMs: until - opts.now, + reason: `X jobs are spaced ${xGapRangeText(range)} apart, drawn per job (social.x.gapMinMinutes, social.x.gapMaxMinutes)`, + drawn: { seconds, range }, + }; + } const gap = queueGapFor(opts.pacing, platform); if (gap.seconds <= 0) return null; const last = await lastQueueEnd(opts.paths, opts.queueKey); @@ -221,7 +346,11 @@ export async function queueGapWait(opts: { // The line a waiting job's log carries: // "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +// X's: "waiting 8m41s (a 9m02s gap drawn from 5-12 min): X jobs are spaced …". export function queueGapLine(w: QueueGapWait): string { + if (w.drawn) { + return `waiting ${waitText(w.remainingMs)} (a ${waitText(w.drawn.seconds * 1000)} gap drawn from ${xGapRangeText(w.drawn.range)}): ${w.reason}`; + } return `waiting ${waitText(w.remainingMs)}: ${w.reason}`; } @@ -296,3 +425,25 @@ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { signal?.addEventListener("abort", onAbort, { once: true }); }); } + +// The latest start or end of an ENDED job on `queueKey` in the job records, if any. +async function lastXJobFromRecords(paths: Pick<Paths, "jobsDir">, queueKey: string): Promise<number | undefined> { + let names: string[]; + try { + names = await readdir(paths.jobsDir); + } catch { + return undefined; + } + let latest: number | undefined; + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + const read = await readJsonFile(path.join(paths.jobsDir, name)); + const m = read.ok ? (read.value as Record<string, unknown> | null) : null; + // An ended job's (not the one now starting, which is running). + if (!m || m.queueKey !== queueKey || m.status === "running" || m.status === "queued") continue; + for (const t of [m.startedAt, m.endedAt]) { + if (typeof t === "number" && Number.isFinite(t) && (latest === undefined || t > latest)) latest = t; + } + } + return latest; +} diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -185,12 +185,18 @@ export type JobRecord = { // counted for (one for a job; one per channel for an X run). Kept on its // sidecar, so a count file that is lost is rebuilt from the records. xStarts?: number[]; + // The X sittings those starts were counted in (jobs/xSitting.ts): each + // start's sitting (the jar's refresh time; null: none on record) and kind, + // so a lost sitting file is rebuilt from the records. + xSittings?: Array<{ began: string | null; kind: "timelines" | "browse"; at: number }>; // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached // when its queue started it, so it did not run — not a failure. It ends // `done` with this: the sentence, and when the next X job may start. // Nothing re-queues it by itself. ALSO (lane clean-unverified): a checked // Clean audio the source rate-limited — it deleted nothing it could not // verify and queued its own retry for `until` (controller/cleanAudioJob.ts). + // AND (lane x-sittings): an X job its sitting refused (used up, or of the + // other kind, jobs/xSitting.ts): `until` is 0 — until a person's Refresh. deferred?: { until: number; sentence: string }; }; diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -25,6 +25,8 @@ import type { JobSpec } from "./jobSpec"; import { kindIsNetwork, kindNeedsMedia, kindNeedsText } from "./jobKinds"; import { guardNetworkJob } from "./networkGuard"; import { noteQueueJobEnd, queueGapClock, waitForQueueGap } from "./queueGap"; +import { X_CLIPS_QUEUE_KEY, X_QUEUE_KEY } from "../lib/xJobRule"; +import { readXAccountState } from "../social/xAccountState"; import { getSettings } from "../lib/settings"; import { assertChannelMediaReachable, @@ -531,6 +533,11 @@ export async function runManagedFunction( queueKey: opts.queueKey, onLog, staleServices: new Set<string>(), + // An X job (on X's queues): its account mark, read at each write + // (review 1 F5; lib/jobContext.ts xAnswersUntrusted). + ...(opts.queueKey === X_QUEUE_KEY || opts.queueKey === X_CLIPS_QUEUE_KEY + ? { xSuspended: async () => (await readXAccountState(opts.paths))?.state === "suspended" } + : {}), }; // A NETWORK JOB (jobs/jobKinds.ts `network`) is guarded again at its // start — an X job queued behind a challenge is refused here, not run — @@ -583,6 +590,24 @@ export async function runManagedFunction( const noteEnd = () => { if (reachedWork) void noteQueueJobEnd(opts.paths, opts.queueKey, queueGapClock().now()); }; + // X'S STOP MET BY THIS JOB (jobs/downloadBackoff.ts recordXStop, review + // 1 F2): it stopped where X answered a rate limit or a bot check, kept + // what it read, and ends DEFERRED — not done, not failed — saying when X + // may be asked again. Nothing re-queues it. + const endedByXStop = (): boolean => { + const stop = jobCtx.xStop; + if (!stop) return false; + const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); + record.deferred = { + until: stop.until, + sentence: + `X answered ${stop.why} at ${hhmm(stop.at)} UTC: this job stopped there and kept what it read; ` + + `no X job starts before ${hhmm(stop.until)} UTC, and a later sitting continues it.`, + }; + onLog(`[deferred] ${record.deferred.sentence}`); + registry.finalize(id, "done"); + return true; + }; run() .then(() => { noteEnd(); @@ -590,6 +615,7 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + if (endedByXStop()) return; registry.finalize(id, "done"); }) .catch((err) => { @@ -598,6 +624,10 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + if (!(err instanceof JobDeferredError) && endedByXStop()) { + onLog(`(it ended with: ${(err as Error).message})`); + return; + } // X'S JOB CAP, MET AT THE START (review 2, ruling R-b): the job did // not run and did not fail. It ends `done`, DEFERRED, with the // sentence and when the next X job may start; nothing re-queues it. diff --git a/common/jobs/unitOutcome.ts b/common/jobs/unitOutcome.ts @@ -54,6 +54,8 @@ import { pruneDeferred, pruneSubtitleDeferrals, settlePlatformClean, + applyXStop, + X_STOP_PLATFORM, } from "./platformBackoff"; import { staticSleepRequestsSeconds } from "../ytdlp/platformArgs.mjs"; @@ -114,6 +116,16 @@ export function applyUnitOutcome( line: `Auto-download: ${unit.videoId} from its stored media URL failed (${unit.failureClass ?? "unknown"}); ${pf} is not touched.`, }; } + // X's rate limit: the X stop (15 minutes), never the generic backoff + // (review 1 F1; jobs/platformBackoff.ts applyXStop). + if (pf === X_STOP_PLATFORM && unit.failureClass === "rate_limit") { + const entry = applyXStop(state, now); + deferVideo(state.videoDeferrals, unit.videoId, unit.channelSlug, now); + return { + markCompleted: false, + line: `Auto-download: X answered a rate limit — X is left alone until ${new Date(entry.until).toISOString().slice(11, 16)} UTC (15 minutes); ${unit.videoId} deferred 6h.`, + }; + } if ( pf !== null && (unit.failureClass === "rate_limit" || unit.failureClass === "network") diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts @@ -37,17 +37,17 @@ const keptSince = (paths: ReturnType<typeof corpus>, since: number) => { test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { const paths = corpus("disk"); - for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); - const refused = await recordXJobStart(paths, T0 + 12 * MIN); + for (let i = 0; i < 6; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); + const refused = await recordXJobStart(paths, T0 + 6 * MIN); assert.equal(refused.ok, false); - assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/); + assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); // A refused start records nothing; the file is one list, with no login in it. assert.deepEqual(Object.keys(fileOf(paths)).sort(), ["starts", "version"]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); // "Restart": nothing is in memory; the file is the count. const again = await xJobCapStatus(paths, T0 + 13 * MIN); - assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); + assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 6, 6, T0 + 60 * MIN]); // A start recorded with the clock set back is recorded at the clock's time // (review 3 S4); the later start on record still counts, and is kept. const p2 = corpus("disk-back"); @@ -59,24 +59,24 @@ test("M1: ONE count for the machine — checked and recorded in one step, kept a assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); // Two at once: both recorded, neither lost. const p3 = corpus("disk-race"); - await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, T0 + i))); - assert.equal(fileOf(p3).starts.length, 12); + await Promise.all(Array.from({ length: 6 }, (_, i) => recordXJobStart(p3, T0 + i))); + assert.equal(fileOf(p3).starts.length, 6); assert.equal((await recordXJobStart(p3, T0 + 20)).ok, false); }); test("M1: a count of the first shape (one list per login key) is the SUM of its lists, and is rewritten as one", async () => { const paths = corpus("migrate"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); - // 7 starts under the profile, 5 under a browser spec: the same machine's twelve. + // 4 starts under the profile, 2 under a browser spec: the same machine's six. const logins = { - profile: Array.from({ length: 7 }, (_, i) => T0 + i * MIN), - "browser:firefox": Array.from({ length: 5 }, (_, i) => T0 + (10 + i) * MIN), + profile: Array.from({ length: 4 }, (_, i) => T0 + i * MIN), + "browser:firefox": Array.from({ length: 2 }, (_, i) => T0 + (10 + i) * MIN), }; writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 1, logins })); const status = await xJobCapStatus(paths, T0 + 20 * MIN); - assert.deepEqual([status.ok, status.lastHour], [false, 12]); + assert.deepEqual([status.ok, status.lastHour], [false, 6]); assert.equal(fileOf(paths).version, 2); - assert.equal(fileOf(paths).starts.length, 12); + assert.equal(fileOf(paths).starts.length, 6); assert.equal((await recordXJobStart(paths, T0 + 21 * MIN)).ok, false); }); @@ -102,7 +102,7 @@ test("a count that cannot be read fails closed: no X job starts, and nothing is test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { const paths = corpus("fresh"); - assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 12, perDay: 150 }); + assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 6, perDay: 150 }); // Records of other queues only: still zero. const p2 = corpus("fresh-other-queues"); meta(p2, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); @@ -200,15 +200,15 @@ test("review 3 S4: a start in the future counts in both windows and never prunes const paths = corpus("future"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). - const real = Array.from({ length: 10 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 4 }, (_, i) => T0 + i * MIN); writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); const status = await xJobCapStatus(paths, T0 + 10 * MIN); - assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 11, 11]); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 5, 5]); const r = await recordXJobStart(paths, T0 + 10 * MIN); - assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 12]); + assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 6]); // The real starts are kept beside the future one. assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); - assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds twelve"); + assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds six"); }); test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts @@ -73,6 +73,13 @@ async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { return { state: "bad" }; } +// The counted starts on disk, for X's sitting rebuild (jobs/xSitting.ts): +// null when the file is absent or cannot be read. A look: nothing written. +export async function readXJobStarts(paths: CapPaths): Promise<number[] | null> { + const file = await readStartsFile(paths); + return file.state === "ok" ? file.starts : null; +} + // ── the records are kept (review 3 M3) ───────────────────────────────────── // RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT diff --git a/common/jobs/xSitting.ts b/common/jobs/xSitting.ts @@ -0,0 +1,252 @@ +// X'S SITTING, ON DISK (lane x-sittings; the rule and its numbers are +// lib/xSitting.ts). `<transcripts>/.x-session/sitting.json`: +// { "version": 1, "began": <iso> | null, "kind": "timelines" | "browse" | "unknown" | null, +// "starts": [{ "at": <ms>, "jobKind": "fetch-posts", "kind": "timelines", "jobId"?, "channel"? }, …] } +// +// - read and written under its lock (one check-and-record at a time), and +// it survives a restart; +// - A NEW SITTING BEGINS ONLY AT A LATER REFRESH: when the jar's refresh +// time (social/xSessionBroker.ts readXSessionStatus: the broker's own +// stamp, written by Connect and Refresh) is later than `began`. Nothing +// else resets it — not a restart, not a jar restored from a backup, not a +// clock set back; +// - it FAILS CLOSED: a file that is there and cannot be read or parsed +// refuses every counted X job until it is repaired; +// - A FILE THAT IS NOT THERE IS NOT A FRESH SITTING: it is rebuilt from what +// else counted the same starts — X's job count (jobs/xJobCap.ts: its +// starts since `began`) and the job records (`xSittings`: each start's +// sitting and kind). A sitting with starts and no recorded kind is +// "unknown", and refuses both kinds until the next Refresh. +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { + isLaterRefresh, + xSittingVerdict, + type XSittingKind, + type XSittingState, + type XSittingVerdict, +} from "../lib/xSitting"; +import { readXJobStarts } from "./xJobCap"; + +type SittingPaths = Pick<Paths, "transcriptsDir" | "jobsDir">; + +export function xSittingFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "sitting.json"); +} + +export type XSittingStart = { at: number; jobKind: string; kind: XSittingKind; jobId?: string; channel?: string }; + +type SittingFile = { + version: 1; + began: string | null; + kind: XSittingKind | "unknown" | null; + starts: XSittingStart[]; +}; + +const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); +const isKind = (v: unknown): v is XSittingKind => v === "timelines" || v === "browse"; + +function parseStart(v: unknown): XSittingStart | null { + const r = v as Record<string, unknown> | null; + if (!r || typeof r !== "object" || !finite(r.at) || typeof r.jobKind !== "string" || !isKind(r.kind)) return null; + return { + at: r.at, + jobKind: r.jobKind, + kind: r.kind, + ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}), + ...(typeof r.channel === "string" ? { channel: r.channel } : {}), + }; +} + +async function readSittingFile(paths: SittingPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; file: SittingFile }> { + const read = await readJsonFile(xSittingFile(paths)); + if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" }; + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || v.version !== 1) return { state: "bad" }; + if (!(v.began === null || (typeof v.began === "string" && Number.isFinite(Date.parse(v.began))))) return { state: "bad" }; + if (!(v.kind === null || v.kind === "unknown" || isKind(v.kind))) return { state: "bad" }; + if (!Array.isArray(v.starts)) return { state: "bad" }; + const starts: XSittingStart[] = []; + for (const raw of v.starts) { + const s = parseStart(raw); + if (!s) return { state: "bad" }; + starts.push(s); + } + return { state: "ok", file: { version: 1, began: v.began as string | null, kind: v.kind as SittingFile["kind"], starts } }; +} + +async function writeSittingFile(paths: SittingPaths, file: SittingFile): Promise<void> { + await writeJsonAtomic(xSittingFile(paths), file, { mkdir: true }); +} + +function stateOf(file: SittingFile): XSittingState { + const first = file.starts[0]; + return { + began: file.began, + kind: file.kind, + used: file.starts.length, + ...(first ? { first: { jobKind: first.jobKind, at: first.at } } : {}), + }; +} + +// ── the rebuild ──────────────────────────────────────────────────────────── + +// The sitting that began at `began`, from the job records and X's job count. +// The larger of the two counts is taken (more rather than fewer); the kind is +// the records' (the first start's), else "unknown" when anything started. +export async function rebuildXSitting(paths: SittingPaths, began: string | null): Promise<SittingFile> { + const since = began === null ? -Infinity : Date.parse(began); + const recorded: XSittingStart[] = []; + let names: string[] = []; + try { + names = await readdir(paths.jobsDir); + } catch { + names = []; + } + for (const name of names) { + if (!name.endsWith(".meta.json")) continue; + let m: Record<string, unknown> | null = null; + try { + const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown; + m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null; + } catch { + m = null; + } + if (!m || !Array.isArray(m.xSittings)) continue; + for (const raw of m.xSittings) { + const r = raw as { began?: unknown; kind?: unknown; at?: unknown } | null; + if (!r || !isKind(r.kind) || !finite(r.at) || (r.began ?? null) !== began) continue; + recorded.push({ + at: r.at, + jobKind: typeof m.kind === "string" ? m.kind : "?", + kind: r.kind, + ...(typeof m.id === "string" ? { jobId: m.id } : {}), + ...(typeof m.channelSlug === "string" ? { channel: m.channelSlug } : {}), + }); + } + } + recorded.sort((a, b) => a.at - b.at); + // X's job count holds every counted start of the last day: those since the + // refresh are this sitting's whether or not a record says so. + const capStarts = ((await readXJobStarts(paths)) ?? []).filter((t) => t >= since); + const starts = [...recorded]; + for (let i = recorded.length; i < capStarts.length; i++) { + // A start with no record of its kind: counted, of no known kind. + starts.push({ at: capStarts[i], jobKind: "?", kind: recorded[0]?.kind ?? "timelines" }); + } + const kind: SittingFile["kind"] = recorded[0]?.kind ?? (starts.length > 0 ? "unknown" : null); + return { version: 1, began, kind, starts }; +} + +// The sitting in force for a jar refreshed at `refreshedAt`, HOLDING THE +// LOCK: the one on disk, a new one when the jar was refreshed since, or the +// rebuilt one; written when it changed. `bad`: the file cannot be read. +async function loadLocked(paths: SittingPaths, refreshedAt: string | null): Promise<{ ok: true; file: SittingFile } | { ok: false }> { + const read = await readSittingFile(paths); + if (read.state === "bad") return { ok: false }; + if (read.state === "ok") { + if (isLaterRefresh(refreshedAt, read.file.began)) { + const fresh: SittingFile = { version: 1, began: refreshedAt, kind: null, starts: [] }; + await writeSittingFile(paths, fresh); + return { ok: true, file: fresh }; + } + return { ok: true, file: read.file }; + } + const rebuilt = await rebuildXSitting(paths, refreshedAt); + await writeSittingFile(paths, rebuilt); + return { ok: true, file: rebuilt }; +} + +export function xSittingUnreadableSentence(file: string): string { + return ( + `X's sitting cannot be read (${file}): no X job starts while it is unreadable, because the jobs a cookie refresh ` + + "admits are counted there. Repair the file (JSON: {version: 1, began, kind, starts: []}) or delete it (it is then " + + "counted again from the job records), then ask again." + ); +} + +export type XSittingStatus = { + // The file could be read (or rebuilt). + readable: boolean; + state: XSittingState; + limit: number; + used: number; + left: number; + // The refusal, when the file cannot be read. + sentence?: string; +}; + +function statusOf(file: SittingFile, limit: number): XSittingStatus { + const state = stateOf(file); + return { readable: true, state, limit, used: state.used, left: Math.max(0, limit - state.used) }; +} + +function closed(paths: SittingPaths, limit: number, began: string | null): XSittingStatus { + return { + readable: false, + state: { began, kind: "unknown", used: limit }, + limit, + used: limit, + left: 0, + sentence: xSittingUnreadableSentence(xSittingFile(paths)), + }; +} + +// The sitting as it stands for a jar refreshed at `refreshedAt` (a look: +// nothing is counted; a new sitting or a rebuild is written, under the lock). +export async function xSittingStatus(paths: SittingPaths, refreshedAt: string | null, limit: number): Promise<XSittingStatus> { + const read = await readSittingFile(paths); + if (read.state === "bad") return closed(paths, limit, refreshedAt); + if (read.state === "ok" && !isLaterRefresh(refreshedAt, read.file.began)) return statusOf(read.file, limit); + const loaded = await withJsonFileLock(xSittingFile(paths), () => loadLocked(paths, refreshedAt)); + return loaded.ok ? statusOf(loaded.file, limit) : closed(paths, limit, refreshedAt); +} + +// Would a job of `kind` start in the sitting now? (A look.) +export async function xSittingLook( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number }, +): Promise<{ status: XSittingStatus; verdict: XSittingVerdict }> { + const status = await xSittingStatus(paths, opts.refreshedAt, opts.limit); + if (!status.readable) { + return { status, verdict: { ok: false, why: "unknown", used: status.used, left: 0, limit: opts.limit, sentence: status.sentence ?? "" } }; + } + return { status, verdict: xSittingVerdict(status.state, opts.kind, opts.limit) }; +} + +// ONE X JOB STARTS IN THE SITTING: checked and recorded in one step, under +// the file's lock. A refusal records nothing. The first start fixes the +// sitting's kind. +export async function recordXSittingStart( + paths: SittingPaths, + opts: { refreshedAt: string | null; kind: XSittingKind; limit: number; jobKind: string; at: number; jobId?: string; channel?: string }, +): Promise<{ verdict: XSittingVerdict; began: string | null }> { + return withJsonFileLock(xSittingFile(paths), async () => { + const loaded = await loadLocked(paths, opts.refreshedAt); + if (!loaded.ok) { + return { + began: opts.refreshedAt, + verdict: { ok: false, why: "unknown", used: opts.limit, left: 0, limit: opts.limit, sentence: xSittingUnreadableSentence(xSittingFile(paths)) }, + }; + } + const file = loaded.file; + const before = xSittingVerdict(stateOf(file), opts.kind, opts.limit); + if (!before.ok) return { verdict: before, began: file.began }; + const start: XSittingStart = { + at: opts.at, + jobKind: opts.jobKind, + kind: opts.kind, + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(opts.channel ? { channel: opts.channel } : {}), + }; + const next: SittingFile = { ...file, kind: file.kind ?? opts.kind, starts: [...file.starts, start] }; + await writeSittingFile(paths, next); + const used = next.starts.length; + return { began: file.began, verdict: { ok: true, used, left: Math.max(0, opts.limit - used), limit: opts.limit } }; + }); +} diff --git a/common/jobs/xSittings.test.ts b/common/jobs/xSittings.test.ts @@ -0,0 +1,681 @@ +// X IN SMALL, UNEVEN SITTINGS (lane x-sittings; lib/xSitting.ts, jobs/xSitting.ts): +// the sitting's count over every kind of X job, through the real job funnel +// (runManagedFunction → the network guard), across an "editor restart", and +// reset by nothing but a later cookie refresh; the one-kind rule; the drawn +// gap; the account marked suspended; the 429 cooldown over every X kind. +// Temp dirs only; no job here asks anything of any site (each job's work is a +// stub that only records that it ran). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xSittings.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-sittings-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +delete process.env.E2E_JOB_GAP_SECONDS; +delete process.env.E2E_X_SITTINGS; +delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; +delete process.env.E2E_TEST_ROUTES; +// A fake gallery-dl (it asks nothing of anyone): FAKE_GDL=ratelimit prints the +// line gallery-dl prints when it aborts at X's rate limit, and exits 1. +const FAKE_GDL = path.join(ROOT, "fake-gallery-dl.mjs"); +await writeFile( + FAKE_GDL, + `#!/usr/bin/env node +if (process.env.FAKE_GDL === "ratelimit") { process.stderr.write("[twitter][error] Rate limit exceeded\\n"); process.exit(1); } +process.exit(0); +`, +); +const { chmod } = await import("node:fs/promises"); +await chmod(FAKE_GDL, 0o755); +process.env.GALLERY_DL_BIN = FAKE_GDL; + +async function writeSettings(x: Record<string, unknown> = {}): Promise<void> { + await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ social: { x: { cookieSource: "profile", ...x } } })); +} +await writeSettings(); + +const transcripts = path.join(ROOT, "transcripts"); +async function channel(slug: string, extra: Record<string, unknown> = {}): Promise<void> { + const dir = path.join(transcripts, "channels", slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", platform: "twitter", name: slug, socialHandle: slug.replace(/-/g, ""), url: `https://x.com/${slug.replace(/-/g, "")}`, ...extra }), + ); +} +const ACCOUNTS = ["acct-one", "acct-two", "acct-three", "acct-four", "acct-five", "acct-six", "acct-seven"]; +for (const s of ACCOUNTS) await channel(s); +await channel("demo-library", { xTrending: {}, url: undefined, postFetcher: undefined }); +await channel("demo-search", { xSearch: { query: "kettles" } }); + +const SESSION = path.join(transcripts, ".x-session"); +const JAR = path.join(SESSION, "cookies.txt"); +// A jar written `ageMs` ago, as an old jar is: its mtime is its time (no +// broker stamp). `refresh` also writes the broker's stamp, as a Refresh does. +async function writeJar(ageMs: number, opts: { refresh?: boolean } = {}): Promise<string> { + await mkdir(path.join(SESSION, "profile"), { recursive: true }); + await writeFile(JAR, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n"); + const t = new Date(Date.now() - ageMs); + await utimes(JAR, t, t); + if (opts.refresh) await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: t.toISOString() })); + return t.toISOString(); +} + +const { getPaths } = await import("../lib/paths"); +const { runManagedFunction } = await import("./streamCommand"); +const { setQueueGapClock, clearQueueGaps, noteQueueJobEnd, queueGapWait, queueGapLine, setXGapRandom, xQueueGapRange } = await import("./queueGap"); +const { xJobStartsFile } = await import("./xJobCap"); +const { xSittingFile } = await import("./xSitting"); +const { xSessionReport, guardNetworkJob, xCapRoom, xCapHeldReason } = await import("./networkGuard"); +const { recordPlatformCooldown } = await import("./downloadBackoff"); +const { writeAutoQueueState, readAutoQueueState } = await import("./autoQueueState"); +const { writeXAccountState, xAccountStateFile, keepVerdictsTrustedWhileSuspended } = await import("../social/xAccountState"); +const { readXSessionStatus } = await import("../social/xSessionBroker"); +const { getRegistry } = await import("./registry"); +const { parseXSittingJobs, xSittingJobs, X_SITTING_MAX_JOBS, drawXGapSeconds, xGapRange } = await import("../lib/xSitting"); +const { sanitizeSocial } = await import("../social/xCookieSource"); + +const paths = getPaths(); + +let fakeNow = Date.now(); +setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; } }); + +async function reset(): Promise<void> { + clearQueueGaps(); + // X's queue gap: a known end long ago (a lost file is answered from the + // job records — review 1 F7 — whose clock is the wall's, not this test's). + await mkdir(paths.jobsDir, { recursive: true }); + await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); + await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + await rm(xSittingFile(paths), { force: true }); + await rm(xAccountStateFile(paths), { force: true }); + await rm(path.join(SESSION, "refreshed.json"), { force: true }); + // No cooldown on record. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + st.download.platformHolds = {}; + await writeAutoQueueState(paths, st); + await writeSettings(); +} + +// One X job through the funnel, its work a stub. Answers how it ended. +async function xJob(kind: string, slug: string | undefined, params?: Record<string, unknown>): Promise<{ queued: boolean; error?: string; status?: string; deferred?: { until: number; sentence: string }; ran: boolean; log?: string }> { + let ran = false; + const res = await runManagedFunction({ + kind, + queueKey: "platform:twitter", + paths, + ...(slug ? { channelSlug: slug } : {}), + ...(params ? { spec: { kind, slug: slug ?? "x", params } } : {}), + fn: async () => { + ran = true; + fakeNow += 2_000; + }, + } as Parameters<typeof runManagedFunction>[0]); + if (!res.ok) return { queued: false, error: res.error, ran }; + const status = (await res.done).status; + const rec = getRegistry().get(res.jobId); + const log = await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8").catch(() => ""); + return { queued: true, status, ran, log, ...(rec?.deferred ? { deferred: rec.deferred } : {}) }; +} + +test("N: a sitting admits 4 X job starts by default; the setting is bounded 1-6 in the code", () => { + assert.equal(xSittingJobs(undefined), 4); + assert.equal(xSittingJobs({ sittingJobs: 2 }), 2); + assert.equal(xSittingJobs({ sittingJobs: 60 }), X_SITTING_MAX_JOBS); + assert.equal(xSittingJobs({ sittingJobs: 0 }), 1); + assert.equal(parseXSittingJobs("4"), undefined); + assert.equal(parseXSittingJobs(9.7), 6); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: 99, gapMinMinutes: 1, gapMaxMinutes: 600 } }).x, { sittingJobs: 6, gapMinMinutes: 5, gapMaxMinutes: 120 }); + assert.deepEqual(sanitizeSocial({ x: { sittingJobs: "lots" } }).x, {}); +}); + +test("the 5th X start after a refresh is refused — over every kind of timelines job together — and ends deferred, not failed", async () => { + await reset(); + await writeJar(2 * 60_000, { refresh: true }); + const ends = [ + await xJob("fetch-posts", ACCOUNTS[0]), + await xJob("capture-posts", ACCOUNTS[1], { ids: ["1"], shots: true }), + await xJob("check-post-availability", ACCOUNTS[2]), + await xJob("import-post", ACCOUNTS[3]), + ]; + for (const e of ends) { + assert.equal(e.queued, true, e.error); + assert.equal(e.status, "done"); + assert.equal(e.ran, true); + } + // Each job's log says where the sitting stands. + assert.match(ends[0].log ?? "", /X sitting: 1 of 4 started \(timelines, since the refresh at \d\d:\d\d UTC\); 3 left\./); + assert.match(ends[3].log ?? "", /X sitting: 4 of 4 started .*; 0 left\./); + // The 5th: refused at enqueue (no job), with the sentence. + const fifth = await xJob("fetch-posts", ACCOUNTS[4]); + assert.equal(fifth.queued, false); + assert.equal(fifth.ran, false); + assert.match(fifth.error ?? "", /^This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at \d\d:\d\d UTC \(social\.x\.sittingJobs, at most 6\)\. A new Refresh cookies on \/cookies starts the next sitting; nothing queues or retries by itself\.$/); + // get x-session shows it: used, left, kind, when it began. + const report = await xSessionReport({ paths }); + assert.equal(report.allowed, false); + assert.equal(report.refusedBy, "sitting"); + assert.deepEqual({ ...report.sitting, began: typeof report.sitting.began }, { began: "string", kind: "timelines", used: 4, left: 0, limit: 4 }); + // A job queued while there was room, started after it is gone: done, DEFERRED (until a Refresh), never run. + await writeFile(xSittingFile(paths), JSON.stringify({ ...JSON.parse(await readFile(xSittingFile(paths), "utf8")), starts: JSON.parse(await readFile(xSittingFile(paths), "utf8")).starts.slice(0, 3) })); + let ran = false; + let release!: () => void; + const blocker = new Promise<void>((r) => (release = r)); + // Hold X's queue with one job so the next one queues while the sitting has room. + const hold = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], fn: async () => { await blocker; } }); + assert.equal(hold.ok, true); + const late = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[5], fn: async () => { ran = true; } }); + assert.equal(late.ok, true, late.ok ? "" : late.error); + release(); + if (hold.ok) await hold.done; + if (late.ok) { + assert.equal((await late.done).status, "done"); + const rec = getRegistry().get(late.jobId); + assert.equal(rec?.deferred?.until, 0); + assert.match(rec?.deferred?.sentence ?? "", /^This X sitting is used up: 4 of 4/); + } + assert.equal(ran, false); +}); + +test("ONE KIND PER SITTING: the first job fixes it; a job of the other kind is refused until the next refresh", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + const read = await xJob("read-x-trending", "demo-library"); + assert.equal(read.status, "done", read.error); + // A search channel's walk and a library's capture are browse too. + assert.equal((await xJob("fetch-posts", "demo-search")).status, "done"); + assert.equal((await xJob("capture-posts", "demo-library", { ids: ["9"], shots: true })).status, "done"); + // A timeline fetch: refused, saying why. + const timeline = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(timeline.queued, false); + assert.match(timeline.error ?? "", /^This X sitting is a browse sitting \(its first job, read-x-trending at \d\d:\d\d UTC, fixed it\): a timelines job does not start in it/); + assert.equal((await xSessionReport({ paths })).sitting.kind, "browse"); + // A later refresh begins a new sitting, of either kind. + await writeJar(0, { refresh: true }); + const after = await xJob("fetch-posts", ACCOUNTS[0]); + assert.equal(after.status, "done", after.error); + const r = await xSessionReport({ paths }); + assert.deepEqual([r.sitting.kind, r.sitting.used], ["timelines", 1]); +}); + +test("the sitting survives an editor restart and is reset by nothing but a LATER refresh", async () => { + await reset(); + const refreshed = await writeJar(5 * 60_000, { refresh: true }); + for (const s of ACCOUNTS.slice(0, 3)) assert.equal((await xJob("fetch-posts", s)).status, "done"); + // A restart: every in-memory store is gone; the file is not. + clearQueueGaps(); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // gallery-dl (or anything) rewriting the jar moves its mtime, not the refresh. + const t = new Date(); + await utimes(JAR, t, t); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, refreshed); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + // A jar restored from an older refresh continues the sitting on record. + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(Date.parse(refreshed) - 3600_000).toISOString() })); + assert.equal((await xSessionReport({ paths })).sitting.used, 3); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: refreshed })); + // The sitting file deleted: rebuilt from the records and X's job count, kind and all. + await rm(xSittingFile(paths)); + const rebuilt = await xSessionReport({ paths }); + assert.deepEqual([rebuilt.sitting.used, rebuilt.sitting.kind], [3, "timelines"]); + // Deleted, with the records' kinds gone too: counted from X's job count, kind unknown — both kinds refused. + await rm(xSittingFile(paths)); + for (const id of getRegistry().list().map((r) => r.id)) { + const meta = path.join(paths.jobsDir, `${id}.meta.json`); + const m = JSON.parse(await readFile(meta, "utf8").catch(() => "{}")); + if (m.xSittings) { + delete m.xSittings; + await writeFile(meta, JSON.stringify(m)); + } + } + const unknown = await xSessionReport({ paths, sittingKind: "timelines" }); + assert.equal(unknown.sitting.kind, "unknown"); + assert.equal(unknown.allowed, false); + assert.match(unknown.reason ?? "", /^This X sitting's kind cannot be told/); + // An unreadable file: every counted X job is refused. + await writeFile(xSittingFile(paths), "{ not json"); + const bad = await xJob("fetch-posts", ACCOUNTS[3]); + assert.equal(bad.queued, false); + assert.match(bad.error ?? "", /^X's sitting cannot be read/); + // Only a later refresh begins a new one (stamped on the jobs' clock, which ran ahead of the wall's here). + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: refreshed, kind: "timelines", starts: [] })); + await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(fakeNow + 1000).toISOString() })); + const fresh = await xSessionReport({ paths }); + assert.deepEqual([fresh.sitting.used, fresh.sitting.kind], [0, null]); +}); + +test("N is the setting, bounded: sittingJobs 2 refuses the 3rd; 50 admits 6 and refuses the 7th", async () => { + await reset(); + await writeSettings({ sittingJobs: 2 }); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.equal((await xJob("fetch-posts", ACCOUNTS[1])).status, "done"); + assert.match((await xJob("fetch-posts", ACCOUNTS[2])).error ?? "", /used up: 2 of 2/); + await writeSettings({ sittingJobs: 50 }); + await writeJar(0, { refresh: true }); + // Out of the hourly cap's way: the first part's starts are forgotten. + await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); + for (const s of ACCOUNTS.slice(0, 6)) { + const e = await xJob("fetch-posts", s); + assert.equal(e.status, "done", e.error); + fakeNow += 11 * 60_000; // out of the hourly cap's way + } + assert.match((await xJob("fetch-posts", ACCOUNTS[6])).error ?? "", /used up: 6 of 6/); +}); + +test("UNEVEN GAPS: X's gap is drawn per job within 5-12 min, never below 5, logged with its draw; seeded only in a test", async () => { + // The pure draw: the bounds, always. + const range = xGapRange(undefined); + assert.deepEqual(range, { minSeconds: 300, maxSeconds: 720 }); + assert.equal(drawXGapSeconds(range, 0), 300); + assert.equal(drawXGapSeconds(range, 0.999999), 720); + for (let i = 0; i < 200; i++) { + const s = drawXGapSeconds(range, Math.random()); + assert.ok(s >= 300 && s <= 720, String(s)); + } + // The floor holds against any setting; an explicit jobGapSeconds.twitter above it raises the minimum, never lowers it. + // …and the range is never one value (review 1 F4): at least 3 minutes wide, whatever is set. + assert.deepEqual(xGapRange({ gapMinMinutes: 1, gapMaxMinutes: 2 }), { minSeconds: 300, maxSeconds: 480 }); + assert.deepEqual(xGapRange({ gapMinMinutes: 6, gapMaxMinutes: 9 }), { minSeconds: 360, maxSeconds: 540 }); + assert.deepEqual(xGapRange({ gapMinMinutes: 8, gapMaxMinutes: 8 }), { minSeconds: 480, maxSeconds: 660 }); + assert.deepEqual(xGapRange(undefined, 900), { minSeconds: 900, maxSeconds: 1080 }); + assert.deepEqual(xGapRange(undefined, 0), { minSeconds: 300, maxSeconds: 720 }); + assert.deepEqual(xQueueGapRange({ jobGapSeconds: { twitter: 30 } }, undefined), { minSeconds: 300, maxSeconds: 720 }); + + // The wait: drawn once per end, kept across re-reads, seeded draws repeat. + clearQueueGaps(); + setXGapRandom(42); + const end = fakeNow; + await noteQueueJobEnd(paths, "platform:twitter", end); + const w1 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + const w2 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 60_000, xGap: {} }); + assert.ok(w1 && w2); + assert.equal(w1!.until, w2!.until, "a re-read keeps the draw"); + assert.ok(w1!.drawn!.seconds >= 300 && w1!.drawn!.seconds <= 720); + assert.match(queueGapLine(w1!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); + clearQueueGaps(); + setXGapRandom(42); + await noteQueueJobEnd(paths, "platform:twitter", end); + const again = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); + assert.equal(again!.drawn!.seconds, w1!.drawn!.seconds, "the same seed, the same draw"); + // Different ends draw differently (not one fixed beat): over 30 ends, more than one value. + const draws = new Set<number>(); + for (let i = 0; i < 30; i++) { + await noteQueueJobEnd(paths, "platform:twitter", end + (i + 1) * 3_600_000); + const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + (i + 1) * 3_600_000 + 1, xGap: {} }); + draws.add(w!.drawn!.seconds); + } + assert.ok(draws.size > 5, `${draws.size} distinct draws`); + setXGapRandom(null); + clearQueueGaps(); + + // Through the funnel: two X jobs, the second starts 5-12 min after the first ended, and its log says the draw. + await reset(); + await writeJar(60_000, { refresh: true }); + const first = await xJob("fetch-posts", ACCOUNTS[0]); + const t1 = fakeNow; + const second = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(second.status, "done", second.error); + assert.match(second.log ?? "", /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\)/); + const waited = fakeNow - 2_000 - t1; + assert.ok(waited >= 300_000 && waited <= 720_000, `${waited} ms`); + assert.equal(first.status, "done"); +}); + +test("SUSPENDED: marked by hand, it refuses availability checks and captures that record deleted posts; other X jobs log it", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await writeXAccountState(paths, "suspended", { note: "read-only since the 21st" }); + const report = await xSessionReport({ paths }); + assert.equal(report.account.state, "suspended"); + assert.match(report.account.alert ?? "", /^The X account is marked suspended \(since .* UTC: read-only since the 21st\)/); + for (const [kind, params] of [ + ["check-post-availability", undefined], + ["capture-posts", { ids: ["1"] }], + ["capture-posts", { ids: ["1"], shots: true }], + ] as const) { + const e = await xJob(kind, ACCOUNTS[0], params); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^The X account is marked suspended .*is refused, because a suspended account's answers are thinned/, kind); + } + // A capture with its screenshots AND its articles off reads no page's verdict: it runs (review 1 F5). + assert.equal((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: false })).status, "done"); + // A fetch runs, and its log says the account is suspended. + const fetch = await xJob("fetch-posts", ACCOUNTS[1]); + assert.equal(fetch.status, "done"); + assert.match(fetch.log ?? "", /The X account is marked suspended .* What X answers it may be thinned\./); + // The last line before a verdict is written (a mark made while a job ran): only "available" is kept. + const lines: string[] = []; + const kept = await keepVerdictsTrustedWhileSuspended(paths, new Map([["1", "deleted"], ["2", "available"], ["3", "account_unavailable"]]), (l) => lines.push(l)); + assert.deepEqual([...kept], [["2", "available"]]); + assert.match(lines.join("\n"), /2 "deleted" or "unavailable" verdict\(s\) from its answers were NOT recorded/); + // Marked ok: the check runs again. + await writeXAccountState(paths, "ok"); + assert.equal((await xJob("check-post-availability", ACCOUNTS[2])).status, "done"); + const all = new Map([["1", "deleted"]]); + assert.equal(await keepVerdictsTrustedWhileSuspended(paths, all, () => {}), all); + // An unreadable state file is taken as suspended. + await writeFile(xAccountStateFile(paths), "nope"); + assert.match((await xJob("check-post-availability", ACCOUNTS[3])).error ?? "", /marked suspended/); +}); + +test("A 429 STOPS EVERY X JOB FOR 15 MINUTES: fetch, capture, availability check, import, X run channel, trending read, search walk", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + await recordPlatformCooldown("twitter", 15 * 60_000, paths); + for (const [kind, slug] of [ + ["fetch-posts", ACCOUNTS[0]], + ["sync", ACCOUNTS[0]], + ["capture-posts", ACCOUNTS[1]], + ["check-post-availability", ACCOUNTS[2]], + ["import-post", ACCOUNTS[3]], + ["read-x-trending", "demo-library"], + ["fetch-posts", "demo-search"], + ] as const) { + const e = await xJob(kind, slug); + assert.equal(e.queued, false, kind); + assert.match(e.error ?? "", /^X answered a rate limit \(429\) a short while ago: no X job starts before \d\d:\d\d UTC \(1[45] min from now\)/, kind); + } + // Each channel of an X run is guarded the same way. + const runGuard = await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], job: { id: "01JXRUN0000000000000000000" }, countStart: true }); + assert.equal(runGuard.ok, false); + // Nothing was counted against the sitting or the cap. + const r = await xSessionReport({ paths }); + assert.equal(r.sitting.used, 0); + assert.equal(r.cap.lastHour, 0); + assert.equal(r.refusedBy, "cooldown"); + assert.ok(r.cooldown && Date.parse(r.cooldown.until) > Date.now() + 14 * 60_000); + // Once it has passed, X jobs start again. + const st = await readAutoQueueState(paths); + st.download.platformBackoff = {}; + await writeAutoQueueState(paths, st); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); +}); + +test("the scheduler queues no more X syncs than the sitting has left, and none into a browse sitting", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal(await xCapRoom(paths, fakeNow), 4); + assert.equal(await xCapHeldReason(paths, fakeNow), null); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.equal(await xCapRoom(paths, fakeNow), 3); + // A browse sitting has no room for a timeline sync. + await writeJar(0, { refresh: true }); + assert.equal((await xJob("read-x-trending", "demo-library")).status, "done"); + assert.equal(await xCapRoom(paths, fakeNow), 0); + assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is a browse sitting/); + // Used up: the sentence says so. + await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: JSON.parse(await readFile(xSittingFile(paths), "utf8")).began, kind: "timelines", starts: [1, 2, 3, 4].map((i) => ({ at: fakeNow - i, jobKind: "fetch-posts", kind: "timelines" })) })); + assert.equal(await xCapRoom(paths, fakeNow), 0); + assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is used up: 4 of 4/); +}); + +// ── review 1 ─────────────────────────────────────────────────────────────── + +const { applyXStop, X_STOP_MS } = await import("./platformBackoff"); +const { recordDownloadBackoff, recordXStop, xStopRemainingMs } = await import("./downloadBackoff"); +const { downloadXPostMedia } = await import("../social/xGalleryDlFetcher"); +const { clearXSession } = await import("../social/xSessionBroker"); +const { runInJobContext } = await import("../lib/jobContext"); +const { writePostCapture, readPostCapture } = await import("../social/postCapture"); +const { writeDownloadOutcome, loadDownloadOutcome } = await import("../lib/downloadOutcome-server"); +const { recordAvailability } = await import("../lib/availability-server"); +const { xSuspendedRefuses } = await import("../lib/xSitting"); +const { X_RATE_LIMIT_HOLD_MS } = await import("../lib/xJobRule"); + +test("F1: a 429 from ANY X reader is the same 15-minute X stop — yt-dlp on an X address, a named cooldown, a post's media download — never the 60 s backoff", async () => { + assert.equal(X_STOP_MS, X_RATE_LIMIT_HOLD_MS); + assert.equal(X_STOP_MS, 15 * 60_000); + const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); + // yt-dlp on an X window / import / download (recordDownloadBackoff is what they call). + await reset(); + await recordDownloadBackoff("twitter", paths, "rate_limit"); + assert.equal(await left(), 15); + // Any caller that names its own length for X gets the X stop. + await reset(); + const { recordPlatformCooldown } = await import("./downloadBackoff"); + await recordPlatformCooldown("twitter", 60_000, paths); + assert.equal(await left(), 15); + // The auto-download lane's unit (pure, on the live state): the X stop too. + const st = { platformBackoff: {} as Record<string, { until: number; fails: number }> }; + const e = applyXStop(st, 1_000); + assert.equal(e.until, 1_000 + 15 * 60_000); + // gallery-dl's media download of one post: its rate-limit line is the X stop, and the capture is told to stop. + await reset(); + process.env.FAKE_GDL = "ratelimit"; + try { + const dir = path.join(ROOT, "media-1"); + await mkdir(dir, { recursive: true }); + const got = await downloadXPostMedia({ id: "123", dir, login: {}, signal: new AbortController().signal }); + assert.equal(got.ok, false); + assert.match(got.ok ? "" : (got.stop ?? ""), /rate limit/); + } finally { + delete process.env.FAKE_GDL; + } + assert.equal(await left(), 15); + // And then every X job is refused. + await writeJar(60_000, { refresh: true }); + assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X answered a rate limit \(429\)/); + // A generic platform keeps its own backoff. + await reset(); + await recordDownloadBackoff("odysee", paths, "rate_limit"); + const od = (await readAutoQueueState(paths)).download.platformBackoff.odysee; + assert.ok(od && od.until - Date.now() < 5 * 60_000, "odysee's first step is short"); +}); + +test("F2: a job that meets the X stop ends DEFERRED at once, saying so, with what it read kept", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + const e = await (async () => { + let ran = false; + const res = await runManagedFunction({ + kind: "fetch-posts", + queueKey: "platform:twitter", + paths, + channelSlug: ACCOUNTS[0], + fn: async () => { + ran = true; + await recordXStop("a rate limit (gallery-dl)", paths); + throw new Error("gallery-dl exited 1"); + }, + }); + assert.ok(res.ok); + const done = await res.done; + return { ran, done, rec: getRegistry().get(res.jobId), log: await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8") }; + })(); + assert.equal(e.ran, true); + assert.equal(e.done.status, "done"); + assert.ok(e.rec?.deferred); + assert.match(e.rec!.deferred!.sentence, /^X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read; no X job starts before/); + assert.ok(e.rec!.deferred!.until > Date.now() + 14 * 60_000); + assert.match(e.log, /X answered a rate limit \(gallery-dl\): X is left alone until \d\d:\d\d UTC \(15 minutes\); this job stops here\./); + assert.doesNotMatch(e.log, /^\[error\]/m); +}); + +test("F3: Clear session forgets the login only — the suspended mark, the sitting, X's count and the 429 stop stay", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + await writeXAccountState(paths, "suspended", { note: "kept across a clear" }); + await recordXStop("a rate limit", paths); + await clearXSession(paths); + const { existsSync } = await import("node:fs"); + assert.equal(existsSync(JAR), false); + assert.equal(existsSync(path.join(SESSION, "profile")), false); + assert.equal(existsSync(path.join(SESSION, "refreshed.json")), false); + assert.equal(existsSync(xAccountStateFile(paths)), true); + assert.equal(existsSync(xSittingFile(paths)), true); + assert.equal(existsSync(xJobStartsFile(paths)), true); + const r = await xSessionReport({ paths }); + assert.equal(r.account.state, "suspended"); + assert.equal(r.sitting.used, 1); + assert.ok(r.cooldown); +}); + +test("F4: an explicit pacing.jobGapSeconds.twitter of 900 still draws unevenly — never one fixed beat", async () => { + const range = xQueueGapRange({ jobGapSeconds: { twitter: 900 } }, { gapMinMinutes: 5, gapMaxMinutes: 5 }); + assert.deepEqual(range, { minSeconds: 900, maxSeconds: 1080 }); + const draws = new Set<number>(); + for (let i = 0; i < 50; i++) draws.add(drawXGapSeconds(range, i / 50)); + assert.ok(draws.size > 20, `${draws.size} distinct gaps`); + for (const d of draws) assert.ok(d >= 900 && d <= 1080); +}); + +test("F5: while suspended nothing records a post or a video as gone from X's answer — captures with articles, video checks, outcomes, availability, capture records", async () => { + // The guard: a capture with its shots off but its articles on, and the video checks. + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: true } }), true); + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false } }), true); + assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: false } }), false); + for (const kind of ["check-availability", "quick-availability-check", "check-maybe-missing", "check-kept-deleted"]) { + assert.equal(xSuspendedRefuses({ kind }), true, kind); + } + await reset(); + await writeJar(60_000, { refresh: true }); + await writeXAccountState(paths, "suspended"); + assert.match((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: true })).error ?? "", /marked suspended/); + assert.match((await xJob("check-availability", ACCOUNTS[0])).error ?? "", /marked suspended/); + // The writers, inside an X job (its context carries the mark). + const ctx = { jobId: "j", kind: "fetch-window", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>(), xSuspended: async () => true }; + const dir = path.join(ROOT, "writers"); + await mkdir(dir, { recursive: true }); + await runInJobContext(ctx, async () => { + await writePostCapture(dir, { version: 1, id: "9", url: "https://x.com/i/status/9", capturedAt: "2026-11-21T00:00:00.000Z", state: "deleted", mediaState: "skipped", media: [] } as never); + await writeDownloadOutcome(dir, { status: "failed", videoId: "v", startedAt: "a", finishedAt: "b", attempts: [{ n: 1, kind: "full", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1, availabilityClass: "deleted" }] } as never); + await recordAvailability(dir, { availability: "deleted", observedAt: "2026-11-21T00:00:00.000Z", source: "download" }); + }); + assert.equal((await readPostCapture(dir))!.state, "error"); + assert.equal((await loadDownloadOutcome(dir))!.attempts[0].availabilityClass, undefined); + const { existsSync } = await import("node:fs"); + assert.equal(existsSync(path.join(dir, "availability.json")), false, "no availability recorded"); + // Not suspended: written as said. + await runInJobContext({ ...ctx, xSuspended: async () => false }, () => + writePostCapture(dir, { version: 1, id: "9", url: "u", capturedAt: "c", state: "deleted", mediaState: "skipped", media: [] } as never), + ); + assert.equal((await readPostCapture(dir))!.state, "deleted"); +}); + +test("F6: in a production-shaped environment the e2e hooks are ignored — the gap, the sittings and the jar rule all hold", async () => { + await reset(); + process.env.E2E_JOB_GAP_SECONDS = "0"; + process.env.E2E_X_SITTINGS = "off"; + process.env.E2E_X_MAX_COOKIE_AGE_MINUTES = "0"; + delete process.env.E2E_TEST_ROUTES; + try { + assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 300, maxSeconds: 720 }); + await writeJar(3 * 3600_000, { refresh: true }); + assert.match((await xSessionReport({ paths })).reason ?? "", /^X cookies were last refreshed 3 h ago/); + await writeSettings({ sittingJobs: 1 }); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + assert.match((await xJob("fetch-posts", ACCOUNTS[1])).error ?? "", /used up: 1 of 1/); + // The test server's gate opens them. + process.env.E2E_TEST_ROUTES = "1"; + assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 0, maxSeconds: 0 }); + assert.equal((await xSessionReport({ paths })).allowed, true); + } finally { + delete process.env.E2E_JOB_GAP_SECONDS; + delete process.env.E2E_X_SITTINGS; + delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; + delete process.env.E2E_TEST_ROUTES; + } +}); + +test("F7a: the three reads fail closed — an unreadable stop file, an unreadable refresh stamp, a lost queue-gaps.json", async () => { + await reset(); + await writeJar(60_000, { refresh: true }); + // 1. The stop cannot be read: every X job is refused. + const { writeFile: wf } = await import("node:fs/promises"); + await wf(paths.autoQueueStateFile, "{ broken"); + assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X's rate-limit stop cannot be read/); + await reset(); + // 2. A stamp that is there and unreadable: the jar reads as never refreshed. + await writeJar(60_000, { refresh: true }); + await wf(path.join(SESSION, "refreshed.json"), "nope"); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, new Date(0).toISOString()); + assert.equal((await xSessionReport({ paths })).allowed, false); + // 3. queue-gaps.json lost after X jobs ran: the next waits a gap from the records. + await reset(); + await writeJar(60_000, { refresh: true }); + assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); + clearQueueGaps(); + await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); + const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: Date.now(), xGap: {} }); + assert.ok(w && w.remainingMs > 200_000, "a gap is waited from the last X job on record"); +}); + +test("F8: one X walk reads at most social.x.maxPostsPerJob posts (300; 20-400 in code)", async () => { + const { xJobPostLimit, X_POSTS_PER_JOB_CEILING } = await import("../lib/xSitting"); + assert.equal(xJobPostLimit(undefined), 300); + assert.equal(xJobPostLimit(undefined, 200), 200); + assert.equal(xJobPostLimit(undefined, 900), 300); + assert.equal(xJobPostLimit({ maxPostsPerJob: 5000 }), X_POSTS_PER_JOB_CEILING); + assert.equal(xJobPostLimit({ maxPostsPerJob: 1 }), 20); + assert.deepEqual(sanitizeSocial({ x: { maxPostsPerJob: 9999 } }).x, { maxPostsPerJob: 400 }); +}); + +test("F1: the auto-download lane's X unit that met a rate limit sets the 15-minute X stop, not the backoff's first step", async () => { + const { applyUnitOutcome } = await import("./unitOutcome"); + const state = { platformBackoff: {}, videoDeferrals: {}, platformPace: {}, platformHolds: {}, subtitleDeferrals: {} } as Parameters<typeof applyUnitOutcome>[0]; + const fx = applyUnitOutcome(state, { platform: "twitter", videoId: "v1", channelSlug: ACCOUNTS[0], outcome: "failed", failureClass: "rate_limit" }, 10_000); + assert.equal(state.platformBackoff.twitter.until, 10_000 + 15 * 60_000); + assert.deepEqual(state.platformHolds, {}, "no hold"); + assert.match(fx.line ?? "", /X answered a rate limit — X is left alone until/); +}); + +test("review 2 G3: a capture takes at most social.x.maxPostsPerJob posts (the rest owed); a trending read's tabs share the setting", async () => { + const { capturePosts } = await import("../controller/capturePosts"); + const { xTrendingPostsPerTab } = await import("../controller/readXTrending"); + const { getSettings } = await import("../lib/settings"); + await reset(); + await writeSettings({ maxPostsPerJob: 50 }); + const ids = Array.from({ length: 51 }, (_, i) => String(1000 + i)); + const log: string[] = []; + const ctx = { jobId: "g3", kind: "capture-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set<string>() }; + await runInJobContext(ctx, () => capturePosts({ paths, slug: ACCOUNTS[0], settings: getSettings(), ids, onLog: (l) => log.push(l) })); + assert.ok(log.some((l) => /^This X capture takes the first 50 of 51 posts \(social\.x\.maxPostsPerJob\); the other 1 are left for a later job, from 1050\.$/.test(l)), log.join("\n")); + // The trending read: the setting over its tabs, never past what was asked. + assert.equal(xTrendingPostsPerTab(200, 2, undefined), 150); + assert.equal(xTrendingPostsPerTab(200, 2, { maxPostsPerJob: 20 }), 10); + assert.equal(xTrendingPostsPerTab(200, 1, { maxPostsPerJob: 9999 }), 200); + assert.equal(xTrendingPostsPerTab(400, 1, { maxPostsPerJob: 9999 }), 400); + await writeSettings(); +}); + +test("review 2 G4: nothing ends the X stop before its time — not a clean answer, not Clear hold — but 'Clear the X stop', confirmed and logged", async () => { + const { recordPlatformClean, clearPlatformHold, clearXStop } = await import("./downloadBackoff"); + const { settlePlatformClean } = await import("./platformBackoff"); + const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); + await reset(); + await recordXStop("a rate limit", paths); + // A clean answer from another reader (a window fetch, a sync) and the lane page's Clear hold. + await recordPlatformClean("twitter", paths); + assert.equal(await left(), 15); + await clearPlatformHold("twitter", paths); + assert.equal(await left(), 15); + // The pure settle, too. + const st = { platformBackoff: { twitter: { until: Date.now() + 600_000, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(st, "twitter", { baseSeconds: 1 }); + assert.ok((st as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter); + // The operator's act: unconfirmed, it clears nothing and says what it risks. + const asked = await clearXStop(paths, { confirm: false, by: "test" }); + assert.equal(asked.ok, false); + assert.match(asked.message, /^Clearing the X stop lets the next X job ask X at once, inside the 15 minutes/); + assert.equal(await left(), 15); + const done = await clearXStop(paths, { confirm: true, by: "test", note: "checked" }); + assert.equal(done.ok, true); + assert.equal(await left(), 0); + const logged = (await readFile(path.join(paths.jobsDir, "x-stop-cleared.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual([logged.at(-1).by, logged.at(-1).note], ["test", "checked"]); + // An ended stop is pruned as before (a clean answer clears an expired entry). + const expired = { platformBackoff: { twitter: { until: Date.now() - 1, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; + settlePlatformClean(expired, "twitter", { baseSeconds: 1 }); + assert.equal((expired as { platformBackoff: Record<string, unknown> }).platformBackoff.twitter, undefined); +}); diff --git a/common/lib/availability-server.ts b/common/lib/availability-server.ts @@ -1,3 +1,4 @@ +import { xAnswersUntrusted } from "./jobContext"; import { AVAILABILITY_FILENAME, AVAILABILITY_VALUES, @@ -54,6 +55,9 @@ export async function recordAvailability( }, opts?: { updateTopLevel?: boolean }, ): Promise<void> { + // Inside an X job whose account is marked suspended, no "gone" verdict from + // X's answer is recorded (review 1 F5). + if (obs.availability !== "public" && obs.availability !== "unlisted" && (await xAnswersUntrusted())) return; const updateTopLevel = opts?.updateTopLevel !== false; const existing = await loadAvailability(videoDir); diff --git a/common/lib/captionTracks-server.ts b/common/lib/captionTracks-server.ts @@ -2,7 +2,9 @@ // says what an alternate is). SERVER-ONLY (node:fs). import path from "node:path"; -import { readdir, readFile } from "node:fs/promises"; +import { readFile } from "node:fs/promises"; +import { logicalEntries } from "./storedText"; +import { isStoredTextReadError, readStoredText, readdirLogical } from "./storedText-server"; import { parseVtt, type Cue } from "./vtt"; import { parseTranscriptJson } from "./whisper"; import { @@ -47,13 +49,17 @@ export async function readEnglishVttTracks( entries: readonly string[], ): Promise<{ filename: string; cues: Cue[] }[]> { const out: { filename: string; cues: Cue[] }[] = []; - for (const filename of englishVttsByPreference(entries)) { + for (const filename of englishVttsByPreference(logicalEntries(entries))) { try { out.push({ filename, - cues: parseVtt(await readFile(path.join(videoDir, filename), "utf8")), + // Either form (lib/storedText.ts): a track stored as `.zst` is read. + cues: parseVtt(await readStoredText(videoDir, filename, "utf8")), }); - } catch { + } catch (err) { + // A stored track that does not decode is an error (REVIEW-1 F3): the + // record must not be written without it. + if (isStoredTextReadError(err)) throw err; // unreadable: not a track } } @@ -72,7 +78,8 @@ export async function readTrackFields( primaryCues: readonly Cue[] | undefined, entries?: readonly string[], ): Promise<TrackFields> { - const listing = entries ?? (await readdir(videoDir).catch(() => [] as string[])); + // LOGICAL (lib/storedText.ts): a stored track is listed under its name. + const listing = entries ? logicalEntries(entries) : await readdirLogical(videoDir); if (!mayHaveAltTracks(primaryKind, listing)) return {}; const vtts = await readEnglishVttTracks(videoDir, listing); let primaryTrack: string; @@ -105,7 +112,7 @@ export async function readTrackFields( export async function readVideoTracks( videoDir: string, ): Promise<{ tracks: AltTrack[] } | null> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = await readdirLogical(videoDir); let primary: AltTrack | null = null; let kind: "vtt" | "whisper" = "vtt"; if (entries.includes(WHISPER_FILENAME)) { diff --git a/common/lib/cleanAudioConfirm.ts b/common/lib/cleanAudioConfirm.ts @@ -7,6 +7,7 @@ import { formatBytes } from "./format"; // The counts it states: the structural part of controller // cleanAudioFromTranscribed's AudioCleanPlan (lib may not import controller). +// `protected` includes the sourceGone group. export type CleanPlanCounts = { files: number; bytes: number; @@ -14,22 +15,59 @@ export type CleanPlanCounts = { protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + sourceGone?: SourceGoneCounts; +}; + +export type SourceGoneCounts = { + videos: number; + files: number; + bytes: number; + inferred: { videos: number; files: number; bytes: number }; }; const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; -export function cleanConfirmationText(plan: CleanPlanCounts): { ask: string; kept: string; button: string } { +// THE OPT-IN'S CHECKBOX (lane mark-provenance), off by default, with its count. +export function sourceGoneOptInLabel(g: SourceGoneCounts): string { + return ( + `Also remove audio kept only because the source was gone (${plural(g.videos, "video")}, ` + + `${plural(g.files, "file")}, ${formatBytes(g.bytes)})` + ); +} + +// `includeSourceGone`: the opt-in is ticked. The group then has its own line +// (videos, files, bytes; the inferred part separately) and leaves the kept +// count; the button counts both. +export function cleanConfirmationText( + plan: CleanPlanCounts, + opts: { includeSourceGone?: boolean } = {}, +): { ask: string; sourceGone: string | null; kept: string; button: string; files: number } { + const g = plan.sourceGone; + const include = opts.includeSourceGone === true && !!g && g.videos > 0; + const files = plan.files + (include ? g!.files : 0); + const keptMarked = include ? plan.protected - g!.videos : plan.protected; return { ask: - plan.files === 0 + files === 0 ? "Nothing to remove: no transcribed video here holds audio a clean would take." : `Remove ${plural(plan.files, "audio file")} (${formatBytes(plan.bytes)}) from ${plural(plan.videos, "transcribed video")} without checking? ` + "The source is not asked, so the audio of videos no longer available anywhere is removed too.", + sourceGone: include + ? `Also removed, kept only because the source was gone: ${plural(g!.files, "audio file")} (${formatBytes(g!.bytes)}) ` + + `from ${plural(g!.videos, "video")} the availability check marked do not clean. Their marks stay.` + + (g!.inferred.videos > 0 + ? ` Of these, ${plural(g!.inferred.videos, "video")} (${plural(g!.inferred.files, "file")}, ${formatBytes(g!.inferred.bytes)}) ` + + "carry marks inferred from the records (marks-backfill), not written by the check itself." + : "") + : null, kept: - `Kept: ${plan.protected} marked do not clean or in the keep-latest window, ` + - `${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + - "Videos with no transcript are not touched, and no saved video is.", - button: `Remove ${plural(plan.files, "file")} without checking`, + `Kept: ${keptMarked} marked do not clean or in the keep-latest window` + + (!include && g && g.videos > 0 ? ` (${g.videos} of them only because the source was gone)` : "") + + `, ${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + + "Videos with no transcript are not touched, and no saved video is." + + (include ? " A mark set by a person, an import or a live recording is never touched." : ""), + button: `Remove ${plural(files, "file")} without checking`, + files, }; } diff --git a/common/lib/clipWindow-server.ts b/common/lib/clipWindow-server.ts @@ -2,6 +2,7 @@ // layout and for why a `clips/` subdirectory is invisible to every video-dir // enumerator in the repo. +import { clampHolds } from "./recordingEnd.mjs"; import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; import { mkdir, readFile, readdir, stat } from "node:fs/promises"; @@ -36,6 +37,14 @@ export type ClipWindow = { // sidecar has a provenance — a height-only sidecar is what a window older // than the field gets after its one probe. height?: number; + // Its sidecar records a clamp at the recording's end (clipWindow.ts + // ClipProvenance `clamp`) that still holds against the saved-video pointer + // and the recording's known length now (recordingEnd.mjs clampHolds): it + // holds any span starting inside it. `clampStale`: a clamp whose facts moved + // (another or a longer container, the known end moved) -- an ordinary window + // of the seconds it holds, which fetch-windows retires. + endsRecording?: true; + clampStale?: true; }; // Every fetched window in a video dir, oldest-window-first by start second. @@ -91,6 +100,11 @@ export async function listClipWindows( provenance, ...(tier !== undefined ? { tier } : {}), ...(height !== undefined ? { height } : {}), + ...(provenance?.clamp + ? (await clampHolds(videoDir, provenance.clamp)) + ? { endsRecording: true as const } + : { clampStale: true as const } + : {}), }); } out.sort((a, b) => a.from - b.from || a.to - b.to || (a.tier ?? 0) - (b.tier ?? 0)); diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -322,8 +322,53 @@ export type ClipProvenance = { // map's `id` and whether it was sure of the span (`certain`; false on a step // or a map that is not ok -- the per-clip quote check settles those). clock?: ClipWindowClock; + // CLAMPED AT THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): the + // window was asked past the end of a saved recording known whole and cut to + // it. `askedTo` the end asked and `cutTo` the end cut (the window's own `to`), + // both on the cue clock; `recordingEnd` the container second it ends at; + // `why` the sentence (the recording's known length, within the tolerance). + // A window carrying it ENDS THE RECORDING while its facts hold + // (clipWindow-server listClipWindows asks recordingEnd.mjs clampHolds): it + // holds any span starting inside it (clipWindowContains), so the same padded + // ask is not cut again. One whose facts moved is retired by fetch-windows. + clamp?: ClipWindowClamp; }; +// `container` (the saved-video pointer's file and bytes) and `knownSeconds` (the +// length it was judged whole by) are what a lookup re-checks (recordingEnd.mjs +// clampHolds): a clamp whose facts have moved no longer ends the recording. +export type ClipWindowClamp = { + askedTo: number; + cutTo: number; + recordingEnd: number; + why: string; + container?: { file: string; bytes: number | null }; + knownSeconds?: number; +}; + +export function coerceClipWindowClamp(v: unknown): ClipWindowClamp | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const r = v as Record<string, unknown>; + const askedTo = num(r.askedTo); + const cutTo = num(r.cutTo); + const recordingEnd = num(r.recordingEnd); + if (askedTo === undefined || cutTo === undefined || recordingEnd === undefined || !(askedTo > cutTo)) return undefined; + const c = r.container as Record<string, unknown> | undefined; + const container = + c && typeof c === "object" && typeof c.file === "string" && c.file !== "" + ? { file: c.file, bytes: typeof c.bytes === "number" && Number.isFinite(c.bytes) ? c.bytes : null } + : undefined; + const knownSeconds = num(r.knownSeconds); + return { + askedTo, + cutTo, + recordingEnd, + why: typeof r.why === "string" ? r.why : "", + ...(container ? { container } : {}), + ...(knownSeconds !== undefined ? { knownSeconds } : {}), + }; +} + export type ClipWindowClock = { id: string; from: number; to: number; offset: number; certain: boolean }; export function coerceClipWindowClock(v: unknown): ClipWindowClock | undefined { @@ -413,20 +458,28 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null { if (setAsideAt) out.setAsideAt = setAsideAt; const clock = coerceClipWindowClock(r.clock); if (clock) out.clock = clock; + const clamp = coerceClipWindowClamp(r.clamp); + if (clamp) out.clamp = clamp; const height = num(r.height); if (height !== undefined && Number.isInteger(height) && height > 0) out.height = height; return out; } -export type ClipWindowSpan = { from: number; to: number }; +// `endsRecording`: the window ends where the recording does (its sidecar's +// `clamp`, lane window-end) — no second after it exists to be held. +export type ClipWindowSpan = { from: number; to: number; endsRecording?: boolean }; -// Does this window hold [from, to] whole, to the naming tolerance? +// Does this window hold [from, to] whole, to the naming tolerance? A window +// that ENDS THE RECORDING holds any span starting inside it: the seconds past +// its end are nowhere (lib/recordingEnd.mjs windowHoldsSpan, the same rule). export function clipWindowContains( w: ClipWindowSpan, from: number, to: number, ): boolean { - return !(w.from > from + WIN_EPS || w.to < to - WIN_EPS); + if (w.from > from + WIN_EPS) return false; + if (w.to >= to - WIN_EPS) return true; + return w.endsRecording === true && from < w.to - WIN_EPS; } // The TIGHTEST window containing [from, to], or null. diff --git a/common/lib/cookieStatus.ts b/common/lib/cookieStatus.ts @@ -63,7 +63,22 @@ export type CookieRow = { export type CookieRunning = { action: CookieRowButton["action"]; since: string; jobId?: string }; -export type CookieStatusPayload = { readAt: string; rows: CookieRow[] }; +// X'S SITTING AND ACCOUNT (lane x-sittings), for the X row's panel: the +// sitting since the last refresh (jobs/xSitting.ts) and the account's state +// as the operator marked it (social/xAccountState.ts). +export type XSittingView = { + began: string | null; + kind: "timelines" | "browse" | "unknown" | null; + used: number; + left: number; + limit: number; + unreadable?: true; + account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; + // X's 15 minutes after a 429, when it is cooling down. + cooldownUntil?: string; +}; + +export type CookieStatusPayload = { readAt: string; rows: CookieRow[]; xSitting?: XSittingView }; export type Displayers = { path: (p: string) => string; text: (s: string) => string }; diff --git a/common/lib/copies/dating.test.ts b/common/lib/copies/dating.test.ts @@ -0,0 +1,93 @@ +// lib/copies/dating.ts: the date a copies scan pairs a video by. Every title, +// channel and date here is synthetic. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { recordedDatePatternProblem } from "../recordedDate"; +import { + dateChannel, + dateEvidence, + datingAdvice, + detectTitleDate, + noCandidatesAdvice, + recordedDatePatchCommand, + TITLE_DATE_SHAPES, + type DatingRecord, +} from "./dating"; + +const upload = (title: string, uploadDate = "20260310"): DatingRecord => ({ title, uploadDate, wasLive: false }); +const live = (title: string, uploadDate: string): DatingRecord => ({ title, uploadDate, wasLive: true }); + +test("every built-in title shape is a valid recordedDate rule, so the one detected can be proposed verbatim", () => { + for (const s of TITLE_DATE_SHAPES) assert.equal(recordedDatePatternProblem(s.pattern), null, s.id); +}); + +test("the order: the channel's rule, else a live stream's day, else a title date, else the upload", () => { + const re = new RegExp(TITLE_DATE_SHAPES[0].pattern, "i"); + assert.deepEqual(dateEvidence({ ...upload("2023-01-02 x"), recordedDate: "20230101" }, re), { date: "20230101", from: "rule" }); + assert.deepEqual(dateEvidence(live("2023-01-02 x", "20230103"), re), { date: "20230103", from: "live" }); + assert.deepEqual(dateEvidence(upload("2023-01-02 x"), re), { date: "20230102", from: "title" }); + assert.deepEqual(dateEvidence(upload("2023-01-02 x"), null), { date: "20260310", from: "upload" }); + // A title date after the upload is a date the title mentions, not the stream's. + assert.deepEqual(dateEvidence(upload("2027-01-02 preview"), re), { date: "20260310", from: "upload" }); + assert.equal(dateEvidence({ title: "x", uploadDate: "", wasLive: false }, re), null); +}); + +test("a re-upload channel's leading title dates are detected in their mixed spellings (fails against upload-date dating)", () => { + const d = dateChannel( + [upload("2023 01 04 a stream"), upload("2023-01-05 the stream"), upload("2023 Jan 06 more"), upload("2012 a stream part 2")], + false, + ); + assert.deepEqual( + d.dated.map((x) => [x.date, x.from]), + [ + ["20230104", "title"], + ["20230105", "title"], + ["20230106", "title"], + ["20260310", "upload"], + ], + ); + assert.equal(d.dating.detectedPattern, TITLE_DATE_SHAPES[0].pattern); + assert.deepEqual(d.dating.span, { from: "20230104", to: "20260310" }); + const advice = datingAdvice("pref-chan", d, null).join("\n"); + assert.match(advice, /pref-chan: 3 of 4 videos are dated by a date their titles carry/); + assert.ok(advice.includes(recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern))); + assert.match(advice, /pref-chan: 1 of 4 videos have only an upload date/); +}); + +test("a mirror's tagged titles are detected; a live channel is dated by its streams whatever its titles say", () => { + const tagged = dateChannel([upload("[Copy] 2023-01-04"), upload("[Copy] 2023-01-05 Part 2/2"), upload("[Copy] 2023-01-07")], false); + assert.equal(tagged.dating.byFrom.title, 3); + const lives = dateChannel([live("[Copy] 2023-01-04", "20230105"), live("A stream", "20230106")], false); + assert.deepEqual(lives.dating.byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 }); + assert.equal(lives.dating.detectedPattern, undefined); + assert.deepEqual(datingAdvice("mirror-chan", lives, null), [], "nothing to set on a live channel"); +}); + +test("a shape that reads only a few titles does not stand for the channel; the advice names it with what it reads", () => { + const recs = [upload("Episode 1"), upload("Episode 2"), upload("Recap of 2023-01-04"), upload("Episode 3"), upload("Episode 4")]; + assert.equal(detectTitleDate(recs), null); + const d = dateChannel(recs, false); + assert.equal(d.dating.byFrom.upload, 5); + const advice = datingAdvice("pref-chan", d, "searched by runtime.").join("\n"); + assert.match(advice, /closest title shape reads 1 of 5/); + assert.match(advice, /searched by runtime\./); +}); + +test("with the channel's rule set, no shape is guessed past it", () => { + const d = dateChannel([{ ...upload("2023-01-04 x"), recordedDate: "20230104" }, upload("2023 Jan 05 y")], true); + assert.deepEqual(d.dating.byFrom, { rule: 1, live: 0, title: 0, upload: 1, none: 0 }); + assert.doesNotMatch(datingAdvice("pref-chan", d, null).join("\n"), /recordedDateTitlePattern/); +}); + +test("the patch command is one valid JSON body, and a scan with no dated pair names each member's span", () => { + const cmd = recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern); + const body = JSON.parse(/--json '(.*)'$/.exec(cmd)![1]); + assert.deepEqual(body, { slug: "pref-chan", patch: { recordedDateTitlePattern: TITLE_DATE_SHAPES[0].pattern } }); + assert.equal( + noCandidatesAdvice(1, [ + { slug: "pref-chan", span: { from: "20260303", to: "20261118" } }, + { slug: "mirror-chan", span: { from: "20230104", to: "20260225" } }, + ]), + "no two members' videos are dated within 1 day(s) of each other (pref-chan 2026-03-03…2026-11-18; mirror-chan 2023-01-04…2026-02-25): check the dates above before reading 0 as \"no copies\".", + ); +}); diff --git a/common/lib/copies/dating.ts b/common/lib/copies/dating.ts @@ -0,0 +1,212 @@ +// THE DATE A COPIES SCAN PAIRS A VIDEO BY (lane copies-dates). Pure. +// +// The copies scan (controller/copiesScan.ts) pairs two members' videos when +// their dates are at most `dateWindowDays` apart, so the date it reads is the +// whole of its first stage. A video's `upload_date` is the day THAT COPY went +// up: right for a live stream (the video is the stream) and for a creator's +// own upload, wrong for a re-upload channel, whose copies go up weeks or years +// after the streams. The first real scan answered 0 candidates for exactly +// that: a re-upload channel dated by its uploads (all of them months after the +// last stream its live mirror held) against the mirror dated by its streams. +// +// THE ORDER, best evidence first; a video is dated by the first that gives one: +// rule the channel's `recordedDate.titlePattern` (lib/recordedDate.ts): +// the operator's word, as the index derived it or applied here. With +// a rule set nothing else is read off a title: a title the rule does +// not read is not guessed past it. +// live a finished live stream's own day: its `upload_date`, which yt-dlp +// sets from the stream (equal to the UTC day of `release_timestamp` +// on 822 of 832 live videos measured, a day apart on the rest — the +// date window absorbs it). +// title with NO rule set, a date the channel's titles carry in one of the +// shapes below, when that shape reads at least TITLE_DATE_MIN_SHARE +// of the channel's videos that are not live streams (and at least +// TITLE_DATE_MIN_VIDEOS of them). The one shape is applied to the +// whole channel, as a rule would be, and the same guards hold: a real +// day, no later than the upload. The scan then SAYS the rule is not +// set and gives the exact patch that sets it, so every other reader +// (coverage, the index) dates the channel the same way. +// upload anything else: a not-live video's upload day. On a re-upload +// channel that is the copy's day, so such a video is also looked for +// by runtime and words (lib/copies/match.ts, runtimeCandidates). +// +// A date only proposes candidates. What a pair IS stays the matcher's: words +// both ways and agreeing runtimes to confirm; a metadata-only pair (one side +// without words) is held for a bounded wait, never skipped. + +import { deriveRecordedDate, recordedDatePatternProblem } from "../recordedDate"; + +export type DateFrom = "rule" | "live" | "title" | "upload"; + +export const DATE_FROM_ORDER: readonly DateFrom[] = ["rule", "live", "title", "upload"]; + +// The title shapes the scan recognises without a rule. Each is a valid +// recordedDate.titlePattern (the dating test proves it), so the one detected +// is proposed to the operator verbatim. +export const TITLE_DATE_SHAPES: readonly { id: string; pattern: string }[] = [ + // "2023-01-04 …", "2023 01 04 …", "2023 Jan 04 …", "(2023.01.04) …" + { id: "leading", pattern: "^\\W{0,3}(?<year>\\d{4})[-\\s._/](?<month>\\d{1,2}|[a-z]{3,9})[-\\s._/](?<day>\\d{1,2})\\b" }, + // "[Mirror] 2023-01-04 …", "[VOD] 2023.01.04 …" + { id: "tagged", pattern: "^\\s*\\[[^\\]]{1,40}\\]\\s*(?<year>\\d{4})[-._/](?<month>\\d{1,2})[-._/](?<day>\\d{1,2})\\b" }, + // "… stream 2023-01-04 …" + { id: "iso", pattern: "\\b(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})\\b" }, + // "… January 4, 2023 …", "… Jan 4th 2023 …" + { id: "month-name", pattern: "\\b(?<month>[a-z]{3,9})\\.? (?<day>\\d{1,2})(?:st|nd|rd|th)?,? (?<year>\\d{4})\\b" }, +]; + +export const TITLE_DATE_MIN_SHARE = 0.5; +export const TITLE_DATE_MIN_VIDEOS = 3; + +export type DatingRecord = { + title: string; + // YYYYMMDD, or "" when unknown. + uploadDate: string; + // The channel rule's date (the index's, or applied by the reader). + recordedDate?: string; + wasLive: boolean; +}; + +export type DetectedTitleDate = { + pattern: string; + // Not-live videos the shape reads, of how many. + reads: number; + of: number; +}; + +const YMD = /^\d{8}$/; + +/** + * The title shape that dates most of a channel's not-live videos, when it + * reads enough of them to stand for the channel; with `best`, the best shape + * whatever it reads (for advice), null when none reads one. + */ +export function detectTitleDate( + records: readonly DatingRecord[], + opts: { best?: boolean } = {}, +): DetectedTitleDate | null { + const notLive = records.filter((r) => !r.wasLive); + if (notLive.length === 0) return null; + let top: DetectedTitleDate | null = null; + for (const shape of TITLE_DATE_SHAPES) { + if (recordedDatePatternProblem(shape.pattern)) continue; + const re = new RegExp(shape.pattern, "i"); + let reads = 0; + for (const r of notLive) if (deriveRecordedDate(re, r.title, r.uploadDate || undefined)) reads++; + if (reads > 0 && (!top || reads > top.reads)) top = { pattern: shape.pattern, reads, of: notLive.length }; + } + if (!top || opts.best) return top; + return top.reads >= TITLE_DATE_MIN_VIDEOS && top.reads >= TITLE_DATE_MIN_SHARE * top.of ? top : null; +} + +/** A video's date and where it came from, by the order above; null: undated. */ +export function dateEvidence( + r: DatingRecord, + detected: RegExp | null, +): { date: string; from: DateFrom } | null { + if (r.recordedDate && YMD.test(r.recordedDate)) return { date: r.recordedDate, from: "rule" }; + const upload = YMD.test(r.uploadDate) ? r.uploadDate : null; + if (r.wasLive && upload) return { date: upload, from: "live" }; + if (!r.wasLive && detected) { + const d = deriveRecordedDate(detected, r.title, upload ?? undefined); + if (d) return { date: d, from: "title" }; + } + return upload ? { date: upload, from: "upload" } : null; +} + +export type ChannelDating = { + videos: number; + byFrom: Record<DateFrom | "none", number>; + // The span of the dates the scan pairs by (YYYYMMDD), null: none dated. + span: { from: string; to: string } | null; + // Whether the channel's config sets a recordedDate rule. + ruleSet: boolean; + // The title shape the scan dated the channel by (no rule set). + detectedPattern?: string; +}; + +export type DatedChannel<T extends DatingRecord> = { + dating: ChannelDating; + dated: { record: T; date: string | null; from: DateFrom | null }[]; + // With no rule set and no shape detected: the best shape and what it reads, + // for the advice (null when no shape reads any title). + bestShape: DetectedTitleDate | null; +}; + +/** One channel's videos, each dated by the order above, with the tally. */ +export function dateChannel<T extends DatingRecord>(records: readonly T[], ruleSet: boolean): DatedChannel<T> { + const detected = ruleSet ? null : detectTitleDate(records); + const re = detected ? new RegExp(detected.pattern, "i") : null; + const byFrom: Record<DateFrom | "none", number> = { rule: 0, live: 0, title: 0, upload: 0, none: 0 }; + let from: string | null = null; + let to: string | null = null; + const dated = records.map((record) => { + const e = dateEvidence(record, re); + byFrom[e?.from ?? "none"]++; + if (e) { + if (!from || e.date < from) from = e.date; + if (!to || e.date > to) to = e.date; + } + return { record, date: e?.date ?? null, from: e?.from ?? null }; + }); + return { + dating: { + videos: records.length, + byFrom, + span: from && to ? { from, to } : null, + ruleSet, + ...(detected ? { detectedPattern: detected.pattern } : {}), + }, + dated, + bestShape: ruleSet || detected ? null : detectTitleDate(records, { best: true }), + }; +} + +/** The ops call that sets a channel's recorded-date rule to `pattern`. */ +export function recordedDatePatchCommand(slug: string, pattern: string): string { + return `pnpm ops channel-config --json '${JSON.stringify({ slug, patch: { recordedDateTitlePattern: pattern } })}'`; +} + +const ymdShow = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`; + +/** + * What the scan says about a channel's dates, as sentences: the rule it lacks + * (with the exact patch), the videos it could date only by their upload. + */ +export function datingAdvice(slug: string, d: DatedChannel<DatingRecord>, runtimeSearch: string | null): string[] { + const out: string[] = []; + const { dating } = d; + if (dating.detectedPattern) { + out.push( + `${slug}: ${dating.byFrom.title} of ${dating.videos} videos are dated by a date their titles carry; the channel ` + + `sets no recordedDate rule, so the scan read the shape itself. Set it, so the index and coverage date them the ` + + `same way: ${recordedDatePatchCommand(slug, dating.detectedPattern)}`, + ); + } + if (dating.byFrom.upload > 0) { + let s = + `${slug}: ${dating.byFrom.upload} of ${dating.videos} videos have only an upload date (not a live stream, no ` + + `date in the title${dating.ruleSet ? " the channel's rule reads" : ""}); on a channel of re-uploads that is the ` + + `day of the copy, not of the stream.`; + if (runtimeSearch) s += ` ${runtimeSearch}`; + // With a rule set, or one proposed above, that is the channel's shape: + // these titles simply carry none, and nothing more is proposed. + if (!dating.ruleSet && !dating.detectedPattern) { + s += d.bestShape + ? ` The closest title shape reads ${d.bestShape.reads} of ${d.bestShape.of}; if the titles carry the ` + + `stream's day, set a rule: ${recordedDatePatchCommand(slug, d.bestShape.pattern)}` + : ` If the titles carry the stream's day, set a rule: ${recordedDatePatchCommand(slug, "<regex with groups year, month, day>")}`; + } + out.push(s); + } + if (dating.byFrom.none > 0) out.push(`${slug}: ${dating.byFrom.none} of ${dating.videos} videos have no date at all.`); + return out; +} + +/** The sentence for a scan with no date candidate at all, naming each member's span. */ +export function noCandidatesAdvice( + windowDays: number, + spans: readonly { slug: string; span: ChannelDating["span"] }[], +): string { + const parts = spans.map((s) => `${s.slug} ${s.span ? `${ymdShow(s.span.from)}…${ymdShow(s.span.to)}` : "undated"}`); + return `no two members' videos are dated within ${windowDays} day(s) of each other (${parts.join("; ")}): check the dates above before reading 0 as "no copies".`; +} diff --git a/common/lib/copies/file.ts b/common/lib/copies/file.ts @@ -15,6 +15,7 @@ // the decisions only ever act on pairs the scan lists. import type { CopyLink, TextEvidence } from "./match"; +import type { ChannelDating, DateFrom } from "./dating"; export const COPIES_DIRNAME = "copies"; export const COPIES_FORMAT = "archilyzer-copies"; @@ -28,6 +29,9 @@ export type CopyMember = { title: string; duration: number; date: string | null; + // Where `date` came from: the channel's rule, the live stream's own day, a + // date the titles carry, or the upload (lib/copies/dating.ts). + dateFrom?: DateFrom | null; }; export type CopyPairRecord = { @@ -43,7 +47,11 @@ export type CopyPairRecord = { evidence: { // What decided the link: the words, or (no text on one side) metadata. kind: "text" | "metadata"; - dateDeltaDays: number; + // How the pair was proposed: dated within the window, or by runtime (one + // side had no date to go by; such a pair is always decided by its words). + via?: "date" | "runtime"; + // null: one side is undated. + dateDeltaDays: number | null; durationOk: boolean; text?: TextEvidence; }; @@ -65,6 +73,11 @@ export type CopiesTotals = { // Candidates the words said were different recordings. rejected: number; withinChannel: number; + // The runtime search (lib/copies/match.ts runtimeCandidates): videos + // searched, the candidates it proposed, those the words rejected, and the + // videos left unsearched by its cap. The date stage's figures above do not + // include them. + runtime?: { searched: number; candidates: number; rejected: number; capped: number }; }; export type CopiesFile = { @@ -84,6 +97,12 @@ export type CopiesFile = { }; pairs: CopyPairRecord[]; totals: CopiesTotals; + // How each member's videos were dated, by channel. + dating?: Record<string, ChannelDating>; + // What the scan says about its own inputs: a channel lacking its + // recorded-date rule (with the exact patch), videos it could date only by + // their upload, a scan whose members' dates never meet. + advice?: string[]; }; // Who gave a decision: the caller's word, as judge-trending takes it (the diff --git a/common/lib/copies/match.test.ts b/common/lib/copies/match.test.ts @@ -6,6 +6,7 @@ import { classifyCandidate, copyCandidates, cuesToWords, + runtimeCandidates, textEvidence, COPY_PHRASE_WORDS, type CopyRecord, @@ -205,3 +206,48 @@ test("the adjacent day's stream with the closer runtime is not linked over the t assert.deepEqual(classifyCandidate(nextDay, null), { link: "metadata" }); assert.equal(classifyCandidate(sameDay, null), null); }); + +test("the runtime search: only for a video its date cannot pair, both sides with words, nearest runtimes first, bounded", async () => { + const up = (channel: string, dir: string, duration: number): CopyRecord => ({ ...rec(channel, dir, "20260310", duration), dateFrom: "upload" }); + const lv = (dir: string, date: string, duration: number): CopyRecord => ({ ...rec("mirror-chan", dir, date, duration), dateFrom: "live" }); + const records = [ + up("pref-chan", "p1", 7200), + up("pref-chan", "p2", 7200), // no words + up("pref-chan", "p3", 7200), // already paired by date + up("pref-chan", "p4", 7205), // same channel: never its own candidate + lv("m1", "20230101", 7260), + lv("m2", "20230102", 7100), + lv("m3", "20230103", 7400), // runtimes apart + lv("m4", "20230104", 7210), + lv("m5", "20230105", 7190), + ]; + const noWords = new Set(["pref-chan/p2"]); + const hasText = (r: CopyRecord) => !noWords.has(`${r.channel}/${r.dir}`); + const dated = new Set(["pref-chan/p3"]); + const s = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3 }); + assert.deepEqual( + s.candidates.map((c) => [c.a.dir, c.b.dir, c.via, c.durationOk]), + [ + ["p1", "m5", "runtime", true], + ["p1", "m4", "runtime", true], + ["p1", "m1", "runtime", true], + ["p4", "m4", "runtime", true], + ["p4", "m5", "runtime", true], + ["p4", "m1", "runtime", true], + ], + "nearest three each; never p2 (no words), p3 (paired by date), m3 (runtimes apart) or p1 with p4", + ); + assert.equal(s.searched, 2, "p1 and p4; a live mirror's own day pairs it, so it is never searched from"); + // The scan's cap: once reached, the rest are counted, not searched. + const capped = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, maxPairs: 2 }); + assert.equal(capped.candidates.length, 2); + assert.deepEqual([capped.searched, capped.capped], [1, 1]); + // A channel with a recordedDate rule is dated by it and never searched from. + const ruled = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, ruled: new Set(["pref-chan"]) }); + assert.deepEqual([ruled.candidates.length, ruled.searched, ruled.capped], [0, 0, 0]); + // A runtime candidate has nothing but its runtime: without words, no pair at all. + assert.equal(classifyCandidate(s.candidates[0], null), null); + assert.deepEqual(classifyCandidate(s.candidates[0], textEvidence(stream(5, 3000), shift(stream(5, 3000), 30))), { + link: "confirmed", + }); +}); diff --git a/common/lib/copies/match.ts b/common/lib/copies/match.ts @@ -37,6 +37,7 @@ // reads a time across copies. import type { SourceGroup } from "./settings"; +import type { DateFrom } from "./dating"; export const COPY_PHRASE_WORDS = 6; export const COPY_PROBES = 40; @@ -66,6 +67,8 @@ export type CopyRecord = { duration: number; // YYYYMMDD, or null when undated. date: string | null; + // Where `date` came from (lib/copies/dating.ts); absent: not said. + dateFrom?: DateFrom | null; }; export type Word = { w: string; t: number }; @@ -112,8 +115,13 @@ export type CopyLink = "confirmed" | "metadata" | "part-of" | "overlaps"; export type CopyCandidate = { a: CopyRecord; b: CopyRecord; - dateDeltaDays: number; + // Days between the two dates; null when one side is undated (a runtime + // candidate). + dateDeltaDays: number | null; durationOk: boolean; + // How it was proposed: dated within the window (the default), or — one side + // dated only by its upload — by runtime, for the words to decide. + via?: "date" | "runtime"; }; export type CopyClassification = { link: CopyLink; part?: "a" | "b" } | null; @@ -315,6 +323,7 @@ export function copyCandidates( b, dateDeltaDays: Math.abs(dd), durationOk: runtimesAgree(a.duration, b.duration, group), + via: "date", }); } } @@ -322,6 +331,119 @@ export function copyCandidates( return out.sort((x, y) => order(x.a, y.a) || order(x.b, y.b)); } +// THE RUNTIME SEARCH, for a video of a channel with NO recordedDate rule whose +// date says nothing about its stream (lib/copies/dating.ts: only an upload +// date, or none) and which found no candidate by date (a channel with a rule +// is dated by the operator's word, and is never searched from, as before): the other members' videos whose runtimes agree, nearest +// first, at most COPY_RUNTIME_PER_VIDEO of them, and at most +// COPY_RUNTIME_MAX_PAIRS such pairs in one scan. Both sides must have words: +// a runtime alone is no evidence of anything, so a runtime candidate is +// decided by its words or dropped (classifyCandidate), never held. The bound: +// at most min(8 × such videos, 2,000) text comparisons per scan, each about +// 0.15 s of one core measured on 4-hour streams — five minutes at worst. +export const COPY_RUNTIME_PER_VIDEO = 8; +export const COPY_RUNTIME_MAX_PAIRS = 2000; + +export type RuntimeSearch = { + candidates: CopyCandidate[]; + // Videos searched (undated or upload-dated, with words and a runtime, no date candidate). + searched: number; + // Such videos left unsearched once the scan's cap was reached. + capped: number; +}; + +const needsRuntimeSearch = (r: CopyRecord, ruled: ReadonlySet<string>) => + (!r.date || r.dateFrom === "upload") && !ruled.has(r.channel); + +/** Whether any record would be searched by runtime (the scan reads no cue file otherwise). */ +export function wantsRuntimeSearch(records: readonly CopyRecord[], ruled: ReadonlySet<string>): boolean { + return records.some((r) => needsRuntimeSearch(r, ruled)); +} + +/** + * Runtime candidates for the videos whose date cannot pair them (above). + * `hasText` says which videos have words; `dated` holds the keys + * (`<channel>/<dir>`) of videos that already have a date candidate; `ruled` + * the channels with a recordedDate rule (never searched from); `breathe` is + * awaited before each searched video (the scan yields to the event loop there). + * Deterministic: by the searched video's rank and dir, then runtime distance. + */ +export async function runtimeCandidates( + group: Pick<SourceGroup, "channels" | "durationToleranceSeconds" | "durationToleranceRatio">, + records: readonly CopyRecord[], + opts: { + hasText: (r: CopyRecord) => boolean; + dated: ReadonlySet<string>; + ruled?: ReadonlySet<string>; + perVideo?: number; + maxPairs?: number; + breathe?: () => Promise<void>; + }, +): Promise<RuntimeSearch> { + const ruled = opts.ruled ?? new Set<string>(); + const perVideo = opts.perVideo ?? COPY_RUNTIME_PER_VIDEO; + const maxPairs = opts.maxPairs ?? COPY_RUNTIME_MAX_PAIRS; + const rank = new Map(group.channels.map((c, i) => [c, i])); + const order = (x: CopyRecord, y: CopyRecord) => + rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0); + const keyOf = (r: CopyRecord) => `${r.channel}/${r.dir}`; + const pool = records + .filter((r) => rank.has(r.channel) && r.duration > 0 && opts.hasText(r)) + .sort((x, y) => x.duration - y.duration || order(x, y)); + const wanted = pool.filter((r) => needsRuntimeSearch(r, ruled) && !opts.dated.has(keyOf(r))).sort(order); + const seen = new Set<string>(); + const out: CopyCandidate[] = []; + let searched = 0; + let capped = 0; + for (const r of wanted) { + if (out.length >= maxPairs) { + capped++; + continue; + } + await opts.breathe?.(); + searched++; + // The pool is sorted by runtime: walk out from r's place both ways. + let lo = 0; + let hi = pool.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (pool[mid].duration < r.duration) lo = mid + 1; + else hi = mid; + } + const near: CopyRecord[] = []; + let i = lo - 1; + let j = lo; + const ok = (o: CopyRecord) => o.channel !== r.channel && runtimesAgree(r.duration, o.duration, group); + while (near.length < perVideo && (i >= 0 || j < pool.length)) { + const left = i >= 0 ? pool[i] : null; + const right = j < pool.length ? pool[j] : null; + const inLeft = left !== null && runtimesAgree(r.duration, left.duration, group); + const inRight = right !== null && runtimesAgree(r.duration, right.duration, group); + if (!inLeft && !inRight) break; + const takeLeft = inLeft && (!inRight || r.duration - left!.duration <= right!.duration - r.duration); + const o = takeLeft ? left! : right!; + if (takeLeft) i--; + else j++; + if (ok(o)) near.push(o); + } + for (const o of near) { + if (out.length >= maxPairs) break; + const [a, b] = order(r, o) <= 0 ? [r, o] : [o, r]; + const key = `${keyOf(a)}\u0000${keyOf(b)}`; + if (seen.has(key)) continue; + seen.add(key); + out.push({ + a, + b, + dateDeltaDays: a.date && b.date ? Math.abs(dayNumber(a.date) - dayNumber(b.date)) : null, + durationOk: true, + via: "runtime", + }); + } + } + return { candidates: out, searched, capped }; +} + /** * What a candidate is, given its text evidence (null = one side has no text). * With words on both sides they decide, and CONFIRMED needs the runtimes to @@ -346,5 +468,7 @@ export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): return null; } } + // A runtime candidate has nothing but its runtime: no words, no pair. + if (c.via === "runtime") return null; return c.durationOk ? { link: "metadata" } : null; } diff --git a/common/lib/doNotClean-server.ts b/common/lib/doNotClean-server.ts @@ -1,39 +1,230 @@ import { + DO_NOT_CLEAN_BY, DO_NOT_CLEAN_FILENAME, + type DoNotCleanAudioRemoved, + type DoNotCleanEvidence, + type DoNotCleanProvenance, type DoNotCleanRecord, } from "./doNotClean"; +import { isOperatorsMark, isSourceGoneMark } from "./doNotClean"; +import { withJsonFileLock } from "./jsonFile-server"; import { sidecar, sidecarField } from "./sidecar-server"; +// THE ONE WRITER of `data/<id>/do-not-clean.json` (lane mark-provenance). Every +// mark is set, cleared, relabelled or annotated here and nowhere else; +// common/lib/doNotCleanGate.test.ts fails the build when any other source file +// names the sidecar or its file name on a code line. +// +// EVERY WRITE HOLDS THE MARK'S LOCK (withJsonFileLock on its path), so a +// read-then-write here never interleaves with another: a person's keep and the +// opt-in's removal under a machine mark (removeUnderSourceGoneMark) are +// ordered, one after the other. + // A parseable-but-malformed marker still means "protected" — it reads as an // empty record rather than as absent. Only an absent, unreadable or -// unparseable file reads as null (sidecar-server's rule). +// unparseable file reads as null (sidecar-server's rule). A `by` that is not +// one of the known writers is dropped: an unknown writer reads as the +// operator's (protected, never machine-set). export function coerceDoNotClean(value: unknown): DoNotCleanRecord { const parsed = value as Partial<DoNotCleanRecord> | null; - if (typeof parsed?.setAt === "string") return parsed as DoNotCleanRecord; - return { setAt: "" }; + if (typeof parsed?.setAt !== "string") return { setAt: "" }; + const out = { ...parsed } as DoNotCleanRecord; + if (out.by !== undefined && !(DO_NOT_CLEAN_BY as readonly string[]).includes(out.by)) delete out.by; + return out; } -export const doNotCleanSidecar = sidecar( +const doNotCleanSidecar = sidecar( DO_NOT_CLEAN_FILENAME, sidecarField(coerceDoNotClean), ); export const { path: doNotCleanPath, load: loadDoNotClean } = doNotCleanSidecar; +const locked = <T>(videoDir: string, fn: () => Promise<T>): Promise<T> => withJsonFileLock(doNotCleanPath(videoDir), fn); + // Presence of a valid sidecar = protected. Cheap existence check for the // cleanup controllers' per-dir loops. export async function isDoNotClean(videoDir: string): Promise<boolean> { return (await loadDoNotClean(videoDir)) !== null; } +// SET OR CLEAR a video's mark. Setting requires the writer's provenance. +// - by "availability-check" NEVER replaces a mark already there (a person's +// mark and note survive a machine's later finding): it writes only where +// there is none, and answers whether it wrote. +// - any other writer (a person, an import, a live recording) REPLACES the +// mark — a person's ask outranks the machine's, so a source-gone mark a +// person re-marks becomes theirs — and carries the earlier record's +// audioRemoved history over, so what was removed stays on record; with +// no note of its own it keeps the earlier note; a mark replaced that was +// not already a person's is recorded in `takenOver`. +export async function setDoNotClean(videoDir: string, enabled: false): Promise<boolean>; +export async function setDoNotClean(videoDir: string, enabled: true, mark: DoNotCleanProvenance): Promise<boolean>; export async function setDoNotClean( videoDir: string, enabled: boolean, - note?: string, -): Promise<void> { - if (!enabled) return doNotCleanSidecar.remove(videoDir); - await doNotCleanSidecar.write(videoDir, { + mark?: DoNotCleanProvenance, +): Promise<boolean> { + if (!enabled) { + return locked(videoDir, async () => { + await doNotCleanSidecar.remove(videoDir); + return true; + }); + } + if (!mark || !(DO_NOT_CLEAN_BY as readonly string[]).includes(mark.by) || !mark.via) { + throw new Error("A do-not-clean mark needs its writer (by and via)."); + } + return locked(videoDir, async () => { + const existing = await loadDoNotClean(videoDir); + if (existing && mark.by === "availability-check") return false; + await doNotCleanSidecar.write(videoDir, replacing(existing, mark)); + return true; + }); +} + +function replacing(existing: DoNotCleanRecord | null, mark: DoNotCleanProvenance): DoNotCleanRecord { + const note = mark.note ?? existing?.note; + const takenOver = + existing && !isOperatorsMark(existing) + ? { + ...(existing.by ? { by: existing.by } : {}), + ...(existing.via ? { via: existing.via } : {}), + setAt: existing.setAt, + ...(existing.inferred ? { inferred: true as const } : {}), + } + : existing?.takenOver; + return { setAt: new Date().toISOString(), ...(note ? { note } : {}), + by: mark.by, + via: mark.via, + ...(mark.surface ? { surface: mark.surface } : {}), + ...(mark.jobId ? { jobId: mark.jobId } : {}), + ...(existing?.audioRemoved?.length ? { audioRemoved: existing.audioRemoved } : {}), + ...(takenOver ? { takenOver } : {}), + }; +} + +// A PERSON'S KEEP (lane mark-provenance review F1): keep-videos by pattern or +// by ids, a pending keep applied on landing, the toggle, "Make it mine", a +// note a person writes. A video already marked by a person stays as it is — +// "already kept" — unless the person gives a note, which is then theirs. A +// mark ANY other writer set (the availability check, an import, a live +// recording) is TAKEN OVER: it becomes the operator's, with this writer's +// via/surface and the given note (else the mark's own), and records what it +// was. Under the mark's lock. A dry run writes nothing and answers the same. +export type PersonKeep = "marked" | "taken-over" | "already-kept"; + +export async function keepByPerson( + videoDir: string, + mark: Omit<DoNotCleanProvenance, "by">, + // `defaultNote`: the note a NEW mark gets when the person gave none (a + // taken-over mark keeps its own; a person's mark is not rewritten for it). + opts: { dryRun?: boolean; defaultNote?: string } = {}, +): Promise<{ outcome: PersonKeep; before: DoNotCleanRecord | null }> { + if (!mark.via) throw new Error("A do-not-clean mark needs its writer (by and via)."); + return locked(videoDir, async () => { + const before = await loadDoNotClean(videoDir); + const outcome: PersonKeep = !before ? "marked" : isOperatorsMark(before) ? "already-kept" : "taken-over"; + if (outcome === "already-kept" && mark.note === undefined) return { outcome, before }; + const note = mark.note ?? (before ? undefined : opts.defaultNote); + if (!opts.dryRun) { + await doNotCleanSidecar.write(videoDir, replacing(before, { ...mark, by: "operator", ...(note !== undefined ? { note } : {}) })); + } + return { outcome, before }; + }); +} + +// THE BACKFILL'S RELABEL (controller/marksBackfill.ts): only a mark that STILL +// has no `by` and the very setAt the proof was made against — a mark a person +// re-set since, or one a writer labelled since, is left alone. Everything the +// mark said is kept; it gains by/via, `inferred: true` and its evidence. +export async function relabelDoNotCleanInferred( + videoDir: string, + expect: { setAt: string }, + evidence: DoNotCleanEvidence, + now: Date = new Date(), +): Promise<boolean> { + return locked(videoDir, async () => { + const existing = await loadDoNotClean(videoDir); + if (!existing || existing.by !== undefined || existing.setAt !== expect.setAt) return false; + await doNotCleanSidecar.write(videoDir, { + ...existing, + by: "availability-check", + via: "pre-clean-check", + inferred: true, + inferredAt: now.toISOString(), + evidence, + }); + return true; + }); +} + +// THE BACKFILL'S UNDO (marks-backfill {"undo": true}): an INFERRED label — +// and only that — returns to unlabelled (the operator's): by, via, inferred, +// inferredAt and evidence go; setAt, note and any audioRemoved stay. A mark +// a person or a writer set since (no longer inferred, or another setAt) is +// left alone. +export async function unlabelDoNotCleanInferred(videoDir: string, expect: { setAt: string }): Promise<boolean> { + return locked(videoDir, async () => { + const existing = await loadDoNotClean(videoDir); + if (!existing || existing.inferred !== true || existing.by !== "availability-check" || existing.setAt !== expect.setAt) { + return false; + } + const { by: _by, via: _via, inferred: _i, inferredAt: _ia, evidence: _e, ...rest } = existing; + await doNotCleanSidecar.write(videoDir, rest); + return true; }); } + +// THE RECORD OF AUDIO REMOVED UNDER A MARK THAT STAYS (the opt-in "also remove +// audio kept only because the source was gone"): appended to a mark that +// still says by "availability-check". The mark is not removed — the video is +// still gone from its source — so every other cleaner (and the saved-video +// prune) keeps treating the video as protected. +export async function recordDoNotCleanAudioRemoved( + videoDir: string, + entry: DoNotCleanAudioRemoved, +): Promise<boolean> { + return locked(videoDir, () => appendAudioRemoved(videoDir, entry)); +} + +async function appendAudioRemoved(videoDir: string, entry: DoNotCleanAudioRemoved): Promise<boolean> { + const existing = await loadDoNotClean(videoDir); + if (!existing || existing.by !== "availability-check") return false; + await doNotCleanSidecar.write(videoDir, { + ...existing, + audioRemoved: [...(existing.audioRemoved ?? []), entry], + }); + return true; +} + +// THE OPT-IN'S REMOVAL, UNDER THE MARK'S LOCK (review F3): the mark is +// re-checked AFTER the lock is taken, and `remove` runs only while it still +// says by "availability-check"; the audioRemoved entry is written before the +// lock is released. A person's keep queued meanwhile runs after, and finds +// the audio gone and recorded; one that got the lock first makes the mark +// theirs, and nothing is removed (null). +export async function removeUnderSourceGoneMark( + videoDir: string, + remove: () => Promise<{ files: string[]; bytes: number }>, + entry: Omit<DoNotCleanAudioRemoved, "files" | "bytes">, +): Promise<{ files: string[]; bytes: number; recorded: boolean } | null> { + return locked(videoDir, async () => { + if (!isSourceGoneMark(await loadDoNotClean(videoDir))) return null; + const out = await remove(); + const recorded = await appendAudioRemoved(videoDir, { ...entry, files: out.files, bytes: out.bytes }); + return { ...out, recorded }; + }); +} + +// Every mark of a channel's videos, as the reads show them (`pnpm ops get +// marks`): who set it, when, and the record. +export async function listDoNotCleanMarks(dataDir: string, ids: readonly string[]): Promise<{ id: string; mark: DoNotCleanRecord }[]> { + const out: { id: string; mark: DoNotCleanRecord }[] = []; + for (const id of ids) { + const mark = await loadDoNotClean(`${dataDir}/${id}`); + if (mark) out.push({ id, mark }); + } + return out; +} diff --git a/common/lib/doNotClean.ts b/common/lib/doNotClean.ts @@ -10,9 +10,138 @@ // Marker semantics: presence of the file = protected. There is no stored // `enabled: false` state — toggling off removes the file — which keeps // isDoNotClean a simple existence check for the controllers' hot loops. +// +// WHO SET IT (lane mark-provenance). Every writer names itself: `by` is the +// kind of writer, `via` which one, `surface` where a person asked (a button or +// pnpm ops), `jobId` the job that wrote it when there is one. A mark with NO +// `by` was written before this was recorded and is the OPERATOR's: nothing +// reads it as machine-set — except a mark the explicit backfill +// (controller/marksBackfill.ts) proved from other records, which says +// `inferred: true` and carries its evidence. +export type DoNotCleanBy = "availability-check" | "live-recording" | "import" | "operator"; + +export const DO_NOT_CLEAN_BY: readonly DoNotCleanBy[] = ["availability-check", "live-recording", "import", "operator"]; + +export type DoNotCleanVia = + // by "availability-check": the checked clean's gate (verifyBeforeClean), the + // per-video clean after capture, the keep-latest window's deletion check. + | "pre-clean-check" + | "clean-after-capture" + | "kept-deleted-check" + // by "live-recording" / "import". + | "record-live" + | "import-media" + // by "operator": the video page's toggle (or `do-not-clean`), keep-videos by + // pattern, keep-videos by ids, and a by-ids keep applied when the video landed. + | "toggle" + | "keep-videos-match" + | "keep-videos-ids" + | "pending-keep"; + +export type DoNotCleanSurface = "button" | "ops"; + +// What a writer declares. Required by setDoNotClean: no mark is written +// without saying who wrote it. +export type DoNotCleanProvenance = { + by: DoNotCleanBy; + via: DoNotCleanVia; + surface?: DoNotCleanSurface; + jobId?: string; + note?: string; +}; + +// The proof a backfilled mark was relabelled on (marksBackfill.ts). +export type DoNotCleanEvidence = { + // availability.json's observation: the gone state, when the check saw it, + // and which part of the record said so. + availability: string; + observedAt: string; + field: "history" | "checkedAt"; + // The clean job whose log names the pin, running at setAt. + jobId: string; + jobKind: string; +}; + +// The audio a clean removed while the mark stayed (the opt-in "also remove +// audio kept only because the source was gone"): when, by which job, and why. +export type DoNotCleanAudioRemoved = { + at: string; + jobId?: string; + files: string[]; + bytes: number; + why: string; +}; + export type DoNotCleanRecord = { setAt: string; note?: string; + by?: DoNotCleanBy; + via?: DoNotCleanVia; + surface?: DoNotCleanSurface; + jobId?: string; + inferred?: true; + inferredAt?: string; + evidence?: DoNotCleanEvidence; + audioRemoved?: DoNotCleanAudioRemoved[]; + // A person took over a mark another writer set (a keep, a note, "Make it + // mine"): who had set it, and when. + takenOver?: { by?: DoNotCleanBy; via?: DoNotCleanVia; setAt: string; inferred?: true }; }; export const DO_NOT_CLEAN_FILENAME = "do-not-clean.json"; + +// THE ONE READING of "kept only because the source was gone": a mark the +// availability check wrote (or one the backfill proved it wrote). An absent +// `by` is the operator's; every other `by` is a person's or a capture's ask. +export function isSourceGoneMark(m: DoNotCleanRecord | null | undefined): boolean { + return m?.by === "availability-check"; +} + +// A mark that is already a PERSON's: by "operator", or no `by` at all (written +// before marks said who set them, so the operator's). Every other mark — the +// availability check's, an import's, a live recording's — a person's keep +// takes over. +export function isOperatorsMark(m: DoNotCleanRecord | null | undefined): boolean { + return !!m && (m.by === undefined || m.by === "operator"); +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +// "3 Nov" (UTC), with the year when it is not `now`'s; null for no date. +export function markDay(iso: string | undefined, now: Date = new Date()): string | null { + const t = iso ? Date.parse(iso) : NaN; + if (!Number.isFinite(t)) return null; + const d = new Date(t); + const day = `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`; + return d.getUTCFullYear() === now.getUTCFullYear() ? day : `${day} ${d.getUTCFullYear()}`; +} + +// WHO SET IT AND WHEN, in words — the one wording every surface shows (the +// video page, the keep lists, `pnpm ops get marks`): "availability check, 3 +// Nov; the source was gone", "you, 20 Nov", "import, 3 Nov", "live recording, +// 3 Nov", and for a mark from before marks said who set them "you, 11 Sep (set +// before marks said who set them)". +export function describeDoNotCleanMark( + m: DoNotCleanRecord, + now: Date = new Date(), +): { who: string; day: string | null; text: string; mine: boolean; sourceGone: boolean } { + const day = markDay(m.setAt, now); + const mine = isOperatorsMark(m); + const sourceGone = isSourceGoneMark(m); + const who = + m.by === "availability-check" + ? m.inferred + ? "availability check (inferred from the records)" + : "availability check" + : m.by === "import" + ? "import" + : m.by === "live-recording" + ? "live recording" + : "you"; + const text = + who + + (day ? `, ${day}` : "") + + (sourceGone ? "; the source was gone" : "") + + (m.by === undefined ? " (set before marks said who set them)" : ""); + return { who, day, text, mine, sourceGone }; +} diff --git a/common/lib/doNotCleanGate.test.ts b/common/lib/doNotCleanGate.test.ts @@ -0,0 +1,85 @@ +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/doNotCleanGate.test.ts +// +// THE ONE WRITER OF do-not-clean.json, ENFORCED (lane mark-provenance). Every +// mark says who set it only if every write goes through lib/doNotClean-server.ts +// (setDoNotClean, which requires the writer's provenance, and the backfill's +// relabel and the opt-in's audioRemoved note beside it). A context-blind grep +// over every source file of the workspace, tests and e2e specs excepted (they +// build fixtures): no other file may name the sidecar's handle, its file-name +// constant or its file name on a code line. Comments may. + +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const ROOTS = ["common", "editor", "umtool", "mcp", "scripts", "export", "homepage", "plans"]; +const SKIP_DIRS = new Set(["node_modules", ".next", "out", "dist", "public", "e2e", ".e2e-song", "test-results", ".git", "coverage"]); +const EXT = /\.(ts|tsx|mts|cts|js|mjs|cjs)$/; +const TEST = /\.(test|spec)\.[cm]?[jt]sx?$|\.unit\.ts$/; + +// The files that may name it, and why. +const ALLOWED = new Map<string, string>([ + ["common/lib/doNotClean.ts", "declares the file name"], + ["common/lib/doNotClean-server.ts", "THE writer"], + ["plans/tools/phase3-files-numbers.ts", "a read-only count of sidecars (loads through loadDoNotClean)"], +]); + +export const FORBIDDEN = [/do-not-clean\.json/, /\bdoNotCleanSidecar\b/, /\bDO_NOT_CLEAN_FILENAME\b/]; + +// A line's code, with `//` comments and block-comment lines dropped. +export function codeOf(line: string): string { + const t = line.trim(); + if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return ""; + const i = line.indexOf("//"); + // A `//` inside a string (a URL) is rare in these files; good enough for a gate. + return i >= 0 && !/["'`][^"'`]*\/\//.test(line.slice(0, i + 2)) ? line.slice(0, i) : line; +} + +export function offendingLines(text: string): number[] { + const out: number[] = []; + text.split("\n").forEach((line, i) => { + const code = codeOf(line); + if (FORBIDDEN.some((re) => re.test(code))) out.push(i + 1); + }); + return out; +} + +async function* walk(dir: string): AsyncGenerator<string> { + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); + for (const e of entries) { + if (e.isDirectory()) { + if (SKIP_DIRS.has(e.name) || e.name.startsWith(".")) continue; + yield* walk(path.join(dir, e.name)); + } else if (e.isFile() && EXT.test(e.name) && !TEST.test(e.name)) { + yield path.join(dir, e.name); + } + } +} + +test("the gate itself: a write outside the writer is caught; a comment is not", () => { + assert.deepEqual(offendingLines(`// do-not-clean.json is set by the toggle\nawait writeFile(path.join(dir, "do-not-clean.json"), "{}");`), [2]); + assert.deepEqual(offendingLines(`await doNotCleanSidecar.write(dir, {});`), [1]); + assert.deepEqual(offendingLines(`const f = path.join(dir, DO_NOT_CLEAN_FILENAME);`), [1]); + assert.deepEqual(offendingLines(` * the do-not-clean.json marker`), []); +}); + +test("nothing but lib/doNotClean-server.ts writes do-not-clean.json", async () => { + const offenders: string[] = []; + const seen = new Set<string>(); + for (const root of ROOTS) { + for await (const file of walk(path.join(REPO, root))) { + const rel = path.relative(REPO, file).split(path.sep).join("/"); + const lines = offendingLines(await readFile(file, "utf8")); + if (lines.length === 0) continue; + seen.add(rel); + if (!ALLOWED.has(rel)) offenders.push(`${rel}:${lines.join(",")}`); + } + } + assert.deepEqual(offenders, [], "write a do-not-clean mark through lib/doNotClean-server.ts (setDoNotClean, with its writer)"); + // The allow-list cannot rot: every entry still names it. + for (const rel of ALLOWED.keys()) assert.ok(seen.has(rel), `${rel} no longer names it: drop it from ALLOWED`); +}); diff --git a/common/lib/downloadOutcome-server.ts b/common/lib/downloadOutcome-server.ts @@ -5,6 +5,7 @@ import { type DownloadOutcomeStatus, } from "./downloadOutcome"; import { sidecar, sidecarField } from "./sidecar-server"; +import { xAnswersUntrusted } from "./jobContext"; export function coerceDownloadOutcome( value: unknown, @@ -32,8 +33,25 @@ export const downloadOutcomeSidecar = sidecar( export const { path: downloadOutcomePath, load: loadDownloadOutcome, - write: writeDownloadOutcome, } = downloadOutcomeSidecar; +// The outcome, written — but inside an X job whose account is marked +// suspended (lib/jobContext.ts xAnswersUntrusted, review 1 F5) no attempt +// keeps a "gone" class (deleted, private, members-only, needs-auth) from what +// X answered. +export async function writeDownloadOutcome(videoDir: string, record: DownloadOutcomeRecord): Promise<void> { + if (await xAnswersUntrusted()) { + record = { + ...record, + attempts: record.attempts.map((a) => { + if (a.availabilityClass === undefined || a.availabilityClass === "public" || a.availabilityClass === "unlisted") return a; + const { availabilityClass: _dropped, ...rest } = a; + return rest; + }), + }; + } + return downloadOutcomeSidecar.write(videoDir, record); +} + // Narrow re-export so callers don't have to import from both modules. export type { DownloadOutcomeStatus }; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -260,8 +260,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AVAILABILITY_PROBE_GAP_MS", audience: "test", default: "the real gap (3 s, stretched by `pacing.jitter`)", readBy: "common/controller/checkAvailability.ts", doc: "The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once." }, { name: "E2E_PACING_JITTER", audience: "test", default: "`pacing.jitter` from settings.json (0.25)", readBy: "common/lib/jitter.ts", doc: "Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts)." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, - { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, - { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, + { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies — but X's gap, drawn per job from `social.x.gapMinMinutes`-`gapMaxMinutes`, is collapsed to this value whatever is set. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, + { name: "E2E_X_SITTINGS", audience: "test", default: "unset (X's sittings apply)", readBy: "common/jobs/networkGuard.ts", doc: "`off` leaves X jobs out of X's SITTINGS (at most `social.x.sittingJobs` X job starts per cookie refresh, of one kind each; common/lib/xSitting.ts) — inert unless `E2E_TEST_ROUTES=1`. The editor's e2e server sets it: its fake X jobs run many to one corpus with no refresh between them. X's job cap is not touched." }, + { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. Honoured only beside `E2E_TEST_ROUTES=1`. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs @@ -29,6 +29,15 @@ // its pad — to WIN_EPS. Within a tier the tightest wins; across tiers the order // above wins. // +// THE RECORDING'S END (lane window-end, ./recordingEnd.mjs): a window that ENDS +// THE RECORDING holds any span starting inside it -- the seconds past its end +// exist nowhere, so the last clip's pad past the end is not a reason to fetch. +// Such a window is a saved container KNOWN WHOLE (its record's duration, else a +// landed live recording's, within 2 s), for a span passing its end, and a +// corpus window the editor cut clamped at that end (its sidecar's `clamp`). +// The source it resolves to says `endsRecording: true`; its `windowEnd` is +// where the footage stops. +// // A file in `data/<id>/` may be a RELATIVE symlink into `media/`, which may be // an absolute symlink to another drive. Every candidate is `stat`ed through its // links before it is returned, and a dangling one — an unmounted drive — is @@ -44,6 +53,7 @@ import { promisify } from "node:util"; import { resolveVideoDir } from "./videoDir-server.mjs"; import { clockForContainer } from "./recordingClock-read.mjs"; import { mapSpan } from "./recordingClock.mjs"; +import { bothStreamsEnd, clampHolds, recordingWholeness, windowHoldsSpan } from "./recordingEnd.mjs"; const execFileP = promisify(execFile); @@ -95,8 +105,9 @@ export async function listNames(dir) { * @typedef {{ id: string, offset: number, certain: boolean }} SourceClock * the recording's time map applied to a saved container (recordingClock.mjs): * the offset the span was mapped by, and whether the map was sure of it - * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock }} SourceWindow - * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock }} LocalSource + * @typedef {{ name: string, path: string, from: number, to: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} SourceWindow + * `endsRecording`: the window ends where the recording does (./recordingEnd.mjs) + * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number, clock?: SourceClock, endsRecording?: boolean }} LocalSource * @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null, want?: { from: number, to: number }, maxHeight?: number, heightOf?: (kind: string, w: SourceWindow) => Promise<number | null> }} TierContext * `want`: the span being resolved, when there is one (resolveFromTiers sets it) -- the @@ -112,13 +123,15 @@ export async function listNames(dir) { */ /** - * Does this window hold [from, to] whole, to the tolerance? - * @param {{ from: number, to: number }} w + * Does this window hold [from, to] whole, to the tolerance? A window that ENDS + * THE RECORDING (`endsRecording`) holds any span starting inside it + * (./recordingEnd.mjs windowHoldsSpan). + * @param {{ from: number, to: number, endsRecording?: boolean }} w * @param {number} from * @param {number} to */ export function windowContains(w, from, to) { - return !(w.from > from + WIN_EPS || w.to < to - WIN_EPS); + return windowHoldsSpan(w, from, to); } /** @@ -360,16 +373,68 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr // one context `{video, slug, channelsDir, probe}`. A tier that cannot apply (no // channelsDir or slug) lists nothing. +/** + * Does a corpus window's sidecar record a clamp at the recording's end (the + * editor's `clamp`, lib/clipWindow.ts)? + * @param {string} windowPath + */ +async function sidecarClamped(windowPath) { + const ext = CORPUS_WINDOW_EXTS.find((x) => windowPath.endsWith(x)); + if (!ext) return false; + const c = await sidecarClampOf(windowPath.slice(0, -ext.length) + ".json"); + if (!c) return false; + // Re-checked against the saved-video pointer and the known length NOW + // (recordingEnd.mjs clampHolds): one whose facts moved is an ordinary window. + return clampHolds(path.dirname(path.dirname(windowPath)), c); +} + +// A sidecar's clamp by path, good while the sidecar keeps its size and mtime. +/** @type {Map<string, { sig: string, clamp: any }>} */ +const clampMemo = new Map(); + +/** @param {string} sidecar */ +async function sidecarClampOf(sidecar) { + let st; + try { + st = await stat(sidecar); + } catch { + return null; + } + const sig = `${st.size}:${st.mtimeMs}`; + const had = clampMemo.get(sidecar); + if (had && had.sig === sig) return had.clamp; + let clamp = null; + try { + const c = JSON.parse(await readFile(sidecar, "utf8"))?.clamp; + clamp = c && typeof c === "object" && Number.isFinite(c.askedTo) && Number.isFinite(c.cutTo) && c.askedTo > c.cutTo ? c : null; + } catch { + clamp = null; + } + if (clampMemo.size > 5000) clampMemo.clear(); + clampMemo.set(sidecar, { sig, clamp }); + return clamp; +} + /** @param {TierContext} ctx */ -async function corpusWindows({ video, slug, channelsDir, platform, maxHeight }) { +async function corpusWindows({ video, slug, channelsDir, platform, maxHeight, want }) { if (!channelsDir || !slug) return []; const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform)); const names = await listNames(dir); const plain = windowsFromBareNames(names, dir); - if (!isTallAsk(maxHeight)) return plain; + const all = isTallAsk(maxHeight) ? [...plain, ...tieredWindowsFromNames(names, dir)] : plain; + // THE RECORDING'S END: a window starting by the span's start and ending + // before its end -- a near miss -- holds it when the editor cut it clamped at + // the recording's end. Only those sidecars are read. + if (want) { + for (const w of all) { + if (w.from <= want.from + WIN_EPS && w.to < want.to - WIN_EPS && w.to > want.from + WIN_EPS && (await sidecarClamped(w.path))) { + w.endsRecording = true; + } + } + } + if (!isTallAsk(maxHeight)) return all; // A TALL ASK: the tiered windows too, and every window's recorded height // (the editor writes it in the sidecar; an old window has none until asked). - const all = [...plain, ...tieredWindowsFromNames(names, dir)]; for (const w of all) { const h = await sidecarHeight(w.path); if (h !== undefined) w.height = h; @@ -401,20 +466,37 @@ async function savedVideoWindows({ video, slug, channelsDir, platform, probe = f if (!Number.isFinite(duration) || duration <= 0) continue; const height = c.height ?? info?.height; const clock = want ? await clockForContainer(videoDir, c.path) : null; + /** @type {SourceWindow} */ + let w = { name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) }; if (clock && want) { const m = mapSpan(clock, want.from, want.to); const shift = m.offsetFrom; - out.push({ + w = { name: c.name, path: c.path, from: shift ? -shift : 0, to: duration - shift, ...(height ? { height } : {}), clock: { id: clock.id, offset: shift, certain: m.certain }, - }); - continue; + }; + } + // THE RECORDING'S END: a span starting inside and ending past a container + // that holds the whole recording -- the container ends the recording. + // Whole on one clock: the container's end on the cue clock (less the + // map's offset AT THE END) against the recording's length. Its footage + // ends where both streams have data (recordingEnd.mjs bothStreamsEnd), on + // the clock the build maps the whole file by (`from`'s one offset). + if (want && want.to > w.to + WIN_EPS && want.from < w.to - WIN_EPS) { + const offsetEnd = clock ? mapSpan(clock, want.from, want.to).offsetTo : 0; + if ((await recordingWholeness(videoDir, duration - offsetEnd)).whole) { + const end = (await bothStreamsEnd(c.path, duration, process.env.FFPROBE_BIN ?? "ffprobe")) + w.from; + if (want.from < end - WIN_EPS) { + w.to = end; + w.endsRecording = true; + } + } } - out.push({ name: c.name, path: c.path, from: 0, to: duration, ...(height ? { height } : {}) }); + out.push(w); } return out; } @@ -457,6 +539,7 @@ export const asSource = (kind, w) => ({ windowEnd: w.to, ...(w.height ? { height: w.height } : {}), ...(w.clock ? { clock: w.clock } : {}), + ...(w.endsRecording ? { endsRecording: true } : {}), }); /** diff --git a/common/lib/jobContext.ts b/common/lib/jobContext.ts @@ -25,6 +25,15 @@ export type JobContext = { onLog: (line: string) => void; // Services whose cookie alert this job met while it ran (serviceCookies). staleServices: Set<string>; + // X'S STOP met by this job (jobs/downloadBackoff.ts recordXStop): a rate + // limit or a bot check from X. The job ends deferred, saying so. + xStop?: { until: number; why: string; at: number }; + // AN X JOB'S ACCOUNT MARK (review 1 F5): set on every job of X's queues + // (jobs/streamCommand.ts). True while the operator has marked the X account + // suspended — then no writer records a post or a video as gone from what X + // answered (xAnswersUntrusted below). Read at each write, so a mark made + // while the job runs counts. + xSuspended?: () => Promise<boolean>; }; const KEY = Symbol.for("archilyzer.jobContext"); @@ -41,3 +50,17 @@ export function runInJobContext<T>(ctx: JobContext, fn: () => T): T { export function currentJobContext(): JobContext | undefined { return storage().getStore(); } + +// Is this write inside an X job whose account is marked suspended? Then what X +// answered is thinned, and nothing may be recorded deleted, unavailable or +// private from it (review 1 F5). False outside a job. A read that throws is +// taken as suspended (fail closed). +export async function xAnswersUntrusted(): Promise<boolean> { + const ask = currentJobContext()?.xSuspended; + if (!ask) return false; + try { + return await ask(); + } catch { + return true; + } +} diff --git a/common/lib/operationUnit.test.ts b/common/lib/operationUnit.test.ts @@ -47,6 +47,7 @@ function files(entries: string[]): VideoFiles { audioFiles: entries.filter((e) => e.startsWith("audio.")), partAudioFiles: [], entries, + physicalEntries: entries, }; } diff --git a/common/lib/pendingKeep-server.ts b/common/lib/pendingKeep-server.ts @@ -16,11 +16,15 @@ import path from "node:path"; import { stat } from "node:fs/promises"; import type { Paths } from "./paths"; import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; -import { isDoNotClean, setDoNotClean } from "./doNotClean-server"; +import { keepByPerson } from "./doNotClean-server"; +import type { DoNotCleanSurface } from "./doNotClean"; export const PENDING_KEEP_FILENAME = "pending-keep.json"; -export type PendingKeepEntry = { id: string; note?: string; at: string }; +// `surface`: where the person asked (the Keep matching control's button or +// pnpm ops), carried onto the mark when it is applied. Absent on entries +// written before it was recorded. +export type PendingKeepEntry = { id: string; note?: string; at: string; surface?: DoNotCleanSurface }; function fileOf(paths: Pick<Paths, "channelsDir">, slug: string): string { return path.join(paths.channelsDir, slug, PENDING_KEEP_FILENAME); @@ -48,11 +52,12 @@ export async function addPendingKeep( ids: readonly string[], note: string | undefined, now: Date = new Date(), + surface?: DoNotCleanSurface, ): Promise<PendingKeepEntry[]> { const entries = await loadPendingKeep(paths, slug); for (const id of ids) { const i = entries.findIndex((e) => e.id === id); - const entry: PendingKeepEntry = { id, ...(note ? { note } : {}), at: now.toISOString() }; + const entry: PendingKeepEntry = { id, ...(note ? { note } : {}), at: now.toISOString(), ...(surface ? { surface } : {}) }; if (i >= 0) entries[i] = entry; else entries.push(entry); } @@ -69,6 +74,8 @@ export async function applyPendingKeep( slug: string, id: string, onLog?: (s: string) => void, + // The landing job (an import, a live recording), recorded on the mark. + jobId?: string, ): Promise<boolean> { try { const entries = await loadPendingKeep(paths, slug); @@ -76,7 +83,19 @@ export async function applyPendingKeep( if (!entry) return false; const videoDir = path.join(paths.channelsDir, slug, "data", id); if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) return false; - if (!(await isDoNotClean(videoDir))) await setDoNotClean(videoDir, true, entry.note ?? "keep-videos: asked before it was fetched"); + // A person's ask: it takes over a mark another writer set meanwhile (the + // availability check, an import, a live recording); a person's own mark + // stays, gaining the note if one was asked with. + await keepByPerson( + videoDir, + { + via: "pending-keep", + ...(entry.surface === "button" || entry.surface === "ops" ? { surface: entry.surface } : {}), + ...(jobId ? { jobId } : {}), + ...(entry.note ? { note: entry.note } : {}), + }, + { defaultNote: "keep-videos: asked before it was fetched" }, + ); await save( paths, slug, diff --git a/common/lib/recordingEnd.mjs b/common/lib/recordingEnd.mjs @@ -0,0 +1,316 @@ +// recordingEnd.mjs — A CLIP WINDOW THAT REACHES THE END OF A SAVED RECORDING. +// +// A clip whose cut ends in the last seconds of a recording asks for a window +// that ends past it: the cut plus its pad (umtool pads 3 s each side). A saved +// container holding that recording WHOLE has every second the window can get -- +// the pad past its end does not exist anywhere, on the platform either. So such +// a window is cut from the saved container, CLAMPED to its end, instead of +// going to the platform's queue for a network fetch of footage already on disk +// (and of a video that may be private or gone by now). +// +// THE RULE, for a span [from, to] on the container's clock (after the one-clock +// map, recordingClock.mjs) and a container of D seconds: +// - to <= D (to WIN_EPS) held, as always; +// - from >= D - WIN_EPS (starts at or after the end) NOT held -- nothing of it +// is in the file; +// - else, the recording KNOWN WHOLE held, clamped: cut [from, ⌊D⌋₂] +// (two decimals, rounded DOWN so +// a window's name never claims a +// second the file lacks); +// - else NOT held, as before. +// +// KNOWN WHOLE: a known length L of the recording that the container reaches, +// L <= E + RECORDING_END_TOLERANCE_SECONDS, ON ONE CLOCK: E is the container's +// end on the cue clock (its length less the recording's time map's offset +// there, recordingClock.mjs; its length when there is no map), L the +// platform's. L is the record's own `duration` (metadata.info.json; ignored +// while the record says the stream is live, upcoming or `post_live` -- a VOD +// still being processed reports a length that is not its last), else a LANDED +// live recording's ended stream's own duration -- `coverage.basis` "duration" +// (never the recorder's clock, which measures the recorder: a recorder that +// died mid-stream measures itself whole), `coverage.covers`, from the start, no +// live-edge fallback, no missing stream, no failure on the record. Anything +// else is NOT whole: a partial recording (a live capture joined late or cut +// short, a download cut short) really may not hold the window, and a network +// fetch is then still right. +// +// A CLAMP IS RE-CHECKED ON EVERY LOOKUP (`clampHolds`): the window's sidecar +// records the saved-video pointer it was cut from (file, bytes) and the known +// length it was judged by; when the pointer names another file or size, or the +// known length has moved, the window no longer ends the recording -- the +// editor's fetch-windows retires it, as it retires a window cut on another +// clock, and cuts the span again. JSON reads only (memoised by size and mtime), +// never a probe. +// +// THE CUT ENDS WHERE BOTH STREAMS HAVE DATA (`containerStreamEnds`): at a +// container's end its picture and sound often stop apart (a merged +// bestvideo+bestaudio download, a live capture's last segments), and a window +// cut to the format's end would carry that gap -- which the sync check sets +// aside. So a clamp cuts to the shorter stream's end, measured once per +// container (its last packets, read from 30 s before its end) and kept for the +// process. +// +// THE TOLERANCE, 2 s: yt-dlp's `duration` is whole seconds on most platforms +// (YouTube's lengthSeconds, Rumble's), so a container that holds the whole +// recording can probe up to a second short of it; the other second is the +// muxer's own rounding of the last frame and packet. A stream longer than the +// container by more than that is a container that does not hold it. +// +// A window cut this way says so in its sidecar (`clamp`: the end asked, the end +// cut, the container's end and why), and a window carrying it ENDS THE +// RECORDING: it holds any later span that starts inside it (`windowHoldsSpan`), +// so the next ask for the same padded span is answered from it, not cut again +// and not fetched. +// +// Plain ESM with no app imports: umtool's report-to-video scripts run under +// bare node and ask the same question of the same disk (evidenceClip.mjs). + +import { execFile } from "node:child_process"; +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; + +const execFileP = promisify(execFile); + +/** How far a container's length may fall short of the recording's known length and still be the whole of it. */ +export const RECORDING_END_TOLERANCE_SECONDS = 2; + +// lib/clipWindow.ts's and evidenceClip.mjs's WIN_EPS: the 2 dp naming tolerance. +const EPS = 0.02; + +/** Two decimals, rounded down. @param {number} x */ +export const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; + +// Parsed JSON by path, good while the file keeps its size and mtime: a +// metadata.info.json can be tens of MB, and a build asks per clip. +/** @type {Map<string, { sig: string, value: any }>} */ +const jsonMemo = new Map(); + +/** @param {string} file @returns {Promise<any>} */ +async function readJson(file) { + let st; + try { + st = await stat(file); + } catch { + return null; + } + const sig = `${st.size}:${st.mtimeMs}`; + const had = jsonMemo.get(file); + if (had && had.sig === sig) return had.value; + let value = null; + try { + value = JSON.parse(await readFile(file, "utf8")); + } catch { + value = null; + } + // Only the few fields read here are kept, never a whole record. + const kept = + value && typeof value === "object" && !Array.isArray(value) + ? { + duration: value.duration, + live_status: value.live_status, + status: value.status, + fromStart: value.fromStart, + fallback: value.fallback, + missingStream: value.missingStream, + failureClass: value.failureClass, + error: value.error, + coverage: value.coverage, + file: value.file, + bytes: value.bytes, + dir: value.dir, + } + : null; + if (jsonMemo.size > 2000) jsonMemo.clear(); + jsonMemo.set(file, { sig, value: kept }); + return kept; +} + +const NOT_FINAL = new Set(["is_live", "is_upcoming", "post_live"]); + +/** + * The recording's known length in seconds and where it came from, or null. + * @param {string} videoDir + * @returns {Promise<{ seconds: number, basis: "metadata" | "live-recording" } | null>} + */ +export async function recordingKnownLength(videoDir) { + const meta = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "metadata.info.json")); + const live = !!meta && NOT_FINAL.has(meta.live_status); + const d = Number(meta?.duration); + if (!live && Number.isFinite(d) && d > 0) return { seconds: d, basis: "metadata" }; + const rec = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "live-recording.json")); + return liveRecordingLength(rec); +} + +/** + * A live recording's record's length of the stream, when it is the ended + * stream's own and the record says the recording holds it all; else null. Pure. + * @param {any} rec live-recording.json + * @returns {{ seconds: number, basis: "live-recording" } | null} + */ +export function liveRecordingLength(rec) { + if (!rec || rec.status !== "landed") return null; + if (rec.fromStart !== true || rec.fallback || rec.missingStream || rec.failureClass || rec.error) return null; + const c = rec.coverage; + if (!c || c.basis !== "duration" || c.covers !== true) return null; + const s = Number(c.streamSeconds); + return Number.isFinite(s) && s > 0 ? { seconds: s, basis: "live-recording" } : null; +} + +/** + * Does a container ending at `containerSeconds` ON THE CUE CLOCK (its length + * less the time map's offset at its end) hold the WHOLE recording? With the + * sentence that says why (or why not), for a sidecar and a log. + * @param {string} videoDir + * @param {number} containerSeconds + * @returns {Promise<{ whole: boolean, knownSeconds: number | null, basis: "metadata" | "live-recording" | null, why: string }>} + */ +export async function recordingWholeness(videoDir, containerSeconds) { + const known = await recordingKnownLength(videoDir); + const d = containerSeconds.toFixed(2); + if (!known) { + return { + whole: false, + knownSeconds: null, + basis: null, + why: `the saved recording ends at ${d} s and the recording's length is not known (no final duration in its record, no landed live recording that holds the whole stream by its own duration), so it may be partial`, + }; + } + const where = known.basis === "metadata" ? "its record's duration" : "the live recording's measured stream"; + const whole = known.seconds <= containerSeconds + RECORDING_END_TOLERANCE_SECONDS; + return { + whole, + knownSeconds: known.seconds, + basis: known.basis, + why: whole + ? `the saved recording ends at ${d} s, the whole recording (${where} is ${known.seconds} s, within ${RECORDING_END_TOLERANCE_SECONDS} s)` + : `the saved recording ends at ${d} s, short of the ${known.seconds} s recording (${where}): it does not hold this window`, + }; +} + +/** + * Does a clamped window still end the recording? Its sidecar's clamp names the + * saved-video pointer it was cut from and the known length it was judged by; + * both must be as they are now (the pointer's file and bytes; the known length + * within 0.5 s). JSON reads only. A clamp from before the pointer was recorded + * does not hold. + * @param {string} videoDir + * @param {{ container?: { file?: string, bytes?: number | null }, knownSeconds?: number } | null | undefined} clamp + */ +export async function clampHolds(videoDir, clamp) { + if (!clamp || !clamp.container || typeof clamp.container.file !== "string" || !Number.isFinite(clamp.knownSeconds)) return false; + const pointer = await readJson(path.join(/* turbopackIgnore: true */ videoDir, "saved-video.json")); + if (!pointer || pointer.file !== clamp.container.file) return false; + if ((Number.isFinite(pointer.bytes) ? pointer.bytes : null) !== (clamp.container.bytes ?? null)) return false; + const known = await recordingKnownLength(videoDir); + return !!known && Math.abs(known.seconds - Number(clamp.knownSeconds)) <= 0.5; +} + +// The stream ends a container was measured to, by path, size and mtime. +/** @type {Map<string, { sig: string, value: { video: number | null, audio: number | null } | null }>} */ +const endsMemo = new Map(); + +/** + * Where a container's picture and its sound each end, in seconds from the + * file's start (as ffmpeg's -ss counts them): its last packets, read from 30 s + * before `durationSec`. Measured once per container per process. Null when it + * cannot be read. + * @param {string} file + * @param {number} durationSec the container's probed length + * @param {string} [ffprobeBin] + * @returns {Promise<{ video: number | null, audio: number | null } | null>} + */ +export async function containerStreamEnds(file, durationSec, ffprobeBin = "ffprobe") { + let st; + try { + st = await stat(file); + } catch { + return null; + } + const sig = `${st.size}:${st.mtimeMs}`; + const had = endsMemo.get(file); + if (had && had.sig === sig) return had.value; + let value = null; + try { + const from = Math.max(0, durationSec - 30); + const { stdout } = await execFileP( + ffprobeBin, + [ + "-v", "error", + "-read_intervals", `${from.toFixed(3)}%`, + "-show_entries", "format=start_time:stream=index,codec_type:stream_disposition=attached_pic:packet=stream_index,pts_time,duration_time", + "-of", "json", + file, + ], + { maxBuffer: 1 << 26, timeout: 60_000 }, + ); + const doc = JSON.parse(stdout); + const start = Number(doc?.format?.start_time); + const zero = Number.isFinite(start) ? start : 0; + /** @type {Map<number, string>} */ + const kinds = new Map(); + for (const s of doc?.streams ?? []) { + if (s?.codec_type === "video" && s?.disposition?.attached_pic === 1) continue; + kinds.set(Number(s.index), String(s.codec_type)); + } + /** @type {{ video: number | null, audio: number | null }} */ + const ends = { video: null, audio: null }; + for (const p of doc?.packets ?? []) { + const kind = kinds.get(Number(p.stream_index)); + if (kind !== "video" && kind !== "audio") continue; + const t = Number(p.pts_time); + if (!Number.isFinite(t)) continue; + const d = Number(p.duration_time); + const e = t + (Number.isFinite(d) ? d : 0) - zero; + if (ends[kind] === null || e > /** @type {number} */ (ends[kind])) ends[kind] = e; + } + value = ends.video === null && ends.audio === null ? null : ends; + } catch { + value = null; + } + endsMemo.set(file, { sig, value }); + return value; +} + +/** + * The second a clamp may cut a container to: where BOTH its streams have data + * (the shorter of the two ends; the one there is, with one), never past its + * probed length. Its probed length when the ends cannot be read. + * @param {string} file + * @param {number} durationSec + * @param {string} [ffprobeBin] + */ +export async function bothStreamsEnd(file, durationSec, ffprobeBin = "ffprobe") { + const ends = await containerStreamEnds(file, durationSec, ffprobeBin); + const have = [ends?.video, ends?.audio].filter((x) => typeof x === "number" && Number.isFinite(x) && x > 0); + return have.length ? Math.min(durationSec, ...have) : durationSec; +} + +/** + * Where a span stands against a container's end. Pure. + * "held" to <= end (to EPS); + * "past" from >= end - EPS: nothing of it is in the file; + * "clamp" it starts inside and ends past: cut to `cutTo` (⌊end⌋₂) if the recording is whole. + * @param {{ from: number, to: number }} span on the container's clock + * @param {number} end the container's length + * @returns {{ kind: "held" } | { kind: "past" } | { kind: "clamp", cutTo: number }} + */ +export function spanAtEnd(span, end) { + if (span.to <= end + EPS) return { kind: "held" }; + if (span.from >= end - EPS) return { kind: "past" }; + return { kind: "clamp", cutTo: floor2(end) }; +} + +/** + * Does a window hold [from, to]? Whole, to EPS -- or, for a window that ENDS + * THE RECORDING (`endsRecording`: a saved container known whole, a window cut + * clamped at its end), any span that starts inside it. Pure. + * @param {{ from: number, to: number, endsRecording?: boolean }} w + * @param {number} from + * @param {number} to + */ +export function windowHoldsSpan(w, from, to) { + if (w.from > from + EPS) return false; + if (w.to >= to - EPS) return true; + return w.endsRecording === true && from < w.to - EPS; +} diff --git a/common/lib/savedVideoWindow-server.test.ts b/common/lib/savedVideoWindow-server.test.ts @@ -386,3 +386,225 @@ test("an ultrawide saved copy is cut tall once; the second tall ask cuts nothing assert.deepEqual(second, { kind: "best", height: 810 }); assert.equal((await listClipWindows(c.videoDir, { tiers: true })).length, 1); }); + +// THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): a window that +// starts inside a saved recording KNOWN WHOLE and ends past it is cut to its +// end, the clamp recorded; one that starts past it, or a container shorter than +// the stream it is of, is not-covering as before. +async function writeMeta(videoDir: string, meta: Record<string, unknown>) { + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta)); +} + +test("the last clip: cut ending 1 s before the end, pad 3 s — cut from the saved video, clamped at its end", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + // The clip is 4–7 of an 8 s recording; its padded window is 1–10. + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(src.kind, "covers"); + if (src.kind !== "covers") return; + assert.ok(src.clamp, "the clamp is on the answer"); + assert.equal(src.clamp?.askedTo, 10); + const end = src.durationSec; + assert.equal(src.clamp?.cutTo, Math.floor(end * 100 + 1e-6) / 100); + assert.equal(src.clamp?.recordingEnd, src.clamp?.cutTo); + assert.match(src.clamp?.why ?? "", /the whole recording \(its record's duration is 8 s, within 2 s\)/); + const logs: string[] = []; + const w = await cutSavedVideoWindow({ + paths: c.paths, + videoDir: c.videoDir, + source: src, + from: 1, + to: 10, + provenance: { requestedBy: "test", clipId: "c9", pad: 3 }, + onLog: (l) => logs.push(l), + }); + const cutTo = src.clamp!.cutTo; + // The name is the footage the file holds, never the end asked. + assert.equal(w.file, `1.00-${cutTo.toFixed(2)}.mp4`); + assert.equal(w.to, cutTo); + const probe = await probeMedia(w.path); + assert.ok(Math.abs((probe?.durationSec ?? 0) - (cutTo - 1)) < 0.25, `duration ${probe?.durationSec}`); + const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", `1.00-${cutTo.toFixed(2)}.json`), "utf8")); + assert.deepEqual( + { askedTo: sidecar.clamp.askedTo, cutTo: sidecar.clamp.cutTo, recordingEnd: sidecar.clamp.recordingEnd }, + { askedTo: 10, cutTo, recordingEnd: cutTo }, + ); + assert.match(sidecar.clamp.why, /whole recording/); + assert.match(logs.join(""), /clamped at the recording's end \(asked to 10\.00\)/); + // The window ENDS THE RECORDING: the same padded ask is answered from it, and so is a later one inside it. + assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file); + assert.equal((await findContainingClipWindow(c.videoDir, 3, 11))?.file, w.file); + assert.equal(await findContainingClipWindow(c.videoDir, 8.5, 11), null, "a span starting past the end is not held"); +}); + +test("a window starting at or after the recording's end: not-covering, even known whole", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 8.5, to: 12 }); + assert.equal(r.kind, "not-covering"); +}); + +test("a partial container against a longer stream: not-covering, and why", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, duration: 60 }); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(r.kind, "not-covering"); + if (r.kind === "not-covering") assert.match(r.why ?? "", /short of the 60 s recording/); +}); + +test("no known length (no duration, no landed live recording): not-covering — a partial recording may not cover", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, live_status: "is_live", duration: 8 }); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(r.kind, "not-covering"); + if (r.kind === "not-covering") assert.match(r.why ?? "", /length is not known/); +}); + +const LIVE = { + status: "landed", + url: "https://example.com/live", + startedAt: "2026-11-20T00:00:00.000Z", + fromStart: true, + parts: [], + coverage: { capturedSeconds: 8, streamSeconds: 9, basis: "duration", toleranceSeconds: 60, covers: true }, +}; + +test("a landed live recording whose ended stream's own duration it holds says whole: clamped", async () => { + const c = await corpus(PICTURE); + await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify(LIVE)); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(r.kind, "covers"); + if (r.kind === "covers") assert.match(r.clamp?.why ?? "", /live recording's measured stream is 9 s/); +}); + +// REVIEW 1, finding 1: the recorder's clock measures the recorder. A from-start +// recorder that died mid-stream and landed (the end-of-stream refresh still +// said is_live, so the length is the clock's: its own parts) is partial. +test("a from-start recorder that died mid-stream and landed: partial, not-covering", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, live_status: "is_live", duration: 8 }); + const died = { ...LIVE, failureClass: "final", coverage: { capturedSeconds: 8, streamSeconds: 8, basis: "clock", toleranceSeconds: 60, covers: true } }; + await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify(died)); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(r.kind, "not-covering"); + if (r.kind === "not-covering") assert.match(r.why ?? "", /length is not known/); + // Each fact alone makes it partial: the clock basis, a failure, a live-edge fallback, a missing stream, not covering, not from the start. + for (const bad of [ + { coverage: { ...LIVE.coverage, basis: "clock" } }, + { failureClass: "final" }, + { fallback: "live-edge" }, + { missingStream: "audio" }, + { coverage: { ...LIVE.coverage, covers: false } }, + { fromStart: false }, + ]) { + await writeFile(path.join(c.videoDir, "live-recording.json"), JSON.stringify({ ...LIVE, ...bad })); + const x = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(x.kind, "not-covering", JSON.stringify(bad)); + } +}); + +test("a post_live record's duration is not trusted: not-covering", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, live_status: "post_live", duration: 8 }); + const r = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(r.kind, "not-covering"); +}); + +test("a cut that does not reach the end carries no clamp key", async () => { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 2, to: 5 }); + assert.equal(src.kind, "covers"); + if (src.kind !== "covers") return; + assert.equal("clamp" in src, false); + await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 2, to: 5, provenance: { requestedBy: "test" } }); + const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", "2.00-5.00.json"), "utf8")); + assert.equal("clamp" in sidecar, false); +}); + +// REVIEW 1, finding 2: a clamp holds only while its facts do -- the +// saved-video pointer (file, bytes) and the recording's known length. +async function clampedWindow() { + const c = await corpus(PICTURE); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(src.kind, "covers"); + if (src.kind !== "covers") throw new Error("not covers"); + const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 10, provenance: { requestedBy: "test" } }); + const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", w.file.replace(/\.mp4$/, ".json")), "utf8")); + assert.deepEqual(sidecar.clamp.container, { file: "source-media.mp4", bytes: 1 }); + assert.equal(sidecar.clamp.knownSeconds, 8); + assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file, "held while its facts hold"); + return { c, w }; +} + +test("a clamp whose recording's known end moved no longer answers the padded ask", async () => { + const { c, w } = await clampedWindow(); + await writeMeta(c.videoDir, { id: ID, duration: 60 }); + assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null); + const listed = (await listClipWindows(c.videoDir)).find((x) => x.file === w.file); + assert.equal(listed?.clampStale, true); + assert.equal(listed?.endsRecording, undefined); + // Its own seconds are still its own. + assert.equal((await findContainingClipWindow(c.videoDir, 2, 5))?.file, w.file); +}); + +test("a clamp whose saved container is another or a longer file no longer answers the padded ask", async () => { + const { c, w } = await clampedWindow(); + const pointer = JSON.parse(await readFile(path.join(c.videoDir, "saved-video.json"), "utf8")); + await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify({ ...pointer, bytes: 999999 })); + assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null, "a longer file"); + await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify({ ...pointer, file: "source-media.webm" })); + assert.equal(await findContainingClipWindow(c.videoDir, 1, 10), null, "another file"); + await writeFile(path.join(c.videoDir, "saved-video.json"), JSON.stringify(pointer)); + assert.equal((await findContainingClipWindow(c.videoDir, 1, 10))?.file, w.file, "the same pointer again: held"); +}); + +// REVIEW 1, finding 3: at a container's end the picture and the sound stop +// apart. The clamp cuts where both have data, so the sync check keeps it. +async function uneven(videoSec: number, audioSec: number) { + const file = path.join(ROOT, "fixtures", `uneven-${videoSec}-${audioSec}.mp4`); + ff([ + "-f", "lavfi", "-i", `testsrc=size=160x90:rate=10:duration=${videoSec}`, + "-f", "lavfi", "-i", `sine=frequency=440:duration=${audioSec}`, + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", file, + ]); + return file; +} + +for (const [v, a] of [[8, 7.6], [7.6, 8]] as const) { + test(`a container whose ${v > a ? "audio" : "video"} ends 0.4 s early: the clamp cuts where both streams have data, and the window stays in sync`, async () => { + const { findInSyncContainingClipWindow, ffprobeWindowProbe } = await import("./clipWindowSync-server"); + const c = await corpus(await uneven(v, a)); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 1, to: 10 }); + assert.equal(src.kind, "covers"); + if (src.kind !== "covers") return; + assert.ok(src.clamp!.recordingEnd <= 7.65 && src.clamp!.recordingEnd >= 7.5, `cut to ${src.clamp!.recordingEnd}`); + const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 1, to: 10, provenance: { requestedBy: "test" } }); + const held = await findInSyncContainingClipWindow(c.videoDir, 1, 10, { probe: ffprobeWindowProbe("ffprobe") }); + assert.deepEqual(held.desynced, [], "nothing set aside"); + assert.equal(held.hit?.file, w.file); + }); +} + + +test("one clock at the end of the file: the clamp is on the container's clock, the name on the cue clock", async () => { + const c = await corpus(PICTURE); + const container = path.join(c.storeDir, "source-media.mp4"); + await writeClock(c.videoDir, container, 2); + await writeMeta(c.videoDir, { id: ID, duration: 8 }); + // Cue 3–9 is the container's 5–11: past its end at ~8. + const src = await savedWindowSource({ paths: c.paths, slug: SLUG, videoDir: c.videoDir, from: 3, to: 9 }); + assert.equal(src.kind, "covers"); + if (src.kind !== "covers") return; + const end = src.clamp!.recordingEnd; + assert.equal(src.clock?.mapped.from, 5); + assert.equal(src.clock?.mapped.to, end, "the container cut ends at the container's end"); + assert.equal(src.clamp?.cutTo, Math.floor((end - 2) * 100 + 1e-6) / 100, "the cue-clock end is the container's end less the offset there"); + const w = await cutSavedVideoWindow({ paths: c.paths, videoDir: c.videoDir, source: src, from: 3, to: 9, provenance: { requestedBy: "test" } }); + assert.equal(w.file, `3.00-${src.clamp!.cutTo.toFixed(2)}.mp4`); + const sidecar = JSON.parse(await readFile(path.join(c.videoDir, "clips", w.file.replace(/\.mp4$/, ".json")), "utf8")); + assert.equal(sidecar.clock.from, 5); + assert.equal(sidecar.clock.to, end); +}); diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts @@ -17,9 +17,20 @@ // silent fall-through to the network: the operator who can plug // the drive in is the one who needs to hear it. // not-covering a pointer whose container ends before the window does: the -// network path. +// network path. `why` says so when the recording's end was +// weighed (below). // covers cut it here. // +// THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): a window that +// starts inside the container and ends past it — the last clip of a recording +// and its pad — COVERS when the recording is known whole (its record's +// duration, else a landed live recording's measured stream, within 2 s of the +// container): `clamp` says the end asked, the end cut (the container's, two +// decimals rounded down, on the cue clock) and why. The cut ends there, its +// file is named for the seconds it holds, and its sidecar records the clamp. +// One that starts at or after the end, or a container shorter than the stream +// it is of, stays not-covering. +// // THE CUT IS evidenceClip-server's (`evidenceCutArgs`): seeked on the input // and re-encoded, so the window's first frame is the asked-for second; H.264 + // AAC in an mp4, fitted inside 1280×720 — the container a fetched window is @@ -55,6 +66,7 @@ import { isDriveNotAnswering, onDrive } from "./storageHealth"; import type { Paths } from "./paths"; import { clockForContainer } from "./recordingClock-read.mjs"; import { mapSpan, type RecordingClock } from "./recordingClock.mjs"; +import { bothStreamsEnd, floor2, recordingWholeness, spanAtEnd } from "./recordingEnd.mjs"; import "./childKillGuard"; // A window cut from a container is seconds of re-encoding; a whole container @@ -65,7 +77,7 @@ const CUT_TIMEOUT_MS = 10 * 60_000; export type SavedWindowSource = | { kind: "none" } | { kind: "unreadable"; error: string } - | { kind: "not-covering"; container: string; durationSec: number } + | { kind: "not-covering"; container: string; durationSec: number; why?: string } | { kind: "covers"; pointer: SavedVideoPointer; @@ -75,8 +87,24 @@ export type SavedWindowSource = // The recording's time map, when its video dir has one about THIS // container (lib/recordingClock.mjs): the span is cut at `mapped`. clock?: { map: RecordingClock; mapped: ReturnType<typeof mapSpan> }; + // The window ends past the recording's end: cut to it (the header). + clamp?: SavedWindowClamp; }; +// A window clamped at the recording's end: `askedTo` and `cutTo` on the cue +// clock (the window's name), `recordingEnd` the container second it ends at. +// `container` the saved-video pointer it was cut from and `knownSeconds` the +// length it was judged whole by: a clamp holds only while both are as now +// (recordingEnd.mjs clampHolds). +export type SavedWindowClamp = { + askedTo: number; + cutTo: number; + recordingEnd: number; + why: string; + container: { file: string; bytes: number | null }; + knownSeconds: number; +}; + // The media guard's sentence (lib/channelMedia.ts, ChannelMediaUnreachableError) // with the saved container as its detail, so a refusal here reads like every // other unreachable-media refusal the operator has seen. @@ -133,8 +161,35 @@ export async function savedWindowSource(opts: { const map = await clockForContainer(opts.videoDir, container); const mapped = map ? mapSpan(map, opts.from, opts.to) : null; const span = mapped ?? { from: opts.from, to: opts.to }; - if (opts.from < 0 || span.from < 0 || span.to > durationSec + WIN_EPS) { - return { kind: "not-covering", container, durationSec }; + if (opts.from < 0 || span.from < 0) return { kind: "not-covering", container, durationSec }; + const at = spanAtEnd(span, durationSec); + if (at.kind === "past") { + return { kind: "not-covering", container, durationSec, why: `the window starts at or after the saved recording's end (${durationSec.toFixed(2)} s)` }; + } + let clamp: SavedWindowClamp | undefined; + let cut = mapped; + if (at.kind === "clamp") { + // Whole, on one clock: the container's end on the cue clock (its length + // less the map's offset there -- past the map's last segment its offset + // holds, recordingClock clockOffsetAt) against the recording's length. + const offsetEnd = mapped ? mapped.offsetTo : 0; + const whole = await recordingWholeness(opts.videoDir, durationSec - offsetEnd); + if (!whole.whole || whole.knownSeconds === null) return { kind: "not-covering", container, durationSec, why: whole.why }; + // The cut ends where both streams have data, so the window is in sync to its last frame. + const recordingEnd = floor2(await bothStreamsEnd(container, durationSec, opts.paths.ffprobeBin)); + const cutTo = floor2(recordingEnd - offsetEnd); + if (!(span.from < recordingEnd - WIN_EPS) || !(cutTo > opts.from + WIN_EPS)) { + return { kind: "not-covering", container, durationSec, why: `the window starts at the saved recording's end (${durationSec.toFixed(2)} s)` }; + } + clamp = { + askedTo: opts.to, + cutTo, + recordingEnd, + why: whole.why, + container: { file: pointer.file, bytes: Number.isFinite(pointer.bytes) ? pointer.bytes : null }, + knownSeconds: whole.knownSeconds, + }; + if (mapped) cut = { ...mapped, to: recordingEnd }; } return { kind: "covers", @@ -142,7 +197,8 @@ export async function savedWindowSource(opts: { container, durationSec, probe, - ...(map && mapped ? { clock: { map, mapped } } : {}), + ...(map && cut ? { clock: { map, mapped: cut } } : {}), + ...(clamp ? { clamp } : {}), }; } @@ -180,7 +236,11 @@ export async function cutSavedVideoWindow(opts: { onLog?: (line: string) => void; signal?: AbortSignal; }): Promise<ClipWindow> { - const { from, to, source } = opts; + const { from, source } = opts; + // A window clamped at the recording's end is cut to it and NAMED for it: + // the file holds no second past the end, and its name says so. + const clamp = source.clamp; + const to = clamp ? clamp.cutTo : opts.to; const tier = isWindowTier(opts.tier) ? opts.tier : undefined; const box = tier ?? EVIDENCE_MAX_HEIGHT; const dest = clipWindowPath(opts.videoDir, from, to, tier); @@ -191,7 +251,7 @@ export async function cutSavedVideoWindow(opts: { // has one; the file keeps the cue-clock name every reader asks for. const mapped = source.clock?.mapped ?? null; const cutFrom = mapped ? mapped.from : from; - const cutTo = mapped ? mapped.to : to; + const cutTo = mapped ? mapped.to : clamp ? clamp.recordingEnd : to; try { const r = await execa(opts.paths.ffmpegBin, evidenceCutArgs(source.container, cutFrom, cutTo, kind, tmp, box), { reject: false, @@ -239,6 +299,18 @@ export async function cutSavedVideoWindow(opts: { }, } : {}), + ...(clamp + ? { + clamp: { + askedTo: clamp.askedTo, + cutTo: clamp.cutTo, + recordingEnd: clamp.recordingEnd, + why: clamp.why, + container: clamp.container, + knownSeconds: clamp.knownSeconds, + }, + } + : {}), }; await writeClipProvenance(opts.videoDir, from, to, provenance, tier); const onClock = mapped @@ -249,7 +321,8 @@ export async function cutSavedVideoWindow(opts: { opts.onLog?.( `Cut ${from.toFixed(2)}–${to.toFixed(2)}${onClock} from the saved video ${source.pointer.file} into ` + `clips/${clipWindowFile(from, to, tier)} (${bytes} bytes` + - `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}); nothing fetched.\n`, + `${height !== null ? `, ${height}p` : ""}${source.pointer.compacted ? ", from the compacted re-encode" : ""}` + + `${clamp ? `; clamped at the recording's end (asked to ${clamp.askedTo.toFixed(2)}): ${clamp.why}` : ""}); nothing fetched.\n`, ); return { file: clipWindowFile(from, to, tier), diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -219,6 +219,28 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " + "10080 (a week). Set in the X account session section of /settings. " + "common/jobs/networkGuard.ts.", + sittingJobs: + "X IN SITTINGS: a sitting begins at a cookie refresh (Refresh cookies or Connect X account on /cookies) and " + + "admits at most this many X job starts — every kind that asks X, counted as X's job cap counts them (each " + + "channel of an X run is one). A start beyond it is refused (at enqueue, or `done`, deferred, at its start: " + + "never a failure that retries): a new Refresh starts the next sitting. A sitting is also ONE KIND, fixed by its " + + "first job: `timelines` (account post fetches, captures, availability checks, one post's import) or `browse` " + + "(trending reads, X search channels' walks, a trending library's captures); a job of the other kind waits for " + + "the next Refresh. The sitting is kept in `.x-session/sitting.json` (rebuilt from the job records if it is " + + "lost) and shown by `pnpm ops get x-session` and on /cookies. ABSENT: 4. Bounded 1-6 in the code " + + "(common/lib/xSitting.ts): no value raises it past 6. common/jobs/xSitting.ts.", + gapMinMinutes: + "THE SHORTEST GAP BEFORE AN X JOB, in minutes: X's queue gap is drawn per job, uniform between this and " + + "`gapMaxMinutes`, after the previous X job ended, and logged (\"waiting 8m41s (a 9m02s gap drawn from 5-12 " + + "min)\"). Never below 5 (the floor is in the code); an explicit `pacing.jobGapSeconds.twitter` above it raises " + + "it. ABSENT: 5. At most 120. common/jobs/queueGap.ts.", + gapMaxMinutes: + "THE LONGEST GAP BEFORE AN X JOB, in minutes (see `gapMinMinutes`). Never less than the minimum plus 3 (a " + + "range of one value is a fixed beat; the spread is in the code). ABSENT: 12. At most 120.", + maxPostsPerJob: + "WHAT ONE X JOB MAY READ: a walk of an account's timeline (sync new, Resume backfill, a full or older walk) or " + + "of an X search reads at most this many posts, then saves its place and ends; the next sitting continues it. " + + "A lower `limit` on the job still applies. ABSENT: 300. Bounded 20-400 in the code (common/lib/xSitting.ts).", }; export type { AutoQueueSettings } from "./autoQueueTypes"; export type { ChannelPriority } from "./channelPriority"; @@ -1988,7 +2010,7 @@ export const siteSettingsSchema = z.object({ "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", ), social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe( - "Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", + "Per-platform settings of the social posts: X's, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`), how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`), how many X jobs one cookie refresh admits (`social.x.sittingJobs`) and the range X's gap is drawn from (`social.x.gapMinMinutes`, `social.x.gapMaxMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", ), sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts @@ -134,7 +134,7 @@ test("doNotClean / excludeTruncatedCheck: a malformed marker still reads as pres test("setDoNotClean / setExcludedFromTruncatedCheck: write, load, remove", async () => { const dir = await scratch(); - await setDoNotClean(dir, true, "kept"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "kept" }); const dnc = await loadDoNotClean(dir); assert.equal(dnc?.note, "kept"); assert.ok(dnc?.setAt); diff --git a/common/lib/storedText-read.d.mts b/common/lib/storedText-read.d.mts @@ -0,0 +1,14 @@ +// Types for ./storedText-read.mjs: the stored-text read path in plain JS. +import type { Stats } from "node:fs"; +export const STORED_TEXT_SUFFIX: ".zst"; +export function isStoredTextName(name: string): boolean; +export function plainNameOf(name: string): string | null; +export function logicalEntries(entries: Iterable<string>): string[]; +export function readdirLogical(dir: string): Promise<string[]>; +export function frameContentSize(head: Uint8Array): number | null; +export function decodeStoredBytes(bytes: Buffer, label?: string): Promise<Buffer>; +export function readStoredText(dir: string, name: string): Promise<Buffer>; +export function readStoredText(dir: string, name: string, encoding: "utf8"): Promise<string>; +export function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer>; +export function statStoredText(dir: string, name: string): Promise<{ form: "plain" | "zst"; stats: Stats }>; +export function storedTextLogicalSize(dir: string, name: string): Promise<number>; diff --git a/common/lib/storedText-read.mjs b/common/lib/storedText-read.mjs @@ -0,0 +1,206 @@ +// STORED TEXT, THE READ PATH IN PLAIN JS — for umtool's bare-node scripts +// (report-to-video's cue source, the clip words, the ingredients rail), which +// cannot import lib/storedText-server.ts. The same rules (lib/storedText.ts): +// a declared file — the raw live chat, or a caption track +// `transcript.<lang>.vtt` — may be on disk as `<name>.zst`, one zstd frame +// whose header carries the content size; THE PLAIN FILE, WHEN PRESENT, IS THE +// TRUTH; a matching listing is LOGICAL (the `.zst` reported under its plain +// name, once). storedText.mjs-twin.test.ts holds this module and the TS one +// equal (names, decode, head, sizes); change one, change the other. +// SERVER-ONLY (node:fs, node:zlib). Read only: nothing here writes. + +import { open, readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import zlib from "node:zlib"; +import { assertZstdSupport } from "./zstdSupport.mjs"; + +// A bare-node script that may read a stored file refuses to start on a Node +// without zstd (REVIEW-1 F3): asked when this module loads. +assertZstdSupport("this script (a reader of stored text)"); + +export const STORED_TEXT_SUFFIX = ".zst"; +const LIVE_CHAT = "transcript.live_chat.json"; +const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/; + +/** @param {string} name */ +export function isStoredTextName(name) { + return name === LIVE_CHAT || CAPTION_RE.test(name); +} + +/** @param {string} name */ +export function plainNameOf(name) { + if (!name.endsWith(STORED_TEXT_SUFFIX)) return null; + const plain = name.slice(0, -STORED_TEXT_SUFFIX.length); + return isStoredTextName(plain) ? plain : null; +} + +/** @param {Iterable<string>} entries */ +export function logicalEntries(entries) { + const out = []; + const seen = new Set(); + for (const e of entries) { + const n = plainNameOf(e) ?? e; + if (seen.has(n)) continue; + seen.add(n); + out.push(n); + } + return out; +} + +/** @param {string} dir */ +export async function readdirLogical(dir) { + return logicalEntries(await readdir(dir).catch(() => [])); +} + +const ZSTD_MAGIC = 0xfd2fb528; + +/** The content size a zstd frame header declares, or null. @param {Uint8Array} head */ +export function frameContentSize(head) { + 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; + const 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; + if (fcsBytes === 1) return head[off]; + if (fcsBytes === 2) return dv.getUint16(off, true) + 256; + if (fcsBytes === 4) return dv.getUint32(off, true); + const n = dv.getUint32(off + 4, true) * 2 ** 32 + dv.getUint32(off, true); + return Number.isSafeInteger(n) ? n : null; +} + +function assertZstd() { + if (typeof zlib.zstdDecompress !== "function" || typeof zlib.createZstdDecompress !== "function") { + throw new Error(`stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`); + } +} + +const isEnoent = (err) => err?.code === "ENOENT" || err?.code === "ENOTDIR"; +const enoent = (dir, name) => + Object.assign(new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`), { code: "ENOENT" }); + +/** A stored file's bytes decoded, its checksum and length checked. @param {Buffer} bytes @param {string} label */ +export async function decodeStoredBytes(bytes, label = "stored text") { + assertZstd(); + const want = frameContentSize(bytes.subarray(0, 18)); + if (want === null) throw new Error(`${label}: not a whole stored-text frame (no content size in the frame header)`); + const out = await new Promise((resolve, reject) => + zlib.zstdDecompress(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) => (err ? reject(err) : resolve(res))), + ).catch((err) => { + throw new Error(`${label}: not a whole stored-text frame (${err.message})`); + }); + if (out.length !== want) throw new Error(`${label}: not a whole stored-text frame (decoded ${out.length} bytes, header says ${want})`); + return out; +} + +/** + * The plain file's bytes when it opens; else (a declared name) the stored form + * decoded; ENOENT when neither opens. + * @param {string} dir @param {string} name @param {"utf8"} [encoding] + */ +export async function readStoredText(dir, name, encoding) { + 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, name + STORED_TEXT_SUFFIX); + let bytes; + 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; +} + +/** The first `bytes` bytes as the plain file has them (decoded from a stored form). */ +export async function readStoredTextHead(dir, name, bytes) { + try { + const fh = await open(path.join(dir, name), "r"); + try { + const buf = Buffer.alloc(bytes); + const { bytesRead } = await fh.read(buf, 0, bytes, 0); + return buf.subarray(0, bytesRead); + } finally { + await fh.close(); + } + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + assertZstd(); + const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX); + let fh; + try { + fh = await open(storedPath, "r"); + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } + const src = fh.createReadStream(); + const dec = zlib.createZstdDecompress(); + const out = []; + let n = 0; + try { + await new Promise((resolve, reject) => { + dec.on("data", (chunk) => { + if (n >= bytes) return; + out.push(chunk); + n += chunk.length; + if (n >= bytes) { + src.unpipe(dec); + src.destroy(); + dec.destroy(); + resolve(); + } + }); + dec.on("end", resolve); + dec.on("error", (err) => reject(new Error(`${storedPath}: not a whole stored-text frame (${err.message})`))); + src.on("error", reject); + src.pipe(dec); + }); + } finally { + src.destroy(); + await fh.close().catch(() => {}); + } + return Buffer.concat(out).subarray(0, bytes); +} + +/** `stat` of the plain name, else of its stored form (which carries the plain file's times). */ +export async function statStoredText(dir, name) { + try { + return { form: "plain", stats: await stat(path.join(dir, name)) }; + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + try { + return { form: "zst", stats: await stat(path.join(dir, name + STORED_TEXT_SUFFIX)) }; + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } +} + +/** The LOGICAL size: the plain file's, or the stored frame header's content size. */ +export async function storedTextLogicalSize(dir, name) { + const s = await statStoredText(dir, name); + if (s.form === "plain") return s.stats.size; + const file = path.join(dir, name + STORED_TEXT_SUFFIX); + const fh = await open(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 Error(`${file}: not a whole stored-text frame (no content size in the frame header)`); + return n; + } finally { + await fh.close(); + } +} diff --git a/common/lib/storedText-read.test.ts b/common/lib/storedText-read.test.ts @@ -0,0 +1,69 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText-read.test.ts +// +// THE PLAIN-JS TWIN (lib/storedText-read.mjs, for umtool's bare-node scripts) +// AND THE TS READ PATH (lib/storedText.ts, lib/storedText-server.ts) GIVE THE +// SAME ANSWERS: which names are declared, the logical listing, the decoded +// bytes and head, the logical size, and a truncated frame refused. Change one, +// change the other. Temp dirs, synthetic names. + +import * as ts from "./storedText"; +import * as tsServer from "./storedText-server"; +import * as mjs from "./storedText-read.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-read-twin-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const NAMES = [ + "transcript.live_chat.json", + "transcript.en.vtt", + "transcript.en-orig.vtt", + "transcript.es.vtt", + "transcript.tmp-77.vtt", + "transcript.json", + "transcript.cues.json", + "metadata.info.json", + "transcript.en.vtt.part", + "transcript.en.srv3", +]; + +test("the declared names and the logical listing are the same in both", () => { + for (const n of NAMES) { + assert.equal(mjs.isStoredTextName(n), ts.isStoredTextName(n), n); + assert.equal(mjs.plainNameOf(`${n}.zst`), ts.plainNameOf(`${n}.zst`), n); + } + const listing = [...NAMES, ...NAMES.map((n) => `${n}.zst`), "x.zst"]; + assert.deepEqual(mjs.logicalEntries(listing), ts.logicalEntries(listing)); +}); + +test("the read, the head, the stat and the logical size are the same in both", async () => { + const dir = path.join(ROOT, "v1"); + await mkdir(dir, { recursive: true }); + const body = "WEBVTT\n\n" + "00:00:00.000 --> 00:00:01.000\nline é\n\n".repeat(400); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), await tsServer.encodeStoredBytes(Buffer.from(body))); + await writeFile(path.join(dir, "transcript.es.vtt"), body); + for (const n of ["transcript.en.vtt", "transcript.es.vtt"]) { + assert.equal(await mjs.readStoredText(dir, n, "utf8"), await tsServer.readStoredText(dir, n, "utf8"), n); + assert.deepEqual(await mjs.readStoredTextHead(dir, n, 2048), await tsServer.readStoredTextHead(dir, n, 2048), n); + assert.equal(await mjs.storedTextLogicalSize(dir, n), await tsServer.storedTextLogicalSize(dir, n), n); + assert.equal((await mjs.statStoredText(dir, n)).stats.mtimeMs, (await tsServer.statStoredText(dir, n)).stats.mtimeMs, n); + } + assert.equal(await mjs.readStoredText(dir, "transcript.en.vtt", "utf8"), body); + assert.deepEqual(await mjs.readdirLogical(dir), await tsServer.readdirLogical(dir)); + await assert.rejects(mjs.readStoredText(dir, "transcript.de.vtt"), { code: "ENOENT" }); +}); + +test("a truncated stored frame is refused by both, never read short", async () => { + const dir = path.join(ROOT, "v2"); + await mkdir(dir, { recursive: true }); + const whole = await tsServer.encodeStoredBytes(Buffer.from("WEBVTT\n\n".repeat(5000))); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), whole.subarray(0, Math.floor(whole.length / 2))); + await assert.rejects(mjs.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/); + await assert.rejects(tsServer.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/); +}); diff --git a/common/lib/storedText-server.ts b/common/lib/storedText-server.ts @@ -59,12 +59,31 @@ export function assertZstdAvailable(): void { typeof z.createZstdCompress !== "function" || typeof z.createZstdDecompress !== "function" ) { - throw new Error( + throw new StoredTextUnsupportedError( `stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`, ); } } +// This Node cannot read a stored file at all (no zstd). Every process asks at +// boot (lib/zstdSupport.mjs) and refuses to start; this is the backstop. +export class StoredTextUnsupportedError extends Error { + constructor(message: string) { + super(message); + this.name = "StoredTextUnsupportedError"; + } +} + +// A STORED FILE THAT IS THERE AND CANNOT BE READ — a frame that does not +// decode, or a Node without zstd — is an ERROR, never "no text" (REVIEW-1 F3, +// captions lane): a reader that skips it as it skips a missing file would let +// the index write a record with no cues over a readable one, or a lane read +// the video as needing a transcript. Readers that tolerate a missing or +// malformed track RETHROW these. +export function isStoredTextReadError(err: unknown): boolean { + return err instanceof StoredTextCorruptError || err instanceof StoredTextUnsupportedError; +} + export const STORED_TEXT_LEVEL = 9; // The compressor's options for a source of `size` bytes: level 9, checksum on, @@ -198,6 +217,63 @@ export async function readStoredText( return encoding ? out.toString(encoding) : out; } +// THE HEAD of a declared file: its first `bytes` bytes as the plain file has +// them — read from the plain file when it opens, else DECODED from the stored +// form (the first bytes of a zstd frame are not text: a sniff of them would +// answer wrong, not absent — the caption provenance sniff, the word-timing +// sniff). Only the head is decoded; the frame's checksum is checked by a whole +// read, not here. ENOENT when neither form opens. +export async function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer> { + try { + const fh = await open(path.join(dir, name), "r"); + try { + const buf = Buffer.alloc(bytes); + const { bytesRead } = await fh.read(buf, 0, bytes, 0); + return buf.subarray(0, bytesRead); + } finally { + await fh.close(); + } + } catch (err) { + if (!isEnoent(err) || !isStoredTextName(name)) throw err; + } + const storedPath = path.join(dir, storedNameOf(name)); + let fh; + try { + fh = await open(storedPath, "r"); + } catch (err) { + if (isEnoent(err)) throw enoent(dir, name); + throw err; + } + const src = fh.createReadStream(); + const dec = createStoredTextDecompressor(); + const out: Buffer[] = []; + let n = 0; + try { + await new Promise<void>((resolve, reject) => { + const finish = () => resolve(); + dec.on("data", (chunk: Buffer) => { + if (n >= bytes) return; + out.push(chunk); + n += chunk.length; + if (n >= bytes) { + src.unpipe(dec); + src.destroy(); + dec.destroy(); + finish(); + } + }); + dec.on("end", finish); + dec.on("error", (err) => reject(new StoredTextCorruptError(storedPath, err.message))); + src.on("error", reject); + src.pipe(dec); + }); + } finally { + src.destroy(); + await fh.close().catch(() => {}); + } + return Buffer.concat(out).subarray(0, bytes); +} + export type StoredTextStat = { // Which form answered. form: "plain" | "zst"; diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts @@ -45,7 +45,9 @@ import { import { keptChatCaptureName } from "./mediaTier"; import { onDrive, stalledLocationForPath } from "./storageHealth"; import { LIVE_RECORDING_FILENAME } from "./liveCapture"; -import { isStoredTextName, plainNameOf, storedNameOf } from "./storedText"; +import { isStoredCaptionName, isStoredTextName, plainNameOf, storedNameOf } from "./storedText"; +import { parseVtt } from "./vtt"; +import { unpinAfterPickDeleted } from "./transcriptPin-server"; import { StoredTextCorruptError, createStoredTextCompressor, @@ -55,10 +57,50 @@ import { // 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); +// nothing else ever writes one) AND every leftover of a stopped run on it — a +// temp, and above all a set-aside original (`.<name>.retire-…`), which is a +// whole copy: left behind, the next compress run would find the name free and +// could bring the deleted file back (REVIEW-1 F2, captions lane). Under the +// file's lock, so no run of ours is between its steps while the file goes; +// a run that holds it is waited for (a few seconds), then this throws and +// nothing is removed. Missing is not an error. +// +// A REFUSAL, NEVER A THROW, when it cannot take the lock (REVIEW-2 N2): a run +// that holds it past the wait, or a disk so full the lock's few bytes do not +// fit. Then NOTHING is removed and `{refused}` says why; the caller reports it. +export type RemoveStoredTextOutcome = { removed: true } | { refused: string }; + +export async function removeStoredText(videoDir: string, name: string): Promise<RemoveStoredTextOutcome> { + for (let attempt = 0; ; attempt++) { + let done: boolean; + try { + done = await withFileLock(videoDir, name, false, async () => { + await removeMediaFile(videoDir, storedNameOf(name)); + await removeMediaFile(videoDir, name); + await removeLeftoversOf(videoDir, name); + return true; + }); + } catch (err) { + if (err instanceof LockUnavailableError) return { refused: `${name} not deleted: ${err.message}` }; + throw err; + } + if (done) return { removed: true }; + if (attempt >= 40) { + return { refused: `${name} not deleted: it is being compressed or restored right now — try again in a moment` }; + } + await new Promise((r) => setTimeout(r, 250)); + } +} + +// Every leftover of a run on `name` in the video dir — temps and set-asides, +// whoever named them — each through removeMediaFile (a set-aside may be a +// tier link: its bytes go too). Only for a deleter: the file is being removed +// on purpose, so a copy of it must not survive to be adopted later. +async function removeLeftoversOf(videoDir: string, name: string): Promise<void> { + const re = leftoverRes(name); + for (const e of await readdir(videoDir).catch(() => [] as string[])) { + if (re.temp.test(e) || re.retire.test(e)) await removeMediaFile(videoDir, e); + } } // ── THE COMPRESSOR ────────────────────────────────────────────────────────── @@ -426,18 +468,30 @@ function lockHolderRunning(owner: Owner): boolean { } // The dir lock, or null when a live run holds it. Returns its release. +// The dir lock could not be made at all — a full disk (ENOSPC), a read-only +// one. Nothing was done; a deleter answers it as a refusal (REVIEW-2 N2). +export class LockUnavailableError extends Error { + constructor(videoDir: string, cause: Error) { + super(`the stored-text lock cannot be made in ${path.basename(videoDir)} (${(cause as NodeJS.ErrnoException).code ?? cause.message})`); + this.name = "LockUnavailableError"; + } +} + 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 { + // Inside the try whose `finally` removes it: on a FULL disk `wx` creates + // the file and then fails to write it, and the empty temp must not stay + // behind, one per file visited (REVIEW-2 N2). + 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 new LockUnavailableError(videoDir, err as Error); + } for (let attempt = 0; attempt < 3; attempt++) { try { await link(tmp, lock); @@ -526,6 +580,20 @@ export function hasStoredTextLeftover(entries: readonly string[], name: string): return entries.some((e) => re.temp.test(e) || re.retire.test(e)); } +// The declared names a listing holds a stopped run's leftover FOR — a caption +// killed after its original was set aside has neither form under its name, +// only `.transcript.en.vtt.retire-<pid>-<token>`, and the job's survey must +// still visit it (`compress-text` captions, which finds names by listing). +export function storedTextLeftoverNames(entries: readonly string[]): string[] { + const out = new Set<string>(); + for (const e of entries) { + const m = /^\.(.+?)(?:\.zst)?\.(?:compressing|stlink|restoring|retire)-\d+(?:-[0-9a-z]+)?$/.exec(e); + if (!m || !isStoredTextName(m[1])) continue; + if (hasStoredTextLeftover([e], m[1])) out.add(m[1]); + } + return [...out].sort(); +} + type RunCtx = { pid: number; token: string; @@ -582,8 +650,22 @@ async function repairLeftovers( 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. + // The original was set aside and not removed. It is ADOPTED — the file + // again, verified like any plain file — ONLY when it is plainly an + // interrupted run's of this compressor (its name carries the run's pid + // AND start token, and that process is gone: checked above) AND no + // deletion happened since: the stored form the run made BEFORE it set + // the original aside is still here. Every deleter removes both forms and + // the set-aside together, so a set-aside with no stored form beside it + // means the file was deleted some other way: it is NOT brought back but + // kept, listed for a person (REVIEW-1 F2, captions lane). + const z = await entryAt(videoDir, storedNameOf(name)); + if (owner.token === undefined || z.kind === "none") { + ctx.log( + ` ${e} kept for a person: ${owner.token === undefined ? "a set-aside named before runs carried a start token" : `no ${storedNameOf(name)} beside it — deleted since?`}`, + ); + return skip("retired-kept", `${e}: not adopted (${owner.token === undefined ? "no start token" : "no stored form"})`); + } await rename(path.join(videoDir, e), path.join(videoDir, name)); ctx.log(` restored ${e} as ${name}`); continue; @@ -747,6 +829,9 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions } const sd = await digestOf(bytesPath, { throttle: opts.throttle }); if (zd.sha !== sd.sha || zd.bytes !== sd.bytes) { + // Recorded, so the job's survey does not count the pair as work on every + // run (REVIEW-1 N2): it waits for a person until either form changes. + await recordBothDiffer(videoDir, name).catch(() => {}); return skip("both-differ", `${name} (${sd.bytes} bytes) and ${stored} (${zd.bytes} bytes) differ`); } // The same content: given the plain file's times, exactly. @@ -786,7 +871,19 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions 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); + try { + await rename(p.path, retiredPath); + } catch (err) { + if (errCode(err) !== "ENOENT") throw err; + // The original was removed since its last look. Every in-app deleter + // holds this file's lock, so what removed it is OUTSIDE the lock — + // yt-dlp's own overwrite in a re-download, which deletes the plain file + // and fetches after. The verified stored copy is KEPT (REVIEW-2 N3): if + // that fetch fails (a 429, a video gone) it is the caption; a new plain + // file landing later is `same` or `both-differ`, both safe. + log(` ${name} was removed while it was being compressed: the verified stored copy is kept`); + return { status: "changed" }; + } crash("retired"); const nowL = await lstatOrNull(retiredPath); const nowS = await stat(retiredPath).catch(() => null); @@ -1362,6 +1459,188 @@ export async function keepPlainAsCapture( }); } +// ── BOTH FORMS DIFFER: RECORDED ONCE, FOR A PERSON (REVIEW-1 N2) ─────────── +// +// A pair the compressor refused (`both-differ`) is written to the CHANNEL's +// `.stored-text-differs.json` (beside its config — the video dir is left +// exactly as it was) with each form's identity (inode, size, mtime). While both +// forms are exactly those files, the job's survey counts the pair as WAITING +// FOR A PERSON — listed by the dry run, never work, never refused again. Any +// change to either form (a person settles it on the files card, a writer +// lands a new one) makes the entry stale and the pair is work again. A record, +// not a lock: nothing is kept from being read or deleted by it. Written only +// by the compress-text job, one per channel at a time. +export const STORED_TEXT_DIFFERS_FILENAME = ".stored-text-differs.json"; + +type FormIdent = { ino: number; size: number; mtimeMs: number }; +type DiffersRecord = Record<string, { plain: FormIdent; stored: FormIdent; at: string }>; + +const channelDirOf = (videoDir: string) => path.dirname(path.dirname(videoDir)); +const differsKey = (videoDir: string, name: string) => `${path.basename(videoDir)}/${name}`; + +async function formIdents(videoDir: string, name: string): Promise<{ plain: FormIdent; stored: FormIdent } | null> { + const [p, z] = await Promise.all([lstatOrNull(path.join(videoDir, name)), lstatOrNull(path.join(videoDir, storedNameOf(name)))]); + if (!p || !z) return null; + const id = (st: Stats): FormIdent => ({ ino: st.ino, size: st.size, mtimeMs: st.mtimeMs }); + return { plain: id(p), stored: id(z) }; +} + +// The channel's record (one read per survey). +export async function readStoredTextDiffers(channelDir: string): Promise<DiffersRecord> { + try { + const v = JSON.parse(await readFile(path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME), "utf8")) as unknown; + return v && typeof v === "object" && !Array.isArray(v) ? (v as DiffersRecord) : {}; + } catch { + return {}; + } +} + +async function recordBothDiffer(videoDir: string, name: string): Promise<void> { + const ids = await formIdents(videoDir, name); + if (!ids) return; + const channelDir = channelDirOf(videoDir); + const rec = await readStoredTextDiffers(channelDir); + rec[differsKey(videoDir, name)] = { ...ids, at: new Date().toISOString() }; + const file = path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME); + const tmp = `${file}.${process.pid}-${selfToken()}`; + await writeFile(tmp, JSON.stringify(rec, null, 1)); + await rename(tmp, file); +} + +// Is this pair the one recorded as differing — both forms the very files +// that were compared? (The survey's question; a stat each, no content read.) +export async function bothDifferRecorded(record: DiffersRecord, videoDir: string, name: string): Promise<boolean> { + const rec = record[differsKey(videoDir, name)]; + if (!rec) return false; + const ids = await formIdents(videoDir, name); + const same = (a: FormIdent, b: FormIdent) => a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs; + return !!ids && same(ids.plain, rec.plain) && same(ids.stored, rec.stored); +} + +// ── A RE-DOWNLOAD OVER A STORED CAPTION (REVIEW-1 F1 of the captions lane) ── +// +// A managed re-download of a youtube-handling video fetches its captions +// again (AGENTS.md: "YouTube's subtitles are fetched again first, as on any +// re-download"): yt-dlp, run without `--no-overwrites`, replaces a plain +// caption it finds. Over a track stored compressed it finds none, and lands +// a new plain file beside the stored one. Main's rule is kept — the new +// caption becomes the track — with one guarantee the overwrite never had: +// the stored copy goes only AFTER the new file is whole and is a caption. +// Per track that was stored-only before the pass: +// +// - nothing landed, or a `.part` of it (a fetch that did not finish): the +// stored track is untouched (a video that is gone returns nothing); +// - a whole new file with the SAME content: the new plain file goes, the +// stored form stays — no churn, its mtime unchanged, the index sees +// nothing; +// - a whole new file with OTHER content that parses to at least one cue: it +// is the track (as an overwrite was on main), and only then the stored +// form is removed; +// - an empty file, or one with no cue: dropped, the stored track untouched; +// - a stored form that does not decode: both kept, for a person. +// +// Each outcome is a line in the job log. + +// A test's seam: called after the new plain file and its dir are fsynced and +// before the stored copy is removed (the order is what REVIEW-2 N1 asks). +let syncedForTest: ((videoDir: string, name: string) => Promise<void> | void) | undefined; +export function setRefetchSyncedHookForTest(fn: typeof syncedForTest): void { + syncedForTest = fn; +} + +export type RefetchedCaptionOutcome = { + track: string; + name: string; + status: "nothing-landed" | "partial" | "same" | "replaced" | "dropped-empty" | "kept-both" | "busy" | "no-stored"; + detail?: string; +}; + +export async function settleRefetchedCaptions( + videoDir: string, + storedTracks: readonly string[], + onLog: (line: string) => void = () => {}, +): Promise<RefetchedCaptionOutcome[]> { + const out: RefetchedCaptionOutcome[] = []; + for (const track of storedTracks) { + const name = `transcript.${track}.vtt`; + if (!isStoredCaptionName(name)) continue; + const r = await withFileLock<RefetchedCaptionOutcome>( + videoDir, + name, + { track, name, status: "busy" }, + () => settleOne(videoDir, track, name), + ); + out.push(r); + const say: Record<RefetchedCaptionOutcome["status"], string> = { + "nothing-landed": "nothing was fetched; the stored track is kept", + partial: "the fetch did not finish (a .part); the stored track is kept", + same: "fetched again with the same content; the stored track is kept (the new copy dropped)", + replaced: "fetched again with new content; the new track replaces the stored one", + "dropped-empty": "fetched again with no cues; dropped, the stored track is kept", + "kept-both": "fetched again; the stored track could not be read, so both are kept for a person", + busy: "being compressed or restored right now; left as it is", + "no-stored": "no stored form any more; left as it is", + }; + onLog(`Captions ${name}: ${say[r.status]}${r.detail ? ` (${r.detail})` : ""}.\n`); + } + return out; +} + +async function settleOne(videoDir: string, track: string, name: string): Promise<RefetchedCaptionOutcome> { + const base = { track, name }; + const entries = await readdir(videoDir).catch(() => [] as string[]); + if (entries.some((e) => e.startsWith(`${name}.part`))) return { ...base, status: "partial" }; + const plain = await entryAt(videoDir, name); + if (plain.kind === "none") return { ...base, status: "nothing-landed" }; + const z = await storedPathOf(videoDir, name); + if (!z) return { ...base, status: "no-stored" }; + let fresh: Buffer; + try { + fresh = await readFile(path.join(videoDir, name)); + } catch (err) { + return { ...base, status: "kept-both", detail: `the new file does not open: ${(err as Error).message}` }; + } + let zd: Digest; + try { + zd = await digestOf(z, { decode: true }); + } catch (err) { + return { ...base, status: "kept-both", detail: (err as Error).message }; + } + const fd = { sha: createHash("sha256").update(fresh).digest("hex"), bytes: fresh.length }; + if (fd.sha === zd.sha && fd.bytes === zd.bytes) { + await removeMediaFile(videoDir, name); + await fsyncDir(videoDir); + return { ...base, status: "same" }; + } + let cues = 0; + try { + cues = fresh.length > 0 ? parseVtt(fresh.toString("utf8")).length : 0; + } catch { + cues = 0; + } + if (cues === 0) { + await removeMediaFile(videoDir, name); + await fsyncDir(videoDir); + return { ...base, status: "dropped-empty", detail: `${fresh.length} bytes` }; + } + // The new track is whole (yt-dlp has exited; no `.part`) and a caption: it + // is the track, as an overwrite was on main. Its data and its name are made + // DURABLE first — yt-dlp never fsyncs, and a power cut after the stored + // copy's removal must not leave a zero-length caption (REVIEW-2 N1). Only + // then the stored one goes. + const fh = await open(path.join(videoDir, name), "r"); + try { + await fh.sync(); + } finally { + await fh.close(); + } + await fsyncDir(videoDir); + await syncedForTest?.(videoDir, name); + await removeMediaFile(videoDir, storedNameOf(name)); + await fsyncDir(videoDir); + return { ...base, status: "replaced", detail: `${cues} cues, ${fresh.length} bytes` }; +} + // ── 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 @@ -1373,18 +1652,38 @@ export async function keepPlainAsCapture( export type RemoveFormOutcome = { removed: string[]; kept?: { name: string; same: "same" | "differs" | "unreadable" }; + // The plain transcript.en.vtt (a "Set as transcript" pick) went beside a + // stored one of other content: the pin went too (transcriptPin-server.ts). + unpinned?: boolean; }; -export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> { +export async function removeStoredTextForm( + videoDir: string, + filename: string, +): Promise<RemoveFormOutcome | "busy" | { refused: string }> { const plain = plainNameOf(filename) ?? filename; if (!isStoredTextName(plain)) { await removeMediaFile(videoDir, filename); return { removed: [filename] }; } + try { + return await removeStoredTextFormLocked(videoDir, filename, plain); + } catch (err) { + // No lock could be made (a full disk): nothing was removed (REVIEW-2 N2). + if (err instanceof LockUnavailableError) return { refused: `${filename} not deleted: ${err.message}` }; + throw err; + } +} + +async function removeStoredTextFormLocked(videoDir: string, filename: string, plain: string): Promise<RemoveFormOutcome | "busy"> { return withFileLock<RemoveFormOutcome | "busy">(videoDir, plain, "busy", async () => { const other = filename === plain ? storedNameOf(plain) : plain; + // A stopped run's leftovers on the name go with any form deleted: a + // set-aside original left behind could be adopted by the next run and + // bring the deleted file back (REVIEW-1 F2, captions lane). if (!(await lstatOrNull(path.join(videoDir, other)))) { await removeMediaFile(videoDir, filename); + await removeLeftoversOf(videoDir, plain); return { removed: [filename] }; } const z = await storedPathOf(videoDir, plain); @@ -1394,7 +1693,12 @@ export async function removeStoredTextForm(videoDir: string, filename: string): ]); const same = !pd || !zd ? "unreadable" : pd.sha === zd.sha && pd.bytes === zd.bytes ? "same" : "differs"; await removeMediaFile(videoDir, filename); + await removeLeftoversOf(videoDir, plain); await fsyncDir(videoDir); - return { removed: [filename], kept: { name: other, same } }; + // The pick deleted, YouTube's own stored `en` beside it: the pin goes too, + // or it would rank that very track first (REVIEW-1 N1, captions lane). + const unpinned = + filename === "transcript.en.vtt" && same === "differs" ? await unpinAfterPickDeleted(videoDir) : false; + return { removed: [filename], kept: { name: other, same }, ...(unpinned ? { unpinned: true } : {}) }; }); } diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts @@ -166,7 +166,12 @@ for (const tiered of [false, true]) { 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); + // Nothing of the video's is touched; the refusal is RECORDED beside the + // channel's config (REVIEW-1 N2 of the captions lane: listed once, not + // work again until a form changes). + const differs = path.join(f.channelDir, ".stored-text-differs.json"); + assert.deepEqual((await tree(f.channelDir)).filter((l) => !l.includes(".stored-text-differs.json")), before); + assert.deepEqual(Object.keys(JSON.parse(await readFile(differs, "utf8"))), [`vid00000001/${CHAT}`]); assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read"); }); @@ -461,7 +466,9 @@ test("an abort mid-write and an appending writer: the original is untouched, no test("not a declared name: refused", async () => { const f = await fixture(false); - const out = await compressStoredText(f.videoDir, "transcript.en.vtt"); + // (A caption track is declared since lane text-compress-captions; the + // metadata is not.) + const out = await compressStoredText(f.videoDir, "metadata.info.json"); assert.equal(out.status === "skipped" && out.reason, "not-declared"); }); diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -56,6 +56,11 @@ const ALLOWED: { file: string; code: RegExp; why: string }[] = [ why: "the migration's own survey: each form's PHYSICAL size, after storedFormsIn said which are there", }, { + file: "common/controller/compressText.ts", + code: /if \(kind === "live-chat"\) return \[LIVE_CHAT_FILENAME\];/, + why: "the migration's kind → declared names table; every read of the name it returns is the survey's storedFormsIn or the compressor's", + }, + { 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)", @@ -84,6 +89,7 @@ const DEFINITIONS = new Set([ "common/lib/storedText.ts", "common/lib/storedText-server.ts", "common/lib/storedText-write-server.ts", + "common/lib/storedText-read.mjs", ]); async function walk(dir: string, out: string[]): Promise<void> { @@ -184,11 +190,19 @@ test("every app line naming the raw live chat goes through the stored-text helpe const SUB_FLAGS = /(["'])--(?:sub-langs?|all-subs|write-subs|write-auto-subs|write-automatic-subs)\1|["'`]--(?:sub-langs?)=|^\s*["'`]live_chat["'`],?\s*$/; +// CAPTIONS TOO (lane text-compress-captions): a caption track stored as +// `transcript.<lang>.vtt.zst` is fetched again by any pass that asks for it. +// The missing-subs pass (`--no-overwrites`, where main skipped a present +// track) excludes the stored tracks by code; the managed download (no +// `--no-overwrites`, where main replaced it) fetches them and settles each +// after the pass. Both take the stored tracks from the PHYSICAL listing. 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)", + guard: + "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs; a stored caption IS fetched " + + "again (main's re-download rule) and its caller settles it after the pass (settleRefetchedCaptions)", + test: "controller/storedText.chat.test.ts (youtubeHandlingArgs); ytdlp/captionsRefetch.test.ts", }, liveChatOnlyArgs: { file: "common/ytdlp/downloadOneManaged.ts", @@ -197,8 +211,8 @@ const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string } }, 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)", + guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat, each stored caption excluded by code", + test: "controller/storedText.chat.test.ts (subLangsForVideo); controller/storedText.captions.test.ts (subLangsForVideo)", }, }; @@ -258,3 +272,157 @@ test("every yt-dlp argv that can write the raw chat is a pinned builder, and eve "be tested, and be counted in CALLERS", ); }); + +// ── THE THIRD GATE: CAPTIONS (lane text-compress-captions) ───────────────── +// +// A caption track may be on disk as `transcript.<lang>.vtt.zst`. A raw read, +// stat or delete of a caption NAME (its constants, a `transcript.<x>.vtt` +// literal, a record's `ytVttFile` / `vttFile` / `picked.filename`) outside the +// stored-text helpers sees a compressed track as ABSENT — and the three +// misses that cost the most are a re-fetch of the URL (destinationExists), an +// audio download and a transcription for a video that has captions +// (hasAnyTranscriptOnDisk), and a purge that leaves the `.zst` (the captions +// come back). Two tripwires, like the first gate: +// +// 1. A LINE THAT CALLS A RAW FS READ, STAT OR DELETE and names a caption in +// the same statement (the line or the two before it) must also name a +// sanctioned reader or deleter there, or be ALLOWED_CAPTION with its +// reason. Writes are not gated: every writer writes the plain name, which +// is the truth (lib/storedText.ts). +// 2. A FILE THAT APPLIES A CAPTION RULE to a listing (`englishVttsByPreference`, +// `resolvePrimaryVtt`, `captionInputs`, `listTranscriptVtts`, …) must take +// a LOGICAL listing somewhere in it (`readVideoFiles`, `logicalEntries`, +// `readdirLogical`, `logicalFileNames`, the umtool twin) — a raw readdir +// fed to the rule loses every stored track — or be a RULE_ONLY file with +// its reason (it is handed a logical listing by its callers). +// +// WHAT THEY CANNOT SEE: a variable holding a caption name read far from where +// it was named; a listing passed through a parameter from a raw readdir in +// another file; a shell or Python reader. + +const CAPTION_NAMES = + /\b(?:VTT_FILENAME|ORIG_VTT_FILENAME|CANONICAL_VTT|EN_ORIG_TRACK)\b|transcript\.[A-Za-z-]*\.vtt(?![.\w])|\.ytVttFile\b|\bvttFile\b|picked\.filename\b/; +const RAW_FS = /\b(?:readFile|readFileSync|stat|statSync|lstat|lstatSync|open|openSync|createReadStream|rm|rmSync|unlink|unlinkSync|copyFile|rename|access|existsSync|removeMediaFile|renameMediaFile)\s*\(/; +const CAPTION_SANCTIONED = + /\b(?:readStoredText|readStoredTextHead|statStoredText|storedTextMtimeMs|storedTextExists|storedTextForms|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|decodeStoredBytes|captionBytes|readEnglishVttCues|readEnglishVttTracks|readVttProvenance|resolveVttProvenance)\b/; + +const ALLOWED_CAPTION: { file: string; code: RegExp; why: string }[] = [ + { + file: "common/lib/localMediaCommit-server.ts", + code: /const current = await lstat\(target\);/, + why: "the new record's DIRECTORY, checked before each link of a commit that made it (mkdir, EEXIST refused): no stored form can be in it", + }, +]; + +// The caption rules, and the files that define them. +const CAPTION_RULES = + /\b(?:englishVttsByPreference|resolvePrimaryVtt|captionInputs|listTranscriptVtts|readEnglishVttCues|readEnglishVttTracks|mayHaveAltTracks|resolveCaptionsProvenance)\s*\(/; +const LOGICAL_LISTING = /\b(?:readVideoFiles|logicalEntries|readdirLogical|logicalFileNames)\b/; +const RULE_ONLY: Record<string, string> = { + "common/lib/videoStatus.ts": "the rules themselves (readEnglishVttCues makes its listing logical)", +}; + +test("every app line that reads, stats or deletes a caption track goes through the stored-text helpers", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel)) continue; + for (let i = 0; i < lines.length; i++) { + const code = codeOnly(lines[i]); + if (!RAW_FS.test(code)) continue; + const statement = [lines[i - 2] ?? "", lines[i - 1] ?? "", code].map(codeOnly).join("\n"); + if (!CAPTION_NAMES.test(statement)) continue; + if (CAPTION_SANCTIONED.test(statement)) continue; + if (ALLOWED_CAPTION.some((a) => a.file === rel && a.code.test(code))) continue; + offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`); + } + } + assert.deepEqual( + offenders, + [], + "read, stat or delete a caption track through lib/storedText(-server|-write-server).ts — it may be stored as .zst", + ); +}); + +test("every file that applies a caption rule to a listing takes a logical listing", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel) || RULE_ONLY[rel]) continue; + const code = lines.map(codeOnly); + const uses = code.findIndex((l) => CAPTION_RULES.test(l) && !/^\s*(?:export\s+)?(?:async\s+)?function\b/.test(l)); + if (uses < 0) continue; + if (code.some((l) => LOGICAL_LISTING.test(l))) continue; + offenders.push(`${rel}:${uses + 1}: ${lines[uses].trim()}`); + } + assert.deepEqual( + offenders, + [], + "a caption rule fed a raw readdir loses every track stored as .zst: list with readVideoFiles / readdirLogical / logicalEntries", + ); +}); + +// ── THE CAPTIONS GATES, TIGHTER (REVIEW-1 N8 of the captions lane) ───────── +// +// 5. In a file that applies a caption rule, EVERY readdir of a video dir is +// logical (wrapped in logicalEntries / readdirLogical on its line or the +// next) or listed below with why: a raw listing fed to the rule loses every +// stored track. A listing of a channel's or the index's own dirs (not a +// video dir) is not asked. +// 6. A caption PARSE (`parseVtt`, `hasWordTiming`, `vttWordStarts`, +// `sniffVttProvenance`) fed by a raw `readFile` in the same statement: +// the bytes of a stored track are zstd, not text. +// 7. The managed download's subtitle pass fetches stored captions again +// (main's rule): the file that calls its argv builder must settle them. + +const NOT_A_VIDEO_DIR = /readdir\(\s*(?:channelsDir|dataDir|paths\.|\w*OutDir\b|\w*ChannelDir\b|channelDir\b|summariesOut\b|transcriptsOutDir)/; +const RAW_VIDEO_READDIR: { file: string; code: RegExp; why: string }[] = [ + { file: "common/controller/channelSnapshot.ts", code: /entries = await readdir\(dir\);/, why: "dirFileBytes: the clips/ cache's files, never a caption" }, + { file: "common/controller/copiesLane.ts", code: /readdir: \(p\) => readdir\(p\)/, why: "the io seam; signatureOf makes the listing logical" }, + { file: "common/controller/findClips.ts", code: /const entries = await readdir\(videoDir\)/, why: "media and sidecar names; the transcript pick wraps it in logicalEntries" }, + { file: "editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts", code: /const entries = await readdir\(videoDir\)\.catch/, why: "the audio files only (isRealAudioFile)" }, + { file: "editor/app/channels/[slug]/videos/[id]/videoActions.ts", code: /const (?:firstEntries|entries) = await readdir\((?:videoDir|resolved)\)/, why: "audio and containers; the captions check wraps it in logicalEntries" }, +]; +const PARSE = /\b(?:parseVtt|hasWordTiming|vttWordStarts|sniffVttProvenance)\s*\(/; +const PARSE_RAW_ALLOWED: { file: string; code: RegExp; why: string }[] = [ + { file: "common/controller/copiesLane.ts", code: /for \(const cue of parseVtt\(text\)\)/, why: "text from io.readCaption (readStoredText); io.readFile only in a test's seam" }, +]; + +test("in a file that applies a caption rule, every readdir of a video dir is logical", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel) || RULE_ONLY[rel]) continue; + const code = lines.map(codeOnly); + if (!code.some((l) => CAPTION_RULES.test(l) || /\b(?:isTranscriptVtt|isEnglishVtt|isTranscriptVttName)\s*\(/.test(l))) continue; + code.forEach((l, i) => { + if (!/\breaddir\s*\(/.test(l) || NOT_A_VIDEO_DIR.test(l)) return; + if (/logicalEntries\(|readdirLogical/.test(l + (code[i + 1] ?? ""))) return; + if (RAW_VIDEO_READDIR.some((a) => a.file === rel && a.code.test(l))) return; + offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`); + }); + } + assert.deepEqual(offenders, [], "a raw readdir beside a caption rule: make it logical (readdirLogical / logicalEntries) or list it with why"); +}); + +test("no caption parse is fed a raw readFile", async () => { + const offenders: string[] = []; + for (const { rel, lines } of await appFiles()) { + if (DEFINITIONS.has(rel) || rel === "common/lib/vtt.ts") continue; + const code = lines.map(codeOnly); + code.forEach((l, i) => { + if (!PARSE.test(l)) return; + const st = [code[i - 2] ?? "", code[i - 1] ?? "", l].join("\n"); + if (!/\breadFile(?:Sync)?\s*\(/.test(st)) return; + if (PARSE_RAW_ALLOWED.some((a) => a.file === rel && a.code.test(l))) return; + offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`); + }); + } + assert.deepEqual(offenders, [], "parse a caption read through readStoredText — its bytes may be zstd"); +}); + +test("the file that builds the managed download's subtitle argv settles stored captions after the pass", async () => { + for (const { rel, lines } of await appFiles()) { + const text = lines.map(codeOnly).join("\n"); + if (!/\byoutubeHandlingArgs\s*\(/.test(text.replace(/export function youtubeHandlingArgs\s*\(/, ""))) continue; + assert.match(text, /\bsettleRefetchedCaptions\s*\(/, `${rel}: calls youtubeHandlingArgs without settleRefetchedCaptions`); + assert.match(text, /\bstoredOnlyCaptionTracks\s*\(/, `${rel}: settles without the PHYSICAL listing's stored tracks`); + } +}); diff --git a/common/lib/storedText.test.ts b/common/lib/storedText.test.ts @@ -12,6 +12,7 @@ import path from "node:path"; import { STORED_TEXT_NAMES, + isStoredCaptionName, isStoredTextName, listingHas, logicalEntries, @@ -33,7 +34,7 @@ import { StoredTextCorruptError, } from "./storedText-server"; import { classifyEntry, isScratchEntry, isTierable, LIVE_CHAT_STORED_FILENAME } from "./mediaTier"; -import { LIVE_CHAT_FILENAME } from "./videoStatus"; +import { LIVE_CHAT_FILENAME, isTranscriptVtt } from "./videoStatus"; const ROOT = await mkdtemp(path.join(tmpdir(), "stored-text-")); test.after(() => rm(ROOT, { recursive: true, force: true })); @@ -47,25 +48,50 @@ async function dir(name: string): Promise<string> { return d; } -test("the declared names: the live chat only, its stored form `.zst`", () => { +test("the declared names: the live chat and every caption track, each with its stored form `.zst`", () => { assert.deepEqual([...STORED_TEXT_NAMES], [CHAT]); assert.equal(isStoredTextName(CHAT), true); - assert.equal(isStoredTextName("transcript.en.vtt"), false); + // Every caption track (lane text-compress-captions), any language code. + for (const c of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.en-US.vtt", "transcript.es.vtt", "transcript.en-en-GB.vtt"]) { + assert.equal(isStoredTextName(c), true, c); + assert.equal(isStoredCaptionName(c), true, c); + assert.equal(isTranscriptVtt(c), true, `${c}: the same pattern as videoStatus`); + assert.equal(plainNameOf(`${c}.zst`), c); + } + // Not declared: the metadata, the whisper transcript, the cues, a + // transcriber's temp, a `.part`, another track format. + for (const n of ["metadata.info.json", "transcript.json", "transcript.cues.json", "transcript.tmp-4242.vtt", "transcript.en.vtt.part", "transcript.en.srv3", "live_chat.cues.json"]) { + assert.equal(isStoredTextName(n), false, n); + assert.equal(plainNameOf(`${n}.zst`), null, n); + } + assert.equal(isStoredCaptionName(CHAT), 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("the classifier: a stored caption is TEXT, never tiered; its compressor's temps and set-aside are scratch", () => { + assert.equal(classifyEntry("transcript.en.vtt.zst"), "text"); + assert.equal(isTierable("transcript.en.vtt.zst"), false); + assert.equal(isScratchEntry(".transcript.en.vtt.zst.compressing-4242-abc123"), true); + assert.equal(isScratchEntry(".transcript.en-orig.vtt.retire-4242-abc123"), true); + assert.equal(isScratchEntry(".transcript.es.vtt.restoring-4242-abc123"), true); + assert.equal(isTierable(".transcript.en.vtt.zst.compressing-4242"), false); +}); + 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(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), true); + assert.equal(listingHas(["metadata.info.json.zst"], "metadata.info.json"), false); + assert.deepEqual( + logicalEntries(["transcript.en-orig.vtt.zst", "transcript.en.vtt", "transcript.en.vtt.zst", "metadata.info.json"]), + ["transcript.en-orig.vtt", "transcript.en.vtt", "metadata.info.json"], + ); 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"); diff --git a/common/lib/storedText.ts b/common/lib/storedText.ts @@ -4,11 +4,13 @@ // 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. +// DECLARED NAMES ONLY. A name is stored compressed only when it is declared +// (`isStoredTextName`); for every other name `<name>.zst` means nothing here. +// Two kinds are declared: the raw live-chat replay (STORED_TEXT_NAMES — lane +// text-compress, slices 1–2: the media drive's tens of GB of chat) and EVERY +// CAPTION TRACK, `transcript.<lang>.vtt` (lane text-compress-captions, slices +// 4–5: about 77 GB on the corpus disk; `isStoredCaptionName`). +// `metadata.info.json` is not declared (a design note only). // // 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. @@ -25,14 +27,26 @@ 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". +// The FIXED 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); +// EVERY CAPTION TRACK: `transcript.<lang>.vtt`, any language code (videoStatus +// `isTranscriptVtt`'s pattern, less the temp below — storedText.test.ts holds +// them together; this module cannot import videoStatus, which imports it). The en / en-orig pair, +// the regional and auto-translated tracks, the foreign-language subtitles. +// Not a transcriber's temp output (`transcript.tmp-<pid>.vtt`, +// controller/transcribeOne.ts): somebody's in-flight bytes, never stored. +const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/; + +export function isStoredCaptionName(name: string): boolean { + return CAPTION_RE.test(name); +} + export function isStoredTextName(name: string): boolean { - return DECLARED.has(name); + return DECLARED.has(name) || CAPTION_RE.test(name); } export function storedNameOf(name: string): string { @@ -44,7 +58,7 @@ export function storedNameOf(name: string): string { 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; + return isStoredTextName(plain) ? plain : null; } // The name a listing that MATCHES reports for this entry. @@ -83,3 +97,30 @@ export function storedFormsIn(entries: readonly string[], name: string): StoredF if (zst) return "zst"; return null; } + +// THE CAPTION TRACKS ON DISK IN THE STORED FORM ONLY, by their track code +// (`transcript.en-orig.vtt.zst` with no plain `transcript.en-orig.vtt` → +// "en-orig"), from a PHYSICAL listing. These are what a yt-dlp subtitle pass +// must not be asked for: yt-dlp's own "already present" skip looks for the +// plain name, so it would fetch the track again and land a second copy beside +// the stored one (a request against the subtitle 429 limit, and two forms). +export function storedOnlyCaptionTracks(entries: readonly string[]): string[] { + const have = new Set(entries); + const out: string[] = []; + for (const e of entries) { + const plain = plainNameOf(e); + if (plain === null || !CAPTION_RE.test(plain) || have.has(plain)) continue; + out.push(plain.slice("transcript.".length, -".vtt".length)); + } + return out.sort(); +} + +// `--sub-langs` with these tracks EXCLUDED: each appended as `-<code>`, its +// regex characters escaped (yt-dlp matches a code as a regex anchored at both +// ends, and applies the exclusions after the requests before them, so +// `en.*,-en` asks every English track but `en`). Unchanged when there are none. +export function excludeSubTracks(subLangs: string, tracks: readonly string[]): string { + if (tracks.length === 0) return subLangs; + const esc = (t: string) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return [subLangs, ...tracks.map((t) => `-${esc(t)}`)].join(","); +} diff --git a/common/lib/subtitleProvenance.ts b/common/lib/subtitleProvenance.ts @@ -1,7 +1,8 @@ import path from "node:path"; -import { createReadStream } from "node:fs"; import { readFile } from "node:fs/promises"; import { englishVttsByPreference, type VideoFiles } from "./videoStatus"; +import { readStoredTextHead } from "./storedText-server"; +import { logicalEntries } from "./storedText"; // Where a VTT transcript came from: YouTube's speech recognition ("asr", what // yt-dlp downloads under --write-auto-subs) or a human-authored/uploaded track @@ -59,37 +60,24 @@ export function sniffVttProvenance(head: string): SubtitleProvenance { return "unknown"; } -// Read only the head of the VTT (createReadStream start/end), never the whole -// file: a 3-hour ASR transcript is multiple MB. +// Read only the head of the VTT, never the whole file: a 3-hour ASR transcript +// is multiple MB. A track stored compressed (`transcript.en.vtt.zst`, +// lib/storedText.ts) has its head DECODED: the raw bytes of a zstd frame +// would sniff as "unknown" — and an ASR track read as manual is one the purge +// keeps and the replace lane never schedules. export async function readVttProvenance( videoDir: string, vttFile: string, ): Promise<SubtitleProvenance> { let head: string; try { - head = await readHead(path.join(videoDir, vttFile), PROVENANCE_SNIFF_BYTES); + head = (await readStoredTextHead(videoDir, vttFile, PROVENANCE_SNIFF_BYTES)).toString("utf8"); } catch { return "unknown"; } return sniffVttProvenance(head); } -function readHead(file: string, bytes: number): Promise<string> { - return new Promise((resolve, reject) => { - const stream = createReadStream(file, { - encoding: "utf8", - start: 0, - end: bytes - 1, - }); - let out = ""; - stream.on("data", (chunk) => { - out += chunk; - }); - stream.on("error", reject); - stream.on("end", () => resolve(out)); - }); -} - // The language/track segment of a transcript sidecar filename: // "transcript.en-US.vtt" -> "en-US". Null for anything else. export function vttTrackName(filename: string): string | null { @@ -150,7 +138,7 @@ export async function resolveCaptionsProvenance( videoDir: string, entries: readonly string[], ): Promise<SubtitleProvenance | null> { - const vtts = englishVttsByPreference(entries); + const vtts = englishVttsByPreference(logicalEntries(entries)); if (vtts.length === 0) return null; let unknown = false; for (const name of vtts) { diff --git a/common/lib/transcriptPin-server.ts b/common/lib/transcriptPin-server.ts @@ -37,3 +37,17 @@ export async function pinTranscript(videoDir: string, from: string): Promise<voi pinnedAt: new Date().toISOString(), }); } + +// THE PIN GOES WITH THE PICK (REVIEW-1 N1, captions lane): "Set as +// transcript" writes the chosen track as a PLAIN transcript.en.vtt and pins +// it. Over a stored `transcript.en.vtt.zst` (YouTube's own `en`, compressed) +// the pick lands beside it; deleting the plain pick then would leave the pin +// ranking the stored `en` first — the very track the pin was made to avoid. +// So a delete of the plain transcript.en.vtt that leaves a stored form of +// OTHER content beside it removes the pin too: the caption-track rule picks +// again. Returns whether a pin was removed. +export async function unpinAfterPickDeleted(videoDir: string): Promise<boolean> { + if (!(await transcriptPinSidecar.load(videoDir))) return false; + await transcriptPinSidecar.remove(videoDir); + return true; +} diff --git a/common/lib/videoStatus.ts b/common/lib/videoStatus.ts @@ -3,6 +3,7 @@ import { readdir, readFile, stat } from "node:fs/promises"; import { isPartAudioFile, isRealAudioFile } from "./mediaFiles"; import { parseVtt, type Cue } from "./vtt"; import { logicalEntries } from "./storedText"; +import { isStoredTextReadError, readStoredText } from "./storedText-server"; export type VideoFiles = { hasMeta: boolean; @@ -29,7 +30,12 @@ export type VideoFiles = { // Surfaced separately so the UI can offer a Resume action; audio-check's // own internal snapshots (.part.good, .part.testing) are excluded. partAudioFiles: string[]; - // The raw readdir() listing this whole record was derived from. + // The LOGICAL readdir() listing this whole record was derived from + // (lib/storedText.ts): a file stored compressed — `transcript.en.vtt.zst`, + // `transcript.live_chat.json.zst` — is listed under its plain name, once, + // and every reader of its bytes goes through lib/storedText-server.ts. A + // caller that OPERATES on each entry as a file (the byte walk, a mover) + // takes `physicalEntries`. // // Exposed so a caller that needs a question this type does not already answer // — "is there a source container?", "is there a saved-video pointer?" — can @@ -39,6 +45,8 @@ export type VideoFiles = { // that is free and one that doubles the report's I/O. See // lib/operations.ts, which classifies missing vs missing-input from it. entries: string[]; + // The raw readdir(): every entry under its own name (a `.zst` is a file). + physicalEntries: string[]; }; export type IndexTranscript = @@ -187,21 +195,26 @@ export function captionInputs(entries: readonly string[]): string[] { // preference order, that parses to at least one cue. When every track parses // to nothing, the most preferred one is returned with its empty list (the // video has captions, they say nothing). Null when there is no English VTT, or -// none can be read. `entries` is the caller's readdir of `videoDir`, when it -// has one. +// none can be read. `entries` is the caller's LOGICAL listing of `videoDir` +// (readVideoFiles().entries), when it has one — a physical readdir is made +// logical here too, so a track stored as `transcript.en.vtt.zst` is read +// (lib/storedText.ts) and the name answered is always the plain one. export async function readEnglishVttCues( videoDir: string, entries?: readonly string[], ): Promise<{ filename: string; cues: Cue[] } | null> { const names = englishVttsByPreference( - entries ?? (await readdir(videoDir).catch(() => [] as string[])), + logicalEntries(entries ?? (await readdir(videoDir).catch(() => [] as string[]))), ); let first: { filename: string; cues: Cue[] } | null = null; for (const filename of names) { let cues: Cue[]; try { - cues = parseVtt(await readFile(path.join(videoDir, filename), "utf8")); - } catch { + cues = parseVtt(await readStoredText(videoDir, filename, "utf8")); + } catch (err) { + // A stored track that is there and does not decode is an error, never + // a track to skip past (lib/storedText-server.ts isStoredTextReadError). + if (isStoredTextReadError(err)) throw err; continue; } if (cues.length > 0) return { filename, cues }; @@ -230,7 +243,8 @@ export async function readVideoFiles( videoDir: string, opts: { checkUntranscribable?: boolean } = {}, ): Promise<VideoFiles> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const physicalEntries = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(physicalEntries); const hasMeta = entries.includes(META_FILENAME); const ytVttFile = resolvePrimaryVtt(entries); const hasYtVtt = ytVttFile !== null; @@ -270,6 +284,7 @@ export async function readVideoFiles( audioFiles, partAudioFiles, entries, + physicalEntries, }; } diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -12,8 +12,8 @@ import { X_JOB_CAP, X_QUEUE_KEY, isXUrl, xJobCapSentence, xJobCapVerdict, xJobAs const T0 = Date.parse("2026-11-18T12:00:00.000Z"); const MIN = 60_000; -test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { - assert.deepEqual({ ...X_JOB_CAP }, { perHour: 12, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); +test("the numbers: 6 X jobs in any 60 minutes, 150 in any 24 hours, and they are frozen", () => { + assert.deepEqual({ ...X_JOB_CAP }, { perHour: 6, hourMs: 3_600_000, perDay: 150, dayMs: 86_400_000 }); assert.ok(Object.isFrozen(X_JOB_CAP)); assert.equal(X_QUEUE_KEY, "platform:twitter"); // Nothing in the rule's two modules reads a setting, an environment variable or an option. @@ -23,44 +23,49 @@ test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they ar } }); -test("the hour window: the 13th start in 60 minutes is refused, and says when the next may start", () => { - const starts = Array.from({ length: 12 }, (_, i) => T0 + i * 5 * MIN); // 12:00 … 12:55 - assert.deepEqual(xJobCapVerdict(starts.slice(0, 11), T0 + 56 * MIN), { ok: true, lastHour: 11, lastDay: 11 }); +test("the hour window: the 7th start in 60 minutes is refused, and says when the next may start", () => { + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * 10 * MIN); // 12:00 … 12:50 + assert.deepEqual(xJobCapVerdict(starts.slice(0, 5), T0 + 56 * MIN), { ok: true, lastHour: 5, lastDay: 5 }); const full = xJobCapVerdict(starts, T0 + 56 * MIN); - assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" }); + assert.deepEqual(full, { ok: false, lastHour: 6, lastDay: 6, nextAt: T0 + 60 * MIN, window: "hour" }); assert.equal( xJobCapSentence(full, T0 + 56 * MIN), - "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " + + "X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes (the cap is 6). The next X job may start at 13:00 UTC (in 4 min); " + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it.", ); // Rolling: at 13:00 the 12:00 start has left the window (a start exactly 60 minutes old is out). assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true); assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN - 1).ok, false); - // X's own gap (5 minutes) makes exactly 12 an hour: the cap never bites a run at the default gap. - assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 11); + assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).lastHour, 5); + // At X's floor gap (5 minutes) six jobs take 25 minutes: the hourly cap bites a run at the floor. + const atFloor = Array.from({ length: 6 }, (_, i) => T0 + i * 5 * MIN); + assert.equal(xJobCapVerdict(atFloor, T0 + 30 * MIN).ok, false); }); test("the day window: the 151st start in 24 hours is refused until the oldest of the last 150 is a day old", () => { - const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 9 * MIN); // one every 9 minutes: 22.5 hours - const now = T0 + 150 * 9 * MIN; + // 150 starts in 20 hours (one every 8 minutes — more than the hourly cap lets through, but the verdict + // judges each window as it is at `now`, and the last hour here is empty). + const starts = Array.from({ length: 150 }, (_, i) => T0 + i * 8 * MIN); + const now = T0 + 1300 * MIN; const full = xJobCapVerdict(starts, now); assert.equal(full.ok, false); assert.equal(full.window, "day"); + assert.equal(full.lastHour, 0); assert.equal(full.lastDay, 150); assert.equal(full.nextAt, T0 + 24 * 60 * MIN); - assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in 90 min\)/); + assert.match(xJobCapSentence(full, now), /150 X jobs started in the last 24 hours \(the cap is 150\)\. The next X job may start at 12:00 UTC \(in about 2 h\)/); // The day is named when it is not today's. - assert.match(xJobCapSentence(xJobCapVerdict(starts, T0 + 151 * 9 * MIN - 23 * 60 * MIN), T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); + assert.match(xJobCapSentence(full, T0 + 5 * MIN), /may start at 2026-11-19 12:00 UTC \(in about 24 h\)/); assert.equal(xJobCapVerdict(starts, T0 + 24 * 60 * MIN).ok, true); assert.equal(xJobCapVerdict(starts.slice(1), now).ok, true); }); test("a clock set back never frees a start early", () => { - const starts = Array.from({ length: 12 }, (_, i) => T0 + i * MIN); // 12:00 … 12:11 + const starts = Array.from({ length: 6 }, (_, i) => T0 + i * MIN); // 12:00 … 12:05 // The clock now reads two hours EARLIER than the latest start: every start still counts. const back = xJobCapVerdict(starts, T0 - 120 * MIN); assert.equal(back.ok, false); - assert.equal(back.lastHour, 12); + assert.equal(back.lastHour, 6); assert.equal(back.nextAt, T0 + 60 * MIN); // Only once the clock has passed them again by the window do they leave it. assert.equal(xJobCapVerdict(starts, T0 + 59 * MIN).ok, false); @@ -86,37 +91,13 @@ test("X jobs run on X's queue only: any other queue is refused, when queued and assert.equal(runInJobContext(ctx("platform:twitter"), () => xJobContextRefusal("example-x", "d")), null); }); -test("ruling R-a: what counts is decided from the job's own plan — only a library's media-only capture, with no way to the login, does not", () => { - // The watch's follow-up capture with shots off, as the editor queues it (xTrendingActions.ts afterXTrendingRead). - const mediaOnly = { queueKey: undefined, ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; - const library = { library: true }; - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: library }), false); - // Each way to a page or to the login makes it count. - for (const [what, params] of [ - ["shots on", { ...mediaOnly, shots: true }], - ["shots by default", { ...mediaOnly, shots: undefined }], - ["articles by default", { ...mediaOnly, articles: undefined }], - ["avatars by default", { ...mediaOnly, avatars: undefined }], - ["context by default", { ...mediaOnly, context: undefined }], - ["a thread shot", { ...mediaOnly, thread: true }], - ["avatars only", { ...mediaOnly, avatarsOnly: true }], - ["context only", { ...mediaOnly, contextOnly: true }], - ["the keep capture (login fallback)", { ...mediaOnly, keptMedia: true }], - ] as const) { - assert.equal(xJobCounts({ kind: "capture-posts", params, channel: library }), true, what); - } - // The channel's thread default counts when the plan does not say no. - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true, postCaptureThread: true } }), true); - assert.equal(xJobCounts({ kind: "capture-posts", params: { ...mediaOnly, thread: false }, channel: { library: true, postCaptureThread: true } }), false); - // Not a library: an X channel's media comes through gallery-dl with X's cookies. - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: false } }), true); - assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly }), true); - // No plan to read: it counts. - assert.equal(xJobCounts({ kind: "capture-posts", channel: library }), true); - // Every other kind of X job counts, whatever its params say. - for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing"]) { - assert.equal(xJobCounts({ kind, params: mediaOnly, channel: library }), true, kind); +test("review 1 F8: every X job counts — a library's media-only capture too; only the transcription worker does not", () => { + const mediaOnly = { ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; + assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true } }), true); + for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing", "capture-posts"]) { + assert.equal(xJobCounts({ kind }), true, kind); } + assert.equal(xJobCounts({ kind: "transcribe-one" }), false); }); test("S5: which network jobs ask x.com — by X's queue, X's clip queue, an import's URL, or an X channel's job that is not local", () => { @@ -268,11 +249,11 @@ test("review 4 B: an import of a file by its page is X's by that page's address, }); test("review 3 S4: a start in the future counts in both windows, and never moves the windows off the real starts", () => { - const real = Array.from({ length: 11 }, (_, i) => T0 + i * MIN); + const real = Array.from({ length: 5 }, (_, i) => T0 + i * MIN); const future = T0 + 365 * 24 * 60 * MIN; - const v = xJobCapVerdict([...real, future], T0 + 11 * MIN); - assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 12, 12]); - // The next may start when the oldest of the newest twelve has left: the real 12:00 start, at 13:00. + const v = xJobCapVerdict([...real, future], T0 + 5 * MIN); + assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 6, 6]); + // The next may start when the oldest of the newest six has left: the real 12:00 start, at 13:00. assert.equal(v.nextAt, T0 + 60 * MIN); // The future start alone keeps counting until the clock has passed it by the window. assert.deepEqual([xJobCapVerdict([future], T0).lastHour, xJobCapVerdict([future], T0).lastDay], [1, 1]); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -36,13 +36,24 @@ import { currentJobContext } from "./jobContext"; export const X_QUEUE_KEY = "platform:twitter"; +// THE HOURLY CAP IS 6 (the operator, 21 Nov 2026: one sitting of 12 timeline +// fetches back to back, at the old cap of 12, preceded the account's +// suspension). At 6 an hour the daily 150 is implied (6 × 24 = 144): it stays +// as a second, independent bound. export const X_JOB_CAP = Object.freeze({ - perHour: 12, + perHour: 6, hourMs: 60 * 60_000, perDay: 150, dayMs: 24 * 60 * 60_000, }); +// HOW LONG X IS LEFT ALONE AFTER IT ANSWERED 429: X's own rate-limit window. +// Written as the `twitter` platform cooldown (jobs/downloadBackoff.ts +// recordPlatformCooldown) by every X reader that meets one — a trending read, +// its media, a capture, a gallery-dl run — and read by the network guard, +// which refuses EVERY X job while it lasts (jobs/networkGuard.ts). +export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; + // ── 1. the queue ─────────────────────────────────────────────────────────── // Why a job that asks X may not be on `queueKey`, or null. `what` names the @@ -154,31 +165,13 @@ export type XJobPlan = { }; // DOES THIS X JOB COUNT AGAINST THE CAP? Every X job does — a read, a fetch in -// any mode, an X run's channel, an import, an availability check, a capture -// with its shots — EXCEPT the one job that cannot ask x.com: a trending -// library's capture of MEDIA ONLY, which takes files from X's two media CDN -// hosts by the addresses already in the saved captures, with no cookie, no -// page and no logged-in fallback. Every half that would open a page must be -// off BY NAME in the plan (shots, articles, avatars, context; no thread shot, -// by the plan or the channel's default; no avatars-only or context-only run), -// and it is not a keep capture (`keptMedia`: a post the CDN cannot serve whole -// is then downloaded the logged-in way). A capture that COULD fall back to -// the login counts. A plan that cannot be read counts. -// -// It still runs on X's queue, spaced from the others by X's gap, under X's -// cooldown and the watch's jar rule: only the count is not asked. +// any mode, an X run's channel, an import, an availability check, and a +// capture of any kind, a trending library's media-only capture included +// (review 1 F8 of lane x-sittings, the operator's ruling: it asks X's media +// hosts, so it is an X job — in the sitting, the cap and the gap). Only the +// transcription worker, which reads a file on disk, does not. export function xJobCounts(plan: XJobPlan): boolean { - // The transcription worker reads a file on disk (review 2 S5). - if (plan.kind === "transcribe-one") return false; - if (plan.kind !== "capture-posts" || plan.channel?.library !== true) return true; - const p = plan.params; - if (!p || typeof p !== "object") return true; - const off = (k: string) => p[k] === false; - if (!(off("shots") && off("articles") && off("avatars") && off("context"))) return true; - if (p.thread === true || (p.thread !== false && plan.channel.postCaptureThread === true)) return true; - if (p.avatarsOnly === true || p.contextOnly === true) return true; - if (p.keptMedia === true) return true; - return p.media === false; + return plan.kind !== "transcribe-one"; } // ── 4. which jobs ask x.com (review 2 S5, review 3 M2/S5/S6) ─────────────── diff --git a/common/lib/xSitting.ts b/common/lib/xSitting.ts @@ -0,0 +1,255 @@ +// X IN SITTINGS (lane x-sittings; the operator, 21 Nov 2026: "Implement all +// your suggestions"). The archive's X account was suspended after one sitting +// of a trending read and 12 timeline fetches back to back, each 5-6 minutes +// after the last. So X is now asked in SMALL, UNEVEN SITTINGS: +// +// 1. A SITTING begins at a cookie refresh (the jar's refresh time, +// social/xSessionBroker.ts) and admits at most `social.x.sittingJobs` X +// job starts (default 4, bounded 1-6 HERE, in code). A start beyond it is +// refused: a new Refresh on /cookies starts the next sitting. +// 2. ONE KIND PER SITTING: "timelines" (account post fetches, captures, +// checks) or "browse" (trending reads, search walks). The first job fixes +// it; a job of the other kind is refused until the next Refresh. +// 3. THE GAP BEFORE AN X JOB IS DRAWN per job, uniform in a range (default +// 5-12 min; the floor 5 min is in code), not a fixed beat. +// +// Pure and client-safe: the settings coercion, the guard (jobs/networkGuard.ts), +// the count on disk (jobs/xSitting.ts), the queue gap (jobs/queueGap.ts) and +// /cookies all read it. What counts is X's job cap's rule (lib/xJobRule.ts +// xJobCounts): the same starts, counted at the same moment. + +export type XSittingKind = "timelines" | "browse"; + +export const X_SITTING_DEFAULT_JOBS = 4; +export const X_SITTING_MIN_JOBS = 1; +export const X_SITTING_MAX_JOBS = 6; + +// `social.x.sittingJobs` as stored: a whole number 1-6, else absent. +export function parseXSittingJobs(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_SITTING_MAX_JOBS, Math.max(X_SITTING_MIN_JOBS, Math.floor(v))); +} + +// The limit in force: the setting, bounded again (a hand-edited file never +// passes 6), else the default. +export function xSittingJobs(x: { sittingJobs?: number } | undefined): number { + return parseXSittingJobs(x?.sittingJobs) ?? X_SITTING_DEFAULT_JOBS; +} + +// ── the kind of an X job ─────────────────────────────────────────────────── + +// The job as it will run: its kind, and what its channel is (read by the +// guard from the channel's config, never from the caller). +export type XSittingPlan = { + kind: string; + channel?: { library?: boolean; search?: boolean }; +}; + +// "browse": reading what X shows — a trending page, a search walk, and the +// capture of what a trending read found (a library's posts). "timelines": +// everything else — an account's posts in any mode, an X run's channel, a +// capture of an account's posts, an availability check, an import of one +// post, an X video window. +export function xSittingKindOf(plan: XSittingPlan): XSittingKind { + if (plan.kind === "read-x-trending") return "browse"; + if (plan.channel?.search === true) return "browse"; + if (plan.channel?.library === true) return "browse"; + return "timelines"; +} + +export const X_SITTING_KIND_TEXT: Readonly<Record<XSittingKind, string>> = Object.freeze({ + timelines: "timelines (account post fetches, captures, checks)", + browse: "browse (trending reads, search walks)", +}); + +// ── the verdict ──────────────────────────────────────────────────────────── + +// The sitting as it stands: when it began (the jar's refresh time; null: no +// refresh on record), its kind (null: no job yet; "unknown": its record was +// lost and its kind cannot be told), the jobs it started, and its first job. +export type XSittingState = { + began: string | null; + kind: XSittingKind | "unknown" | null; + used: number; + first?: { jobKind: string; at: number }; +}; + +export type XSittingVerdict = + | { ok: true; used: number; left: number; limit: number } + | { ok: false; why: "used-up" | "kind" | "unknown"; used: number; left: number; limit: number; sentence: string }; + +const hhmm = (iso: string | number) => new Date(iso).toISOString().slice(11, 16); + +function beganText(began: string | null): string { + return began ? `since the cookies were refreshed at ${hhmm(began)} UTC` : "with no cookie refresh on record"; +} + +const NEXT = "A new Refresh cookies on /cookies starts the next sitting; nothing queues or retries by itself."; + +// May a job of `kind` start in this sitting? +export function xSittingVerdict(state: XSittingState, kind: XSittingKind, limit: number): XSittingVerdict { + const used = state.used; + const left = Math.max(0, limit - used); + const base = { used, left, limit }; + if (used >= limit) { + return { + ok: false, + why: "used-up", + ...base, + sentence: + `This X sitting is used up: ${used} of ${limit} X job${limit === 1 ? "" : "s"} started ${beganText(state.began)} ` + + `(social.x.sittingJobs, at most ${X_SITTING_MAX_JOBS}). ${NEXT}`, + }; + } + if (state.kind === "unknown") { + return { + ok: false, + why: "unknown", + ...base, + sentence: + `This X sitting's kind cannot be told: its record is gone and the ${used} X job${used === 1 ? "" : "s"} it started left none. ` + + `No X job starts in it. ${NEXT}`, + }; + } + if (state.kind !== null && state.kind !== kind) { + const first = state.first ? ` (its first job, ${state.first.jobKind} at ${hhmm(state.first.at)} UTC, fixed it)` : ""; + return { + ok: false, + why: "kind", + ...base, + sentence: + `This X sitting is a ${state.kind} sitting${first}: a ${kind} job does not start in it — ` + + `one sitting is ${X_SITTING_KIND_TEXT.timelines} or ${X_SITTING_KIND_TEXT.browse}, never both. ${NEXT}`, + }; + } + return { ok: true, ...base }; +} + +// Is `next` a LATER refresh than `began`, so a new sitting begins? An equal or +// earlier time (a jar restored from a backup, a clock set back) continues the +// sitting on record: only a real refresh resets it. +export function isLaterRefresh(next: string | null | undefined, began: string | null): boolean { + if (!next) return false; + const n = Date.parse(next); + if (!Number.isFinite(n)) return false; + if (began === null) return true; + const b = Date.parse(began); + return !Number.isFinite(b) || n > b; +} + +// ── the gap before an X job ──────────────────────────────────────────────── + +// The floor of X's gap: never below the fixed five minutes it replaced. +export const X_GAP_FLOOR_MINUTES = 5; +export const X_GAP_DEFAULT_MIN_MINUTES = 5; +export const X_GAP_DEFAULT_MAX_MINUTES = 12; +export const X_GAP_CEILING_MINUTES = 120; +// THE RANGE IS NEVER ONE VALUE (review 1 F4): the longest gap is at least +// this much above the shortest, whatever is set — a range of one value is a +// fixed beat again. +export const X_GAP_MIN_SPREAD_MINUTES = 3; + +// `social.x.gapMinMinutes` / `gapMaxMinutes` as stored: whole minutes from +// the floor to the ceiling, else absent. +export function parseXGapMinutes(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_GAP_CEILING_MINUTES, Math.max(X_GAP_FLOOR_MINUTES, Math.floor(v))); +} + +export type XGapRange = { minSeconds: number; maxSeconds: number }; + +// The range in force, in seconds. The minimum is the setting (else 5 min), +// never below the floor, and raised — never lowered — by an explicit +// `pacing.jobGapSeconds.twitter` above it; the maximum is the setting (else +// 12 min), never less than the minimum plus X_GAP_MIN_SPREAD_MINUTES. +export function xGapRange( + x: { gapMinMinutes?: number; gapMaxMinutes?: number } | undefined, + explicitTwitterSeconds?: number, +): XGapRange { + const minMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + let minSeconds = minMinutes * 60; + if (typeof explicitTwitterSeconds === "number" && Number.isFinite(explicitTwitterSeconds) && explicitTwitterSeconds > minSeconds) { + minSeconds = Math.floor(explicitTwitterSeconds); + } + const maxMinutes = parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES; + const maxSeconds = Math.max(minSeconds + X_GAP_MIN_SPREAD_MINUTES * 60, maxMinutes * 60); + return { minSeconds, maxSeconds }; +} + +// One draw from the range, uniform: `rand` in [0, 1). +export function drawXGapSeconds(range: XGapRange, rand: number): number { + const r = Number.isFinite(rand) ? Math.min(Math.max(rand, 0), 1) : 0; + const s = range.minSeconds + Math.floor(r * (range.maxSeconds - range.minSeconds + 1)); + return Math.min(range.maxSeconds, Math.max(range.minSeconds, s)); +} + +// "5-12 min" (whole minutes), else "300-720 s". +export function xGapRangeText(range: XGapRange): string { + const whole = range.minSeconds % 60 === 0 && range.maxSeconds % 60 === 0; + return whole ? `${range.minSeconds / 60}-${range.maxSeconds / 60} min` : `${range.minSeconds}-${range.maxSeconds} s`; +} + +// ── the account's state (suspension) ────────────────────────────────────── + +// The operator's word on the account X answers as: "suspended" (read-only: +// its answers are thinned, so a post it cannot see is NOT a deleted post) or +// "ok". Marked by hand (`pnpm ops x-session`, /cookies). +export type XAccountState = "ok" | "suspended"; + +export function isXAccountState(v: unknown): v is XAccountState { + return v === "ok" || v === "suspended"; +} + +// The kinds a suspended account refuses: they RECORD posts as deleted or +// unavailable from what X answers. A capture with its screenshots off records +// no availability (social/xPostCapture.ts records it with the shot only). +// (review 1 F5) A capture refuses unless both halves that read a page's +// verdict — the post's shot and its article — are off by name; the video +// checks (check-availability and its kin) on an X channel refuse as the +// post check does. Every other writer is covered at the write +// (lib/jobContext.ts xAnswersUntrusted). +const SUSPENDED_REFUSED_KINDS: ReadonlySet<string> = new Set([ + "check-post-availability", + "check-availability", + "quick-availability-check", + "check-maybe-missing", + "check-kept-deleted", +]); + +export function xSuspendedRefuses(plan: { kind: string; params?: Readonly<Record<string, unknown>> }): boolean { + if (SUSPENDED_REFUSED_KINDS.has(plan.kind)) return true; + if (plan.kind !== "capture-posts") return false; + const p = plan.params; + if (p?.avatarsOnly === true || p?.contextOnly === true) return false; + return p?.shots !== false || p?.articles !== false; +} + +export function xSuspendedSentence(what: string, since: string, note?: string): string { + return ( + `The X account is marked suspended (since ${since.slice(0, 16).replace("T", " ")} UTC${note ? `: ${note}` : ""}): ` + + `${what} is refused, because a suspended account's answers are thinned and a post it cannot see would be recorded ` + + `deleted or unavailable when it is not. Mark it ok (pnpm ops x-session --json '{"accountState":"ok"}', or /cookies) once it is restored.` + ); +} + +// ── what ONE X job may read (review 1 F8) ───────────────────────────────── + +// A walk of an account's timeline (sync new, backfill, full, older) or of an +// X search reads at most `social.x.maxPostsPerJob` posts (default 300), and +// never more than the ceiling in the code; then it saves its place and ends, +// to be continued in a later sitting. One job read 634 on 20 Nov 2026. +export const X_POSTS_PER_JOB_DEFAULT = 300; +export const X_POSTS_PER_JOB_MIN = 20; +export const X_POSTS_PER_JOB_CEILING = 400; + +export function parseXPostsPerJob(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v)) return undefined; + return Math.min(X_POSTS_PER_JOB_CEILING, Math.max(X_POSTS_PER_JOB_MIN, Math.floor(v))); +} + +// The posts this job may read: the caller's limit when lower, else the +// setting, never above the ceiling. +export function xJobPostLimit(x: { maxPostsPerJob?: number } | undefined, asked?: number): number { + const cap = parseXPostsPerJob(x?.maxPostsPerJob) ?? X_POSTS_PER_JOB_DEFAULT; + return typeof asked === "number" && Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), cap) : cap; +} diff --git a/common/lib/zstdSupport.d.mts b/common/lib/zstdSupport.d.mts @@ -0,0 +1,4 @@ +// Types for ./zstdSupport.mjs: the boot-time zstd assertion. +export const ZSTD_NODE_NEEDED: ">= 22.15"; +export function zstdSupportProblem(z?: object, version?: string): string | null; +export function assertZstdSupport(who: string, z?: object, version?: string): void; diff --git a/common/lib/zstdSupport.mjs b/common/lib/zstdSupport.mjs @@ -0,0 +1,29 @@ +// STORED TEXT NEEDS node:zlib's zstd (Node >= 22.15; 23.8 on the 23 line) — +// asked ONCE AT BOOT by every process that may read the corpus (the editor's +// instrumentation, every common/bin CLI through runIfEntryPoint, umtool's bin +// and its bare-node readers through lib/storedText-read.mjs). A process on an +// older Node would read every caption or chat stored as `.zst` as unreadable: +// the index would drop their text, a lane would schedule work for them. So it +// REFUSES TO START with this sentence instead of running degraded (REVIEW-1 +// F3, captions lane). Plain JS, no import but node:zlib: safe to load first. + +import zlib from "node:zlib"; + +export const ZSTD_NODE_NEEDED = ">= 22.15"; + +/** The problem, or null when this Node has zstd. @param {object} [z] node:zlib (a test passes a fake) @param {string} [version] */ +export function zstdSupportProblem(z = zlib, version = process.version) { + const ok = + typeof z.zstdDecompress === "function" && + typeof z.createZstdCompress === "function" && + typeof z.createZstdDecompress === "function"; + return ok + ? null + : `stored text (captions and live chats stored as .zst) needs node:zlib zstd — Node ${ZSTD_NODE_NEEDED} (this is ${version})`; +} + +/** Throws the problem, naming who refuses. @param {string} who @param {object} [z] @param {string} [version] */ +export function assertZstdSupport(who, z = zlib, version = process.version) { + const p = zstdSupportProblem(z, version); + if (p) throw new Error(`${who} refuses to start: ${p}`); +} diff --git a/common/package.json b/common/package.json @@ -49,6 +49,7 @@ "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/recordingClock.mjs": "./lib/recordingClock.mjs", "./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs", + "./lib/recordingEnd.mjs": "./lib/recordingEnd.mjs", "./lib/jitter.mjs": "./lib/jitter.mjs", "./lib/ttsTuning.mjs": "./lib/ttsTuning.mjs", "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs", @@ -79,6 +80,8 @@ "./lib/sourceStatus.mjs": "./lib/sourceStatus.mjs", "./lib/sourceStatus-server.mjs": "./lib/sourceStatus-server.mjs", "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", + "./lib/storedText-read.mjs": "./lib/storedText-read.mjs", + "./lib/zstdSupport.mjs": "./lib/zstdSupport.mjs", "./lib/videoDirId.mjs": "./lib/videoDirId.mjs", "./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs", "./lib/*": "./lib/*.ts", diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -71,11 +71,12 @@ import { isLocalRecord } from "../lib/localMedia"; import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view"; -import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; +import { isStoredTextReadError, readStoredText, readdirLogical } from "../lib/storedText-server"; import { type Site } from "../lib/site"; import { storeReportDir } from "../lib/report/store"; import { getSettings } from "../lib/settings"; @@ -295,11 +296,15 @@ export type CitedRecord = { wayback: WaybackProvenance | null; }; -async function readCues(file: string, kind: "vtt" | "whisper"): Promise<Cue[]> { +// Either form (lib/storedText.ts): a caption stored as `.zst` is read. +async function readCues(dir: string, name: string, kind: "vtt" | "whisper"): Promise<Cue[]> { try { - const raw = await readFile(file, "utf8"); + const raw = await readStoredText(dir, name, "utf8"); return kind === "vtt" ? parseVtt(raw) : parseTranscriptJson(raw); - } catch { + } catch (err) { + // A stored track that does not decode is an error, never "no cues": a + // quote checked against nothing would read as not said (REVIEW-1 F3). + if (isStoredTextReadError(err)) throw err; return []; } } @@ -315,7 +320,8 @@ export async function readCitedRecord( // The record's directory: a Twitch record's v<n> is data/<n>/ (release 23 // F1b). The record keeps the id it is cited by. const dir = await resolveVideoDir(channelsDir, slug, id); - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a stored caption is listed under its name. + const entries = await readdirLogical(dir); if (entries.length === 0) return null; let summary: CitedRecord["summary"] | null = null; let cues: Cue[] = []; @@ -332,7 +338,7 @@ export async function readCitedRecord( const meta = await loadRawMetadataFromDir(dir); if (!meta) return null; summary = summarize(slug, id, meta, channelName); - if (entries.includes(WHISPER_FILENAME)) cues = await readCues(path.join(dir, WHISPER_FILENAME), "whisper"); + if (entries.includes(WHISPER_FILENAME)) cues = await readCues(dir, WHISPER_FILENAME, "whisper"); } // The caption-track rule (videoStatus.ts): the first English VTT, `en-orig` // first, that has cues. @@ -343,11 +349,11 @@ export async function readCitedRecord( if (n?.cues?.length) tracks.push({ name: path.basename(fresh.cuesPath), cues: n.cues }); } if (entries.includes(WHISPER_FILENAME)) { - const w = await readCues(path.join(dir, WHISPER_FILENAME), "whisper"); + const w = await readCues(dir, WHISPER_FILENAME, "whisper"); if (w.length > 0) tracks.push({ name: WHISPER_FILENAME, cues: w }); } for (const name of englishVttsByPreference(entries)) { - const v = await readCues(path.join(dir, name), "vtt"); + const v = await readCues(dir, name, "vtt"); if (v.length > 0) tracks.push({ name, cues: v }); } if (tracks.length === 0 && cues.length > 0) tracks.push({ name: "cues", cues }); diff --git a/common/social/fakeXProfileBrowser.test.ts b/common/social/fakeXProfileBrowser.test.ts @@ -46,7 +46,7 @@ test("the gate: test server, inside transcriptsDir, the file exists", async () = test("refreshXCookies on the fake writes the jar from the fixture's cookies", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); try { - const paths = { transcriptsDir: root } as Parameters<typeof refreshXCookies>[0]; + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Parameters<typeof refreshXCookies>[0]; await mkdir(path.join(root, ".x-session", "profile"), { recursive: true }); const file = path.join(root, ".fake-x-profile-cookies.json"); await writeFile( @@ -70,7 +70,7 @@ test("refreshXCookies on the fake writes the jar from the fixture's cookies", as test("connectXAccount on the fake: the window closes by itself, the login is exported; clearXSession forgets it", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "fake-x-")); try { - const paths = { transcriptsDir: root } as Parameters<typeof connectXAccount>[0]; + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Parameters<typeof connectXAccount>[0]; const file = path.join(root, ".fake-x-profile-cookies.json"); await writeFile( file, diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -112,6 +112,9 @@ export type PostFetchResult = { error?: string; // The run stopped on `drain` at a resume point (`cursor`). Not a failure. drained?: boolean; + // X answered a rate limit or a bot check: the run stopped at its resume + // point (`cursor` / `position`) and the X stop is recorded (review 1 F2). + rateLimited?: boolean; // A forum thread's walk positions after the run (with every checkpoint's). forumWalk?: ForumWalkState; // What stopped the run, when the source refused or challenged it — the @@ -188,6 +191,8 @@ export type OlderPostFetchResult = { error?: string; // The walk stopped on `drain`; `position` is where the next run resumes. drained?: boolean; + // X answered a rate limit: the walk stopped at `position` (review 1 F2). + rateLimited?: boolean; }; // Input for an X SEARCH channel's walk (`SocialFetcher.fetchSearch`, release diff --git a/common/social/headedDisplay.test.ts b/common/social/headedDisplay.test.ts @@ -437,7 +437,7 @@ test("a browser that opens no window (the e2e fake) needs no display", async () // --- each Connect passes the env ------------------------------------------------------------------ -const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths; +const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name), autoQueueStateFile: path.join(TMP, name, ".auto-queue", "state.json") }) as unknown as Paths; test("Connect X account: the window gets the display, and the result says which", async () => { const { chromium, launches } = stubChromium(); diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -24,6 +24,7 @@ // // SERVER-ONLY (node:fs). +import { xAnswersUntrusted } from "../lib/jobContext"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { readdir, stat } from "node:fs/promises"; @@ -308,6 +309,17 @@ export async function writePostCapture( dir: string, record: PostCaptureRecord, ): Promise<void> { + // Inside an X job whose account is marked suspended (review 1 F5): a post + // or an article X showed as deleted or unavailable is recorded as an error, + // owed again — never as settled. + if (await xAnswersUntrusted()) { + const gone = (st: string) => st === "deleted" || st === "unavailable"; + const note = "not recorded as gone: the X account is marked suspended"; + if (gone(record.state)) record = { ...record, state: "error", error: record.error ? `${record.error}; ${note}` : note }; + if (record.article && gone(record.article.state)) { + record = { ...record, article: { ...record.article, state: "error", error: record.article.error ? `${record.article.error}; ${note}` : note } }; + } + } await writeJsonAtomic(path.join(dir, CAPTURE_FILENAME), record, { mkdir: true }); } diff --git a/common/social/xAccountState.ts b/common/social/xAccountState.ts @@ -0,0 +1,107 @@ +// THE X ACCOUNT'S STATE, AS THE OPERATOR MARKED IT (lane x-sittings): whether +// the account X answers as is suspended (read-only). `<transcripts>/.x-session/account.json`: +// { "version": 1, "state": "suspended" | "ok", "note"?: "…", "at": <iso>, "by": "operator" } +// +// Marked BY HAND only (`pnpm ops x-session --json '{"accountState":…}'`, the +// control on /cookies). The fetchers were searched for an explicit signal of +// OUR account's suspension in X's own answers and carry none (gallery-dl's +// "account suspended" is about the account being read, not ours — +// social/xGalleryDlSignals.ts), so nothing here guesses one. +// +// While it is "suspended" the network guard refuses the X jobs that record +// posts as deleted or unavailable (lib/xSitting.ts xSuspendedRefuses), and +// every other X job's log says the account is suspended. +// +// A file that cannot be read is taken as SUSPENDED (fail closed: the jobs it +// refuses are the ones that could write a false "deleted"). +// +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import { isXAccountState, type XAccountState } from "../lib/xSitting"; + +export function xAccountStateFile(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, ".x-session", "account.json"); +} + +export type XAccountRecord = { + state: XAccountState; + note?: string; + at: string; + by: "operator"; + // The file is there and could not be read: taken as suspended. + unreadable?: true; +}; + +export const X_ACCOUNT_NOTE_MAX = 300; + +// The state on record; absent means "ok" (nothing marked). +export async function readXAccountState(paths: Pick<Paths, "transcriptsDir">): Promise<XAccountRecord | null> { + const read = await readJsonFile(xAccountStateFile(paths)); + if (!read.ok) { + if (read.reason === "absent") return null; + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + const v = read.value as Record<string, unknown> | null; + if (!v || typeof v !== "object" || !isXAccountState(v.state) || typeof v.at !== "string") { + return { state: "suspended", at: new Date(0).toISOString(), by: "operator", unreadable: true, note: "account.json cannot be read" }; + } + return { + state: v.state, + at: v.at, + by: "operator", + ...(typeof v.note === "string" && v.note.trim() ? { note: v.note.trim().slice(0, X_ACCOUNT_NOTE_MAX) } : {}), + }; +} + +// The operator marks the account. Answers what is now on record. +export async function writeXAccountState( + paths: Pick<Paths, "transcriptsDir">, + state: XAccountState, + opts: { note?: string; now?: number } = {}, +): Promise<XAccountRecord> { + const note = opts.note?.trim().slice(0, X_ACCOUNT_NOTE_MAX); + const record: XAccountRecord = { + state, + at: new Date(opts.now ?? Date.now()).toISOString(), + by: "operator", + ...(note ? { note } : {}), + }; + await writeJsonAtomic(xAccountStateFile(paths), { version: 1, ...record }, { mkdir: true }); + return record; +} + +// The alert line /cookies and `get x-session` show while it is suspended. +export function xAccountAlertLine(r: XAccountRecord): string { + if (r.unreadable) return "The X account's state cannot be read (.x-session/account.json): taken as suspended until it is marked again."; + return `The X account is marked suspended (since ${r.at.slice(0, 16).replace("T", " ")} UTC${r.note ? `: ${r.note}` : ""}). Availability checks and captures that record deleted posts are refused.`; +} + +// THE LAST LINE BEFORE A VERDICT IS WRITTEN (an X capture, an X availability +// check): while the account is marked suspended — marked during the run, the +// guard having let the job start — no post is recorded deleted or +// unavailable from what it answered. Only "available" is kept. Answers the +// observations to write (the same map when nothing is dropped). +export async function keepVerdictsTrustedWhileSuspended<V extends string>( + paths: Pick<Paths, "transcriptsDir">, + observations: Map<string, V>, + log: (line: string) => void, +): Promise<Map<string, V>> { + const acct = await readXAccountState(paths).catch(() => null); + if (acct?.state !== "suspended") return observations; + const kept = new Map<string, V>(); + let dropped = 0; + for (const [id, v] of observations) { + if (v === "available") kept.set(id, v); + else dropped++; + } + if (dropped > 0) { + log( + `The X account is marked suspended: ${dropped} "deleted" or "unavailable" verdict(s) from its answers were NOT recorded ` + + "(a suspended account's answers are thinned).", + ); + } + return kept; +} diff --git a/common/social/xArticleCapture.test.ts b/common/social/xArticleCapture.test.ts @@ -470,3 +470,15 @@ test("run: an older record's article is not lost by a run that does not read it" assert.deepEqual(h.visits, []); assert.deepEqual((await readPostCapture(dir))!.article, article); }); + +// LANE X-SITTINGS, review 2 G2: an image X's host answers 429 ends the image +// loop at once and marks the article refused, so the capture records the X +// stop and loads no further page. +test("article: an image answered 429 stops the images at once and marks the article refused", async () => { + const dir = await tmpDir(); + const p = articlePage([articleSnap()], { served: { [orig(COVER)]: { status: 429 } } }); + const res = await captureXArticle(p, LINK, dir, { now: NOW }); + assert.deepEqual(p.fetched, [orig(COVER)], "nothing after the 429"); + assert.equal(res.refused, true); + assert.match(res.stop ?? "", /rate limit \(429\) to an article image/); +}); diff --git a/common/social/xArticleCapture.ts b/common/social/xArticleCapture.ts @@ -190,6 +190,9 @@ export type XArticleCaptureResult = { record: ArticleCaptureRecord; // Set when the run must stop here (a login wall, X refusing pages). stop?: string; + // X refused the page ("Something went wrong", "rate limit exceeded"): the + // X stop (review 1 F1). + refused?: true; }; export type XArticleCaptureOptions = { @@ -220,6 +223,7 @@ export async function captureXArticle( ...(verdict.error ? { error: verdict.error } : {}), }, ...(verdict.stop ? { stop: verdict.stop } : {}), + ...(verdict.refused ? { refused: true as const } : {}), }); try { @@ -334,6 +338,9 @@ export async function captureXArticle( ...(trimmed ? { trimmed: true } : {}), ...(error ? { error } : {}), }, + // An image refused with 429: the caller records X's stop and loads no + // further page (review 2 G2). + ...(images.refused ? { refused: true as const, stop: "X answered a rate limit (429) to an article image; stopping rather than asking again." } : {}), }; } @@ -345,7 +352,7 @@ async function fetchArticleImages( blocks: ReadonlyArray<XArticleBlock>, dir: string, opts: XArticleCaptureOptions, -): Promise<{ saved: Map<string, CapturedFile>; errors: string[] }> { +): Promise<{ saved: Map<string, CapturedFile>; errors: string[]; refused?: true }> { const saved = new Map<string, CapturedFile>(); const errors: string[] = []; const srcs = [...new Set(blocks.flatMap((b) => (b.type === "image" && b.src ? [b.src] : [])))]; @@ -355,7 +362,9 @@ async function fetchArticleImages( return { saved, errors }; } let n = 0; + let refused = false; for (const src of srcs) { + if (refused) break; if (opts.signal?.aborted) { errors.push("cancelled before the rest of the images"); break; @@ -369,6 +378,12 @@ async function fetchArticleImages( const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); if (!res.ok()) { last = `HTTP ${res.status()} for ${url}`; + // X's image host rate-limited it: the X stop, and no further image + // (review 2 G2). + if (res.status() === 429) { + refused = true; + break; + } continue; } const body = await res.body(); @@ -384,7 +399,7 @@ async function fetchArticleImages( if (last) errors.push(last); } if (saved.size) opts.onLog?.(`article: ${saved.size} image(s) saved.`); - return { saved, errors }; + return { saved, errors, ...(refused ? { refused: true as const } : {}) }; } // A re-capture with fewer images leaves no older numbered file behind. diff --git a/common/social/xAvatarCapture.ts b/common/social/xAvatarCapture.ts @@ -204,6 +204,16 @@ export async function saveXAvatars( } try { const res = await page.request.get(url, { timeout: 30_000, failOnStatusCode: false }); + // X's media host rate-limited the avatar: the one X stop (review 1 F1), + // and no further avatar is asked in this run. + if (res.status() === 429) { + const { recordXStop } = await import("../jobs/downloadBackoff"); + const { getPaths } = await import("../lib/paths"); + await recordXStop("a rate limit (429) to an avatar", getPaths()).catch(() => 0); + summary.failed.push({ handle: c.handle, error: `HTTP 429 for ${url}` }); + onLog?.(`avatar @${c.handle}: X answered 429 (rate limit); no further avatar is asked.`); + break; + } if (!res.ok()) throw new Error(`HTTP ${res.status()} for ${url}`); const type = res.headers()["content-type"] ?? ""; if (type && !/^image\//i.test(type)) throw new Error(`${url} answered ${type.split(";")[0]}, not an image`); diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -20,6 +20,7 @@ // controller and the editor's Settings section all read it. import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk"; +import { parseXGapMinutes, parseXPostsPerJob, parseXSittingJobs } from "../lib/xSitting"; export type XCookieSource = "browser" | "profile"; @@ -56,6 +57,14 @@ export type XSocialSettings = { // many minutes and carries a login. 0 turns the rule off. Absent = // X_DEFAULT_MAX_COOKIE_AGE_MINUTES. common/jobs/networkGuard.ts. maxCookieAgeMinutes?: number; + // X IN SITTINGS (lib/xSitting.ts): the X job starts one cookie refresh + // admits (1-6; absent = 4), and the range X's queue gap is drawn from + // (minutes, never below 5; absent = 5 and 12). + sittingJobs?: number; + gapMinMinutes?: number; + gapMaxMinutes?: number; + // The posts one X walk may read (20-400; absent = 300). + maxPostsPerJob?: number; }; // Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click @@ -127,11 +136,19 @@ export function sanitizeSocial(value: unknown): SocialSettings { }; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes); + const sittingJobs = parseXSittingJobs(x.sittingJobs); + const gapMinMinutes = parseXGapMinutes(x.gapMinMinutes); + const gapMaxMinutes = parseXGapMinutes(x.gapMaxMinutes); + const maxPostsPerJob = parseXPostsPerJob(x.maxPostsPerJob); return { x: { ...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}), ...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}), ...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}), + ...(sittingJobs !== undefined ? { sittingJobs } : {}), + ...(gapMinMinutes !== undefined ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== undefined ? { gapMaxMinutes } : {}), + ...(maxPostsPerJob !== undefined ? { maxPostsPerJob } : {}), }, ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), ...(Object.keys(instagram).length > 0 ? { instagram } : {}), diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -305,7 +305,7 @@ test("search argv: the timeline's flags and login, latest-first max_id paging, n "extractor.twitter.search-results=latest", "extractor.twitter.search-pagination=max_id", "extractor.twitter.sleep-request=4.0-10.0", - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]) { assert.ok(argv.includes(opt), opt); } @@ -334,13 +334,13 @@ test("stream: tracks the oldest post id read (any post, archived or not) and the assert.equal(s.pendingCount(), 0); }); -test("every X read paces itself: a random 4–10 s before each request, rate limits waited out", () => { +test("every X read paces itself: a random 4–10 s before each request, a rate limit stops the run (abort, review 1 F2)", () => { for (const argv of [ buildGalleryDlArgs({ accountUrl: "https://x.com/example_user" }), buildGalleryDlSearchArgs({ handle: "example_user", position: { since: "2020-12-11", until: "2021-03-11" } }), ]) { assert.ok(argv.includes(`extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`)); - assert.ok(argv.includes("extractor.twitter.ratelimit=wait")); + assert.ok(argv.includes("extractor.twitter.ratelimit=abort")); } const [lo, hi] = X_SLEEP_REQUEST.split("-").map(Number); assert.ok(lo >= 4 && hi > lo, "a range, not a fixed gap"); @@ -377,7 +377,7 @@ test("capture argv: paced and logged in exactly as the reads are", () => { const capture = buildGalleryDlCaptureArgs({ id: "42", dir: "/d", cookieFile: JAR }); for (const flag of [ `extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`, - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]) { assert.ok(read.includes(flag) && capture.includes(flag), flag); } @@ -617,3 +617,14 @@ test("stream: after a search-phase place `3_<N>/`, a first-page post above N mea assert.equal(after([299, 350]), true); assert.equal(after([...Array.from({ length: TOP_RESTART_WINDOW }, (_, i) => 300 - i), 301]), false); }); + +// LANE X-SITTINGS: gallery-dl reads a cookie FILE and never writes it back +// (its `cookies-update` is on by default and rewrote the broker's jar after +// every run — the jar's mtime then said "refreshed" after every fetch). +import { galleryDlLoginArgs } from "./xGalleryDlFetcher"; +test("a cookie file is passed with cookies-update off; a browser's store is passed as it was", () => { + assert.deepEqual(galleryDlLoginArgs({ cookieFile: "/c/.x-session/cookies.txt" }), ["--cookies", "/c/.x-session/cookies.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "file:/c/other.txt" }), ["--cookies", "/c/other.txt", "-o", "cookies-update=false"]); + assert.deepEqual(galleryDlLoginArgs({ cookies: "firefox" }), ["--cookies-from-browser", "firefox"]); + assert.deepEqual(galleryDlLoginArgs({}), []); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -31,6 +31,8 @@ import type { Readable } from "node:stream"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; +import { recordXStop } from "../jobs/downloadBackoff"; +import { currentJobContext } from "../lib/jobContext"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post, PostRef } from "../lib/posts"; @@ -233,15 +235,18 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { // account-history walk is hundreds of requests, so every read waits a RANDOM // 4–10 s before each one (gallery-dl's own "a-b" range, a uniform draw per // request): no fixed rhythm, and well under the rate a person scrolling would -// make. Running into the limit anyway is waited out, never pushed through -// ("wait" is gallery-dl's default; stated so it stays). Every gallery-dl run +// make. Running into the limit anyway STOPS THE RUN AT ONCE ("abort"; the +// operator, 21 Nov 2026, review 1 F2 of lane x-sittings): it used to be waited +// out in-process ("wait") and the same job paged on after X's reset. Now the +// run ends at its last page, the 15-minute X stop is recorded the moment the +// line is seen (recordXStop), and the job ends deferred. Every gallery-dl run // against X carries these — the reads and the post capture alike. function galleryDlPacingArgs(): string[] { return [ "-o", `extractor.twitter.sleep-request=${X_SLEEP_REQUEST}`, "-o", - "extractor.twitter.ratelimit=wait", + "extractor.twitter.ratelimit=abort", ]; } @@ -251,11 +256,17 @@ function galleryDlPacingArgs(): string[] { // session, though — gallery-dl will block for minutes on "Waiting for N // minutes (rate limit)" — so credentials remain the path for a deep backfill. // When none are configured we simply run as a guest rather than failing. -function galleryDlLoginArgs(opts: GalleryDlLoginAndCap): string[] { - if (opts.cookieFile) return ["--cookies", opts.cookieFile]; +// +// A COOKIE FILE IS READ, NEVER WRITTEN BACK (lane x-sittings): gallery-dl's +// `cookies-update` is on by default and rewrites a `--cookies` file with the +// session's cookies after every run (gallery-dl 1.32.9 Extractor.cookies_store). +// On the broker's jar that rewrite made every fetch look like a refresh (the +// jar's mtime), so it is passed off. +export function galleryDlLoginArgs(opts: Pick<GalleryDlLoginAndCap, "cookieFile" | "cookies">): string[] { // Same browser-cookie spec yt-dlp uses (cookiePolicy.ts), same syntax — // `file:<path>` included, which is `--cookies <path>`. - return cookieArgs(opts.cookies); + const args = opts.cookieFile ? ["--cookies", opts.cookieFile] : cookieArgs(opts.cookies); + return args.includes("--cookies") ? [...args, "-o", "cookies-update=false"] : args; } // The random gap a post capture waits before each contact with X after its @@ -354,7 +365,14 @@ export async function downloadXPostMedia(args: { for (const line of stderr.split("\n")) { if (line.trim()) args.onLog?.(`gallery-dl: ${line.trim()}`); } + // X's rate limit or bot check on a post's media (review 1 F1): the X stop, + // and the capture run stops here. + const stopWhy = stderr.split("\n").map(xStopLine).find((w) => w !== null) ?? null; + if (stopWhy) await noteXRateLimit(args.onLog, stopWhy.replace("(gallery-dl)", "(gallery-dl, a post's media)")); const blocked = stderr.split("\n").find((l) => !/\]\[debug\]/.test(l) && xBlockLine(l)); + if (stopWhy && !blocked) { + return { ok: false, error: `X answered ${stopWhy} to the media download.`, stop: "X answered a rate limit; stopping rather than asking again." }; + } if (blocked && !res.isCanceled) { await noteXOutcome(blocked, `https://x.com/i/status/${args.id}`, "", args.onLog); return { ok: false, needsCookies: true, error: xBlockedError(blocked) }; @@ -431,6 +449,10 @@ export async function captureXPostsByIds( downloadMedia: input.downloadMedia ? (args) => input.downloadMedia!(args, loginDownload) : loginDownload, pauseMs: () => xRequestPauseMs(), pause, + // X refused a page: the X stop, recorded at once (review 1 F1). + noteXStop: (why) => recordXStop(why, paths), + // Any reader of this job that met X's stop (an avatar's 429) halts it. + xStopped: () => Boolean(currentJobContext()?.xStop), articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), }); } @@ -682,7 +704,18 @@ const CHECKPOINT_EVERY_MS = 60_000; const CURSOR_LINE = /\]\[debug\]\s+Cursor:\s+(\S+)\s*$/; const DEBUG_LINE = /\]\[debug\]/; -const RATE_LIMIT_LINE = /Waiting for .*rate limit|429 Too Many Requests/i; +// gallery-dl's rate-limit lines: its wait ("Waiting for … (rate limit)", an +// older run's), its abort ("[twitter][error] Rate limit exceeded") and a bare 429. +const RATE_LIMIT_LINE = /Waiting for .*rate limit|429 Too Many Requests|rate limit exceeded/i; + +// Does this stderr line say X answered a rate limit, or a bot check (a +// challenge)? Either is the X stop (review 1 F1). +export function xStopLine(line: string): "a rate limit (gallery-dl)" | "a bot check (gallery-dl)" | null { + if (DEBUG_LINE.test(line)) return null; + if (RATE_LIMIT_LINE.test(line)) return "a rate limit (gallery-dl)"; + if (xBlockLine(line) && xBlockKind(line) === "challenge") return "a bot check (gallery-dl)"; + return null; +} const STDERR_TAIL_LINES = 20; export type GalleryDlCheckpoint = { posts: Post[]; cursor: string }; @@ -1055,6 +1088,19 @@ async function galleryDlLoginFor( return { cookies: choice.cookies, cookieFile: choice.cookieFile }; } +// X ANSWERED THIS RUN 429 (gallery-dl waited it out between pages): X is left +// alone for 15 minutes after it — the cooldown the network guard refuses +// every X job with (lane x-sittings, rule 6). Best effort: a failed write is +// logged, never thrown. +async function noteXRateLimit(onLog?: (line: string) => void, why = "a rate limit (gallery-dl)"): Promise<void> { + try { + const until = await recordXStop(why, getPaths()); + onLog?.(`X is left alone until ${new Date(until).toISOString().slice(11, 16)} UTC (15 minutes after its rate limit): no X job starts before then.`); + } catch (err) { + onLog?.(`X's rate-limit cooldown could not be recorded: ${(err as Error).message}`); + } +} + // Feed a pipe to `onLine` a line at a time; resolves once it has closed. function readLines( input: Readable | null | undefined, @@ -1290,12 +1336,21 @@ async function walkSearchWindows( stream.pushStdout(line); maybeCheckpoint(); }); + // X'S STOP, THE MOMENT ITS LINE IS SEEN (review 1 F1/F2): recorded at + // once and the run ended — never waited out and paged on. + let xStopped: Promise<void> | null = null; const stderrDone = readLines(subprocess.stderr, (line) => { stream.pushStderr(line); + const why = xStopLine(line); + if (why && !xStopped) { + xStopped = noteXRateLimit(onLog, why); + subprocess.kill("SIGTERM"); + } maybeCheckpoint(); }); const res = await subprocess; drain?.removeEventListener("abort", onDrain); + if (xStopped) await xStopped; await Promise.all([stdoutDone, stderrDone]); await checkpoints; @@ -1314,7 +1369,9 @@ async function walkSearchWindows( maxId: stream.oldestId ?? windowStart.maxId, }; if (stream.rateLimited) { - onLog?.("[rate-limit] X throttled this search — gallery-dl paused between pages."); + onLog?.(`[rate-limit] X answered this search with a rate limit: the walk stops at ${here.since} – ${here.until}; a later sitting resumes there.`); + if (!xStopped) await noteXRateLimit(onLog); + return stopped(here, { rateLimited: true }); } onLog?.( `${windowStart.since} – ${windowStart.until}: read ${stream.distinct} post(s), ${stream.newPosts} new` + @@ -1565,11 +1622,19 @@ export const xGalleryDlFetcher: SocialFetcher = { subprocess.kill(); } }); + // X'S STOP, THE MOMENT ITS LINE IS SEEN (review 1 F1/F2): recorded at + // once and the run ended at its last page. + let xStopped: Promise<void> | null = null; const stderrDone = readLines(subprocess.stderr, (line) => { if (stream.pushStderr(line)) { betweenPages = true; if (input.drain?.aborted) stopForDrain(); } + const why = xStopLine(line); + if (why && !xStopped) { + xStopped = noteXRateLimit(onLog, why); + subprocess.kill("SIGTERM"); + } maybeCheckpoint(); }); @@ -1577,6 +1642,7 @@ export const xGalleryDlFetcher: SocialFetcher = { input.drain?.removeEventListener("abort", onDrain); await Promise.all([stdoutDone, stderrDone]); await checkpoints; + if (xStopped) await xStopped; const spawnError = `${res.code ?? ""} ${res.message ?? ""}`; if (res.failed && /ENOENT/.test(spawnError) && stream.distinct === 0) { @@ -1586,13 +1652,13 @@ export const xGalleryDlFetcher: SocialFetcher = { } const posts = stream.finish(); - if (stream.rateLimited) { + const rateLimitedHere = stream.rateLimited; + if (rateLimitedHere) { onLog?.( - "[rate-limit] X throttled this run — gallery-dl paused between pages. " + - (cookieFile || cookies - ? "Consider a longer sync interval." - : "This is a guest (no-credential) run; guest quota is much smaller."), + "[rate-limit] X answered this run with a rate limit: gallery-dl stopped at its last page. " + + (cookieFile || cookies ? "" : "This is a guest (no-credential) run; guest quota is much smaller."), ); + if (!xStopped) await noteXRateLimit(onLog); } onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + @@ -1638,6 +1704,10 @@ export const xGalleryDlFetcher: SocialFetcher = { }; } + // Stopped at X's rate limit: what was read is kept, and the walk resumes + // from its last page in a later sitting. + if (rateLimitedHere) return { posts, complete: false, cursor: resumeAt, rateLimited: true }; + if (stoppedAtKnown) return { posts, complete: true, caughtUp: true }; if (res.isCanceled || signal.aborted || res.timedOut) { diff --git a/common/social/xPlaywrightFetcher.ts b/common/social/xPlaywrightFetcher.ts @@ -125,6 +125,23 @@ function mergeTweet( return merged; } +// REFUSED (lane x-sittings, review 2 G1, the operator's ruling): this reader +// reads no response status and no refusal or challenge page, so a 429 from X +// would be scrolled past and reported as a complete walk, with no X stop and +// no place to continue from. Until it can tell X's refusals (and keep a +// place), no X job runs it: fetchPosts refuses the channel, and fetch() below +// refuses too, for any caller that reaches it another way. +export const X_PLAYWRIGHT_REFUSED = (slug: string) => + `${slug}'s post fetcher is x-playwright (the Playwright fallback), which cannot tell when X refuses or rate-limits ` + + "it, so it is refused: set the channel's postFetcher to x-gallery-dl (the channel page → Configure → scraping " + + `method, or pnpm ops channel-config --json '{"slug":"${slug}","patch":{"postFetcher":"x-gallery-dl"}}'), then fetch again. Nothing was asked of X.`; + +// Always: no setting, environment variable or option turns the refusal off. +// Lifting it is a code change, made once this reader sees X's refusals. +export function xPlaywrightRefused(): boolean { + return true; +} + export const xPlaywrightFetcher: SocialFetcher = { id: "x-playwright", label: "X / Twitter (Playwright fallback)", @@ -155,6 +172,10 @@ export const xPlaywrightFetcher: SocialFetcher = { }, async fetch(input: PostFetchInput): Promise<PostFetchResult> { + // Refused before anything opens (review 2 G1). + if (xPlaywrightRefused()) { + return { posts: [], complete: false, error: X_PLAYWRIGHT_REFUSED(input.channelSlug || "This channel") }; + } const { accountUrl, channelSlug, since, seenIds, limit, signal, onLog } = input; const paths = getPaths(); diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -15,6 +15,7 @@ import type { PageLike } from "./playwrightRuntime"; import { captureXPosts, classifyXPostSnapshot, + X_STOPPED_CAPTURE, shootXPost, type XCaptureDeps, type XPostSnapshot, @@ -501,3 +502,45 @@ process.stdout.write(tag + "\\thttps://pbs.example/77.jpg\\t" + file + "\\n"); delete process.env.FAKE_MODE; } }); + +// LANE X-SITTINGS, review 1 F1: a page X refused ("Something went wrong", +// "rate limit exceeded") is a refusal like a 429 — the run records the X stop +// through its deps, at once, and stops there. +test("run: a refused page records the X stop and stops the run", async () => { + const h = harness({ "11": [post()], "22": [page("Something went wrong. Try reloading. Retry")], "33": [post()] }); + const stops: string[] = []; + const res = await captureXPosts(await input(["11", "22", "33"]), { ...h.deps, noteXStop: async (why) => void stops.push(why) }); + assert.deepEqual(stops, ["a refused page to a capture"]); + assert.match(res.stoppedEarly ?? "", /Stopped at 22/); + assert.deepEqual(res.outcomes.map((o) => o.id), ["11", "22"]); + assert.equal(classifyXPostSnapshot(page("Rate limit exceeded")).refused, true); +}); + +// LANE X-SITTINGS, review 2 G2: once any reader of the job met X's stop (an +// avatar's 429), the capture loads no further page; three pages in a row that +// would not render record the stop. +test("run: a stop met by another reader of the job halts the capture before its next page load", async () => { + const h = harness({ "11": [post()], "22": [post()], "33": [post()] }); + let stoppedNow = false; + const res = await captureXPosts(await input(["11", "22", "33"]), { + ...h.deps, + // The first post's media download is where "the avatar's 429" landed. + downloadMedia: async (a) => { + const r = await h.deps.downloadMedia(a); + stoppedNow = true; + return r; + }, + xStopped: () => stoppedNow, + }); + assert.equal(res.stoppedEarly, X_STOPPED_CAPTURE); + assert.deepEqual(res.outcomes.map((o) => o.id), ["11"]); + assert.deepEqual(h.downloads, ["11"], "no page or download after the stop"); +}); + +test("run: three pages in a row that would not render record the X stop", async () => { + const h = harness({ "11": [page("")], "22": [page("")], "33": [page("")], "44": [post()] }); + const stops: string[] = []; + const res = await captureXPosts(await input(["11", "22", "33", "44"]), { ...h.deps, noteXStop: async (w) => void stops.push(w) }); + assert.deepEqual(stops, ["three pages in a row it would not render, to a capture"]); + assert.match(res.stoppedEarly ?? "", /3 posts in a row failed/); +}); diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -194,6 +194,9 @@ export type XPostVerdict = { // Set when the run must stop here: the next post would meet the same page. stop?: string; error?: string; + // X REFUSED THE PAGE ("Something went wrong", "rate limit exceeded"): a + // refusal like a 429 — the X stop is recorded (review 1 F1). + refused?: true; }; // What a snapshot means. Pure, so every marker is testable without a browser. @@ -217,6 +220,7 @@ export function classifyXPostSnapshot( state: "error", error: `X answered “Something went wrong” instead of the ${noun}.`, stop: "X is refusing pages right now; stopping rather than asking again.", + refused: true, }; } if (DELETED_TEXT.some((re) => re.test(s.text))) return { state: "deleted" }; @@ -355,6 +359,14 @@ export type XCaptureDeps = { // A page in the logged-in profile. Opened on the first shot, closed at the // end of the run. openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>; + // X REFUSED a page or the media (a rate limit, a bot check): the X stop, + // recorded at once (jobs/downloadBackoff.ts recordXStop in production). + noteXStop?: (why: string) => Promise<unknown>; + // Has this job met X's stop (a refusal recorded by any reader inside it — + // an avatar's 429, an article image's)? Asked before every page load: a + // capture asks X nothing more once it has (review 2 G2). Production: the + // job context's xStop. + xStopped?: () => boolean; // One post's media into `dir` (gallery-dl in production). downloadMedia: (args: { id: string; @@ -374,6 +386,23 @@ export type XCaptureDeps = { // failing every post should not page through the rest of the list. const STOP_AFTER_ERRORS = 3; +export const X_STOPPED_CAPTURE = + "X refused this capture (a rate limit, a bot check or a page it would not render): the X stop is recorded and no further page is loaded in this job; the rest are left for a later sitting."; + +// The capture's halt (review 2 G2): the stop noted in this run, or met by any +// reader of this job. +function haltFor(deps: Pick<XCaptureDeps, "noteXStop" | "xStopped">) { + let noted = false; + return { + note: async (why: string) => { + noted = true; + await deps.noteXStop?.(why); + }, + halted: () => noted || (deps.xStopped?.() ?? false), + }; +} + + // The capture loop: per id, what is owed (captureWork), the shot, the media, // the record. Every post's record is written as soon as that post is done, so // a cancel or a crash loses at most the post in hand. @@ -403,6 +432,7 @@ export async function captureXPosts( let errorsInARow = 0; let browser: { page: PageLike; close: () => Promise<void> } | undefined; + const halt = haltFor(deps); const contact = async () => { if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); }; @@ -424,6 +454,7 @@ export async function captureXPosts( try { for (const [i, id] of input.ids.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); const dir = postCaptureDir(input.outDir, id); @@ -463,6 +494,7 @@ export async function captureXPosts( let stop: string | undefined; if (work.shot || threadOwed) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -499,6 +531,7 @@ export async function captureXPosts( threadError = res.error ?? `The page showed the post as ${res.state}.`; } stop = res.stop; + if (res.refused) await halt.note("a refused page to a capture"); if (res.thread) { if ("thread" in res.thread) thread = res.thread.thread; else if ("none" in res.thread) threadNone = res.thread.none; @@ -515,6 +548,7 @@ export async function captureXPosts( // download: X has nothing to give for a deleted or walled one. const postIsThere = state === undefined || state === "captured"; if (work.media && postIsThere && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); await mkdir(dir, { recursive: true }); @@ -548,6 +582,7 @@ export async function captureXPosts( let article: ArticleCaptureRecord | undefined = existing?.article; let articleFailed = false; if (work.article && articleLink && (state === undefined || state === "captured") && !stop) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); await contact(); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); browser ??= await deps.openPage(); @@ -564,6 +599,7 @@ export async function captureXPosts( // A run that only read the article learns of the post only that it // linked to a readable article. state ??= article.state === "captured" ? "captured" : "error"; + if (got.refused) await halt.note("a refusal to an article (its page or an image) in a capture"); if (got.stop) { stop = got.stop; if (article.state === "login-wall") needsCookies = true; @@ -621,6 +657,9 @@ export async function captureXPosts( } errorsInARow = finalState === "error" || articleFailed ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + // Pages that would not render, three in a row: X's bot check as + // often as not — the X stop (review 2 G2). + await halt.note("three pages in a row it would not render, to a capture"); return stopped( `${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`, ); @@ -695,8 +734,10 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, id] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -713,6 +754,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no avatar read — ${why}.`); + if (res.refused) await halt.note("a refused page to a capture"); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { needsCookies: res.state === "login-wall", @@ -720,6 +762,7 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; @@ -784,8 +827,10 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): onLog?.(why); return done({ stoppedEarly: why, ...extra }); }; + const halt = haltFor(deps); try { for (const [i, { id, existing }] of picks.entries()) { + if (halt.halted()) return stopped(X_STOPPED_CAPTURE); if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); @@ -804,6 +849,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): if (res.state !== "captured") { const why = res.error ?? `the page showed the post as ${res.state}`; onLog?.(`${id}: no context read — ${why}.`); + if (res.refused) await halt.note("a refused page to a capture"); summary.failed.push({ id, error: why }); if (res.stop) { return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { @@ -812,6 +858,7 @@ async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): } errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; if (errorsInARow >= STOP_AFTER_ERRORS) { + await halt.note("three pages in a row it would not render, to a capture"); return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); } continue; diff --git a/common/social/xSessionBroker.test.ts b/common/social/xSessionBroker.test.ts @@ -13,7 +13,7 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChromiumLike } from "./playwrightRuntime"; import { writeXBrowserRecord } from "./xBrowser"; -import { refreshXCookies, xCookieFile, xProfileDir } from "./xSessionBroker"; +import { connectXAccount, readXSessionStatus, refreshXCookies, xCookieFile, xJarRefreshedFile, xProfileDir } from "./xSessionBroker"; const TMP = mkdtempSync(path.join(os.tmpdir(), "xl-broker-")); after(() => rm(TMP, { recursive: true, force: true })); @@ -70,7 +70,8 @@ function fakeChromium(answers: Record<string, Cookie[] | Error>) { let n = 0; async function corpus(opts: { jar?: "logged-in" | "logged-out"; recorded?: boolean }) { - const paths = { transcriptsDir: path.join(TMP, `corpus-${++n}`) } as Paths; + const root = path.join(TMP, `corpus-${++n}`); + const paths = { transcriptsDir: root, autoQueueStateFile: path.join(root, ".auto-queue", "state.json") } as Paths; await mkdir(xProfileDir(paths), { recursive: true }); if (opts.recorded) { await writeXBrowserRecord( @@ -155,3 +156,41 @@ test("the bundled build cannot open the profile: the recorded browser reads it", assert.deepEqual(launches, ["bundled", SYSTEM_EXE]); assert.match(await jarText(paths), /auth_token\tVIA-RECORD/); }); + +test("lane x-sittings: a refresh is STAMPED, and the jar's refresh time is the stamp, not the jar's mtime (gallery-dl rewrote the jar after every run)", async () => { + const paths = await corpus({ jar: "logged-in", recorded: true }); + // A jar from before the stamp: its time is its mtime. + const old = new Date(Date.now() - 3 * 3600_000); + const { utimes } = await import("node:fs/promises"); + await utimes(xCookieFile(paths), old, old); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, old.toISOString()); + // A Refresh writes the stamp beside the jar. + const { chromium } = fakeChromium({ bundled: [cookie("auth_token", "FRESH")] }); + const before = Date.now(); + const status = await refreshXCookies(paths, { chromium }); + const stamp = JSON.parse(await readFile(xJarRefreshedFile(paths), "utf8")); + assert.equal(stamp.version, 1); + assert.ok(Date.parse(stamp.at) >= before - 1000); + assert.equal(status.cookiesUpdatedAt, new Date(Date.parse(stamp.at)).toISOString()); + // Anything else rewriting the jar (gallery-dl's cookies-update, a copy, touch) moves its mtime, not its refresh. + const later = new Date(Date.now() + 3600_000); + await utimes(xCookieFile(paths), later, later); + assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, status.cookiesUpdatedAt); +}); + +test("review 1 F9: Connect and Refresh ask X, so they are refused during X's 15-minute stop — with when it ends — and when the stop cannot be read", async () => { + const { recordXStop } = await import("../jobs/downloadBackoff"); + const { writeFile: wf, mkdir: md } = await import("node:fs/promises"); + const paths = await corpus({ jar: "logged-in", recorded: true }); + const { chromium, launches } = fakeChromium({ bundled: [cookie("auth_token", "FRESH")] }); + await recordXStop("a rate limit", paths); + await assert.rejects(refreshXCookies(paths, { chromium }), /^Error: Refresh cookies is refused until \d\d:\d\d UTC \(1[45] min\): X answered a rate limit or a bot check/); + await assert.rejects(connectXAccount(paths, { chromium }), /^Error: Connect X account is refused until/); + assert.deepEqual(launches, [], "no browser was opened"); + assert.match(await jarText(paths), /OLD-LOGIN/, "the jar is untouched"); + // A stop that cannot be read refuses too. + const p2 = await corpus({ jar: "logged-in", recorded: true }); + await md(path.dirname(p2.autoQueueStateFile), { recursive: true }); + await wf(p2.autoQueueStateFile, "{ broken"); + await assert.rejects(refreshXCookies(p2, { chromium }), /cannot be read/); +}); diff --git a/common/social/xSessionBroker.ts b/common/social/xSessionBroker.ts @@ -27,8 +27,9 @@ import path from "node:path"; import { readFile, rm, stat } from "node:fs/promises"; import { execa } from "execa"; -import { writeFileAtomic } from "../lib/jsonFile-server"; +import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; +import { xStopRemainingMs } from "../jobs/downloadBackoff"; import { importPlaywright, type BrowserContextLike, @@ -57,12 +58,37 @@ export function xCookieFile(paths: Paths): string { return path.join(paths.transcriptsDir, ".x-session", "cookies.txt"); } +// WHEN THE JAR WAS LAST REFRESHED (lane x-sittings): the broker's own stamp, +// written beside the jar by Connect and Refresh (writeCookieJar, the jar's one +// writer), `{version: 1, at: <iso>}`. Not the jar's mtime: gallery-dl rewrote +// the jar after every run (its `cookies-update`, on by default — now passed +// off, xGalleryDlFetcher.ts), so the mtime said "refreshed" after every fetch, +// the fresh-jar rule never bit inside a chain of fetches, and a sitting keyed +// to it would never end (jobs/xSitting.ts). +export function xJarRefreshedFile(paths: Paths): string { + return path.join(paths.transcriptsDir, ".x-session", "refreshed.json"); +} + +// ABSENT: undefined (a jar from before the stamp: its mtime is its time). +// THERE BUT UNREADABLE: the epoch (review 1 F7) — fail closed: the jar reads +// as never refreshed (the fresh-jar rule refuses) and no new sitting begins. +const UNREADABLE_STAMP = new Date(0).toISOString(); + +async function readRefreshedAt(paths: Paths): Promise<string | undefined> { + const read = await readJsonFile(xJarRefreshedFile(paths)).catch(() => ({ ok: false as const, reason: "unreadable" as const })); + if (!read.ok) return read.reason === "absent" ? undefined : UNREADABLE_STAMP; + const at = (read.value as { at?: unknown } | null)?.at; + return typeof at === "string" && Number.isFinite(Date.parse(at)) ? new Date(Date.parse(at)).toISOString() : UNREADABLE_STAMP; +} + export type XSessionStatus = { // A profile directory exists on disk. hasProfile: boolean; // A cookie jar has been exported. hasCookies: boolean; - // When the cookie jar was last written. + // When the cookie jar was last REFRESHED (Connect / Refresh): the broker's + // stamp (xJarRefreshedFile); for a jar written before the stamp existed, + // the jar's mtime. cookiesUpdatedAt?: string; // True when the exported jar carries the session cookie X actually // authenticates with. A jar without it is present-but-useless. @@ -83,7 +109,7 @@ export async function readXSessionStatus(paths: Paths): Promise<XSessionStatus> try { const st = await stat(cookieFile); hasCookies = true; - cookiesUpdatedAt = new Date(st.mtimeMs).toISOString(); + cookiesUpdatedAt = (await readRefreshedAt(paths)) ?? new Date(st.mtimeMs).toISOString(); const text = await readFile(cookieFile, "utf8"); looksAuthenticated = text.includes(AUTH_COOKIE); } catch { @@ -179,6 +205,24 @@ function firstLine(err: unknown): string { // Playwright is imported dynamically: this module must stay importable on a // host with no browsers installed (the Docker build image), where only the // status/read helpers above are ever called. +// A CONNECT OR A REFRESH ASKS X (it loads x.com): refused while X's +// 15-minute stop after a rate limit or a bot check lasts (review 1 F9), with +// when it ends — and while that stop cannot be read. +export async function xStopRefusalForSession(paths: Paths, what: string, now: number = Date.now()): Promise<string | null> { + let ms: number; + try { + ms = await xStopRemainingMs(paths, now); + } catch (err) { + return `${what} is refused: X's rate-limit stop cannot be read (${(err as Error).message}), and ${what.toLowerCase()} loads x.com.`; + } + if (ms <= 0) return null; + const until = new Date(now + ms).toISOString().slice(11, 16); + return ( + `${what} is refused until ${until} UTC (${Math.ceil(ms / 60_000)} min): X answered a rate limit or a bot check, ` + + `and ${what.toLowerCase()} loads x.com. Press it again after ${until} UTC.` + ); +} + export async function connectXAccount( paths: Paths, opts: { @@ -192,6 +236,8 @@ export async function connectXAccount( display?: HeadedDisplayLaunchDeps; } = {}, ): Promise<XSessionStatus & { browser: string; display: string }> { + const stopped = await xStopRefusalForSession(paths, "Connect X account"); + if (stopped) throw new Error(stopped); const log = opts.onLog ?? (() => {}); const profileDir = xProfileDir(paths); // The profile directory is made by launchHeadedContext, once a display is found. @@ -321,6 +367,8 @@ export async function refreshXCookies( paths: Paths, opts: ProfileLaunchOpts = {}, ): Promise<XSessionStatus> { + const stopped = await xStopRefusalForSession(paths, "Refresh cookies"); + if (stopped) throw new Error(stopped); const log = opts.onLog ?? (() => {}); const profileDir = xProfileDir(paths); if (!(await exists(profileDir))) { @@ -378,6 +426,8 @@ async function writeCookieJar( mkdir: true, mode: 0o600, }); + // The refresh, stamped: what the fresh-jar rule and X's sitting read. + await writeJsonAtomic(xJarRefreshedFile(paths), { version: 1, at: new Date().toISOString() }, { mkdir: true }); const authed = cookies.some((c) => c.name === AUTH_COOKIE); log( `Exported ${cookies.length} X cookie(s) to ${file}` + @@ -385,8 +435,14 @@ async function writeCookieJar( ); } -// Forget the stored session entirely (profile + exported jar). +// Forget the stored LOGIN: the profile, the exported jar and its refresh +// stamp. NOT what describes the ACCOUNT and its use (review 1 F3): the +// operator's suspended mark (account.json), the sitting (sitting.json) and X's +// job count (job-starts.json) stay; X's 15-minute stop is not here at all. +// Clearing those is its own act (Mark ok; a new sitting at the next Refresh). export async function clearXSession(paths: Paths): Promise<void> { - await rm(path.dirname(xCookieFile(paths)), { recursive: true, force: true }); + await rm(xProfileDir(paths), { recursive: true, force: true }); + await rm(xCookieFile(paths), { force: true }); + await rm(xJarRefreshedFile(paths), { force: true }); } diff --git a/common/ytdlp/captionsRefetch.test.ts b/common/ytdlp/captionsRefetch.test.ts @@ -0,0 +1,232 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, 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/captionsRefetch.test.ts +// +// A MANAGED RE-DOWNLOAD OVER A CAPTION STORED COMPRESSED (REVIEW-1 F1 of the +// captions lane). Main's rule is kept: a re-download fetches the captions +// again and the new file replaces the old one. Over a stored track the new +// file lands beside it, and after the pass each such track is settled: the +// same content keeps the stored form (the new copy dropped, nothing moves); +// new content with cues replaces it, only once whole; nothing, a `.part`, an +// empty or cue-less file leaves the stored track untouched. The job log says +// which, per track. The yt-dlp is a temp node script; no network. + +const ID = "Zz0capRefet"; +const VIDEO = `https://www.youtube.com/watch?v=${ID}`; +const EN = "transcript.en.vtt"; + +// The prefetch writes the info json; the subtitle pass copies whatever the +// scenario put in `landing/` into the video dir (what yt-dlp would write, not +// seeing a .zst), or exits 1 as for a video that is gone. Any other pass (an +// audio download) writes audio.mp3. +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 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 (has("--write-subs")) { + if (fs.existsSync(path.join(root, "gone"))) { console.error("ERROR: [youtube] ${ID}: Video unavailable. This video has been removed by the uploader"); process.exit(1); } + for (const n of fs.readdirSync(path.join(root, "landing"))) fs.copyFileSync(path.join(root, "landing", n), path.join(dir, n)); + process.exit(0); +} +fs.writeFileSync(path.join(dir, "audio.mp3"), "AUDIO"); +process.exit(0); +`; + +const vtt = (words: string) => + `WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n${words}\n\n00:00:02.000 --> 00:00:04.000\n${words} again\n`; +const OLD = vtt("the stored words"); +const META = { + id: ID, + title: "A video", + duration: 600, + upload_date: "20260101", + webpage_url: VIDEO, + automatic_captions: { en: [{ ext: "vtt" }] }, +}; + +async function runWith(landing: Record<string, string>, opts: { gone?: boolean; handling?: "youtube" | "transcribe" } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "captions-refetch-")); + 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 mkdir(path.join(root, "landing")); + for (const [n, t] of Object.entries(landing)) await writeFile(path.join(root, "landing", n), t); + if (opts.gone) await writeFile(path.join(root, "gone"), ""); + 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)); + await writeFile(path.join(videoDir, EN), OLD); + await storeFixture(videoDir, EN); + const storedMtime = (await stat(path.join(videoDir, `${EN}.zst`))).mtimeMs; + let log = ""; + const record = await downloadOneManaged({ + channelSlug: "c", + channelConfig: { handling: opts.handling ?? "youtube", url: "https://www.youtube.com/@c/videos" } 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, + storedMtime, + subPasses: argvs.filter((a) => a.includes("--write-subs")), + captions: (await readdir(videoDir)).filter((f) => f.startsWith("transcript.") && !f.endsWith(".json")).sort(), + cleanup: () => rm(root, { recursive: true, force: true }), + }; +} + +test("the caption is asked for again (main's re-download rule): no stored track left out of --sub-langs", async () => { + const r = await runWith({ [EN]: OLD }); + try { + assert.equal(r.subPasses.length, 1, r.log); + const langs = r.subPasses[0][r.subPasses[0].indexOf("--sub-langs") + 1]; + assert.ok(!/-en\b/.test(langs), `no exclusion: ${langs}`); + } finally { + await r.cleanup(); + } +}); + +test("fetched again with the SAME content: the stored form stays, its mtime unchanged; the new copy dropped", async () => { + const r = await runWith({ [EN]: OLD }); + try { + assert.deepEqual(r.captions, [`${EN}.zst`]); + assert.equal((await stat(path.join(r.videoDir, `${EN}.zst`))).mtimeMs, r.storedMtime, "nothing moved: the index sees nothing"); + assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with the same content; the stored track is kept/); + } finally { + await r.cleanup(); + } +}); + +test("fetched again with NEW content that has cues: it is the track, and the stored one is gone", async () => { + const NEW = vtt("the corrected manual words"); + const r = await runWith({ [EN]: NEW }); + try { + assert.deepEqual(r.captions, [EN]); + assert.equal(await readFile(path.join(r.videoDir, EN), "utf8"), NEW); + assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with new content; the new track replaces the stored one \(2 cues/); + } finally { + await r.cleanup(); + } +}); + +test("a video that is gone returns nothing: the stored caption stays", async () => { + const r = await runWith({}, { gone: true }); + try { + assert.deepEqual(r.captions, [`${EN}.zst`]); + assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); + assert.match(r.log, /Captions transcript\.en\.vtt: nothing was fetched; the stored track is kept/); + } finally { + await r.cleanup(); + } +}); + +test("a fetch that left a .part: the stored track untouched", async () => { + const r = await runWith({ [`${EN}.part`]: "WEBVTT\n\n00:00:00.000 --> 00:0" }); + try { + assert.ok(r.captions.includes(`${EN}.zst`)); + assert.ok(!r.captions.includes(EN)); + assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); + assert.match(r.log, /Captions transcript\.en\.vtt: the fetch did not finish \(a \.part\); the stored track is kept/); + } finally { + await r.cleanup(); + } +}); + +for (const [what, body] of [["an empty file", ""], ["a header with no cue", "WEBVTT\n\n"]] as const) { + test(`fetched again as ${what}: dropped, the stored track untouched`, async () => { + const r = await runWith({ [EN]: body }); + try { + assert.deepEqual(r.captions, [`${EN}.zst`]); + assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); + assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with no cues; dropped, the stored track is kept/); + } finally { + await r.cleanup(); + } + }); +} + +test("a track that is NEW (not stored before) is not settled: it lands as yt-dlp wrote it", async () => { + const ORIG = vtt("what was said"); + const r = await runWith({ [EN]: OLD, "transcript.en-orig.vtt": ORIG }); + try { + assert.deepEqual(r.captions, ["transcript.en-orig.vtt", `${EN}.zst`]); + assert.doesNotMatch(r.log, /Captions transcript\.en-orig\.vtt/); + } finally { + await r.cleanup(); + } +}); + +test("replaceAutoSubs's audio download (transcribe handling) asks for no caption and leaves the stored one untouched", async () => { + const r = await runWith({ [EN]: vtt("must not land") }, { handling: "transcribe" }); + try { + assert.equal(r.subPasses.length, 0, "no subtitle pass"); + assert.ok(r.captions.includes(`${EN}.zst`)); + assert.ok(!r.captions.includes(EN)); + assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD); + assert.doesNotMatch(r.log, /Captions transcript\.en\.vtt/); + } finally { + await r.cleanup(); + } +}); + +// REVIEW-2 N1: the new plain file and its dir are fsynced BEFORE the stored +// copy goes (yt-dlp never fsyncs; a power cut must not leave a zero-length +// caption and no stored form). The seam runs between the two. +test("replaced: the new file is synced while the stored copy is still there; only then the stored copy goes", async () => { + const { setRefetchSyncedHookForTest, settleRefetchedCaptions } = await import("../lib/storedText-write-server"); + const { mkdtemp: mk } = await import("node:fs/promises"); + const dir = path.join(await mk(path.join(tmpdir(), "settle-order-")), "channels", "c", "data", "v1"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, EN), OLD); + await storeFixture(dir, EN); + await writeFile(path.join(dir, EN), vtt("new words")); + const seen: string[][] = []; + setRefetchSyncedHookForTest(async (d) => void seen.push((await readdir(d)).sort())); + try { + const out = await settleRefetchedCaptions(dir, ["en"]); + assert.equal(out[0].status, "replaced"); + } finally { + setRefetchSyncedHookForTest(undefined); + } + assert.deepEqual(seen, [[".stored-text.lock", EN, `${EN}.zst`]], "synced with both forms on disk (under the file's lock)"); + assert.deepEqual((await readdir(dir)).sort(), [EN]); + await rm(path.dirname(path.dirname(path.dirname(path.dirname(dir)))), { recursive: true, force: true }); +}); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -70,7 +70,13 @@ 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 { + listingHas, + logicalEntries, + storedFormsIn, + storedOnlyCaptionTracks, +} from "../lib/storedText"; +import { settleRefetchedCaptions } from "../lib/storedText-write-server"; import { upsertMetadataScan, type MetadataScanEntry, @@ -293,11 +299,21 @@ export type ManagedDownloadOpts = { // 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. // -// 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. +// A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts) is left out of the +// sub-langs, as for a `later` channel: this pass runs without +// `--no-overwrites`, and yt-dlp's default REPLACES a subtitle file it finds — +// over a compressed chat it finds none and fetches the whole replay again, +// which is often shorter than the live capture (lane text-compress, REVIEW-2 +// R1: no capture is replaced because another arrived). +// +// A CAPTION TRACK STORED COMPRESSED IS FETCHED AGAIN, as on main (AGENTS.md: +// "YouTube's subtitles are fetched again first, as on any re-download"): main +// replaced a plain caption with the new download. Over a stored one the new +// file lands beside it, and the caller settles each such track after the pass +// (settleRefetchedCaptions, lib/storedText-write-server.ts): the same content +// keeps the stored form, new content with cues replaces it — only once the +// new file is whole — and nothing, a `.part` or an empty file leaves the +// stored track untouched. Exported for its test. export function youtubeHandlingArgs( config: ChannelConfig, reuseInfoJson = false, @@ -671,8 +687,11 @@ async function sourceMediaPartials(videoDir: string): Promise<string[]> { return out; } +// LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst` is +// a transcript on disk — a miss here downloads the audio and queues a +// transcription for a video that has captions. async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> { - const entries = await readdir(videoDir).catch(() => [] as string[]); + const entries = logicalEntries(await readdir(videoDir).catch(() => [] as string[])); return entries.some((e) => { if (e === "transcript.json") return true; const m = e.match( @@ -685,6 +704,9 @@ async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> { }); } +// Exported for the unit test ONLY (controller/storedText.captions.test.ts). +export const __hasAnyTranscriptOnDiskForTest = hasAnyTranscriptOnDisk; + // Listed, none of them (lib/listedCaptions-server.ts — the one rule): the // no-subs fallback's reason to fetch audio. No readable metadata says nothing. async function metadataReportsNoCaptions( @@ -1323,13 +1345,15 @@ 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 = + // What is stored compressed in the video's dir (lib/storedText.ts): the + // chat (left out of the subtitle request) and the caption tracks (fetched + // again, then settled against the stored form after the pass). + const storedListing = opts.channelConfig.handling === "youtube" && canonicalId - ? storedFormsIn( - await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]), - LIVE_CHAT_FILENAME, - ) === "zst" - : false; + ? await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]) + : []; + const chatStored = storedFormsIn(storedListing, LIVE_CHAT_FILENAME) === "zst"; + const storedCaptionTracks = storedOnlyCaptionTracks(storedListing); const mediaArgs = opts.channelConfig.handling === "youtube" ? [ @@ -1632,6 +1656,14 @@ async function runManagedDownload( } } + // THE CAPTIONS FETCHED AGAIN OVER STORED ONES (REVIEW-1 F1, captions lane): + // each track that was stored-only before the pass is settled now — after + // every subtitle-fetching attempt, before anything reads the dir — whether + // the pass succeeded or not (a whole file it landed is judged on its own). + if (storedCaptionTracks.length > 0 && canonicalId) { + await settleRefetchedCaptions(path.join(channelDir, "data", canonicalId), storedCaptionTracks, opts.onLog); + } + // A RATE-LIMITED DOWNLOAD FALLS BACK TO THE STORED URL (release 32 R7): the // measured case — yt-dlp's own fetch of Odysee's original file answered 429 // while the player's ranged reads of it answered 206. diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -2,7 +2,12 @@ // 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 { + excludeSubTracks, + logicalEntries, + storedFormsIn, + storedOnlyCaptionTracks, +} from "../lib/storedText"; import path from "node:path"; import { mkdir, readdir, readFile } from "node:fs/promises"; import { writeFileAtomic } from "../lib/jsonFile-server"; @@ -1842,13 +1847,22 @@ function compileSubLangMatcher(spec: string): (track: string) => boolean { const SUB_EXT_PATTERN = "(?:vtt|json|json3|srv1|srv2|srv3)"; -// 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. +// One video's `--sub-langs` for the missing-subs fetch, from its PHYSICAL +// listing. This pass runs with `--no-overwrites`, under which yt-dlp skips a +// track that is "already present" — by the PLAIN name only. A chat or a +// caption track stored compressed (lib/storedText.ts) is on disk, so it is +// left out, keeping main's behaviour (fetch only what is missing) instead of +// landing a second copy beside it: a stored chat as for a `later` channel, +// each stored caption by its code (`,-en,-en-orig`). (The managed download, +// which runs WITHOUT `--no-overwrites` and so replaced a caption on main, +// fetches stored captions again and settles them: downloadOneManaged.ts.) +// 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" }); + const chatLeftOut = + storedFormsIn(entries, LIVE_CHAT_FILENAME) === "zst" + ? effectiveSubLangs({ subLangs, chat: "later" }) + : subLangs; + return excludeSubTracks(chatLeftOut, storedOnlyCaptionTracks(entries)); } // Over a LOGICAL listing (lib/storedText.ts): a chat stored as @@ -2166,7 +2180,9 @@ export async function destinationExists( } = {}, ): Promise<boolean> { const dir = path.join(dataDir, id); - const entries = await readdir(dir).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst` + // is the destination on disk — a miss here re-fetches the URL. + const entries = logicalEntries(await readdir(dir).catch(() => [] as string[])); // A retry of a corrupt full source asks the source again whatever is on // disk — the kept container, or a salvage transcript made from it (release // 30, lane Q). Only the retry asks; a sweep still counts it as there. diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts @@ -150,7 +150,7 @@ async function storeFiles(p: SavedVideoPointer): Promise<string[]> { test("an explicit persist over a landed copy: both kept, the download active, the landed one flagged; the pin stays", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "v7h6xzw", { landed: true }); - await setDoNotClean(dir, true, "keep"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "keep" }); const log = await download(paths, dir, { explicit: true }); assert.match( log, @@ -207,7 +207,7 @@ test("an explicit persist much shorter than the landed copy still becomes active test("an automatic download over a landed copy of the same length: both kept, the landed one stays active", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vauto", { landed: true }); - await setDoNotClean(dir, true); + await setDoNotClean(dir, true, { by: "operator", via: "toggle" }); const log = await download(paths, dir, { explicit: false }); assert.match( log, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -22,6 +22,109 @@ disabled fails its listings; the key file must be yours, mode 600, under the config directory. - `pnpm ops network`, `pnpm ops network-exit`, `pnpm ops get network [--probe]`, and /settings → Network exits. The startup probe only connects to each proxy and can be turned off. Not a disguise: no fingerprint or user-agent changes. +- **The copies scan dates a re-upload by the stream's day, not the upload's, and says what it could not date.** + - Before, it dated every video by its channel's `recordedDate` rule, else its upload day. A re-upload channel with + no rule was dated by its uploads, months after the streams its live mirror held, and the scan answered "0 + candidate pairs" with nothing to say why. + - Now each video is dated by the best evidence it has: the channel's rule, else a live stream's own day, else (no + rule set) a date the channel's titles carry in a shape the scan recognises (it must read at least half the + channel's videos that are not live streams), else the upload day. Each pair's members record where their date came from. + - The runtime search: on a channel with NO `recordedDate` rule, a video with only an upload day, or none, that + finds no candidate by date is compared, by its words, with the videos of the other channels whose runtimes agree + (its 8 nearest, at most 2,000 such pairs a scan). Such a pair is decided by its words only; without words on both + sides it is no pair, never a hold. A channel with a rule is never searched from, so a group whose channels all + have rules is scanned exactly as before. + - The scan's result and log carry `advice`: a channel dated from its titles with no rule set, with the exact + `pnpm ops channel-config` patch that sets one; videos dated only by their upload; and, when no two members' + videos are dated near each other, each member's dated span. `dating` gives each channel's count by source. +- **A do-not-clean mark says who set it, and Clean without checking can drop the audio kept only because the source was gone.** + - Every mark now records `by`: `availability-check` (the checked clean's gate, clean after capture, the keep-latest + window's deletion check), `live-recording`, `import` or `operator` (the video page's toggle, `do-not-clean`, + `keep-videos`, a keep asked before the video landed), with `via`, the `surface` a person used (`button` or + `ops`) and the job's id. One writer writes the file; a test fails the build if anything else does. A machine + never replaces a mark that is there; a person's replaces the machine's. + - A mark from before this has no `by` and is the operator's. `pnpm ops marks-backfill {slug, dryRun}` (a dry run + unless `"dryRun": false`) relabels one as `by: "availability-check", inferred: true` only on proof from other + records: availability.json says a check found the video gone within a minute of the mark, and a clean job's log, + running then, names the pin. Never from the note. It lists every relabel with its evidence and every other mark + with why not. On a corpus whose old pins were made on cached verdicts, or whose job logs are pruned, it relabels + nothing. + - Clean without checking's confirmation has a new checkbox, off by default: "Also remove audio kept only because + the source was gone" (`"includeSourceGone": true` with `"unchecked": true` over ops). It reaches only marks by + the availability check, inferred ones counted on their own, and never a mark a person, an import or a live + recording set. The group has its own line in the confirmation (videos, files, bytes) and in the plan + (`plan.sourceGone`). The job carries its ids and re-reads each mark before removing. The mark stays and records + `audioRemoved` (when, which job, the files, why). The channel key never implies it, and a Retry or a restart + never carries it. + - A person's keep makes a mark another writer set theirs: keep-videos (by pattern or ids), a keep asked before the + video landed, the toggle, a note, and the video page's new **Make it mine** (`do-not-clean {"keep": true}`). + "Already kept" now means a person's mark. + - The video page, the Keep matching lists, keep-videos' answer and the new `pnpm ops get marks <slug>` say who set + a mark and when: "Do not clean: on (availability check, 3 Nov; the source was gone)" or "(you, 20 Nov)". + - The opt-in's removal runs under the mark's lock. `"expectSourceGone"` makes the dry run's count binding. The + backfill's proof is one-sided in time, and `marks-backfill {"undo": true}` returns inferred labels. +- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.** + - Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a + 3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage + that was on disk. + - Now a window that starts inside the container is cut from it, to its end, when the recording is known whole: + the record's final duration (not while live, upcoming or `post_live`), else a landed live recording's ended + stream's own duration with nothing failed or missing. It must be within 2 s of the container's end on the same + clock. + - The cut ends where both the picture and the sound have data, so the window stays in sync. It is named for what + it holds, and its sidecar records `clamp` (the end asked, the end cut, the container it was cut from, the length + it was judged by). + - The window answers the same ask next time, until the container or the known length changes. Then fetch-windows + retires it and asks the span again. + - A window that starts at or after the end, a partial container, and a recording of unknown length stay + not-covering, with the reason. + - `fetch-windows` lists the window under `atRecordingEnd`. `umtool fetch --dry-run` says "saved-video, clamped at + the recording's end", and `umtool window` / `timeline insert` say so when the clip is written. + - The render holds the clip's end at the recording's last second, never padding with black or silence. +- **X is asked in small, uneven sittings.** The archive's X account was suspended after one sitting of a trending + read and 12 timeline fetches back to back, each 5-6 minutes after the last. + - A cookie refresh (Refresh cookies or Connect X account on /cookies) now admits at most **4 X job starts** + (`social.x.sittingJobs`, 1-6; it cannot be set higher). The 5th is refused when it is queued, or ends + **deferred** when its turn comes: "This X sitting is used up: 4 of 4 X jobs started since the cookies were + refreshed at 14:02 UTC … A new Refresh cookies on /cookies starts the next sitting." Nothing retries it. + - A sitting is **one kind**, set by its first job: timelines (account fetches, captures, availability checks, + an import) or browse (trending reads, X searches, a library's captures). A job of the other kind waits for + the next Refresh, saying why. + - **The gap before an X job is drawn anew each time**, 5-12 minutes by default (set in the X account session; + never below 5). The job's log says what was drawn: "waiting 8m41s (a 9m02s gap drawn from 5-12 min)". + - **At most 6 X jobs start in any hour** (was 12). The daily 150 is unchanged. + - A refresh is now the only thing that resets the cookies' age. gallery-dl rewrote the cookie file after every + fetch, so the file's time said "refreshed" after each one, and a chain of fetches could stay inside the + 60-minute limit. gallery-dl no longer writes the file, and the refresh time is recorded on its own. + - **A 429 from X stops every kind of X job for 15 minutes**: fetches, syncs, X runs, captures and checks too, + where before only trending reads and captures waited. A fetch that X rate-limited now records the 15 minutes + as well. + - **Mark suspended** on /cookies (or `pnpm ops x-session --json '{"accountState":"suspended"}'`) records that + the X account is suspended. While it is marked, deleted-post checks and captures with screenshots are refused, + because a suspended account may not see posts that still exist. Every other X job's log says so. **Mark ok** + lifts it. + - /cookies shows the sitting on X's row ("Sitting: 2 of 4 used, 2 left · timelines · began 14:02 UTC"), the + 15-minute wait after a 429 and the account's state. `pnpm ops get x-session` reports `sitting`, `account`, + `cooldown` and `refusedBy`. + - **One 15-minute stop for any rate limit or bot check from X**, whoever met it: gallery-dl, yt-dlp on an X + address (it used to get a 1-minute backoff), a capture whose pages X refused, a post's media download. + gallery-dl now stops at X's rate limit instead of waiting it out inside the same job; the job keeps what it + read and ends **deferred**, saying so. Refresh cookies and Connect X account are refused until the stop ends. + - **One X job reads at most 300 posts** (`social.x.maxPostsPerJob`, 20-400): a sync, a backfill or a search + then saves its place, and the next sitting continues it. + - A library's media-only capture is now an X job like the others: in the sitting, the cap and the gap. + - **Forget session keeps the suspended mark, the sitting and X's job count.** While the account is marked + suspended, nothing is written as deleted or unavailable from X's answers, video checks and outcomes included. + - The drawn gap is always at least 3 minutes wide, whatever is set. + - Nothing ends the 15-minute stop early except **Clear the X stop** on /cookies (or `pnpm ops x-session + --json '{"clearStop":true,"confirm":true}'`), which asks first and is logged. A clean answer from another + reader and Clear hold no longer end it. + - Inside a capture, a refusal from any part of it (an avatar, an article image, three pages that would not + render) records the stop and ends the capture at once. A capture takes at most 300 posts per job; the rest + are left for a later one. + - **Channels on the Playwright fallback fetcher (`x-playwright`) are refused**, because it cannot tell when X + refuses it. Switch the channel to `x-gallery-dl`. + - Needs a restart of the editor. - **umtool: name a channel once for a whole cut.** - A cut made from two recordings of one channel showed two names for it, the older record's uploader name and the current one. Before, the only fix was to hand-edit `channelTitle` on every clip. @@ -100,6 +203,31 @@ 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. +- **Caption tracks may be on disk compressed, and every reader still finds them.** + - A caption track (`transcript.en.vtt`, `transcript.en-orig.vtt`, any `transcript.<lang>.vtt`) may be stored as + `transcript.<lang>.vtt.zst`. Every reader reads either form with the same times: the index, normalize, the + snapshot's buckets, the caption-provenance sniff (it decodes the head), report compose, the remote worker's + inputs (sent plain), the clip tools. Nothing is fetched or transcribed again because a track is stored: + "already downloaded" and "has a transcript" count it, and a subtitle download leaves a stored track out of + `--sub-langs`. + - The superseded-auto-caption purge and the clear-transcript fix remove both forms; the purge keeps both when + they differ. The tier migration's reclaim takes a platter copy whose twin is stored only when it decodes to the + same bytes. + - The video page lists and labels a stored track under its own name; the files card shows the `.zst` as a file + and previews its decoded text. + - **`pnpm ops compress-text --json '{"kinds":["captions"]}'` compresses them** (zstd, about 20 % of the size), on + the corpus disk, with the chat's rules: one file at a time, verified before the original goes, the next run + finishes a stopped one, person-started only. Captions only when named: `kinds` still defaults to the live chat. + The dry run reports per channel and kind, and counts the en / en-orig pairs of equal size (compressed each as it + is, not deduped). A plain caption beside a stored one of other content is refused, both kept and listed. + `"restore": true` with the same `kinds` is the rollback; restore before running an older checkout, which reads a + stored caption as no transcript at all. + - A re-download still fetches a stored caption again, as before: the same content keeps the stored form, new + content with cues replaces it once whole, and nothing, a `.part` or an empty file leaves it; the job log says + which, per track. A refused pair is listed once, not on every run. Deleting a caption also removes a stopped + run's set-aside, so it cannot come back. Deleting a "Set as transcript" pick beside a stored `en` removes the pin. + - The editor, the CLIs and umtool refuse to start on a Node without zstd (>= 22.15 needed). A stored file that + does not decode is an error: the index keeps the record it had and says so. - **Clean audio without checking, and a rate-limited clean that says so.** - The channel page's Cleanup stage has **Clean without checking…** beside Clean audio. It first counts what it would remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio files (X) diff --git a/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts @@ -66,3 +66,36 @@ test("a path that leaves the video dir is refused; a missing file is a 404", asy }); assert.equal(missing.status, 404); }); + +// A CAPTION STORED COMPRESSED (lane text-compress-captions): the files card +// previews `transcript.en.vtt.zst` as its decoded text (`?decoded=1`), and the +// plain name answers the decoded text when only the stored form is on disk. +// Without `?decoded=1` the stored name is its own file, bytes as they are. +test("a stored caption: its decoded text by the plain name or ?decoded=1; its own bytes without", async () => { + const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server"); + const text = "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nstored words\n"; + const zst = await encodeStoredBytes(Buffer.from(text)); + await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt.zst"), zst); + const ask = (name: string, q = "") => + GET(new Request(`http://localhost/api/channels/chan/videos/vidA/files/${name}${q}`), { + params: Promise.resolve({ slug: "chan", id: "vidA", name }), + }); + const byPlain = await ask("transcript.en.vtt"); + assert.equal(byPlain.status, 200); + assert.match(byPlain.headers.get("content-type") ?? "", /^text\/vtt/); + assert.equal(await byPlain.text(), text); + const decoded = await ask("transcript.en.vtt.zst", "?decoded=1"); + assert.equal(decoded.status, 200); + assert.equal(await decoded.text(), text); + const raw = await ask("transcript.en.vtt.zst"); + assert.equal(raw.status, 200); + assert.equal(raw.headers.get("content-type"), "application/octet-stream"); + assert.deepEqual(Buffer.from(await raw.arrayBuffer()), zst); + // A plain file beside it is the truth: the plain name serves it as it is. + await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt"), "WEBVTT\n\nnewer\n"); + assert.equal(await (await ask("transcript.en.vtt")).text(), "WEBVTT\n\nnewer\n"); + // …and the stored one, asked by its own name decoded, is still its own. + assert.equal(await (await ask("transcript.en.vtt.zst", "?decoded=1")).text(), text); + // Neither form: a 404. + assert.equal((await ask("transcript.de.vtt")).status, 404); +}); diff --git a/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts @@ -1,6 +1,6 @@ import path from "node:path"; import { createReadStream, type ReadStream } from "node:fs"; -import { lstat, stat } from "node:fs/promises"; +import { lstat, readFile, stat } from "node:fs/promises"; import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { makeSafeController } from "yt-dlp-transcript-common/lib/safeStreamController"; @@ -15,6 +15,8 @@ import { isDriveNotAnswering, onDrive, } from "yt-dlp-transcript-common/lib/storageHealth"; +import { isStoredCaptionName, plainNameOf, storedNameOf } from "yt-dlp-transcript-common/lib/storedText"; +import { decodeStoredBytes, readStoredText } from "yt-dlp-transcript-common/lib/storedText-server"; export const dynamic = "force-dynamic"; @@ -168,6 +170,50 @@ export async function GET( if (onMediaTier && channelMediaStall(channelConfig)) return notAnswering(); const drive = onMediaTier ? mediaDir || legacyDrive : legacyDrive; + // A CAPTION STORED COMPRESSED (lib/storedText.ts) is served as its text, + // decoded: asked by its stored name with `?decoded=1` (the files card's + // preview of `transcript.en.vtt.zst`), or by its plain name when only the + // stored form is on disk (a reader that asks for the track it was listed). + // Captions only — small text on the corpus disk; the raw chat is never read + // whole to be served. Without `?decoded=1` the stored name is its own file. + const decoded = new URL(request.url).searchParams.get("decoded") === "1"; + const storedPlain = plainNameOf(name); + const captionOf = + decoded && storedPlain !== null && isStoredCaptionName(storedPlain) + ? storedPlain + : isStoredCaptionName(name) && + !(await lstat(fullPath).then(() => true, () => false)) && + (await lstat(path.join(path.dirname(fullPath), storedNameOf(name))).then(() => true, () => false)) + ? name + : null; + if (captionOf !== null) { + const dir = path.dirname(fullPath); + let text: string; + try { + // Asked by the plain name: `readStoredText` (the plain file when it is + // there — the truth — else the stored form). Asked by the stored name: + // THAT file's bytes, decoded (its frame's checksum and length checked), + // whatever stands beside it. + const read = async () => + captionOf === name + ? readStoredText(dir, captionOf, "utf8") + : (await decodeStoredBytes(await readFile(fullPath), name)).toString("utf8"); + text = await (legacyDrive ? onDrive(legacyDrive, read) : read()); + } catch (err) { + if (isDriveNotAnswering(err)) return notAnswering(); + return NextResponse.json({ error: `Not read: ${(err as Error).message}` }, { status: 404 }); + } + const body = Buffer.from(text, "utf8"); + return new Response(body, { + status: 200, + headers: { + "Content-Type": contentTypeFor(captionOf), + "Content-Length": String(body.length), + "Cache-Control": "no-store", + }, + }); + } + let stats; try { stats = await (drive ? onDrive(drive, () => stat(fullPath)) : stat(fullPath)); diff --git a/editor/app/api/ops/_markProvenance.test.ts b/editor/app/api/ops/_markProvenance.test.ts @@ -0,0 +1,94 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { callPost, setupOpsCorpus } from "./_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_markProvenance.test.ts" +// +// Lane mark-provenance over ops, against a temp corpus: the opt-in flag is +// checked at the door and the plan counts its group apart; marks-backfill is a +// dry run unless told otherwise, writes nothing then, and refuses an unknown +// key. Nothing here starts a job or revalidates a page. + +const corpus = await setupOpsCorpus("one-youtube-channel-with-data"); +type Post = Parameters<typeof callPost>[0]; +const route = async (name: string) => (await import(`./${name}/route`)).POST as Post; +const SLUG = "test-youtube"; +const VIDEO = "20240101_test1234567"; +test.after(() => corpus.cleanup()); + +const videoDir = () => path.join(corpus.transcripts, "channels", SLUG, "data", VIDEO); + +test("cleanup: includeSourceGone needs unchecked; the dry plan answers the source-gone group on its own", async () => { + const cleanup = await route("cleanup"); + const refused = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", includeSourceGone: true }); + assert.equal(refused.status, 400); + assert.match(String(refused.body.error), /"includeSourceGone" applies to a clean without checking only/); + const bad = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: "yes" }); + assert.equal(bad.status, 400); + + const dry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: true }); + assert.equal(dry.status, 200, JSON.stringify(dry.body)); + const plan = dry.body.plan as { sourceGone: Record<string, unknown> }; + assert.deepEqual(Object.keys(plan.sourceGone).sort(), ["bytes", "files", "ids", "inferred", "videos"]); + assert.equal(dry.body.includeSourceGone, true); +}); + +test("marks-backfill: a dry run by default, writes nothing, says why a mark is not proven; unknown keys refused", async () => { + const backfill = await route("marks-backfill"); + const markFile = path.join(videoDir(), "do-not-clean.json"); + const before = JSON.stringify({ setAt: "2026-10-20T10:00:30.000Z", note: "deleted from source (pre-clean check): deleted" }); + await writeFile(markFile, before); + const r = await callPost(backfill, { slug: SLUG }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.dryRun, true); + assert.deepEqual(r.body.relabelled, []); + assert.deepEqual(r.body.notProven, [{ id: VIDEO, setAt: "2026-10-20T10:00:30.000Z", reason: "no-availability-record" }]); + assert.equal(await readFile(markFile, "utf8"), before); + + const unknown = await callPost(backfill, { slug: SLUG, apply: true }); + assert.equal(unknown.status, 400); + const noChannel = await callPost(backfill, { slug: "no-such" }); + assert.equal(noChannel.status, 400); + assert.match(String(noChannel.body.error), /no-such/); +}); + +// --- Review 1 --------------------------------------------------------------- + +const MACHINE = { setAt: "2026-11-03T08:00:00.000Z", note: "deleted from source (pre-clean check): deleted", by: "availability-check", via: "pre-clean-check" }; + +test("F4: expectSourceGone makes the dry run binding — a changed count is refused and nothing is queued", async () => { + const cleanup = await route("cleanup"); + await writeFile(path.join(videoDir(), "do-not-clean.json"), JSON.stringify(MACHINE)); + const alone = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, expectSourceGone: 1 }); + assert.equal(alone.status, 400); + assert.match(String(alone.body.error), /"expectSourceGone" goes with "includeSourceGone": true/); + const dry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: true }); + const now = (dry.body.plan as { sourceGone: { videos: number } }).sourceGone.videos; + const off = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, includeSourceGone: true, expectSourceGone: now + 1 }); + assert.equal(off.status, 409, JSON.stringify(off.body)); + assert.match(String(off.body.error), new RegExp(`is now ${now} video\\(s\\), not the ${now + 1} expected: nothing was queued`)); + assert.deepEqual(await corpus.listJobIds(), []); +}); + +test("F2: get marks says who set each mark and when; marks-backfill undo is a dry run first", async () => { + await writeFile(path.join(videoDir(), "do-not-clean.json"), JSON.stringify(MACHINE)); + const { GET } = (await import("./marks/route")) as { GET: (r: Request) => Promise<Response> }; + const res = await GET(new Request(`http://x/api/ops/marks?slug=${SLUG}`, { headers: { authorization: `Bearer ${process.env.WORKER_TOKEN}` } })); + const body = (await res.json()) as { count: number; sourceGone: number; marks: { id: string; setBy: string; mine: boolean }[] }; + assert.equal(res.status, 200, JSON.stringify(body)); + assert.equal(body.count, 1); + assert.equal(body.sourceGone, 1); + assert.match(body.marks[0].setBy, /^availability check, 3 Nov( 2026)?; the source was gone$/); + assert.equal(body.marks[0].mine, false); + + const backfill = await route("marks-backfill"); + const undo = await callPost(backfill, { slug: SLUG, undo: true }); + assert.equal(undo.status, 200, JSON.stringify(undo.body)); + assert.deepEqual([undo.body.undo, undo.body.dryRun, undo.body.unlabelled], [true, true, []]); + const keep = await route("do-not-clean"); + const badNote = await callPost(keep, { slug: SLUG, id: VIDEO, note: 5 }); + assert.equal(badNote.status, 400, "the note is checked at the door"); +}); diff --git a/editor/app/api/ops/cleanup/route.ts b/editor/app/api/ops/cleanup/route.ts @@ -7,7 +7,7 @@ import { planCleanAudioUncheckedAction, removeWrongFormatAudioAction, } from "../../../channels/[slug]/whisperActions"; -import { jobResponse, oneOf, ops, opsFail, OpsInputError, optBool, reqSlug } from "../_lib"; +import { jobResponse, oneOf, ops, opsFail, OpsInputError, optBool, optNonNegativeInt, reqSlug } from "../_lib"; export const dynamic = "force-dynamic"; @@ -44,6 +44,20 @@ export const dynamic = "force-dynamic"; // whose config sets cleanAudioWithoutChecking runs "transcribed" unchecked // without the flag, discovering at start (nobody confirmed a count); the key // is re-read when the job starts. +// +// ALSO REMOVE AUDIO KEPT ONLY BECAUSE THE SOURCE WAS GONE (lane +// mark-provenance): "includeSourceGone": true, with "unchecked": true only — an +// explicit opt-in, default off, never implied by the channel key. The plan +// always answers that group on its own, {plan: {sourceGone: {ids, videos, +// files, bytes, inferred: {…}}}}: videos whose do-not-clean mark the +// availability check set (or marks-backfill proved it set) and that nothing +// else holds. With the flag the job carries those ids too and removes their +// audio; the marks stay and record it. A mark set by a person, an import or a +// live recording (or one from before marks said who set them) is never +// reached. A non-dry call answers that group's counts beside the main +// group's, and the job logs both before removing anything. `"expectSourceGone": +// <n>` (the dry run's `plan.sourceGone.videos`) makes the dry run binding: a +// fresh count that differs is refused and nothing is queued. const SWEEPS = { transcribed: cleanAudioAction, "extra-formats": cleanExtraAudioFormatsAction, @@ -52,11 +66,19 @@ const SWEEPS = { } as const; export async function POST(request: Request) { - return ops(request, ["slug", "sweep", "unchecked", "dryRun"], async (body) => { + return ops(request, ["slug", "sweep", "unchecked", "dryRun", "includeSourceGone", "expectSourceGone"], async (body) => { const slug = reqSlug(body, "slug"); const sweep = oneOf(body, "sweep", Object.keys(SWEEPS) as (keyof typeof SWEEPS)[]); const unchecked = optBool(body, "unchecked") ?? false; const dryRun = optBool(body, "dryRun") ?? false; + const includeSourceGone = optBool(body, "includeSourceGone") ?? false; + if (includeSourceGone && !unchecked) { + throw new OpsInputError('"includeSourceGone" applies to a clean without checking only — give "unchecked": true'); + } + const expectSourceGone = optNonNegativeInt(body, "expectSourceGone"); + if (expectSourceGone !== undefined && !includeSourceGone) { + throw new OpsInputError('"expectSourceGone" goes with "includeSourceGone": true'); + } if (unchecked && sweep !== "transcribed") { throw new OpsInputError('"unchecked" applies to the "transcribed" sweep only'); } @@ -66,7 +88,7 @@ export async function POST(request: Request) { if (unchecked && dryRun) { const r = await planCleanAudioUncheckedAction(slug); if (!r.ok) return opsFail(r.error); - return NextResponse.json({ ok: true, dryRun: true, plan: r.plan }); + return NextResponse.json({ ok: true, dryRun: true, ...(includeSourceGone ? { includeSourceGone: true } : {}), plan: r.plan }); } // A non-dry unchecked call is its own confirmation: its plan is computed // NOW and carried, so the job removes at most what this call would have @@ -76,11 +98,36 @@ export async function POST(request: Request) { if (unchecked) { const r = await planCleanAudioUncheckedAction(slug); if (!r.ok) return opsFail(r.error); - const { ids, ...counts } = r.plan; - const job = await cleanAudioUncheckedAction(slug, undefined, ids, counts); + const { ids, sourceGone, ...rest } = r.plan; + if (expectSourceGone !== undefined && expectSourceGone !== sourceGone.videos) { + return opsFail( + `The audio kept only because the source was gone is now ${sourceGone.videos} video(s), not the ${expectSourceGone} expected: nothing was queued. Run the dry run again.`, + 409, + { plan: { sourceGone: { videos: sourceGone.videos, files: sourceGone.files, bytes: sourceGone.bytes } } }, + ); + } + const groupCounts = { + videos: sourceGone.videos, + files: sourceGone.files, + bytes: sourceGone.bytes, + inferred: { videos: sourceGone.inferred.videos, files: sourceGone.inferred.files, bytes: sourceGone.inferred.bytes }, + }; + const counts = { ...rest, ...(includeSourceGone ? { sourceGone: groupCounts } : {}) }; + const job = await cleanAudioUncheckedAction( + slug, + undefined, + ids, + counts, + includeSourceGone ? sourceGone.ids : undefined, + ); if (!job.ok) return jobResponse(job); void job.stream.cancel(); - return NextResponse.json({ ok: true, jobId: job.jobId, plan: counts }); + return NextResponse.json({ + ok: true, + jobId: job.jobId, + plan: { ...rest, sourceGone: groupCounts }, + includeSourceGone, + }); } return jobResponse(await SWEEPS[sweep](slug)); }); diff --git a/editor/app/api/ops/compress-text/route.test.ts b/editor/app/api/ops/compress-text/route.test.ts @@ -38,7 +38,9 @@ test("refusals before any job", async () => { [{ 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/], + [{ kinds: ["metadata"] }, /"kinds" must be a list of: live-chat, captions/], + [{ kinds: [] }, /"kinds" must be a list of: live-chat, captions/], + [{ kinds: "captions" }, /"kinds" must be a list of: live-chat, captions/], [{ limit: 0 }, /limit/], [{ limit: 5 }, /"limit" is per channel: name exactly one in "slugs"/], [{ dryRun: true, verify: true }, /two different runs/], @@ -74,3 +76,25 @@ test("a restore's dry run answers the stored files and writes nothing", async () assert.equal(synth?.pending, 0); assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]); }); + +test("kinds captions: a dry run answers the caption files per channel, the pairs of equal size, and writes nothing", async () => { + const vtt = "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nwords\n"; + await writeFile(path.join(videoDir, "transcript.en.vtt"), vtt); + await writeFile(path.join(videoDir, "transcript.en-orig.vtt"), vtt); + try { + const r = await post({ dryRun: true, kinds: ["captions"] }); + assert.equal(r.status, 200, JSON.stringify(r.json)); + const result = r.json.result as { + kinds: string[]; + channels: { slug: string; plainFiles: number; byKind: { captions?: { plainFiles: number; pairsEqualSize?: number } } }[]; + }; + assert.deepEqual(result.kinds, ["captions"]); + const synth = result.channels.find((c) => c.slug === "synth"); + assert.equal(synth?.plainFiles, 2, "the captions only: the chat is not asked"); + assert.equal(synth?.byKind.captions?.pairsEqualSize, 1); + assert.deepEqual((await readdir(videoDir)).sort(), ["transcript.en-orig.vtt", "transcript.en.vtt", "transcript.live_chat.json"]); + } finally { + await rm(path.join(videoDir, "transcript.en.vtt")); + await rm(path.join(videoDir, "transcript.en-orig.vtt")); + } +}); diff --git a/editor/app/api/ops/compress-text/route.ts b/editor/app/api/ops/compress-text/route.ts @@ -1,18 +1,27 @@ import { NextResponse } from "next/server"; import { compressTextAction } from "../../../storage/compressTextActions"; +import { + COMPRESS_TEXT_KINDS, + isCompressTextKind, + type CompressTextKind, +} from "yt-dlp-transcript-common/controller/compressText"; 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 } } +// dryRun -> { ok: true, dryRun: true, result: { kinds, channels: [{ slug, +// plainFiles, plainBytes, storedFiles, storedBytes, +// storedLogicalBytes, estimateAfterBytes, free, byKind: { <kind>: +// { …the same, pairsEqualSize? } } }], 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): +// Big text files put into their stored form (lib/storedText.ts): the raw +// live-chat replays, `transcript.live_chat.json` → `.zst` (lane text-compress), +// and with `kinds: ["captions"]` every caption track, `transcript.<lang>.vtt` → +// `.zst` (lane text-compress-captions; a dry run also counts the en / en-orig +// pairs of equal size, each compressed as it is): // 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 @@ -30,17 +39,21 @@ export const dynamic = "force-dynamic"; // 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'); +// `kinds`: what to compress — "live-chat" (the raw live-chat replays, the +// default) and "captions" (every caption track, `transcript.<lang>.vtt` → +// `.zst`, on the corpus disk; lane text-compress-captions). Captions are +// compressed only when named. +function optKinds(body: OpsBody): CompressTextKind[] | undefined { + if (body.kinds === undefined) return undefined; + if (!Array.isArray(body.kinds) || body.kinds.length === 0 || body.kinds.some((k) => !isCompressTextKind(k))) { + throw new OpsInputError(`"kinds" must be a list of: ${COMPRESS_TEXT_KINDS.join(", ")}`); } + return [...new Set(body.kinds as CompressTextKind[])]; } export async function POST(request: Request) { return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify", "restore"], async (body) => { - optKinds(body); + const kinds = optKinds(body); const dryRun = optBool(body, "dryRun") ?? false; const verify = optBool(body, "verify") ?? false; const restore = optBool(body, "restore") ?? false; @@ -49,6 +62,7 @@ export async function POST(request: Request) { const limit = optPositiveInt(body, "limit"); const result = await compressTextAction({ ...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}), + ...(kinds ? { kinds } : {}), dryRun, verify, restore, diff --git a/editor/app/api/ops/do-not-clean/route.ts b/editor/app/api/ops/do-not-clean/route.ts @@ -1,23 +1,30 @@ import { NextResponse } from "next/server"; import { toggleDoNotCleanAction } from "../../../channels/[slug]/videos/[id]/videoActions"; -import { ops, opsFail, optBool, reqSlug, reqVideoId } from "../_lib"; +import { ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, keep?: boolean } +// POST { slug, id, keep?: boolean, note?: string } +// -> { ok, outcome: "marked" | "taken-over" | "already-kept" | "removed" } // // One video's "Do not clean" marker (do-not-clean.json), set to the value // given — `keep` defaults to true; false removes it. Set, not toggled: a retry // of the same body is the same answer. The cleanup sweeps skip a marked // video's audio. `keep-videos` is the bulk form, by title/description match. +// `keep: true` on a mark another writer set (the availability check, an +// import, a live recording) MAKES IT YOURS — the video page's "Make it mine" +// ("taken-over"); `note` is written on it, and on a mark that is already +// yours. export async function POST(request: Request) { - return ops(request, ["slug", "id", "keep"], async (body) => { + return ops(request, ["slug", "id", "keep", "note"], async (body) => { const res = await toggleDoNotCleanAction( reqSlug(body, "slug"), reqVideoId(body, "id"), optBool(body, "keep") ?? true, + "ops", + optString(body, "note"), ); if (!res.ok) return opsFail(res.error); - return NextResponse.json({ ok: true }); + return NextResponse.json({ ok: true, outcome: res.outcome }); }); } diff --git a/editor/app/api/ops/keep-videos/route.ts b/editor/app/api/ops/keep-videos/route.ts @@ -46,6 +46,7 @@ export async function POST(request: Request) { ids: reqStringArray(body, "ids"), note: optString(body, "note"), dryRun: optBool(body, "dryRun"), + surface: "ops", }); if (!result.ok) return opsFail(result.error); return NextResponse.json({ ok: true, ...result.result }); @@ -71,6 +72,7 @@ export async function POST(request: Request) { fields, note: optString(body, "note"), dryRun: optBool(body, "dryRun"), + surface: "ops", }); if (!result.ok) return opsFail(result.error); return NextResponse.json({ ok: true, ...result.result }); diff --git a/editor/app/api/ops/marks-backfill/route.ts b/editor/app/api/ops/marks-backfill/route.ts @@ -0,0 +1,30 @@ +import { NextResponse } from "next/server"; +import { marksBackfillAction } from "../../../channels/actions"; +import { ops, opsFail, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?: true } +// -> { ok, slug, dryRun, marks, labelled, relabelled: [{id, setAt, evidence: +// {availability, observedAt, field, jobId, jobKind}}], notProven: [{id, +// setAt, reason}], oldestCleanJobAt } +// +// Relabel a channel's do-not-clean marks written before marks said who set +// them as set by the availability check (`by: "availability-check", +// inferred: true`) — ONLY where the records prove it: availability.json says +// the check found the video gone within a minute of the mark, and a clean +// job's log, running then, names the pin. Never from the mark's note. Every +// other old mark stays the operator's. A DRY RUN unless "dryRun": false. +// +// POST { slug, undo: true, dryRun?: true } +// -> { ok, slug, dryRun, undo: true, marks, unlabelled: [{id, setAt, +// evidence}], changedSince } +// Every INFERRED label of the channel back to unlabelled (the operator's): +// only marks with "inferred": true; setAt, note and audioRemoved stay. +export async function POST(request: Request) { + return ops(request, ["slug", "dryRun", "undo"], async (body) => { + const r = await marksBackfillAction(reqSlug(body, "slug"), optBool(body, "dryRun") ?? true, optBool(body, "undo") ?? false); + if (!r.ok) return opsFail(r.error); + return NextResponse.json({ ok: true, ...r.result }); + }); +} diff --git a/editor/app/api/ops/marks/route.ts b/editor/app/api/ops/marks/route.ts @@ -0,0 +1,25 @@ +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; +import { listMarksAction } from "../../../channels/actions"; +import { readRoute } from "../_read"; +import { opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET ?slug=<channel> +// -> { ok, count, sourceGone, marks: [{ id, setBy, mine, sourceGone, mark }] } +// +// Every do-not-clean mark of one channel and WHO SET IT AND WHEN, in the +// video page's words ("availability check, 3 Nov; the source was gone", +// "you, 20 Nov"). `mine`: a person's (by "operator", or from before marks said +// who set them). `sourceGone`: set by the availability check, so Clean without +// checking's opt-in can reach its audio; `do-not-clean {"keep": true}` makes +// it yours. +export async function GET(request: Request) { + return readRoute(request, ["slug"], async (q) => { + const slug = q.get("slug")?.trim() ?? ""; + if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`); + const r = await listMarksAction(slug); + if (!r.ok) return opsFail(r.error); + return { count: r.marks.length, sourceGone: r.marks.filter((m) => m.sourceGone).length, marks: r.marks }; + }); +} diff --git a/editor/app/api/ops/x-session/route.test.ts b/editor/app/api/ops/x-session/route.test.ts @@ -0,0 +1,76 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/x-session/route.test.ts" +// +// Lane x-sittings: the operator marks the X account suspended (or ok) through +// POST /api/ops/x-session, and GET reports it with X's sitting. Temp dirs +// only; nothing reaches X. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-session-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile" } } })); + +const { POST, GET } = await import("./route"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const AUTH = { authorization: "Bearer test-token" }; + +async function post(body: Record<string, unknown>) { + const res = await POST( + new Request("http://localhost/api/ops/x-session", { + method: "POST", + headers: { ...AUTH, "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, body: (await res.json()) as { ok: boolean; error?: string; account?: { state: string; note?: string } } }; +} + +async function get() { + const res = await GET(new Request("http://localhost/api/ops/x-session", { headers: AUTH })); + return (await res.json()) as { account: { state: string; alert?: string }; sitting: { used: number; limit: number; left: number } }; +} + +test("POST marks the account suspended with a note, GET shows it as the account's alert, and ok lifts it", async () => { + assert.equal((await get()).account.state, "ok"); + const marked = await post({ accountState: "suspended", note: "read-only since the 21st" }); + assert.equal(marked.status, 200, marked.body.error); + assert.deepEqual([marked.body.account?.state, marked.body.account?.note], ["suspended", "read-only since the 21st"]); + const file = JSON.parse(await readFile(path.join(ROOT, ".x-session", "account.json"), "utf8")); + assert.equal(file.state, "suspended"); + const after = await get(); + assert.equal(after.account.state, "suspended"); + assert.match(after.account.alert ?? "", /^The X account is marked suspended .*read-only since the 21st/); + // The sitting is reported beside it: the default four, none used. + assert.deepEqual([after.sitting.used, after.sitting.limit, after.sitting.left], [0, 4, 4]); + assert.equal((await post({ accountState: "ok" })).status, 200); + assert.equal((await get()).account.state, "ok"); +}); + +test("POST refuses a state it does not know, a stray key and a note that is not a string", async () => { + for (const body of [{ accountState: "banned" }, {}, { accountState: "ok", when: "now" }, { accountState: "ok", note: 3 }]) { + const r = await post(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.equal(r.body.ok, false); + } +}); + +test("POST clearStop: unconfirmed answers 409 with what it risks; confirmed clears it", async () => { + const { recordXStop, xStopRemainingMs } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + await recordXStop("a rate limit", getPaths()); + const asked = await post({ clearStop: true }); + assert.equal(asked.status, 409); + assert.match(asked.body.error ?? "", /^Clearing the X stop lets the next X job ask X at once/); + assert.ok((await xStopRemainingMs(getPaths())) > 0); + const done = await post({ clearStop: true, confirm: true }); + assert.equal(done.status, 200); + assert.equal(await xStopRemainingMs(getPaths()), 0); +}); diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts @@ -1,15 +1,19 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import { NextResponse } from "next/server"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; import { readRoute } from "../_read"; -import { opsFail } from "../_lib"; +import { oneOf, ops, opsFail, optString } from "../_lib"; export const dynamic = "force-dynamic"; // GET /api/ops/x-session[?slug=<channel>] // -> { ok, source, sourceChosen, browserSpec?, profileDir, cookieFile, // hasProfile, hasCookies, looksAuthenticated, cookiesUpdatedAt, -// ageMinutes, maxAgeMinutes, ageChecked, alert, allowed, reason, note? } +// ageMinutes, maxAgeMinutes, ageChecked, alert, cap, sitting, account, +// cooldown, allowed, reason, refusedBy?, note? } // // The X login an X job would use and whether one would start NOW: the // fresh-jar rule's inputs (the source, the exported jar's age, the limit @@ -25,3 +29,32 @@ export async function GET(request: Request) { return { ...(await xSessionReport({ paths: getPaths(), channelSlug: slug })) }; }); } + +// POST /api/ops/x-session {"accountState": "suspended" | "ok", "note"?} +// -> { ok, account: {state, note?, at, by} } +// +// The operator's word on the X account (social/xAccountState.ts): while it is +// "suspended" the network guard refuses the X jobs that record posts as +// deleted or unavailable, and every other X job logs it. Nothing is asked of +// X; nothing else is written. /cookies has the same control. +// +// POST {"clearStop": true, "confirm"?: true, "note"?} — "Clear the X stop" +// (common/jobs/downloadBackoff.ts clearXStop): the one way X's 15-minute stop +// after a rate limit or a bot check ends before its time. Without "confirm" it +// clears nothing and answers 409 with what it risks; each clear is logged. +export async function POST(request: Request) { + return ops(request, ["accountState", "note", "clearStop", "confirm"], async (body) => { + if (body.clearStop !== undefined) { + if (body.clearStop !== true) return opsFail('"clearStop" must be true'); + if (body.accountState !== undefined) return opsFail('"clearStop" and "accountState" are two acts: send one'); + const note = optString(body, "note"); + const r = await clearXStop(getPaths(), { confirm: body.confirm === true, by: "pnpm ops x-session", ...(note ? { note } : {}) }); + if (!r.ok) return opsFail(r.message, 409, { confirmNeeded: true }); + return NextResponse.json({ ok: true, cleared: r.cleared, message: r.message }); + } + const state = oneOf(body, "accountState", ["suspended", "ok"] as const); + const note = optString(body, "note"); + const account = await writeXAccountState(getPaths(), state, note ? { note } : {}); + return NextResponse.json({ ok: true, account }); + }); +} diff --git a/editor/app/channels/[slug]/components/KeepMatchingControl.tsx b/editor/app/channels/[slug]/components/KeepMatchingControl.tsx @@ -67,7 +67,16 @@ export function KeepByIdControl({ slug }: { slug: string }) { )} {result && ( <p role="status" className="text-xs"> - {result.marked.length} kept now, {result.alreadyKept.length} already kept, {result.pending.length} pending (not here yet) + {result.marked.length} kept now + {result.takenOver.length > 0 && ` (${result.takenOver.length} made yours: another writer had set them)`},{" "} + {result.alreadyKept.length} already kept, {result.pending.length} pending (not here yet) + {Object.keys(result.keptBy).length > 0 && ( + <span className="block text-muted-foreground"> + {Object.entries(result.keptBy) + .map(([id, by]) => `${id}: was set by ${by}`) + .join("; ")} + </span> + )} </p> )} {pendingList && pendingList.length > 0 && ( @@ -161,7 +170,8 @@ export function KeepMatchingControl({ slug }: { slug: string }) { <div className="flex flex-col gap-1 text-xs" aria-label="keep matches"> <p role="status"> {result.matched.length} match{result.matched.length === 1 ? "" : "es"} of {result.considered} - {result.dryRun ? "" : `; ${result.marked} kept now`}, {result.alreadyKept} already kept + {result.dryRun ? "" : `; ${result.marked} kept now`} + {result.takenOver > 0 && ` (${result.takenOver} ${result.dryRun ? "would be" : ""} made yours)`}, {result.alreadyKept} already kept {result.notDownloaded.length > 0 && `, ${result.notDownloaded.length} not downloaded`} {result.unscanned > 0 && `, ${result.unscanned} never scanned (not tested)`} </p> @@ -172,7 +182,13 @@ export function KeepMatchingControl({ slug }: { slug: string }) { {m.id} </Link>{" "} {m.title} - {m.alreadyKept ? " (kept)" : m.marked ? " (kept now)" : ""} + {m.alreadyKept + ? ` (kept: ${m.keptBy ?? "you"})` + : m.takenOver + ? ` (${m.marked ? "made yours" : "would be made yours"}; was set by ${m.keptBy})` + : m.marked + ? " (kept now)" + : ""} </li> ))} </ul> diff --git a/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx b/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx @@ -7,6 +7,7 @@ import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cl import { TURN_ON_CONFIRMATION, cleanConfirmationText, + sourceGoneOptInLabel, } from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; import { cancelJobAction } from "../../../../jobs/actions"; import { setCleanAudioWithoutCheckingAction } from "../../../actions"; @@ -27,7 +28,11 @@ const EXPIRING_VOD_PLATFORMS = new Set(["twitch", "kick"]); // deletes) and stated, then a second button runs THAT plan — the job carries // its video ids and removes at most those. `mode`: "button" is the one-off // "Clean without checking"; "channel-setting" is Clean audio on a channel whose -// key is on (the key is read again when the job starts). +// key is on (the key is read again when the job starts). The one-off also +// offers the opt-in "also remove audio kept only because the source was gone" +// (lane mark-provenance): unticked by default, never offered on the +// channel-key path; ticked, its group gets its own line and the job carries +// its ids. export function CleanWithoutCheckingSection({ slug, mode = "button", @@ -41,17 +46,23 @@ export function CleanWithoutCheckingSection({ const [plan, setPlan] = useState<AudioCleanPlan | null>(null); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); + const [includeSourceGone, setIncludeSourceGone] = useState(false); const ask = async () => { setBusy(true); setError(null); + setIncludeSourceGone(false); const r = await planCleanAudioUncheckedAction(slug); setBusy(false); if (r.ok) setPlan(r.plan); else setError(r.error); }; - const text = plan ? cleanConfirmationText(plan) : null; - const run = (ids: string[]) => - mode === "button" ? cleanAudioUncheckedAction(slug, queueKey, ids) : cleanAudioAction(slug, queueKey, ids); + const offerSourceGone = mode === "button" && !!plan && plan.sourceGone.videos > 0; + const include = offerSourceGone && includeSourceGone; + const text = plan ? cleanConfirmationText(plan, { includeSourceGone: include }) : null; + const run = (p: AudioCleanPlan) => + mode === "button" + ? cleanAudioUncheckedAction(slug, queueKey, p.ids, undefined, include ? p.sourceGone.ids : undefined) + : cleanAudioAction(slug, queueKey, p.ids); return ( <div aria-label="clean without checking section" className="flex flex-col gap-2 rounded border border-border p-3"> <div> @@ -84,11 +95,24 @@ export function CleanWithoutCheckingSection({ {plan && text && ( <div role="group" aria-label="confirm clean without checking" className="flex flex-col gap-2"> <p className="text-sm font-medium">{text.ask}</p> + {offerSourceGone && ( + <label className="flex items-center gap-2 text-sm"> + <input + type="checkbox" + checked={includeSourceGone} + onChange={(e) => setIncludeSourceGone(e.target.checked)} + aria-label="also remove audio kept only because the source was gone" + /> + {sourceGoneOptInLabel(plan.sourceGone)} + </label> + )} + {text.sourceGone && <p className="text-sm font-medium">{text.sourceGone}</p>} <p className="text-xs text-muted-foreground">{text.kept}</p> <div className="flex flex-wrap items-start gap-2"> - {plan.files > 0 && ( + {text.files > 0 && ( <StreamActionLog - trigger={() => run(plan.ids)} + key={include ? "with-source-gone" : "plain"} + trigger={() => run(plan)} cancelAction={cancelJobAction} buttonLabel={text.button} runningLabel="Cleaning…" diff --git a/editor/app/channels/[slug]/incompleteTranscriptActions.ts b/editor/app/channels/[slug]/incompleteTranscriptActions.ts @@ -198,8 +198,11 @@ export async function clearIncompleteTranscriptsAction( let succeeded = 0; for (const id of cleaned) { try { - await clearIncompleteTranscriptOne({ slug, videoId: id, paths }); - succeeded++; + const r = await clearIncompleteTranscriptOne({ slug, videoId: id, paths }); + // A caption that could not be locked (a full disk) was refused, not + // removed: the video is not cleared, and says why. + if (r.refused?.length) failures.push({ videoId: id, error: r.refused.join("; ") }); + else succeeded++; } catch (e) { failures.push({ videoId: id, error: (e as Error).message }); } diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/lib/fixIncompleteTranscript.test.ts" +// +// CLEARING A TRUNCATED TRANSCRIPT CLEARS ITS CAPTIONS IN BOTH FORMS (lane +// text-compress-captions). A track stored as `transcript.<lang>.vtt.zst` +// (lib/storedText.ts) missed by the clear would bring the cleared transcript +// back. Temp corpus, synthetic names. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "clear-incomplete-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const { clearIncompleteTranscriptOne } = await import("./fixIncompleteTranscript"); +const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); +const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("every caption track goes, stored or plain, and the metadata stays", async () => { + const dir = path.join(ROOT, "channels", "synth", "data", "vid00000001"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), "{}"); + await writeFile(path.join(dir, "audio.mp3"), "A"); + await writeFile(path.join(dir, "transcript.json"), "{}"); + await writeFile(path.join(dir, "transcript.en.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nstored\n"))); + await writeFile(path.join(dir, "transcript.en-orig.vtt"), "WEBVTT\n\nplain\n"); + await writeFile(path.join(dir, "transcript.en-orig.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nolder\n"))); + const out = await clearIncompleteTranscriptOne({ slug: "synth", videoId: "vid00000001", paths: getPaths() }); + assert.equal(out.removed, 4, "audio, transcript.json and the two caption tracks (each in every form)"); + assert.deepEqual(await readdir(dir), ["metadata.info.json"]); +}); diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts @@ -11,6 +11,7 @@ import { removeMediaFile } from "yt-dlp-transcript-common/lib/mediaTier-server"; import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import path from "node:path"; import { readdir } from "node:fs/promises"; import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig"; @@ -132,7 +133,7 @@ export async function clearIncompleteTranscriptOne(opts: { slug: string; videoId: string; paths: Paths; -}): Promise<{ removed: number }> { +}): Promise<{ removed: number; refused?: string[] }> { const { slug, videoId, paths } = opts; const videoDir = videoDirOf(paths, slug, videoId); const dataDir = path.resolve(paths.channelsDir, slug, "data"); @@ -143,7 +144,9 @@ export async function clearIncompleteTranscriptOne(opts: { `Refusing to clear: video path resolved outside the data dir (${videoId})`, ); } - const entries = await readdir(resolved).catch(() => [] as string[]); + // LOGICAL (lib/storedText.ts): a caption track stored as `.zst` is listed + // under its plain name, so it is cleared too (in both forms, below). + const entries = logicalEntries(await readdir(resolved).catch(() => [] as string[])); const toRemove = entries.filter( (name) => isRealAudioFile(name) || @@ -151,12 +154,16 @@ export async function clearIncompleteTranscriptOne(opts: { name === "transcript.json" || name === "transcript.cues.json", ); + const refused: string[] = []; for (const name of toRemove) { // 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); + // behind would bring the cleared transcript back. One that cannot be + // locked (a full disk, a run holding it) is refused, nothing removed. + if (isTranscriptVtt(name)) { + const out = await removeStoredText(resolved, name); + if ("refused" in out) refused.push(out.refused); + } else await removeMediaFile(resolved, name); } - return { removed: toRemove.length }; + return { removed: toRemove.length - refused.length, ...(refused.length ? { refused } : {}) }; } diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -31,6 +31,7 @@ import { PipelineStatusStrip } from "./PipelineStatusStrip"; import { AvailabilityHistoryList } from "./cards/AvailabilityHistoryList"; import { DeleteVideoDirSection } from "./cards/DeleteVideoDirSection"; import { DoNotCleanSection } from "./cards/DoNotCleanSection"; +import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean"; import { DownloadOutcomeBadge } from "./cards/DownloadOutcomeBadge"; import { ExcludeTruncatedCheckSection } from "./cards/ExcludeTruncatedCheckSection"; import { FetchedWindows, type FetchedWindow } from "./cards/FetchedWindows"; @@ -50,6 +51,7 @@ import { isAudioFile, isTranscodeSource, isTranscriptVttName, + logicalFileNames, type VideoFile, } from "./cards/videoFiles"; @@ -77,6 +79,8 @@ type Props = { availabilityHistory: AvailabilityHistoryEntry[]; channelAudioFormat?: AudioFormat; doNotClean?: boolean; + // The mark's record: who set it and when (DoNotCleanSection says so). + doNotCleanMark?: DoNotCleanRecord | null; // When true the user has opted this video out of the truncated/incomplete // check, so the "looks truncated" banner is suppressed and the toggle reads // as on. Drives ExcludeTruncatedCheckSection. @@ -133,6 +137,7 @@ export function VideoPanel({ availabilityHistory, channelAudioFormat, doNotClean = false, + doNotCleanMark = null, excludedFromTruncatedCheck = false, savedVideo = null, sourceVideoQuality, @@ -159,9 +164,10 @@ export function VideoPanel({ !hasTranscriptJson && primaryVtt !== null && vttProvenance[primaryVtt] === "asr"; - const vttTracks = files - .filter((f) => isTranscriptVttName(f.name)) - .map((f) => f.name) + // LOGICAL (lib/storedText.ts): a track stored as `.zst` is listed under + // its plain name — the name every action on it takes. + const vttTracks = logicalFileNames(files) + .filter((name) => isTranscriptVttName(name)) .sort(); // The transcript the index/viewer will actually use: whisper wins over VTT. const activeTranscript = hasTranscriptJson ? WHISPER_FILENAME : primaryVtt; @@ -489,9 +495,11 @@ export function VideoPanel({ id="archive-media" title="Archive media" summary={ - doNotClean - ? "Protected — cleanup will skip this video." - : "Exclude this video's media from cleanup jobs." + doNotCleanMark + ? `Do not clean: on (${describeDoNotCleanMark(doNotCleanMark).text})` + : doNotClean + ? "Protected — cleanup will skip this video." + : "Exclude this video's media from cleanup jobs." } defaultOpen={true} tone={doNotClean ? "ok" : "neutral"} @@ -500,6 +508,7 @@ export function VideoPanel({ slug={slug} videoId={videoId} doNotClean={doNotClean} + mark={doNotCleanMark} /> </PipelineStageCard> diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx @@ -1,52 +1,104 @@ "use client"; import { useState, useTransition } from "react"; +import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean"; import { toggleDoNotCleanAction, } from "../../videoActions"; +// The video's "Do not clean" marker: on or off, WHO SET IT AND WHEN (lane +// mark-provenance review F2), "Make it mine" for a mark another writer set — +// the one kind Clean without checking's opt-in can remove audio under is the +// availability check's — and the mark's note, which a person writes (writing +// it makes the mark theirs too). export function DoNotCleanSection({ slug, videoId, doNotClean, + mark = null, }: { slug: string; videoId: string; doNotClean: boolean; + mark?: DoNotCleanRecord | null; }) { const [pending, startTransition] = useTransition(); const [error, setError] = useState<string | null>(null); + const [note, setNote] = useState(mark?.note ?? ""); const next = !doNotClean; + const who = mark ? describeDoNotCleanMark(mark) : null; + const run = (enabled: boolean, withNote?: string) => { + setError(null); + startTransition(async () => { + const res = await toggleDoNotCleanAction(slug, videoId, enabled, "button", withNote); + if (!res.ok) setError(res.error); + }); + }; return ( <div className="flex flex-col gap-2"> + {who && ( + <p className="text-sm font-medium" aria-label="do not clean set by"> + Do not clean: on ({who.text}) + </p> + )} <p className="text-sm text-muted-foreground"> {doNotClean - ? "This video is marked “do not clean”. The transcribed-audio and extra-format cleanup jobs will skip it, so its media is preserved for archiving. Reversible — allow cleanup to remove the marker." + ? who && !who.mine + ? who.sourceGone + ? "Set by the availability check, not by you: Clean without checking can remove its audio when its “also remove audio kept only because the source was gone” box is ticked. Make it yours to keep it from that too." + : "Set by another writer, not by you. Make it yours to say you want it kept." + : "This video is marked “do not clean”. The transcribed-audio and extra-format cleanup jobs will skip it, so its media is preserved for archiving. Reversible — allow cleanup to remove the marker." : "Mark this video “do not clean” so the cleanup jobs never delete its audio (e.g. a deleted or members-only upload you want to keep). Reversible at any time."} </p> - <button - type="button" - disabled={pending} - aria-label={ - next - ? `mark video ${videoId} do not clean` - : `allow cleanup for video ${videoId}` - } - onClick={() => { - setError(null); - startTransition(async () => { - const res = await toggleDoNotCleanAction(slug, videoId, next); - if (!res.ok) setError(res.error); - }); - }} - className="self-start px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50" - > - {pending - ? "Saving…" - : doNotClean - ? "Allow cleanup" - : "Mark do not clean"} - </button> + <div className="flex flex-wrap gap-2"> + {who && !who.mine && ( + <button + type="button" + disabled={pending} + aria-label={`make the do not clean mark of ${videoId} mine`} + onClick={() => run(true)} + className="px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50" + > + {pending ? "Saving…" : "Make it mine"} + </button> + )} + <button + type="button" + disabled={pending} + aria-label={ + next + ? `mark video ${videoId} do not clean` + : `allow cleanup for video ${videoId}` + } + onClick={() => run(next)} + className="self-start px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50" + > + {pending + ? "Saving…" + : doNotClean + ? "Allow cleanup" + : "Mark do not clean"} + </button> + </div> + {doNotClean && ( + <div className="flex flex-wrap items-center gap-2"> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + aria-label="do not clean note" + placeholder="note" + className="rounded border border-border bg-card px-2 py-1 text-sm w-64 max-w-full" + /> + <button + type="button" + disabled={pending || !note.trim() || note.trim() === (mark?.note ?? "")} + onClick={() => run(true, note)} + className="rounded border border-border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50" + > + {who && !who.mine ? "Save note (makes it mine)" : "Save note"} + </button> + </div> + )} {error && ( <span className="text-sm text-destructive" diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx @@ -7,7 +7,7 @@ import { TextFilePreview } from "../TextFilePreview"; import { deleteVideoFileAction, } from "../../videoActions"; -import { mediaKind, mediaUrl, type VideoFile } from "./videoFiles"; +import { isStoredCaptionFile, mediaKind, mediaUrl, type VideoFile } from "./videoFiles"; export function FilesList({ slug, @@ -27,7 +27,10 @@ export function FilesList({ className="flex flex-col gap-3" > {files.map((f) => { - const kind = mediaKind(f.name); + // A caption stored compressed (`transcript.en.vtt.zst`, lib/storedText.ts) + // is listed as the file it is, and previewed as its decoded text. + const storedCaption = isStoredCaptionFile(f.name); + const kind = storedCaption ? "text" : mediaKind(f.name); return ( <li key={f.name} @@ -53,7 +56,7 @@ export function FilesList({ /> ) : kind === "text" ? ( <TextFilePreview - src={mediaUrl(slug, videoId, f.name)} + src={`${mediaUrl(slug, videoId, f.name)}${storedCaption ? "?decoded=1" : ""}`} filename={f.name} /> ) : null} diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts b/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts @@ -2,6 +2,11 @@ import { AUDIO_EXTS, VIDEO_CONTAINER_EXTS, } from "yt-dlp-transcript-common/lib/mediaFiles"; +import { + isStoredCaptionName, + logicalEntries, + plainNameOf, +} from "yt-dlp-transcript-common/lib/storedText"; export type VideoFile = { name: string; @@ -21,6 +26,19 @@ export function isTranscriptVttName(name: string): boolean { return /^transcript\.[^.]+\.vtt$/.test(name); } +// The files card's listing is PHYSICAL: a caption stored compressed is +// `transcript.en.vtt.zst` there (lib/storedText.ts). Everything that MATCHES +// names — which tracks there are, which is primary — takes this LOGICAL list +// of it, where that file is `transcript.en.vtt`, once. +export function logicalFileNames(files: readonly VideoFile[]): string[] { + return logicalEntries(files.map((f) => f.name)); +} + +export function isStoredCaptionFile(name: string): boolean { + const plain = plainNameOf(name); + return plain !== null && isStoredCaptionName(plain); +} + // One list, shared with the detection predicates in lib/mediaFiles.ts — these // were duplicated here and drifting. isAudioFile deliberately stays on // AUDIO_EXTS alone: audio.mp4 is a wrong-format cleanup target, not something diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -1,5 +1,6 @@ import type { Metadata } from "next"; import { LiveRecordingsAttention } from "../../../../components/LiveRecordingsAttention"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import Link from "next/link"; import { notFound } from "next/navigation"; import path from "node:path"; @@ -10,7 +11,7 @@ import { loadAvailability } from "yt-dlp-transcript-common/lib/availability-serv import { loadMetadataHistory } from "yt-dlp-transcript-common/lib/metadataHistory-server"; import { metadataHistoryView } from "yt-dlp-transcript-common/views/metadataHistoryView"; import { listClipWindows } from "yt-dlp-transcript-common/lib/clipWindow-server"; -import { isDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server"; +import { loadDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server"; import { isExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server"; import { loadSavedVideo } from "yt-dlp-transcript-common/lib/savedVideo-server"; import { loadArchiveOrgProvenance } from "yt-dlp-transcript-common/lib/archiveOrg-server"; @@ -169,7 +170,10 @@ export default async function VideoDetailPage({ await loadMetadataHistory(videoDir), Date.now(), ); - const doNotClean = await isDoNotClean(videoDir); + // The mark itself, so the page says who set it and when (lane + // mark-provenance review F2). + const doNotCleanMark = await loadDoNotClean(videoDir); + const doNotClean = doNotCleanMark !== null; const excludedFromTruncatedCheck = await isExcludedFromTruncatedCheck(videoDir); const savedVideo = await loadSavedVideo(videoDir); @@ -196,9 +200,11 @@ export default async function VideoDetailPage({ // auto-captions" vs "manual captions" — and offer to replace the former with a // transcript of our own. One 4 KB head read per VTT (see subtitleProvenance). const vttProvenance: Record<string, SubtitleProvenance> = {}; - for (const f of dirData.files) { - if (!isTranscriptVtt(f.name)) continue; - vttProvenance[f.name] = await resolveVttProvenance(videoDir, f.name); + // By LOGICAL name (lib/storedText.ts): a track stored as `.zst` is sniffed + // decoded, under its plain name. + for (const name of logicalEntries(dirData.files.map((f) => f.name))) { + if (!isTranscriptVtt(name)) continue; + vttProvenance[name] = await resolveVttProvenance(videoDir, name); } const cov = await readTranscriptCoverage(videoDir); const coverage = cov @@ -260,6 +266,7 @@ export default async function VideoDetailPage({ availabilityHistory, metadataHistory, doNotClean, + doNotCleanMark, excludedFromTruncatedCheck, savedVideo, archiveOrg, @@ -296,6 +303,7 @@ export default async function VideoDetailPage({ availabilityHistory, metadataHistory, doNotClean, + doNotCleanMark, excludedFromTruncatedCheck, savedVideo, archiveOrg, @@ -425,7 +433,7 @@ export default async function VideoDetailPage({ // Read HERE, in the server component, never in the client one: an env // var does not exist in the browser. Unset means no link at all. umtoolUrl={process.env.UMTOOL_URL?.replace(/\/+$/, "") || null} - primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))} + primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))} vttProvenance={vttProvenance} handling={config.handling} defaultQueueKey={defaultQueueKey} @@ -435,6 +443,7 @@ export default async function VideoDetailPage({ availabilityHistory={availabilityHistory} channelAudioFormat={config.audioFormat} doNotClean={doNotClean} + doNotCleanMark={doNotCleanMark} excludedFromTruncatedCheck={excludedFromTruncatedCheck} savedVideo={savedVideo} sourceVideoQuality={resolveSourceVideoQuality({ diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -42,7 +42,7 @@ import { isXUrl, X_QUEUE_KEY, xJobContextRefusal } from "yt-dlp-transcript-commo import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; -import { setDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server"; +import { keepByPerson, setDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server"; import { loadPendingKeep, type PendingKeepEntry } from "yt-dlp-transcript-common/lib/pendingKeep-server"; import { KeepVideosError, @@ -61,6 +61,8 @@ import { 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 { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; +import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-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"; @@ -756,7 +758,8 @@ export async function whisperVideoAction( : await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries }); if (!audioOnDisk && asr !== true && r.config.handling === "youtube") { - const onDisk = englishVttsByPreference(firstEntries); + // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is on disk. + const onDisk = englishVttsByPreference(logicalEntries(firstEntries)); if (onDisk.length > 0) { return { ok: false, @@ -1080,18 +1083,25 @@ export async function deleteVideoFileAction( if (out === "busy") { return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` }; } + if ("refused" in out) return { ok: false, error: out.refused }; + // The pick deleted beside a stored `en` of other content: the pin went with + // it (removeStoredTextForm; REVIEW-1 N1, captions lane). + const unpinned = out.unpinned === true; revalidatePath(`/channels/${slug}/videos/${videoId}`); requestChannelSnapshot(getPaths(), slug); if (out.kept) { const k = out.kept; + const pinNote = unpinned + ? " The transcript pin was removed with it: the caption-track rule picks the transcript again." + : ""; 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 === "same" + ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still read it.` : 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).`, + : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`) + pinNote, }; } return { ok: true }; @@ -1122,10 +1132,16 @@ export async function setPrimaryTranscriptAction( } let raw: string; try { - raw = await readFile(source, "utf8"); + // Either form (lib/storedText.ts): a track stored as `.zst` is read. + raw = await readStoredText(videoDir, path.basename(source), "utf8"); } catch { return { ok: false, error: `File not found: ${filename}` }; } + // The copy is written under the plain name. A STORED `transcript.en.vtt.zst` + // beside it (YouTube's own `en` track, compressed) is NOT removed: the new + // plain file is what every reader reads (lib/storedText.ts, plain is the + // truth), and the earlier track stays beside it — both forms, different + // content, which compress-text lists and never settles by deleting one. if (filename !== VTT_FILENAME) { await writeFileAtomic(path.join(videoDir, VTT_FILENAME), raw); } @@ -1294,11 +1310,20 @@ export async function markVideoUntranscribableAction( return { ok: true }; } +// `surface`: where the person asked — the video page's toggle ("button", the +// default) or `pnpm ops do-not-clean` ("ops"); recorded on the mark. +// ON IS A PERSON'S KEEP (keepByPerson): a mark another writer set — the +// availability check, an import, a live recording — becomes the operator's +// ("Make it mine" on the video page; `do-not-clean {keep: true}`), keeping +// its note unless `note` is given; a person's own mark is left as it is, or +// gains the `note`. export async function toggleDoNotCleanAction( slug: string, videoId: string, enabled: boolean, -): Promise<{ ok: true } | { ok: false; error: string }> { + surface: "button" | "ops" = "button", + note?: string, +): Promise<{ ok: true; outcome?: "marked" | "taken-over" | "already-kept" | "removed" } | { ok: false; error: string }> { const videoDir = videoDirOf(slug, videoId); try { const s = await stat(videoDir); @@ -1308,11 +1333,20 @@ export async function toggleDoNotCleanAction( } catch { return { ok: false, error: `Video directory not found: ${videoId}` }; } - await setDoNotClean(videoDir, enabled); + const trimmed = typeof note === "string" ? note.trim() : ""; + const outcome = enabled + ? ( + await keepByPerson(videoDir, { + via: "toggle", + surface: surface === "ops" ? "ops" : "button", + ...(trimmed ? { note: trimmed } : {}), + }) + ).outcome + : (await setDoNotClean(videoDir, false), "removed" as const); revalidatePath(`/channels/${slug}/videos/${videoId}`); revalidatePath(`/channels/${slug}`); requestChannelSnapshot(getPaths(), slug); - return { ok: true }; + return { ok: true, outcome }; } // The BULK form of the toggle above: set the do-not-clean marker on every video @@ -1328,6 +1362,7 @@ export async function keepVideosAction(input: { fields?: KeepVideosField[]; note?: string; dryRun?: boolean; + surface?: "button" | "ops"; }): Promise<{ ok: true; result: KeepVideosResult } | { ok: false; error: string }> { let result: KeepVideosResult; try { @@ -1338,6 +1373,7 @@ export async function keepVideosAction(input: { fields: input.fields, note: input.note, dryRun: input.dryRun, + surface: input.surface === "button" ? "button" : "ops", }); } catch (e) { if (e instanceof KeepVideosError || e instanceof ChannelMediaUnreachableError) { @@ -1363,6 +1399,9 @@ export async function keepVideoIdsAction(input: { ids: string[]; note?: string; dryRun?: boolean; + // Where the person asked: the Keep matching control ("button", the + // default) or `pnpm ops keep-videos` ("ops"). + surface?: "button" | "ops"; }): Promise<{ ok: true; result: KeepVideosByIdsResult } | { ok: false; error: string }> { let result: KeepVideosByIdsResult; try { @@ -1372,6 +1411,7 @@ export async function keepVideoIdsAction(input: { ids: input.ids, note: input.note, dryRun: input.dryRun, + surface: input.surface === "ops" ? "ops" : "button", }); } catch (e) { if (e instanceof KeepVideosError || e instanceof ChannelMediaUnreachableError) { diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -188,8 +188,15 @@ export type FetchWindowsActionResult = // and why; and the asked height when clips.windowMaxHeight clamped it. lower?: FetchWindowsLower[]; clampedFrom?: number; + // THE RECORDING'S END (lane window-end, lib/recordingEnd.mjs): of the + // saved-video group, the windows asked past the end of a saved recording + // known whole, which the job cuts clamped at it — the end asked, the end + // it will be cut to (the window's name) and why. + atRecordingEnd?: FetchWindowsAtEnd[]; }; +export type FetchWindowsAtEnd = { item: FetchWindowsItem; askedTo: number; cutTo: number; why: string }; + export type FetchWindowsLower = { item: FetchWindowsItem; file: string; height: number | null; asked: number; why: string }; export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string }; @@ -242,6 +249,7 @@ async function planFetchWindows( stored: Set<FetchWindowsItem>; lower: FetchWindowsLower[]; clampedFrom?: number; + atRecordingEnd: FetchWindowsAtEnd[]; }> { const paths = getPaths(); const settings = getSettings(); @@ -252,6 +260,7 @@ async function planFetchWindows( const { cap, clampedFrom } = clampWindowCap(maxHeight, ceiling); const tier = windowTierOf(cap, ceiling); const lower: FetchWindowsLower[] = []; + const atRecordingEnd: FetchWindowsAtEnd[] = []; const heightProbe = (file: string) => probeVideoHeight({ ffprobeBin: paths.ffprobeBin, file }); const configs = new Map<string, ChannelConfig | null>(); const groups = new Map<string, FetchWindowsGroup>(); @@ -400,6 +409,9 @@ async function planFetchWindows( queueKey, items: [], }; + if (saved.kind === "covers" && saved.clamp) { + atRecordingEnd.push({ item, askedTo: saved.clamp.askedTo, cutTo: saved.clamp.cutTo, why: saved.clamp.why }); + } group.items.push(item); groups.set(queueKey, group); continue; @@ -508,6 +520,7 @@ async function planFetchWindows( registered, lower, ...(clampedFrom !== undefined ? { clampedFrom } : {}), + atRecordingEnd, }; } @@ -651,7 +664,7 @@ export async function fetchWindowsAction( const archive: ConnectedArchive | null = req.archive?.trim() ? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive) : null; - const { groups, cached, inFlight, unresolved, stored, registered, lower, clampedFrom } = await planFetchWindows( + const { groups, cached, inFlight, unresolved, stored, registered, lower, clampedFrom, atRecordingEnd } = await planFetchWindows( req.items, req.queueKey, req.maxHeight, @@ -675,6 +688,7 @@ export async function fetchWindowsAction( refused: [], ...(lower.length ? { lower } : {}), ...(clampedFrom !== undefined ? { clampedFrom } : {}), + ...(atRecordingEnd.length ? { atRecordingEnd } : {}), }; if (req.dryRun) return { ok: true, dryRun: true, ...base }; if (groups.length === 0) return { ok: true, dryRun: false, ...base }; @@ -761,6 +775,7 @@ export async function fetchWindowsAction( refused, ...(lower.length ? { lower } : {}), ...(clampedFrom !== undefined ? { clampedFrom } : {}), + ...(atRecordingEnd.length ? { atRecordingEnd } : {}), }; } diff --git a/editor/app/channels/[slug]/videos/page.tsx b/editor/app/channels/[slug]/videos/page.tsx @@ -1,5 +1,6 @@ import path from "node:path"; import type { Metadata } from "next"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText"; import { notFound } from "next/navigation"; import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import type { ChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; @@ -249,7 +250,7 @@ export default async function ChannelVideosPage({ slug={slug} videoId={selectedVideoId} files={dirData.files} - primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))} + primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))} handling={config.handling} defaultQueueKey={platformDefaultQueueKey} existingQueues={existingQueues} diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -354,6 +354,8 @@ export async function cleanAudioButtonAction( // not asked; every other protection of the sweep holds; at most the plan's // videos lose their audio. A call with no plan queues a job that removes // nothing and ends failed, "Confirmed plan lost; confirm again". +// `sourceGone`: the opt-in "also remove audio kept only because the source was +// gone", as the plan's sourceGone ids a person confirmed (default: none — off). export async function cleanAudioUncheckedAction( slug: string, queueKey?: string, @@ -361,9 +363,16 @@ export async function cleanAudioUncheckedAction( // The plan's counts, stated in the job's log before anything is removed // (`pnpm ops cleanup {"unchecked": true}` counts at the call). planCounts?: CleanPlanCountsLog, + sourceGone?: string[], ): Promise<StreamActionResult> { await supersedeCleanRetries(slug); - return runCleanAudio(slug, queueKey, cleanAudioRequestFor(null, { explicit: "button", plan }), undefined, planCounts); + return runCleanAudio( + slug, + queueKey, + cleanAudioRequestFor(null, { explicit: "button", plan, ...(sourceGone ? { sourceGone } : {}) }), + undefined, + planCounts, + ); } // The retry of a rate-limited clean, queued by its schedule at its not-before @@ -426,7 +435,7 @@ function runCleanAudio( ): Promise<StreamActionResult> { const paths = getPaths(); const kind = retry ? "clean-audio-retry" : req.kind; - const { unchecked, plan } = req; + const { unchecked, plan, sourceGone } = req; // A retry runs on the CHANNEL's queue, whatever queue the request took. const key = retry ? channelQueueKey(slug) : resolveQueueKey(channelQueueKey(slug), queueKey); return runManagedFunction({ @@ -442,6 +451,7 @@ function runCleanAudio( ...(unchecked ? { unchecked } : {}), ...(plan ? { plan } : {}), ...(plan && planCounts ? { planCounts } : {}), + ...(sourceGone ? { sourceGone } : {}), ...(retry ? { retry } : {}), }, }, @@ -459,6 +469,7 @@ function runCleanAudio( ...(unchecked ? { unchecked } : {}), ...(plan ? { plan } : {}), ...(plan && planCounts ? { planCounts } : {}), + ...(sourceGone ? { sourceGone } : {}), ...(retry ? { retry } : {}), onLog, signal, @@ -571,12 +582,13 @@ export async function checkKeptDeletedAction( paths, channelSlug: slug, spec: { kind: "check-kept-deleted", slug, params: { queueKey } }, - fn: async (onLog, signal) => { + fn: async (onLog, signal, _setProgress, ctx) => { const result = await checkKeptDeleted({ channelSlug: slug, paths, onLog, signal, + jobId: ctx.jobId, }); onLog( `Kept-deletion check: inspected ${result.kept}, ${result.deleted} gone from source, pinned ${result.pinned}.`, diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -1,11 +1,21 @@ "use server"; import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { + backfillMarkProvenance, + undoMarkProvenanceBackfill, + type MarkBackfillResult, + type MarkUndoResult, +} from "yt-dlp-transcript-common/controller/marksBackfill"; +import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean"; +import { listDoNotCleanMarks } from "yt-dlp-transcript-common/lib/doNotClean-server"; import { cleanRetryDeps } from "./[slug]/cleanRetryScheduler"; import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel"; import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults"; import { revalidatePath } from "next/cache"; +import path from "node:path"; +import { readdir } from "node:fs/promises"; import { redirect } from "next/navigation"; import slugify from "@sindresorhus/slugify"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; @@ -667,6 +677,56 @@ export async function setCleanAudioWithoutCheckingAction( return undefined; } +// MARKS-BACKFILL (lane mark-provenance; `pnpm ops marks-backfill`): relabel a +// channel's old do-not-clean marks as set by the availability check, inferred, +// only where availability.json and a clean job's log prove it. Dry run unless +// `dryRun` is exactly false. No UI: an operator's one-off, from the CLI. +// `undo`: every INFERRED label of the channel back to unlabelled. +export async function marksBackfillAction( + slug: string, + dryRun = true, + undo = false, +): Promise<{ ok: true; result: MarkBackfillResult | MarkUndoResult } | { ok: false; error: string }> { + const paths = getPaths(); + if (!(await readChannelConfig(paths, slug))) return { ok: false, error: `Channel "${slug}" not found` }; + try { + const result = undo + ? await undoMarkProvenanceBackfill({ paths, channelSlug: slug, dryRun: dryRun !== false }) + : await backfillMarkProvenance({ paths, channelSlug: slug, dryRun: dryRun !== false }); + const changed = "undo" in result ? result.unlabelled.length : result.relabelled.length; + if (!result.dryRun && changed > 0) { + revalidatePath(`/channels/${slug}`); + revalidatePath("/cleanup"); + } + return { ok: true, result }; + } catch (err) { + return { ok: false, error: (err as Error).message }; + } +} + +// THE MARKS OF A CHANNEL (`pnpm ops get marks <slug>`): every do-not-clean +// mark, who set it and when (describeDoNotCleanMark, the video page's words), +// and whether Clean without checking's opt-in could reach it. +export async function listMarksAction( + slug: string, +): Promise< + | { ok: true; marks: { id: string; setBy: string; mine: boolean; sourceGone: boolean; mark: DoNotCleanRecord }[] } + | { ok: false; error: string } +> { + const paths = getPaths(); + if (!(await readChannelConfig(paths, slug))) return { ok: false, error: `Channel "${slug}" not found` }; + const dataDir = path.join(paths.channelsDir, slug, "data"); + const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); + const rows = await listDoNotCleanMarks(dataDir, ids); + return { + ok: true, + marks: rows.map(({ id, mark }) => { + const d = describeDoNotCleanMark(mark); + return { id, setBy: d.text, mine: d.mine, sourceGone: d.sourceGone, mark }; + }), + }; +} + // Toggle whether this channel's reclaimable bytes count toward the aggregate // "cleanable data" total on the /cleanup page (and its sidebar badge). The // cleanup sweeps themselves stay available regardless; this only flips the diff --git a/editor/app/cookies/CookiesBoard.tsx b/editor/app/cookies/CookiesBoard.tsx @@ -13,9 +13,10 @@ import { ageSentence, type CookieRow, type CookieStatusPayload, + type XSittingView, } from "yt-dlp-transcript-common/lib/cookieStatus"; import { usePolledPayload } from "../lib/usePolledPayload"; -import { cookieControlsAction, pressCookieButtonAction } from "./actions"; +import { clearXStopAction, cookieControlsAction, pressCookieButtonAction, setXAccountStateAction } from "./actions"; import { sectionFailed, type CookieControls } from "../lib/cookieControlsTypes"; import { XSessionSection } from "../settings/components/XSessionSection"; import { ArchiveSourcesSection } from "../settings/components/ArchiveSessionSection"; @@ -175,6 +176,116 @@ function Row({ ); } + +// X'S SITTING AND ACCOUNT (lane x-sittings): how many X job starts the last +// Refresh admitted and has left, its kind, when it began; X's cooldown after +// a 429; and the account's state with its one control (Mark suspended / Mark +// ok — `pnpm ops x-session` is the same write). +function XSittingPanel({ view, onStatus }: { view: XSittingView; onStatus: (s: CookieStatusPayload) => void }) { + const [note, setNote] = useState(""); + const [pending, setPending] = useState(false); + const [answer, setAnswer] = useState<{ text: string; ok: boolean } | null>(null); + const suspended = view.account.state === "suspended"; + const mark = async () => { + if (pending) return; + setPending(true); + setAnswer(null); + try { + const r = await setXAccountStateAction(suspended ? "ok" : "suspended", suspended ? undefined : note); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + if (r.ok) setNote(""); + } catch (e) { + setAnswer({ text: (e as Error).message || "The mark failed.", ok: false }); + } finally { + setPending(false); + } + }; + const began = view.began ? `began ${hms(view.began)}` : "no refresh on record"; + const kind = view.kind === null ? "no job yet" : view.kind; + return ( + <section aria-label="X sitting" className="flex flex-col gap-2 border-t border-border pt-2"> + <p className="text-sm" aria-label="X sitting count"> + {view.unreadable ? ( + <span className="text-destructive">Sitting unreadable: no X job starts until .x-session/sitting.json is repaired.</span> + ) : ( + <> + Sitting: {view.used} of {view.limit} used, {view.left} left + <span className="text-muted-foreground"> · {kind} · {began}</span> + </> + )} + </p> + {view.left === 0 && !view.unreadable && ( + <p className="text-xs text-muted-foreground">Used up: Refresh starts the next sitting.</p> + )} + {view.cooldownUntil && ( + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + <p className="text-xs text-destructive" aria-label="X cooldown"> + X answered a rate limit or a bot check: no X job starts before {hms(view.cooldownUntil)}. + </p> + <button + type="button" + aria-label="Clear the X stop" + disabled={pending} + onClick={async () => { + if ( + !window.confirm( + "Clearing the X stop lets the next X job ask X at once, inside the 15 minutes X was left alone for. " + + "Asking again then is what gets an account limited or locked. Clear it?", + ) + ) + return; + setPending(true); + try { + const r = await clearXStopAction(true); + onStatus(r.status); + setAnswer({ text: r.message, ok: r.ok }); + } finally { + setPending(false); + } + }} + className="w-full rounded-md border border-destructive/60 px-3 py-2 text-sm text-destructive hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + Clear the X stop + </button> + </div> + )} + {view.account.alert && ( + <p role="alert" aria-label="X account alert" className="text-xs text-destructive break-words"> + {view.account.alert} + </p> + )} + <div className="flex flex-col gap-2 sm:flex-row sm:items-center"> + {!suspended && ( + <input + type="text" + value={note} + onChange={(e) => setNote(e.target.value)} + placeholder="Note (optional)" + aria-label="X account note" + maxLength={300} + className="w-full rounded-md border border-border bg-background px-2 py-1.5 text-sm sm:w-64" + /> + )} + <button + type="button" + onClick={mark} + disabled={pending} + aria-label={suspended ? "Mark X account ok" : "Mark X account suspended"} + className="w-full rounded-md border border-border px-3 py-2 text-sm hover:bg-muted disabled:opacity-50 sm:w-auto sm:py-1.5" + > + {pending ? "Saving…" : suspended ? "Mark ok" : "Mark suspended"} + </button> + </div> + {answer && ( + <p role="status" aria-label="X account mark result" className={`text-xs ${answer.ok ? "text-success" : "text-destructive"}`}> + {answer.text} + </p> + )} + </section> + ); +} + const DISCLOSURE = "border-t border-border pt-2"; const SUMMARY = "cursor-pointer text-sm font-medium"; @@ -296,6 +407,7 @@ export function CookiesBoard({ initial, controls }: { initial: CookieStatusPaylo controls={ctl} gen={gens[row.service] ?? 0} refetch={() => void refetch()} + {...(row.service === "x" && status.xSitting ? { xSitting: status.xSitting, onXStatus: take } : {})} /> ))} </ul> @@ -310,16 +422,21 @@ function ItemsFor({ controls, gen, refetch, + xSitting, + onXStatus, }: { row: CookieRow; take: (s: CookieStatusPayload) => void; controls?: CookieControls; gen: number; refetch: () => void; + xSitting?: XSittingView; + onXStatus?: (s: CookieStatusPayload) => void; }) { return ( <> <Row row={row} onStatus={take}> + {xSitting ? <XSittingPanel view={xSitting} onStatus={onXStatus ?? take} /> : null} {controls ? <Controls row={row} controls={controls} gen={gen} refetch={refetch} /> : null} </Row> {controls && row.service === "odysee" && ( diff --git a/editor/app/cookies/actions.ts b/editor/app/cookies/actions.ts @@ -37,6 +37,8 @@ import { connectForumAt } from "../lib/connectForum"; import { listForumChannels } from "../lib/forumChannels"; import { loadCookieStatus } from "../lib/cookieStatus"; import { loadCookieControls, type CookieControls } from "../lib/cookieControls"; +import { writeXAccountState } from "yt-dlp-transcript-common/social/xAccountState"; +import { clearXStop } from "yt-dlp-transcript-common/jobs/downloadBackoff"; export type CookiePressResult = { ok: boolean; @@ -105,3 +107,37 @@ export async function pressCookieButtonAction(service: string, action: string): // An error may carry a path: drawn as the page draws one. return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(getPaths(), { fresh: action === "recheck" }) }; } + +// THE X ACCOUNT'S STATE, MARKED BY HAND (lane x-sittings): "suspended" refuses +// the X jobs that record posts as deleted or unavailable; "ok" lifts that. The +// same write as `pnpm ops x-session --json '{"accountState":…}'`. Nothing is +// asked of X. Answers the screen's rows read again. +export async function setXAccountStateAction(state: string, note?: string): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + if (state !== "suspended" && state !== "ok") { + answer = { ok: false, message: `Not an account state: ${String(state)}` }; + } else { + try { + const r = await writeXAccountState(paths, state, typeof note === "string" && note.trim() ? { note } : {}); + answer = { ok: true, message: r.state === "suspended" ? "Marked suspended." : "Marked ok." }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} + +// "CLEAR THE X STOP" on /cookies (common/jobs/downloadBackoff.ts clearXStop): +// the page asks the operator to confirm what it risks first; logged. +export async function clearXStopAction(confirm: boolean): Promise<CookiePressResult> { + const paths = getPaths(); + let answer: Answer; + try { + const r = await clearXStop(paths, { confirm: confirm === true, by: "/cookies" }); + answer = { ok: r.ok, message: r.message }; + } catch (e) { + answer = { ok: false, message: (e as Error).message }; + } + return { ...answer, message: displayText(answer.message), status: await loadCookieStatus(paths) }; +} diff --git a/editor/app/instrumentation.test.ts b/editor/app/instrumentation.test.ts @@ -0,0 +1,35 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Run with: +// pnpm -C editor exec tsx --test app/instrumentation.test.ts +// +// REVIEW-1 F3 (captions lane): on a Node without zstd the editor REFUSES TO +// START — register() says which Node it needs and exits — instead of running +// with every stored caption and chat unreadable. The check is the first thing +// register() does in the Node runtime, before any runner is armed. + +const EDITOR = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +test("register() on a Node without zstd: the editor refuses to start, naming the Node it needs", async (t) => { + const own = await mkdtemp(path.join(os.tmpdir(), "editor-no-zstd-")); + t.after(() => rm(own, { recursive: true, force: true })); + const preload = path.join(own, "no-zstd.mjs"); + await writeFile(preload, 'import zlib from "node:zlib";\nfor (const k of ["zstdDecompress", "createZstdCompress", "createZstdDecompress"]) delete zlib[k];\n'); + const tsx = path.join(EDITOR, "..", "node_modules", ".bin", "tsx"); + const script = `import(${JSON.stringify(path.join(EDITOR, "instrumentation.ts"))}).then((m) => m.register()).then(() => console.log("BOOTED"));`; + const r = spawnSync(tsx, ["-e", script], { + cwd: EDITOR, + encoding: "utf8", + timeout: 60_000, + env: { ...process.env, NODE_OPTIONS: `--import=${preload}`, NEXT_RUNTIME: "nodejs", TRANSCRIPTS_DIR: own, SETTINGS_FILE: path.join(own, "s.json") }, + }); + assert.equal(r.status, 1, r.stdout + r.stderr); + assert.doesNotMatch(r.stdout, /BOOTED/); + assert.match(r.stderr, /editor refuses to start: stored text .*needs node:zlib zstd — Node >= 22\.15/); +}); diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -22,6 +22,7 @@ import { isSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFor import { isPersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; import { compactChannelVideosAction } from "../saved-videos/compactActions"; import { compressTextJobAction } from "../storage/compressTextActions"; +import { isCompressTextKind } from "yt-dlp-transcript-common/controller/compressText"; import { downloadAction, downloadMissingAction, @@ -649,10 +650,14 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { "compress-text": (spec) => { const { p } = params(spec); const limit = num(p.limit); + // The kinds it ran over (a spec from before captions were a kind has + // none: the live chat alone, the default). + const kinds = (strings(p.kinds) ?? []).filter(isCompressTextKind); return compressTextJobAction(spec.slug, { ...(limit !== undefined ? { limit } : {}), ...(p.verify === true ? { verify: true } : {}), ...(p.restore === true ? { restore: true } : {}), + ...(kinds.length ? { kinds } : {}), }); }, "compact-saved-videos": (spec) => { diff --git a/editor/app/lib/cookieControls.ts b/editor/app/lib/cookieControls.ts @@ -7,6 +7,7 @@ // cookieMode), and each forum host's session status. Never the whole settings // object, never a corpus walk. The rows themselves are lib/cookieStatus.ts. +import { xPacingOf } from "./xPacing"; import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings, type SiteSettings } from "yt-dlp-transcript-common/lib/settings"; import { displayText } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; @@ -61,6 +62,7 @@ export async function loadCookieControls( initialSource: xSourceForDisplay(xCookieSourceView(resolved)), initialVisibility: xPostsVisibility(st), initialMaxCookieAge: xMaxCookieAgeMinutes(st.social.x), + initialPacing: xPacingOf(st.social.x), }; }), ), diff --git a/editor/app/lib/cookieControlsTypes.ts b/editor/app/lib/cookieControlsTypes.ts @@ -20,6 +20,8 @@ export type XControls = { initialSource: XCookieSourceView; initialVisibility: XPostsVisibility; initialMaxCookieAge: number; + // X in sittings (lib/xSitting.ts): jobs per refresh, the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; }; export type ArchiveControls = { initial: ArchivesSettings; session: ArchiveSessionStatus }; export type YtdlpControls = { cookiesFromBrowser: string; cookieMode: string }; diff --git a/editor/app/lib/cookieStatus.ts b/editor/app/lib/cookieStatus.ts @@ -37,6 +37,8 @@ import { forumSessionDir, readForumSessionStatus } from "yt-dlp-transcript-commo import { loadCookieAlerts } from "./cookieAlerts"; import { listForumChannels } from "./forumChannels"; import { runningCookieActions } from "./cookieRefreshGuard"; +import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard"; +import type { XSittingView } from "yt-dlp-transcript-common/lib/cookieStatus"; async function safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> { try { @@ -123,7 +125,17 @@ export async function loadCookieStatus( const forumChannels = await safe(() => listForumChannels(paths, { fresh: opts.fresh === true }), []); - return buildCookieStatus({ + // X's sitting and account (lane x-sittings), read from disk: nothing asks X. + const report = await safe(() => xSessionReport({ paths, now }), null); + const xSitting: XSittingView | undefined = report + ? { + ...report.sitting, + account: report.account, + ...(report.cooldown ? { cooldownUntil: report.cooldown.until } : {}), + } + : undefined; + + const payload = buildCookieStatus({ now, alerts, state, @@ -135,4 +147,5 @@ export async function loadCookieStatus( running: runningCookieActions(), display: { path: displayPath, text: displayText }, }); + return xSitting ? { ...payload, xSitting } : payload; } diff --git a/editor/app/lib/xPacing.ts b/editor/app/lib/xPacing.ts @@ -0,0 +1,18 @@ +// X's sitting and gap settings as the X session controls draw them +// (common/lib/xSitting.ts): each resolved, the default where none is set. +import { + X_GAP_MIN_SPREAD_MINUTES, + X_GAP_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + parseXGapMinutes, + xSittingJobs, +} from "yt-dlp-transcript-common/lib/xSitting"; + +export function xPacingOf(x: { sittingJobs?: number; gapMinMinutes?: number; gapMaxMinutes?: number } | undefined) { + const gapMinMinutes = parseXGapMinutes(x?.gapMinMinutes) ?? X_GAP_DEFAULT_MIN_MINUTES; + return { + sittingJobs: xSittingJobs(x), + gapMinMinutes, + gapMaxMinutes: Math.max(gapMinMinutes + X_GAP_MIN_SPREAD_MINUTES, parseXGapMinutes(x?.gapMaxMinutes) ?? X_GAP_DEFAULT_MAX_MINUTES), + }; +} diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx @@ -38,10 +38,12 @@ function age(ms: number): string { } // X's queue gap, as the run waits it between two channels. -function gapText(seconds: number): string { - if (seconds <= 0) return "no gap between channels"; - if (seconds < 120) return `${seconds} s between channels`; - return `${Math.round(seconds / 60)} min between channels`; +function gapText(seconds: number, maxSeconds = seconds): string { + if (maxSeconds <= 0) return "no gap between channels"; + if (maxSeconds < 120) return seconds === maxSeconds ? `${seconds} s between channels` : `${seconds}-${maxSeconds} s between channels`; + const lo = Math.round(seconds / 60); + const hi = Math.round(maxSeconds / 60); + return lo === hi ? `${lo} min between channels` : `${lo}-${hi} min between channels, drawn per channel`; } function when(iso: string | null): string { @@ -338,7 +340,7 @@ export function XRunConsole({ initial }: { initial: XRunConsolePayload }) { Start X run ({chosen.length}) </button> <span className="text-xs text-muted-foreground"> - ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds)} + ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds, view.gapMaxSeconds ?? view.gapSeconds)} </span> </div> {note && ( diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -28,7 +28,7 @@ import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap"; // platform's key is set by hand in settings.json. const JOB_GAP_FIELDS = [ { key: "default", label: "Every platform" }, - { key: "twitter", label: "X" }, + { key: "twitter", label: "X (minimum)" }, { key: "xenforo", label: "Forums" }, { key: "bluesky", label: "Bluesky" }, { key: "instagram", label: "Instagram" }, @@ -127,7 +127,9 @@ export function SettingsForm({ initial }: Props) { only this long after the previous one on the same platform ended; its row on /jobs says how long it still waits. Built in: 20 s everywhere, 300 s for X, 60 s for forums and Bluesky. 0 turns a - gap off. + gap off — except X&apos;s: its gap is drawn anew for each job in + 5–12 min (set in the X account session), and a value here above + 300 s only raises its minimum. </span> </fieldset> <Field diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -20,6 +20,7 @@ import { refreshXCookiesAction, setXCookieSourceAction, setXMaxCookieAgeAction, + setXPacingAction, type XSessionActionResult, } from "../xSessionActions"; import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; @@ -37,6 +38,7 @@ export function XSessionSection({ initialSource, initialVisibility, initialMaxCookieAge, + initialPacing = { sittingJobs: 4, gapMinMinutes: 5, gapMaxMinutes: 12 }, onChange, cookiesLink = true, }: { @@ -48,12 +50,17 @@ export function XSessionSection({ initialVisibility: XPostsVisibility; // `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off). initialMaxCookieAge: number; + // X in sittings: jobs per cookie refresh (1-6) and the gap's range (min). + initialPacing?: { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; // Told after every action here ends (the /cookies screen re-reads its row). onChange?: () => void; // The one-line link to /cookies (left out when drawn ON /cookies). cookiesLink?: boolean; }) { const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge)); + const [sittingJobs, setSittingJobs] = useState(String(initialPacing.sittingJobs)); + const [gapMin, setGapMin] = useState(String(initialPacing.gapMinMinutes)); + const [gapMax, setGapMax] = useState(String(initialPacing.gapMaxMinutes)); const [status, setStatus] = useState<XSessionStatus>(initial); const [source, setSource] = useState<XCookieSourceView>(initialSource); const [login, setLogin] = useState<XLoginStatus | null>(null); @@ -264,8 +271,78 @@ export function XSessionSection({ unless the cookies were refreshed this recently — press Refresh cookies first. The editor never refreshes them itself: a refresh loads x.com. With the browser login the age cannot be read and is not checked. 0 - turns the check off. X jobs are also spaced 5 minutes apart, and none - starts while X&apos;s cookie alert is up on the dashboard. + turns the check off. None starts while X&apos;s cookie alert is up on + the dashboard, or for 15 minutes after X answers a rate limit. + </p> + + <div className="flex flex-wrap items-center gap-2"> + <label htmlFor="x-sitting-jobs" className="text-sm"> + At most + </label> + <input + id="x-sitting-jobs" + aria-label="x jobs per sitting" + type="number" + min={1} + max={6} + value={sittingJobs} + onChange={(e) => setSittingJobs(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">X jobs per cookie refresh, spaced</span> + <input + aria-label="x gap min minutes" + type="number" + min={5} + max={120} + value={gapMin} + onChange={(e) => setGapMin(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">to</span> + <input + aria-label="x gap max minutes" + type="number" + min={5} + max={120} + value={gapMax} + onChange={(e) => setGapMax(e.target.value)} + className="w-16 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">min apart</span> + <button + type="button" + aria-label="save x sittings" + disabled={checking} + onClick={() => + startChecking(async () => { + setError(null); + setNote(null); + const res = await setXPacingAction({ + sittingJobs: Number(sittingJobs), + gapMinMinutes: Number(gapMin), + gapMaxMinutes: Number(gapMax), + }); + if (res.ok) { + setNote( + `A refresh now admits ${res.pacing.sittingJobs} X job${res.pacing.sittingJobs === 1 ? "" : "s"}, ` + + `${res.pacing.gapMinMinutes}–${res.pacing.gapMaxMinutes} min apart.`, + ); + } else setError(res.error); + onChange?.(); + }) + } + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Save + </button> + </div> + <p className="text-xs text-muted-foreground"> + One refresh, one sitting: its first job makes it timelines (account + fetches, captures, checks) or browse (trending reads, X searches), and + a job of the other kind waits for the next Refresh. The gap is drawn + anew for each job. At most 6 per sitting and 5 min apart, whatever is + set here. </p> <div className="flex flex-wrap gap-2"> diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -14,6 +14,7 @@ import { StreamErrorBoundary } from "../components/StreamErrorBoundary"; import { e2eStreamDelay } from "../lib/streamDelay"; import { xSourceForDisplay } from "../lib/xSourceDisplay"; import { XSessionSection } from "./components/XSessionSection"; +import { xPacingOf } from "../lib/xPacing"; import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; @@ -195,6 +196,7 @@ async function XSection({ settings }: { settings: SiteSettings }) { initialSource={xSource} initialVisibility={xPostsVisibility(settings)} initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)} + initialPacing={xPacingOf(settings.social.x)} /> </StreamFilled> ); diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -17,6 +17,16 @@ import { revalidatePath } from "next/cache"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { + X_GAP_CEILING_MINUTES, + X_GAP_DEFAULT_MAX_MINUTES, + X_GAP_DEFAULT_MIN_MINUTES, + X_GAP_FLOOR_MINUTES, + X_GAP_MIN_SPREAD_MINUTES, + X_SITTING_DEFAULT_JOBS, + X_SITTING_MAX_JOBS, + X_SITTING_MIN_JOBS, +} from "yt-dlp-transcript-common/lib/xSitting"; +import { clearXSession, connectXAccount, readXSessionStatus, @@ -238,3 +248,40 @@ export async function setXMaxCookieAgeAction(minutes: number): Promise<XMaxCooki revalidatePath("/settings"); return { ok: true, minutes }; } + +// X IN SITTINGS (common/lib/xSitting.ts): the X job starts one cookie refresh +// admits (`social.x.sittingJobs`, 1-6) and the range X's gap is drawn from +// (`gapMinMinutes`-`gapMaxMinutes`, never below 5). A default is written as no +// key. The same keys `pnpm ops settings` writes. +export type XPacingInput = { sittingJobs: number; gapMinMinutes: number; gapMaxMinutes: number }; +export type XPacingResult = { ok: true; pacing: XPacingInput } | { ok: false; error: string }; + +export async function setXPacingAction(input: XPacingInput): Promise<XPacingResult> { + const { sittingJobs, gapMinMinutes, gapMaxMinutes } = input ?? ({} as XPacingInput); + if (!Number.isInteger(sittingJobs) || sittingJobs < X_SITTING_MIN_JOBS || sittingJobs > X_SITTING_MAX_JOBS) { + return { ok: false, error: `Jobs per sitting must be a whole number, ${X_SITTING_MIN_JOBS}–${X_SITTING_MAX_JOBS}.` }; + } + if (!Number.isInteger(gapMinMinutes) || gapMinMinutes < X_GAP_FLOOR_MINUTES || gapMinMinutes > X_GAP_CEILING_MINUTES) { + return { ok: false, error: `The shortest gap must be a whole number of minutes, ${X_GAP_FLOOR_MINUTES}–${X_GAP_CEILING_MINUTES}.` }; + } + if (!Number.isInteger(gapMaxMinutes) || gapMaxMinutes < gapMinMinutes + X_GAP_MIN_SPREAD_MINUTES || gapMaxMinutes > X_GAP_CEILING_MINUTES) { + return { + ok: false, + error: `The longest gap must be a whole number of minutes, at least ${X_GAP_MIN_SPREAD_MINUTES} above the shortest and at most ${X_GAP_CEILING_MINUTES}: a range of one value is a fixed beat.`, + }; + } + try { + await saveSettings( + socialXPatch(({ sittingJobs: _s, gapMinMinutes: _a, gapMaxMinutes: _b, ...rest }) => ({ + ...rest, + ...(sittingJobs !== X_SITTING_DEFAULT_JOBS ? { sittingJobs } : {}), + ...(gapMinMinutes !== X_GAP_DEFAULT_MIN_MINUTES ? { gapMinMinutes } : {}), + ...(gapMaxMinutes !== X_GAP_DEFAULT_MAX_MINUTES ? { gapMaxMinutes } : {}), + })), + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/settings"); + return { ok: true, pacing: { sittingJobs, gapMinMinutes, gapMaxMinutes } }; +} diff --git a/editor/app/storage/compressTextActions.ts b/editor/app/storage/compressTextActions.ts @@ -6,6 +6,7 @@ import { COMPRESS_RATE_BYTES, COMPRESS_RATE_RECORDING_BYTES, compressText, + type CompressTextKind, type CompressTextResult, } from "yt-dlp-transcript-common/controller/compressText"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; @@ -78,7 +79,7 @@ const sleep = (ms: number, signal?: AbortSignal) => export async function compressTextJobAction( slug: string, - opts: { limit?: number; verify?: boolean; restore?: boolean } = {}, + opts: { limit?: number; verify?: boolean; restore?: boolean; kinds?: CompressTextKind[] } = {}, ): Promise<StreamActionResult> { const paths = getPaths(); return runManagedFunction({ @@ -93,6 +94,7 @@ export async function compressTextJobAction( ...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.verify ? { verify: true } : {}), ...(opts.restore ? { restore: true } : {}), + ...(opts.kinds?.length ? { kinds: opts.kinds } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -102,6 +104,7 @@ export async function compressTextJobAction( ...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.verify ? { verify: true } : {}), ...(opts.restore ? { restore: true } : {}), + ...(opts.kinds?.length ? { kinds: opts.kinds } : {}), onLog, signal, drainSignal: ctx.drainSignal, @@ -124,6 +127,8 @@ export async function compressTextJobAction( // check, or to restore). export async function compressTextAction(input: { slugs?: string[]; + // Default: the live chat alone (controller/compressText.ts). + kinds?: CompressTextKind[]; dryRun?: boolean; verify?: boolean; restore?: boolean; @@ -137,7 +142,14 @@ export async function compressTextAction(input: { 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: () => {} }); + const plan = await compressText({ + paths, + slugs, + dryRun: true, + ...(input.restore ? { restore: true } : {}), + ...(input.kinds?.length ? { kinds: input.kinds } : {}), + onLog: () => {}, + }); if (input.dryRun) return { ok: true, dryRun: true, result: plan }; const jobs: { slug: string; jobId: string }[] = []; const skipped: { slug: string; reason: string }[] = []; @@ -152,6 +164,7 @@ export async function compressTextAction(input: { ...(input.limit !== undefined ? { limit: input.limit } : {}), ...(input.verify ? { verify: true } : {}), ...(input.restore ? { restore: true } : {}), + ...(input.kinds?.length ? { kinds: input.kinds } : {}), }); if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId }); else skipped.push({ slug: line.slug, reason: r.error }); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -51,6 +51,11 @@ export const E2E_SERVER_ENV: Record<string, string> = { // gets exactly that (pacing.spec, x-session.spec). E2E_JOB_GAP_SECONDS: "0", E2E_X_MAX_COOKIE_AGE_MINUTES: "0", + // X's SITTINGS (common/lib/xSitting.ts) are off on the test server: its fake + // X jobs run many to one corpus with no cookie refresh between them, and of + // both kinds. X's job cap (6 an hour) is NOT off. Honoured only beside + // E2E_TEST_ROUTES=1 (common/jobs/networkGuard.ts e2eSittingsOff). + E2E_X_SITTINGS: "off", E2E_LIVE_CHECK: "skip", WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), ARCHILYZER_BRANCH: "main", diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -19,16 +19,35 @@ export async function register() { // its transitive imports (runTick -> server actions, lmdb, fs) are Node-only, // so guard the import — and run nothing on Edge. if (process.env.NEXT_RUNTIME !== "nodejs") return; - // WHAT EVERY CHILD INHERITS (lane network-exits, review 2): before anything - // can spawn, NETWORK_EXIT_* credentials leave process.env and, once a - // network policy exists, no child inherits a proxy variable - // (common/lib/childEnvGuard.mjs; lib/childEnvGuard.gate.test.ts). + // WHAT EVERY CHILD INHERITS (lane network-exits, reviews 2-3): before + // anything can spawn, NETWORK_EXIT_* credentials leave process.env and, once + // a network policy exists, no child inherits a proxy variable + // (common/lib/childEnvGuard.mjs; lib/childEnvGuard.gate.test.ts). The policy + // is read from the editor's own settings file. A guard that does not install + // is no boot: the editor refuses to start rather than run unguarded. try { const { setNetworkPolicySettingsFile } = await import("yt-dlp-transcript-common/lib/childEnvGuard.mjs"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); setNetworkPolicySettingsFile(getPaths().settingsFile); } catch (e) { - console.error(`editor: the child environment guard failed to install: ${e instanceof Error ? e.message : String(e)}`); + console.error( + `editor refuses to start: the child environment guard (common/lib/childEnvGuard.mjs) did not install — ${ + e instanceof Error ? e.message : String(e) + }`, + ); + process.exit(1); + } + // STORED TEXT NEEDS node:zlib zstd (common/lib/zstdSupport.mjs): on an older + // Node every caption or chat stored as `.zst` would read as unreadable — the + // index would drop its text, a lane would schedule work for it. The editor + // refuses to start instead of running degraded (REVIEW-1 F3, captions lane). + { + const { zstdSupportProblem } = await import("yt-dlp-transcript-common/lib/zstdSupport.mjs"); + const problem = zstdSupportProblem(); + if (problem) { + console.error(`editor refuses to start: ${problem}`); + process.exit(1); + } } // ARCHILYZER_NO_NETWORK (common/lib/noNetwork.mjs) is the test harness's switch. A server booted with it reaches // no site at all, so it is said first and loudly: set by accident in a service unit, it must not pass for a diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -41,6 +41,11 @@ import { currentSlot } from "./e2e/testPaths"; // E2E_X_MAX_COOKIE_AGE_MINUTES cookie-age limit are off on the test server // (common/jobs/queueGap.ts, networkGuard.ts); a // value a spec writes into settings.json applies +// (X's drawn gap excepted: E2E_JOB_GAP_SECONDS +// collapses its range) +// E2E_X_SITTINGS off: X's sittings (jobs per cookie refresh, one +// kind each) are off on the test server, beside +// E2E_TEST_ROUTES=1 only (networkGuard.ts) // E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -126,6 +126,8 @@ // pnpm ops lane --json '{"lane":"publish","action":"drain"}' // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}' +// pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait +// pnpm ops marks-backfill --json '{"slug":"x"}' // pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}' // pnpm ops get job <jobId> --tail 20 // pnpm ops get jobs --failed --slug x @@ -155,6 +157,9 @@ // pnpm ops get tags eva-collab // pnpm ops get services // pnpm ops get x-session +// pnpm ops x-session --json '{"accountState":"suspended","note":"read-only since the 21st"}' +// pnpm ops x-session --json '{"accountState":"ok"}' +// pnpm ops x-session --json '{"clearStop":true,"confirm":true,"note":"checked by hand"}' // pnpm ops get cookies [fresh] // pnpm ops recheck-service --json '{"service":"rumble"}' // pnpm ops recheck-service --json '{"service":"x"}' @@ -338,6 +343,8 @@ const GETTERS = { // rolled back past compaction would mistreat), and drops in flight. "kept-originals": (slug) => slug ? `/api/ops/kept-originals?slug=${encodeURIComponent(slug)}` : "/api/ops/kept-originals", + // A channel's do-not-clean marks: who set each one and when. + marks: (slug) => `/api/ops/marks?slug=${encodeURIComponent(slug)}`, // Every site: id, title, siteUrl, Pages project, audience, policy, channels. sites: () => "/api/ops/sites", // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's, @@ -720,6 +727,10 @@ const ACTIONS = [ // stopped re-run once it is OK again ({service}). "recheck-service", "dismiss-service", + // The X account's state as the operator marks it ({accountState: + // "suspended" | "ok", note?}): suspended refuses the X jobs that record + // deleted posts (common/social/xAccountState.ts). `get x-session` reads it. + "x-session", "rerun-service-jobs", "workers", "transcribe-one", @@ -727,6 +738,10 @@ const ACTIONS = [ "do-not-clean", "drop-saved-alternate", "cleanup", + // Relabel a channel's old do-not-clean marks as set by the availability + // check, inferred, where its records prove it ({slug, dryRun?: true}). + // Synchronous; a dry run unless "dryRun": false. + "marks-backfill", // The Cleanup stage's "Diarize speakers" for one channel: diarization and // voice fingerprints for the videos still holding audio. "diarize", @@ -1421,6 +1436,7 @@ export function usage() { " pnpm ops get saved-alternates [<slug>]", " pnpm ops get compaction-review [<slug>]", " pnpm ops get kept-originals [<slug>]", + " pnpm ops get marks <slug>", " pnpm ops get services", " pnpm ops get x-session [<slug>]", " pnpm ops get cookies [fresh]", @@ -1494,6 +1510,11 @@ export function usage() { " availability and why, the original's entry, sizes, checks, the re-check,", ' "watch" (both files and an smplayer command that plays them) and any', ' "leftover" of an interrupted drop.', + "get marks <slug> lists the channel's do-not-clean marks and who set each", + ' one and when, as the video page says it ("setBy": "availability check,', + ' 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live', + ' recording, …"), with "mine" and "sourceGone" (the marks Clean without', + ' checking\'s opt-in can reach). `do-not-clean {"keep": true}` makes one yours.', "get kept-originals [<slug>] lists every saved video that keeps an original", ' ("keptAs": "original") or a former original ("former-original") beside', " its active copy, or has a drop in flight (pendingDrops: a file the pointer", @@ -1523,15 +1544,27 @@ export function usage() { " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,", " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes", " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,", - " allowed, and reason (the refusal an X job would get); and X's JOB CAP:", - " cap {lastHour, perHour: 12, lastDay, perDay: 150, reached, nextAt?} -", - " at most 12 X jobs start in any 60 minutes and 150 in any 24 hours ON", + " allowed, reason (the refusal an X job would get) and refusedBy (alert,", + " jar, cap, sitting, cooldown or suspended); X's JOB CAP:", + " cap {lastHour, perHour: 6, lastDay, perDay: 150, reached, nextAt?} -", + " at most 6 X jobs start in any 60 minutes and 150 in any 24 hours ON", " THIS MACHINE: one count over every kind of X job, whatever the login", " source, cookie spec or channel. A job past it is refused when queued,", " with the time the next may start; one that meets it when its queue", - " starts it ends done, deferred (not failed). A library's media-only", - " capture is not counted. The numbers are constants of the code", + " starts it ends done, deferred (not failed). Every X job counts, a", + " library's media-only capture too. The numbers are constants of the code", " (common/lib/xJobRule.ts): no setting, option or queue raises them.", + " X's SITTING: sitting {began, kind, used, left, limit} - a cookie", + " refresh begins a sitting of at most social.x.sittingJobs X job starts", + " (default 4, 1-6 in the code), of ONE kind fixed by its first job:", + " timelines (account fetches, captures, availability checks, an import)", + " or browse (trending reads, X search walks, a library's captures). A", + " start past it, or of the other kind, is refused (at its start: done,", + " deferred); a new Refresh on /cookies starts the next. account {state,", + " since?, note?, alert?} is the operator's mark (x-session, below);", + " cooldown {until} is X's 15-minute stop after a rate limit or a bot check", + " met by any reader (gallery-dl, yt-dlp, the profile's pages), which", + " refuses every X job and Refresh/Connect.", " <slug> names a", " channel whose own cookiesFromBrowser may decide the source. Nothing is", " asked of X: a refresh is Refresh cookies / Connect X account on", @@ -1802,6 +1835,18 @@ export function usage() { ' Asked while a recheck or another press for the service runs (a click,', ' the dashboard\'s, the timer\'s): refused, 409 {busy: true}, never queued.', 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.', + 'x-session marks the X account\'s state by hand: {"accountState":', + ' "suspended" | "ok", "note"?}. While it is suspended, check-post-', + " availability and capture-posts with screenshots on X (the jobs that", + " record a post as deleted or unavailable) are refused, because a", + " suspended account's answers are thinned; every other X job logs it.", + " get x-session and /cookies show it as the account's alert. Nothing is", + " asked of X. Answers {account: {state, note?, at, by}}.", + ' {"clearStop": true, "confirm": true, "note"?} is "Clear the X stop": the', + " one way X's 15-minute stop after a rate limit or a bot check ends early", + " (a clean answer or clear-platform-hold never ends it). Without", + ' "confirm" it clears nothing and answers 409 with what it risks; each', + " clear is logged in .jobs/x-stop-cleared.jsonl.", 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', "", @@ -1851,7 +1896,23 @@ export function usage() { ' 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.)', + ' "keep"?: true, "note"?}; "keep": false removes it. (keep-videos is the', + ' bulk form.) On a mark another writer set (the availability check, an', + ' import, a live recording) "keep": true MAKES IT YOURS (the video page\'s', + ' "Make it mine"): {outcome: "taken-over"}; a "note" is written on it, and', + ' on a mark already yours. keep-videos takes such marks over too.', + "", + 'marks-backfill relabels a channel\'s old do-not-clean marks (no "by") as', + ' set by the availability check, "inferred": true, only where the records', + ' prove it: availability.json says a check found the video gone within a', + ' minute of the mark, and a clean job of the channel running then names', + ' the pin in its log. Never from the note. {"slug", "dryRun"?: true} — a', + ' dry run unless "dryRun": false; answers {marks, labelled, relabelled:', + ' [{id, setAt, evidence}], notProven: [{id, setAt, reason}],', + ' oldestCleanJobAt}. The proof is one-sided: observed by the check, then', + ' pinned within the minute, inside the job\'s run. {"slug", "undo": true,', + ' "dryRun"?: true} returns every INFERRED label to unlabelled (the', + ' operator\'s): {unlabelled: [{id, setAt, evidence}], changedSince}.', "", 'drop-saved-alternate deletes one saved alternate of one video, as its', ' "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}.', @@ -1891,6 +1952,16 @@ export function usage() { ' videos\' audio. It never touches a saved video. With the channel\'s', ' cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked', ' with no count (so do job retry and retry-failed of a clean).', + ' "includeSourceGone": true (with "unchecked" only; off by default, never', + ' implied by the channel key, never replayed) also removes the audio of', + ' videos kept ONLY because the source was gone: a mark by the', + ' availability check (inferred ones included) that nothing else holds.', + ' The plan counts that group apart, {plan: {sourceGone: {ids, videos,', + ' files, bytes, inferred: {ids, videos, files, bytes}}}}; the marks stay', + ' and record the removal. A mark a person, an import or a live recording', + ' set, or one from before marks said who set them, is never reached.', + ' The reply and the job\'s log state that group\'s counts; "expectSourceGone":', + ' <the dry run\'s plan.sourceGone.videos> refuses (409) a count that changed.', ' A checked clean the source rate-limits ends deferred and schedules a', ' retry off the queue after at least 15 min (twice at most), then gives', ' up; `job cancel <the deferred job id>` cancels the retry.', @@ -2570,36 +2641,45 @@ 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', + 'compress-text stores big text files compressed (zstd, level 9): the raw', + " live-chat replays (transcript.live_chat.json -> .zst, kind live-chat,", + ' the default) and the caption tracks (every', + ' transcript.<lang>.vtt -> .zst, on the corpus disk: "kinds": ["captions"],', + " only when named). Read back by every reader as the same file, with the", + " same times (the index sees no change): {\"slugs\"?: [...], \"kinds\"?:", + ' ["live-chat", "captions"], "dryRun"?, "limit"?, "verify"?, "restore"?}.', + " A caption's dry run also counts the en / en-orig pairs of equal size", + " (compressed each as it is, never deduped). 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, both kept and", + " listed once (recorded per channel; not visited again until a form", + " changes): nothing removes a stored copy because a different one arrived.", + " 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 and kind the files, their bytes, the', + " stored ones, the estimate after (about 5 % for a chat, 20 % for a", + " caption: estimates) 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);", + ' "restore": true is the rollback: every stored file of the kinds 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).", + " read a stored chat or caption (OPERATING.md).", "", 'compaction-markers lists the "being compacted" markers (.compacting.json),', ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale', @@ -3362,8 +3442,18 @@ export function usage() { 'copies-scan pairs a source group\'s channels video by video: {"group",', ' "dryRun"?} -> {jobId}. The group is settings.sourceGroups\' (an ordered', " list of channels holding the same recordings, the preferred source first;", - " pnpm ops settings sets it). Two videos are candidates when their recorded", - " dates are at most dateWindowDays apart. Where both have a cue file their", + " pnpm ops settings sets it). Two videos are candidates when their dates", + " are at most dateWindowDays apart. A video is dated by the best evidence", + " it has: its channel's recordedDate rule, else a live stream's own day,", + " else (no rule set) a date the channel's titles carry in a shape the scan", + " recognises, else its upload day. On a channel with no rule, a video with", + " only an upload day (on a re-upload channel, the copy's day) or none, and", + " no candidate by date, is looked for by runtime instead: its 8 nearest", + " agreeing runtimes on the other channels, at most 2,000 such pairs a", + " scan, decided by their words", + " only (no words, no pair). The result's advice says what the scan could", + " not date well, with the exact channel-config patch that sets a", + " channel's rule. Where both have a cue file their", " words decide, probed both ways (40 phrases each way, each counted once):", " each copy holding at least 75 % of the other AND runtimes within the", " group's tolerance is confirmed; one inside the other, or the words the", @@ -3379,7 +3469,7 @@ export function usage() { " reported only (get copies says each one's reason). Cancelling the job", " stops it with nothing written; dryRun writes nothing. The log ends with", " @@copies-scan {group, dryRun, unchanged, file?, channels, missing?,", - " totals}.", + " totals, dating, advice?}.", "", 'copies-release releases copies to their lanes: {"group", "video":', ' "<channel>/<dir>" | "videos": [...], "undo"?, "note"?, "by"?} ->', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -939,6 +939,7 @@ test("the archival writes are POSTs to their routes, each named in the usage", ( "do-not-clean", "drop-saved-alternate", "cleanup", + "marks-backfill", ]) { const p = parseArgs([action, "--json", "{}"]); assert.equal(p.method, "POST", action); @@ -949,6 +950,9 @@ test("the archival writes are POSTs to their routes, each named in the usage", ( assert.equal(parseArgs(["get", "settings"]).method, "GET"); assert.match(usage(), /"dryRun": true answers each channel's preview/); assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/); + // Lane mark-provenance: the opt-in and the backfill are named with their limits. + assert.match(usage(), /"includeSourceGone": true \(with "unchecked" only; off by default, never/); + assert.match(usage(), /dry run unless "dryRun": false/); }); // COOKIE REFRESH ALERTS: the read side and the banner's three buttons. @@ -984,6 +988,18 @@ test("get x-session is a GET on its route, with an optional channel", () => { assert.equal(parseArgs(["get", "x-session", "some-x"]).path, "/api/ops/x-session?slug=some-x"); assert.match(usage(), /pnpm ops get x-session \[<slug>\]/); assert.match(usage(), /maxAgeMinutes/); + assert.match(usage(), /perHour: 6/); + assert.match(usage(), /sitting \{began, kind, used, left, limit\}/); +}); + +// LANE X-SITTINGS: the operator marks the X account suspended (or ok) by hand. +test("x-session (no get) is a POST that marks the X account's state", () => { + const p = parseArgs(["x-session", "--json", '{"accountState":"suspended","note":"read-only"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/x-session"); + assert.deepEqual(p.body, { accountState: "suspended", note: "read-only" }); + assert.equal(parseArgs(["get", "x-session"]).method, "GET"); + assert.match(usage(), /x-session marks the X account's state by hand/); }); // RELEASE 36 LANE A: the clip finder's chain and one video's chat replay. diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -151,6 +151,7 @@ import process from "node:process"; // What every child inherits (lane network-exits): installed before anything // can spawn (common/lib/childEnvGuard.mjs). import "../../common/lib/childEnvGuard.mjs"; +import { zstdSupportProblem } from "yt-dlp-transcript-common/lib/zstdSupport.mjs"; import { PROJECT_KINDS, REPORTS_ROOT, @@ -205,6 +206,15 @@ import { outDirState, } from "../lib/report/storage.mjs"; +// It reads the corpus, where captions and chats may be stored as `.zst`: on a +// Node without zstd it refuses to start (common/lib/zstdSupport.mjs). +{ + const zstd = zstdSupportProblem(); + if (zstd) { + console.error(`umtool refuses to start: ${zstd}`); + process.exit(1); + } +} const argv = process.argv.slice(2); const cmd = argv.find((a) => !a.startsWith("-")) ?? "help"; const rest = argv.filter((a) => a !== cmd); @@ -1224,8 +1234,15 @@ async function cmdWindow() { try { const { updateTakeClip } = await import("../lib/report/takeEdit.mjs"); const res = await updateTakeClip(p.dir, take, clipId, patch); - if (json) return out({ ok: true, take, ...res }); + // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs). + const atEnd = await (async () => { + const { recordingEndOf } = await import("../lib/report/recordingEndNote.mjs"); + const { resolveTakeManifest } = await import("../lib/report/takeManifest.mjs"); + return recordingEndOf(p, (await resolveTakeManifest(p.dir, take)).manifest, res.entry).catch(() => null); + })(); + if (json) return out({ ok: true, take, ...res, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }); console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`); + if (atEnd) console.log((await import("../lib/report/recordingEndNote.mjs")).recordingEndLine(atEnd)); if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`); if (gapsText(res.entry)) console.log(` gaps: ${gapsText(res.entry)}`); if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${reviewWords(res.entry)}`); @@ -1244,10 +1261,14 @@ async function cmdWindow() { // routes use: on a generated manifest the change is also an `edit` note // for the agent that generates it, or the next rebuild undoes it silently. const { result: res, editNotes } = await withEditNotes(p, () => updateClip(p.dir, clipId, patch)); - if (json) return out({ ok: true, ...res, editNotes }); + // The last clip's pad past a whole saved recording's end: said, nothing to change (lib/report/recordingEndNote.mjs). + const { recordingEndOf, recordingEndLine } = await import("../lib/report/recordingEndNote.mjs"); + const atEnd = await (async () => recordingEndOf(p, await (await import("../lib/projects/report.mjs")).readManifest(p.dir), res.entry))().catch(() => null); + if (json) return out({ ok: true, ...res, editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }); console.log( `${clipId}: ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`, ); + if (atEnd) console.log(recordingEndLine(atEnd)); if (res.entry.cutStart != null) { console.log( ` cut: ${res.entry.cutStart}–${res.entry.cutEnd} ` + diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -50,6 +50,12 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +**A clip at the end of its recording.** A clip's `end` may run to the end of a saved recording known whole. Its +fetch pad past that end is not a reason to shorten it. The editor cuts the window from the saved video, clamped at +the end. `umtool window` / `timeline insert` print `at the recording's end: …`, `umtool fetch <p> --dry-run` prints +`at end <clip>: saved-video, clamped at the recording's end`, and the render holds the end at the recording's last +second. There is no knob: it is the rule in OPERATING.md, "Prepare and export reports". + ## The cite follows the edge A clip's `cite` is the second the clock prints and its `citeUrl`'s `t=` the second the QR opens; both diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -3161,6 +3161,25 @@ cannot resolve); **Start** queues one paced job per platform and the panel follows them to their end, naming each window a job failed. Every run is recorded in `fetch-runs.json` beside the manifest. +THE LAST CLIP OF A RECORDING (lane window-end). A clip whose cut ends in the +last seconds of a saved recording asks for a window that ends past it, because +of the pad. When the recording is known whole (its record's duration, else a +landed live recording's, within 2 s of the container), the editor cuts that +window from the saved video, clamped at the end. Nothing is fetched. The dry +run prints `at end <clip>: saved-video, clamped at the recording's end (asked +to X, cut to Y) — why`, and `umtool window` / `timeline insert` print an +`at the recording's end:` line. + +The build, cut points and every lookup read the clamped window (or the whole +container) as ending the recording, while its clamp still matches the saved +video and the recording's known length. A gap-joined clip's last piece stops +at the end too. A montage phrase cut at the very end is not yet held there. Silence detection stops at the end, and +the clip's end is held at the file's last second: it never snaps past it, and +nothing is padded with black or silence. A clip whose own end is past the +recording's plays to the end, with a note. So keep a last clip's whole ending; +shortening it loses seconds that are on disk. The rule and its limits are in +OPERATING.md, "Prepare and export reports". + TALLER WINDOWS ARE OPT-IN per project: `umtool look <p> tallWindows=true` ([knobs.md](knobs.md#taller-windows-rendertallwindows)). Without it nothing here changes: no `maxHeight` in the body, no height probe, no taller window read. With it the body carries `maxHeight`, the manifest's `render.maxHeightSource`, and the editor keeps a taller window beside the 720 diff --git a/umtool/lib/ingredients/stages.mjs b/umtool/lib/ingredients/stages.mjs @@ -27,6 +27,7 @@ import { describeClock } from "yt-dlp-transcript-common/lib/recordingClock.mjs"; import { readRecordingClock } from "yt-dlp-transcript-common/lib/recordingClock-read.mjs"; import { audioFilesOf, present, readSavedVideoPointer, WIN_EPS } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; import { readChannelPlatform, recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { archiveMomentUrl } from "umtool-report-to-video/site-links"; import { readLog } from "../research/log.mjs"; import { readQuoteCheck, rowIsCurrent } from "../report/quoteCheck.mjs"; @@ -221,7 +222,8 @@ async function downloadedStage({ idn }) { const f = await fileState(dir, n); if (f) media.push(f); } - const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + // LOGICAL (common/lib/storedText-read.mjs): a caption stored as `.zst` is a caption. + const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n)); const problems = []; if (outcome && !outcome.status.startsWith("ok")) problems.push(`the last download ended ${outcome.status}`); if (availability && !AVAILABLE.has(availability.availability)) problems.push(`the recording reads ${availability.availability} (checked ${availability.checkedAt ?? "?"})`); @@ -276,7 +278,7 @@ async function transcribedStage({ idn }) { const outcome = to && typeof to === "object" ? { at: to.transcribedAt ?? null, worker: to.worker?.appId ?? to.worker?.id ?? null, durationMs: fin(to.durationMs) ? to.durationMs : null, salvaged: !!to.salvaged } : null; const words = await statOf(path.join(dir, "words.json")); const names = await readdir(dir).catch(() => []); - const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n)); + const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n)); const line = cues ? `${cues.source ?? "cues"}${cues.engine ?? outcome?.worker ? ` (${cues.engine ?? outcome?.worker})` : ""}${cues.coverage !== null ? `, ${Math.round(cues.coverage * 100)}% of ${hms(cues.duration)}` : ""}${outcome?.salvaged ? ", SALVAGED (gaps)" : ""}${words ? ", timed words" : ""}${pin ? ", pinned" : ""}` : vtts.length diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -202,7 +202,8 @@ async function diskSourceOf(entry, ctx) { const offset = await cached("offset", fk, async () => (await alignedClipSource(disk)).startOffset ?? 0); const fetchStart = disk.fetchStart + offset; const scan = disk.scan ? { from: Math.max(0, disk.scan.from - offset), to: disk.scan.to - offset } : null; - return { path: src.path, fk, fetchStart, scan }; + // A file ending the recording (the last clip's pad past it): where its footage stops, the build's own hold. + return { path: src.path, fk, fetchStart, scan, ...(Number.isFinite(disk.sourceEnd) ? { sourceEnd: disk.sourceEnd } : {}) }; } /** @@ -258,7 +259,7 @@ async function clipCutPoints(real, ctx) { const pieced = disk.pieced ?? null; const entry = pieced ? pieced.entry : real; const src = { path: disk.path }; - const { fk, fetchStart, scan } = disk; + const { fk, fetchStart, scan, sourceEnd } = disk; const k = snapKnobs(render); const sil = await cached( "silences", @@ -269,7 +270,7 @@ async function clipCutPoints(real, ctx) { const locked = lockedEdges(entry, render); // A clip's gaps (gaps.mjs): no edge snaps across one, as in the build. None in a montage. const clipGaps = montage ? [] : renderGaps(entry, render); - const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}) }); + const cut = renderCut({ sil, fetchStart, playFrom: pw.from, playTo: pw.to, render, locked, ...(clipGaps.length ? { gaps: clipGaps } : {}), ...(Number.isFinite(sourceEnd) ? { sourceEnd } : {}) }); const { cutA, cutB } = cut.file; let segA = cutA; let segB = cutB; diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs @@ -70,6 +70,12 @@ export function summaryLines(s) { for (const l of s.lower ?? []) { lines.push(` lower ${l.clipId}: ${l.height !== null ? `${l.height}p` : "height unknown"} (asked ${l.asked}p) in ${l.file} — ${l.why}`); } + // THE RECORDING'S END: the last clip's pad runs past a whole saved recording -- cut from it, to its end. + for (const e of s.atRecordingEnd ?? []) { + lines.push( + ` at end ${e.clipId}: saved-video, clamped at the recording's end (asked to ${e.askedTo.toFixed(2)}, cut to ${e.cutTo.toFixed(2)}) — ${e.why}`, + ); + } return lines; } diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -403,6 +403,14 @@ export function summarizeAnswer(a) { why: String(l.why ?? ""), })), ...(Number.isFinite(Number(a?.clampedFrom)) ? { clampedFrom: Number(a.clampedFrom) } : {}), + // THE RECORDING'S END (lane window-end): windows asked past the end of a + // saved recording known whole, cut from it clamped at that end. + atRecordingEnd: (a?.atRecordingEnd ?? []).map((e) => ({ + clipId: label(e.item), + askedTo: Number(e.askedTo), + cutTo: Number(e.cutTo), + why: String(e.why ?? ""), + })), jobs: (a?.jobs ?? []).map((j) => ({ platform: j.platform, queueKey: j.queueKey ?? null, jobId: j.jobId, items: Number(j.items ?? 0) })), }; } diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs @@ -322,3 +322,37 @@ test("a tall project's body carries its maxHeightSource as maxHeight; the answer assert.ok(lines.some((l) => /2160p asked; the editor's clips\.windowMaxHeight/.test(l))); assert.deepEqual(summarizeAnswer({}).lower, []); }); + +// THE RECORDING'S END (lane window-end): the editor plans the last clip's +// window on the saved-video queue, clamped at the recording's end, and the dry +// run says so in those words. +test("umtool fetch --dry-run: a window past a whole saved recording's end reads 'saved-video, clamped at the recording's end'", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-")); + try { + const dir = path.join(root, "synth-oops"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2)); + const ed = fakeEditor({ + "POST /api/ops/fetch-windows": (b) => ({ + ok: true, + dryRun: true, + groups: [{ platform: "saved-video", queueKey: "clips:saved-video", items: [b.items[1]] }], + cached: [], + inFlight: [], + unresolved: [], + atRecordingEnd: [{ item: b.items[1], askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }], + }), + }); + const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch }; + const lines = []; + assert.equal(await fetchCommand(["synth-oops", "--dry-run"], { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }), 0); + const text = lines.join("\n"); + assert.match(text, /saved-video 1 window\(s\)/); + assert.match(text, /at end {5}s02: saved-video, clamped at the recording's end \(asked to 7\.50, cut to 6\.96\) — the saved recording ends at 6\.96 s/); + const doc = await readFetchRuns(dir); + assert.deepEqual(doc.runs[0].summary.atRecordingEnd, [{ clipId: "s02", askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }]); + assert.deepEqual(summarizeAnswer({}).atRecordingEnd, []); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/recordingEndNote.mjs b/umtool/lib/report/recordingEndNote.mjs @@ -0,0 +1,73 @@ +// THE RECORDING'S END, SAID WHERE A CLIP'S EXTENT IS WRITTEN (lane window-end): +// `umtool window` and `timeline insert` say when a clip's padded fetch window +// runs past the end of a saved recording known whole -- the last clip of a +// recording, its pad past the end. Nothing has to change: the editor cuts that +// window from the saved video clamped at the end (common/lib/recordingEnd.mjs), +// `umtool fetch --dry-run` says "saved-video, clamped at the recording's end", +// and the render holds the clip's end there (snap.mjs `endAt`). So the clip +// keeps its whole ending; shortening it to dodge a network fetch loses seconds +// that are on disk. +// +// Cheap: the record's duration is read first, and a clip whose padded end is +// more than the tolerance before it costs nothing more. Only a clip near the +// end asks the disk (sources.mjs resolveLocalSource over the corpus tiers: a +// window the editor already cut clamped, else the saved container's probe). +// Never fetches, never writes. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { resolveLocalSource, ffprobeSource } from "umtool-report-to-video/sources"; +import { RECORDING_END_TOLERANCE_SECONDS } from "yt-dlp-transcript-common/lib/recordingEnd.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { channelFor, channelsDirFor, hasShadowChannels } from "../projects/report.mjs"; + +/** + * Where a clip's padded fetch window stands against the end of its saved + * recording: null when it does not reach it (or nothing says where it is), + * else the end, the window and whether the clip's own end is past it. + * + * @param {{ dir: string }} project + * @param {Record<string, any>} manifest the manifest the clip is read in (a take's, for a take) + * @param {Record<string, any>} entry + * @param {{ probe?: Function, channelsDir?: string }} [opts] + * @returns {Promise<null | { recordingEnd: number, from: number, to: number, clipEndPast: boolean, source: string }>} + */ +export async function recordingEndOf(project, manifest, entry, opts = {}) { + if (!entry || entry.type !== "clip" || entry.src || !entry.video) return null; + const start = Number(entry.start); + const end = Number(entry.end); + if (!Number.isFinite(start) || !Number.isFinite(end)) return null; + const slug = channelFor(manifest, entry); + if (!slug) return null; + const render = manifest?.render ?? {}; + const pad = Number.isFinite(Number(render.fetchPad)) ? Number(render.fetchPad) : 3; + const from = Number(Math.max(0, start - pad).toFixed(2)); + const to = Number((end + pad).toFixed(2)); + const channelsDir = opts.channelsDir ?? channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + // The record's own length first: far from the end, nothing is probed. + const videoDir = await resolveVideoDir(channelsDir, slug, String(entry.video)).catch(() => null); + if (videoDir) { + try { + const d = Number(JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8"))?.duration); + if (Number.isFinite(d) && d > 0 && to < d - RECORDING_END_TOLERANCE_SECONDS) return null; + } catch { + // No record: the disk is asked. + } + } + const hit = await resolveLocalSource( + { video: String(entry.video), slug, from, to }, + { channelsDir, probe: opts.probe ?? ffprobeSource, kinds: ["corpus-window", "saved-video"], render }, + ); + if (!hit?.endsRecording || !(hit.windowEnd < to)) return null; + const recordingEnd = Number(hit.windowEnd.toFixed(2)); + return { recordingEnd, from, to, clipEndPast: end > hit.windowEnd + 0.05, source: hit.kind }; +} + +/** The line `umtool window` / `timeline insert` print for it. Pure. */ +export function recordingEndLine(r) { + if (!r) return null; + return ( + ` at the recording's end: its fetch window ${r.from.toFixed(2)}–${r.to.toFixed(2)} runs past the saved recording's end ` + + `(${r.recordingEnd.toFixed(2)} s, known whole) — cut from the saved video, clamped there; nothing is fetched` + + (r.clipEndPast ? `. Its end is past the recording's: it plays to ${r.recordingEnd.toFixed(2)}` : "") + ); +} diff --git a/umtool/lib/report/recordingEndNote.test.mjs b/umtool/lib/report/recordingEndNote.test.mjs @@ -0,0 +1,65 @@ +// THE RECORDING'S END at window / insert time (lane window-end): a clip whose +// padded fetch window runs past a whole saved recording's end is said to be +// cut from the saved video, clamped there; a clip far from the end, or a +// partial recording, says nothing. +// +// Run with: node --test lib/report/recordingEndNote.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; +import path from "node:path"; +import os from "node:os"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { recordingEndLine, recordingEndOf } from "./recordingEndNote.mjs"; + +async function tree(meta) { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-recend-")); + const channelsDir = path.join(root, "channels"); + const videoDir = path.join(channelsDir, "synth-chan", "data", "vid1"); + const storeDir = path.join(root, "store"); + await mkdir(videoDir, { recursive: true }); + await mkdir(storeDir, { recursive: true }); + await writeFile(path.join(storeDir, "source-media.mp4"), Buffer.alloc(16, 1)); + await writeFile(path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-11-21T00:00:00Z", dir: storeDir, file: "source-media.mp4", bytes: 16 })); + if (meta) await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(meta)); + const project = { dir: path.join(root, "proj") }; + await mkdir(project.dir, { recursive: true }); + const manifest = { provenance: { channelsDir, channelSlug: "synth-chan" }, render: { fetchPad: 3 } }; + return { root, project, manifest }; +} + +const clip = (start, end) => ({ type: "clip", id: "last", video: "vid1", start, end }); +const probe = async () => ({ duration: 300.5 }); + +test("a clip ending 1 s before a whole recording's end, pad 3: said, and the line names the clamp", async () => { + const t = await tree({ id: "vid1", duration: 300 }); + try { + const r = await recordingEndOf(t.project, t.manifest, clip(290, 299.5), { probe }); + assert.deepEqual(r, { recordingEnd: 300.5, from: 287, to: 302.5, clipEndPast: false, source: "saved-video" }); + assert.match(recordingEndLine(r), /runs past the saved recording's end \(300\.50 s, known whole\) — cut from the saved video, clamped there; nothing is fetched$/); + // Its end itself past the recording's: it plays to the end. + const past = await recordingEndOf(t.project, t.manifest, clip(295, 301.5), { probe }); + assert.equal(past.clipEndPast, true); + assert.match(recordingEndLine(past), /it plays to 300\.50$/); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +test("far from the end nothing is probed; a partial recording says nothing", async () => { + const t = await tree({ id: "vid1", duration: 300 }); + try { + let probed = 0; + const counting = async () => (probed++, { duration: 300.5 }); + assert.equal(await recordingEndOf(t.project, t.manifest, clip(100, 110), { probe: counting }), null); + assert.equal(probed, 0); + } finally { + await rm(t.root, { recursive: true, force: true }); + } + const p = await tree({ id: "vid1", duration: 3600 }); + try { + assert.equal(await recordingEndOf(p.project, p.manifest, clip(290, 299.5), { probe }), null); + } finally { + await rm(p.root, { recursive: true, force: true }); + } + assert.equal(recordingEndLine(null), null); +}); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -659,6 +659,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => let result; let editNotes = null; let attribution = null; + // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs). + let atEnd = null; switch (verb) { case "insert": { const toSection = intFlag(flags, "--to-section"); @@ -722,6 +724,10 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => result = done.result; editNotes = done.editNotes; attribution = done.attribution; + { + const { recordingEndOf } = await import("./recordingEndNote.mjs"); + atEnd = await recordingEndOf(project, manifest, attribution ?? result?.entry ?? null).catch(() => null); + } if (done.attributionError) { // The clip is in; only its header failed. Say both, and how to finish. const msg = done.attributionError; @@ -937,10 +943,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } if (json) { - out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes }, null, 2)); + out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2)); return 0; } out(summaryOf(verb, result, attribution)); + if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); // What a restored clip's removal re-anchored or dropped stays as it is now: said, not undone. for (const line of result.notPutBack ?? []) out(` not put back: ${line}`); @@ -1067,13 +1074,21 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { } else { result = await edit.undoTakeEdit(project.dir, take, { token }); } + // A clip inserted at a recording's end (its pad past a whole saved recording's): said (recordingEndNote.mjs). + let atEnd = null; + if (verb === "insert" && result?.entry) { + const { recordingEndOf } = await import("./recordingEndNote.mjs"); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + atEnd = await (async () => recordingEndOf(project, (await resolveTakeManifest(project.dir, take)).manifest, result.entry))().catch(() => null); + } if (json) { - out(JSON.stringify({ ok: true, op: verb, take, ...result }, null, 2)); + out(JSON.stringify({ ok: true, op: verb, take, ...result, ...(atEnd ? { atRecordingEnd: atEnd } : {}) }, null, 2)); return 0; } if (verb === "undo") out(`take ${take}: undid ${result.op}: restored ${result.restored} (the state before the undo kept as ${result.saved})`); else { out(`take ${take}: ${summaryOf(verb, result, null)}`); + if (atEnd) out((await import("./recordingEndNote.mjs")).recordingEndLine(atEnd)); out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`); } return 0; diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -1307,6 +1307,11 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) { if (!hit) return null; // What the log calls it: a fallback is not the same fact as an audio-only clip. const kind = hit.kind === "audio" && use === "audio-fallback" ? "audio-fallback" : hit.kind; + // THE RECORDING'S END (lane window-end, sources.mjs `endsRecording`): the + // file ends the recording before the padded span does -- the last clip's pad + // runs past the end. `sourceEnd` is where its footage stops (source + // seconds): the scan stops there and the cut never passes it. + const ends = hit.endsRecording === true && hit.windowEnd < to; return { path: hit.path, fetchStart: hit.windowStart, @@ -1314,13 +1319,15 @@ export async function onDiskClipSource(entry, meta, render, local, opts = {}) { source: kind, // A whole container is hours long and silence detection decodes what it // is given: give it the span a fetch would have produced, no more. - ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: to - hit.windowStart } }), + ...(hit.kind === "raw-cache" ? {} : { scan: { from: from - hit.windowStart, to: (ends ? hit.windowEnd : to) - hit.windowStart } }), + ...(ends ? { sourceEnd: hit.windowEnd } : {}), log: { id: entry.id, video: entry.video, from, to, cached: true, source: kind, ...(hit.kind !== "raw-cache" || hit.name !== name ? { reuse: hit.name } : {}), local: hit.path, window: [hit.windowStart, hit.windowEnd], ...(hit.height ? { height: hit.height } : {}), + ...(ends ? { atRecordingEnd: true } : {}), }, }; } @@ -1476,6 +1483,16 @@ export async function piecedClipSource(entry, meta, render, local, opts, outDir) if (await onDiskClipSource(entry, meta, render, local, opts)) return null; const parts = []; for (const span of spans) parts.push({ span, ...(await fetchClipAligned(entry, meta, render, local, { ...opts, span })) }); + // THE RECORDING'S END (lane window-end): the last piece's source ends the + // recording before its span does (its pad past the end): the piece is held + // to where its footage stops, so the joined file carries no frozen frame or + // silence past it, and the cut stops there too (`sourceEnd` on the pieces clock). + const last = parts[parts.length - 1]; + if (Number.isFinite(last.sourceEnd) && last.sourceEnd < last.span.to && last.sourceEnd > last.span.from) { + last.span = { ...last.span, to: last.sourceEnd }; + spans[spans.length - 1] = last.span; + } + const endsRecording = Number.isFinite(last.sourceEnd) && last.span.to === last.sourceEnd; const probes = await Promise.all(parts.map((p) => probeMedia(p.path))); const withPicture = probes.filter((p) => p.hasVideo).length; if (withPicture && withPicture < parts.length) { @@ -1537,7 +1554,10 @@ export async function piecedClipSource(entry, meta, render, local, opts, outDir) id: entry.id, file: path.basename(file), seconds: Number(clock.total.toFixed(2)), pieces: spans.map((s) => [Number(s.from.toFixed(2)), Number(s.to.toFixed(2))]), }); - return { path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock) }; + return { + path: file, fetchStart: 0, cached: true, source: "pieces", clock, entry: virtualEntry(entry, clock), + ...(endsRecording ? { sourceEnd: clock.total } : {}), + }; } // The silences of a file, in its own seconds (cut-points.mjs detectSilence, @@ -1579,7 +1599,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // (piecedClipSource): `clipE` is the clip on that file's clock, `toReal` // maps a cut on it back to the source's. Every other clip: itself, as ever. const pieced = await piecedClipSource(entry, meta, render, dirs.local, opts, outDir); - const { path: raw, fetchStart, scan } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts)); + const { path: raw, fetchStart, scan, sourceEnd } = pieced ?? (await fetchClipAligned(entry, meta, render, dirs.local, opts)); const clipE = pieced ? pieced.entry : entry; const toReal = pieced ? pieced.clock.toReal : (t) => t; // Every file this writes in segments/ is written through a rename (the @@ -1625,9 +1645,18 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, } } - // Desired cut points, expressed relative to the over-fetched file. + // Desired cut points, expressed relative to the over-fetched file. A file + // that ENDS THE RECORDING (onDiskClipSource `sourceEnd`: the last clip, its + // pad past the end) holds the end at its last second -- never a cut past it, + // so nothing is padded with black or silence for seconds that do not exist. + const endAt = Number.isFinite(sourceEnd) ? sourceEnd - fetchStart : null; const wantA = playFrom - fetchStart; - const wantB = playTo - fetchStart; + const wantB = endAt !== null ? Math.min(playTo - fetchStart, endAt) : playTo - fetchStart; + if (endAt !== null && playTo - fetchStart > endAt + 0.05) { + EMIT("note", { + message: `${entry.id}: its end ${toReal(playTo).toFixed(2)} is past the recording's end ${toReal(sourceEnd).toFixed(2)} — it plays to the end`, + }); + } const win = render.snapWindow ?? 1.6; const sil = await detectSilence(raw, render, scan); @@ -1654,6 +1683,7 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, // and no edge snaps across a gap (a gap's edges are exact). const snapped = mont ? null : snapCut({ sil, wantA, wantB, render, locked: lockedEdges(clipE, render), + ...(endAt !== null ? { endAt } : {}), ...(clipGaps.length ? { gaps: clipGaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), }); const a = mont ? mont.win.start : snapped.a; diff --git a/umtool/report-to-video/clip-words.mjs b/umtool/report-to-video/clip-words.mjs @@ -21,6 +21,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { hasLocalMedia } from "./local-media.mjs"; import { whisperWords } from "./montage.mjs"; @@ -105,7 +106,8 @@ export async function clipWords(entry, provenance, from, to, { channelsDir }) { const cues = await json("transcript.cues.json"); const names = [...new Set([typeof cues?.vttFile === "string" ? path.basename(cues.vttFile) : null, "transcript.en-orig.vtt", "transcript.en.vtt"].filter(Boolean))]; for (const name of names) { - const text = await readFile(path.join(dir, name), "utf8").catch(() => null); + // Either form (common/lib/storedText-read.mjs): a stored caption is read. + const text = await readStoredText(dir, name, "utf8").catch(() => null); if (!text) continue; const words = vttWordStarts(text).filter(inSpan); if (words.length) return { words, timed: false, from: "captions" }; diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -64,6 +64,7 @@ import os from "node:os"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { readdirLogical, readStoredTextHead, storedTextLogicalSize } from "yt-dlp-transcript-common/lib/storedText-read.mjs"; import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs"; // For the other readers of an archive that come through this module (linkCheck.mjs). @@ -165,19 +166,23 @@ async function staleCaptionRecord(videoDir, record) { if (record?.source !== "vtt" || record.captionTrackRule === CAPTION_TRACK_RULE_VERSION) { return false; } - const entries = await readdir(videoDir).catch(() => []); + // LOGICAL (common/lib/storedText-read.mjs): a caption stored as + // `transcript.en.vtt.zst` is a track under its plain name; its head is read + // DECODED and its size is the LOGICAL one (the frame header's) — the raw + // bytes of a stored track would sniff and size as something else. + const entries = await readdirLogical(videoDir); const english = entries.filter((e) => ENGLISH_VTT_RE.test(e)); if (!Array.isArray(record.cues) || record.cues.length === 0) { if (english.length !== 1) return true; - const head = (await readFile(path.join(videoDir, english[0]), "utf8").catch(() => "")).slice(0, 2048); + const head = (await readStoredTextHead(videoDir, english[0], 2048).catch(() => Buffer.alloc(0))).toString("utf8"); return !/<\d{2}:\d{2}:\d{2}\.\d{3}>/.test(head); } if (!entries.includes("transcript.en.vtt") || !entries.includes("transcript.en-orig.vtt")) return false; const [en, orig] = await Promise.all([ - stat(path.join(videoDir, "transcript.en.vtt")), - stat(path.join(videoDir, "transcript.en-orig.vtt")), + storedTextLogicalSize(videoDir, "transcript.en.vtt"), + storedTextLogicalSize(videoDir, "transcript.en-orig.vtt"), ]); - return en.size !== orig.size; + return en !== orig; } export class CueLookupError extends Error { diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -10,6 +10,7 @@ import test from "node:test"; import { mkdtemp, mkdir, symlink, writeFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; +import { zstdCompressSync } from "node:zlib"; import { CAPTION_TRACK_RULE_VERSION, @@ -278,6 +279,46 @@ test("a local caption record from before the caption-track rule is refused where } }); +// --- the same, over captions STORED COMPRESSED (lane text-compress-captions) -- +// A track may be `transcript.<lang>.vtt.zst` (common/lib/storedText.ts): one +// zstd frame with its content size. The rule's listing, head and sizes must be +// the LOGICAL ones — on the raw listing a stored en reads as absent, and an +// unversioned record beside an en / en-orig that DIFFER would be cut from. + +const stored = (text) => zstdCompressSync(Buffer.from(text, "utf8")); + +test("over stored captions: a differing pair is still refused, an identical pair and a lone word-timed track are read", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "cues-stored-")); + try { + const vdir = path.join(dir, "chan", "data", "vid1"); + await mkdir(vdir, { recursive: true }); + await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nserved words\n")); + await writeFile(path.join(vdir, "transcript.en-orig.vtt"), "WEBVTT\n\nwhat was said\n"); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ ...RECORD, source: "vtt" })); + const src = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, fetchImpl: stubFetch(ROUTES) }); + await assert.rejects(src.load("chan", "vid1"), /older caption-track rule/); + + // Both stored, byte-identical: equal LOGICAL sizes — read as usual. + await rm(path.join(vdir, "transcript.en-orig.vtt")); + await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nwhat was said\n")); + await writeFile(path.join(vdir, "transcript.en-orig.vtt.zst"), stored("WEBVTT\n\nwhat was said\n")); + assert.equal((await src.load("chan", "vid1")).from, "local"); + + // A zero-cue record beside ONE stored track with word timing: genuinely + // empty, read from the DECODED head. + const lone = path.join(dir, "chan", "data", "vid2"); + await mkdir(lone, { recursive: true }); + await writeFile( + path.join(lone, "transcript.en.vtt.zst"), + stored("WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nword<00:00:01.000><c> timed</c>\n"), + ); + await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ ...RECORD, id: "vid2", source: "vtt", cues: [] })); + assert.equal((await src.load("chan", "vid2")).from, "local"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + test("a lone-track caption record with cues needs no rule to be read", async () => { const dir = await mkdtemp(path.join(tmpdir(), "cues-rule-")); try { diff --git a/umtool/report-to-video/snap.mjs b/umtool/report-to-video/snap.mjs @@ -86,7 +86,8 @@ export const GAP_KEEP = GAP_LIMITS.keep; * desired end, the end at least a second after the start. * * @param {{ sil: Array<{ s: number, e: number }>, wantA: number, wantB: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null, + * endAt?: number | null }} o * `wantA`/`wantB`: the play window's edges in the file's seconds; `locked`: * which of them are the author's, exact (mute.mjs lockedEdges) -- each * snapped only outward, inside its own silence; `gaps`: the clip's gaps @@ -94,10 +95,17 @@ export const GAP_KEEP = GAP_LIMITS.keep; * edge snaps across one (nor nearer it than GAP_KEEP): such a snap is not * taken and the edge stays where it was asked */ -export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = null }) { +export function snapCut({ sil, wantA, wantB: asked, render = {}, locked = null, gaps = null, endAt = null }) { const win = render.snapWindow ?? SNAP_DEFAULTS.snapWindow; + // THE RECORDING'S END (lane window-end): a file that ends the recording + // (`endAt`, its last second on the file's clock) is never cut past it -- the + // end is held there and does not snap beyond it, so nothing is padded with + // black or silence for seconds that do not exist. + const end = Number.isFinite(endAt) ? Number(endAt) : Infinity; + const wantB = Math.min(asked, end); let a = snap(wantA, sil, "start", win, render, { pinned: !!locked?.start }); let b = snap(wantB, sil, "end", win, render, { pinned: !!locked?.end }); + if (b.at > end) b = { at: end, snapped: false }; if (gaps?.length) { const first = gaps.reduce((m, g) => Math.min(m, g.from), Infinity); const last = gaps.reduce((m, g) => Math.max(m, g.to), -Infinity); @@ -105,7 +113,7 @@ export function snapCut({ sil, wantA, wantB, render = {}, locked = null, gaps = if (b.at < wantB && b.at < last + GAP_KEEP) b = { at: wantB, snapped: false }; } const cutA = Math.min(a.at, wantB - 1); - const cutB = Math.max(b.at, cutA + 1); + const cutB = Math.min(Math.max(b.at, cutA + 1), Math.max(end, cutA)); return { win, a, b, cutA, cutB }; } @@ -117,14 +125,18 @@ export const recordSecond = (fetchStart, t) => Number((fetchStart + t).toFixed(3 * file it is cut from: what `<id>.cut.json` records (`start`, `end`, * `snapped`) for a clip with no room and no montage. `playFrom`/`playTo` are * the play window (deck.mjs playWindow); `fetchStart` the file's first - * second in the recording; `gaps` the clip's (gaps.mjs), source seconds. + * second in the recording; `gaps` the clip's (gaps.mjs), source seconds; + * `sourceEnd` the source second the file's footage ends at when it ends the + * recording (onDiskClipSource) -- the cut never passes it. * * @param {{ sil: Array<{ s: number, e: number }>, fetchStart: number, playFrom: number, playTo: number, render?: Record<string, any>, - * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null }} o + * locked?: { start?: boolean, end?: boolean } | null, gaps?: Array<{ from: number, to: number }> | null, + * sourceEnd?: number | null }} o */ -export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null }) { +export function renderCut({ sil, fetchStart, playFrom, playTo, render = {}, locked = null, gaps = null, sourceEnd = null }) { const c = snapCut({ sil, wantA: playFrom - fetchStart, wantB: playTo - fetchStart, render, locked, + ...(Number.isFinite(sourceEnd) ? { endAt: Number(sourceEnd) - fetchStart } : {}), ...(gaps?.length ? { gaps: gaps.map((g) => ({ from: g.from - fetchStart, to: g.to - fetchStart })) } : {}), }); return { diff --git a/umtool/report-to-video/snap.test.mjs b/umtool/report-to-video/snap.test.mjs @@ -22,3 +22,22 @@ test("snap: snapTail / snapLead keep more of the pause, never more than it holds assert.equal(Number(snap(20, SIL, "end", 1, render).at.toFixed(3)), 20.12); assert.equal(snap(20.1, SIL, "start", 1, render).at, 20); }); + +// THE RECORDING'S END (lane window-end): a file that ends the recording holds +// the cut's end at its last second -- never snapped or cut past it. +test("snapCut / renderCut: a file ending the recording holds the end at its last second", async () => { + const { snapCut, renderCut } = await import("./snap.mjs"); + // The file's last second is 9.5; a pause at 9.4-9.9 would snap the end past it. + const sil = [{ s: 9.4, e: 9.9 }]; + const free = snapCut({ sil, wantA: 3, wantB: 9.45, render: {} }); + assert.ok(free.cutB > 9.5, `without the end the snap goes to ${free.cutB}`); + const held = snapCut({ sil, wantA: 3, wantB: 9.45, render: {}, endAt: 9.5 }); + assert.ok(held.cutB <= 9.5, `held at ${held.cutB}`); + // An end asked past the file's last second plays to it. + assert.equal(snapCut({ sil: [], wantA: 3, wantB: 12, render: {}, endAt: 9.5 }).cutB, 9.5); + // renderCut takes the source second: 100 + 9.5. + const cut = renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {}, sourceEnd: 109.5 }); + assert.equal(cut.end, 109.5); + // Nothing said: as before. + assert.equal(renderCut({ sil: [], fetchStart: 100, playFrom: 103, playTo: 112, render: {} }).end, 112); +}); diff --git a/umtool/report-to-video/sources.test.mjs b/umtool/report-to-video/sources.test.mjs @@ -29,6 +29,7 @@ import { findContainingWindow, localSources, needsFetchMessage, + onDiskClipSource, planLocalSources, } from "./build-video.mjs"; @@ -689,3 +690,166 @@ test("a tall ask between rungs resolves the rung's window: 900 and 1000 read .h1 await rm(t.root, { recursive: true, force: true }); } }); + +// THE RECORDING'S END (lane window-end, common/lib/recordingEnd.mjs): the last +// clip's padded span runs past a saved recording KNOWN WHOLE -- its container +// serves it, ending the recording; a span starting past the end, or a +// container shorter than its record, does not. A corpus window the editor cut +// clamped at the end (its sidecar's `clamp`) serves the same padded span. +test("the recording's end: a whole saved recording serves a padded span past its end; a partial one does not", async () => { + const t = await tree(); + try { + await touch(path.join(t.storeDir, "source-media.mp4")); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4"); + const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe }; + // The clip is 290-299.5, padded 3: 287-302.5. + const want = { video: VIDEO, slug: SLUG, from: 287, to: 302.5 }; + assert.equal(await resolveLocalSource(want, cfg), null, "no known length: a partial recording may not cover"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 301 })); + const hit = await resolveLocalSource(want, cfg); + assert.equal(hit?.kind, "saved-video"); + assert.equal(hit.windowEnd, 300.5); + assert.equal(hit.endsRecording, true); + assert.equal(await resolveLocalSource({ ...want, from: 300.6, to: 305 }, cfg), null, "a span starting past the end"); + // The record says the stream is longer than the container: not whole. + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 3600 })); + assert.equal(await resolveLocalSource(want, cfg), null); + // A span inside the container is served as ever, and says nothing about the end. + const inside = await resolveLocalSource({ ...want, from: 100, to: 110 }, cfg); + assert.equal(inside.endsRecording, undefined); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +// The editor's clamp (common/lib/clipWindow.ts): the pointer it was cut from +// and the known length it was judged by -- re-checked on every lookup. +async function clampedCorpusWindow(t) { + await touch(path.join(t.storeDir, "source-media.mp4")); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 })); + await touch(path.join(t.clipsDir, "287.00-300.49.mp4")); + await writeFile( + path.join(t.clipsDir, "287.00-300.49.json"), + JSON.stringify({ + requestedBy: "umtool", + source: "saved-video", + clamp: { askedTo: 302.5, cutTo: 300.49, recordingEnd: 300.49, why: "whole", container: { file: "source-media.mp4", bytes: 16 }, knownSeconds: 300 }, + }), + ); +} + +test("the recording's end: the editor's clamped window serves the same padded span, before the container is probed", async () => { + const t = await tree(); + try { + await clampedCorpusWindow(t); + const { probe, calls } = fakeProbe(300.5); + const hit = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe }); + assert.equal(hit?.kind, "corpus-window"); + assert.equal(hit.name, "287.00-300.49.mp4"); + assert.equal(hit.endsRecording, true); + assert.deepEqual(calls, [], "nothing probed"); + // A window with no clamp in its sidecar is no answer for the padded span. + await writeFile(path.join(t.clipsDir, "287.00-300.49.json"), JSON.stringify({ requestedBy: "umtool" })); + const miss = await resolveLocalSource({ video: VIDEO, slug: SLUG, from: 287, to: 302.5 }, { channelsDir: t.channelsDir, probe }); + assert.notEqual(miss?.kind, "corpus-window"); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +// REVIEW 1, finding 2: a clamp whose facts moved is an ordinary window again. +test("the recording's end: a clamped window whose known end moved, or whose container changed, ends nothing", async () => { + const t = await tree(); + try { + await clampedCorpusWindow(t); + const cfg = { channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe }; + const want = { video: VIDEO, slug: SLUG, from: 287, to: 302.5 }; + assert.equal((await resolveLocalSource(want, cfg))?.kind, "corpus-window"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 3600 })); + assert.equal(await resolveLocalSource(want, cfg), null, "the known end moved: neither the window nor the container"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 })); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4", { bytes: 17 }); + const other = await resolveLocalSource(want, cfg); + assert.notEqual(other?.kind, "corpus-window", "another container: the clamped window does not answer"); + // Its own seconds are still served. + assert.equal((await resolveLocalSource({ ...want, to: 299 }, cfg))?.name, "287.00-300.49.mp4"); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +test("the recording's end: the build's on-disk source stops its scan at the end and says where the footage stops", async () => { + const t = await tree(); + try { + await touch(path.join(t.storeDir, "source-media.mp4")); + await pointTo(t.videoDir, t.storeDir, "source-media.mp4"); + await writeFile(path.join(t.videoDir, "metadata.info.json"), JSON.stringify({ id: VIDEO, duration: 300 })); + const local = localSources({ rawDir: t.rawDir, channelsDir: t.channelsDir, probe: fakeProbe(300.5).probe }); + // The clip ends 1 s before the end; the pad is 3 s. + const entry = { type: "clip", id: "last", channel: SLUG, video: VIDEO, start: 290, end: 299.5 }; + const src = await onDiskClipSource(entry, null, { fetchPad: 3 }, local, {}); + assert.equal(src?.source, "saved-video"); + assert.equal(src.sourceEnd, 300.5); + assert.deepEqual(src.scan, { from: 287, to: 300.5 }); + assert.equal(src.log.atRecordingEnd, true); + // A clip well inside: no sourceEnd, the scan as ever. + const mid = await onDiskClipSource({ ...entry, start: 100, end: 110 }, null, { fetchPad: 3 }, local, {}); + assert.equal(mid.sourceEnd, undefined); + assert.deepEqual(mid.scan, { from: 97, to: 113 }); + // REVIEW 1, nit: a corpus window a hair (under WIN_EPS) short of the span is scanned to the span, as on main. + await writeFile(path.join(t.clipsDir, "196.00-220.99.mp4"), Buffer.alloc(16, 1)); + const hair = await onDiskClipSource({ ...entry, start: 199, end: 218 }, null, { fetchPad: 3 }, local, {}); + assert.equal(hair.source, "corpus-window"); + assert.deepEqual(hair.scan, { from: 0, to: 25 }); + } finally { + await rm(t.root, { recursive: true, force: true }); + } +}); + +// REVIEW 1: a gap-joined clip's LAST piece at the recording's end is held to +// where its footage stops -- no frozen frame or silence past it in the joined +// file -- and the cut stops there (`sourceEnd` on the pieces clock). +test("the recording's end: a gap-joined clip's last piece stops at the end", async () => { + const { execFileSync, spawnSync } = await import("node:child_process"); + if (!["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0)) return; + const { piecedClipSource } = await import("./build-video.mjs"); + const root = await mkdtemp(path.join(os.tmpdir(), "rtv-pieces-end-")); + try { + const mk = (file, seconds) => + execFileSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", `testsrc=size=160x90:rate=10:duration=${seconds}`, + "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", file, + ]); + const first = path.join(root, "9.00-16.00.mp4"); + const last = path.join(root, "source-media.mp4"); + mk(first, 7); + // The recording's last 10.5 s, 90–100.5: it ends the recording. + mk(last, 10.5); + const local = { + rawDir: null, + channelsDir: null, + slugOf: () => SLUG, + resolve: async (_e, span) => + span.from < 50 && span.to <= 16 + ? { kind: "corpus-window", path: first, name: "9.00-16.00.mp4", windowStart: 9, windowEnd: 16 } + : span.from < 90 + ? null + : { kind: "saved-video", path: last, name: "source-media.mp4", windowStart: 90, windowEnd: 100.5, endsRecording: true }, + }; + // 10-100 with 15-95 cut out: pieces 9-16 and 94-101, 78 s apart. The last ends past the recording's 100.5. + const entry = { type: "clip", id: "pe", channel: SLUG, video: VIDEO, start: 10, end: 100, gaps: [{ from: 15, to: 95 }] }; + const render = { fps: 10, fetchPad: 1 }; + await mkdir(path.join(root, "out", "segments"), { recursive: true }); + const r = await piecedClipSource(entry, null, render, local, {}, path.join(root, "out")); + assert.ok(r, "cut from its pieces"); + assert.deepEqual(r.clock.spans, [{ from: 9, to: 16 }, { from: 94, to: 100.5 }]); + assert.equal(r.sourceEnd, 13.5, "the end on the pieces clock: 7 + 6.5"); + const out = execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", r.path]).toString(); + assert.ok(Math.abs(Number(out) - 13.5) < 0.15, `the joined file is ${out.trim()} s, no padding past the end`); + } finally { + await rm(root, { recursive: true, force: true }); + } +});