commit 4a865d047927fbca14a94a04803935fcfdeece6a
parent b08a6ca150b3d78710efa3bbef483b83bf9e1c66
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 01:43:39 -0500
copies: source groups, the copies scan, and the lanes skip or hold a copy
A source group (settings.sourceGroups, empty by default) is an ordered
list of channels that archive the same recordings, the preferred source
first. The copies scan pairs the members' videos by recorded date and
runtime, then by their words where both have them (the largest set of
consistent phrase offsets, never the match count), into
transcripts/copies/<group>.json with each pair's link (confirmed by text,
metadata only, partial) and its evidence. It is idempotent: firstSeenAt
is carried and an unchanged scan does not rewrite the file.
The transcription and Speakers lanes, in the runner tick and in
computeLeafPending alike, skip a text-confirmed copy whose other copy's
work is done and readable on disk, and hold a metadata-only one with its
reason until the wait ends (default 7 days) or a release. The copy that
already has the work keeps it whatever the order; a preferred copy that
is not queued, in flight or done never blocks the other. A lane whose
only work is held copies says "copies-held". With no group nothing is
read and the lanes are unchanged. Downloads, files, records and the
published sites are untouched; no time is mapped between copies.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
19 files changed, 2210 insertions(+), 3 deletions(-)
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -109,6 +109,8 @@ import {
} from "./laneWaybackAuto";
import { ChatBacklogLane } from "./laneChatBacklog";
import { isGateHeld } from "../lib/pauseGates";
+import { copyHoldsForLane } from "./copiesLane";
+import { summarizeCopyHolds, type CopyHoldSummary } from "../lib/copies/laneHold";
import {
inspectChannelMedia,
markerHoldsText,
@@ -282,6 +284,11 @@ export type AutoRunnerIdleReason =
| "engine-unreachable"
// There is genuinely nothing to do.
| "no-pending"
+ // Every pending video is a copy of a recording another member of its
+ // source group has done or will do (settings.sourceGroups): skipped or held,
+ // each with its reason in the lane's pending view (`copies`) and in
+ // `pnpm ops get copies`. Distinct from no-pending, which would hide them.
+ | "copies-held"
// Work exists but every path to it is at a maxWorkers ceiling (a node cap, or
// the per-platform one-download-at-a-time gate).
| "capped";
@@ -613,6 +620,38 @@ export function makeFocusHoldReporter(
};
}
+// The once-per-change line a lane writes while it skips or holds copies for a
+// source group (lane cross-source-dupes). Keyed by the two counts, so the log
+// says when the set moves and is silent while it stands; nothing at all while
+// no group acts on the lane.
+export function copyHoldLine(kind: AutoQueueKind, summary: CopyHoldSummary | null): string | null {
+ if (!summary) return null;
+ if (summary.skipped === 0 && summary.held === 0) {
+ return `Auto-${kind}: no copy skipped or held for a source group.`;
+ }
+ return (
+ `Auto-${kind}: ${summary.skipped} cop${summary.skipped === 1 ? "y" : "ies"} skipped (another copy of the ` +
+ `recording has the work), ${summary.held} held (waiting, or matched by metadata only) — ` +
+ `each one's reason: pnpm ops get copies.`
+ );
+}
+
+export function makeCopyHoldReporter(
+ kind: AutoQueueKind,
+ onLog: (line: string) => void,
+): (summary: CopyHoldSummary | null) => void {
+ let state = "none";
+ return (summary) => {
+ const next = summary ? `${summary.skipped}/${summary.held}` : "none";
+ if (next === state) return;
+ const first = state === "none";
+ state = next;
+ const line = copyHoldLine(kind, summary);
+ // The first "nothing held" of a lane is not news.
+ if (line && !(first && summary && summary.skipped === 0 && summary.held === 0)) onLog(line);
+ };
+}
+
// ONCE PER STATE CHANGE, not once per tick. buildChannelWork runs on every
// scheduling tick of all four lanes and on a three-second status poll; logging a
// skip each time would write the same line thousands of times an hour and bury
@@ -1028,6 +1067,10 @@ export type LeafPending = {
recency: Record<string, RecencyKey>;
// What the policy would pick right now, or null when it would pick nothing.
nextUp: NextUpView | null;
+ // The copies this lane skipped or held for a source group (lane
+ // cross-source-dupes), each with its reason. ABSENT when no group acts on
+ // this lane, so the payload is what it was before groups existed.
+ copies?: CopyHoldSummary;
};
// Per-leaf pending (snapshot-derived) work for the status panel — what the
@@ -1096,6 +1139,20 @@ export async function computeLeafPending(
if (live && live.inFlight.size > 0) {
removeIds(pending, new Set(live.inFlight.keys()));
}
+ // THE SAME COPY HOLDS THE RUNNER APPLIES, in the same place (after the
+ // in-flight set): a copy skipped or held for its source group is not this
+ // lane's pending work, and the reason is carried beside the counts.
+ const copyHolds = await copyHoldsForLane({
+ kind,
+ paths,
+ settings,
+ pending,
+ owner,
+ inFlight: live ? live.inFlight.values() : [],
+ });
+ if (copyHolds) {
+ for (const leafId of Object.keys(pending)) pending[leafId] = copyHolds.pending[leafId] ?? [];
+ }
const counts: Record<string, number> = {};
const head: Record<string, string[]> = {};
@@ -1152,7 +1209,14 @@ export async function computeLeafPending(
};
}
- return { counts, head, owner: ownerOut, recency, nextUp };
+ return {
+ counts,
+ head,
+ owner: ownerOut,
+ recency,
+ nextUp,
+ ...(copyHolds ? { copies: summarizeCopyHolds(copyHolds.decisions) } : {}),
+ };
}
// Back-compat shim for callers that only ever wanted the counts.
@@ -1464,6 +1528,7 @@ async function runLoop(
// which the log needs to stay readable. Logged on each transition instead.
let diskIdle = false;
const reportFocusHold = makeFocusHoldReporter(kind, onLog);
+ const reportCopyHolds = makeCopyHoldReporter(kind, onLog);
// A graceful stop (the job record is gone after an e2e reset, or the policy was
// disabled) is modeled as a soft drain: stop picking, let in-flight finish.
@@ -1799,6 +1864,24 @@ async function runLoop(
// attribution-diarized is offered the same video.
removeIds(pending, new Set(live.inFlight.keys()));
dropCompleted(pending, root, laneOperations);
+ // A SOURCE GROUP'S COPIES (lane cross-source-dupes): a video another copy
+ // of the same recording has done is skipped, and one that waits on that
+ // copy is held, on the transcription and Speakers lanes only. Null — and
+ // nothing read — while no group acts on this lane, which is the lane as
+ // it always was. computeLeafPending applies the same call.
+ const pendingBeforeCopies = countPending(pending);
+ const copyHolds = await copyHoldsForLane({
+ kind,
+ paths,
+ settings,
+ pending,
+ owner,
+ inFlight: live.inFlight.values(),
+ });
+ if (copyHolds) {
+ for (const leafId of Object.keys(pending)) pending[leafId] = copyHolds.pending[leafId] ?? [];
+ }
+ reportCopyHolds(copyHolds ? summarizeCopyHolds(copyHolds.decisions) : null);
const pendingBeforeGates = countPending(pending);
// Say — ONCE per transition — whether a focus is holding this lane. Read off
// the `prio-*` leaf ids in the map just built, so it costs one pass over
@@ -2075,7 +2158,9 @@ async function runLoop(
// Attribute the idleness. Nothing pending at all is a different situation
// from work that exists but is unreachable, and both differ from work the
// platform gates just took away — the page says which.
- if (pendingBeforeGates === 0) live.idleReason = "no-pending";
+ if (pendingBeforeGates === 0) {
+ live.idleReason = pendingBeforeCopies > 0 ? "copies-held" : "no-pending";
+ }
else if (countPending(pending) === 0) {
live.idleReason = anyCooling
? "cooldown"
diff --git a/common/controller/copies.test.ts b/common/controller/copies.test.ts
@@ -0,0 +1,273 @@
+// The copies scan and the lanes' copy holds over a TEMP corpus (lane
+// cross-source-dupes, slice 1). Never the real corpus, never the network;
+// every channel, id and word is synthetic.
+import "./autoRunner.settings.fixture";
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { computeLeafPending } from "./autoRunner";
+import { copiesReport, copiesScanRefusal, parseCopiesReleaseBody, runCopiesScan } from "./copiesScan";
+import { resetCopiesLaneCacheForTest } from "./copiesLane";
+import { emptyAutoQueueState } from "../jobs/autoQueueState";
+import { bucketLaneOperationId } from "../lib/operations";
+import { sanitizeSourceGroups } from "../lib/copies/settings";
+import { copiesPath, updateCopiesReleases } from "../lib/copies/file-server";
+
+const CATCH_ALL_ROOT = {
+ id: "root",
+ mode: "strict",
+ weight: 1,
+ maxWorkers: null,
+ children: [{ id: "all", match: { type: "all" }, weight: 1, maxWorkers: null }],
+};
+
+function writeSettings(extra: Record<string, unknown>): void {
+ writeFileSync(
+ process.env.SETTINGS_FILE!,
+ JSON.stringify({ autoQueue: { transcription: { root: CATCH_ALL_ROOT }, download: { root: CATCH_ALL_ROOT } }, ...extra }),
+ );
+}
+
+const GROUP = { id: "stream-copies", channels: ["pref-chan", "mirror-chan"] };
+
+function corpus(): Paths {
+ const dir = mkdtempSync(path.join(tmpdir(), "copies-"));
+ const transcriptsDir = path.join(dir, "transcripts");
+ mkdirSync(transcriptsDir, { recursive: true });
+ return {
+ transcriptsDir,
+ channelsDir: path.join(transcriptsDir, "channels"),
+ sitesDir: path.join(transcriptsDir, "sites"),
+ jobsDir: path.join(dir, "jobs"),
+ lmdbPath: path.join(transcriptsDir, "index.mdb"),
+ autoQueueStateFile: path.join(dir, "auto-queue.json"),
+ } as Paths;
+}
+
+function rng(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 2 ** 32;
+ };
+}
+const VOCAB = Array.from({ length: 800 }, (_, i) => `w${i.toString(36)}x`);
+// 3000 nonsense words as 10-word cues, one word every 0.4 s, from `start`.
+function cues(seed: number, start = 0) {
+ const r = rng(seed);
+ const words = Array.from({ length: 3000 }, () => VOCAB[Math.floor(r() * VOCAB.length)]);
+ const out = [];
+ for (let i = 0; i < words.length; i += 10) {
+ out.push({ start: start + i * 0.4, end: start + (i + 10) * 0.4, text: words.slice(i, i + 10).join(" ") });
+ }
+ return out;
+}
+
+function channel(p: Paths, slug: string): void {
+ mkdirSync(path.join(p.channelsDir, slug, "data"), { recursive: true });
+ writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe" }));
+}
+
+function video(
+ p: Paths,
+ slug: string,
+ id: string,
+ o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean; audio?: boolean },
+): void {
+ const d = path.join(p.channelsDir, slug, "data", id);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "metadata.info.json"), JSON.stringify({ id, title: `Stream ${id}`, duration: o.duration, upload_date: o.date }));
+ if (o.cues) writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id, cues: o.cues }));
+ if (o.transcript) {
+ writeFileSync(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "synthetic words", offsets: { from: 0, to: 1000 } }] }));
+ }
+ if (o.audio) writeFileSync(path.join(d, "audio.mp3"), Buffer.alloc(1234));
+}
+
+function snapshot(p: Paths, slug: string, pending: string[]): void {
+ const opId = bucketLaneOperationId("transcription");
+ writeFileSync(
+ path.join(p.channelsDir, slug, "snapshot.json"),
+ JSON.stringify({
+ generatedAt: new Date().toISOString(),
+ totals: { videos: pending.length, downloaded: pending.length, transcribed: 0 },
+ buckets: { downloadedNoTranscript: pending, noTranscript: pending },
+ ...(opId ? { backfill: { [opId]: { ids: pending } } } : {}),
+ }),
+ );
+}
+
+// p1/m1 one recording with words on both sides (m1 has the transcript);
+// p2/m2 a date+runtime match where p2 has no words; p3/m3 the same day and
+// runtime but different words; m4 alone.
+function streams(p: Paths): void {
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ video(p, "pref-chan", "p1", { date: "20260301", duration: 7200, cues: cues(1), audio: true });
+ video(p, "mirror-chan", "m1", { date: "20260301", duration: 7260, cues: cues(1, 45), transcript: true, audio: true });
+ video(p, "pref-chan", "p2", { date: "20260305", duration: 7200 });
+ video(p, "mirror-chan", "m2", { date: "20260306", duration: 7230, cues: cues(2), audio: true });
+ video(p, "pref-chan", "p3", { date: "20260310", duration: 7200, cues: cues(3) });
+ video(p, "mirror-chan", "m3", { date: "20260310", duration: 7200, cues: cues(4), audio: true });
+ video(p, "mirror-chan", "m4", { date: "20260320", duration: 5000, audio: true });
+}
+
+const settingsWith = (groups: unknown[]) => ({ sourceGroups: sanitizeSourceGroups(groups) });
+
+test("the scan records how each pair was matched, and its evidence", async () => {
+ const p = corpus();
+ streams(p);
+ const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ assert.ok(out.path, "written");
+ const f = out.file;
+ assert.deepEqual(
+ f.pairs.map((x) => [x.key, x.link, x.evidence.kind]),
+ [
+ ["pref-chan/p1|mirror-chan/m1", "confirmed", "text"],
+ ["pref-chan/p2|mirror-chan/m2", "metadata", "metadata"],
+ ],
+ );
+ assert.equal(f.pairs[0].evidence.text?.verdict, "same");
+ assert.equal(f.pairs[0].evidence.text?.offsetMedianSeconds, 45);
+ assert.equal(f.totals.rejected, 1, "p3/m3: the words say different, whatever the runtime");
+ assert.deepEqual(f.totals.videos, { "pref-chan": 3, "mirror-chan": 4 });
+});
+
+test("the scan is idempotent: a second run changes nothing and keeps firstSeenAt", async () => {
+ const p = corpus();
+ streams(p);
+ const first = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-21T00:00:00Z") });
+ const file = copiesPath(p.transcriptsDir, "stream-copies");
+ const bytes = await readFile(file, "utf8");
+ const mtime = statSync(file).mtimeMs;
+ const second = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-22T00:00:00Z") });
+ assert.equal(second.unchanged, true);
+ assert.equal(second.path, undefined);
+ assert.equal(await readFile(file, "utf8"), bytes);
+ assert.equal(statSync(file).mtimeMs, mtime);
+ // A new pair joins with its own firstSeenAt; the old ones keep theirs.
+ video(p, "pref-chan", "p4", { date: "20260320", duration: 5010 });
+ const third = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-23T00:00:00Z") });
+ assert.deepEqual(
+ third.file.pairs.map((x) => [x.key, x.firstSeenAt]),
+ [
+ ["pref-chan/p1|mirror-chan/m1", first.file.generatedAt],
+ ["pref-chan/p2|mirror-chan/m2", first.file.generatedAt],
+ ["pref-chan/p4|mirror-chan/m4", "2026-03-23T00:00:00.000Z"],
+ ],
+ );
+});
+
+test("a dry run writes nothing; an unknown group or a group short of channels is refused", async () => {
+ const p = corpus();
+ streams(p);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true });
+ assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"]);
+ assert.match((await copiesScanRefusal(p, settingsWith([GROUP]), "nope"))!, /no source group "nope"/);
+ assert.match(
+ (await copiesScanRefusal(p, settingsWith([{ id: "short", channels: ["pref-chan", "not-here"] }]), "short"))!,
+ /needs two of its channels/,
+ );
+ assert.throws(() => parseCopiesReleaseBody({ group: "stream-copies", video: "../x" }), /not a video key/);
+});
+
+async function lane(p: Paths) {
+ resetCopiesLaneCacheForTest();
+ return computeLeafPending("transcription", p, { state: emptyAutoQueueState() });
+}
+
+const allPending = (r: Awaited<ReturnType<typeof lane>>) => Object.values(r.head).flat().sort();
+
+test("no group configured: the lane is exactly what it was (and a group with lanes off too)", async () => {
+ const p = corpus();
+ streams(p);
+ snapshot(p, "pref-chan", ["p1"]);
+ snapshot(p, "mirror-chan", ["m2", "m3", "m4"]);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ writeSettings({});
+ const before = await lane(p);
+ assert.equal("copies" in before, false, "no copies field on the payload");
+ assert.deepEqual(allPending(before), ["m2", "m3", "m4", "p1"]);
+ writeSettings({ sourceGroups: [] });
+ assert.deepEqual(await lane(p), before);
+ writeSettings({ sourceGroups: [{ ...GROUP, lanes: false }] });
+ assert.deepEqual(await lane(p), before, "the scan's file is there, but the group does not act");
+});
+
+test("with the group: the done copy's twin is skipped, the metadata match held, and both are reversible", async () => {
+ const p = corpus();
+ streams(p);
+ snapshot(p, "pref-chan", ["p1"]);
+ snapshot(p, "mirror-chan", ["m2", "m3", "m4"]);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ writeSettings({ sourceGroups: [GROUP] });
+ const r = await lane(p);
+ // p1: its fallback copy m1 has the transcript — not transcribed again.
+ // m2: probably p2 (date + runtime only), p2 not done — held, with the wait.
+ assert.deepEqual(allPending(r), ["m3", "m4"]);
+ assert.equal(r.copies?.skipped, 1);
+ assert.equal(r.copies?.held, 1);
+ const [skip, hold] = r.copies!.head;
+ assert.deepEqual([skip.channel, skip.id, skip.action, skip.link, skip.partner], ["pref-chan", "p1", "skip", "confirmed", "mirror-chan/m1"]);
+ assert.deepEqual([hold.channel, hold.id, hold.action, hold.link], ["mirror-chan", "m2", "hold", "metadata"]);
+ assert.ok(hold.until, "a metadata hold ends by itself");
+
+ // The release brings m2 back, and undoing it holds it again.
+ await updateCopiesReleases(p.transcriptsDir, "stream-copies", ["mirror-chan/m2"]);
+ assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4"]);
+ await updateCopiesReleases(p.transcriptsDir, "stream-copies", ["mirror-chan/m2"], { undo: true });
+ assert.deepEqual(allPending(await lane(p)), ["m3", "m4"]);
+
+ // Removing the group restores the lane; nothing was deleted on the way.
+ writeSettings({});
+ assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p1"]);
+ for (const [slug, id, name] of [["mirror-chan", "m1", "transcript.json"], ["pref-chan", "p1", "audio.mp3"], ["mirror-chan", "m2", "audio.mp3"]]) {
+ assert.ok(statSync(path.join(p.channelsDir, slug, "data", id, name)).isFile(), `${slug}/${id}/${name} kept`);
+ }
+});
+
+test("a confirmed copy is skipped only when the other copy's transcript is actually there and readable", async () => {
+ const p = corpus();
+ streams(p);
+ snapshot(p, "pref-chan", ["p1"]);
+ snapshot(p, "mirror-chan", []);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ writeSettings({ sourceGroups: [GROUP] });
+ // m1's transcript replaced by an unreadable one: p1 is not skipped.
+ writeFileSync(path.join(p.channelsDir, "mirror-chan", "data", "m1", "transcript.json"), "{not json");
+ const r = await lane(p);
+ assert.deepEqual(allPending(r), ["p1"]);
+ assert.equal(r.copies?.skipped, 0);
+});
+
+test("the report reads the scan, counts the duplicated copies' audio, and writes nothing", async () => {
+ const p = corpus();
+ streams(p);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ const before = readdirSync(path.join(p.transcriptsDir, "copies")).sort();
+ const [g] = await copiesReport(p, settingsWith([GROUP]), { pairs: true });
+ assert.equal(g.id, "stream-copies");
+ assert.deepEqual(g.pairs, { confirmed: 1, metadata: 1, partial: 0, withinChannel: 0 });
+ assert.deepEqual(g.duplicated, { seconds: 7260, byChannel: { "mirror-chan": { bytes: 1234, videos: 1 } } });
+ assert.equal(g.list?.length, 2);
+ assert.deepEqual(readdirSync(path.join(p.transcriptsDir, "copies")).sort(), before);
+});
+
+test("the runner says once when the copies it skips or holds change, and nothing with no group", async () => {
+ const { makeCopyHoldReporter } = await import("./autoRunner");
+ const lines: string[] = [];
+ const report = makeCopyHoldReporter("transcription", (l) => lines.push(l));
+ report(null);
+ report({ skipped: 0, held: 0, head: [] });
+ assert.deepEqual(lines, []);
+ report({ skipped: 2, held: 1, head: [] });
+ report({ skipped: 2, held: 1, head: [] });
+ assert.equal(lines.length, 1);
+ assert.match(lines[0], /^Auto-transcription: 2 copies skipped .* 1 held .*pnpm ops get copies/);
+ report({ skipped: 0, held: 0, head: [] });
+ assert.equal(lines.length, 2);
+});
diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts
@@ -0,0 +1,221 @@
+// THE LANES' SIDE OF A SOURCE GROUP (lane cross-source-dupes, slice 1): the
+// plan read from settings.sourceGroups and the scan's files, each other copy's
+// work read off its own files, and lib/copies/laneHold.ts applied. Called by
+// the runner tick AND by computeLeafPending (controller/autoRunner.ts), right
+// after the in-flight set and the completed set are taken out, so the panel's
+// numbers are the runner's numbers.
+//
+// NO GROUP, NO READ. `loadCopyPlan` answers null before touching the disk
+// when no group has `lanes` on, and the caller then leaves its pending lists
+// exactly as they were: no group configured is today's lane, byte for byte.
+//
+// Only the transcription and Speakers (backfill) lanes act on copies. The
+// download lane is untouched in slice 1 — the fallback copy keeps downloading
+// exactly as before, because it is the copy that survives a takedown — and so
+// is the digest lane.
+
+import path from "node:path";
+import { readFile, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { SiteSettings } from "../lib/settings";
+import type { AutoQueueKind } from "../lib/autoQueueTypes";
+import { mapConcurrent } from "../lib/concurrency";
+import { isVideoTranscribed, pickIndexTranscript, readVideoFiles } from "../lib/videoStatus";
+import { operationsForLane } from "../lib/operations";
+import { copyVideoKey } from "../lib/copies/file";
+import { copiesPath, copiesReleasesPath, readCopiesFile, readCopiesReleases } from "../lib/copies/file-server";
+import {
+ applyCopyHolds,
+ copyPartnersToRead,
+ type CopyHoldDecision,
+ type CopyPartner,
+ type CopyPlan,
+} from "../lib/copies/laneHold";
+import type { SourceGroup } from "../lib/copies/settings";
+
+export const COPY_LANES: readonly AutoQueueKind[] = ["transcription", "backfill"];
+
+export function laneActsOnCopies(kind: AutoQueueKind): boolean {
+ return COPY_LANES.includes(kind);
+}
+
+// What each lane calls its work, in a hold's reason.
+const LANE_WORK: Partial<Record<AutoQueueKind, string>> = {
+ transcription: "transcript",
+ backfill: "speakers work",
+};
+
+const DONE_TTL_MS = 60_000;
+const DONE_READ_CONCURRENCY = 16;
+
+type PlanCacheEntry = { key: string; plan: CopyPlan };
+let planCache: PlanCacheEntry | null = null;
+const doneCache = new Map<string, { at: number; done: boolean }>();
+
+export function resetCopiesLaneCacheForTest(): void {
+ planCache = null;
+ doneCache.clear();
+}
+
+async function mtimeOf(file: string): Promise<number> {
+ return stat(file).then(
+ (st) => st.mtimeMs,
+ () => -1,
+ );
+}
+
+/**
+ * The lanes' copy plan: every cross-channel confirmed or metadata-only pair of
+ * every group whose `lanes` is on, oriented by the group's CURRENT order, and
+ * the released videos. Null — with no I/O at all — when no group acts. A pair
+ * whose channel has since left its group is dropped, so removing a channel
+ * (or the group) restores the lane at once. Cached on the files' mtimes.
+ */
+export async function loadCopyPlan(paths: Paths, settings: Pick<SiteSettings, "sourceGroups">): Promise<CopyPlan | null> {
+ const groups: SourceGroup[] = (settings.sourceGroups ?? []).filter((g) => g.lanes);
+ if (groups.length === 0) return null;
+ const stamps = await Promise.all(
+ groups.map(async (g) => [
+ await mtimeOf(copiesPath(paths.transcriptsDir, g.id)),
+ await mtimeOf(copiesReleasesPath(paths.transcriptsDir, g.id)),
+ ]),
+ );
+ const key = JSON.stringify([paths.transcriptsDir, groups, stamps]);
+ if (planCache?.key === key) return planCache.plan;
+ const byVideo = new Map<string, CopyPartner[]>();
+ const released = new Set<string>();
+ const add = (k: string, p: CopyPartner) => {
+ const list = byVideo.get(k);
+ if (list) list.push(p);
+ else byVideo.set(k, [p]);
+ };
+ for (const g of groups) {
+ const [file, releases] = await Promise.all([
+ readCopiesFile(paths.transcriptsDir, g.id),
+ readCopiesReleases(paths.transcriptsDir, g.id),
+ ]);
+ for (const k of Object.keys(releases.released)) released.add(k);
+ if (!file) continue;
+ const rank = new Map(g.channels.map((c, i) => [c, i]));
+ for (const pair of file.pairs) {
+ if (pair.withinChannel || pair.a.channel === pair.b.channel) continue;
+ if (pair.link !== "confirmed" && pair.link !== "metadata") continue;
+ const ra = rank.get(pair.a.channel);
+ const rb = rank.get(pair.b.channel);
+ if (ra === undefined || rb === undefined) continue;
+ const common = { group: g.id, link: pair.link, firstSeenAt: pair.firstSeenAt, waitDays: g.waitDays };
+ add(copyVideoKey(pair.a.channel, pair.a.dir), { ...common, channel: pair.b.channel, dir: pair.b.dir, partnerPreferred: rb < ra });
+ add(copyVideoKey(pair.b.channel, pair.b.dir), { ...common, channel: pair.a.channel, dir: pair.a.dir, partnerPreferred: ra < rb });
+ }
+ }
+ const plan: CopyPlan = { byVideo, released };
+ planCache = { key, plan };
+ return plan;
+}
+
+// A transcript that is there and READS: the index transcript of the dir, a
+// non-empty file, and for whisper's JSON one that parses with segments.
+async function transcriptDone(videoDir: string): Promise<boolean> {
+ const files = await readVideoFiles(videoDir, { checkUntranscribable: true });
+ if (!isVideoTranscribed(files) || files.isUntranscribable) return false;
+ const t = pickIndexTranscript(files);
+ if (!t) return false;
+ try {
+ const text = await readFile(path.join(videoDir, t.filename), "utf8");
+ if (!text.trim()) return false;
+ if (t.kind === "whisper") {
+ const parsed = JSON.parse(text) as { transcription?: unknown };
+ return Array.isArray(parsed.transcription) && parsed.transcription.length > 0;
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// The Speakers lane's work, done: every one of the lane's operations has an
+// opinion on the video and at least one is `present`, none still to do.
+async function speakersDone(paths: Paths, settings: SiteSettings, channel: string, dir: string): Promise<boolean> {
+ const ops = operationsForLane("backfill", settings);
+ if (ops.length === 0) return false;
+ const videoDir = path.join(paths.channelsDir, channel, "data", dir);
+ const files = await readVideoFiles(videoDir, { checkUntranscribable: true });
+ let present = 0;
+ for (const op of ops) {
+ const target = await op.resolveTarget({ settings, paths, channelSlug: channel });
+ const state = await op.state({ videoDir, videoId: dir, files, target, settings });
+ if (state === "present") present++;
+ else if (state !== "not-applicable") return false;
+ }
+ return present > 0;
+}
+
+/** Whether each `<channel>/<dir>` has this lane's work done and readable (memoized a minute). */
+export async function readCopyDone(
+ kind: AutoQueueKind,
+ paths: Paths,
+ settings: SiteSettings,
+ keys: Iterable<string>,
+ now: number = Date.now(),
+): Promise<Map<string, boolean>> {
+ const list = [...keys];
+ const out = new Map<string, boolean>();
+ await mapConcurrent(list, DONE_READ_CONCURRENCY, async (k) => {
+ const cacheKey = `${kind}\u0000${paths.channelsDir}\u0000${k}`;
+ const hit = doneCache.get(cacheKey);
+ if (hit && now - hit.at < DONE_TTL_MS) {
+ out.set(k, hit.done);
+ return;
+ }
+ const slash = k.indexOf("/");
+ const channel = k.slice(0, slash);
+ const dir = k.slice(slash + 1);
+ let done = false;
+ try {
+ done =
+ kind === "transcription"
+ ? await transcriptDone(path.join(paths.channelsDir, channel, "data", dir))
+ : kind === "backfill"
+ ? await speakersDone(paths, settings, channel, dir)
+ : false;
+ } catch {
+ done = false;
+ }
+ doneCache.set(cacheKey, { at: now, done });
+ out.set(k, done);
+ });
+ return out;
+}
+
+/**
+ * The lane's pending lists with its copies skipped or held, or null when this
+ * lane does not act on copies or no group acts (the caller keeps its lists).
+ */
+export async function copyHoldsForLane(opts: {
+ kind: AutoQueueKind;
+ paths: Paths;
+ settings: SiteSettings;
+ pending: Record<string, string[]>;
+ owner: ReadonlyMap<string, string>;
+ inFlight: Iterable<{ videoId: string; channelSlug: string }>;
+ now?: number;
+}): Promise<{ pending: Record<string, string[]>; decisions: CopyHoldDecision[] } | null> {
+ if (!laneActsOnCopies(opts.kind)) return null;
+ const plan = await loadCopyPlan(opts.paths, opts.settings);
+ if (!plan || plan.byVideo.size === 0) return null;
+ const now = opts.now ?? Date.now();
+ const toRead = copyPartnersToRead(opts.pending, opts.owner, plan);
+ const done = await readCopyDone(opts.kind, opts.paths, opts.settings, toRead, now);
+ const inFlight = new Set<string>();
+ for (const u of opts.inFlight) inFlight.add(copyVideoKey(u.channelSlug, u.videoId));
+ return applyCopyHolds({
+ lane: opts.kind,
+ work: LANE_WORK[opts.kind] ?? "work",
+ pending: opts.pending,
+ owner: opts.owner,
+ plan,
+ inFlight,
+ done,
+ now,
+ });
+}
diff --git a/common/controller/copiesScan.ts b/common/controller/copiesScan.ts
@@ -0,0 +1,429 @@
+// THE COPIES SCAN (lane cross-source-dupes, slice 1): a source group's member
+// channels (settings.sourceGroups) paired video by video — recorded date and
+// runtime first, then the words where both copies have them
+// (lib/copies/match.ts) — into `transcripts/copies/<group>.json`
+// (lib/copies/file.ts). A `copies-scan` job, `pnpm ops copies-scan`.
+//
+// CHEAP AND OFFLINE: no media is opened and nothing is fetched. Each member's
+// records come from controller/mirrorScan.ts's reader (the index's summaries,
+// else metadata.info.json off disk, the channel's title rule for the recorded
+// date) behind each channel's text guard — an unmounted or moving drive is
+// refused, never read as an empty channel. The words are each video's
+// `transcript.cues.json`; a video without one has no text, and its pairs can
+// only be metadata-only.
+//
+// IDEMPOTENT: a pair keeps the `firstSeenAt` of the scan that first recorded
+// it, and a scan that finds exactly what the file already says does not
+// rewrite it. A dry run reads and matches the same and writes nothing.
+//
+// The report (`pnpm ops get copies`) is `copiesReport` below: read only.
+
+import path from "node:path";
+import { readdir, readFile, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { SiteSettings } from "../lib/settings";
+import { CUES_JSON_FILENAME } from "../lib/videoStatus";
+import { isRealAudioFile } from "../lib/mediaFiles";
+import { inspectChannelMedia } from "../lib/channelMedia";
+import { isMediaHeld } from "../lib/channelMediaHold";
+import { contentDate } from "../lib/mirrors/match";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { readChannelConfig } from "./channels";
+import { readChannelRecords } from "./mirrorScan";
+import {
+ classifyCandidate,
+ copyCandidates,
+ cuesToWords,
+ textEvidence,
+ type CopyRecord,
+ type TextEvidence,
+ type Word,
+} from "../lib/copies/match";
+import {
+ COPIES_FORMAT,
+ COPIES_VERSION,
+ copyPairKey,
+ type CopiesFile,
+ type CopiesTotals,
+ type CopyMember,
+ type CopyPairRecord,
+} from "../lib/copies/file";
+import { readCopiesFile, readCopiesReleases, writeCopiesFile } from "../lib/copies/file-server";
+import { SOURCE_GROUP_ID_RE, type SourceGroup } from "../lib/copies/settings";
+
+export const COPIES_SCAN_JOB_KIND = "copies-scan";
+// One scan at a time, machine-wide: each reads thousands of cue files.
+export const COPIES_SCAN_QUEUE = "copies-scan";
+export const COPIES_SCAN_RESULT_MARKER = "@@copies-scan ";
+export const COPIES_SCAN_BODY_KEYS = ["group", "dryRun"] as const;
+export const COPIES_RELEASE_BODY_KEYS = ["group", "video", "videos", "undo", "note"] as const;
+
+// How many videos' words are kept while a scan walks its candidates.
+const WORDS_CACHE = 16;
+
+function groupOf(settings: Pick<SiteSettings, "sourceGroups">, id: string): SourceGroup | null {
+ return (settings.sourceGroups ?? []).find((g) => g.id === id) ?? null;
+}
+
+// The refusal for a group that cannot be scanned, or null.
+export async function copiesScanRefusal(
+ paths: Paths,
+ settings: Pick<SiteSettings, "sourceGroups">,
+ id: string,
+): Promise<string | null> {
+ if (!SOURCE_GROUP_ID_RE.test(id)) return `not a source group id: ${JSON.stringify(id)}`;
+ const group = groupOf(settings, id);
+ if (!group) {
+ const known = (settings.sourceGroups ?? []).map((g) => g.id);
+ return (
+ `no source group "${id}" — settings.sourceGroups names ${known.join(", ") || "none"}; add one with ` +
+ `pnpm ops settings --json '{"patch":{"sourceGroups":[{"id":"${id}","channels":["<preferred-slug>","<fallback-slug>"]}]}}'`
+ );
+ }
+ const found = await Promise.all(group.channels.map(async (s) => ((await readChannelConfig(paths, s)) ? s : null)));
+ if (found.filter(Boolean).length < 2) {
+ return `source group "${id}" needs two of its channels in this corpus; it holds ${found.filter(Boolean).join(", ") || "none"} of ${group.channels.join(", ")}`;
+ }
+ return null;
+}
+
+type CuesFileShape = { cues?: { start: number; end?: number; text: string }[] };
+
+async function readWords(paths: Paths, channel: string, dir: string): Promise<Word[] | null> {
+ try {
+ const raw = JSON.parse(await readFile(path.join(paths.channelsDir, channel, "data", dir, CUES_JSON_FILENAME), "utf8")) as CuesFileShape;
+ return Array.isArray(raw.cues) ? cuesToWords(raw.cues) : null;
+ } catch {
+ return null;
+ }
+}
+
+function member(r: CopyRecord): CopyMember {
+ return { channel: r.channel, dir: r.dir, id: r.id, title: r.title, duration: r.duration, date: r.date };
+}
+
+export type CopiesScanOptions = {
+ dryRun?: boolean;
+ jobId?: string;
+ onLog?: (line: string) => void;
+ now?: () => Date;
+};
+
+export type CopiesScanOutcome = {
+ file: CopiesFile;
+ // Where it was written; absent on a dry run and when nothing changed.
+ path?: string;
+ unchanged: boolean;
+};
+
+// The file's content without the per-run stamps, for "did anything change".
+function contentOf(f: CopiesFile): string {
+ return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals]);
+}
+
+export async function runCopiesScan(
+ paths: Paths,
+ settings: Pick<SiteSettings, "sourceGroups">,
+ id: string,
+ opts: CopiesScanOptions = {},
+): Promise<CopiesScanOutcome> {
+ const log = opts.onLog ?? (() => {});
+ const refusal = await copiesScanRefusal(paths, settings, id);
+ if (refusal) throw new Error(refusal);
+ const group = groupOf(settings, id)!;
+ const now = (opts.now?.() ?? new Date()).toISOString();
+
+ const missing: string[] = [];
+ const records: CopyRecord[] = [];
+ const videos: Record<string, number> = {};
+ let undated = 0;
+ for (const slug of group.channels) {
+ if (!(await readChannelConfig(paths, slug))) {
+ missing.push(slug);
+ continue;
+ }
+ const c = await readChannelRecords(paths, slug);
+ videos[slug] = c.records.length;
+ for (const r of c.records) {
+ const date = contentDate(r);
+ if (!date) undated++;
+ records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date });
+ }
+ log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk)`);
+ }
+ if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`);
+
+ const candidates = copyCandidates(group, records);
+ log(`${candidates.length} candidate pairs dated within ${group.dateWindowDays} day(s)`);
+
+ // A small cache of words: candidates come grouped by their `a` side.
+ const cache = new Map<string, Word[] | null>();
+ const wordsOf = async (r: CopyRecord): Promise<Word[] | null> => {
+ const k = `${r.channel}/${r.dir}`;
+ if (cache.has(k)) {
+ const v = cache.get(k)!;
+ cache.delete(k);
+ cache.set(k, v);
+ return v;
+ }
+ const v = await readWords(paths, r.channel, r.dir);
+ cache.set(k, v);
+ if (cache.size > WORDS_CACHE) cache.delete(cache.keys().next().value!);
+ return v;
+ };
+
+ const previous = await readCopiesFile(paths.transcriptsDir, group.id);
+ const seen = new Map((previous?.pairs ?? []).map((p) => [p.key, p.firstSeenAt]));
+ const totals: CopiesTotals = {
+ videos,
+ undated,
+ candidates: candidates.length,
+ confirmed: 0,
+ metadata: 0,
+ partial: 0,
+ rejected: 0,
+ withinChannel: 0,
+ };
+ const pairs: CopyPairRecord[] = [];
+ for (const c of candidates) {
+ const [wa, wb] = [await wordsOf(c.a), await wordsOf(c.b)];
+ const text: TextEvidence | null = wa && wb ? textEvidence(wa, wb) : null;
+ const usable = text && text.verdict !== "no-text" ? text : null;
+ const link = classifyCandidate(c, usable);
+ if (!link) {
+ if (usable) totals.rejected++;
+ continue;
+ }
+ const key = copyPairKey(c.a, c.b);
+ const withinChannel = c.a.channel === c.b.channel;
+ totals[link]++;
+ if (withinChannel) totals.withinChannel++;
+ pairs.push({
+ key,
+ a: member(c.a),
+ b: member(c.b),
+ link,
+ withinChannel,
+ evidence: {
+ kind: usable ? "text" : "metadata",
+ dateDeltaDays: c.dateDeltaDays,
+ durationOk: c.durationOk,
+ ...(usable ? { text: usable } : {}),
+ },
+ firstSeenAt: seen.get(key) ?? now,
+ });
+ }
+ const file: CopiesFile = {
+ format: COPIES_FORMAT,
+ version: COPIES_VERSION,
+ group: group.id,
+ channels: [...group.channels],
+ ...(missing.length > 0 ? { missing } : {}),
+ generatedAt: now,
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ rules: {
+ dateWindowDays: group.dateWindowDays,
+ durationToleranceSeconds: group.durationToleranceSeconds,
+ durationToleranceRatio: group.durationToleranceRatio,
+ withinChannels: group.withinChannels,
+ },
+ pairs,
+ totals,
+ };
+ log(
+ `${totals.confirmed} confirmed by text, ${totals.metadata} metadata only, ${totals.partial} partial, ` +
+ `${totals.rejected} rejected by text${totals.withinChannel ? `; ${totals.withinChannel} inside one channel (report only)` : ""}`,
+ );
+ if (previous && contentOf(previous) === contentOf(file)) {
+ return { file: previous, unchanged: true };
+ }
+ if (opts.dryRun) return { file, unchanged: false };
+ return { file, path: await writeCopiesFile(paths.transcriptsDir, file), unchanged: false };
+}
+
+export function copiesScanSummary(out: CopiesScanOutcome, dryRun: boolean) {
+ const f = out.file;
+ return {
+ group: f.group,
+ dryRun,
+ unchanged: out.unchanged,
+ ...(out.path ? { file: out.path } : {}),
+ channels: f.channels,
+ ...(f.missing ? { missing: f.missing } : {}),
+ totals: f.totals,
+ };
+}
+
+export type CopiesScanBody = { group: string; dryRun: boolean };
+
+export function parseCopiesScanBody(raw: Record<string, unknown>): CopiesScanBody {
+ const group = typeof raw.group === "string" ? raw.group.trim() : "";
+ if (!group) throw new Error('"group" is required: a settings.sourceGroups id');
+ if (!SOURCE_GROUP_ID_RE.test(group)) throw new Error(`not a source group id: ${JSON.stringify(group)}`);
+ if (raw.dryRun !== undefined && typeof raw.dryRun !== "boolean") throw new Error('"dryRun" must be true or false');
+ return { group, dryRun: raw.dryRun === true };
+}
+
+// Enqueue a `copies-scan` job (refused before any job for an unknown group).
+export async function enqueueCopiesScan(
+ raw: Record<string, unknown>,
+ deps: { paths: Paths; settings: Pick<SiteSettings, "sourceGroups">; now?: () => Date },
+): Promise<StreamActionResult> {
+ let body: CopiesScanBody;
+ try {
+ body = parseCopiesScanBody(raw);
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ const refusal = await copiesScanRefusal(deps.paths, deps.settings, body.group);
+ if (refusal) return { ok: false, error: refusal };
+ return runManagedFunction({
+ kind: COPIES_SCAN_JOB_KIND,
+ queueKey: COPIES_SCAN_QUEUE,
+ paths: deps.paths,
+ network: false,
+ fn: async (onLog, _signal, _setProgress, ctx) => {
+ onLog(`copies scan of ${body.group}${body.dryRun ? " (dry run: nothing is written)" : ""}`);
+ const out = await runCopiesScan(deps.paths, deps.settings, body.group, {
+ dryRun: body.dryRun,
+ jobId: ctx.jobId,
+ onLog,
+ ...(deps.now ? { now: deps.now } : {}),
+ });
+ if (out.path) onLog(`wrote ${out.path}`);
+ else if (out.unchanged) onLog("nothing changed since the last scan; the file is left as it was");
+ onLog(`${COPIES_SCAN_RESULT_MARKER}${JSON.stringify(copiesScanSummary(out, body.dryRun))}`);
+ },
+ });
+}
+
+// --- The release: a person's word that a held or skipped copy runs ----------
+
+export type CopiesReleaseBody = { group: string; videos: string[]; undo: boolean; note?: string };
+
+const VIDEO_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[^/\s]{1,200}$/;
+
+export function parseCopiesReleaseBody(raw: Record<string, unknown>): CopiesReleaseBody {
+ const group = typeof raw.group === "string" ? raw.group.trim() : "";
+ if (!SOURCE_GROUP_ID_RE.test(group)) throw new Error('"group" is required: a settings.sourceGroups id');
+ const list: unknown[] = raw.videos !== undefined ? (Array.isArray(raw.videos) ? raw.videos : [null]) : raw.video !== undefined ? [raw.video] : [];
+ if (list.length === 0) throw new Error('"video" ("<channel>/<dir>") or "videos" ([…]) is required');
+ const videos: string[] = [];
+ for (const v of list) {
+ if (typeof v !== "string" || !VIDEO_KEY_RE.test(v.trim()) || v.includes("..")) {
+ throw new Error(`not a video key: ${JSON.stringify(v)} — "<channel>/<dir>", as the report names it`);
+ }
+ if (!videos.includes(v.trim())) videos.push(v.trim());
+ }
+ if (raw.undo !== undefined && typeof raw.undo !== "boolean") throw new Error('"undo" must be true or false');
+ if (raw.note !== undefined && typeof raw.note !== "string") throw new Error('"note" must be a string');
+ const note = typeof raw.note === "string" ? raw.note.trim().slice(0, 500) : "";
+ return { group, videos, undo: raw.undo === true, ...(note ? { note } : {}) };
+}
+
+// --- The report: read only --------------------------------------------------
+
+export type CopiesMemberBytes = { bytes: number | null; videos: number; heldBy?: string };
+
+export type CopiesGroupReport = {
+ id: string;
+ label: string;
+ channels: { slug: string; rank: number; inCorpus: boolean }[];
+ lanes: boolean;
+ waitDays: number;
+ scan: null | {
+ generatedAt: string;
+ jobId?: string;
+ totals: CopiesTotals;
+ missing?: string[];
+ };
+ // Cross-channel pairs the lanes act on, by link; inside-one-channel ones apart.
+ pairs: { confirmed: number; metadata: number; partial: number; withinChannel: number };
+ // What the non-preferred copies of confirmed cross-channel pairs hold: the
+ // seconds of recording and the audio bytes (through tier links), per channel.
+ // `bytes: null` with `heldBy` when the channel's media cannot be read now —
+ // never a 0 read off an unmounted drive.
+ duplicated: { seconds: number; byChannel: Record<string, CopiesMemberBytes> };
+ released: string[];
+ // With `pairs` asked for: every pair, as the file holds it.
+ list?: CopyPairRecord[];
+};
+
+async function audioBytesOf(dir: string): Promise<number> {
+ const names = await readdir(dir).catch(() => [] as string[]);
+ let total = 0;
+ for (const n of names) {
+ if (!isRealAudioFile(n)) continue;
+ total += await stat(path.join(dir, n)).then((s) => s.size, () => 0);
+ }
+ return total;
+}
+
+export async function copiesReport(
+ paths: Paths,
+ settings: Pick<SiteSettings, "sourceGroups">,
+ opts: { group?: string | null; pairs?: boolean } = {},
+): Promise<CopiesGroupReport[]> {
+ const groups = (settings.sourceGroups ?? []).filter((g) => !opts.group || g.id === opts.group);
+ const out: CopiesGroupReport[] = [];
+ for (const g of groups) {
+ const [file, releases] = await Promise.all([
+ readCopiesFile(paths.transcriptsDir, g.id),
+ readCopiesReleases(paths.transcriptsDir, g.id),
+ ]);
+ const channels = await Promise.all(
+ g.channels.map(async (slug, rank) => ({ slug, rank, inCorpus: !!(await readChannelConfig(paths, slug)) })),
+ );
+ const rank = new Map(g.channels.map((c, i) => [c, i]));
+ const pairs = { confirmed: 0, metadata: 0, partial: 0, withinChannel: 0 };
+ const copiesByChannel = new Map<string, Map<string, number>>();
+ for (const p of file?.pairs ?? []) {
+ if (p.withinChannel) {
+ pairs.withinChannel++;
+ continue;
+ }
+ pairs[p.link]++;
+ if (p.link !== "confirmed") continue;
+ const ra = rank.get(p.a.channel);
+ const rb = rank.get(p.b.channel);
+ if (ra === undefined || rb === undefined) continue;
+ const copy = ra <= rb ? p.b : p.a;
+ const m = copiesByChannel.get(copy.channel) ?? new Map<string, number>();
+ m.set(copy.dir, copy.duration);
+ copiesByChannel.set(copy.channel, m);
+ }
+ let seconds = 0;
+ const byChannel: Record<string, CopiesMemberBytes> = {};
+ for (const [slug, dirs] of copiesByChannel) {
+ for (const d of dirs.values()) seconds += d;
+ const location = await inspectChannelMedia(paths, slug).catch(() => null);
+ if (!location || isMediaHeld(location.status)) {
+ byChannel[slug] = { bytes: null, videos: dirs.size, heldBy: location?.status ?? "unreadable" };
+ continue;
+ }
+ let bytes = 0;
+ for (const dir of dirs.keys()) bytes += await audioBytesOf(path.join(paths.channelsDir, slug, "data", dir));
+ byChannel[slug] = { bytes, videos: dirs.size };
+ }
+ out.push({
+ id: g.id,
+ label: g.label,
+ channels,
+ lanes: g.lanes,
+ waitDays: g.waitDays,
+ scan: file
+ ? {
+ generatedAt: file.generatedAt,
+ ...(file.jobId ? { jobId: file.jobId } : {}),
+ totals: file.totals,
+ ...(file.missing ? { missing: file.missing } : {}),
+ }
+ : null,
+ pairs,
+ duplicated: { seconds, byChannel },
+ released: Object.keys(releases.released),
+ ...(opts.pairs ? { list: file?.pairs ?? [] } : {}),
+ });
+ }
+ return out;
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1429,6 +1429,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsText: true,
},
+ // The copies scan (lane cross-source-dupes, slice 1): a source group's
+ // member channels (settings.sourceGroups) paired by recorded date, runtime
+ // and their words, into `transcripts/copies/<group>.json` — `pnpm ops
+ // copies-scan`. Reads the index, metadata and cue files of several
+ // channels (the text tier, each guarded in the controller): needsText, no
+ // channelSlug. Its own queue; not replayable (run it again).
+ "copies-scan": {
+ kind: "copies-scan",
+ label: "Copies scan",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsText: true,
+ },
// The audio audit (release 31, lane A): a tolerant decode of each audio
// file a channel holds, its verdict in `audio-integrity.json` beside it —
// `pnpm ops audio-audit`, one job per channel on `audio-audit`. OPENS EVERY
diff --git a/common/lib/copies/file-server.ts b/common/lib/copies/file-server.ts
@@ -0,0 +1,91 @@
+// The disk half of lib/copies/file.ts: `<transcriptsDir>/copies/<group>.json`
+// and `<group>.releases.json`, read and written. SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+import { withJsonFileLock, writeJsonAtomic } from "../jsonFile-server";
+import { SOURCE_GROUP_ID_RE } from "./settings";
+import {
+ COPIES_DIRNAME,
+ COPIES_RELEASES_FORMAT,
+ COPIES_VERSION,
+ isCopiesFile,
+ isCopiesReleasesFile,
+ type CopiesFile,
+ type CopiesReleasesFile,
+ type CopyRelease,
+} from "./file";
+
+export function copiesDirOf(transcriptsDir: string): string {
+ return path.join(transcriptsDir, COPIES_DIRNAME);
+}
+
+function checkedId(group: string): string {
+ if (!SOURCE_GROUP_ID_RE.test(group)) throw new Error(`not a source group id: ${JSON.stringify(group)}`);
+ return group;
+}
+
+export function copiesPath(transcriptsDir: string, group: string): string {
+ return path.join(copiesDirOf(transcriptsDir), `${checkedId(group)}.json`);
+}
+
+export function copiesReleasesPath(transcriptsDir: string, group: string): string {
+ return path.join(copiesDirOf(transcriptsDir), `${checkedId(group)}.releases.json`);
+}
+
+// The group's scan, or null (none yet, unreadable, or another format).
+export async function readCopiesFile(transcriptsDir: string, group: string): Promise<CopiesFile | null> {
+ try {
+ const v = JSON.parse(await readFile(copiesPath(transcriptsDir, group), "utf8")) as unknown;
+ return isCopiesFile(v) && v.group === group ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function writeCopiesFile(transcriptsDir: string, file: CopiesFile): Promise<string> {
+ const p = copiesPath(transcriptsDir, file.group);
+ await writeJsonAtomic(p, file, { mkdir: true });
+ return p;
+}
+
+export function emptyReleases(group: string): CopiesReleasesFile {
+ return { format: COPIES_RELEASES_FORMAT, version: COPIES_VERSION, group, released: {} };
+}
+
+// The group's releases; none (or an unreadable file) is an empty set.
+export async function readCopiesReleases(transcriptsDir: string, group: string): Promise<CopiesReleasesFile> {
+ try {
+ const v = JSON.parse(await readFile(copiesReleasesPath(transcriptsDir, group), "utf8")) as unknown;
+ if (isCopiesReleasesFile(v) && v.group === group) return v;
+ } catch {
+ // none yet
+ }
+ return emptyReleases(group);
+}
+
+/**
+ * THE ONE WRITER of a group's releases: release (or, with `undo`, un-release)
+ * each `<channel>/<dir>` key, under the file's lock, atomically. Answers the
+ * file as written.
+ */
+export async function updateCopiesReleases(
+ transcriptsDir: string,
+ group: string,
+ keys: readonly string[],
+ opts: { undo?: boolean; note?: string; now?: () => Date } = {},
+): Promise<CopiesReleasesFile> {
+ const p = copiesReleasesPath(transcriptsDir, group);
+ return withJsonFileLock(p, async () => {
+ const file = await readCopiesReleases(transcriptsDir, group);
+ const at = (opts.now?.() ?? new Date()).toISOString();
+ const released: Record<string, CopyRelease> = { ...file.released };
+ for (const k of keys) {
+ if (opts.undo) delete released[k];
+ else released[k] = { at, ...(opts.note ? { note: opts.note } : {}) };
+ }
+ const next: CopiesReleasesFile = { ...file, released: Object.fromEntries(Object.entries(released).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))) };
+ await writeJsonAtomic(p, next, { mkdir: true });
+ return next;
+ });
+}
diff --git a/common/lib/copies/file.ts b/common/lib/copies/file.ts
@@ -0,0 +1,115 @@
+// THE COPIES FILES of a source group (lane cross-source-dupes, slice 1). Pure:
+// the shapes and their guards; copies/file-server.ts reads and writes them.
+//
+// transcripts/copies/<group>.json the scan's pairs, machine-written,
+// regenerated whole by each scan
+// transcripts/copies/<group>.releases.json the operator's releases, written
+// only by `copies-release`
+//
+// PRIVATE: nothing under transcripts/copies/ is read by the export build or
+// shipped to a site. Deleting either file restores today's lane behaviour.
+
+import type { CopyLink, TextEvidence } from "./match";
+
+export const COPIES_DIRNAME = "copies";
+export const COPIES_FORMAT = "archilyzer-copies";
+export const COPIES_VERSION = 1;
+export const COPIES_RELEASES_FORMAT = "archilyzer-copies-releases";
+
+export type CopyMember = {
+ channel: string;
+ dir: string;
+ id: string;
+ title: string;
+ duration: number;
+ date: string | null;
+};
+
+export type CopyPairRecord = {
+ // `<a.channel>/<a.dir>|<b.channel>/<b.dir>`: a is the more preferred side.
+ key: string;
+ a: CopyMember;
+ b: CopyMember;
+ link: CopyLink;
+ // Both members on one channel: report only, the lanes never act on it.
+ withinChannel: boolean;
+ evidence: {
+ // What decided the link: the words, or (no text on one side) metadata.
+ kind: "text" | "metadata";
+ dateDeltaDays: number;
+ durationOk: boolean;
+ text?: TextEvidence;
+ };
+ // When a scan first recorded this pair (ISO-8601), carried across scans:
+ // a held copy's wait is counted from here.
+ firstSeenAt: string;
+};
+
+export type CopiesTotals = {
+ videos: Record<string, number>;
+ undated: number;
+ candidates: number;
+ confirmed: number;
+ metadata: number;
+ partial: number;
+ // Candidates the words said were different recordings.
+ rejected: number;
+ withinChannel: number;
+};
+
+export type CopiesFile = {
+ format: typeof COPIES_FORMAT;
+ version: typeof COPIES_VERSION;
+ group: string;
+ channels: string[];
+ // Members this corpus does not hold, skipped by the scan.
+ missing?: string[];
+ generatedAt: string;
+ jobId?: string;
+ rules: {
+ dateWindowDays: number;
+ durationToleranceSeconds: number;
+ durationToleranceRatio: number;
+ withinChannels: boolean;
+ };
+ pairs: CopyPairRecord[];
+ totals: CopiesTotals;
+};
+
+export type CopyRelease = { at: string; note?: string };
+
+export type CopiesReleasesFile = {
+ format: typeof COPIES_RELEASES_FORMAT;
+ version: typeof COPIES_VERSION;
+ group: string;
+ // `<channel>/<dir>` → when it was released: the lanes treat that video as
+ // they did before the group existed.
+ released: Record<string, CopyRelease>;
+};
+
+export function copyVideoKey(channel: string, dir: string): string {
+ return `${channel}/${dir}`;
+}
+
+export function copyPairKey(a: Pick<CopyMember, "channel" | "dir">, b: Pick<CopyMember, "channel" | "dir">): string {
+ return `${copyVideoKey(a.channel, a.dir)}|${copyVideoKey(b.channel, b.dir)}`;
+}
+
+export function isCopiesFile(v: unknown): v is CopiesFile {
+ if (!v || typeof v !== "object") return false;
+ const f = v as Partial<CopiesFile>;
+ return f.format === COPIES_FORMAT && f.version === COPIES_VERSION && typeof f.group === "string" && Array.isArray(f.pairs);
+}
+
+export function isCopiesReleasesFile(v: unknown): v is CopiesReleasesFile {
+ if (!v || typeof v !== "object") return false;
+ const f = v as Partial<CopiesReleasesFile>;
+ return (
+ f.format === COPIES_RELEASES_FORMAT &&
+ f.version === COPIES_VERSION &&
+ typeof f.group === "string" &&
+ !!f.released &&
+ typeof f.released === "object" &&
+ !Array.isArray(f.released)
+ );
+}
diff --git a/common/lib/copies/laneHold.test.ts b/common/lib/copies/laneHold.test.ts
@@ -0,0 +1,142 @@
+// lib/copies/laneHold.ts: which pending copies a lane skips or holds. Pure;
+// synthetic channels and ids.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { applyCopyHolds, copyPartnersToRead, type CopyPartner, type CopyPlan } from "./laneHold";
+
+const NOW = Date.parse("2026-03-20T00:00:00Z");
+const RECENT = "2026-03-18T00:00:00Z";
+const LONG_AGO = "2026-03-01T00:00:00Z";
+
+// pref-chan is preferred over mirror-chan.
+function plan(
+ pairs: { pref: string; mirror: string; link: CopyPartner["link"]; firstSeenAt?: string }[],
+ released: string[] = [],
+): CopyPlan {
+ const byVideo = new Map<string, CopyPartner[]>();
+ const add = (k: string, p: CopyPartner) => byVideo.set(k, [...(byVideo.get(k) ?? []), p]);
+ for (const x of pairs) {
+ const common = { group: "g", link: x.link, firstSeenAt: x.firstSeenAt ?? RECENT, waitDays: 7 };
+ add(`pref-chan/${x.pref}`, { ...common, channel: "mirror-chan", dir: x.mirror, partnerPreferred: false });
+ add(`mirror-chan/${x.mirror}`, { ...common, channel: "pref-chan", dir: x.pref, partnerPreferred: true });
+ }
+ return { byVideo, released: new Set(released) };
+}
+
+function owner(ids: string[]): Map<string, string> {
+ return new Map(ids.map((id) => [id, id.startsWith("p") ? "pref-chan" : "mirror-chan"]));
+}
+
+function run(
+ pendingIds: string[],
+ p: CopyPlan,
+ done: string[] = [],
+ inFlight: string[] = [],
+ everyone: string[] = pendingIds,
+) {
+ return applyCopyHolds({
+ lane: "transcription",
+ work: "transcript",
+ pending: { all: pendingIds },
+ owner: owner([...everyone, ...done, ...inFlight]),
+ plan: p,
+ inFlight: new Set(inFlight),
+ done: new Map(done.map((k) => [k, true])),
+ now: NOW,
+ });
+}
+
+test("an empty plan hands the lists back untouched", () => {
+ const pending = { all: ["p1", "m1"] };
+ const out = applyCopyHolds({
+ lane: "transcription",
+ work: "transcript",
+ pending,
+ owner: owner(["p1", "m1"]),
+ plan: { byVideo: new Map(), released: new Set() },
+ inFlight: new Set(),
+ done: new Map(),
+ now: NOW,
+ });
+ assert.equal(out.pending, pending);
+ assert.deepEqual(out.decisions, []);
+});
+
+test("a confirmed copy is skipped only when the other copy's work is done", () => {
+ const p = plan([{ pref: "p1", mirror: "m1", link: "confirmed" }]);
+ // Not done: the mirror waits for its queued preferred copy (held, not skipped).
+ const notDone = run(["p1", "m1"], p);
+ assert.deepEqual(notDone.pending.all, ["p1"]);
+ assert.equal(notDone.decisions[0].action, "hold");
+ assert.match(notDone.decisions[0].reason, /waiting for the preferred copy pref-chan\/p1 \(queued/);
+ // Done on disk: skipped.
+ const done = run(["m1"], p, ["pref-chan/p1"]);
+ assert.deepEqual(done.pending.all, []);
+ assert.equal(done.decisions[0].action, "skip");
+ assert.equal(done.decisions[0].partner, "pref-chan/p1");
+ // Done on disk but still queued on this lane: not done.
+ const stillQueued = run(["p1", "m1"], p, ["pref-chan/p1"]);
+ assert.equal(stillQueued.decisions[0].action, "hold");
+});
+
+test("the copy that already has the transcript keeps it whatever the order", () => {
+ const p = plan([{ pref: "p1", mirror: "m1", link: "confirmed" }]);
+ // The FALLBACK copy has the transcript; the preferred one is pending.
+ const out = run(["p1"], p, ["mirror-chan/m1"]);
+ assert.deepEqual(out.pending.all, [], "the preferred copy is not transcribed again");
+ assert.equal(out.decisions[0].channel, "pref-chan");
+ assert.equal(out.decisions[0].action, "skip");
+});
+
+test("a metadata-only match is held, never skipped, then released after the wait", () => {
+ const recent = plan([{ pref: "p1", mirror: "m1", link: "metadata", firstSeenAt: RECENT }]);
+ const held = run(["m1"], recent);
+ assert.deepEqual(held.pending.all, []);
+ assert.equal(held.decisions[0].action, "hold");
+ assert.equal(held.decisions[0].until, "2026-03-25T00:00:00.000Z");
+ assert.match(held.decisions[0].reason, /date and runtime only/);
+ assert.match(held.decisions[0].reason, /copies-release/);
+ // The wait is over and the preferred copy still has no transcript: released.
+ const old = plan([{ pref: "p1", mirror: "m1", link: "metadata", firstSeenAt: LONG_AGO }]);
+ const released = run(["m1"], old);
+ assert.deepEqual(released.pending.all, ["m1"]);
+ assert.deepEqual(released.decisions, []);
+ // The other copy IS done: held until a person releases it, wait or not.
+ const doneOther = run(["m1"], old, ["pref-chan/p1"]);
+ assert.equal(doneOther.decisions[0].action, "hold");
+ assert.equal(doneOther.decisions[0].until, undefined);
+ // Released by a person: the lane is today's lane for it.
+ const byHand = run(["m1"], plan([{ pref: "p1", mirror: "m1", link: "metadata" }], ["mirror-chan/m1"]), ["pref-chan/p1"]);
+ assert.deepEqual(byHand.pending.all, ["m1"]);
+ assert.deepEqual(byHand.decisions, []);
+});
+
+test("a preferred copy that is gone or unavailable does not block the mirror", () => {
+ // Confirmed, the preferred copy neither done, queued nor in flight (gone at
+ // its source, on a paused channel, never downloaded): the mirror runs now.
+ const p = plan([{ pref: "p1", mirror: "m1", link: "confirmed" }]);
+ assert.deepEqual(run(["m1"], p).pending.all, ["m1"]);
+ // In flight on this lane: held.
+ assert.deepEqual(run(["m1"], p, [], ["pref-chan/p1"]).pending.all, []);
+ // Queued, but the wait is over: runs.
+ const old = plan([{ pref: "p1", mirror: "m1", link: "confirmed", firstSeenAt: LONG_AGO }]);
+ assert.deepEqual(run(["p1", "m1"], old).pending.all, ["p1", "m1"]);
+});
+
+test("the preferred copy is never held by a fallback that is not done; a partial pair changes nothing", () => {
+ const p = plan([
+ { pref: "p1", mirror: "m1", link: "confirmed" },
+ { pref: "p2", mirror: "m2", link: "metadata" },
+ { pref: "p3", mirror: "m3", link: "partial" },
+ ]);
+ const out = run(["p1", "p2", "p3", "m3"], p);
+ assert.deepEqual(out.pending.all, ["p1", "p2", "p3", "m3"]);
+ assert.deepEqual(out.decisions, []);
+ // Done partial partner: still nothing.
+ assert.deepEqual(run(["m3"], p, ["pref-chan/p3"]).pending.all, ["m3"]);
+});
+
+test("the partners to read are the pending videos' partners, released ones left out", () => {
+ const p = plan([{ pref: "p1", mirror: "m1", link: "confirmed" }, { pref: "p2", mirror: "m2", link: "confirmed" }], ["mirror-chan/m2"]);
+ assert.deepEqual([...copyPartnersToRead({ a: ["m1", "m2"] }, owner(["m1", "m2"]), p)], ["pref-chan/p1"]);
+});
diff --git a/common/lib/copies/laneHold.ts b/common/lib/copies/laneHold.ts
@@ -0,0 +1,229 @@
+// WHICH PENDING VIDEOS A LANE SKIPS OR HOLDS BECAUSE ANOTHER COPY OF THE SAME
+// RECORDING HAS (OR WILL GET) THE WORK (lane cross-source-dupes, slice 1).
+// Pure: the plan, the pending lists, what is in flight and what is done go in;
+// the trimmed lists and one decision per affected video come out. The runner
+// tick and the status panel's twin (controller/autoRunner.ts) both call it,
+// through controller/copiesLane.ts, so the two can never disagree.
+//
+// THE RULES, per pending video X and each other copy P of it (pairs across
+// channels only, in a group whose `lanes` is on, X not released):
+//
+// P's work is done (read off P's own files, not assumed):
+// text-confirmed pair → X is SKIPPED: the recording has the work.
+// metadata-only pair → X is HELD until a person releases it (3 % of such
+// pairs name the wrong copy, so it is never a skip).
+// P not done, and P is the PREFERRED copy (its channel earlier in the group):
+// text-confirmed → X is HELD while P is queued or in flight on this lane,
+// until the wait ends; else X runs (P gone, paused,
+// never downloaded … never blocks X).
+// metadata-only → X is HELD until the wait ends, then released by itself.
+// Anything else (a partial pair, X preferred and P not done) changes nothing.
+//
+// WORK ALREADY DONE IS NEVER REDONE OR DISCARDED: the copy that has the work
+// owns it whatever the order, because a done P skips or holds X whichever of
+// the two is preferred. The order only decides who gets NEW work.
+//
+// A skip or hold only takes the video off this lane's pending list. Nothing is
+// deleted, hidden, un-downloaded or published differently, and no time is
+// mapped between the copies.
+
+import type { CopyLink } from "./match";
+import { copyVideoKey } from "./file";
+
+export const COPY_HOLD_HEAD = 20;
+
+export type CopyPartner = {
+ group: string;
+ // The other copy.
+ channel: string;
+ dir: string;
+ link: CopyLink;
+ // The partner's channel is earlier in the group than this video's.
+ partnerPreferred: boolean;
+ // ISO-8601: when the scan first saw the pair; the wait runs from here.
+ firstSeenAt: string;
+ waitDays: number;
+};
+
+export type CopyPlan = {
+ // `<channel>/<dir>` → its other copies the lanes act on.
+ byVideo: Map<string, CopyPartner[]>;
+ // `<channel>/<dir>` released by a person: treated as if no group existed.
+ released: Set<string>;
+};
+
+export type CopyHoldDecision = {
+ channel: string;
+ id: string;
+ action: "skip" | "hold";
+ group: string;
+ link: CopyLink;
+ // The other copy, `<channel>/<dir>`.
+ partner: string;
+ // Why, in the lane's words.
+ reason: string;
+ // A hold that ends by itself: when (ISO-8601).
+ until?: string;
+};
+
+export type CopyHoldSummary = {
+ skipped: number;
+ held: number;
+ // The first COPY_HOLD_HEAD decisions, skips first, in pending order.
+ head: CopyHoldDecision[];
+};
+
+export type CopyHoldInput = {
+ lane: string;
+ // What the lane calls its work, for the reasons ("transcript", "speakers").
+ work: string;
+ pending: Record<string, string[]>;
+ // videoId → channel slug (the projection's owner map).
+ owner: ReadonlyMap<string, string>;
+ plan: CopyPlan;
+ // `<channel>/<dir>` of every unit in flight on this lane.
+ inFlight: ReadonlySet<string>;
+ // `<channel>/<dir>` → done (and readable) for this lane. A key absent is not done.
+ done: ReadonlyMap<string, boolean>;
+ now: number;
+};
+
+const DAY_MS = 86_400_000;
+
+function waitEnds(p: CopyPartner): number {
+ const t = Date.parse(p.firstSeenAt);
+ return (Number.isFinite(t) ? t : 0) + p.waitDays * DAY_MS;
+}
+
+function releaseHint(group: string, key: string): string {
+ return `pnpm ops copies-release --json '{"group":"${group}","video":"${key}"}'`;
+}
+
+/** The partners whose done state a decision needs: every partner of a pending video. */
+export function copyPartnersToRead(
+ pending: Record<string, string[]>,
+ owner: ReadonlyMap<string, string>,
+ plan: CopyPlan,
+): Set<string> {
+ const out = new Set<string>();
+ if (plan.byVideo.size === 0) return out;
+ for (const ids of Object.values(pending)) {
+ for (const id of ids) {
+ const slug = owner.get(id);
+ if (!slug) continue;
+ const key = copyVideoKey(slug, id);
+ if (plan.released.has(key)) continue;
+ for (const p of plan.byVideo.get(key) ?? []) out.add(copyVideoKey(p.channel, p.dir));
+ }
+ }
+ return out;
+}
+
+function decideOne(
+ key: string,
+ slug: string,
+ id: string,
+ partners: readonly CopyPartner[],
+ input: CopyHoldInput,
+ pendingKeys: ReadonlySet<string>,
+): CopyHoldDecision | null {
+ let hold: CopyHoldDecision | null = null;
+ for (const p of partners) {
+ const pk = copyVideoKey(p.channel, p.dir);
+ const base = { channel: slug, id, group: p.group, link: p.link, partner: pk };
+ // DONE MEANS DONE ON DISK AND NOT STILL THE LANE'S WORK: a partner this
+ // lane would still run (queued) or is running is not done, whatever its
+ // files say — so two copies can never each skip the other.
+ const partnerDone = input.done.get(pk) === true && !pendingKeys.has(pk) && !input.inFlight.has(pk);
+ if (partnerDone) {
+ if (p.link === "confirmed") {
+ return {
+ ...base,
+ action: "skip",
+ reason: `a text-confirmed copy of ${pk}, whose ${input.work} is done — not done twice`,
+ };
+ }
+ if (p.link === "metadata" && !hold) {
+ hold = {
+ ...base,
+ action: "hold",
+ reason:
+ `held: probably the same recording as ${pk} (date and runtime only, not confirmed by text), ` +
+ `whose ${input.work} is done — release: ${releaseHint(p.group, key)}`,
+ };
+ }
+ continue;
+ }
+ if (!p.partnerPreferred || p.link === "partial") continue;
+ const ends = waitEnds(p);
+ if (input.now >= ends) continue;
+ const until = new Date(ends).toISOString();
+ if (p.link === "confirmed") {
+ const state = input.inFlight.has(pk) ? "in flight" : pendingKeys.has(pk) ? "queued" : null;
+ if (!state || hold) continue;
+ hold = {
+ ...base,
+ action: "hold",
+ until,
+ reason: `held: waiting for the preferred copy ${pk} (${state} on this lane), until ${until.slice(0, 10)} at the latest`,
+ };
+ } else if (p.link === "metadata" && !hold) {
+ hold = {
+ ...base,
+ action: "hold",
+ until,
+ reason:
+ `held: probably the same recording as the preferred copy ${pk} (date and runtime only); ` +
+ `waiting for its ${input.work} until ${until.slice(0, 10)}, then released by itself — release now: ${releaseHint(p.group, key)}`,
+ };
+ }
+ }
+ return hold;
+}
+
+/**
+ * The lane's pending lists with every skipped and held copy taken out, and a
+ * decision for each. With an empty plan the lists come back untouched (the
+ * same object) and no decision: no group configured is today's lane.
+ */
+export function applyCopyHolds(input: CopyHoldInput): {
+ pending: Record<string, string[]>;
+ decisions: CopyHoldDecision[];
+} {
+ const { plan, owner } = input;
+ if (plan.byVideo.size === 0) return { pending: input.pending, decisions: [] };
+ const pendingKeys = new Set<string>();
+ for (const ids of Object.values(input.pending)) {
+ for (const id of ids) {
+ const slug = owner.get(id);
+ if (slug) pendingKeys.add(copyVideoKey(slug, id));
+ }
+ }
+ const decided = new Map<string, CopyHoldDecision | null>();
+ const decisions: CopyHoldDecision[] = [];
+ const out: Record<string, string[]> = {};
+ for (const [leaf, ids] of Object.entries(input.pending)) {
+ out[leaf] = ids.filter((id) => {
+ const slug = owner.get(id);
+ if (!slug) return true;
+ const key = copyVideoKey(slug, id);
+ if (plan.released.has(key)) return true;
+ const partners = plan.byVideo.get(key);
+ if (!partners || partners.length === 0) return true;
+ let d = decided.get(key);
+ if (d === undefined) {
+ d = decideOne(key, slug, id, partners, input, pendingKeys);
+ decided.set(key, d);
+ if (d) decisions.push(d);
+ }
+ return d === null;
+ });
+ }
+ return { pending: out, decisions };
+}
+
+export function summarizeCopyHolds(decisions: readonly CopyHoldDecision[]): CopyHoldSummary {
+ const skips = decisions.filter((d) => d.action === "skip");
+ const holds = decisions.filter((d) => d.action === "hold");
+ return { skipped: skips.length, held: holds.length, head: [...skips, ...holds].slice(0, COPY_HOLD_HEAD) };
+}
diff --git a/common/lib/copies/match.test.ts b/common/lib/copies/match.test.ts
@@ -0,0 +1,130 @@
+// lib/copies/match.ts: the metadata stage and the text-anchor stage. Every
+// word, channel and id here is synthetic.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyCandidate,
+ copyCandidates,
+ cuesToWords,
+ textEvidence,
+ COPY_PHRASE_WORDS,
+ type CopyRecord,
+ type Word,
+} from "./match";
+import { sanitizeSourceGroups } from "./settings";
+
+// A deterministic stream of nonsense words, one every 0.4 s.
+function rng(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 2 ** 32;
+ };
+}
+const VOCAB = Array.from({ length: 800 }, (_, i) => `w${i.toString(36)}x`);
+function stream(seed: number, n: number, start = 0): Word[] {
+ const r = rng(seed);
+ return Array.from({ length: n }, (_, i) => ({ w: VOCAB[Math.floor(r() * VOCAB.length)], t: start + i * 0.4 }));
+}
+const shift = (ws: readonly Word[], by: number): Word[] => ws.map((x) => ({ w: x.w, t: x.t + by }));
+const retime = (ws: readonly Word[], start: number): Word[] => ws.map((x, i) => ({ w: x.w, t: start + i * 0.4 }));
+
+test("the same recording on another clock is the same, with its offset as evidence", () => {
+ const a = stream(1, 3000);
+ const b = shift(a.slice(100), 30);
+ const e = textEvidence(a, b);
+ assert.equal(e.verdict, "same");
+ assert.ok(e.consistent >= 30, `consistent ${e.consistent}`);
+ assert.equal(e.offsetMedianSeconds, 30);
+});
+
+test("collisions at random offsets do not confirm (fails against a match-count verdict)", () => {
+ // Another recording that happens to share 12 of the 40 probed phrases, each
+ // at a random place: a match COUNT says 12 (≥ 8, 'same'); the consistent
+ // offsets say different.
+ const a = stream(2, 3000);
+ const usable = a.length - COPY_PHRASE_WORDS;
+ const b = stream(3, 3000).map((x) => ({ ...x }));
+ const r = rng(99);
+ for (let k = 1; k <= 12; k++) {
+ const pos = Math.floor((usable * k) / 41);
+ const at = 50 + Math.floor(r() * 2800);
+ for (let j = 0; j < COPY_PHRASE_WORDS; j++) b[at + j] = { w: a[pos + j].w, t: b[at + j].t };
+ }
+ const e = textEvidence(a, b);
+ assert.ok(e.matched >= 10, `the collisions are found (${e.matched})`);
+ assert.notEqual(e.verdict, "same");
+ assert.ok(e.consistent < 4, `consistent ${e.consistent}`);
+});
+
+test("a stepped pair is the same recording, with a second cluster", () => {
+ const a = stream(4, 3000);
+ const b = [...shift(a.slice(0, 1500), 10), ...shift(a.slice(1500), 60)];
+ const e = textEvidence(a, b);
+ assert.equal(e.verdict, "same");
+ assert.ok(e.secondCluster >= 4, `second cluster ${e.secondCluster}`);
+});
+
+test("a part of the recording is partial, not the same", () => {
+ const a = stream(5, 3000);
+ const b = retime([...stream(6, 300), ...a.slice(1000, 1100), ...stream(7, 300)], 0);
+ const e = textEvidence(a, b);
+ assert.equal(e.verdict, "partial", JSON.stringify(e));
+});
+
+test("too few words on either side is no text", () => {
+ assert.equal(textEvidence(stream(8, 150), stream(8, 3000)).verdict, "no-text");
+});
+
+test("cues become words spread across each cue", () => {
+ const ws = cuesToWords([{ start: 10, end: 12, text: "Hello, there world" }, { start: 13, text: "again" }]);
+ assert.deepEqual(ws.map((w) => w.w), ["hello", "there", "world", "again"]);
+ assert.equal(ws[0].t, 10);
+ assert.ok(ws[2].t > 11 && ws[2].t < 12);
+ assert.equal(ws[3].t, 13);
+});
+
+const [GROUP] = sanitizeSourceGroups([{ id: "g", channels: ["pref-chan", "mirror-chan"] }]);
+const rec = (channel: string, dir: string, date: string | null, duration: number): CopyRecord => ({
+ channel,
+ dir,
+ id: dir,
+ title: `${dir} title`,
+ duration,
+ date,
+});
+
+test("candidates: dated within the window, across channels only, the preferred channel as `a`", () => {
+ const records = [
+ rec("mirror-chan", "m1", "20260301", 7200),
+ rec("pref-chan", "p1", "20260302", 7210),
+ rec("pref-chan", "p2", "20260304", 7200),
+ rec("pref-chan", "p3", "20260301", 3000),
+ rec("mirror-chan", "m0", null, 7200),
+ ];
+ const c = copyCandidates(GROUP, records);
+ assert.deepEqual(
+ c.map((x) => [x.a.dir, x.b.dir, x.dateDeltaDays, x.durationOk]),
+ [
+ ["p1", "m1", 1, true],
+ ["p3", "m1", 0, false],
+ ],
+ );
+ // Inside one channel only when asked.
+ const [within] = sanitizeSourceGroups([{ id: "g", channels: ["pref-chan", "mirror-chan"], withinChannels: true }]);
+ const w = copyCandidates(within, records);
+ assert.ok(w.some((x) => x.a.dir === "p1" && x.b.dir === "p3"));
+});
+
+test("the adjacent day's stream with the closer runtime is not linked over the text-confirmed one", () => {
+ const recorded = stream(10, 3000);
+ const other = stream(11, 3000);
+ const mirror = rec("mirror-chan", "m1", "20260301", 7200);
+ const sameDay = { a: rec("pref-chan", "p-same", "20260301", 6500), b: mirror, dateDeltaDays: 0, durationOk: false };
+ const nextDay = { a: rec("pref-chan", "p-next", "20260302", 7200), b: mirror, dateDeltaDays: 1, durationOk: true };
+ assert.equal(classifyCandidate(sameDay, textEvidence(recorded, shift(recorded, -50))), "confirmed");
+ assert.equal(classifyCandidate(nextDay, textEvidence(other, shift(recorded, -50))), null, "text overrules the runtime");
+ // With no text on one side the runtime is all there is: metadata only.
+ assert.equal(classifyCandidate(nextDay, null), "metadata");
+ assert.equal(classifyCandidate(sameDay, null), null);
+});
diff --git a/common/lib/copies/match.ts b/common/lib/copies/match.ts
@@ -0,0 +1,268 @@
+// WHICH VIDEOS OF A SOURCE GROUP ARE THE SAME RECORDING (lane
+// cross-source-dupes, slice 1). Pure: records and words in, pairs out. The
+// scan (controller/copiesScan.ts) reads the disk and calls this.
+//
+// TWO STAGES, and the difference between them is the whole design:
+//
+// METADATA — recorded dates at most `dateWindowDays` apart and runtimes that
+// agree (max(seconds, ratio × the longer)). Free, and measured at 99.7 %
+// for "this stream is held elsewhere" but 3 % WRONG about WHICH copy (the
+// adjacent day's stream of similar length). Good enough to HOLD a copy's
+// work, never to skip it.
+// TEXT — 40 probes spread through one copy's words; at each, a 6-word phrase
+// unique on both sides, and the signed offset between where it sits in
+// each. The verdict is the LARGEST SET OF OFFSETS INSIDE ONE 20 s WINDOW,
+// never the match count: two different streams of one speaker in one week
+// share 4–20 of 40 phrases, at random offsets. ≥ 8 is the same recording,
+// 4–7 a part of it, fewer is different. Only this confirms a copy.
+//
+// NO TIME IS MAPPED. The offsets are kept as evidence (their median and
+// spread), never as a clock: two copies of one stream are measured stepped and
+// drifting, and a constant offset would cut the wrong words. Nothing in slice 1
+// reads a time across copies.
+
+import type { SourceGroup } from "./settings";
+
+export const COPY_PHRASE_WORDS = 6;
+export const COPY_PROBES = 40;
+// A window this wide holds one recording's consistent offsets.
+export const COPY_OFFSET_WINDOW_SECONDS = 20;
+export const COPY_SAME_MIN = 8;
+export const COPY_PARTIAL_MIN = 4;
+// Fewer words than this on either side is "no text" — too little to probe.
+export const COPY_MIN_WORDS = 200;
+// How far past a probe's position a unique phrase is looked for.
+const PROBE_SEARCH_WORDS = 300;
+
+export type CopyRecord = {
+ channel: string;
+ // The data/<dir>/ the video lives in (a Rumble video's dir is not its id).
+ dir: string;
+ id: string;
+ title: string;
+ // Seconds; 0 = unknown.
+ duration: number;
+ // YYYYMMDD, or null when undated.
+ date: string | null;
+};
+
+export type Word = { w: string; t: number };
+
+export type CueLike = { start: number; end?: number; text: string };
+
+export type TextVerdict = "same" | "partial" | "different" | "no-text";
+
+export type TextEvidence = {
+ verdict: TextVerdict;
+ probes: number;
+ // Probes whose phrase was found, unique, on the other side.
+ matched: number;
+ // The largest set of those inside one 20 s window of offsets: the verdict.
+ consistent: number;
+ // The next largest such set outside it — a second segment (a step).
+ secondCluster: number;
+ // EVIDENCE ONLY, never a clock: the median and spread of the consistent
+ // offsets (other side's seconds minus this side's), rounded to 0.1 s.
+ offsetMedianSeconds: number | null;
+ offsetSpreadSeconds: number | null;
+};
+
+export type CopyLink = "confirmed" | "metadata" | "partial";
+
+export type CopyCandidate = {
+ a: CopyRecord;
+ b: CopyRecord;
+ dateDeltaDays: number;
+ durationOk: boolean;
+};
+
+// The words of a cue list, each at a time spread across its cue's span.
+export function cuesToWords(cues: readonly CueLike[]): Word[] {
+ const out: Word[] = [];
+ for (const c of cues) {
+ if (!c || typeof c.text !== "string" || typeof c.start !== "number" || !Number.isFinite(c.start)) continue;
+ const ws = c.text
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s]/gu, " ")
+ .split(/\s+/)
+ .filter(Boolean);
+ const end = typeof c.end === "number" && Number.isFinite(c.end) ? c.end : c.start;
+ const span = Math.max(0, end - c.start);
+ ws.forEach((w, i) => out.push({ w, t: c.start + (ws.length > 1 ? (span * i) / ws.length : 0) }));
+ }
+ return out;
+}
+
+type GramIndex = Map<string, { t: number; n: number }>;
+
+function gramAt(ws: readonly Word[], i: number): string {
+ let key = ws[i].w;
+ for (let j = 1; j < COPY_PHRASE_WORDS; j++) key += " " + ws[i + j].w;
+ return key;
+}
+
+function gramIndex(ws: readonly Word[]): GramIndex {
+ const idx: GramIndex = new Map();
+ for (let i = 0; i + COPY_PHRASE_WORDS <= ws.length; i++) {
+ const key = gramAt(ws, i);
+ const e = idx.get(key);
+ if (e) e.n++;
+ else idx.set(key, { t: ws[i].t, n: 1 });
+ }
+ return idx;
+}
+
+// The largest run of sorted values inside one window: [from, to] indexes.
+function largestWindow(sorted: readonly number[], width: number): [number, number] | null {
+ if (sorted.length === 0) return null;
+ let bi = 0;
+ let bj = 0;
+ for (let i = 0, j = 0; i < sorted.length; i++) {
+ while (sorted[i] - sorted[j] > width) j++;
+ if (i - j > bj - bi) {
+ bi = j;
+ bj = i;
+ }
+ }
+ return [bi, bj];
+}
+
+const round1 = (x: number) => Math.round(x * 10) / 10;
+
+/**
+ * Whether `a` and `b` are the same recording by their words: probes spread
+ * through `a`, each a phrase unique on both sides, and the verdict from the
+ * largest set of consistent offsets.
+ */
+export function textEvidence(
+ a: readonly Word[],
+ b: readonly Word[],
+ opts: { probes?: number; minWords?: number } = {},
+): TextEvidence {
+ const probes = opts.probes ?? COPY_PROBES;
+ const minWords = opts.minWords ?? COPY_MIN_WORDS;
+ const none: TextEvidence = {
+ verdict: "no-text",
+ probes: 0,
+ matched: 0,
+ consistent: 0,
+ secondCluster: 0,
+ offsetMedianSeconds: null,
+ offsetSpreadSeconds: null,
+ };
+ if (a.length < minWords || b.length < minWords) return none;
+ const aIdx = gramIndex(a);
+ const bIdx = gramIndex(b);
+ const usable = a.length - COPY_PHRASE_WORDS;
+ const offsets: number[] = [];
+ for (let k = 1; k <= probes; k++) {
+ const pos = Math.floor((usable * k) / (probes + 1));
+ const lim = Math.min(usable + 1, pos + PROBE_SEARCH_WORDS);
+ for (let i = pos; i < lim; i++) {
+ const key = gramAt(a, i);
+ if (aIdx.get(key)?.n !== 1) continue;
+ const hit = bIdx.get(key);
+ if (!hit || hit.n !== 1) continue;
+ offsets.push(hit.t - a[i].t);
+ break;
+ }
+ }
+ const sorted = [...offsets].sort((x, y) => x - y);
+ const w = largestWindow(sorted, COPY_OFFSET_WINDOW_SECONDS);
+ if (!w) return { ...none, verdict: "different", probes };
+ const inl = sorted.slice(w[0], w[1] + 1);
+ const rest = [...sorted.slice(0, w[0]), ...sorted.slice(w[1] + 1)];
+ const w2 = largestWindow(rest, COPY_OFFSET_WINDOW_SECONDS);
+ const consistent = inl.length;
+ return {
+ verdict: consistent >= COPY_SAME_MIN ? "same" : consistent >= COPY_PARTIAL_MIN ? "partial" : "different",
+ probes,
+ matched: offsets.length,
+ consistent,
+ secondCluster: w2 ? w2[1] - w2[0] + 1 : 0,
+ offsetMedianSeconds: round1(inl[Math.floor(inl.length / 2)]),
+ offsetSpreadSeconds: round1(inl[inl.length - 1] - inl[0]),
+ };
+}
+
+function dayNumber(ymd: string): number {
+ return Date.UTC(Number(ymd.slice(0, 4)), Number(ymd.slice(4, 6)) - 1, Number(ymd.slice(6, 8))) / 86_400_000;
+}
+
+/** Whether two runtimes agree within max(seconds, ratio × the longer). Unknown (0) never agrees. */
+export function runtimesAgree(
+ a: number,
+ b: number,
+ group: Pick<SourceGroup, "durationToleranceSeconds" | "durationToleranceRatio">,
+): boolean {
+ if (!(a > 0) || !(b > 0)) return false;
+ const tol = Math.max(group.durationToleranceSeconds, Math.max(a, b) * group.durationToleranceRatio);
+ return Math.abs(a - b) <= tol;
+}
+
+/**
+ * Every pair of the group's videos dated within the window — across members,
+ * and inside one member when `withinChannels` — with `a` the more preferred
+ * side (the earlier channel in the group; inside one channel, the smaller dir).
+ * Deterministic order: by a's channel rank, a's dir, b's channel rank, b's dir.
+ */
+export function copyCandidates(
+ group: Pick<
+ SourceGroup,
+ "channels" | "dateWindowDays" | "durationToleranceSeconds" | "durationToleranceRatio" | "withinChannels"
+ >,
+ records: readonly CopyRecord[],
+): CopyCandidate[] {
+ const rank = new Map(group.channels.map((c, i) => [c, i]));
+ const dated = records
+ .filter((r) => rank.has(r.channel) && r.date && /^\d{8}$/.test(r.date))
+ .map((r) => ({ r, day: dayNumber(r.date!) }));
+ const byDay = new Map<number, typeof dated>();
+ for (const d of dated) {
+ const list = byDay.get(d.day);
+ if (list) list.push(d);
+ else byDay.set(d.day, [d]);
+ }
+ const order = (x: CopyRecord, y: CopyRecord) =>
+ rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0);
+ const seen = new Set<string>();
+ const out: CopyCandidate[] = [];
+ for (const d of dated) {
+ for (let dd = -group.dateWindowDays; dd <= group.dateWindowDays; dd++) {
+ for (const e of byDay.get(d.day + dd) ?? []) {
+ if (e.r === d.r) continue;
+ const same = e.r.channel === d.r.channel;
+ if (same && !group.withinChannels) continue;
+ const [a, b] = order(d.r, e.r) <= 0 ? [d.r, e.r] : [e.r, d.r];
+ const key = `${a.channel}/${a.dir}\u0000${b.channel}/${b.dir}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({
+ a,
+ b,
+ dateDeltaDays: Math.abs(dd),
+ durationOk: runtimesAgree(a.duration, b.duration, group),
+ });
+ }
+ }
+ }
+ return out.sort(
+ (x, y) =>
+ order(x.a, y.a) || order(x.b, y.b),
+ );
+}
+
+/**
+ * What a candidate is, given its text evidence (null = one side has no text):
+ * text decides when both sides have it — same is CONFIRMED, a part is PARTIAL,
+ * anything else is no pair at all, whatever the metadata said; with no text,
+ * agreeing runtimes make a METADATA-only pair and anything else no pair.
+ */
+export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): CopyLink | null {
+ if (text && text.verdict !== "no-text") {
+ if (text.verdict === "same") return "confirmed";
+ if (text.verdict === "partial") return "partial";
+ return null;
+ }
+ return c.durationOk ? "metadata" : null;
+}
diff --git a/common/lib/copies/settings.test.ts b/common/lib/copies/settings.test.ts
@@ -0,0 +1,43 @@
+// settings.sourceGroups' coercion. Synthetic slugs only.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { sanitizeSourceGroups } from "./settings";
+import { defaults } from "../settingsSchema";
+
+test("no group by default", () => {
+ assert.deepEqual(defaults().sourceGroups, []);
+ assert.deepEqual(sanitizeSourceGroups(undefined), []);
+ assert.deepEqual(sanitizeSourceGroups({ channels: ["a-chan", "b-chan"] }), []);
+});
+
+test("a group keeps its order and gets its defaults", () => {
+ const [g] = sanitizeSourceGroups([{ label: "Stream copies", channels: ["b-chan", "a-chan"] }]);
+ assert.deepEqual(g, {
+ id: "stream-copies",
+ label: "Stream copies",
+ channels: ["b-chan", "a-chan"],
+ lanes: true,
+ waitDays: 7,
+ dateWindowDays: 1,
+ durationToleranceSeconds: 120,
+ durationToleranceRatio: 0.02,
+ withinChannels: false,
+ });
+});
+
+test("duplicate and bad slugs are dropped, a channel stays in its first group, a short group goes", () => {
+ const groups = sanitizeSourceGroups([
+ { id: "one", channels: ["a-chan", "a-chan", "../x", 7, "b-chan"] },
+ { id: "two", channels: ["b-chan", "c-chan"] },
+ { id: "three", channels: ["c-chan", "d-chan"], waitDays: 9999, dateWindowDays: -3, lanes: false },
+ { id: "one", channels: ["e-chan", "f-chan"] },
+ { channels: ["g-chan", "h-chan"] },
+ ]);
+ assert.deepEqual(
+ groups.map((g) => [g.id, g.channels, g.lanes, g.waitDays, g.dateWindowDays]),
+ [
+ ["one", ["a-chan", "b-chan"], true, 7, 1],
+ ["three", ["c-chan", "d-chan"], false, 365, 0],
+ ],
+ );
+});
diff --git a/common/lib/copies/settings.ts b/common/lib/copies/settings.ts
@@ -0,0 +1,147 @@
+// settings.sourceGroups — channels that archive the SAME recordings from
+// different sources (lane cross-source-dupes, slice 1). A group is an ORDERED
+// list of channel slugs: the first is the preferred source, the rest fall back
+// in order. A recording held on two members is transcribed and given speakers
+// once; the other copy stays on disk as the fallback.
+//
+// EMPTY BY DEFAULT, and with no group the lanes are byte for byte what they
+// were: nothing here is read by a lane until a group names channels. No
+// channel is named in code; a group is a settings patch on the machine that
+// runs it (`pnpm ops settings`).
+//
+// Pure: the types, the defaults, the sanitizer settingsSchema.ts runs the
+// block through, and the per-field docs SETTINGS.md renders.
+
+import type { FieldDocs } from "../fieldDocs";
+
+export type SourceGroup = {
+ id: string;
+ label: string;
+ // ORDER IS PREFERENCE: the first slug is the preferred source. A channel is
+ // in one group at most.
+ channels: string[];
+ // Whether the transcription and Speakers lanes act on this group's pairs.
+ // false = the scan and the report only.
+ lanes: boolean;
+ // How long a held copy waits for the other copy (days), after which it is
+ // released by itself when that copy still has no transcript.
+ waitDays: number;
+ // The metadata stage: recorded dates at most this many days apart …
+ dateWindowDays: number;
+ // … and runtimes within max(seconds, ratio × the longer runtime).
+ durationToleranceSeconds: number;
+ durationToleranceRatio: number;
+ // Also pair copies inside one member (a channel that re-uploaded its own
+ // streams). Report only: the lanes never act on a pair inside one channel.
+ withinChannels: boolean;
+};
+
+export const SOURCE_GROUP_DEFAULT_WAIT_DAYS = 7;
+export const SOURCE_GROUP_MAX_WAIT_DAYS = 365;
+export const SOURCE_GROUP_DEFAULT_DATE_WINDOW_DAYS = 1;
+export const SOURCE_GROUP_MAX_DATE_WINDOW_DAYS = 7;
+export const SOURCE_GROUP_DEFAULT_DURATION_SECONDS = 120;
+export const SOURCE_GROUP_DEFAULT_DURATION_RATIO = 0.02;
+
+// A group id is a file name (`transcripts/copies/<id>.json`): a lowercase slug.
+export const SOURCE_GROUP_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+// A channel slug as the channels tree names it (the citations' segment rule).
+const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+
+export const SOURCE_GROUP_FIELD_DOCS: FieldDocs<SourceGroup> = {
+ id:
+ "The group's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its scan is kept under " +
+ "(`transcripts/copies/<id>.json`, never published). Omitted: made from `label`. An entry with neither is " +
+ "dropped, and so is a second entry with an id already used.",
+ label: "What the group is called in the report. Omitted: the id.",
+ channels:
+ "The member channels' slugs, IN ORDER OF PREFERENCE: the first is the preferred source and gets new work; " +
+ "the rest are fallbacks, kept, synced and downloaded exactly as before. A slug listed twice, or already in an " +
+ "earlier group, is dropped; a group left with fewer than two channels is dropped. A slug this corpus does not " +
+ "hold is ignored when the group is used.",
+ lanes:
+ "Whether the transcription and Speakers lanes act on the group's pairs: skip a text-confirmed copy whose " +
+ "other copy has the work done, hold a metadata-only one. false = the scan and the report only. Default true.",
+ waitDays:
+ "How long a held copy waits for its other copy, in days from when the scan first saw the pair; after that " +
+ "it is released by itself while the other copy still has no transcript. Clamped to [0, 365]; default 7.",
+ dateWindowDays:
+ "The metadata stage: two videos are candidates when their recorded dates (the channel's title rule, else the " +
+ "upload date) are at most this many days apart. Clamped to [0, 7]; default 1.",
+ durationToleranceSeconds:
+ "The metadata stage: runtimes agree within max(this, `durationToleranceRatio` × the longer). Clamped to " +
+ "[0, 3600]; default 120.",
+ durationToleranceRatio: "See `durationToleranceSeconds`. Clamped to [0, 0.5]; default 0.02.",
+ withinChannels:
+ "Also pair copies inside one member channel (one channel holding two upload series of the same streams). " +
+ "Report only: the lanes never act on a pair inside one channel. Default false.",
+};
+
+function num(value: unknown, fallback: number, min: number, max: number, integer: boolean): number {
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
+ if (!Number.isFinite(n)) return fallback;
+ const v = Math.min(max, Math.max(min, n));
+ return integer ? Math.round(v) : v;
+}
+
+/** A lowercase slug made from free text: "Stream copies!" → "stream-copies". */
+export function sourceGroupIdFrom(text: string): string {
+ return text
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 64)
+ .replace(/-+$/, "");
+}
+
+/**
+ * The block, coerced. Never throws. A channel is kept in the FIRST group that
+ * names it; a duplicate slug inside a group is dropped; a group with fewer than
+ * two channels left, or no usable id, or an id already used, is dropped.
+ */
+export function sanitizeSourceGroups(value: unknown): SourceGroup[] {
+ if (!Array.isArray(value)) return [];
+ const out: SourceGroup[] = [];
+ const ids = new Set<string>();
+ const claimed = new Set<string>();
+ for (const raw of value) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
+ const r = raw as Record<string, unknown>;
+ const rawId = typeof r.id === "string" ? r.id.trim() : "";
+ const rawLabel = typeof r.label === "string" ? r.label.trim() : "";
+ const id = SOURCE_GROUP_ID_RE.test(rawId) ? rawId : sourceGroupIdFrom(rawId || rawLabel);
+ if (!SOURCE_GROUP_ID_RE.test(id) || ids.has(id)) continue;
+ const channels: string[] = [];
+ if (Array.isArray(r.channels)) {
+ for (const c of r.channels) {
+ if (typeof c !== "string") continue;
+ const slug = c.trim();
+ if (!slug || slug === ".." || !CHANNEL_SLUG_RE.test(slug)) continue;
+ if (channels.includes(slug) || claimed.has(slug)) continue;
+ channels.push(slug);
+ }
+ }
+ if (channels.length < 2) continue;
+ ids.add(id);
+ for (const c of channels) claimed.add(c);
+ out.push({
+ id,
+ label: rawLabel || id,
+ channels,
+ lanes: r.lanes === false ? false : true,
+ waitDays: num(r.waitDays, SOURCE_GROUP_DEFAULT_WAIT_DAYS, 0, SOURCE_GROUP_MAX_WAIT_DAYS, false),
+ dateWindowDays: num(r.dateWindowDays, SOURCE_GROUP_DEFAULT_DATE_WINDOW_DAYS, 0, SOURCE_GROUP_MAX_DATE_WINDOW_DAYS, true),
+ durationToleranceSeconds: num(r.durationToleranceSeconds, SOURCE_GROUP_DEFAULT_DURATION_SECONDS, 0, 3600, false),
+ durationToleranceRatio: num(r.durationToleranceRatio, SOURCE_GROUP_DEFAULT_DURATION_RATIO, 0, 0.5, false),
+ withinChannels: r.withinChannels === true,
+ });
+ }
+ return out;
+}
+
+/** The rank of `slug` in its group (0 = preferred), or -1 when it is not a member. */
+export function preferenceRank(group: Pick<SourceGroup, "channels">, slug: string): number {
+ return group.channels.indexOf(slug);
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -17,6 +17,7 @@ import {
JOBS_SETTINGS_FIELD_DOCS,
LOOKOUTS_SETTINGS_FIELD_DOCS,
LOOKOUT_ITEM_FIELD_DOCS,
+ SOURCE_GROUP_FIELD_DOCS,
PRIVACY_SETTINGS_FIELD_DOCS,
SERVICE_COOKIES_SETTINGS_FIELD_DOCS,
VOICE_CONVERT_SETTINGS_FIELD_DOCS,
@@ -225,6 +226,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }],
+ sourceGroups: [{ path: "sourceGroups[]", docs: SOURCE_GROUP_FIELD_DOCS }],
savedVideoBackup: [
{
path: "savedVideoBackup",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -39,6 +39,7 @@ import type { SavedVideoCompactionSettings } from "./savedVideoCompaction";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
import type { LookoutsSettings } from "./lookoutSettings";
+import type { SourceGroup } from "./copies/settings";
import type { PrivacySettings } from "./privacySettings";
import type { VoiceSettings } from "./voiceSettings";
import type { GenerationSettings } from "./generationSettings";
@@ -142,6 +143,8 @@ type PreSchemaSiteSettings = {
serviceCookies: ServiceCookiesSettings;
// Saved lookouts (lane/lookout).
lookouts: LookoutsSettings;
+ // Channels that archive the same recordings (lane cross-source-dupes).
+ sourceGroups: SourceGroup[];
// What the pages show of this machine (demo epic D4).
privacy: PrivacySettings;
};
@@ -150,7 +153,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 49 fields, in file order", () => {
+test("SiteSettings keeps its 50 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -202,6 +205,7 @@ test("SiteSettings keeps its 49 fields, in file order", () => {
"jobs",
"serviceCookies",
"lookouts",
+ "sourceGroups",
"privacy",
]);
// A parsed object carries every key, in that order — writeSettings writes
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -83,6 +83,7 @@ import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeVoice, type VoiceSettings } from "./voiceSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
+import { sanitizeSourceGroups, type SourceGroup } from "./copies/settings";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeSavedVideoCompaction, type SavedVideoCompactionSettings } from "./savedVideoCompaction";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
@@ -115,6 +116,7 @@ export {
} from "./voiceSettings";
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives";
+export { SOURCE_GROUP_FIELD_DOCS, type SourceGroup } from "./copies/settings";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { SAVED_VIDEO_COMPACTION_SETTINGS_FIELD_DOCS, type SavedVideoCompactionSettings } from "./savedVideoCompaction";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
@@ -2101,6 +2103,9 @@ export const siteSettingsSchema = z.object({
lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe(
"Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.",
),
+ sourceGroups: settingsField((v): SourceGroup[] => sanitizeSourceGroups(v)).describe(
+ "Channels that archive the SAME recordings from different sources (lane cross-source-dupes, lib/copies/): each group an ORDERED list of channel slugs, the preferred source first. `pnpm ops copies-scan` pairs the members' videos (recorded date and runtime, then their words) into `transcripts/copies/<id>.json`, never published; `pnpm ops get copies` is the read-only report. With a group, the transcription and Speakers lanes skip a TEXT-CONFIRMED copy whose other copy has the work done, and HOLD a metadata-only one, visibly, until the wait ends or `pnpm ops copies-release` releases it; the copy that already has a transcript keeps it whatever the order. Downloads, files, records and the published sites are untouched, and no time is mapped between copies. Empty = no group, every lane exactly as before. See SourceGroup.",
+ ),
privacy: settingsField((v): PrivacySettings => sanitizePrivacy(v)).describe(
"What the editor's and umtool's pages SHOW of this machine (demo epic D4): local paths with the home directory as `~` or masked, the hostname as a fixed word, private sites left out of the pickers, e-mail addresses masked, and the operator's own display aliases in the source mirror's scrub format. Display only — nothing stored, logged, sent to a job or written to a record changes, and copy buttons copy the real path. Every default is today's behaviour: with the block absent or at its defaults the pages are byte-identical. `archilyzer privacy audit` checks the rendered pages against a denylist. Set with `pnpm ops settings --json '{\"patch\":{\"privacy\":{\"displayPaths\":\"home\"}}}'`. See PrivacySettings and common/lib/privacy/.",
),
diff --git a/common/views/activeJobs.ts b/common/views/activeJobs.ts
@@ -401,6 +401,8 @@ function autoIdleNote(
switch (reason) {
case "no-pending":
return "nothing pending";
+ case "copies-held":
+ return "every pending video is a copy skipped or held for its source group (pnpm ops get copies)";
case "capped":
return "every route to the work is at a worker cap";
case "cooldown":
diff --git a/common/views/autoQueueStatus.ts b/common/views/autoQueueStatus.ts
@@ -1,3 +1,4 @@
+import type { CopyHoldSummary } from "../lib/copies/laneHold";
import type { LiveInputs } from "./inputs";
import {
type AutoRunnerStatus,
@@ -90,6 +91,9 @@ export type AutoQueueKindStatus = {
recencyByVideo: Record<string, RecencyKeyView>;
// What the policy would dispatch next, and which rules it passed over.
nextUp: NextUpView | null;
+ // The copies this lane skips or holds for a source group, each with its
+ // reason (lane cross-source-dupes). Absent while no group acts on the lane.
+ copies?: CopyHoldSummary;
picks: AutoQueuePick[];
// Platforms paused by a rate-limit/network backoff (download kind only).
cooldowns: PlatformCooldownView[];
@@ -248,6 +252,7 @@ function buildKind(
ownerByVideo: pending.owner,
recencyByVideo: pending.recency,
nextUp: pending.nextUp,
+ ...(pending.copies ? { copies: pending.copies } : {}),
picks: inputs.state[kind].picks,
cooldowns,
deferred,
diff --git a/editor/app/operations/components/dispatch.ts b/editor/app/operations/components/dispatch.ts
@@ -150,6 +150,8 @@ export function idleReasonText(
switch (reason) {
case "no-pending":
return "nothing pending — every rule is empty";
+ case "copies-held":
+ return "every pending video is a copy another source has done or will do — skipped or held (pnpm ops get copies)";
case "capped":
return "work exists, but every route to it is at a worker cap";
case "cooldown":