Archilyzer · Source

archilyzer

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

commit 26bfd37795913a8b5f5d295e3188de48dcbd6421
parent 05d59163aeb3464845191007d14d0f2391b050d2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:51:37 -0500

Merge main into lane/verify-resume: pre-clean pins keep mark provenance

Conflicts:
- common/controller/verifyBeforeClean.ts, VerifyBeforeCleanOptions and the
  destructuring: kept both sides (this lane's `now`/`maxAgeHours` seams and
  main's `jobId`). Every pin the gate writes, the individual confirmation
  of suspects and of newer-evidence suspects included, goes through the
  one `pin`, which main's mark-provenance writes with by
  "availability-check", via "pre-clean-check" and the job id. No evidence
  rule changed.
- editor/CHANGELOG.md: both Unreleased entries kept (main's first).

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

Diffstat:
MCOMMANDS.md | 38+++++++++++++++++++++++++++++---------
MENVIRONMENT.md | 5+++--
MOPERATING.md | 130++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
MSETTINGS.md | 6+++++-
Mcommon/controller/capturePosts.ts | 34++++++++++++++++++++++++++--------
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++++
Mcommon/controller/copies.test.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/copiesScan.ts | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/controller/fetchOlderPosts.test.ts | 5++---
Mcommon/controller/fetchPosts.test.ts | 34+++++++++++++++++++++++++++++++---
Mcommon/controller/fetchPosts.ts | 12++++++++++++
Mcommon/controller/importMedia.ts | 17+++++++++++++----
Mcommon/controller/keepVideosMatching.test.ts | 5++++-
Mcommon/controller/keepVideosMatching.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Acommon/controller/markProvenance.test.ts | 648+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/marksBackfill.ts | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/pruneSavedVideos.test.ts | 2+-
Mcommon/controller/readXTrending.test.ts | 3++-
Mcommon/controller/readXTrending.ts | 31+++++++++++++++++++++++++++----
Mcommon/controller/recordLive.ts | 9+++++++--
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/cleanAudioConfirm.ts | 50++++++++++++++++++++++++++++++++++++++++++++------
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/jobContext.ts | 23+++++++++++++++++++++++
Mcommon/lib/pendingKeep-server.ts | 27+++++++++++++++++++++++----
Mcommon/lib/settingsSchema.ts | 24+++++++++++++++++++++++-
Mcommon/lib/sidecar-server.test.ts | 2+-
Mcommon/lib/xJobRule.test.ts | 79++++++++++++++++++++++++++++++-------------------------------------------------
Mcommon/lib/xJobRule.ts | 43++++++++++++++++++-------------------------
Acommon/lib/xSitting.ts | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/ytdlp/savedAlternates.test.ts | 4++--
Meditor/CHANGELOG.md | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/_markProvenance.test.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/cleanup/route.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++------
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]/videos/[id]/components/VideoPanel.tsx | 13++++++++++---
Meditor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx | 100++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 10++++++++--
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 32++++++++++++++++++++++++++++----
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++++++++++++++++++++++++++++++++++++
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/e2e/servers.ts | 5+++++
Meditor/playwright.config.ts | 5+++++
Mscripts/archilyzer-ops.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mscripts/archilyzer-ops.test.mjs | 16++++++++++++++++
111 files changed, 6311 insertions(+), 453 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -198,15 +198,17 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | -| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "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}'` | @@ -236,7 +238,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. | | @@ -269,6 +271,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] @@ -340,6 +343,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 @@ -369,15 +377,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 @@ -261,8 +261,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 @@ -517,11 +517,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 @@ -543,16 +596,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 @@ -562,10 +613,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): @@ -772,8 +822,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 @@ -1102,6 +1152,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 @@ -1135,8 +1191,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 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/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/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). @@ -137,6 +155,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 @@ -161,14 +183,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. // @@ -182,19 +217,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", }; @@ -224,6 +262,8 @@ export async function cleanAudioFromTranscribed({ verifyAvailability, unchecked, onlyIds, + sourceGone: sourceGoneAsked, + jobId, probes, assertReachable = assertChannelMediaReachable, onLog, @@ -254,12 +294,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; @@ -295,6 +363,7 @@ export async function cleanAudioFromTranscribed({ candidateIds: candidates.map((c) => c.id), onLog: log, signal, + ...(jobId ? { jobId } : {}), ...(probes ? { probes } : {}), }); excluded = excludedIds(verdicts); @@ -322,7 +391,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) { @@ -333,6 +402,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; @@ -391,12 +507,15 @@ export async function cleanAudioFromTranscribed({ prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}), + ...(sourceGoneRemoved ? { sourceGoneRemoved } : {}), ...(stopped ? { stopped } : {}), ...(partial ? { partial } : {}), ...(chain ?? {}), }; } +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 @@ -408,6 +527,7 @@ async function discoverAudioCandidates({ dirs, log, signal, + sourceGone = false, }: { paths: Paths; channelSlug: string; @@ -415,8 +535,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; @@ -434,18 +559,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 = { @@ -459,9 +589,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 @@ -481,24 +627,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 }, }; } @@ -607,8 +757,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/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/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/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/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/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/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/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/recordLive.ts b/common/controller/recordLive.ts @@ -1590,10 +1590,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/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -129,6 +129,8 @@ export type VerifyBeforeCleanOptions = { // verifyBeforeCleanMaxAgeHours). now?: () => number; maxAgeHours?: number; + // The clean job this gate runs in, recorded on every mark it writes. + jobId?: string; }; // A per-video probe that found the video on its platform inside the window, @@ -304,6 +306,7 @@ export async function verifyBeforeClean({ probes, now, maxAgeHours, + jobId, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -318,11 +321,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, @@ -537,6 +539,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 — @@ -589,6 +596,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(); @@ -596,6 +621,7 @@ export async function runManagedFunction( registry.finalize(id, "cancelled"); return; } + if (endedByXStop()) return; registry.finalize(id, "done"); }) .catch((err) => { @@ -604,6 +630,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/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/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 @@ -258,8 +258,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/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/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/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -217,6 +217,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"; @@ -2007,7 +2029,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/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/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/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 @@ -1,6 +1,47 @@ # Changelog ## [Unreleased] +- **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. - **Clean audio cleans what a rate-limited listing did return.** - Before, a checked Clean audio whose channel listing was rate-limited part-way cleaned nothing: a Rumble channel of about 8,000 videos stopped after 408 entries and left all 350 candidates unverified. @@ -51,6 +92,50 @@ - `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. 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/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]/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"; @@ -78,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. @@ -134,6 +137,7 @@ export function VideoPanel({ availabilityHistory, channelAudioFormat, doNotClean = false, + doNotCleanMark = null, excludedFromTruncatedCheck = false, savedVideo = null, sourceVideoQuality, @@ -491,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"} @@ -502,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]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -11,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"; @@ -170,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); @@ -263,6 +266,7 @@ export default async function VideoDetailPage({ availabilityHistory, metadataHistory, doNotClean, + doNotCleanMark, excludedFromTruncatedCheck, savedVideo, archiveOrg, @@ -299,6 +303,7 @@ export default async function VideoDetailPage({ availabilityHistory, metadataHistory, doNotClean, + doNotCleanMark, excludedFromTruncatedCheck, savedVideo, archiveOrg, @@ -438,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, @@ -1310,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); @@ -1324,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 @@ -1344,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 { @@ -1354,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) { @@ -1379,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 { @@ -1388,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]/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/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" }, @@ -125,7 +125,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"; @@ -185,6 +186,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/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/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 @@ -121,6 +121,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 @@ -150,6 +152,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"}' @@ -328,6 +333,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, @@ -702,6 +709,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", @@ -709,6 +720,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", @@ -1398,6 +1413,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]", @@ -1471,6 +1487,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", @@ -1500,15 +1521,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", @@ -1744,6 +1777,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.', "", @@ -1793,7 +1838,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"?}.', @@ -1833,6 +1894,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.', @@ -3313,8 +3384,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", @@ -3330,7 +3411,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.