commit 32ea4b5cfa22c9fe4582746733a2b838df25221d
parent d6d29d60bad863aa276363d49c37dc6ed79e4f41
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 01:53:19 -0400
common, editor, scripts: the mirror scan — a `mirror-scan` job, `pnpm ops mirror-scan`, transcripts/mirrors/<slug>.json (release 31 D)
controller/mirrorScan.ts reads the mirror and its `mirror.of` channels cheaply
— each data dir's summary from the index (the `mtimes` range gives the index
key, `sums` the record), a dir the index has not seen off its
metadata.info.json — fills a missing recorded date from the channel's rule,
reads the creator's gone state through sourceGoneState only where a match or
the removed list can reach, runs the matcher and writes
`transcripts/mirrors/<slug>.json` atomically (archilyzer-mirror-scan v1: of,
missing?, rules, window, platforms, totals both ways, videos with matches and
status, removed uploads with heldBy). dryRun writes nothing. Refused before
any job for a channel with no mirror.of. The job kind is `mirror-scan`
(needsText) on its own queue; the log ends `@@mirror-scan {…}`, which
`pnpm ops mirror-scan --wait` prints. lib/mirrors/scanFile.ts has the shape
and `copiesIndex` (a video's copies across scans). COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 733 insertions(+), 2 deletions(-)
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": "<regex with named groups year, month, day>"} (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": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (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"?} -> {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"?: \["<article>"\], "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)} -> {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/<run>/ (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"?} -> {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.<profile>.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"?} -> {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}}. | `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"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `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
@@ -994,6 +994,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/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/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]/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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -122,6 +122,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}'
@@ -458,6 +460,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
@@ -487,6 +493,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 ";
@@ -716,6 +725,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,
@@ -1023,7 +1033,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',
@@ -1453,6 +1465,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", …}.',