// 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/.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 { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { readChannelConfig } from "./channels"; import { readChannelRecords } from "./mirrorScan"; import { classifyCandidate, copyCandidates, COPY_RUNTIME_PER_VIDEO, cuesToWords, prepareCopyText, runtimeCandidates, textEvidence, wantsRuntimeSearch, type CopyRecord, type CopyText, type TextEvidence, } from "../lib/copies/match"; import { COPIES_FORMAT, COPIES_VERSION, copyPairKey, resolveCopyPairRef, resolveCopyVideoRef, type CopiesDecisionsFile, type CopiesFile, type CopiesTotals, type CopyDecisionBy, type CopyMember, type CopyPairRecord, } from "../lib/copies/file"; import { readCopiesDecisions, readCopiesFile, updateCopiesDecisions, writeCopiesFile } from "../lib/copies/file-server"; import { SOURCE_GROUP_ID_RE, type SourceGroup } from "../lib/copies/settings"; import { dateChannel, datingAdvice, noCandidatesAdvice, type ChannelDating, type DatedChannel } from "../lib/copies/dating"; export const COPIES_SCAN_JOB_KIND = "copies-scan"; // One scan at a time, machine-wide: each reads thousands of cue files. 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", "by"] as const; export const COPIES_DECIDE_BODY_KEYS = ["group", "pair", "pairs", "undo", "note", "by"] as const; // How many videos' words (with their phrase index) are kept while a scan // walks its candidates. const WORDS_CACHE = 16; // The scan gives the event loop back at least this often (ms): it runs in the // editor's process, beside the lanes and the pages. const SCAN_SLICE_MS = 15; function groupOf(settings: Pick, 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, id: string, ): Promise { 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":["",""]}]}}'` ); } 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 readText(paths: Paths, channel: string, dir: string): Promise { 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) ? prepareCopyText(cuesToWords(raw.cues)) : null; } catch { return null; } } const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve)); export class CopiesScanCancelled extends Error { constructor() { super("copies scan cancelled: nothing was written"); } } function member(r: CopyRecord): CopyMember { return { channel: r.channel, dir: r.dir, id: r.id, title: r.title, duration: r.duration, date: r.date, ...(r.dateFrom !== undefined ? { dateFrom: r.dateFrom } : {}), }; } async function hasCuesFile(paths: Paths, r: CopyRecord): Promise { return stat(path.join(paths.channelsDir, r.channel, "data", r.dir, CUES_JSON_FILENAME)).then( (s) => s.isFile() && s.size > 0, () => false, ); } export type CopiesScanOptions = { dryRun?: boolean; jobId?: string; onLog?: (line: string) => void; now?: () => Date; // A cancelled scan stops between pairs and writes nothing. signal?: AbortSignal; }; 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, f.dating ?? {}, f.advice ?? []]); } export async function runCopiesScan( paths: Paths, settings: Pick, id: string, opts: CopiesScanOptions = {}, ): Promise { const log = opts.onLog ?? (() => {}); const checkCancel = () => { if (opts.signal?.aborted) throw new CopiesScanCancelled(); }; let sliceAt = Date.now(); // CHUNKED: the matching is synchronous work, so the event loop is handed // back every SCAN_SLICE_MS, and a cancel is seen at the same points. const breathe = async () => { if (Date.now() - sliceAt >= SCAN_SLICE_MS) { await yieldToLoop(); sliceAt = Date.now(); } checkCancel(); }; 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 = {}; const datings = new Map>(); let undated = 0; for (const slug of group.channels) { checkCancel(); const config = await readChannelConfig(paths, slug); if (!config) { missing.push(slug); continue; } const c = await readChannelRecords(paths, slug); videos[slug] = c.records.length; // DATED BY THE BEST EVIDENCE EACH VIDEO HAS (lib/copies/dating.ts): the // channel's rule, a live stream's own day, a date its titles carry, its upload. const d = dateChannel(c.records, !!config.recordedDate); datings.set(slug, d); for (const { record: r, date, from } of d.dated) { if (!date) undated++; records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date, dateFrom: from }); } const by = Object.entries(d.dating.byFrom) .filter(([, n]) => n > 0) .map(([k, n]) => `${n} by ${k === "none" ? "nothing (undated)" : k}`) .join(", "); log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk); dated ${by || "none"}`); } if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`); const candidates = copyCandidates(group, records); log(`${candidates.length} candidate pairs dated within ${group.dateWindowDays} day(s)`); // THE RUNTIME SEARCH for videos whose date cannot pair them (only an upload // day, or none) and that found no candidate by date: bounded, and decided by // the words only (lib/copies/match.ts runtimeCandidates). const pairedByDate = new Set(); for (const c of candidates) { if (c.a.channel === c.b.channel) continue; pairedByDate.add(`${c.a.channel}/${c.a.dir}`); pairedByDate.add(`${c.b.channel}/${c.b.dir}`); } const ruled = new Set([...datings].filter(([, d]) => d.dating.ruleSet).map(([slug]) => slug)); const textKnown = new Set(); if (wantsRuntimeSearch(records, ruled)) { for (const r of records) { await breathe(); if (r.duration > 0 && (await hasCuesFile(paths, r))) textKnown.add(`${r.channel}/${r.dir}`); } } const search = await runtimeCandidates(group, records, { hasText: (r) => textKnown.has(`${r.channel}/${r.dir}`), dated: pairedByDate, ruled, breathe, }); if (search.searched > 0 || search.capped > 0) { log( `${search.candidates.length} candidate pairs by runtime for ${search.searched} video(s) with no date to pair by` + `${search.capped ? ` (${search.capped} more left unsearched: the scan's cap)` : ""}`, ); } const runtimeSentence = search.searched > 0 || search.capped > 0 ? `Those with words were looked for by runtime instead (at most ${COPY_RUNTIME_PER_VIDEO} nearest each): ${search.searched} searched, ` + `${search.candidates.length} compared${search.capped ? `, ${search.capped} left unsearched by the cap` : ""}.` : null; const advice: string[] = []; for (const [slug, d] of datings) advice.push(...datingAdvice(slug, d, d.dating.byFrom.upload + d.dating.byFrom.none > 0 ? runtimeSentence : null)); const crossDated = candidates.some((c) => c.a.channel !== c.b.channel); if (!crossDated && datings.size >= 2 && records.length > 0) { advice.push(noCandidatesAdvice(group.dateWindowDays, [...datings].map(([slug, d]) => ({ slug, span: d.dating.span })))); } for (const a of advice) log(`note: ${a}`); // A small cache of words and their phrase index: candidates come grouped // by their `a` side, so each is built once per run of its candidates. const cache = new Map(); const wordsOf = async (r: CopyRecord): Promise => { 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 readText(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, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0, ...(search.searched > 0 || search.capped > 0 ? { runtime: { searched: search.searched, candidates: search.candidates.length, rejected: 0, capped: search.capped } } : {}), }; const pairs: CopyPairRecord[] = []; for (const c of [...candidates, ...search.candidates]) { await breathe(); const [wa, wb] = [await wordsOf(c.a), await wordsOf(c.b)]; const text: TextEvidence | null = wa && wb ? textEvidence(wa, wb) : null; const usable = text && text.verdict !== "no-text" ? text : null; const cls = classifyCandidate(c, usable); if (!cls) { if (usable) { if (c.via === "runtime") totals.runtime!.rejected++; else totals.rejected++; } continue; } const { link } = cls; const key = copyPairKey(c.a, c.b); const withinChannel = c.a.channel === c.b.channel; if (link === "part-of") totals.partOf++; else totals[link]++; if (withinChannel) totals.withinChannel++; pairs.push({ key, a: member(c.a), b: member(c.b), link, ...(cls.part ? { part: cls.part } : {}), withinChannel, evidence: { kind: usable ? "text" : "metadata", via: c.via ?? "date", 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, dating: Object.fromEntries([...datings].map(([slug, d]) => [slug, d.dating])) as Record, ...(advice.length > 0 ? { advice } : {}), }; log( `${totals.confirmed} confirmed by text and runtime, ${totals.metadata} metadata only, ${totals.partOf} part of ` + `the other, ${totals.overlaps} overlapping, ${totals.rejected} rejected by text` + `${totals.withinChannel ? `; ${totals.withinChannel} inside one channel (report only)` : ""}`, ); checkCancel(); 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, ...(f.dating ? { dating: f.dating } : {}), ...(f.advice ? { advice: f.advice } : {}), }; } export type CopiesScanBody = { group: string; dryRun: boolean }; export function parseCopiesScanBody(raw: Record): 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, deps: { paths: Paths; settings: Pick; now?: () => Date }, ): Promise { 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, signal, ...(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))}`); }, }); } // --- A person's word: release a video, confirm or reject a pair ------------ const BY_VALUES: readonly CopyDecisionBy[] = ["operator", "agent"]; // `by` is the caller's word, as judge-trending takes it: the route cannot tell // who is asking. Default "agent". function parseBy(raw: Record): CopyDecisionBy { if (raw.by === undefined) return "agent"; if (typeof raw.by !== "string" || !BY_VALUES.includes(raw.by as CopyDecisionBy)) { throw new Error('"by" is "operator" or "agent" (the default)'); } return raw.by as CopyDecisionBy; } function parseCommon(raw: Record): { group: string; undo: boolean; note?: string; by: CopyDecisionBy } { 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'); 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, undo: raw.undo === true, ...(note ? { note } : {}), by: parseBy(raw) }; } function listOf(raw: Record, one: string, many: string): unknown[] { if (raw[many] !== undefined) return Array.isArray(raw[many]) ? (raw[many] as unknown[]) : [null]; return raw[one] !== undefined ? [raw[one]] : []; } export type CopiesReleaseBody = { group: string; videos: string[]; undo: boolean; note?: string; by: CopyDecisionBy }; const VIDEO_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[^/|\s]{1,200}$/; const validVideoRef = (v: unknown): v is string => typeof v === "string" && VIDEO_KEY_RE.test(v.trim()) && !v.includes(".."); export function parseCopiesReleaseBody(raw: Record): CopiesReleaseBody { const common = parseCommon(raw); const list = listOf(raw, "video", "videos"); if (list.length === 0) throw new Error('"video" ("/" or "/") or "videos" ([…]) is required'); const videos: string[] = []; for (const v of list) { if (!validVideoRef(v)) { throw new Error(`not a video key: ${JSON.stringify(v)} — "/" (or "/"), as the report names it`); } if (!videos.includes(v.trim())) videos.push(v.trim()); } return { ...common, videos }; } export type CopiesDecideBody = { group: string; pairs: string[]; undo: boolean; note?: string; by: CopyDecisionBy }; export function parseCopiesDecideBody(raw: Record): CopiesDecideBody { const common = parseCommon(raw); const list = listOf(raw, "pair", "pairs"); if (list.length === 0) throw new Error('"pair" ("/|/", as get copies names it) or "pairs" ([…]) is required'); const pairs: string[] = []; for (const v of list) { const parts = typeof v === "string" ? v.trim().split("|") : []; if (parts.length !== 2 || !parts.every(validVideoRef)) { throw new Error(`not a pair: ${JSON.stringify(v)} — "/|/" (a dir or an id), as get copies names it`); } const ref = parts.join("|"); if (!pairs.includes(ref)) pairs.push(ref); } return { ...common, pairs }; } export type CopiesDecisionAction = "release" | "confirm" | "reject"; export type CopiesDecisionResult = | { ok: false; status: number; error: string } | { ok: true; group: string; action: CopiesDecisionAction; undo: boolean; // The keys written (a video's `/`, a pair's key). applied: string[]; // What the scan does not list: nothing was stored for these. unknown: string[]; // Listed, but not something this action takes, each with why. skipped: { ref: string; reason: string }[]; // The group's decisions of this kind after the write. now: string[]; }; function confirmRefusal(p: CopyPairRecord): string | null { if (p.withinChannel) return "both copies are on one channel: the lanes never act on such a pair"; if (p.link === "confirmed") return "already confirmed by its words and runtime"; if (p.link === "part-of") return "the words say one copy is part of the other: a part is not a copy of the whole"; if (p.link === "overlaps") return "the words say the two only share a stretch: not the same recording"; return null; } /** * THE THREE WORDS a person (or an agent, by its own word) gives on a group's * copies, checked against the scan before anything is written: `release` a * held or skipped video to its lanes; `confirm` a metadata-only pair as the * same recording (its copy is then skipped once the other copy is done); * `reject` a pair (it never holds or skips again). `undo` takes any of them * back. A video or pair may be named by dir or by id. What the scan does not * list is reported in `unknown` and not stored. */ export async function applyCopiesDecision( paths: Paths, settings: Pick, action: CopiesDecisionAction, raw: Record, deps: { now?: () => Date } = {}, ): Promise { let parsed: CopiesReleaseBody | CopiesDecideBody; try { parsed = action === "release" ? parseCopiesReleaseBody(raw) : parseCopiesDecideBody(raw); } catch (e) { return { ok: false, status: 400, error: (e as Error).message }; } const groups = settings.sourceGroups ?? []; if (!groups.some((g) => g.id === parsed.group)) { return { ok: false, status: 404, error: `no source group "${parsed.group}" — settings.sourceGroups names ${groups.map((g) => g.id).join(", ") || "none"}`, }; } const [file, decisions] = await Promise.all([ readCopiesFile(paths.transcriptsDir, parsed.group), readCopiesDecisions(paths.transcriptsDir, parsed.group), ]); const applied: string[] = []; const unknown: string[] = []; const skipped: { ref: string; reason: string }[] = []; const held = (kind: "released" | "confirmed" | "rejected") => decisions[kind]; if (action === "release") { for (const ref of (parsed as CopiesReleaseBody).videos) { const key = resolveCopyVideoRef(file, ref) ?? (parsed.undo && held("released")[ref] ? ref : null); if (!key) unknown.push(ref); else if (!applied.includes(key)) applied.push(key); } } else { const kind = action === "confirm" ? "confirmed" : "rejected"; for (const ref of (parsed as CopiesDecideBody).pairs) { const pair = resolveCopyPairRef(file, ref); const key = pair?.key ?? (parsed.undo && held(kind)[ref] ? ref : null); if (!key) { unknown.push(ref); continue; } const why = action === "confirm" && !parsed.undo && pair ? confirmRefusal(pair) : null; if (why) skipped.push({ ref, reason: why }); else if (!applied.includes(key)) applied.push(key); } } let next: CopiesDecisionsFile = decisions; if (applied.length > 0) { next = await updateCopiesDecisions(paths.transcriptsDir, parsed.group, { ...(action === "release" ? { release: applied } : action === "confirm" ? { confirm: applied } : { reject: applied }), undo: parsed.undo, by: parsed.by, ...(parsed.note ? { note: parsed.note } : {}), ...(deps.now ? { now: deps.now } : {}), }); } const kind = action === "release" ? "released" : action === "confirm" ? "confirmed" : "rejected"; return { ok: true, group: parsed.group, action, undo: parsed.undo, applied, unknown, skipped, now: Object.keys(next[kind]), }; } // --- The report: read only -------------------------------------------------- export type CopiesMemberBytes = { bytes: number | null; videos: number; heldBy?: string }; // A metadata-only pair the lanes may hold now, with what a person needs to // confirm or reject it. export type CopiesMetadataPairView = { key: string; a: CopyMember; b: CopyMember; dateDeltaDays: number; // |a.duration − b.duration|, seconds. durationDifferenceSeconds: number; firstSeenAt: string; // When its hold ends by itself (ISO-8601). waitEnds: string; }; export type CopiesGroupReport = { id: string; label: string; channels: { slug: string; rank: number; inCorpus: boolean }[]; lanes: boolean; waitDays: number; captionsCountAsDone: boolean; scan: null | { generatedAt: string; jobId?: string; totals: CopiesTotals; missing?: string[]; // What the scan said about its own inputs (CopiesFile.advice). advice?: string[]; }; // Cross-channel pairs by link (a metadata pair a person confirmed counts as // confirmed; a rejected pair counts nowhere but `rejected`); the pairs // inside one channel apart. pairs: { confirmed: number; confirmedByDecision: number; metadata: number; partOf: number; overlaps: number; rejected: 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 }; // The undecided metadata-only pairs still inside their wait — the ones a // lane may be holding — with their evidence, oldest first, for confirming // (or rejecting) in bulk. metadataPairs: CopiesMetadataPairView[]; confirmHint: string; decisions: { released: string[]; confirmed: { key: string; at: string; by: string; note?: string }[]; rejected: { key: string; at: string; by: string; note?: string }[]; }; // With `pairs` asked for: every pair, as the file holds it. list?: CopyPairRecord[]; }; async function audioBytesOf(dir: string): Promise { 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; } const DAY_MS = 86_400_000; export async function copiesReport( paths: Paths, settings: Pick, opts: { group?: string | null; pairs?: boolean; now?: number } = {}, ): Promise { const now = opts.now ?? Date.now(); const groups = (settings.sourceGroups ?? []).filter((g) => !opts.group || g.id === opts.group); const out: CopiesGroupReport[] = []; for (const g of groups) { const [file, decisions] = await Promise.all([ readCopiesFile(paths.transcriptsDir, g.id), readCopiesDecisions(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, confirmedByDecision: 0, metadata: 0, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0 }; const metadataPairs: CopiesMetadataPairView[] = []; const copiesByChannel = new Map>(); for (const p of file?.pairs ?? []) { if (p.withinChannel) { pairs.withinChannel++; continue; } if (decisions.rejected[p.key]) { pairs.rejected++; continue; } const byDecision = p.link === "metadata" && !!decisions.confirmed[p.key]; if (byDecision) pairs.confirmedByDecision++; if (p.link === "confirmed" || byDecision) pairs.confirmed++; else if (p.link === "metadata") pairs.metadata++; else if (p.link === "part-of") pairs.partOf++; else pairs.overlaps++; if (p.link === "metadata" && !byDecision) { const seen = Date.parse(p.firstSeenAt); const ends = (Number.isFinite(seen) ? seen : 0) + g.waitDays * DAY_MS; if (now < ends) { metadataPairs.push({ key: p.key, a: p.a, b: p.b, dateDeltaDays: p.evidence.dateDeltaDays ?? 0, durationDifferenceSeconds: Math.round(Math.abs(p.a.duration - p.b.duration)), firstSeenAt: p.firstSeenAt, waitEnds: new Date(ends).toISOString(), }); } } if (!(p.link === "confirmed" || byDecision)) 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(); m.set(copy.dir, copy.duration); copiesByChannel.set(copy.channel, m); } metadataPairs.sort((x, y) => (x.firstSeenAt < y.firstSeenAt ? -1 : x.firstSeenAt > y.firstSeenAt ? 1 : x.key < y.key ? -1 : 1)); let seconds = 0; const byChannel: Record = {}; 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 }; } const decisionList = (m: CopiesDecisionsFile["confirmed"]) => Object.entries(m).map(([key, d]) => ({ key, at: d.at, by: d.by, ...(d.note ? { note: d.note } : {}) })); out.push({ id: g.id, label: g.label, channels, lanes: g.lanes, waitDays: g.waitDays, captionsCountAsDone: g.captionsCountAsDone, scan: file ? { generatedAt: file.generatedAt, ...(file.jobId ? { jobId: file.jobId } : {}), totals: file.totals, ...(file.missing ? { missing: file.missing } : {}), ...(file.advice ? { advice: file.advice } : {}), } : null, pairs, duplicated: { seconds, byChannel }, metadataPairs, confirmHint: `pnpm ops copies-confirm --json '{"group":"${g.id}","pairs":["", …],"by":"operator"}' ` + `(or copies-reject, the same shape)`, decisions: { released: Object.keys(decisions.released), confirmed: decisionList(decisions.confirmed), rejected: decisionList(decisions.rejected), }, ...(opts.pairs ? { list: file?.pairs ?? [] } : {}), }); } return out; }