Archilyzer · Source

archilyzer

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

commit 1c449ffdf4174a8933c6c5e95743e0e6aa59971c
parent bde68e4a1362599578bd63315118cc6f3f8dbf22
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 02:52:09 -0400

Merge r31/mirrors: a channel can mirror others (config mirror.of); a pure matcher (recorded date, day window, title Jaccard, duration, was_live) and a mirror-scan job writing transcripts/mirrors/<slug>.json with both directions' counts; the channel page's Mirror stage; MCP copies line and copies: only-here. Private: no export reads it

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	editor/CHANGELOG.md
#	plans/FACTS.md

Diffstat:
MCHANNEL.md | 7+++++++
MCOMMANDS.md | 3++-
Acommon/controller/mirrorScan.test.ts | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/mirrorScan.ts | 295+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 14++++++++++++++
Mcommon/lib/channelConfig.ts | 7++++++-
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/fileSchemaDocs.ts | 8++++++++
Acommon/lib/mirrors/config.test.ts | 27+++++++++++++++++++++++++++
Acommon/lib/mirrors/config.ts | 35+++++++++++++++++++++++++++++++++++
Acommon/lib/mirrors/match.test.ts | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mirrors/match.ts | 406+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mirrors/scanFile-server.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/mirrors/scanFile.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 1+
Acommon/testing/mirrors/mirrorCorpus.d.mts | 32++++++++++++++++++++++++++++++++
Acommon/testing/mirrors/mirrorCorpus.mjs | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/pipeline/stageStatus.ts | 27+++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/mirror-scan/route.ts | 27+++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/stages/MirrorStage.tsx | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/mirrorActions.ts | 22++++++++++++++++++++++
Meditor/app/channels/[slug]/page.tsx | 27+++++++++++++++++++++++++++
Meditor/app/channels/components/ChannelForm.tsx | 8++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 2++
Meditor/app/channels/components/parseChannelForm.test.ts | 24++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 13+++++++++++++
Aeditor/e2e/mirror-panel.spec.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.ts | 5++++-
Amcp/src/mirrorCopies.test.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amcp/src/mirrorCopies.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/server.ts | 29+++++++++++++++++++++++++++++
Mplans/FACTS.md | 44++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-31/mirrors.md | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 30+++++++++++++++++++++++++++++-
36 files changed, 2314 insertions(+), 5 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -47,6 +47,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. | | `audioCheck` | config | Opt-in audio-integrity checking for sources that intermittently serve corrupt audio mid-download (e.g. Odysee "original"): the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption. transcribe-handling only. See [`audioCheck`](#audiocheck). | | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | +| `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | #### `downloadFilter` @@ -72,3 +73,9 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | Key | Default | Description | |---|---|---| | `titlePattern` | required | Case-insensitive regex SOURCE (no delimiters, no flags) matched against each video's title, with three named groups: `year` (four digits, or two read as 20YY), `month` (1–12, or an English month name, whole or cut to three or more letters) and `day`. Trimmed; at most 200 characters, no nested quantifier (the download filter's rules). A pattern that breaks any of this drops the whole rule. | + +#### `mirror` + +| Key | Default | Description | +|---|---|---| +| `of` | required | The slugs of the creator's channels in this corpus that this channel copies (every platform the creator uploads to), e.g. `["creator-youtube", "creator-rumble"]`. Trimmed and de-duplicated; a value that is not a channel slug is dropped, and a list left empty drops the whole key. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -90,7 +90,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | action | what it does | example | |---|---|---| | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'` | -| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | +| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | | `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | @@ -153,6 +153,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -&gt; {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&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 or limit with it)} -&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` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -&gt; {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -&gt; {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | ### Usage, flags and environment diff --git a/common/controller/mirrorScan.test.ts b/common/controller/mirrorScan.test.ts @@ -0,0 +1,185 @@ +// The mirror scan (release 31, lane D) over the synthetic mirror corpus +// (common/testing/mirrors/): off disk with no index, then through the REAL +// buildIndex (the records from `sums`, the recorded dates the index derived), +// the same totals both ways; a dry run writes nothing; a channel with no +// mirror.of is refused; the job kind reads the text tier. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/mirrorScan.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "mirror-scan-")); +const PINNED: Record<string, string> = { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}; +Object.assign(process.env, PINNED); +delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("./buildIndex"); +const { mirrorScanRefusal, parseMirrorScanBody, readChannelRecords, runMirrorScan, mirrorScanSummary } = await import("./mirrorScan"); +const { readMirrorScan, listMirrorScans, mirrorScanPath } = await import("../lib/mirrors/scanFile-server"); +const { copiesIndex } = await import("../lib/mirrors/scanFile"); +const { kindNeedsText, kindNeedsMedia, jobKindLabel } = await import("../jobs/jobKinds"); +const { writeMirrorCorpus, EXPECTED, MIRROR_SLUG, CREATOR_SLUG, RUMBLE_SLUG } = await import("../testing/mirrors/mirrorCorpus.mjs"); + +const paths = getPaths(); +mkdirSync(paths.channelsDir, { recursive: true }); +writeFileSync(paths.settingsFile, "{}"); +await writeMirrorCorpus(paths.channelsDir); + +function checkTotals(f: Awaited<ReturnType<typeof runMirrorScan>>["file"]) { + assert.deepEqual(f.window, EXPECTED.window); + assert.deepEqual(Object.fromEntries(f.videos.map((v) => [v.id, v.status])), EXPECTED.status); + assert.deepEqual(f.totals.byStatus, EXPECTED.byStatus); + assert.deepEqual(f.totals.byPlatform, EXPECTED.byPlatform); + assert.equal(f.totals.creatorRemoved.inWindow, EXPECTED.creatorRemoved.inWindow); + assert.equal(f.totals.creatorRemoved.held, EXPECTED.creatorRemoved.held); + assert.deepEqual(Object.fromEntries(f.removed.map((r) => [r.id, r.heldBy])), EXPECTED.held); + assert.deepEqual(f.platforms, { [CREATOR_SLUG]: "youtube", [RUMBLE_SLUG]: "rumble" }); +} + +test("the job kind reads the text tier", () => { + assert.equal(kindNeedsText("mirror-scan"), true); + assert.equal(kindNeedsMedia("mirror-scan"), false); + assert.equal(jobKindLabel("mirror-scan"), "Mirror scan"); +}); + +test("the body: a slug, dryRun a boolean", () => { + assert.deepEqual(parseMirrorScanBody({ slug: " a-b " }), { slug: "a-b", dryRun: false }); + assert.deepEqual(parseMirrorScanBody({ slug: "a", dryRun: true }), { slug: "a", dryRun: true }); + assert.throws(() => parseMirrorScanBody({}), /"slug" is required/); + assert.throws(() => parseMirrorScanBody({ slug: "../x" }), /not a channel slug/); + assert.throws(() => parseMirrorScanBody({ slug: "a", dryRun: "yes" }), /"dryRun" must be true or false/); +}); + +test("refused: an unknown channel, a channel with no mirror.of", async () => { + assert.match((await mirrorScanRefusal(paths, "no-such")) ?? "", /Channel "no-such" not found/); + assert.match((await mirrorScanRefusal(paths, CREATOR_SLUG)) ?? "", /is not a mirror: its config has no mirror\.of/); + assert.equal(await mirrorScanRefusal(paths, MIRROR_SLUG), null); + await assert.rejects(runMirrorScan(paths, CREATOR_SLUG), /is not a mirror/); +}); + +test("off disk (no index): the records, the recorded dates from the rule, the totals both ways; a dry run writes nothing", async () => { + const m = await readChannelRecords(paths, MIRROR_SLUG); + assert.equal(m.fromIndex, 0); + assert.equal(m.fromDisk, 6); + assert.equal(m.platform, "odysee"); + assert.equal(m.records.find((r) => r.id === "vod-m1")?.recordedDate, "20230301"); + assert.equal(m.records.find((r) => r.id === "vod-m7")?.recordedDate, undefined); + const r = await readChannelRecords(paths, RUMBLE_SLUG, { goneWindow: { from: "20230101", to: "20231231" } }); + assert.deepEqual(r.records.map((x) => [x.id, x.dir]).sort(), [ + ["v4embed1", "v1abc-big-news-day"], + ["v4embed2", "v1abd-oven-lawsuit"], + ["v4embed5", "v1abe-pan-review"], + ]); + const c = await readChannelRecords(paths, CREATOR_SLUG, { goneWindow: { from: "20230228", to: "20230322" } }); + assert.equal(c.records.find((x) => x.id === "yt-s2")?.gone, "deleted"); + assert.equal(c.records.find((x) => x.id === "yt-s3")?.gone, "private"); + assert.equal(c.records.find((x) => x.id === "yt-x1")?.gone, null, "outside the window: not read"); + assert.equal(c.records.find((x) => x.id === "yt-s1")?.wasLive, true); + + const dry = await runMirrorScan(paths, MIRROR_SLUG, { dryRun: true, now: () => new Date("2026-10-16T00:00:00Z") }); + assert.equal(dry.path, undefined); + assert.equal(existsSync(mirrorScanPath(paths.transcriptsDir, MIRROR_SLUG)), false); + checkTotals(dry.file); + assert.equal(dry.file.generatedAt, "2026-10-16T00:00:00.000Z"); + assert.deepEqual(mirrorScanSummary(dry, true).byStatus, EXPECTED.byStatus); +}); + +test("through the real index: the same totals, the file written and read back, the copies index", async () => { + mkdirSync(path.join(paths.sitesDir, "testsite"), { recursive: true }); + writeFileSync( + path.join(paths.sitesDir, "testsite", "site.json"), + JSON.stringify({ + siteId: "testsite", + siteTitle: "Test Site", + siteDescription: "fixture", + headerTitle: "Test Site", + homeTagline: "", + socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: [MIRROR_SLUG, CREATOR_SLUG, RUMBLE_SLUG].map((slug) => ({ slug, groupId: "default" })), + }), + ); + await buildIndex({ paths, onLog: () => {} }); + const m = await readChannelRecords(paths, MIRROR_SLUG); + assert.equal(m.fromIndex, 6, "every mirror video from the index"); + assert.equal(m.records.find((r) => r.id === "vod-m2")?.recordedDate, "20230305", "the index's recorded date"); + const r = await readChannelRecords(paths, RUMBLE_SLUG); + assert.equal(r.fromIndex, 3); + assert.equal(r.records.find((x) => x.id === "v4embed2")?.dir, "v1abd-oven-lawsuit"); + + const out = await runMirrorScan(paths, MIRROR_SLUG, { jobId: "job-1" }); + assert.equal(out.path, mirrorScanPath(paths.transcriptsDir, MIRROR_SLUG)); + checkTotals(out.file); + const back = await readMirrorScan(paths.transcriptsDir, MIRROR_SLUG); + assert.ok(back); + assert.equal(back.jobId, "job-1"); + assert.equal(back.format, "archilyzer-mirror-scan"); + assert.equal(back.version, 1); + assert.deepEqual(JSON.parse(await readFile(out.path!, "utf8")).totals, out.file.totals); + const all = await listMirrorScans(paths.transcriptsDir); + assert.equal(all.length, 1); + + const idx = copiesIndex(all); + assert.deepEqual(idx.get(`${MIRROR_SLUG}/vod-m2`), { + role: "mirror", + mirror: MIRROR_SLUG, + status: "creator-deleted", + matches: [ + { channel: CREATOR_SLUG, id: "yt-s2", gone: "deleted" }, + { channel: RUMBLE_SLUG, id: "v4embed2" }, + ], + }); + assert.deepEqual(idx.get(`${CREATOR_SLUG}/yt-s3`), { role: "creator", copies: [{ mirror: MIRROR_SLUG, id: "vod-m3" }], gone: "private" }); + assert.equal(idx.get(`${CREATOR_SLUG}/yt-x2`), undefined, "removed, not held"); +}); + +test("as a job: refused before any job without mirror.of; the log ends with the totals; onDone after a write only", async () => { + const { enqueueMirrorScan } = await import("./mirrorScan"); + const { getRegistry } = await import("../jobs/registry"); + const refused = await enqueueMirrorScan({ slug: CREATOR_SLUG }, { paths }); + assert.equal(refused.ok, false); + const done: string[] = []; + for (const dryRun of [true, false]) { + const out = await enqueueMirrorScan({ slug: MIRROR_SLUG, dryRun }, { paths, onDone: (s) => done.push(s) }); + assert.ok(out.ok, JSON.stringify(out)); + const job = getRegistry().get(out.jobId)!; + assert.equal(job.kind, "mirror-scan"); + assert.equal(job.queueKey, "mirror-scan"); + assert.equal(job.channelSlug, MIRROR_SLUG); + void out.stream.cancel(); + const end = await out.done; + const log = await readFile(job.logPath, "utf8"); + assert.equal(end.status, "done", log); + const line = log.split("\n").find((l) => l.startsWith("@@mirror-scan "))!; + const summary = JSON.parse(line.slice("@@mirror-scan ".length)); + assert.equal(summary.dryRun, dryRun); + assert.deepEqual(summary.byStatus, EXPECTED.byStatus); + assert.equal(summary.creatorRemoved.held, EXPECTED.creatorRemoved.held); + assert.equal("file" in summary, !dryRun); + assert.match(log, /the creator removed 3 in this window; the mirror holds 2/); + } + assert.deepEqual(done, [MIRROR_SLUG]); +}); diff --git a/common/controller/mirrorScan.ts b/common/controller/mirrorScan.ts @@ -0,0 +1,295 @@ +// THE MIRROR SCAN (release 31, lane D): a mirror channel (config `mirror.of`) +// paired with the creator's channels by lib/mirrors/match.ts, the result in +// `transcripts/mirrors/<slug>.json` (lib/mirrors/scanFile.ts) — a `mirror-scan` +// job, `pnpm ops mirror-scan {slug, dryRun?}`, the channel page's Mirror stage. +// +// CHEAP: no media, no network. Each channel's records come from the LMDB index +// (the `mtimes` range of the channel gives each data dir's index key, `sums` its +// summary: title, upload date, duration, live, recorded date), and only a dir +// the index has not seen is read off disk (its metadata.info.json through +// summarize(), as the index would). A record's recorded date is the index's, +// else the channel's title rule applied here — so a scan is right before the +// index is rebuilt for a new rule. The creator's gone state is THE gone reading +// (lib/sourceGone-server.ts sourceGoneState: availability.json reconciled with +// download-outcome.json), read only for videos dated where a match or the +// removed list can reach (the mirror's window widened by the day margins). +// +// A dry run reads and matches the same and writes nothing; the totals are in +// the log's `@@mirror-scan` line either way. + +import path from "node:path"; +import { existsSync } from "node:fs"; +import { open } from "lmdb"; +import type { Paths } from "../lib/paths"; +import type { TranscriptSummary } from "../lib/transcripts"; +import { loadRawMetadataFromDir, summarize } from "../lib/transcripts-server"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { mapConcurrent } from "../lib/concurrency"; +import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate"; +import { sourceGoneState } from "../lib/sourceGone-server"; +import { isSafeChannelSegment } from "../lib/citations/moments"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { + addDays, + contentDate, + matchMirror, + MIRROR_DAYS_AFTER, + MIRROR_DAYS_BEFORE, + type MirrorRecord, +} from "../lib/mirrors/match"; +import { MIRROR_RULES, MIRROR_SCAN_FORMAT, MIRROR_SCAN_VERSION, type MirrorScanFile } from "../lib/mirrors/scanFile"; +import { writeMirrorScan } from "../lib/mirrors/scanFile-server"; +import { readChannelConfig } from "./channels"; +import { heldVideoIds } from "./videoCues"; + +export const MIRROR_SCAN_JOB_KIND = "mirror-scan"; +// One scan at a time, machine-wide: each reads the index and thousands of +// small sidecars; two at once only halve each other. +export const MIRROR_SCAN_QUEUE = "mirror-scan"; +export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan "; +export const MIRROR_SCAN_BODY_KEYS = ["slug", "dryRun"] as const; + +const GONE_READ_CONCURRENCY = 32; + +type IndexKey = [string, string, string]; +type PathKey = [string, string]; + +export type ChannelRecords = { + slug: string; + platform: string; + records: MirrorRecord[]; + fromIndex: number; + fromDisk: number; + // Data dirs with no readable metadata (no record). + noMetadata: number; +}; + +// The channel's index summaries by data dir. Never throws: a missing, locked +// or mid-rebuild index is "nothing from the index", and the disk carries on. +function indexSummaries(paths: Paths, slug: string, dirs: ReadonlySet<string>): Map<string, TranscriptSummary> { + const out = new Map<string, TranscriptSummary>(); + if (dirs.size === 0 || !existsSync(paths.lmdbPath)) return out; + let root: ReturnType<typeof open>; + try { + // `compression: true` on a reader too (videoTitles.ts's note). + root = open({ path: paths.lmdbPath, readOnly: true, maxDbs: 18, compression: true }); + } catch { + return out; + } + try { + const sums = root.openDB<TranscriptSummary, IndexKey>({ name: "sums", encoding: "msgpack" }); + const mtimes = root.openDB<{ indexKey?: IndexKey }, PathKey>({ name: "mtimes", encoding: "msgpack" }); + for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "￿"] })) { + const k = key as PathKey; + if (k[0] !== slug) break; + if (!dirs.has(k[1]) || !value?.indexKey) continue; + const s = sums.get(value.indexKey); + if (s && typeof s.id === "string") out.set(k[1], s); + } + } catch { + // A partial read stands; the rest comes off disk. + } finally { + void root.close().catch(() => {}); + } + return out; +} + +// The platform a channel is on: its config's, else the one most of its +// records carry. +function channelPlatform(configured: string | undefined, summaries: Iterable<TranscriptSummary>): string { + if (configured) return configured; + const n = new Map<string, number>(); + for (const s of summaries) n.set(s.platform, (n.get(s.platform) ?? 0) + 1); + return [...n.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? "unknown"; +} + +// One channel's videos as the matcher reads them; the gone state read for the +// records dated inside `goneWindow` (none read without one). +export async function readChannelRecords( + paths: Paths, + slug: string, + opts: { goneWindow?: { from: string; to: string } | null } = {}, +): Promise<ChannelRecords> { + const config = await readChannelConfig(paths, slug); + if (!config) throw new Error(`Channel "${slug}" not found`); + // The text guard: an unmounted or moving drive is not an empty channel. + await assertChannelTextReadable(paths, slug, config); + const dataDir = path.join(paths.channelsDir, slug, "data"); + const dirs = await heldVideoIds(dataDir); + const fromIndex = indexSummaries(paths, slug, dirs); + const summaries = new Map(fromIndex); + let noMetadata = 0; + const rest = [...dirs].filter((d) => !summaries.has(d)).sort(); + await mapConcurrent(rest, 16, async (dir) => { + const meta = await loadRawMetadataFromDir(path.join(dataDir, dir)).catch(() => null); + if (!meta) { + noMetadata++; + return; + } + summaries.set(dir, summarize(slug, dir, meta, config.name)); + }); + const rule = config.recordedDate ? compileRecordedDateRule(config.recordedDate) : null; + const records: (MirrorRecord & { dir: string })[] = []; + for (const [dir, s] of [...summaries.entries()].sort((a, b) => a[0].localeCompare(b[0]))) { + const recordedDate = s.recordedDate ?? (rule ? deriveRecordedDate(rule, s.title, s.uploadDate) : undefined); + records.push({ + id: s.id, + dir, + title: s.title, + duration: typeof s.duration === "number" && Number.isFinite(s.duration) ? s.duration : 0, + uploadDate: s.uploadDate ?? "", + ...(recordedDate ? { recordedDate } : {}), + wasLive: s.isLivestream === true, + gone: null, + }); + } + const w = opts.goneWindow; + if (w) { + const inWindow = records.filter((r) => { + const d = contentDate(r); + return d !== null && d >= w.from && d <= w.to; + }); + await mapConcurrent(inWindow, GONE_READ_CONCURRENCY, async (r) => { + r.gone = await sourceGoneState(path.join(dataDir, r.dir)).catch(() => null); + }); + } + return { + slug, + platform: channelPlatform(config.platform, summaries.values()), + records, + fromIndex: fromIndex.size, + fromDisk: summaries.size - fromIndex.size, + noMetadata, + }; +} + +export type MirrorScanOptions = { + dryRun?: boolean; + jobId?: string; + onLog?: (line: string) => void; + now?: () => Date; +}; + +export type MirrorScanOutcome = { + file: MirrorScanFile; + // Where it was written; absent on a dry run. + path?: string; +}; + +// The refusal for a channel that cannot be scanned, or null. +export async function mirrorScanRefusal(paths: Paths, slug: string): Promise<string | null> { + if (!isSafeChannelSegment(slug)) return `not a channel slug: ${JSON.stringify(slug)}`; + const config = await readChannelConfig(paths, slug); + if (!config) return `Channel "${slug}" not found`; + const of = (config.mirror?.of ?? []).filter((s) => s !== slug); + if (of.length === 0) { + return `${slug} is not a mirror: its config has no mirror.of — set the creator's channels first: pnpm ops channel-config --json '{"slug":"${slug}","patch":{"mirrorOf":"<creator-slug>, …"}}'`; + } + const found = await Promise.all(of.map(async (s) => ((await readChannelConfig(paths, s)) ? s : null))); + if (!found.some(Boolean)) return `none of ${slug}'s mirror.of channels is in this corpus (${of.join(", ")})`; + return null; +} + +export async function runMirrorScan(paths: Paths, slug: string, opts: MirrorScanOptions = {}): Promise<MirrorScanOutcome> { + const log = opts.onLog ?? (() => {}); + const refusal = await mirrorScanRefusal(paths, slug); + if (refusal) throw new Error(refusal); + const config = (await readChannelConfig(paths, slug))!; + const of = config.mirror!.of.filter((s) => s !== slug); + const missing: string[] = []; + for (const s of of) if (!(await readChannelConfig(paths, s))) missing.push(s); + if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`); + + const mirror = await readChannelRecords(paths, slug); + log(`${slug}: ${mirror.records.length} videos (${mirror.fromIndex} from the index, ${mirror.fromDisk} from disk)`); + const dates = mirror.records.map(contentDate).filter((d): d is string => d !== null).sort(); + const goneWindow = dates.length > 0 ? { from: addDays(dates[0], -MIRROR_DAYS_BEFORE), to: addDays(dates.at(-1)!, MIRROR_DAYS_AFTER) } : null; + const creators: ChannelRecords[] = []; + for (const s of of.filter((x) => !missing.includes(x))) { + const c = await readChannelRecords(paths, s, { goneWindow }); + const gone = c.records.filter((r) => r.gone).length; + log(`${s} (${c.platform}): ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk), ${gone} gone in reach`); + creators.push(c); + } + const result = matchMirror({ + mirror: { slug, platform: mirror.platform, records: mirror.records, titleRule: config.recordedDate ? compileRecordedDateRule(config.recordedDate) : null }, + creators: creators.map((c) => ({ slug: c.slug, platform: c.platform, records: c.records })), + }); + const file: MirrorScanFile = { + format: MIRROR_SCAN_FORMAT, + version: MIRROR_SCAN_VERSION, + mirror: slug, + of, + ...(missing.length > 0 ? { missing } : {}), + generatedAt: (opts.now?.() ?? new Date()).toISOString(), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + rules: { ...MIRROR_RULES }, + ...result, + }; + if (opts.dryRun) return { file }; + return { file, path: await writeMirrorScan(paths.transcriptsDir, file) }; +} + +// The `@@mirror-scan` line's JSON: the totals both ways, no per-video rows. +export function mirrorScanSummary(out: MirrorScanOutcome, dryRun: boolean) { + const f = out.file; + return { + slug: f.mirror, + dryRun, + ...(out.path ? { file: out.path } : {}), + of: f.of, + ...(f.missing ? { missing: f.missing } : {}), + window: f.window, + videos: f.totals.videos, + matched: f.totals.matched, + byStatus: f.totals.byStatus, + byPlatform: f.totals.byPlatform, + creatorRemoved: f.totals.creatorRemoved, + }; +} + +export type MirrorScanBody = { slug: string; dryRun: boolean }; + +export function parseMirrorScanBody(raw: Record<string, unknown>): MirrorScanBody { + const slug = typeof raw.slug === "string" ? raw.slug.trim() : ""; + if (!slug) throw new Error('"slug" is required: the mirror channel'); + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + if (raw.dryRun !== undefined && typeof raw.dryRun !== "boolean") throw new Error('"dryRun" must be true or false'); + return { slug, dryRun: raw.dryRun === true }; +} + +// Enqueue a `mirror-scan` job (refused before any job for a channel that is no +// mirror). `onDone` runs after a scan that wrote its file (the editor +// revalidates the channel page there). +export async function enqueueMirrorScan( + raw: Record<string, unknown>, + deps: { paths: Paths; onDone?: (slug: string) => void; now?: () => Date }, +): Promise<StreamActionResult> { + let body: MirrorScanBody; + try { + body = parseMirrorScanBody(raw); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const refusal = await mirrorScanRefusal(deps.paths, body.slug); + if (refusal) return { ok: false, error: refusal }; + return runManagedFunction({ + kind: MIRROR_SCAN_JOB_KIND, + queueKey: MIRROR_SCAN_QUEUE, + paths: deps.paths, + channelSlug: body.slug, + fn: async (onLog, _signal, _setProgress, ctx) => { + onLog(`mirror scan of ${body.slug}${body.dryRun ? " (dry run: nothing is written)" : ""}`); + const out = await runMirrorScan(deps.paths, body.slug, { dryRun: body.dryRun, jobId: ctx.jobId, onLog, ...(deps.now ? { now: deps.now } : {}) }); + const t = out.file.totals; + onLog( + `${t.videos} videos: ${t.byStatus["only-copy"]} only copy, ${t.byStatus["creator-deleted"]} creator deleted, ` + + `${t.byStatus["never-uploaded"]} never uploaded, ${t.byStatus["creator-public"]} creator public`, + ); + onLog(`the creator removed ${t.creatorRemoved.inWindow} in this window; the mirror holds ${t.creatorRemoved.held}`); + if (out.path) onLog(`wrote ${out.path}`); + onLog(`${MIRROR_SCAN_RESULT_MARKER}${JSON.stringify(mirrorScanSummary(out, body.dryRun))}`); + if (out.path) deps.onDone?.(body.slug); + }, + }); +} diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -1009,6 +1009,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", needsMedia: true, }, + // The mirror scan (release 31, lane D): a mirror channel's videos paired + // with its creator's channels (`mirror.of`) by date and title, into + // `transcripts/mirrors/<slug>.json` — `pnpm ops mirror-scan`, the channel + // page's Mirror stage. Reads the index, metadata and availability sidecars + // of the mirror and the creator's channels (the text tier, each guarded in + // the controller): needsText. Its own queue; not replayable (Scan again). + "mirror-scan": { + kind: "mirror-scan", + label: "Mirror scan", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + needsText: true, + }, "tts-file": { kind: "tts-file", label: "Text to speech", diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -8,6 +8,7 @@ import { import { isCookieMode, type CookieMode } from "./cookiePolicy"; import type { FieldDocs } from "./fieldDocs"; import { coerceRecordedDateRule, type RecordedDateRule } from "./recordedDate"; +import { coerceMirrorConfig, type MirrorConfig } from "./mirrors/config"; export type ChannelHandling = "youtube" | "transcribe"; @@ -148,6 +149,7 @@ export type ChannelConfig = { sleepBetweenDownloadsSeconds?: number; audioCheck?: AudioCheckConfig; recordedDate?: RecordedDateRule; + mirror?: MirrorConfig; }; // In the order parseChannelConfig emits (and CHANNEL.md lists) them. @@ -207,7 +209,9 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { audioCheck: "Opt-in audio-integrity checking for sources that intermittently serve corrupt audio mid-download (e.g. Odysee \"original\"): the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption. transcribe-handling only.", recordedDate: - "For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped." + "For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped.", + mirror: + "For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped." }; // Every key a config.json may carry, in emission order. The unknown-key oracle: @@ -412,6 +416,7 @@ export const CHANNEL_CONFIG_COERCIONS: { : undefined, audioCheck: coerceAudioCheck, recordedDate: coerceRecordedDateRule, + mirror: coerceMirrorConfig, }; // A channel's config.json as a ChannelConfig, or null when it is not a channel diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 33); + assert.equal(CHANNEL_CONFIG_KEYS.length, 34); assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -76,6 +76,7 @@ export const channelConfigObjectSchema = z.object({ sleepBetweenDownloadsSeconds: field("sleepBetweenDownloadsSeconds"), audioCheck: field("audioCheck"), recordedDate: field("recordedDate"), + mirror: field("mirror"), }); // Drop every own key whose value is `undefined` (the OMIT rule, above). diff --git a/common/lib/fileSchemaDocs.ts b/common/lib/fileSchemaDocs.ts @@ -23,6 +23,7 @@ import { DOWNLOAD_FILTER_FIELD_DOCS, } from "./channelConfig"; import { RECORDED_DATE_RULE_FIELD_DOCS } from "./recordedDate"; +import { MIRROR_CONFIG_FIELD_DOCS } from "./mirrors/config"; import { SOCIAL_LINK_FIELD_DOCS } from "./settingsSchema"; import { RELATED_SITE_GROUP_FIELD_DOCS, @@ -141,6 +142,13 @@ const CHANNEL_NESTED: Partial<Record<string, KeyTable[]>> = { defaults: () => "required", }, ], + mirror: [ + { + path: "mirror", + docs: MIRROR_CONFIG_FIELD_DOCS, + defaults: () => "required", + }, + ], }; function channelKind(key: string): string { diff --git a/common/lib/mirrors/config.test.ts b/common/lib/mirrors/config.test.ts @@ -0,0 +1,27 @@ +// The `mirror` config key (release 31, lane D): `of` kept as valid slugs, +// trimmed and de-duplicated; nothing usable drops the key, as its siblings do. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mirrors/config.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { coerceMirrorConfig, mirrorSlugs } from "./config"; +import { parseChannelConfig } from "../channelConfig"; +import { channelConfigSchema } from "../channelConfigSchema"; + +test("coerceMirrorConfig keeps valid slugs and drops the rest", () => { + assert.deepEqual(coerceMirrorConfig({ of: [" a-b ", "c_d", "a-b", "../x", 3, ""] }), { of: ["a-b", "c_d"] }); + assert.equal(coerceMirrorConfig({ of: [] }), undefined); + assert.equal(coerceMirrorConfig({ of: ["../x"] }), undefined); + assert.equal(coerceMirrorConfig({}), undefined); + assert.equal(coerceMirrorConfig(["a"]), undefined); + assert.equal(coerceMirrorConfig("a"), undefined); + assert.deepEqual(mirrorSlugs("a, b c,,a"), ["a", "b", "c"]); +}); + +test("a config.json's mirror reads through both compositions", () => { + const raw = { handling: "transcribe", mirror: { of: ["creator-yt", "bad/slug"] } }; + assert.deepEqual(parseChannelConfig(raw)?.mirror, { of: ["creator-yt"] }); + assert.deepEqual(channelConfigSchema.parse(raw)?.mirror, { of: ["creator-yt"] }); + assert.equal("mirror" in (channelConfigSchema.parse({ handling: "transcribe", mirror: { of: [] } }) ?? {}), false); +}); diff --git a/common/lib/mirrors/config.ts b/common/lib/mirrors/config.ts @@ -0,0 +1,35 @@ +// A channel's `mirror` config key (release 31, lane D): the channel MIRRORS +// another creator's streams, and `of` names the creator's channels in this +// corpus (their slugs). The mirror scan (controller/mirrorScan.ts) pairs the +// two (lib/mirrors/match.ts). +// +// Pure, client-safe (channelConfig.ts imports the coercion). + +import { isSafeChannelSegment } from "../citations/moments"; + +export type MirrorConfig = { + of: string[]; +}; + +export const MIRROR_CONFIG_FIELD_DOCS: Record<keyof MirrorConfig, string> = { + of: "The slugs of the creator's channels in this corpus that this channel copies (every platform the creator uploads to), e.g. `[\"creator-youtube\", \"creator-rumble\"]`. Trimmed and de-duplicated; a value that is not a channel slug is dropped, and a list left empty drops the whole key.", +}; + +// The slugs of a list (an array, or text separated by commas or whitespace), +// trimmed, valid and de-duplicated, in order. +export function mirrorSlugs(v: unknown): string[] { + const raw = Array.isArray(v) ? v : typeof v === "string" ? v.split(/[\s,]+/) : []; + const out: string[] = []; + for (const x of raw) { + if (typeof x !== "string") continue; + const s = x.trim(); + if (s && isSafeChannelSegment(s) && !out.includes(s)) out.push(s); + } + return out; +} + +export function coerceMirrorConfig(v: unknown): MirrorConfig | undefined { + if (!v || typeof v !== "object" || Array.isArray(v)) return undefined; + const of = mirrorSlugs((v as Record<string, unknown>).of); + return of.length > 0 ? { of } : undefined; +} diff --git a/common/lib/mirrors/match.test.ts b/common/lib/mirrors/match.test.ts @@ -0,0 +1,185 @@ +// The mirror matcher (release 31, lane D): match.py's rules on hand-built +// cases (each rule branch, the day window's edges, stop words, the topic), +// status.py's strong cut and the four statuses, then the synthetic mirror +// corpus both ways. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mirrors/match.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + addDays, + contentDate, + durationsAgree, + isStrong, + matchMirror, + matchRule, + mirrorTopic, + statusOf, + titleJaccard, + titleWords, + MIRROR_DURATION_TOLERANCE, + MIRROR_LIVE_MIN_SECONDS, + type MirrorRecord, +} from "./match"; +import { + CREATOR_RECORDS, + CREATOR_SLUG, + EXPECTED, + MIRROR_RECORDS, + MIRROR_SLUG, + RECORDED_DATE_PATTERN, + RUMBLE_RECORDS, + RUMBLE_SLUG, +} from "../../testing/mirrors/mirrorCorpus.mjs"; + +const RULE = new RegExp(RECORDED_DATE_PATTERN, "i"); + +function rec(id: string, title: string, date: string, extra: Partial<MirrorRecord> = {}): MirrorRecord { + return { id, title, uploadDate: date, duration: 0, wasLive: false, gone: null, ...extra }; +} + +function one(mirror: MirrorRecord, creators: MirrorRecord[], platform = "youtube") { + return matchMirror({ + mirror: { slug: "m", platform: "odysee", records: [mirror], titleRule: RULE }, + creators: [{ slug: "c", platform, records: creators }], + }).videos[0]; +} + +test("words: lowercase [a-z0-9'] runs, one-letter words and stop words dropped", () => { + assert.deepEqual([...titleWords("The Oven's BIG Day & More w/ a Guest: 2023!")].sort(), ["2023", "big", "day", "guest", "oven's"]); + assert.deepEqual([...titleWords("This is what he gets, and got")], ["what", "he"]); + assert.equal(titleJaccard(new Set(["a", "b"]), new Set(["b", "c"])), 1 / 3); + assert.equal(titleJaccard(new Set(), new Set()), 0); +}); + +test("topic: the title after the date the rule reads, before it when nothing follows, whole otherwise", () => { + assert.equal(mirrorTopic("[VOD] Name - 03/01/2023 - Big News Day", RULE), "Big News Day"); + assert.equal(mirrorTopic("Big News Day | 03/01/2023", RULE), "Big News Day"); + assert.equal(mirrorTopic("[VOD] Name - Bonus Stream", RULE), "[VOD] Name - Bonus Stream"); + assert.equal(mirrorTopic("Anything", null), "Anything"); +}); + +test("dates: recorded first, else upload; whole calendar days", () => { + assert.equal(contentDate({ uploadDate: "20230304", recordedDate: "20230301" }), "20230301"); + assert.equal(contentDate({ uploadDate: "20230304" }), "20230304"); + assert.equal(contentDate({ uploadDate: "" }), null); + assert.equal(addDays("20230228", 1), "20230301"); + assert.equal(addDays("20240101", -1), "20231231"); +}); + +test("durations agree under 25% of the mirror's, both known", () => { + assert.equal(MIRROR_DURATION_TOLERANCE, 0.25); + assert.equal(durationsAgree(1000, 1249), true); + assert.equal(durationsAgree(1000, 1250), false, "strictly less"); + assert.equal(durationsAgree(1000, 751), true); + assert.equal(durationsAgree(0, 1000), false); + assert.equal(durationsAgree(1000, 0), false); +}); + +test("rules in order: title ≥ 0.25; ≥ 0.12 with durations; a long stream with durations", () => { + const stream = { duration: 4000, wasLive: true }; + assert.equal(matchRule(0.25, false, stream), "title"); + assert.equal(matchRule(0.24, false, stream), null); + assert.equal(matchRule(0.12, true, { duration: 100, wasLive: false }), "title-duration"); + assert.equal(matchRule(0.11, true, { duration: 100, wasLive: false }), null); + assert.equal(matchRule(0, true, stream), "live-duration"); + assert.equal(matchRule(0, true, { duration: MIRROR_LIVE_MIN_SECONDS, wasLive: true }), null, "longer than 3000 s"); + assert.equal(matchRule(0, true, { duration: 4000, wasLive: false }), null, "a stream"); + assert.equal(matchRule(0, false, stream), null, "durations must agree"); +}); + +test("strong: score ≥ 0.5, or ≥ 0.25 with durations (the score is the Jaccard to two decimals)", () => { + assert.equal(isStrong(0.5, false), true); + assert.equal(isStrong(0.49, false), false); + assert.equal(isStrong(0.25, true), true); + assert.equal(isStrong(0.24, true), false); +}); + +test("each rule branch on hand-built videos", () => { + const m = rec("m1", "[VOD] X - 03/01/2023 - alpha beta gamma delta", "20230305", { recordedDate: "20230301", duration: 4000 }); + // title: 2 of 6 words = 0.33 — a match, strong only with durations. + let v = one(m, [rec("c1", "alpha beta zeta eta", "20230301")]); + assert.equal(v.matches[0].rule, "title"); + assert.equal(v.matches[0].score, 0.33); + assert.equal(v.matches[0].strong, false); + v = one(m, [rec("c1", "alpha beta zeta eta", "20230301", { duration: 4100 })]); + assert.equal(v.matches[0].strong, true); + // under 0.25 with no durations: nothing. + assert.equal(one(m, [rec("c1", "alpha zeta", "20230301")]).matches.length, 0, "1 of 5 = 0.2"); + v = one(m, [rec("c1", "alpha beta gamma", "20230301")]); + assert.equal(v.matches[0].score, 0.75); + assert.equal(v.matches[0].strong, true); + // title-duration: 1/7 ≈ 0.14 with durations. + v = one(m, [rec("c2", "alpha one two three", "20230301", { duration: 4100 })]); + assert.equal(v.matches[0].rule, "title-duration"); + assert.equal(v.matches[0].strong, false); + // live-duration: nothing shared, a 4100 s stream. + v = one(m, [rec("c3", "unrelated words", "20230301", { duration: 4100, wasLive: true })]); + assert.equal(v.matches[0].rule, "live-duration"); + assert.equal(v.matches[0].strong, false); + assert.equal(v.status, "only-copy", "a weak match decides nothing"); + // none. + v = one(m, [rec("c4", "unrelated words", "20230301", { duration: 9000, wasLive: true })]); + assert.equal(v.matches.length, 0); +}); + +test("the day window: one day before to two after the recorded date", () => { + const m = rec("m1", "[VOD] X - 03/10/2023 - alpha beta", "20230320", { recordedDate: "20230310" }); + const at = (d: string) => one(m, [rec("c", "alpha beta", d)]).matches.length; + assert.equal(at("20230308"), 0); + assert.equal(at("20230309"), 1); + assert.equal(at("20230310"), 1); + assert.equal(at("20230312"), 1); + assert.equal(at("20230313"), 0); + // No recorded date: the upload date. + const u = rec("m2", "alpha beta", "20230320"); + assert.equal(one(u, [rec("c", "alpha beta", "20230321")]).matches.length, 1); + assert.equal(one(u, [rec("c", "alpha beta", "20230310")]).matches.length, 0); +}); + +test("stop words do not make a match", () => { + const m = rec("m1", "[VOD] X - 03/10/2023 - the more of this", "20230320", { recordedDate: "20230310" }); + assert.equal(one(m, [rec("c", "The More Of This", "20230310")]).matches.length, 0); +}); + +test("statuses from presence", () => { + assert.equal(statusOf({ youtube: "none", rumble: "none" }), "only-copy"); + assert.equal(statusOf({ youtube: "gone", rumble: "none" }), "only-copy"); + assert.equal(statusOf({ youtube: "gone", rumble: "public" }), "creator-deleted"); + assert.equal(statusOf({ youtube: "none", rumble: "public" }), "never-uploaded"); + assert.equal(statusOf({ youtube: "public", rumble: "public" }), "creator-public"); + assert.equal(statusOf({ youtube: "public" }), "creator-public"); +}); + +test("the synthetic mirror corpus, both directions", () => { + const r = matchMirror({ + mirror: { slug: MIRROR_SLUG, platform: "odysee", records: MIRROR_RECORDS, titleRule: RULE }, + creators: [ + { slug: CREATOR_SLUG, platform: "youtube", records: CREATOR_RECORDS }, + { slug: RUMBLE_SLUG, platform: "rumble", records: RUMBLE_RECORDS }, + ], + }); + assert.deepEqual(r.window, EXPECTED.window); + assert.deepEqual(Object.fromEntries(r.videos.map((v) => [v.id, v.status])), EXPECTED.status); + assert.deepEqual(r.totals.byStatus, EXPECTED.byStatus); + assert.deepEqual(r.totals.byPlatform, EXPECTED.byPlatform); + assert.equal(r.totals.creatorRemoved.inWindow, EXPECTED.creatorRemoved.inWindow); + assert.equal(r.totals.creatorRemoved.held, EXPECTED.creatorRemoved.held); + assert.deepEqual(Object.fromEntries(r.removed.map((x) => [x.id, x.heldBy])), EXPECTED.held); + assert.deepEqual(r.totals.creatorRemoved.byChannel, { + [CREATOR_SLUG]: { inWindow: 3, held: 2 }, + [RUMBLE_SLUG]: { inWindow: 0, held: 0 }, + }); + const m2 = r.videos.find((v) => v.id === "vod-m2")!; + assert.deepEqual( + m2.matches.map((x) => [x.channel, x.id, x.gone ?? null, x.strong]), + [ + [CREATOR_SLUG, "yt-s2", "deleted", true], + [RUMBLE_SLUG, "v4embed2", null, true], + ], + ); + assert.equal(m2.matches[1].dir, "v1abd-oven-lawsuit", "a Rumble match names its dir"); + assert.equal(r.totals.matched, 4); + assert.equal(r.totals.dated, 6); +}); diff --git a/common/lib/mirrors/match.ts b/common/lib/mirrors/match.ts @@ -0,0 +1,406 @@ +// A MIRROR CHANNEL AND THE CREATOR IT COPIES (release 31, lane D). +// +// A channel that mirrors another creator's streams (a VOD archive on another +// platform: config `mirror.of` names the creator's channels) holds copies whose +// originals the creator may have deleted, made private, or never uploaded at +// all. The duplicate finder (lib/duplicates.ts) clusters only short videos, so +// a 1–5 h stream never folds with its original; this module is the one place +// that pairs a mirror's videos with the creator's, in BOTH directions, from the +// same matches — so "the mirror holds N of the creator's removed videos" and +// "M of the mirror's videos are the only copy" are counted off one set. +// +// PURE: no fs, no clock. The records come from controller/mirrorScan.ts (the +// index, else metadata on disk) with their gone state already read through the +// one gone reading (lib/sourceGone-server.ts, `sourceGoneState`). +// +// ── A MATCH ── +// +// Each mirror video is dated by its RECORDED date (`recordedDate`, the +// channel's title rule — lib/recordedDate.ts), else its upload date; a creator +// video the same way (`contentDate`). A creator video is a CANDIDATE when its +// date is within MIRROR_DAYS_BEFORE days before to MIRROR_DAYS_AFTER days +// after the mirror video's (an upload lands the day of the stream or a day or +// two later; a mirror's title date is sometimes the day after a late stream). +// A candidate MATCHES by the first rule that holds: +// +// "title" title Jaccard ≥ MIRROR_TITLE_JACCARD +// "title-duration" title Jaccard ≥ MIRROR_WEAK_TITLE_JACCARD and the +// durations agree +// "live-duration" the durations agree, the creator video is a stream +// (`wasLive`) and longer than MIRROR_LIVE_MIN_SECONDS +// +// The title Jaccard is over word sets (lowercase `[a-z0-9']+`, words of one +// character and MIRROR_STOP_WORDS dropped). The mirror's side is its TOPIC: the +// title after the recorded date its rule reads (the creator's name and the +// date are not the topic), or before it when nothing follows; the whole title +// when the rule does not match. Durations AGREE when both are known and differ +// by less than MIRROR_DURATION_TOLERANCE of the mirror's. +// +// A match is STRONG when its score (the Jaccard to two decimals) is ≥ +// MIRROR_STRONG_TITLE_JACCARD, or ≥ MIRROR_STRONG_DURATION_TITLE_JACCARD with +// the durations agreeing. Every match is kept in the file; only STRONG ones +// decide a status or hold a removed upload. (The research scripts this +// generalises: ~/reports/quartering-cornbreadman match.py = the rules, +// status.py = strong; the thresholds are theirs.) +// +// ── A MIRROR VIDEO'S STATUS ── +// +// `presence` per creator PLATFORM (the platforms of the `mirror.of` channels): +// "public" when a strong match on that platform is not gone, else "gone" when a +// strong match there is gone (deleted or private), else "none". Then the +// status, the first that holds: +// +// only-copy no platform is "public": the mirror holds the only public +// copy (the creator removed it, or never uploaded it, or both) +// creator-deleted a platform is "gone" (the creator removed a copy) and +// another is "public" +// never-uploaded a platform is "none" (never uploaded there) and the rest +// are "public" +// creator-public every creator platform has it public +// +// A mirror video with no date has no candidates: only-copy. +// +// ── THE CREATOR'S REMOVED UPLOADS ── +// +// The other direction: every creator video that is gone and whose date lies in +// the mirror's WINDOW (the first to the last date of the mirror's dated +// videos). One is HELD by the mirror when it is a strong match of a mirror +// video; `heldBy` names them. + +import type { GoneState } from "../sourceGone"; + +export const MIRROR_DAYS_BEFORE = 1; +export const MIRROR_DAYS_AFTER = 2; +export const MIRROR_TITLE_JACCARD = 0.25; +export const MIRROR_WEAK_TITLE_JACCARD = 0.12; +export const MIRROR_DURATION_TOLERANCE = 0.25; +export const MIRROR_LIVE_MIN_SECONDS = 3000; +export const MIRROR_STRONG_TITLE_JACCARD = 0.5; +export const MIRROR_STRONG_DURATION_TITLE_JACCARD = 0.25; +export const MIRROR_MIN_WORD_LENGTH = 2; +export const MIRROR_STOP_WORDS: ReadonlySet<string> = new Set( + "the a an and of to in is on for w with & more much by it at as be are his her i my me you we our this that gets got".split(" "), +); + +export const MIRROR_STATUSES = ["only-copy", "creator-deleted", "never-uploaded", "creator-public"] as const; +export type MirrorStatus = (typeof MIRROR_STATUSES)[number]; + +export const MIRROR_STATUS_LABELS: Readonly<Record<MirrorStatus, string>> = Object.freeze({ + "only-copy": "Only copy", + "creator-deleted": "Creator deleted", + "never-uploaded": "Never uploaded", + "creator-public": "Creator public", +}); + +export type MirrorRule = "title" | "title-duration" | "live-duration"; +export type Presence = "public" | "gone" | "none"; + +// One video, as the matcher reads it. +export type MirrorRecord = { + id: string; + // The data/<dir>/ it lives in, when that is not `id` (a Rumble embed id). + dir?: string; + title: string; + // Seconds; 0 = unknown. + duration: number; + // YYYYMMDD, or "" when unknown. + uploadDate: string; + recordedDate?: string; + wasLive: boolean; + // The gone reading (sourceGone.ts); null = not gone (or never checked). + gone: GoneState | null; +}; + +export type MirrorChannelInput = { + slug: string; + platform: string; + records: MirrorRecord[]; +}; + +export type MirrorMatchInput = { + mirror: MirrorChannelInput & { + // The mirror's recorded-date title rule, for the topic; null = none. + titleRule?: RegExp | null; + }; + creators: MirrorChannelInput[]; +}; + +export type MirrorMatch = { + channel: string; + id: string; + dir?: string; + title: string; + date: string; + duration: number; + wasLive: boolean; + rule: MirrorRule; + // The title Jaccard, to two decimals. + score: number; + durationAgrees: boolean; + strong: boolean; + gone?: GoneState; +}; + +export type MirrorVideo = { + id: string; + dir?: string; + title: string; + // The date it was matched by (recorded, else upload); null = undated. + date: string | null; + recordedDate?: string; + duration: number; + status: MirrorStatus; + presence: Record<string, Presence>; + // Strongest first. + matches: MirrorMatch[]; +}; + +export type RemovedUpload = { + channel: string; + id: string; + dir?: string; + title: string; + date: string; + duration: number; + gone: GoneState; + // Mirror video ids holding it (strong matches); empty = not held. + heldBy: string[]; +}; + +export type MirrorTotals = { + videos: number; + dated: number; + // Mirror videos with at least one strong match. + matched: number; + byStatus: Record<MirrorStatus, number>; + byPlatform: Record<string, Record<Presence, number>>; + creatorRemoved: { + inWindow: number; + held: number; + byChannel: Record<string, { inWindow: number; held: number }>; + }; +}; + +export type MirrorMatchResult = { + window: { from: string; to: string } | null; + platforms: Record<string, string>; + videos: MirrorVideo[]; + removed: RemovedUpload[]; + totals: MirrorTotals; +}; + +const YMD = /^\d{8}$/; + +// The date a record is matched by: recorded, else upload; null when neither is +// a YYYYMMDD. +export function contentDate(r: { uploadDate: string; recordedDate?: string }): string | null { + if (r.recordedDate && YMD.test(r.recordedDate)) return r.recordedDate; + return YMD.test(r.uploadDate) ? r.uploadDate : null; +} + +// A YYYYMMDD moved by `days` (UTC calendar days). +export function addDays(ymd: string, days: number): string { + const d = new Date(Date.UTC(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8)) + days)); + return `${d.getUTCFullYear()}${String(d.getUTCMonth() + 1).padStart(2, "0")}${String(d.getUTCDate()).padStart(2, "0")}`; +} + +// The words a title is compared on. +export function titleWords(s: string): Set<string> { + const out = new Set<string>(); + for (const w of (s ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? []) { + if (w.length >= MIRROR_MIN_WORD_LENGTH && !MIRROR_STOP_WORDS.has(w)) out.add(w); + } + return out; +} + +export function titleJaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number { + let inter = 0; + for (const w of a) if (b.has(w)) inter++; + const union = a.size + b.size - inter; + return inter / Math.max(1, union); +} + +const SEPARATORS = /^[\s\-–—|:•·,.]+|[\s\-–—|:•·,.]+$/g; + +// A mirror title's topic: what follows the date its rule reads (else what +// precedes it), or the whole title when the rule reads none. +export function mirrorTopic(title: string, rule: RegExp | null | undefined): string { + if (!rule) return title; + const m = new RegExp(rule.source, rule.flags.replace("g", "")).exec(title); + if (!m) return title; + const after = title.slice(m.index + m[0].length).replace(SEPARATORS, ""); + if (titleWords(after).size > 0) return after; + return title.slice(0, m.index).replace(SEPARATORS, ""); +} + +export function durationsAgree(mirrorSeconds: number, creatorSeconds: number): boolean { + return mirrorSeconds > 0 && creatorSeconds > 0 && Math.abs(creatorSeconds - mirrorSeconds) < MIRROR_DURATION_TOLERANCE * mirrorSeconds; +} + +// The rule a candidate matches by, or null. +export function matchRule(j: number, durationAgrees: boolean, creator: { duration: number; wasLive: boolean }): MirrorRule | null { + if (j >= MIRROR_TITLE_JACCARD) return "title"; + if (j >= MIRROR_WEAK_TITLE_JACCARD && durationAgrees) return "title-duration"; + if (durationAgrees && creator.duration > MIRROR_LIVE_MIN_SECONDS && creator.wasLive) return "live-duration"; + return null; +} + +export const roundScore = (j: number): number => Math.round(j * 100) / 100; + +export function isStrong(score: number, durationAgrees: boolean): boolean { + return score >= MIRROR_STRONG_TITLE_JACCARD || (durationAgrees && score >= MIRROR_STRONG_DURATION_TITLE_JACCARD); +} + +export function statusOf(presence: Record<string, Presence>): MirrorStatus { + const p = Object.values(presence); + if (!p.includes("public")) return "only-copy"; + if (p.includes("gone")) return "creator-deleted"; + if (p.includes("none")) return "never-uploaded"; + return "creator-public"; +} + +type Candidate = { channel: string; platform: string; rec: MirrorRecord; date: string; words: Set<string> }; + +const byIdThenChannel = (a: { id: string; channel?: string }, b: { id: string; channel?: string }) => + (a.channel ?? "").localeCompare(b.channel ?? "") || a.id.localeCompare(b.id); + +export function matchMirror(input: MirrorMatchInput): MirrorMatchResult { + const platforms: Record<string, string> = {}; + for (const c of input.creators) platforms[c.slug] = c.platform; + const platformList = [...new Set(input.creators.map((c) => c.platform))].sort(); + + // The creator's videos by date. + const byDate = new Map<string, Candidate[]>(); + for (const c of input.creators) { + for (const rec of c.records) { + const date = contentDate(rec); + if (!date) continue; + const list = byDate.get(date) ?? []; + list.push({ channel: c.slug, platform: c.platform, rec, date, words: titleWords(rec.title) }); + byDate.set(date, list); + } + } + + const rule = input.mirror.titleRule ?? null; + const videos: MirrorVideo[] = []; + // creator channel + id → mirror ids holding it (strong). + const held = new Map<string, string[]>(); + let dated = 0; + let from: string | null = null; + let to: string | null = null; + for (const m of input.mirror.records) { + const date = contentDate(m); + const matches: (MirrorMatch & { platform: string })[] = []; + if (date) { + dated++; + if (!from || date < from) from = date; + if (!to || date > to) to = date; + const words = titleWords(mirrorTopic(m.title, rule)); + for (let k = -MIRROR_DAYS_BEFORE; k <= MIRROR_DAYS_AFTER; k++) { + for (const cand of byDate.get(addDays(date, k)) ?? []) { + const j = titleJaccard(words, cand.words); + const agrees = durationsAgree(m.duration, cand.rec.duration); + const how = matchRule(j, agrees, cand.rec); + if (!how) continue; + const score = roundScore(j); + const strong = isStrong(score, agrees); + matches.push({ + channel: cand.channel, + platform: cand.platform, + id: cand.rec.id, + ...(cand.rec.dir && cand.rec.dir !== cand.rec.id ? { dir: cand.rec.dir } : {}), + title: cand.rec.title, + date: cand.date, + duration: cand.rec.duration, + wasLive: cand.rec.wasLive, + rule: how, + score, + durationAgrees: agrees, + strong, + ...(cand.rec.gone ? { gone: cand.rec.gone } : {}), + }); + if (strong) { + const key = `${cand.channel}\x00${cand.rec.id}`; + const list = held.get(key) ?? []; + if (!list.includes(m.id)) list.push(m.id); + held.set(key, list); + } + } + } + } + matches.sort((a, b) => b.score - a.score || Number(b.strong) - Number(a.strong) || byIdThenChannel(a, b)); + const presence: Record<string, Presence> = {}; + for (const p of platformList) { + const strong = matches.filter((x) => x.strong && x.platform === p); + presence[p] = strong.some((x) => !x.gone) ? "public" : strong.length > 0 ? "gone" : "none"; + } + videos.push({ + id: m.id, + ...(m.dir && m.dir !== m.id ? { dir: m.dir } : {}), + title: m.title, + date, + ...(m.recordedDate ? { recordedDate: m.recordedDate } : {}), + duration: m.duration, + status: statusOf(presence), + presence, + matches: matches.map(({ platform: _p, ...rest }) => rest), + }); + } + videos.sort((a, b) => (a.date ?? "").localeCompare(b.date ?? "") || a.id.localeCompare(b.id)); + + const removed: RemovedUpload[] = []; + if (from && to) { + for (const c of input.creators) { + for (const rec of c.records) { + const date = contentDate(rec); + if (!rec.gone || !date || date < from || date > to) continue; + removed.push({ + channel: c.slug, + id: rec.id, + ...(rec.dir && rec.dir !== rec.id ? { dir: rec.dir } : {}), + title: rec.title, + date, + duration: rec.duration, + gone: rec.gone, + heldBy: [...(held.get(`${c.slug}\x00${rec.id}`) ?? [])].sort(), + }); + } + } + } + removed.sort((a, b) => a.date.localeCompare(b.date) || byIdThenChannel(a, b)); + + const byStatus = Object.fromEntries(MIRROR_STATUSES.map((s) => [s, 0])) as Record<MirrorStatus, number>; + const byPlatform: Record<string, Record<Presence, number>> = {}; + for (const p of platformList) byPlatform[p] = { public: 0, gone: 0, none: 0 }; + let matched = 0; + for (const v of videos) { + byStatus[v.status]++; + if (v.matches.some((x) => x.strong)) matched++; + for (const [p, pr] of Object.entries(v.presence)) byPlatform[p][pr]++; + } + const byChannel: Record<string, { inWindow: number; held: number }> = {}; + for (const c of input.creators) byChannel[c.slug] = { inWindow: 0, held: 0 }; + for (const r of removed) { + byChannel[r.channel].inWindow++; + if (r.heldBy.length > 0) byChannel[r.channel].held++; + } + + return { + window: from && to ? { from, to } : null, + platforms, + videos, + removed, + totals: { + videos: videos.length, + dated, + matched, + byStatus, + byPlatform, + creatorRemoved: { + inWindow: removed.length, + held: removed.filter((r) => r.heldBy.length > 0).length, + byChannel, + }, + }, + }; +} diff --git a/common/lib/mirrors/scanFile-server.ts b/common/lib/mirrors/scanFile-server.ts @@ -0,0 +1,45 @@ +// The disk half of lib/mirrors/scanFile.ts: `<transcriptsDir>/mirrors/<slug>.json`, +// read and written. SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import { writeJsonAtomic } from "../jsonFile-server"; +import { isSafeChannelSegment } from "../citations/moments"; +import { isMirrorScanFile, MIRRORS_DIRNAME, type MirrorScanFile } from "./scanFile"; + +export function mirrorsDirOf(transcriptsDir: string): string { + return path.join(transcriptsDir, MIRRORS_DIRNAME); +} + +export function mirrorScanPath(transcriptsDir: string, slug: string): string { + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + return path.join(mirrorsDirOf(transcriptsDir), `${slug}.json`); +} + +// The channel's scan, or null (none yet, unreadable, or another format). +export async function readMirrorScan(transcriptsDir: string, slug: string): Promise<MirrorScanFile | null> { + try { + const v = JSON.parse(await readFile(mirrorScanPath(transcriptsDir, slug), "utf8")) as unknown; + return isMirrorScanFile(v) ? v : null; + } catch { + return null; + } +} + +// Every channel's scan (a missing directory is none). +export async function listMirrorScans(transcriptsDir: string): Promise<MirrorScanFile[]> { + const names = await readdir(mirrorsDirOf(transcriptsDir)).catch(() => [] as string[]); + const out: MirrorScanFile[] = []; + for (const n of names.sort()) { + if (!n.endsWith(".json")) continue; + const f = await readMirrorScan(transcriptsDir, n.slice(0, -".json".length)).catch(() => null); + if (f) out.push(f); + } + return out; +} + +export async function writeMirrorScan(transcriptsDir: string, file: MirrorScanFile): Promise<string> { + const p = mirrorScanPath(transcriptsDir, file.mirror); + await writeJsonAtomic(p, file, { mkdir: true }); + return p; +} diff --git a/common/lib/mirrors/scanFile.ts b/common/lib/mirrors/scanFile.ts @@ -0,0 +1,113 @@ +// `transcripts/mirrors/<slug>.json` — a mirror scan's result (release 31, +// lane D; written by controller/mirrorScan.ts, read by the editor's Mirror +// stage and the MCP's `copies`). PRIVATE: corpus-side only, never published — +// nothing in the export build reads `transcripts/mirrors/`. +// +// Shape: `{format: "archilyzer-mirror-scan", version: 1, mirror, of, missing?, +// generatedAt, jobId?, rules, window, platforms, totals, videos, removed}` — +// `videos`, `removed` and `totals` are lib/mirrors/match.ts's. +// +// Pure, client-safe (types and the copies index). + +import { + MIRROR_DAYS_AFTER, + MIRROR_DAYS_BEFORE, + MIRROR_DURATION_TOLERANCE, + MIRROR_LIVE_MIN_SECONDS, + MIRROR_STRONG_DURATION_TITLE_JACCARD, + MIRROR_STRONG_TITLE_JACCARD, + MIRROR_TITLE_JACCARD, + MIRROR_WEAK_TITLE_JACCARD, + type MirrorMatchResult, + type MirrorStatus, +} from "./match"; + +export const MIRROR_SCAN_FORMAT = "archilyzer-mirror-scan"; +export const MIRROR_SCAN_VERSION = 1; +export const MIRRORS_DIRNAME = "mirrors"; + +export type MirrorRules = { + daysBefore: number; + daysAfter: number; + titleJaccard: number; + weakTitleJaccard: number; + durationTolerance: number; + liveMinSeconds: number; + strongTitleJaccard: number; + strongDurationTitleJaccard: number; +}; + +export const MIRROR_RULES: MirrorRules = Object.freeze({ + daysBefore: MIRROR_DAYS_BEFORE, + daysAfter: MIRROR_DAYS_AFTER, + titleJaccard: MIRROR_TITLE_JACCARD, + weakTitleJaccard: MIRROR_WEAK_TITLE_JACCARD, + durationTolerance: MIRROR_DURATION_TOLERANCE, + liveMinSeconds: MIRROR_LIVE_MIN_SECONDS, + strongTitleJaccard: MIRROR_STRONG_TITLE_JACCARD, + strongDurationTitleJaccard: MIRROR_STRONG_DURATION_TITLE_JACCARD, +}); + +export type MirrorScanFile = MirrorMatchResult & { + format: typeof MIRROR_SCAN_FORMAT; + version: typeof MIRROR_SCAN_VERSION; + // The mirror channel's slug. + mirror: string; + // Its `mirror.of` at the scan, and those of them not found in the corpus. + of: string[]; + missing?: string[]; + generatedAt: string; + jobId?: string; + rules: MirrorRules; +}; + +export function isMirrorScanFile(v: unknown): v is MirrorScanFile { + const f = v as Partial<MirrorScanFile> | null; + return ( + !!f && + typeof f === "object" && + f.format === MIRROR_SCAN_FORMAT && + f.version === MIRROR_SCAN_VERSION && + typeof f.mirror === "string" && + Array.isArray(f.videos) && + Array.isArray(f.removed) && + !!f.totals + ); +} + +// What the corpus knows about a video's copies, across every scan. +export type VideoCopies = + // A mirror's video: its status and its strong matches. + | { role: "mirror"; mirror: string; status: MirrorStatus; matches: { channel: string; id: string; gone?: string }[] } + // A creator's video a mirror holds (a strong match of a mirror video). + | { role: "creator"; copies: { mirror: string; id: string }[]; gone?: string }; + +// `${channel}/${id}` → what the scans say about it. A video both a mirror's +// and a creator's (a mirror of a mirror) keeps the mirror reading. +export function copiesIndex(files: readonly MirrorScanFile[]): Map<string, VideoCopies> { + const out = new Map<string, VideoCopies>(); + for (const f of files) { + for (const v of f.videos) { + out.set(`${f.mirror}/${v.id}`, { + role: "mirror", + mirror: f.mirror, + status: v.status, + matches: v.matches.filter((m) => m.strong).map((m) => ({ channel: m.channel, id: m.id, ...(m.gone ? { gone: m.gone } : {}) })), + }); + } + } + for (const f of files) { + for (const v of f.videos) { + for (const m of v.matches) { + if (!m.strong) continue; + const key = `${m.channel}/${m.id}`; + const prev = out.get(key); + if (prev?.role === "mirror") continue; + const copies = prev?.role === "creator" ? prev.copies : []; + if (!copies.some((c) => c.mirror === f.mirror && c.id === v.id)) copies.push({ mirror: f.mirror, id: v.id }); + out.set(key, { role: "creator", copies, ...(m.gone ? { gone: m.gone } : {}) }); + } + } + } + return out; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -26,6 +26,7 @@ transcript, channel or person goes in these fixtures, ever. | `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | | `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | +| `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). | | `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | diff --git a/common/testing/mirrors/mirrorCorpus.d.mts b/common/testing/mirrors/mirrorCorpus.d.mts @@ -0,0 +1,32 @@ +export type SynthMirrorRecord = { + id: string; + dir?: string; + title: string; + uploadDate: string; + recordedDate?: string; + duration: number; + wasLive: boolean; + gone: "deleted" | "private" | null; +}; + +export const MIRROR_SLUG: string; +export const CREATOR_SLUG: string; +export const RUMBLE_SLUG: string; +export const RECORDED_DATE_PATTERN: string; +export const MIRROR_RECORDS: SynthMirrorRecord[]; +export const CREATOR_RECORDS: SynthMirrorRecord[]; +export const RUMBLE_RECORDS: SynthMirrorRecord[]; +export const CHANNELS: { + slug: string; + platform: string; + config: Record<string, unknown>; +}[]; +export function writeMirrorCorpus(channelsDir: string, opts?: { noMirrorOf?: boolean }): Promise<void>; +export const EXPECTED: { + window: { from: string; to: string }; + status: Record<string, string>; + byStatus: Record<string, number>; + byPlatform: Record<string, { public: number; gone: number; none: number }>; + creatorRemoved: { inWindow: number; held: number }; + held: Record<string, string[]>; +}; diff --git a/common/testing/mirrors/mirrorCorpus.mjs b/common/testing/mirrors/mirrorCorpus.mjs @@ -0,0 +1,164 @@ +// A SYNTHETIC MIRROR CORPUS (release 31, lane D) — a creator who streams on +// two platforms and a channel that archives the streams on a third. Invented +// names, titles and ids; nothing from a real channel. +// +// synth-streamer the creator on "youtube": three streams (one public, +// one deleted, one private), a removed short outside +// the mirror's window, a removed short inside it that +// the mirror does not hold, a public video nothing +// matches. +// synth-streamer-rumble the creator's "rumble" twin: copies of the public and +// the deleted stream, and a stream never on YouTube. +// Rumble's data dirs are URL slugs, its ids embed ids. +// synth-vod-archive the MIRROR ("odysee"): titles +// "[VOD] SynthStreamer - MM/DD/YYYY - <topic>", uploaded +// days after the stream; one title with no date (dated +// by its upload). config `recordedDate` + `mirror.of`. +// +// `MIRROR_RECORDS` / `CREATOR_RECORDS` are the records as the matcher reads them +// (lib/mirrors/match.ts MirrorRecord, recorded dates filled in); +// `writeMirrorCorpus(channelsDir)` writes the same three channels to disk +// (config.json, data/<dir>/metadata.info.json, availability.json) for the +// controller and the editor's e2e; `EXPECTED` is what a scan finds. + +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const MIRROR_SLUG = "synth-vod-archive"; +export const CREATOR_SLUG = "synth-streamer"; +export const RUMBLE_SLUG = "synth-streamer-rumble"; +export const RECORDED_DATE_PATTERN = "(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{4})"; + +const vod = (date, topic) => `[VOD] SynthStreamer - ${date} - ${topic}`; + +// [id, dir?, title, uploadDate, recordedDate?, duration, live, availability?] +const MIRROR = [ + ["vod-m1", null, vod("03/01/2023", "Big News Day, Kitchen Fire & More"), "20230304", "20230301", 10790, false], + ["vod-m2", null, vod("03/05/2023", "Oven Lawsuit Explained And Toaster Recall"), "20230308", "20230305", 8950, false], + ["vod-m3", null, vod("03/09/2023", "Spatula Drama Gets Worse"), "20230311", "20230309", 7180, false], + ["vod-m4", null, vod("03/11/2023", "Garden Hose Investigation"), "20230314", "20230311", 5000, false], + ["vod-m5", null, vod("03/12/2023", "Pan Review Marathon"), "20230316", "20230312", 14350, false], + ["vod-m7", null, "[VOD] SynthStreamer - Bonus Stream", "20230320", undefined, 3600, false], +]; + +const CREATOR = [ + ["yt-s1", null, "Big News Day, Kitchen Fire & More", "20230301", undefined, 10800, true, "public"], + ["yt-s2", null, "Oven Lawsuit Explained And Toaster Recall", "20230306", undefined, 9000, true, "deleted"], + ["yt-s3", null, "Spatula Drama Gets Worse", "20230309", undefined, 7200, true, "private"], + ["yt-x1", null, "Old Pantry Tour", "20220110", undefined, 400, false, "deleted"], + ["yt-x2", null, "Short Clip About Forks", "20230307", undefined, 300, false, "deleted"], + ["yt-n1", null, "Weekly Mailbag", "20230312", undefined, 600, false, undefined], +]; + +const RUMBLE = [ + ["v4embed1", "v1abc-big-news-day", "Big News Day, Kitchen Fire & More", "20230301", undefined, 10805, true, "public"], + ["v4embed2", "v1abd-oven-lawsuit", "Oven Lawsuit Explained And Toaster Recall", "20230306", undefined, 9010, true, undefined], + ["v4embed5", "v1abe-pan-review", "Pan Review Marathon", "20230313", undefined, 14400, true, "public"], +]; + +function record(row) { + const [id, dir, title, uploadDate, recordedDate, duration, wasLive, availability] = row; + const gone = availability === "deleted" || availability === "private" ? availability : null; + return { + id, + ...(dir ? { dir } : {}), + title, + uploadDate, + ...(recordedDate ? { recordedDate } : {}), + duration, + wasLive, + gone, + }; +} + +export const MIRROR_RECORDS = MIRROR.map(record); +export const CREATOR_RECORDS = CREATOR.map(record); +export const RUMBLE_RECORDS = RUMBLE.map(record); + +export const CHANNELS = [ + { + slug: MIRROR_SLUG, + platform: "odysee", + rows: MIRROR, + config: { + handling: "transcribe", + platform: "odysee", + name: "Synth VOD Archive", + url: "https://odysee.com/@SynthVodArchive:0", + recordedDate: { titlePattern: RECORDED_DATE_PATTERN }, + mirror: { of: [CREATOR_SLUG, RUMBLE_SLUG] }, + }, + page: (id) => `https://odysee.com/@SynthVodArchive:0/${id}:1`, + }, + { + slug: CREATOR_SLUG, + platform: "youtube", + rows: CREATOR, + config: { handling: "youtube", platform: "youtube", name: "SynthStreamer", url: "https://www.youtube.com/@SynthStreamer/videos" }, + page: (id) => `https://www.youtube.com/watch?v=${id}`, + }, + { + slug: RUMBLE_SLUG, + platform: "rumble", + rows: RUMBLE, + config: { handling: "transcribe", platform: "rumble", name: "SynthStreamer (Rumble)", url: "https://rumble.com/c/SynthStreamer" }, + page: (_id, dir) => `https://rumble.com/${dir}.html`, + }, +]; + +// The three channels on disk under `channelsDir`. No index: a scan reads them +// off disk (the controller's fallback for videos the index has not seen). +export async function writeMirrorCorpus(channelsDir, opts = {}) { + for (const ch of CHANNELS) { + const dir = path.join(channelsDir, ch.slug); + await mkdir(path.join(dir, "data"), { recursive: true }); + const config = opts.noMirrorOf && ch.slug === MIRROR_SLUG ? { ...ch.config, mirror: undefined } : ch.config; + await writeFile(path.join(dir, "config.json"), JSON.stringify(config, null, 2)); + for (const [id, vdir, title, uploadDate, , duration, live, availability] of ch.rows) { + const videoDir = path.join(dir, "data", vdir ?? id); + await mkdir(videoDir, { recursive: true }); + const webpageUrl = ch.page(id, vdir ?? id); + await writeFile( + path.join(videoDir, "metadata.info.json"), + JSON.stringify({ + id, + title, + upload_date: uploadDate, + duration, + webpage_url: webpageUrl, + ...(ch.platform === "odysee" ? { webpage_url_basename: id, extractor_key: "LBRY" } : {}), + ...(ch.platform === "rumble" ? { extractor_key: "Rumble" } : {}), + ...(ch.platform === "youtube" ? { extractor_key: "Youtube" } : {}), + live_status: live ? "was_live" : "not_live", + }), + ); + if (availability) { + await writeFile( + path.join(videoDir, "availability.json"), + JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability, webpageUrl }), + ); + } + } + } +} + +// What a scan of the corpus finds (lib/mirrors/match.ts's rules). +export const EXPECTED = { + window: { from: "20230301", to: "20230320" }, + status: { + "vod-m1": "creator-public", + "vod-m2": "creator-deleted", + "vod-m3": "only-copy", + "vod-m4": "only-copy", + "vod-m5": "never-uploaded", + "vod-m7": "only-copy", + }, + byStatus: { "only-copy": 3, "creator-deleted": 1, "never-uploaded": 1, "creator-public": 1 }, + byPlatform: { + rumble: { public: 3, gone: 0, none: 3 }, + youtube: { public: 1, gone: 2, none: 3 }, + }, + // yt-s2 (vod-m2), yt-s3 (vod-m3) held; yt-x2 not; yt-x1 outside the window. + creatorRemoved: { inWindow: 3, held: 2 }, + held: { "yt-s2": ["vod-m2"], "yt-s3": ["vod-m3"], "yt-x2": [] }, +}; diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts @@ -72,6 +72,10 @@ export type StageId = // and no group owns it — so it is hand-listed at the call site alongside them // and is deliberately absent from GROUP_STAGES below. | "storage" + // A MIRROR CHANNEL'S PAIRING WITH THE CREATOR IT COPIES (release 31, lane D; + // controller/mirrorScan.ts). A channel chore, hand-listed at the call site + // and only for a channel whose config has `mirror`. + | "mirror" | "danger"; // THE STAGES EACH OPERATION GROUP OWNS, in the group's own order. @@ -142,6 +146,7 @@ const JOB_KIND_TO_STAGE: Record<string, StageId> = { "clean-extra-audio-formats": "cleanup", "remove-wrong-format-audio": "cleanup", "check-availability": "diagnostics", + "mirror-scan": "mirror", }; function pluralize(n: number, singular: string, plural?: string): string { @@ -188,6 +193,10 @@ export type ComputeStageStatusesInput = { // have to do I/O to get them — an omitted location reads as "in place", which // is what every channel was before relocation existed. media?: ChannelMediaLocation | null; + // The channel's last mirror scan, in numbers (lib/mirrors/scanFile.ts), or + // null when it has none. Read only by the `mirror` stage, which the page + // lists only for a channel with `mirror` in its config; omitted = no scan. + mirrorScan?: { videos: number; onlyCopy: number; removedInWindow: number; held: number } | null; }; export function computeStageStatuses( @@ -201,6 +210,7 @@ export function computeStageStatuses( backfillEnabled = true, backfillKindIds, media, + mirrorScan, } = input; const buckets = normalizeBuckets(snapshot.buckets); @@ -608,6 +618,22 @@ export function computeStageStatuses( : "neutral", }; + const mirrorRunning = runningByStage.has("mirror"); + const mirror: StageStatus = { + id: "mirror", + title: "Mirror", + pending: 0, + failed: 0, + running: mirrorRunning, + defaultOpen: true, + summary: mirrorRunning + ? "Scanning…" + : mirrorScan + ? `${mirrorScan.onlyCopy} of ${pluralize(mirrorScan.videos, "video")} the only copy; the mirror holds ${mirrorScan.held} of ${mirrorScan.removedInWindow} the creator removed.` + : "Not scanned.", + tone: mirrorRunning ? "running" : "neutral", + }; + const danger: StageStatus = { id: "danger", title: "Danger zone", @@ -629,6 +655,7 @@ export function computeStageStatuses( cleanup, diagnostics, storage, + mirror, danger, }; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,6 +3,7 @@ ## [Unreleased] - **A poker frame scan finds the moments a highlight reel is made of.** Besides the double-ups, busts and big pots, the derivation now marks: every pot the streamer's player takes (a pot of 25 big blinds or more is a big pot; the same log line read twice with a digit off is one pot), the player's all-ins with how they ended (doubled, won, lost, busted, or not read), each blind level going up (from the client's "Blinds are now" line; a misread line that a later one contradicts is ignored, in the big blind too), and the field falling under 100, 50, 27 and 18 players and to the final table (from the client's "position N of M" only, once each). Each of these says which rule made it, what it read, and whether a second reading backs it (`confirmed`) or not; a reading flagged against a spoken number still makes nothing. An all-in banner the model reads is the player's only when the player's chips are all in the middle. The new moments appear on an existing scan by re-deriving it, with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`. Needs a restart of the editor. - **A frame-scan supercut has substance, and shows the numbers on screen.** `umtool new <slug> --from <channel>/<video> --seed frames` now ranks the scan's moments — big pots and won all-ins first, then the final table, players-left marks and the bust, then the other swings, the smaller pots, and level-ups last — and takes them until the clips fill `--target <seconds>` (240 by default). The draft turns on the on-screen deck with a new **stats** panel: the stack, the stack in big blinds, players left and the level, in a corner of the picture over each clip, each number changing when the scan read it change (`render.chrome.stats`; a clip's `"stats": false` leaves it out, `"stats": true` draws it on one clip only). A build checks the panel's frames, and fails when a clip that asks for it was drawn without it. The project is new: re-seeding an existing one needs a new slug. +- **A channel that copies another creator's streams can be paired with the creator, both ways.** Name the creator's channels on the mirror's Configure form ("Mirror of (channel slugs)", or `pnpm ops channel-config --json '{"slug":"<mirror>","patch":{"mirrorOf":"<creator>, <creator-rumble>"}}'`). The channel page then has a **Mirror** stage: **Scan** (or `pnpm ops mirror-scan --json '{"slug":"<mirror>"}'`, `"dryRun": true` to count without writing) matches each of the mirror's videos, by the day it was recorded (the title's date when the channel has a recorded-date pattern) and its title and length, with the creator's videos uploaded a day before to two days after. Each video is then the **only copy** (no creator channel has it public), **creator deleted** (removed on one platform, public on another), **never uploaded** (missing from one platform) or **creator public**, with a filter for each and links to the creator's copies; and the other way, the creator's deleted or private videos in the mirror's span and how many of them the mirror holds. The result stays on this machine (`transcripts/mirrors/<slug>.json`) and is never published. With the MCP on a local archive, `get_video_metadata` says what copies a video has, and `enumerate_matches` takes `"copies": "only-here"` for the videos that survive only on a mirror; a published site says this is not available. - **find-copy can bring a deleted or private video's whole audio home, so it gets transcribed.** `pnpm ops find-copy --json '{"siteId":"<site>","gone":"no-transcript","dryRun":true}'` (or `{"slug":"<channel>", …}`) lists every gone video of the site's channels (or of one channel) that has no audio and no transcript, and the copy each would use: the Wayback Machine when it holds the video, else an archive.org mirror of the upload. `"gone":"all"` takes the transcribed ones too, after the others. Without `dryRun` it looks up at most `max` videos (10 by default, at most 200) and starts one **Fetch copies** job on archive.org's download queue, which fetches each copy's audio into the video's own record as `audio.<format>`, one at a time with a pause between them; the transcription lane then picks it up like any downloaded audio. The video's title, date and page stay the original's. Its page says **Audio from a copy:** and links the Wayback capture (with its date) or the archive.org item, where the Wayback or archive.org line used to be. A video neither archive holds is noted in its `copy-attempts.json` and left out of the next 30 days of runs, as is one whose copy failed at its source; `"retryFailed": true` asks again. Needs a restart of the editor. - **A frame scan's timeline reads like the stream.** One tournament stays one tournament until the streamer busts: a hand description, a player's name or a misread of the title no longer starts a new one, and the tournament is named by the title most frames agree on. A stack read mid-hand (chips in the pot) or misread no longer makes a double-up or a big loss; players left come only from the client's own "position N of M" or the log's finishing places, so a table's seats are not the field and no final table appears from them; the big blind is the log's "Blinds are now", so a stack is never 700 big blinds by a misread; "won" banners on other players' hands are gone. A frame and a spoken number that disagree are flagged, and a flagged reading makes no event. **Re-derive** an existing scan with no model call: `pnpm ops frame-scan --json '{"slug":"<channel>","id":"<video>","rederive":true}'`, or `archilyzer frames rederive <channel>/<video> --dry` to see what would change. Needs a restart of the editor. - **Retrying a corrupt full source downloads it again.** A video whose download completed with malformed audio (Odysee's intermittent AAC, on a channel with the audio check) kept its file, and that file made every retry say "Nothing to fetch". A retry of the **corrupt full sources** bucket — the new card on the channel's Download stage, or `pnpm ops retry-bucket --json '{"slug": "<channel>", "bucket": "corruptFullSource"}'` — now sets the kept file aside and downloads again: a clean result replaces it; a malformed one keeps whichever copy decodes longer; a download that fails (a 429, the network) puts the kept file back and the video stays in the bucket, with the attempt recorded. Each retry is recorded in the video's `download-outcome.json`. Needs a restart of the editor. diff --git a/editor/app/api/ops/mirror-scan/route.ts b/editor/app/api/ops/mirror-scan/route.ts @@ -0,0 +1,27 @@ +import { MIRROR_SCAN_BODY_KEYS } from "yt-dlp-transcript-common/controller/mirrorScan"; +import { mirrorScanAction } from "../../../channels/[slug]/mirrorActions"; +import { jobResponse, ops, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun? } -> { ok: true, jobId } +// +// The mirror scan (release 31, lane D), as a `mirror-scan` job on its own +// queue: the mirror channel's videos (config `mirror.of` names the creator's +// channels) paired with the creator's by recorded date and title, into +// `transcripts/mirrors/<slug>.json` — per mirror video its matches and status +// (only-copy, creator-deleted, never-uploaded, creator-public), and the +// creator's removed uploads in the mirror's window with the mirror's copies. +// `dryRun: true` reads and matches the same and writes nothing. Refused before +// any job for a channel with no `mirror.of`. The log ends `@@mirror-scan +// {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, +// byPlatform, creatorRemoved}`. +// +// AN ADAPTER: the refusals are the controller's (controller/mirrorScan.ts). +export async function POST(request: Request) { + return ops(request, MIRROR_SCAN_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const dryRun = optBool(body, "dryRun"); + return jobResponse(await mirrorScanAction(slug, { dryRun })); + }); +} diff --git a/editor/app/channels/[slug]/components/stages/MirrorStage.tsx b/editor/app/channels/[slug]/components/stages/MirrorStage.tsx @@ -0,0 +1,207 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { formatDate, formatDuration } from "yt-dlp-transcript-common/lib/format"; +import { + MIRROR_STATUSES, + MIRROR_STATUS_LABELS, + type MirrorStatus, + type Presence, +} from "yt-dlp-transcript-common/lib/mirrors/match"; +import type { MirrorScanFile } from "yt-dlp-transcript-common/lib/mirrors/scanFile"; +import { mirrorScanAction } from "../../mirrorActions"; +import { cancelJobAction } from "../../../../jobs/actions"; + +// THE MIRROR STAGE (release 31, lane D): a mirror channel's last scan +// (transcripts/mirrors/<slug>.json, controller/mirrorScan.ts) — the totals +// both ways, the videos by status with their matches on the creator's +// channels, the creator's removed uploads in the window — and the Scan button. + +type Props = { + slug: string; + of: string[]; + scan: MirrorScanFile | null; +}; + +const PRESENCE_WORDS: Record<Presence, string> = { public: "public", gone: "removed", none: "none" }; + +const chip = (active: boolean) => + `text-xs rounded-full border px-2.5 py-1 ${ + active ? "border-info/30 bg-info-soft text-info" : "border-border bg-card hover:bg-muted" + }`; + +const videoHref = (channel: string, v: { id: string; dir?: string }) => + `/channels/${encodeURIComponent(channel)}/videos/${encodeURIComponent(v.dir ?? v.id)}`; + +const day = (d: string | null) => (d ? formatDate(d) : "undated"); + +export function MirrorStage({ slug, of, scan }: Props) { + const [status, setStatus] = useState<MirrorStatus | null>(null); + const rows = scan ? scan.videos.filter((v) => status === null || v.status === status) : []; + const t = scan?.totals; + return ( + <div className="flex flex-col gap-5"> + <div className="flex flex-col gap-2"> + <p className="text-sm text-muted-foreground" aria-label="mirror status line"> + Mirror of {of.join(", ")} + {scan ? ` · scanned ${scan.generatedAt.slice(0, 16).replace("T", " ")} UTC` : " · not scanned yet"} + {scan?.missing?.length ? ` · not in this corpus: ${scan.missing.join(", ")}` : ""} + </p> + <StreamActionLog + trigger={() => mirrorScanAction(slug)} + cancelAction={cancelJobAction} + buttonLabel={scan ? "Scan again" : "Scan"} + runningLabel="Scanning…" + label="Mirror scan" + /> + </div> + + {!scan || !t ? ( + <p className="text-sm" aria-label="mirror scan missing"> + No scan yet: nothing pairs this channel&apos;s videos with the creator&apos;s. + </p> + ) : ( + <> + <section aria-label="mirror totals" className="flex flex-col gap-2 text-sm"> + <p> + <span className="font-medium">{t.byStatus["only-copy"]}</span> of {t.videos} videos are the only copy + {scan.window ? ` (${formatDate(scan.window.from)} – ${formatDate(scan.window.to)})` : ""}. + </p> + <p aria-label="mirror creator removed"> + The creator removed {t.creatorRemoved.inWindow} videos in this window; the mirror holds{" "} + {t.creatorRemoved.held}. + </p> + <ul className="text-muted-foreground" aria-label="mirror presence by platform"> + {Object.entries(t.byPlatform).map(([p, n]) => ( + <li key={p}> + {p}: {n.public} public, {n.gone} removed, {n.none} none + </li> + ))} + </ul> + </section> + + <section aria-label="mirror videos" className="flex flex-col gap-2"> + <div className="flex flex-wrap gap-1.5" aria-label="mirror status filter"> + <button type="button" aria-pressed={status === null} onClick={() => setStatus(null)} className={chip(status === null)}> + All {t.videos} + </button> + {MIRROR_STATUSES.map((s) => ( + <button + key={s} + type="button" + aria-pressed={status === s} + onClick={() => setStatus(status === s ? null : s)} + className={chip(status === s)} + > + {MIRROR_STATUS_LABELS[s]} {t.byStatus[s]} + </button> + ))} + </div> + <table className="text-sm border-collapse"> + <thead> + <tr className="text-left text-muted-foreground"> + <th className="py-1 pr-4 font-medium">Recorded</th> + <th className="py-1 pr-4 font-medium">Video</th> + <th className="py-1 pr-4 font-medium">Status</th> + <th className="py-1 font-medium">On the creator&apos;s channels</th> + </tr> + </thead> + <tbody> + {rows.map((v) => { + const strong = v.matches.filter((m) => m.strong); + return ( + <tr key={v.id} className="border-t border-border align-top" aria-label={`mirror video ${v.id}`} data-status={v.status}> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{day(v.date)}</td> + <td className="py-1 pr-4"> + <Link href={videoHref(slug, v)} className="underline hover:no-underline"> + {v.title} + </Link> + {v.duration > 0 ? <span className="text-muted-foreground"> · {formatDuration(v.duration)}</span> : null} + </td> + <td className="py-1 pr-4 whitespace-nowrap"> + {MIRROR_STATUS_LABELS[v.status]} + <div className="text-xs text-muted-foreground"> + {Object.entries(v.presence) + .map(([p, pr]) => `${p} ${PRESENCE_WORDS[pr]}`) + .join(", ")} + </div> + </td> + <td className="py-1"> + {strong.length === 0 ? ( + <span className="text-muted-foreground">no match</span> + ) : ( + <ul> + {strong.map((m) => ( + <li key={`${m.channel}/${m.id}`}> + <Link href={videoHref(m.channel, m)} className="underline hover:no-underline"> + {m.title} + </Link>{" "} + <span className="text-muted-foreground"> + ({m.channel}, {formatDate(m.date)} + {m.gone ? `, ${m.gone === "deleted" ? "deleted" : "private"}` : ""}) + </span> + </li> + ))} + </ul> + )} + </td> + </tr> + ); + })} + </tbody> + </table> + </section> + + <details aria-label="creator removed in window" className="text-sm"> + <summary className="cursor-pointer font-medium"> + The creator&apos;s removed videos in this window ({t.creatorRemoved.inWindow}) + </summary> + <table className="mt-2 border-collapse"> + <thead> + <tr className="text-left text-muted-foreground"> + <th className="py-1 pr-4 font-medium">Uploaded</th> + <th className="py-1 pr-4 font-medium">Video</th> + <th className="py-1 font-medium">Held by the mirror</th> + </tr> + </thead> + <tbody> + {scan.removed.map((r) => ( + <tr key={`${r.channel}/${r.id}`} className="border-t border-border align-top"> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{formatDate(r.date)}</td> + <td className="py-1 pr-4"> + <Link href={videoHref(r.channel, r)} className="underline hover:no-underline"> + {r.title} + </Link>{" "} + <span className="text-muted-foreground"> + ({r.channel}, {r.gone}) + </span> + </td> + <td className="py-1"> + {r.heldBy.length === 0 ? ( + <span className="text-muted-foreground">not held</span> + ) : ( + r.heldBy.map((id, i) => { + const v = scan.videos.find((x) => x.id === id); + return ( + <span key={id}> + {i > 0 ? ", " : ""} + <Link href={videoHref(slug, v ?? { id })} className="underline hover:no-underline"> + {id} + </Link> + </span> + ); + }) + )} + </td> + </tr> + ))} + </tbody> + </table> + </details> + </> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/mirrorActions.ts b/editor/app/channels/[slug]/mirrorActions.ts @@ -0,0 +1,22 @@ +"use server"; + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { enqueueMirrorScan } from "yt-dlp-transcript-common/controller/mirrorScan"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../lib/safeRevalidate"; + +// The mirror scan (release 31, lane D; controller/mirrorScan.ts) as a +// `mirror-scan` job: the Mirror stage's Scan button and `pnpm ops +// mirror-scan`. A scan that wrote its file revalidates the channel page. +export async function mirrorScanAction( + slug: string, + opts: { dryRun?: boolean } = {}, +): Promise<StreamActionResult> { + return enqueueMirrorScan( + { slug, ...(opts.dryRun ? { dryRun: true } : {}) }, + { + paths: getPaths(), + onDone: (s) => safeRevalidate([`/channels/${s}`]), + }, + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -95,6 +95,8 @@ import { TranscribeStage } from "./components/stages/TranscribeStage"; import { DigestStage } from "./components/stages/DigestStage"; import { SpeakersStage } from "./components/stages/SpeakersStage"; import { StorageStage } from "./components/stages/StorageStage"; +import { MirrorStage } from "./components/stages/MirrorStage"; +import { readMirrorScan } from "yt-dlp-transcript-common/lib/mirrors/scanFile-server"; import { getOperation, backfillLaneOperations, @@ -314,6 +316,12 @@ export default async function ChannelDetailPage({ // now carries an entry for every catalog operation including digest, which has // its own station and its own queue key. const laneOperations = backfillLaneOperations(settings); + // A mirror channel's last scan (release 31, lane D): one small file, read + // only for a channel whose config has `mirror`. + const mirrorOf = config.mirror?.of ?? []; + const mirrorScan = config.mirror + ? await readMirrorScan(paths.transcriptsDir, slug) + : null; const stages = computeStageStatuses({ snapshot, failedVideoIds, @@ -322,6 +330,14 @@ export default async function ChannelDetailPage({ backfillEnabled: laneOperations.length > 0, backfillKindIds: laneOperations.map((k) => k.id), media, + mirrorScan: mirrorScan + ? { + videos: mirrorScan.totals.videos, + onlyCopy: mirrorScan.totals.byStatus["only-copy"], + removedInWindow: mirrorScan.totals.creatorRemoved.inWindow, + held: mirrorScan.totals.creatorRemoved.held, + } + : null, }); // THE MIDDLE COMES FROM THE REGISTRY, in OPERATION_GROUP_ORDER. Same array as @@ -343,6 +359,8 @@ export default async function ChannelDetailPage({ "cleanup", "diagnostics", "storage", + // Only on a channel that mirrors another's streams (config `mirror`). + ...(config.mirror ? (["mirror"] as const) : []), "danger", ]; @@ -654,6 +672,15 @@ export default async function ChannelDetailPage({ downloadDefaultQueueKey={platformDefaultQueueKey} /> ); + case "mirror": { + return ( + <MirrorStage + slug={slug} + of={mirrorOf} + scan={mirrorScan} + /> + ); + } case "storage": { // The free-space figure names the volume the media is on RIGHT NOW — // the platter for a relocated channel, the corpus disk otherwise — so diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -878,6 +878,14 @@ export function ChannelForm({ hint="For a channel that mirrors another's streams, whose upload dates are the copies'. Case-insensitive regex naming three groups — year, month (a number or an English month name) and day — e.g. (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}). The index reads each video's recorded date from its title, and coverage uses it before the upload date. A title it does not match keeps the upload date." /> <Field + label="Mirror of (channel slugs)" + name="mirrorOf" + state={state} + defaultValue={c?.mirror?.of.join(", ") ?? ""} + placeholder="(not a mirror)" + hint="For a channel that copies another creator's streams: the creator's channels here, by slug, separated by commas. The channel page then has a Mirror stage, where a scan pairs each video with the creator's and says which are the only copy left." + /> + <Field label="Cookies from browser" name="cookiesFromBrowser" state={state} diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -51,6 +51,7 @@ export const CHANNEL_FORM_VALUES = [ "downloadFilterExclude", "downloadFilterRejectedLivestreams", "recordedDateTitlePattern", + "mirrorOf", "audioCheckIntervalSeconds", "audioCheckMaxRollbacks", "audioCheckCopyTimeoutSeconds", @@ -116,6 +117,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { config.downloadFilter?.rejectedLivestreams, ); put(fd, "recordedDateTitlePattern", config.recordedDate?.titlePattern); + put(fd, "mirrorOf", config.mirror?.of.join(", ")); if (config.audioCheck?.enabled) { fd.set("audioCheckEnabled", "on"); putNum(fd, "audioCheckIntervalSeconds", config.audioCheck.intervalSeconds); diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -61,3 +61,27 @@ test("the ops patch sets and clears it over the channel's current form", () => { applyChannelFormPatch(back, { recordedDateTitlePattern: "" }); assert.equal("recordedDate" in parseChannelForm(back).config, false); }); + +// The Configure form's mirror field (release 31, lane D): slugs separated by +// commas or spaces into `mirror.of`, a value that is not a slug refused, the +// ops patch round trip, an empty value clearing it. + +test("the form writes mirror.of from slugs, de-duplicated", () => { + const { config } = parseChannelForm(form({ mirrorOf: " creator-yt, creator-rumble creator-yt " })); + assert.deepEqual(config.mirror, { of: ["creator-yt", "creator-rumble"] }); + assert.equal("mirror" in parseChannelForm(form({})).config, false); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("mirror")); + assert.throws(() => parseChannelForm(form({ mirrorOf: "creator-yt, ../etc" })), /Mirror of: "\.\.\/etc" is not a channel slug/); +}); + +test("the ops patch sets and clears mirrorOf over the channel's current form", () => { + validateChannelFormPatch({ mirrorOf: "creator-yt,creator-rumble" }); + const fd = channelConfigToFormData({ handling: "transcribe", name: "Example VODs" }); + applyChannelFormPatch(fd, { mirrorOf: "creator-yt,creator-rumble" }); + const set = parseChannelForm(fd).config; + assert.deepEqual(set.mirror, { of: ["creator-yt", "creator-rumble"] }); + const back = channelConfigToFormData(set); + assert.equal(back.get("mirrorOf"), "creator-yt, creator-rumble"); + applyChannelFormPatch(back, { mirrorOf: "" }); + assert.equal("mirror" in parseChannelForm(back).config, false); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -26,6 +26,7 @@ import { } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { downloadFilterPatternProblem } from "yt-dlp-transcript-common/lib/downloadFilters"; import { recordedDatePatternProblem } from "yt-dlp-transcript-common/lib/recordedDate"; +import { mirrorSlugs } from "yt-dlp-transcript-common/lib/mirrors/config"; import { isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; export type ParsedChannelForm = { @@ -60,6 +61,7 @@ export const CHANNEL_FORM_FIELDS = [ "audioCheck", "downloadFilter", "recordedDate", + "mirror", ] as const satisfies ReadonlyArray<keyof ChannelConfig>; // Maps FormData -> ChannelConfig. Throws on invalid input so the server @@ -291,6 +293,16 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (problem) throw new Error(`Recorded-date pattern ${problem}`); } + // A mirror's creator channels (release 31, lib/mirrors/config.ts): slugs + // separated by commas or spaces; one that is not a slug is refused here + // rather than silently dropped by the config reader. + const mirrorOfRaw = stringOrUndef(formData, "mirrorOf"); + const mirrorOf = mirrorOfRaw ? mirrorSlugs(mirrorOfRaw) : []; + if (mirrorOfRaw) { + const bad = mirrorOfRaw.split(/[\s,]+/).filter((x) => x && !mirrorSlugs([x]).length); + if (bad.length > 0) throw new Error(`Mirror of: ${bad.map((b) => `"${b}"`).join(", ")} is not a channel slug`); + } + const audioCheckEnabled = formData.get("audioCheckEnabled") != null; let audioCheck: AudioCheckConfig | undefined; if (audioCheckEnabled) { @@ -383,6 +395,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (recordedDateTitlePattern) { config.recordedDate = { titlePattern: recordedDateTitlePattern }; } + if (mirrorOf.length > 0) config.mirror = { of: mirrorOf }; return { name, slug, config }; } diff --git a/editor/e2e/mirror-panel.spec.ts b/editor/e2e/mirror-panel.spec.ts @@ -0,0 +1,64 @@ +import { test, expect } from "@playwright/test"; +import { join } from "node:path"; +// By relative path, as frame-scan.spec.ts imports the kit: plain .mjs. +import { MIRROR_SLUG, CREATOR_SLUG, writeMirrorCorpus } from "../../common/testing/mirrors/mirrorCorpus.mjs"; +import { resetData, testPaths } from "./helpers"; + +// The Mirror stage (release 31, lane D) on a synthetic mirror channel (the +// kit's VOD archive of a creator on two platforms): no scan yet and the Scan +// button, the mirror-scan job, then the totals both ways, the status filter, +// the rows linking the creator's copies. A channel with no `mirror` has no +// Mirror stage. + +test("Mirror stage: Scan enqueues mirror-scan; the totals, the filter, the rows", async ({ page }) => { + test.setTimeout(120_000); + await resetData("empty"); + await writeMirrorCorpus(join(testPaths().transcriptsDir, "channels")); + + await page.goto(`/channels/${MIRROR_SLUG}?stage=mirror`); + const stage = page.getByRole("region", { name: "Mirror stage" }); + await expect(stage.getByLabel("mirror scan missing")).toBeVisible(); + await expect(page.getByLabel("Mirror stage summary")).toHaveText("Not scanned."); + await stage.getByRole("button", { name: "Scan", exact: true }).click(); + await expect(page.getByLabel("Mirror scan output")).toContainText("@@mirror-scan", { timeout: 60_000 }); + + await page.reload(); + await expect(page.getByLabel("Mirror stage summary")).toHaveText( + "3 of 6 videos the only copy; the mirror holds 2 of 3 the creator removed.", + ); + const totals = stage.getByLabel("mirror totals"); + await expect(totals).toContainText("3 of 6 videos are the only copy (2023-03-01 – 2023-03-20)."); + await expect(stage.getByLabel("mirror creator removed")).toHaveText( + "The creator removed 3 videos in this window; the mirror holds 2.", + ); + await expect(stage.getByLabel("mirror presence by platform")).toContainText("youtube: 1 public, 2 removed, 3 none"); + + const rows = stage.getByLabel("mirror videos").locator("tbody tr"); + await expect(rows).toHaveCount(6); + const filter = stage.getByLabel("mirror status filter"); + await filter.getByRole("button", { name: "Only copy 3" }).click(); + await expect(rows).toHaveCount(3); + await expect(stage.locator('tbody tr[data-status="only-copy"]')).toHaveCount(3); + await filter.getByRole("button", { name: "Never uploaded 1" }).click(); + await expect(rows).toHaveCount(1); + await expect(rows.first()).toHaveAttribute("aria-label", "mirror video vod-m5"); + await filter.getByRole("button", { name: "Creator deleted 1" }).click(); + const m2 = stage.getByLabel("mirror video vod-m2"); + await expect(m2.getByRole("link", { name: "Oven Lawsuit Explained And Toaster Recall", exact: true }).first()).toHaveAttribute( + "href", + `/channels/${CREATOR_SLUG}/videos/yt-s2`, + ); + await expect(m2).toContainText("deleted"); + await expect(m2.getByRole("link", { name: "Oven Lawsuit Explained And Toaster Recall", exact: true }).nth(1)).toHaveAttribute( + "href", + "/channels/synth-streamer-rumble/videos/v1abd-oven-lawsuit", + ); + await filter.getByRole("button", { name: "All 6" }).click(); + await expect(rows).toHaveCount(6); + await expect(stage.getByRole("button", { name: "Scan again", exact: true })).toBeVisible(); + + // A channel that is no mirror has no Mirror stage. + await page.goto(`/channels/${CREATOR_SLUG}`); + await expect(page.getByLabel("pipeline stages")).toBeVisible(); + await expect(page.getByLabel("Mirror stage tab")).toHaveCount(0); +}); diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -502,7 +502,10 @@ export function buildSweepInstructions( `implies them: a filtered scan reads only the shard pages that can hold ` + `a match, which is the difference between seconds and a minute per ` + `query — and it makes the answer narrower and more honest at the same ` + - `time.`, + `time. \`enumerate_matches\` alone also takes \`copies: "only-here"\`: ` + + `a MIRROR channel's videos that no creator platform still has public ` + + `(the mirror scan's only-copy status) — a local archive only; a ` + + `published site has no mirror data and refuses it.`, ); steps.push( diff --git a/mcp/src/mirrorCopies.test.ts b/mcp/src/mirrorCopies.test.ts @@ -0,0 +1,108 @@ +// The mirror scans in the MCP (release 31, lane D): get_video_metadata's +// `copies` line and enumerate_matches' `copies: "only-here"`, read from a +// local archive's transcripts/mirrors/; a published site has none and says so. +// Synthetic only: the draft corpus, with `synth-other` scanned as a mirror of +// `synth-kitchen`. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { matchMirror } from "yt-dlp-transcript-common/lib/mirrors/match"; +import { MIRROR_RULES, MIRROR_SCAN_FORMAT, MIRROR_SCAN_VERSION, type MirrorScanFile } from "yt-dlp-transcript-common/lib/mirrors/scanFile"; +import { writeMirrorScan } from "yt-dlp-transcript-common/lib/mirrors/scanFile-server"; +import { createCorpusTools, type CorpusTools } from "./callTool"; +import { COPIES_NOT_AVAILABLE, describeCopies, loadMirrorScans, onlyHereIds } from "./mirrorCopies"; +import { LocalSource, RemoteSource } from "./source"; + +let dir: string; +let transcripts: string; +let corpus: CorpusTools; +const savedEnv = process.env.TRANSCRIPTS_DIR; + +const rec = (id: string, title: string, uploadDate: string, gone: "deleted" | null = null) => ({ + id, + title, + uploadDate, + duration: 3600, + wasLive: true, + gone, +}); + +function scanFile(): MirrorScanFile { + const r = matchMirror({ + mirror: { + slug: "synth-other", + platform: "youtube", + records: [rec("flat-loaf-01", "The flat loaf", "20260112"), rec("mirror-pie-09", "Pie stream", "20260210")], + }, + creators: [ + { + slug: "synth-kitchen", + platform: "youtube", + records: [rec("bread-day-01", "Bread day", "20260105"), rec("pie-stream-02", "Pie stream", "20260210", "deleted")], + }, + ], + }); + return { + format: MIRROR_SCAN_FORMAT, + version: MIRROR_SCAN_VERSION, + mirror: "synth-other", + of: ["synth-kitchen"], + generatedAt: "2026-10-16T00:00:00.000Z", + rules: { ...MIRROR_RULES }, + ...r, + }; +} + +before(async () => { + dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "mcp-mirrors-"))); + transcripts = await mkdtemp(path.join(os.tmpdir(), "mcp-mirrors-transcripts-")); + process.env.TRANSCRIPTS_DIR = transcripts; + await writeMirrorScan(transcripts, scanFile()); + corpus = await createCorpusTools({ source: `local:${dir}` }); +}); + +after(async () => { + if (savedEnv === undefined) delete process.env.TRANSCRIPTS_DIR; + else process.env.TRANSCRIPTS_DIR = savedEnv; + await corpus.close(); + await rm(dir, { recursive: true, force: true }); + await rm(transcripts, { recursive: true, force: true }); +}); + +test("the scans: read for a local source only", async () => { + const local = await loadMirrorScans(new LocalSource(dir), transcripts); + assert.equal(local?.length, 1); + assert.equal(await loadMirrorScans(new RemoteSource("https://example.invalid"), transcripts), null); + assert.deepEqual(onlyHereIds(local!), { ids: ["flat-loaf-01", "mirror-pie-09"], channels: ["synth-other"] }); +}); + +test("the copies line: a mirror video, a creator's video held, nothing known, remote", () => { + const scans = [scanFile()]; + assert.equal(describeCopies(scans, "synth-other", "flat-loaf-01"), "- copies: a MIRROR copy — only copy; the creator's copies: none found"); + assert.equal(describeCopies(scans, "synth-other", "mirror-pie-09"), "- copies: a MIRROR copy — only copy; the creator's copies: pie-stream-02 (synth-kitchen, deleted)"); + assert.equal(describeCopies(scans, "synth-kitchen", "pie-stream-02"), "- copies: this video is deleted on its platform; a mirror holds it: mirror-pie-09 (synth-other)"); + assert.equal(describeCopies(scans, "synth-kitchen", "bread-day-01"), ""); + assert.equal(describeCopies(null, "synth-kitchen", "bread-day-01"), `- copies: ${COPIES_NOT_AVAILABLE}`); +}); + +test("get_video_metadata carries the copies line", async () => { + const text = await corpus.call("get_video_metadata", { video_id: "flat-loaf-01" }); + assert.match(text, /- copies: a MIRROR copy — only copy; the creator's copies: none found/); + const other = await corpus.call("get_video_metadata", { video_id: "bread-day-01" }); + assert.doesNotMatch(other, /copies:/); +}); + +test("enumerate_matches copies: only-here keeps the only-copy mirror videos", async () => { + const all = await corpus.call("enumerate_matches", { query: ".", regex: true }); + assert.match(all, /bread-day-01/); + const only = await corpus.call("enumerate_matches", { query: ".", regex: true, copies: "only-here" }); + assert.deepEqual([...only.matchAll(/^- ([^ |]+) \| /gm)].map((m) => m[1]), ["flat-loaf-01"]); + assert.match(only, /copies: only-here — 2 mirror video\(s\) that are the only copy, from 1 mirror scan\(s\)/); + const none = await corpus.call("enumerate_matches", { query: ".", regex: true, copies: "only-here", ids: ["bread-day-01"] }); + assert.match(none, /^No matches/); + await assert.rejects(corpus.call("enumerate_matches", { query: ".", copies: "everywhere" }), /copies must be "only-here"/); +}); diff --git a/mcp/src/mirrorCopies.ts b/mcp/src/mirrorCopies.ts @@ -0,0 +1,57 @@ +// A video's COPIES as the mirror scans see them (release 31, lane D): +// `transcripts/mirrors/<slug>.json` (lib/mirrors/scanFile.ts), written by the +// editor's mirror scan. Mirror data is PRIVATE — no published site carries it — +// so only a LOCAL source reads it (the archive's own `transcripts/`, i.e. +// TRANSCRIPTS_DIR or the checkout's); a remote or hub source answers "not +// available" rather than guessing. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { listMirrorScans } from "yt-dlp-transcript-common/lib/mirrors/scanFile-server"; +import { copiesIndex, type MirrorScanFile, type VideoCopies } from "yt-dlp-transcript-common/lib/mirrors/scanFile"; +import { MIRROR_STATUS_LABELS } from "yt-dlp-transcript-common/lib/mirrors/match"; +import { LocalSource, type ShardSource } from "./source"; + +export const COPIES_NOT_AVAILABLE = + "not available: mirror scans are local-only (no published site carries them) — ask a local archive's MCP (--local)"; + +// The scans, or null when this source cannot have them (not local). +export async function loadMirrorScans( + source: ShardSource, + transcriptsDir: string = getPaths().transcriptsDir, +): Promise<MirrorScanFile[] | null> { + if (!(source instanceof LocalSource)) return null; + return listMirrorScans(transcriptsDir).catch(() => []); +} + +// The `copies` line of get_video_metadata, or "" when the scans say nothing of +// this video. +export function describeCopies(scans: MirrorScanFile[] | null, channel: string, id: string): string { + if (scans === null) return `- copies: ${COPIES_NOT_AVAILABLE}`; + const c: VideoCopies | undefined = copiesIndex(scans).get(`${channel}/${id}`); + if (!c) return ""; + if (c.role === "mirror") { + const theirs = c.matches.length + ? c.matches.map((m) => `${m.id} (${m.channel}${m.gone ? `, ${m.gone}` : ""})`).join(", ") + : "none found"; + return `- copies: a MIRROR copy — ${MIRROR_STATUS_LABELS[c.status].toLowerCase()}; the creator's copies: ${theirs}`; + } + const held = c.copies.map((x) => `${x.id} (${x.mirror})`).join(", "); + return c.gone + ? `- copies: this video is ${c.gone} on its platform; a mirror holds it: ${held}` + : `- copies: a mirror holds a copy: ${held}`; +} + +// The record ids of mirror videos that are the only copy (status only-copy), +// with the mirror channels they are on. +export function onlyHereIds(scans: MirrorScanFile[]): { ids: string[]; channels: string[] } { + const ids: string[] = []; + const channels = new Set<string>(); + for (const f of scans) { + for (const v of f.videos) { + if (v.status !== "only-copy") continue; + ids.push(v.id); + channels.add(f.mirror); + } + } + return { ids, channels: [...channels].sort() }; +} diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -5,6 +5,7 @@ import { type Tool, } from "@modelcontextprotocol/server"; import { salvageCaveat } from "yt-dlp-transcript-common/lib/salvageMark"; +import { COPIES_NOT_AVAILABLE, describeCopies, loadMirrorScans, onlyHereIds } from "./mirrorCopies"; import { transcriptToMarkdown } from "yt-dlp-transcript-common/lib/transcriptToMarkdown"; import { formatDate, formatDuration } from "yt-dlp-transcript-common/lib/format"; import { manifestHasDigest } from "yt-dlp-transcript-common/lib/digests"; @@ -588,6 +589,15 @@ export const TOOLS: Tool[] = [ "holding them are read, so the scan is bounded by the ids rather " + "than the scope. The footer says how many of them the scope holds.", }, + copies: { + type: "string", + enum: ["only-here"], + description: + "Optional: \"only-here\" keeps only a MIRROR channel's videos that no " + + "creator platform still has public (the mirror scan's only-copy " + + "status): what survives nowhere else. A local archive only — a " + + "published site carries no mirror data and refuses it.", + }, }, required: ["query"], additionalProperties: false, @@ -1771,6 +1781,21 @@ async function handleEnumerateMatches( source: ShardSource, args: Record<string, unknown>, ): Promise<ToolResult> { + // `copies: "only-here"` (release 31, mirrorCopies.ts): the scan narrowed to + // the mirror videos that are the only copy, by id. + let copiesNote = ""; + if (args.copies !== undefined) { + if (args.copies !== "only-here") return errorText('copies must be "only-here"'); + const scans = await loadMirrorScans(source); + if (scans === null) return errorText(`copies: "only-here" is ${COPIES_NOT_AVAILABLE}`); + const only = onlyHereIds(scans); + const asked = strArray(args.ids); + const ids = asked ? only.ids.filter((id) => asked.includes(id)) : only.ids; + copiesNote = `copies: only-here — ${only.ids.length} mirror video(s) that are the only copy, from ${scans.length} mirror scan(s)`; + if (ids.length === 0) return text(`No matches for "${String(args.query ?? "").trim()}" (${copiesNote}).`); + const { copies: _copies, ...rest } = args; + args = { ...rest, ids, ...(rest.channels || rest.groups || rest.channel || rest.group ? {} : { channels: only.channels }) }; + } // The scan is enumerate.ts's, shared with umtool's Research page: this tool // only renders it. const e = await enumerate(source, args); @@ -1827,6 +1852,7 @@ async function handleEnumerateMatches( (prunedNote ? `; ${prunedNote}` : "") + (dupNote ? `; ${dupNote}` : "") + (idsNote ? `; ${idsNote}` : "") + + (copiesNote ? `; ${copiesNote}` : "") + (scopeNote ? `; ${scopeNote}` : "") + (filterNote ? `; ${filterNote}` : "") + (postsNote ? `; ${postsNote}` : "") + @@ -2408,6 +2434,9 @@ async function handleGetMetadata( // as the caveat it is whatever the stats layer says. if (found.record.salvaged) lines.push(`- ${salvageCaveat(found.record.salvaged)}`); + // ── transcripts/mirrors/ (local only) ── + lines.push(describeCopies(await loadMirrorScans(source), found.ch.slug, found.record.id)); + // ── duplicates.json ── lines.push(await describeOtherCopies(source, slug)); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9780,3 +9780,47 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri only when a clip declares it. compose-chrome `--region stats` → `chrome/stats/`, `chrome/stats-frames/` (keyed, windowable); the build lays it after the stamps (`statsRegion`); `verify-build` fails on a declared clip missing from the schedule's `stats` or a missing/short `stats-frames` (pruned counts read from `pruned.json`). + +## Release 31 lane D: a mirror channel and the creator it copies (verified 2026-10-16, branch `r31/mirrors`) + +- **Config `mirror: {of: string[]}`** (`lib/mirrors/config.ts` `coerceMirrorConfig`): the creator's channel slugs, + trimmed, de-duplicated, invalid ones dropped, an empty list drops the key. Written by the Configure form's + `mirrorOf` field (commas or spaces; a value that is not a slug is refused) and so by `ops channel-config` + `{"patch": {"mirrorOf": "a, b"}}`. CHANNEL.md documents it (nested table `mirror`). +- **The matcher** (`lib/mirrors/match.ts`, pure): a mirror video is dated by `contentDate` (recordedDate, else + uploadDate); a creator video is a candidate when its date is `MIRROR_DAYS_BEFORE` (1) before to `MIRROR_DAYS_AFTER` + (2) after; it matches by `title` (word Jaccard ≥ 0.25), `title-duration` (≥ 0.12 and durations within 25 % of the + mirror's) or `live-duration` (durations agree, creator `wasLive` and > 3000 s). Words: lowercase `[a-z0-9']+`, one + letter and `MIRROR_STOP_WORDS` dropped; the mirror's side is its TOPIC (`mirrorTopic`: the title after the date its + recorded-date rule reads, else before it, else whole). STRONG = score (Jaccard to 2 dp) ≥ 0.5, or ≥ 0.25 with + durations — only strong matches decide anything. `presence` per creator PLATFORM (public | gone | none) → status: + `only-copy` (no platform public) > `creator-deleted` (one gone, another public) > `never-uploaded` (one none, rest + public) > `creator-public`. The other way: creator videos that are gone with a date in the mirror's window (first to + last dated mirror video), `heldBy` = mirror videos that strongly match them. The thresholds are the research + scripts' (`~/reports/quartering-cornbreadman/match.py`, `status.py`); wasLive is the record's `isLivestream`. +- **The scan** (`controller/mirrorScan.ts`; job kind `mirror-scan`, needsText, queue `mirror-scan`; `pnpm ops + mirror-scan {slug, dryRun?}`; the editor's `mirrorScanAction`): records from the index — `mtimes` range `[slug]` + gives each data dir's `indexKey`, `sums` its summary — and a dir the index has not seen off disk (`summarize`); a + missing recordedDate is derived from the channel's rule (so a scan is right before the index rebuild); gone = + `sourceGoneState` on the creator's dirs dated within the window ± the day margins only. Refused before any job + without `mirror.of` (or when none of its channels exists); a missing creator slug is skipped and listed in + `missing`. The log ends `@@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, + byPlatform, creatorRemoved}`. +- **`transcripts/mirrors/<slug>.json`** (`lib/mirrors/scanFile.ts`, `scanFile-server.ts`): `{format: + "archilyzer-mirror-scan", version: 1, mirror, of, missing?, generatedAt, jobId?, rules, window, platforms + (creator slug → platform), totals: {videos, dated, matched, byStatus, byPlatform: {<platform>: {public, gone, + none}}, creatorRemoved: {inWindow, held, byChannel}}, videos: [{id, dir?, title, date, recordedDate?, duration, + status, presence, matches: [{channel, id, dir?, title, date, duration, wasLive, rule, score, durationAgrees, strong, + gone?}]}], removed: [{channel, id, dir?, title, date, duration, gone, heldBy}]}`, written atomically. `dir` is set + only when the data dir is not the record id (Rumble). PRIVATE: nothing in `export/`, `common/publish/` or the index + build reads `transcripts/mirrors/`. +- **The editor**: stage `mirror` (StageId; `computeStageStatuses` `mirrorScan` input; `mirror-scan` → `mirror` in + JOB_KIND_TO_STAGE), listed only for a channel with `mirror` (`?stage=mirror`). `MirrorStage`: the status line, Scan + / Scan again (`Mirror scan output`), totals (`mirror totals`, `mirror creator removed`, `mirror presence by + platform`), the status filter (`mirror status filter`, chips "Only copy N" …), rows `mirror video <id>` with + `data-status`, the removed list in a `<details>`. +- **The MCP** (`mcp/src/mirrorCopies.ts`): only a `LocalSource` reads the scans (`getPaths().transcriptsDir`, i.e. + TRANSCRIPTS_DIR or the checkout's `transcripts/`); a remote or hub source answers `COPIES_NOT_AVAILABLE`. + `get_video_metadata` adds a `- copies:` line (`copiesIndex`: a mirror video's status and the creator's strong + matches; a creator video held by a mirror, and whether it is gone); `enumerate_matches` `copies: "only-here"` + restricts the scan to the only-copy mirror videos by id (to the mirror channels unless the call scopes itself). diff --git a/plans/release-31/mirrors.md b/plans/release-31/mirrors.md @@ -0,0 +1,94 @@ +# Release 31, lane D — a mirror channel and the creator it copies (as shipped) + +Branch `r31/mirrors` from `main` `3ef1b558` (`main` `c9ec3bc8`, lane C, merged in before the final gates). Brief: +`r31d-brief.md` (the plan of record for this lane). FACTS: "Release 31 lane D: a mirror channel and the creator it +copies". + +## What and why + +A channel that MIRRORS another creator's streams (a VOD archive on another platform) was invisible as one: the +duplicate finder clusters only short videos, so a 1–5 h stream never folds with its original, and nothing said which +of the mirror's videos survive nowhere else, or which of the creator's removed videos the mirror still holds. The +research that answered it once did so by hand, in two scripts whose counts did not reconcile. This lane makes it one +source, both directions. + +- **Config `mirror: {of}`** (`lib/mirrors/config.ts`): the creator's channel slugs (every platform). Declared in the + channel schema (drop-invalid like its siblings; CHANNEL.md regenerated), written by the Configure form's + "Mirror of (channel slugs)" field and so by `ops channel-config` `{"patch": {"mirrorOf": "a, b"}}` (the route's + allowlist is the form's value list; `mirrorOf` added). +- **The matcher** (`lib/mirrors/match.ts`, pure, every threshold a named constant): the research's rules + (`match.py`) for a match and its strong cut (`status.py`), over records dated by recorded date else upload date, + with the mirror's title reduced to its topic (after the date the recorded-date rule reads). Per mirror video: every + match (rule, score, strong, gone), `presence` per creator platform, and the status `only-copy` | `creator-deleted` + | `never-uploaded` | `creator-public` (defined in the module doc and FACTS). The other way: the creator's gone + uploads inside the mirror's window and the mirror videos that hold them — from the SAME strong matches, so the two + directions reconcile by construction. +- **The scan** (`controller/mirrorScan.ts`, job kind `mirror-scan` (needsText) on its own queue, `pnpm ops mirror-scan + {slug, dryRun?}`): records from the index (`mtimes` → `sums`; a dir the index has not seen off disk), recorded + dates from the index or the channel's rule, the gone state through THE gone reading (`sourceGoneState`) only + where it can matter; `transcripts/mirrors/<slug>.json` written atomically (`archilyzer-mirror-scan` v1); a dry + run writes nothing; refused before any job without `mirror.of`. +- **The editor**: a **Mirror** stage on a channel with `mirror` only — the totals both ways, a filter per status, + each row linking the mirror video and the creator's copies (removed ones marked), the creator's removed videos in + the window with what holds them, Scan / Scan again; "No scan yet" with the button when the file is missing. The + stage summary is on the overview's switcher. +- **The MCP**: `get_video_metadata`'s `- copies:` line and `enumerate_matches`' `copies: "only-here"`, from the + scans on a LOCAL source; a remote or hub source says "not available" (`instructions.ts` names the filter). +- **Private**: the scan file is corpus-side only. Checked: nothing in `export/`, `common/publish/`, the index build or + the stats build reads `transcripts/mirrors/` (the only `readdir(transcriptsDir)` in publish is the + `duplicates*.json` listing; `reader-fs` lists a composed site's `transcripts/`, not the corpus). No new key reaches + a record, a page or a site. + +| Commit | What | +| --- | --- | +| `70bef53e` | common, editor: the `mirror` config key (schema, form field, CHANNEL.md), the matcher, the synthetic mirror corpus in the kit | +| `fb08bd35` | common, editor, scripts: the scan controller, the job kind, the scan file, the ops route and action, ops help, COMMANDS.md | +| `08d76737` | merge `main` `c9ec3bc8` (lane C) — clean, no conflicts | +| `ffec8a82` | common, editor: the Mirror stage, `e2e/mirror-panel.spec.ts` | +| `af67049b` | mcp: the copies line, `copies: "only-here"`, instructions | +| `c9201d97` | mcp: the filter's refusal asserted as a tool error | +| (this commit) | this record, FACTS, CHANGELOG | + +## Gates + +From the worktree root, every heavy step through the shared lock, on `08d76737` (main merged in) and after. + +- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before each commit (last on `08d76737` + with the UI and MCP changes in the tree). +- common 4379 → 4398/4398 (+19: `lib/mirrors/match.test.ts` 11, `lib/mirrors/config.test.ts` 2, + `controller/mirrorScan.test.ts` 6 — off disk, through the REAL `buildIndex`, the dry run, the refusals, the job). +- editor unit 320 → 322/322 (`parseChannelForm.test.ts` +2: the `mirrorOf` field and its ops patch). +- mcp 373 → 377/377 (`mirrorCopies.test.ts` 4: local/remote, the copies line, get_video_metadata, + `copies: "only-here"`). +- `pnpm run test:scripts` 1030 passed + 3 skipped (1033), unchanged (the ops CLI's new action is a list entry). +- `docs files --check`, `docs env --check`, `docs cli --check`, `settings example --check`: clean (CHANNEL.md, + COMMANDS.md regenerated). +- e2e (editor, one spec, through the lock): `mirror-panel.spec.ts` 1/1 passed (20.3 s; its start-mode build 102 s; + 173 s in all). +- A read-only run of the matcher over the real corpus (the scan's own readers, no write; the orchestrator's live + sequence is in the lane report) reproduced the research's forward figures exactly. + +## Rulings and calls + +- **The statuses are one exclusive partition, by platform presence** (only-copy > creator-deleted > never-uploaded > + creator-public). The brief's four names overlap as written (an only copy is also deleted or never uploaded); the + partition keeps a filter per status meaningful, and the file's `presence` and `totals.byPlatform` keep the + research's per-platform figures (YouTube public / removed / none, Rumble public). +- **`live-duration` uses the CREATOR's duration > 3000 s**, as `match.py` does (the brief's prose said the mirror's; + with durations within 25 % the difference is a hair). wasLive is the record's `isLivestream` (was_live, or + live_status was_live / is_live / is_upcoming) — `match.py` read live_status `was_live` only. +- **Strong is judged on the score rounded to two decimals**, as `status.py` did on `match.py`'s rounded `j`; the rules + themselves use the exact Jaccard. +- **Gone is the gone reading** (deleted or private, effective availability), not "anything but public": the research + counted unlisted, members-only, error probes and never-checked videos as not public. The counts move accordingly + (the report's prediction says by how much). +- **The removed window is the mirror's first to last dated video**, with no day margins; a removed upload is held + when a mirror video STRONGLY matches it (the research's held-gone used ±1 day and Jaccard > 0.3, a looser, + separate rule). +- **The scan derives a missing recorded date from the channel's rule itself**, so it is right before the index is + rebuilt for a new pattern (the index's own `recordedDate` wins when present). +- **The Mirror panel is a channel stage** (`?stage=mirror`), listed only for a mirror — the channel page's panels are + its stages. +- **The MCP reads the scans only for a local source**, from the archive's own `transcripts/` (TRANSCRIPTS_DIR or the + checkout's): a LocalSource is a composed site dir, but its ids are the corpus's, and mirror data exists nowhere + else. Remote or hub: "not available". diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -124,6 +124,8 @@ // 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 // pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}' // pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}' +// pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait +// pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait // pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait // pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}' // pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}' @@ -461,6 +463,10 @@ const ACTIONS = [ // frame-scan job on `frames` (API) or draft:local. evict removes the frame // cache, rederive works the derived timeline out again (no job, no model). "frame-scan", + // THE MIRROR SCAN (release 31): a mirror channel's videos paired with the + // creator's channels its config's mirror.of names ({slug, dryRun?}), into + // transcripts/mirrors/<slug>.json, as a mirror-scan job. + "mirror-scan", // RECURRING REPORTS (umtool R5): a living report or a dated series on a // cadence the editor keeps ({action: list | create | update | pause | // resume | delete | tick-now | reset-triage, …}); tick-now is a @@ -490,6 +496,9 @@ export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; // The same for a frame scan (FRAME_SCAN_RESULT_MARKER in // common/controller/frameScan.ts). export const FRAME_SCAN_RESULT_MARKER = "@@frame-scan "; +// The same for a mirror scan (MIRROR_SCAN_RESULT_MARKER in +// common/controller/mirrorScan.ts). +export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan "; // The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in // common/controller/remoteListing.ts). export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing "; @@ -719,6 +728,7 @@ export function parseArgs(argv) { ...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}), ...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}), ...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}), + ...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}), ...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}), wait, quiet, @@ -1026,7 +1036,9 @@ export function usage() { ' site; an unknown site id is refused), "excludeFromBuild" and', ' "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror\'s', ' recorded date: "patch": {"recordedDateTitlePattern": "<regex with named', - ' groups year, month, day>"} (CHANNEL.md, recordedDate).', + ' groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror\'s', + ' creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md,', + ' mirror; then mirror-scan).', "", 'site-config sets two keys of a site as its form does: {"siteId"} and any of', ' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s', @@ -1473,6 +1485,22 @@ export function usage() { " file, frames, kept, read, failed, readings, spentUsd, totalUsd, events,", " tournaments, flags, stopped?}.", "", + 'mirror-scan pairs a mirror channel with the creator it copies: {"slug",', + ' "dryRun"?} -> {jobId}. The channel\'s config names the creator\'s channels', + ' (mirror.of; channel-config\'s "mirrorOf"); refused without them. Each of', + " the mirror's videos, dated by its recorded date (else its upload date), is", + " matched with the creator's videos uploaded one day before to two after, by", + " title words and duration (the index's records; no media, no network); per", + " video the matches and a status: only-copy (no creator platform has it", + " public), creator-deleted (removed on one platform, public on another),", + " never-uploaded (missing on one platform, public on the rest) or", + " creator-public. The other way: the creator's removed (deleted or private)", + " uploads dated inside the mirror's window, and which the mirror holds.", + " Written to transcripts/mirrors/<slug>.json (private: never published); the", + " channel page's Mirror stage shows it. dryRun writes nothing. The log ends", + " with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos,", + " matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}.", + "", 'report-schedule keeps a recurring report on a cadence the editor ticks:', ' {"action": "list" | "create" | "update" | "pause" | "resume" | "delete" |', ' "tick-now" | "reset-triage" | "learn" | "unlearn" | "promote-alias", …}.',