commit 65e823747517cd530b03c2cfe04e1e381e7c7c47
parent d065a8a887788c08ddc571646ba35bad6dae138b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 04:15:27 -0500
copies: holds always end, confirm means whole, done means real work
Fixes the first review of source groups (slice 1).
- A metadata-only hold always ends: after the group's wait the copy runs,
whatever the other copy's state, and waitDays 0 means no hold. The saving
for unconfirmed matches comes from a person instead: copies-confirm turns
a metadata-only pair into a confirmed one, copies-reject takes a pair off
the lanes for good, and copies-release now checks its keys against the
scan. All three take one or a list, by dir or id, and record who and when
in transcripts/copies/<group>.decisions.json. get copies lists the
metadata pairs in their wait with titles, dates, runtimes and difference.
- The text stage probes both ways, counts each phrase once (a probe only
searches its own stretch) and sums runs of 4 agreeing offsets. A pair is
confirmed only when each copy holds 75 % of the other AND the runtimes
agree within the group's tolerance; a part, a trim or a rerun inside a
longer broadcast is part-of, a shared stretch (a passage, a video both
streams played, boilerplate) is overlaps, and both are reported only.
- Done is real work of the kind the lane would produce: our own transcript
with at least max(50, 10 a minute) words of speech; platform captions only
with the new group setting captionsCountAsDone (default false), and never
a YouTube ASR track the lane would replace. Speakers: the operations'
outputs present, tested over real-shaped sidecars.
- The partner state is cached by size and mtime, re-checked in the
background, single-flight; a tick with nothing changed reads no
transcript file. The scan yields to the event loop and stops on cancel
with nothing written.
- Chains resolve: a copy is judged against the copy its partner resolved
to, never held behind one that is itself held or skipped.
- The status memo key includes sourceGroups.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
22 files changed, 2001 insertions(+), 496 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -234,8 +234,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -> {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.<profile>.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` |
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
-| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -> {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their recorded dates are at most dateWindowDays apart; where both have a cue file their words decide (40 phrases probed, the largest set at one consistent offset: 8 or more confirmed, 4-7 partial, fewer not a pair), and where one has no words agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/<group>.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done and hold a metadata-only one (get copies says each one's reason). dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals}. | |
-| `copies-release` | copies-release releases copies to their lanes: {"group", "video": "<channel>/<dir>" \| "videos": \[...\], "undo"?, "note"?} -> {group, released}. A released video is queued by its lanes as if it had no source group, whether it was held (a metadata-only match, or waiting on its preferred copy) or skipped; undo takes the release back. Written to transcripts/copies/<group>.releases.json, which the scan never touches. | |
+| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -> {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their recorded dates are at most dateWindowDays apart. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/<group>.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals}. | |
+| `copies-release` | copies-release releases copies to their lanes: {"group", "video": "<channel>/<dir>" \| "videos": \[...\], "undo"?, "note"?, "by"?} -> {group, action, undo, applied, unknown, skipped, now}. A released video is queued by its lanes as if it had no source group, whether it was held or skipped; undo takes the release back. A video may be named by its dir or its id (a Rumble video's differ); one the scan does not list is reported in unknown and not stored. by is "operator" or "agent" (the default), the caller's word, recorded with the time and the note in transcripts/copies/<group>.decisions.json, which the scan never touches. | |
+| `copies-confirm` | copies-confirm confirms metadata-only pairs as the same recording: {"group", "pair": "<channel>/<dir>\|<channel>/<dir>" \| "pairs": \[...\], "undo"?, "note"?, "by"?} -> {group, action, undo, applied, unknown, skipped, now}. A confirmed pair acts as one confirmed by text: the copy is skipped once the other copy's work is done. Only a metadata-only pair takes it; a part-of or overlapping one is skipped with the reason. get copies lists the metadata pairs in their wait, with titles, dates and runtimes, for confirming in bulk. Recorded with who and when, as copies-release. | |
+| `copies-reject` | copies-reject rejects pairs: the same body as copies-confirm. A rejected pair never holds or skips again, whatever its link; undo takes it back, and a later confirm replaces it. | |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. A pass the source refuses for the video as members-only or private records that in its availability.json (source fetch); a removal is recorded only by the channel's Check availability. A chat captured while the stream was live is put on the recording's clock (the broadcast's start, or a recording begun "from now" its own start) and its cues say which in "clock". "renormalize": true parses the raw chat already on disk again, fresh or not, with no network — for a chat normalized before that; refused when no raw is here (it never fetches). | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait`<br>`pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>","renormalize":true}' --wait` |
@@ -439,12 +441,16 @@ get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):
get copies [<group>] is the source groups' copies report (settings.sourceGroups,
SETTINGS.md), read only: each group's channels in order of preference,
whether the lanes act on it, its last scan (transcripts/copies/<group>.json:
- when, the totals), its pairs by link (confirmed by text, metadata only,
- partial, inside one channel), what the fallback copies of confirmed
- recordings hold (seconds; audio bytes through tier links, null with the
- reason when a channel's media cannot be read now) and the released videos;
- and `lanes`: what the transcription and Speakers lanes skip and hold right
- now, each video with its reason. With <group>, every pair and its evidence.
+ when, the totals), its pairs by link (confirmed, metadata only, part-of,
+ overlapping, rejected, inside one channel), what the fallback copies of
+ confirmed recordings hold (seconds; audio bytes through tier links, null
+ with the reason when a channel's media cannot be read now), the
+ metadata-only pairs still in their wait (titles, dates, runtimes and
+ their difference, when each wait ends) for copies-confirm or
+ copies-reject in bulk, the decisions given (released, confirmed,
+ rejected, with who and when), and `lanes`: what the transcription and
+ Speakers lanes skip and hold right now, each video with its reason. With
+ <group>, every pair and its evidence.
get lookout-run <id> [--run <runId>] is one lookout's latest run (or the
one named), whole: its window, the selection it read, calls, seconds,
the reading counts (read, reused from fresh notes, failed), its ideas and
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -1546,7 +1546,7 @@ Default:
## `sourceGroups`
-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.
+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, probed both ways) 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 CONFIRMED copy (each holding 75 % of the other's words and runtimes that agree, or confirmed by `pnpm ops copies-confirm`) whose other copy has the work done, and HOLD a metadata-only one, or one waiting on its preferred copy, visibly and for at most `waitDays` — then it runs, whatever the other copy's state. A part-of or overlapping pair is reported, never acted on; `pnpm ops copies-reject` takes a pair off the lanes and `pnpm ops copies-release` runs a copy. The copy that already has the work 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.
#### `sourceGroups[]`
@@ -1557,8 +1557,9 @@ Per entry — each entry spells its own values.
| `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. |
+| `lanes` | Whether the transcription and Speakers lanes act on the group's pairs: skip a CONFIRMED copy (by text and runtime, or by `copies-confirm`) whose other copy has the work done, and hold a metadata-only one or one waiting on its preferred copy for at most `waitDays`. A part-of or overlapping pair is reported, never acted on. false = the scan and the report only. Default true. |
+| `waitDays` | How long a held copy waits, in days from when the scan FIRST SAW the pair (not from when a lane held it: a pair older than this never holds; re-ordering the group makes new pairs and a new wait). After it the copy is released and its lane does the work, whatever the other copy's state — a metadata-only match is never held longer, even when the other copy is done (`copies-confirm` makes it a skip). 0 = no hold at all. Clamped to [0, 365]; default 7. |
+| `captionsCountAsDone` | Whether the other copy's platform captions (a VTT track) count as its transcription done. Default false: only a transcript of our own engine (`transcript.json`) counts, so the fallback copy still gets its own when the preferred copy has captions only. With true a caption track counts, except a YouTube ASR track while the transcription lane would replace it (`replaceAutoSubs`, or a rule on the auto-captions buckets). Either way a transcript counts only with real words for its length (at least max(50, 10 per minute of runtime), bracketed non-speech like [Music] left out). |
| `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. |
diff --git a/common/controller/copies.test.ts b/common/controller/copies.test.ts
@@ -4,18 +4,37 @@
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 { mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { readdir as fsReaddir, readFile, readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
import { tmpdir } from "node:os";
+import { fileURLToPath } from "node:url";
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 {
+ applyCopiesDecision,
+ copiesReport,
+ copiesScanRefusal,
+ CopiesScanCancelled,
+ parseCopiesReleaseBody,
+ runCopiesScan,
+} from "./copiesScan";
+import {
+ copyHoldsForLane,
+ readCopyDone,
+ resetCopiesLaneCacheForTest,
+ setCopiesLaneIoForTest,
+ copiesLaneSettledForTest,
+ type CopiesLaneIo,
+} 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";
+import { copiesDecisionsPath, copiesPath, updateCopiesDecisions } from "../lib/copies/file-server";
+import { defaultSiteSettings, type SiteSettings } from "../lib/settings";
+import { DEFAULT_DIARIZATION_THRESHOLD, DIARIZATION_FILENAME, type DiarizationRecord } from "../lib/diarization";
+import { ATTRIBUTION_FILENAME, ATTRIBUTION_PROMPT_VERSION, type AttributionRecord } from "../lib/attribution";
+import { OLLAMA_DIGEST_APP_ID } from "../lib/digest";
const CATCH_ALL_ROOT = {
id: "root",
@@ -67,6 +86,23 @@ function cues(seed: number, start = 0) {
return out;
}
+// A transcript.json of `words` words of speech (whisper's shape).
+function whisperJson(words: number): string {
+ const segs = [];
+ for (let i = 0; i < words; i += 10) segs.push({ text: Array.from({ length: Math.min(10, words - i) }, (_, j) => `word${(i + j) % 97}`).join(" "), offsets: { from: i * 400, to: (i + 10) * 400 } });
+ return JSON.stringify({ transcription: segs });
+}
+
+// A VTT of `lines` cues, each `text`; `asr` marks it as YouTube's speech recognition.
+function vtt(lines: number, text: (i: number) => string, asr = false): string {
+ const ts = (s: number) => `${String(Math.floor(s / 3600)).padStart(2, "0")}:${String(Math.floor((s % 3600) / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`;
+ let out = "WEBVTT\nKind: captions\nLanguage: en\n\n";
+ for (let i = 0; i < lines; i++) {
+ out += `${ts(i * 4)} --> ${ts(i * 4 + 4)}${asr ? " align:start position:0%" : ""}\n${text(i)}\n\n`;
+ }
+ 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" }));
@@ -75,16 +111,16 @@ function channel(p: Paths, slug: string): void {
function video(
p: Paths,
slug: string,
- id: string,
- o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean; audio?: boolean },
+ dir: string,
+ o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean | number; audio?: boolean; id?: string },
): void {
- const d = path.join(p.channelsDir, slug, "data", id);
+ const d = path.join(p.channelsDir, slug, "data", dir);
mkdirSync(d, { recursive: true });
+ const id = o.id ?? dir;
writeFileSync(path.join(d, "metadata.info.json"), JSON.stringify({ id, title: `Stream ${id}`, duration: o.duration, upload_date: o.date }));
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 } }] }));
- }
+ // A real-length transcript by default: 20 words a minute of runtime.
+ if (o.transcript) writeFileSync(path.join(d, "transcript.json"), whisperJson(typeof o.transcript === "number" ? o.transcript : Math.ceil((o.duration / 60) * 20)));
if (o.audio) writeFileSync(path.join(d, "audio.mp3"), Buffer.alloc(1234));
}
@@ -133,10 +169,31 @@ test("the scan records how each pair was matched, and its evidence", async () =>
);
assert.equal(f.pairs[0].evidence.text?.verdict, "same");
assert.equal(f.pairs[0].evidence.text?.offsetMedianSeconds, 45);
+ assert.ok(f.pairs[0].evidence.text!.bInA.fraction >= 0.75, "probed both ways");
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("a part of a stream is recorded part-of, and never reaches a lane", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ const whole = cues(9);
+ video(p, "mirror-chan", "m1", { date: "20260301", duration: 1200, cues: whole, transcript: true, audio: true });
+ // The preferred copy is the stream's middle fifth, on its own clock.
+ const part = whole.slice(100, 160).map((c) => ({ ...c, start: c.start - 400, end: c.end - 400 }));
+ video(p, "pref-chan", "p1", { date: "20260301", duration: 240, cues: part, audio: true });
+ const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ assert.deepEqual(out.file.pairs.map((x) => [x.link, x.part]), [["part-of", "a"]]);
+ assert.equal(out.file.totals.partOf, 1);
+ snapshot(p, "pref-chan", ["p1"]);
+ snapshot(p, "mirror-chan", []);
+ writeSettings({ sourceGroups: [GROUP] });
+ const r = await lane(p);
+ assert.deepEqual(allPending(r), ["p1"], "a part is transcribed for itself");
+ assert.equal(r.copies, undefined, "no pair the lanes act on, so the lane is today's");
+});
+
test("the scan is idempotent: a second run changes nothing and keeps firstSeenAt", async () => {
const p = corpus();
streams(p);
@@ -162,11 +219,21 @@ test("the scan is idempotent: a second run changes nothing and keeps firstSeenAt
);
});
-test("a dry run writes nothing; an unknown group or a group short of channels is refused", async () => {
+test("a dry run writes nothing, over an existing file too; 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"]);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ const file = copiesPath(p.transcriptsDir, "stream-copies");
+ const bytes = readFileSync(file);
+ const mtime = statSync(file).mtimeMs;
+ video(p, "pref-chan", "p4", { date: "20260320", duration: 5010 });
+ const dry = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true });
+ assert.equal(dry.unchanged, false, "the dry run sees the new pair");
+ assert.equal(dry.path, undefined);
+ assert.ok(readFileSync(file).equals(bytes), "and leaves the file byte for byte");
+ assert.equal(statSync(file).mtimeMs, mtime);
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"))!,
@@ -175,27 +242,67 @@ test("a dry run writes nothing; an unknown group or a group short of channels is
assert.throws(() => parseCopiesReleaseBody({ group: "stream-copies", video: "../x" }), /not a video key/);
});
-async function lane(p: Paths) {
+test("a cancelled scan stops between pairs and writes nothing", async () => {
+ const p = corpus();
+ streams(p);
+ const early = new AbortController();
+ early.abort();
+ await assert.rejects(runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { signal: early.signal }), CopiesScanCancelled);
+ // Mid-scan: cancelled once the candidates are listed.
+ const mid = new AbortController();
+ await assert.rejects(
+ runCopiesScan(p, settingsWith([GROUP]), "stream-copies", {
+ signal: mid.signal,
+ onLog: (l) => {
+ if (/candidate pairs/.test(l)) mid.abort();
+ },
+ }),
+ CopiesScanCancelled,
+ );
+ assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"], "no copies file");
+});
+
+async function lane(p: Paths, kind: "transcription" | "backfill" = "transcription") {
resetCopiesLaneCacheForTest();
- return computeLeafPending("transcription", p, { state: emptyAutoQueueState() });
+ return computeLeafPending(kind, 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 () => {
+// Counts every disk call the lanes' copies code makes.
+function countingIo(): { io: CopiesLaneIo; calls: string[] } {
+ const calls: string[] = [];
+ return {
+ calls,
+ io: {
+ readFile: (f) => (calls.push(`readFile ${path.basename(f)}`), fsReadFile(f, "utf8")),
+ readdir: (f) => (calls.push(`readdir ${path.basename(f)}`), fsReaddir(f)),
+ stat: (f) => (calls.push(`stat ${path.basename(f)}`), fsStat(f)),
+ },
+ };
+}
+
+test("no group configured: the lane is exactly what it was, with no copies disk call (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");
+ const { io, calls } = countingIo();
+ setCopiesLaneIoForTest(io);
+ try {
+ 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");
+ assert.deepEqual(calls, [], "not one stat, readdir or read");
+ } finally {
+ setCopiesLaneIoForTest(null);
+ }
});
test("with the group: the done copy's twin is skipped, the metadata match held, and both are reversible", async () => {
@@ -207,29 +314,224 @@ test("with the group: the done copy's twin is skipped, the metadata match held,
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"]);
+ // m2: probably p2 (date + runtime only), p2 not done but queued? No: p2 is
+ // not pending here (no audio), so nothing waits on it — m2 runs.
+ assert.deepEqual(allPending(r), ["m2", "m3", "m4"]);
assert.equal(r.copies?.skipped, 1);
- assert.equal(r.copies?.held, 1);
- const [skip, hold] = r.copies!.head;
+ const [skip] = 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"]);
+
+ // p2 queued: m2 is held behind it, with the date its hold ends.
+ snapshot(p, "pref-chan", ["p1", "p2"]);
+ const held = await lane(p);
+ assert.deepEqual(allPending(held), ["m3", "m4", "p2"]);
+ const hold = held.copies!.head.find((d) => d.id === "m2")!;
+ assert.deepEqual([hold.action, hold.link], ["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"]);
+ await updateCopiesDecisions(p.transcriptsDir, "stream-copies", { release: ["mirror-chan/m2"], by: "operator" });
+ assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p2"]);
+ await updateCopiesDecisions(p.transcriptsDir, "stream-copies", { release: ["mirror-chan/m2"], undo: true, by: "operator" });
+ assert.deepEqual(allPending(await lane(p)), ["m3", "m4", "p2"]);
// Removing the group restores the lane; nothing was deleted on the way.
writeSettings({});
- assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p1"]);
+ assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p1", "p2"]);
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 channel taken out of the group, or renamed in it, drops its pairs and restores the lane", 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] });
+ assert.deepEqual(allPending(await lane(p)), []);
+ writeSettings({ sourceGroups: [{ id: "stream-copies", channels: ["pref-chan", "mirror-chan-renamed"] }] });
+ assert.deepEqual(allPending(await lane(p)), ["p1"]);
+});
+
+test("confirm, reject and release: checked against the scan, by dir or id, with who and when", async () => {
+ const p = corpus();
+ streams(p);
+ // A Rumble-like video: its dir (the URL slug) is not its id (the embed id).
+ video(p, "mirror-chan", "stream-slug-m5", { id: "v5embed", date: "20260325", duration: 6000, audio: true });
+ video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, audio: true });
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ const settings = settingsWith([GROUP]);
+ const now = () => new Date("2026-03-26T00:00:00Z");
+
+ // Named by the EMBED id, in the other order: resolves to the pair keyed by dir.
+ const c = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pair: "mirror-chan/v5embed|pref-chan/p5", by: "operator", note: "listened" }, { now });
+ assert.equal(c.ok, true);
+ if (!c.ok) return;
+ assert.deepEqual(c.applied, ["pref-chan/p5|mirror-chan/stream-slug-m5"]);
+ const file = JSON.parse(readFileSync(copiesDecisionsPath(p.transcriptsDir, "stream-copies"), "utf8"));
+ assert.deepEqual(file.confirmed["pref-chan/p5|mirror-chan/stream-slug-m5"], { at: "2026-03-26T00:00:00.000Z", by: "operator", note: "listened" });
+
+ // A text-confirmed pair cannot be confirmed again; an unknown one is reported, nothing stored for it.
+ const c2 = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pairs: ["pref-chan/p1|mirror-chan/m1", "pref-chan/nope|mirror-chan/m9"] });
+ assert.ok(c2.ok);
+ if (!c2.ok) return;
+ assert.deepEqual(c2.applied, []);
+ assert.deepEqual(c2.unknown, ["pref-chan/nope|mirror-chan/m9"]);
+ assert.match(c2.skipped[0].reason, /already confirmed/);
+
+ // Release by the id form lands on the dir key; an unknown video is reported.
+ const rel = await applyCopiesDecision(p, settings, "release", { group: "stream-copies", videos: ["mirror-chan/v5embed", "mirror-chan/zzz"] });
+ assert.ok(rel.ok);
+ if (!rel.ok) return;
+ assert.deepEqual([rel.applied, rel.unknown], [["mirror-chan/stream-slug-m5"], ["mirror-chan/zzz"]]);
+
+ // Reject replaces the confirm.
+ const rj = await applyCopiesDecision(p, settings, "reject", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/stream-slug-m5" });
+ assert.ok(rj.ok);
+ const after = JSON.parse(readFileSync(copiesDecisionsPath(p.transcriptsDir, "stream-copies"), "utf8"));
+ assert.deepEqual(Object.keys(after.confirmed), []);
+ assert.equal(after.rejected["pref-chan/p5|mirror-chan/stream-slug-m5"].by, "agent", "the default hand");
+ const bad = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pair: "p5" });
+ assert.equal(bad.ok, false);
+ assert.equal((await applyCopiesDecision(p, settings, "reject", { group: "other", pair: "a/b|c/d" })).ok, false);
+});
+
+test("the lanes key a Rumble-like video by its dir: held under the dir the snapshot lists, released by its id", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ video(p, "mirror-chan", "stream-slug-m5", { id: "v5embed", date: "20260325", duration: 6000, audio: true });
+ video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, audio: true });
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ snapshot(p, "pref-chan", ["p5"]);
+ snapshot(p, "mirror-chan", ["stream-slug-m5"]);
+ writeSettings({ sourceGroups: [GROUP] });
+ const r = await lane(p);
+ assert.deepEqual(allPending(r), ["p5"]);
+ assert.deepEqual(r.copies!.head.map((d) => [d.channel, d.id, d.action]), [["mirror-chan", "stream-slug-m5", "hold"]]);
+ await applyCopiesDecision(p, settingsWith([GROUP]), "release", { group: "stream-copies", video: "mirror-chan/v5embed" });
+ assert.deepEqual(allPending(await lane(p)), ["p5", "stream-slug-m5"]);
+});
+
+test("a confirmed pair whose other copy is done skips; a rejected pair never acts again", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, transcript: true });
+ video(p, "mirror-chan", "m5", { date: "20260325", duration: 6000, audio: true });
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ snapshot(p, "pref-chan", []);
+ snapshot(p, "mirror-chan", ["m5"]);
+ writeSettings({ sourceGroups: [GROUP] });
+ assert.equal((await lane(p)).copies!.head[0].action, "hold", "metadata only: held within the wait");
+ await applyCopiesDecision(p, settingsWith([GROUP]), "confirm", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/m5", by: "operator" });
+ const confirmed = await lane(p);
+ assert.deepEqual(allPending(confirmed), []);
+ assert.equal(confirmed.copies!.head[0].action, "skip");
+ assert.match(confirmed.copies!.head[0].reason, /operator's word/);
+ await applyCopiesDecision(p, settingsWith([GROUP]), "reject", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/m5" });
+ assert.deepEqual(allPending(await lane(p)), ["m5"]);
+ const [g] = await copiesReport(p, settingsWith([GROUP]));
+ assert.equal(g.pairs.rejected, 1);
+});
+
+// --- What counts as the other copy's work done ------------------------------
+
+async function doneOf(p: Paths, key: string, o: { captions?: boolean; duration?: number; settings?: SiteSettings } = {}) {
+ resetCopiesLaneCacheForTest();
+ const settings = o.settings ?? defaultSiteSettings();
+ const facts = new Map([[key, { duration: o.duration ?? 600, captionsCountAsDone: o.captions ?? false }]]);
+ return (await readCopyDone("transcription", p, settings, [key], facts)).get(key);
+}
+
+test("transcription done is a transcript the lane would not redo, with real words for its length (fails against any non-empty file)", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ const dir = (id: string) => {
+ const d = path.join(p.channelsDir, "pref-chan", "data", id);
+ mkdirSync(d, { recursive: true });
+ return d;
+ };
+ // Headers only.
+ writeFileSync(path.join(dir("h1"), "transcript.en.vtt"), "WEBVTT\nKind: captions\nLanguage: en\n\n");
+ // Music only.
+ writeFileSync(path.join(dir("h2"), "transcript.en.vtt"), vtt(200, () => "[Music]"));
+ // Real human captions: 200 cues of 8 words = 1600 words for 10 minutes.
+ writeFileSync(path.join(dir("h3"), "transcript.en.vtt"), vtt(200, (i) => `caption line ${i} with some more spoken words`));
+ // YouTube ASR captions, as many words.
+ writeFileSync(path.join(dir("h4"), "transcript.en.vtt"), vtt(200, (i) => `auto line ${i} with some more spoken words`, true));
+ // Our own transcript, too short for 10 minutes, and one of real length.
+ writeFileSync(path.join(dir("h5"), "transcript.json"), whisperJson(20));
+ writeFileSync(path.join(dir("h6"), "transcript.json"), whisperJson(400));
+
+ // captionsCountAsDone is off by default: no caption track counts.
+ for (const id of ["h1", "h2", "h3", "h4"]) assert.equal(await doneOf(p, `pref-chan/${id}`), false, id);
+ assert.equal(await doneOf(p, "pref-chan/h5"), false, "20 words for 10 minutes");
+ assert.equal(await doneOf(p, "pref-chan/h6"), true);
+ // With it on: real captions count, headers-only and music-only never do.
+ assert.equal(await doneOf(p, "pref-chan/h1", { captions: true }), false);
+ assert.equal(await doneOf(p, "pref-chan/h2", { captions: true }), false);
+ assert.equal(await doneOf(p, "pref-chan/h3", { captions: true }), true);
+ assert.equal(await doneOf(p, "pref-chan/h4", { captions: true }), true, "ASR counts while nothing would replace it");
+ // …but not while the transcription lane would replace auto-captions.
+ const replacing = defaultSiteSettings();
+ replacing.autoQueue.transcription.replaceAutoSubs = true;
+ assert.equal(await doneOf(p, "pref-chan/h4", { captions: true, settings: replacing }), false);
+ assert.equal(await doneOf(p, "pref-chan/h3", { captions: true, settings: replacing }), true, "human captions are not replaced");
+});
+
+test("the fallback copy still gets its own transcript when the preferred copy has captions only", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ const words = cues(21);
+ video(p, "pref-chan", "p1", { date: "20260301", duration: 1200, cues: words });
+ writeFileSync(path.join(p.channelsDir, "pref-chan", "data", "p1", "transcript.en.vtt"), vtt(300, (i) => `caption line ${i} with some more spoken words`));
+ video(p, "mirror-chan", "m1", { date: "20260301", duration: 1210, cues: words, audio: true });
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ snapshot(p, "pref-chan", []);
+ snapshot(p, "mirror-chan", ["m1"]);
+ writeSettings({ sourceGroups: [GROUP] });
+ assert.deepEqual(allPending(await lane(p)), ["m1"], "captionsCountAsDone off: m1 is transcribed");
+ writeSettings({ sourceGroups: [{ ...GROUP, captionsCountAsDone: true }] });
+ assert.deepEqual(allPending(await lane(p)), [], "on: the captions stand for the recording");
+});
+
+test("a tick with nothing changed reads no transcript file; a changed transcript is read again, off the tick", 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] });
+ const { io, calls } = countingIo();
+ // Re-checked on every tick (0 ms), to prove the re-check itself reads nothing.
+ setCopiesLaneIoForTest(io, { revalidateMs: 0 });
+ try {
+ resetCopiesLaneCacheForTest();
+ const tick = () => computeLeafPending("transcription", p, { state: emptyAutoQueueState() });
+ assert.deepEqual(allPending(await tick()), []);
+ const reads = () => calls.filter((c) => c.startsWith("readFile")).length;
+ assert.equal(reads(), 1, "the first sight of m1 reads its transcript once");
+ for (let i = 0; i < 3; i++) {
+ assert.deepEqual(allPending(await tick()), []);
+ await copiesLaneSettledForTest();
+ }
+ assert.equal(reads(), 1, "three more ticks, nothing changed: no transcript read");
+ assert.ok(calls.some((c) => c === "stat transcript.json"), "only stats");
+ // m1's transcript replaced by a header-only one: the next re-check reads it.
+ writeFileSync(path.join(p.channelsDir, "mirror-chan", "data", "m1", "transcript.json"), JSON.stringify({ transcription: [] }));
+ await tick();
+ await copiesLaneSettledForTest();
+ assert.equal(reads(), 2);
+ assert.deepEqual(allPending(await tick()), ["p1"], "and the tick after knows m1 is not done");
+ } finally {
+ setCopiesLaneIoForTest(null);
+ }
+});
+
test("a confirmed copy is skipped only when the other copy's transcript is actually there and readable", async () => {
const p = corpus();
streams(p);
@@ -244,19 +546,142 @@ test("a confirmed copy is skipped only when the other copy's transcript is actua
assert.equal(r.copies?.skipped, 0);
});
-test("the report reads the scan, counts the duplicated copies' audio, and writes nothing", async () => {
+// --- Speakers, over real-shaped files ----------------------------------------
+
+function speakersSettings(): SiteSettings {
+ const s = defaultSiteSettings();
+ return {
+ ...s,
+ diarization: {
+ ...s.diarization,
+ enabled: true,
+ segModel: "/opt/models/seg-1.onnx",
+ embModel: "/opt/models/emb-1.onnx",
+ threshold: DEFAULT_DIARIZATION_THRESHOLD,
+ },
+ attribution: {
+ ...s.attribution,
+ enabled: true,
+ diarizedEnabled: true,
+ textOnlyEnabled: true,
+ appId: OLLAMA_DIGEST_APP_ID,
+ model: "qwen2.5:7b",
+ },
+ };
+}
+
+const DIARIZED_AT = "2026-08-06T00:00:00.000Z";
+
+function speakersFiles(d: string, o: { diarization?: boolean; attribution?: boolean }): void {
+ writeFileSync(path.join(d, "transcript.json"), whisperJson(400));
+ if (o.diarization) {
+ writeFileSync(
+ path.join(d, DIARIZATION_FILENAME),
+ JSON.stringify({
+ videoId: path.basename(d),
+ generatedAt: DIARIZED_AT,
+ speakers: 2,
+ turns: [{ start: 0, end: 4, speaker: 0 }],
+ engine: { engine: "sherpa-onnx", segmentationModel: "seg-1.onnx", embeddingModel: "emb-1.onnx", threshold: DEFAULT_DIARIZATION_THRESHOLD },
+ voiceprints: [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb-1.onnx" }],
+ } satisfies DiarizationRecord),
+ );
+ }
+ if (o.attribution) {
+ writeFileSync(
+ path.join(d, ATTRIBUTION_FILENAME),
+ JSON.stringify({
+ videoId: path.basename(d),
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ speakers: [{ index: 0, label: "Host" }],
+ segments: [{ start: 0, end: 10, speaker: 0 }],
+ provenance: {
+ method: "diarized",
+ appId: OLLAMA_DIGEST_APP_ID,
+ model: "qwen2.5:7b",
+ modelRequested: "qwen2.5:7b",
+ promptVersion: ATTRIBUTION_PROMPT_VERSION,
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ diarizationGeneratedAt: DIARIZED_AT,
+ },
+ } satisfies AttributionRecord),
+ );
+ }
+}
+
+test("Speakers: the other copy's diarization and names on disk skip the copy; anything less does not", async () => {
const p = corpus();
streams(p);
await runCopiesScan(p, settingsWith([GROUP]), "stream-copies");
+ const settings = { ...speakersSettings(), sourceGroups: sanitizeSourceGroups([GROUP]) };
+ const m1 = path.join(p.channelsDir, "mirror-chan", "data", "m1");
+ const holds = async () => {
+ resetCopiesLaneCacheForTest();
+ return copyHoldsForLane({
+ kind: "backfill",
+ paths: p,
+ settings,
+ pending: { all: ["p1"] },
+ owner: new Map([["p1", "pref-chan"]]),
+ inFlight: [],
+ });
+ };
+ // m1 has a transcript but no Speakers outputs: p1 gets its own.
+ assert.deepEqual((await holds())!.pending.all, ["p1"]);
+ // Diarized, not yet named: still work on m1, so p1 is not skipped.
+ speakersFiles(m1, { diarization: true });
+ assert.deepEqual((await holds())!.pending.all, ["p1"]);
+ // Diarized and named, both fresh: p1 is skipped.
+ speakersFiles(m1, { diarization: true, attribution: true });
+ const done = (await holds())!;
+ assert.deepEqual(done.pending.all, []);
+ assert.equal(done.decisions[0].action, "skip");
+ assert.match(done.decisions[0].reason, /speakers work is done/);
+ // A malformed diarization file is not done.
+ writeFileSync(path.join(m1, DIARIZATION_FILENAME), "{half written");
+ assert.deepEqual((await holds())!.pending.all, ["p1"]);
+});
+
+test("the report reads the scan, counts the duplicated copies' audio, lists the metadata pairs in their wait, and writes nothing", async () => {
+ const p = corpus();
+ streams(p);
+ await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-21T00:00:00Z") });
const before = readdirSync(path.join(p.transcriptsDir, "copies")).sort();
- const [g] = await copiesReport(p, settingsWith([GROUP]), { pairs: true });
+ const [g] = await copiesReport(p, settingsWith([GROUP]), { pairs: true, now: Date.parse("2026-03-22T00:00:00Z") });
assert.equal(g.id, "stream-copies");
- assert.deepEqual(g.pairs, { confirmed: 1, metadata: 1, partial: 0, withinChannel: 0 });
+ assert.deepEqual(g.pairs, { confirmed: 1, confirmedByDecision: 0, metadata: 1, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0 });
assert.deepEqual(g.duplicated, { seconds: 7260, byChannel: { "mirror-chan": { bytes: 1234, videos: 1 } } });
assert.equal(g.list?.length, 2);
+ assert.deepEqual(
+ g.metadataPairs.map((x) => [x.key, x.a.title, x.b.date, x.durationDifferenceSeconds, x.dateDeltaDays, x.waitEnds]),
+ [["pref-chan/p2|mirror-chan/m2", "Stream p2", "20260306", 30, 1, "2026-03-28T00:00:00.000Z"]],
+ );
+ const [late] = await copiesReport(p, settingsWith([GROUP]), { now: Date.parse("2026-04-01T00:00:00Z") });
+ assert.deepEqual(late.metadataPairs, [], "past its wait a pair holds nothing");
assert.deepEqual(readdirSync(path.join(p.transcriptsDir, "copies")).sort(), before);
});
+test("the lanes' copies are applied in one place: the runner tick and its panel twin, never a manual run", async () => {
+ // A manual transcribe or Speakers run goes through its own route and never
+ // asks copyHoldsForLane; only autoRunner.ts does (twice: the tick and
+ // computeLeafPending).
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
+ const hits: string[] = [];
+ const walk = (dir: string) => {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
+ const f = path.join(dir, e.name);
+ if (e.isDirectory()) walk(f);
+ else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\./.test(e.name)) {
+ const n = (readFileSync(f, "utf8").match(/\bcopyHoldsForLane\(/g) ?? []).length;
+ if (n > 0) hits.push(`${path.relative(root, f)}:${n}`);
+ }
+ }
+ };
+ for (const d of ["common", "editor/app", "scripts"]) walk(path.join(root, d));
+ assert.deepEqual(hits.sort(), ["common/controller/autoRunner.ts:2", "common/controller/copiesLane.ts:1"]);
+});
+
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[] = [];
diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts
@@ -1,29 +1,42 @@
// 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.
+// plan read from settings.sourceGroups, the scan's files and the decisions
+// file, 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.
//
+// OFF THE HOT PATH. What a partner copy holds is read once and kept, keyed by
+// the size and mtime of the files that decide it; a tick answers from that
+// cache, and a cached answer older than COPY_DONE_REVALIDATE_MS is re-checked
+// in the background (one stat per file, single-flight per video) — the file
+// itself is re-read only when its size or mtime moved. Only a copy never seen
+// before is read inline, once.
+//
// 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 { readdir, 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 { isGroup, type AutoQueueKind, type AutoQueueNode, type AutoQueuePolicy } from "../lib/autoQueueTypes";
import { mapConcurrent } from "../lib/concurrency";
-import { isVideoTranscribed, pickIndexTranscript, readVideoFiles } from "../lib/videoStatus";
+import { isTranscriptVtt, readVideoFiles, resolvePrimaryVtt, WHISPER_FILENAME } from "../lib/videoStatus";
+import { parseVtt } from "../lib/vtt";
+import { resolveCaptionsProvenance } from "../lib/subtitleProvenance";
import { operationsForLane } from "../lib/operations";
+import { DIARIZATION_FILENAME } from "../lib/videoStatus";
+import { ATTRIBUTION_FILENAME } from "../lib/attribution";
+import { AUDIO_INTEGRITY_FILENAME } from "../lib/audioIntegrity";
import { copyVideoKey } from "../lib/copies/file";
-import { copiesPath, copiesReleasesPath, readCopiesFile, readCopiesReleases } from "../lib/copies/file-server";
+import { copiesDecisionsPath, copiesPath, readCopiesDecisions, readCopiesFile } from "../lib/copies/file-server";
import {
applyCopyHolds,
copyPartnersToRead,
@@ -45,96 +58,226 @@ const LANE_WORK: Partial<Record<AutoQueueKind, string>> = {
backfill: "speakers work",
};
-const DONE_TTL_MS = 60_000;
+// A TRANSCRIPT THAT IS REAL WORK: at least this many words of speech, and
+// this many per minute of runtime. Speech runs 120–160 words a minute; a
+// stream that is mostly gameplay still averages far above 10. A file under it
+// is headers only, music only ([Music] cues), or a failed track — not the
+// recording transcribed.
+export const COPY_DONE_MIN_WORDS = 50;
+export const COPY_DONE_WORDS_PER_MINUTE = 10;
+
+export const COPY_DONE_REVALIDATE_MS = 30_000;
const DONE_READ_CONCURRENCY = 16;
-type PlanCacheEntry = { key: string; plan: CopyPlan };
+// The disk calls this module makes, one seam so a test can count them.
+export type CopiesLaneIo = {
+ readFile: (p: string) => Promise<string>;
+ readdir: (p: string) => Promise<string[]>;
+ stat: (p: string) => Promise<{ mtimeMs: number; size: number }>;
+};
+const realIo: CopiesLaneIo = {
+ readFile: (p) => readFile(p, "utf8"),
+ readdir: (p) => readdir(p),
+ stat: (p) => stat(p),
+};
+let io: CopiesLaneIo = realIo;
+let revalidateMs = COPY_DONE_REVALIDATE_MS;
+
+// What the lanes need to know about a video of a group, beyond its pairs.
+export type CopyFacts = { duration: number; captionsCountAsDone: boolean };
+
+export type LaneCopyPlan = { plan: CopyPlan; facts: Map<string, CopyFacts> };
+
+type PlanCacheEntry = { key: string; value: LaneCopyPlan };
let planCache: PlanCacheEntry | null = null;
-const doneCache = new Map<string, { at: number; done: boolean }>();
+
+type DoneEntry = { sig: string; done: boolean; checkedAt: number; refreshing: Promise<void> | null };
+const doneCache = new Map<string, DoneEntry>();
+const firstReads = new Map<string, Promise<DoneEntry>>();
export function resetCopiesLaneCacheForTest(): void {
planCache = null;
doneCache.clear();
+ firstReads.clear();
}
-async function mtimeOf(file: string): Promise<number> {
- return stat(file).then(
- (st) => st.mtimeMs,
- () => -1,
+export function setCopiesLaneIoForTest(next: CopiesLaneIo | null, opts: { revalidateMs?: number } = {}): void {
+ io = next ?? realIo;
+ revalidateMs = opts.revalidateMs ?? COPY_DONE_REVALIDATE_MS;
+}
+
+/** Resolves once every background re-check started so far has settled. */
+export async function copiesLaneSettledForTest(): Promise<void> {
+ await Promise.all([...doneCache.values()].map((e) => e.refreshing ?? Promise.resolve()));
+}
+
+async function stampOf(file: string): Promise<string> {
+ return io.stat(file).then(
+ (st) => `${st.mtimeMs}:${st.size}`,
+ () => "-",
);
}
/**
- * 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.
+ * The lanes' copy plan: every cross-channel pair of every group whose `lanes`
+ * is on that is CONFIRMED (by text and runtime, or by copies-confirm) or
+ * METADATA-only, oriented by the group's CURRENT order, minus the rejected
+ * pairs, 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'
+ * sizes and mtimes.
*/
-export async function loadCopyPlan(paths: Paths, settings: Pick<SiteSettings, "sourceGroups">): Promise<CopyPlan | null> {
+export async function loadCopyPlan(
+ paths: Paths,
+ settings: Pick<SiteSettings, "sourceGroups">,
+): Promise<LaneCopyPlan | 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)),
+ await stampOf(copiesPath(paths.transcriptsDir, g.id)),
+ await stampOf(copiesDecisionsPath(paths.transcriptsDir, g.id)),
]),
);
const key = JSON.stringify([paths.transcriptsDir, groups, stamps]);
- if (planCache?.key === key) return planCache.plan;
+ if (planCache?.key === key) return planCache.value;
const byVideo = new Map<string, CopyPartner[]>();
const released = new Set<string>();
+ const facts = new Map<string, CopyFacts>();
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([
+ const [file, decisions] = await Promise.all([
readCopiesFile(paths.transcriptsDir, g.id),
- readCopiesReleases(paths.transcriptsDir, g.id),
+ readCopiesDecisions(paths.transcriptsDir, g.id),
]);
- for (const k of Object.keys(releases.released)) released.add(k);
+ for (const k of Object.keys(decisions.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;
+ if (decisions.rejected[pair.key]) continue;
+ const confirmedBy = pair.link === "metadata" ? decisions.confirmed[pair.key]?.by : undefined;
+ const link = pair.link === "confirmed" || confirmedBy ? "confirmed" : pair.link === "metadata" ? "metadata" : null;
+ // A part-of or overlapping pair is reported, never acted on.
+ if (!link) 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 common = {
+ group: g.id,
+ pair: pair.key,
+ link,
+ ...(confirmedBy ? { confirmedBy } : {}),
+ firstSeenAt: pair.firstSeenAt,
+ waitDays: g.waitDays,
+ } as const;
+ const ka = copyVideoKey(pair.a.channel, pair.a.dir);
+ const kb = copyVideoKey(pair.b.channel, pair.b.dir);
+ add(ka, { ...common, channel: pair.b.channel, dir: pair.b.dir, rank: rb, selfRank: ra });
+ add(kb, { ...common, channel: pair.a.channel, dir: pair.a.dir, rank: ra, selfRank: rb });
+ facts.set(ka, { duration: pair.a.duration, captionsCountAsDone: g.captionsCountAsDone });
+ facts.set(kb, { duration: pair.b.duration, captionsCountAsDone: g.captionsCountAsDone });
}
}
- const plan: CopyPlan = { byVideo, released };
- planCache = { key, plan };
- return plan;
+ const value: LaneCopyPlan = { plan: { byVideo, released }, facts };
+ planCache = { key, value };
+ return value;
}
-// 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;
+// Whether the transcription lane would redo a YouTube ASR caption track: the
+// replace-auto-captions switch, or any rule drawing the auto-captions buckets.
+export function policyReplacesAutoSubs(policy: Pick<AutoQueuePolicy, "replaceAutoSubs" | "root"> | undefined): boolean {
+ if (!policy) return false;
+ if (policy.replaceAutoSubs) return true;
+ const walk = (n: AutoQueueNode): boolean =>
+ isGroup(n)
+ ? n.children.some(walk)
+ : n.match?.bucket === "autoSubsOnly" || n.match?.bucket === "downloadedAutoSubsOnly";
+ return policy.root ? walk(policy.root) : false;
+}
+
+// Words of speech in a cue's text: bracketed non-speech ([Music], (applause))
+// and music notes left out.
+export function speechWords(text: string): number {
+ const cleaned = text.replace(/\[[^\]]*\]|\([^)]*\)|<[^>]*>|[♪♫]/g, " ");
+ let n = 0;
+ for (const t of cleaned.split(/\s+/)) if (/[\p{L}\p{N}]/u.test(t)) n++;
+ return n;
+}
+
+export function minDoneWords(durationSeconds: number): number {
+ const minutes = durationSeconds > 0 ? durationSeconds / 60 : 0;
+ return Math.max(COPY_DONE_MIN_WORDS, Math.ceil(COPY_DONE_WORDS_PER_MINUTE * minutes));
+}
+
+type DoneRules = {
+ facts: CopyFacts;
+ replaceAutoSubs: boolean;
+ // Backfill only: the operations' targets, fingerprinted.
+ targets?: string;
+};
+
+// The files that decide a video's done state for the lane, with their sizes
+// and mtimes: equal signatures, equal answers.
+async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig: string; entries: string[] }> {
+ const entries = (await io.readdir(videoDir).catch(() => [] as string[])).sort();
+ const decisive =
+ kind === "transcription"
+ ? entries.filter((e) => e === WHISPER_FILENAME || isTranscriptVtt(e))
+ : entries.filter(
+ (e) =>
+ e === WHISPER_FILENAME ||
+ isTranscriptVtt(e) ||
+ e === DIARIZATION_FILENAME ||
+ e === ATTRIBUTION_FILENAME ||
+ e === AUDIO_INTEGRITY_FILENAME,
+ );
+ const stamps = await Promise.all(decisive.map((e) => stampOf(path.join(videoDir, e))));
+ // The Speakers states also turn on which other files are there (audio, a
+ // container), so the backfill signature carries the whole listing.
+ return { sig: JSON.stringify([kind === "backfill" ? entries : decisive, stamps]), entries };
+}
+
+// THE TRANSCRIPTION, DONE: a transcript this lane would not itself redo, with
+// real words for its length. Our own engine's transcript.json counts; platform
+// captions only with the group's captionsCountAsDone, and a YouTube ASR track
+// never while the lane would replace it.
+async function transcriptDone(videoDir: string, entries: readonly string[], rules: DoneRules): Promise<boolean> {
+ const min = minDoneWords(rules.facts.duration);
+ if (entries.includes(WHISPER_FILENAME)) {
+ try {
+ const parsed = JSON.parse(await io.readFile(path.join(videoDir, WHISPER_FILENAME))) as {
+ transcription?: { text?: unknown }[];
+ };
+ if (Array.isArray(parsed.transcription)) {
+ let words = 0;
+ for (const seg of parsed.transcription) if (typeof seg?.text === "string") words += speechWords(seg.text);
+ if (words >= min) return true;
+ }
+ } catch {
+ // unreadable: not done by this file
}
- return true;
+ }
+ if (!rules.facts.captionsCountAsDone) return false;
+ const vtt = resolvePrimaryVtt(entries);
+ if (!vtt) return false;
+ if (rules.replaceAutoSubs && (await resolveCaptionsProvenance(videoDir, entries)) === "asr") return false;
+ try {
+ let words = 0;
+ for (const cue of parseVtt(await io.readFile(path.join(videoDir, vtt)))) words += speechWords(cue.text);
+ return words >= min;
} 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.
+// THE SPEAKERS, DONE: every one of the lane's operations has its output on
+// the video (state `present`), at least one, none still to do — a video none
+// of them applies to (no transcript) is not done.
async function speakersDone(paths: Paths, settings: SiteSettings, channel: string, dir: string): Promise<boolean> {
const ops = operationsForLane("backfill", settings);
if (ops.length === 0) return false;
@@ -150,39 +293,97 @@ async function speakersDone(paths: Paths, settings: SiteSettings, channel: strin
return present > 0;
}
-/** Whether each `<channel>/<dir>` has this lane's work done and readable (memoized a minute). */
+async function computeDone(
+ kind: AutoQueueKind,
+ paths: Paths,
+ settings: SiteSettings,
+ key: string,
+ rules: DoneRules,
+ entries: readonly string[],
+): Promise<boolean> {
+ const slash = key.indexOf("/");
+ const channel = key.slice(0, slash);
+ const dir = key.slice(slash + 1);
+ try {
+ if (kind === "transcription") return await transcriptDone(path.join(paths.channelsDir, channel, "data", dir), entries, rules);
+ if (kind === "backfill") return await speakersDone(paths, settings, channel, dir);
+ } catch {
+ // unreadable: not done
+ }
+ return false;
+}
+
+/**
+ * Whether each `<channel>/<dir>` has this lane's work done and readable. A copy
+ * seen before answers from the cache at once; one never seen is read now.
+ */
export async function readCopyDone(
kind: AutoQueueKind,
paths: Paths,
settings: SiteSettings,
keys: Iterable<string>,
+ facts: ReadonlyMap<string, CopyFacts>,
now: number = Date.now(),
): Promise<Map<string, boolean>> {
const list = [...keys];
const out = new Map<string, boolean>();
+ if (list.length === 0) return out;
+ const replaceAutoSubs = kind === "transcription" && policyReplacesAutoSubs(settings.autoQueue?.transcription);
+ const targetsByChannel = new Map<string, string>();
+ const targetsOf = async (channel: string): Promise<string | undefined> => {
+ if (kind !== "backfill") return undefined;
+ const hit = targetsByChannel.get(channel);
+ if (hit !== undefined) return hit;
+ const ops = operationsForLane("backfill", settings);
+ const ts = await Promise.all(ops.map(async (op) => [op.id, await op.resolveTarget({ settings, paths, channelSlug: channel })]));
+ const fp = JSON.stringify(ts);
+ targetsByChannel.set(channel, fp);
+ return fp;
+ };
await mapConcurrent(list, DONE_READ_CONCURRENCY, async (k) => {
- const cacheKey = `${kind}\u0000${paths.channelsDir}\u0000${k}`;
+ const channel = k.slice(0, k.indexOf("/"));
+ const rules: DoneRules = {
+ facts: facts.get(k) ?? { duration: 0, captionsCountAsDone: false },
+ replaceAutoSubs,
+ ...(kind === "backfill" ? { targets: await targetsOf(channel) } : {}),
+ };
+ const cacheKey = JSON.stringify([kind, paths.channelsDir, k, rules]);
+ const videoDir = path.join(paths.channelsDir, channel, "data", k.slice(k.indexOf("/") + 1));
const hit = doneCache.get(cacheKey);
- if (hit && now - hit.at < DONE_TTL_MS) {
+ if (hit) {
out.set(k, hit.done);
+ // In the background, never on this tick: a stat of the deciding files,
+ // and a re-read only when one of them moved.
+ if (!hit.refreshing && now - hit.checkedAt >= revalidateMs) {
+ hit.refreshing = (async () => {
+ try {
+ const { sig, entries } = await signatureOf(kind, videoDir);
+ if (sig !== hit.sig) {
+ hit.done = await computeDone(kind, paths, settings, k, rules, entries);
+ hit.sig = sig;
+ }
+ hit.checkedAt = Date.now();
+ } catch {
+ // keep the last answer; the next tick tries again
+ } finally {
+ hit.refreshing = null;
+ }
+ })();
+ }
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;
+ let first = firstReads.get(cacheKey);
+ if (!first) {
+ first = (async () => {
+ const { sig, entries } = await signatureOf(kind, videoDir);
+ const done = await computeDone(kind, paths, settings, k, rules, entries);
+ const entry: DoneEntry = { sig, done, checkedAt: now, refreshing: null };
+ doneCache.set(cacheKey, entry);
+ return entry;
+ })().finally(() => firstReads.delete(cacheKey));
+ firstReads.set(cacheKey, first);
}
- doneCache.set(cacheKey, { at: now, done });
- out.set(k, done);
+ out.set(k, (await first).done);
});
return out;
}
@@ -201,11 +402,12 @@ export async function copyHoldsForLane(opts: {
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 loaded = await loadCopyPlan(opts.paths, opts.settings);
+ if (!loaded || loaded.plan.byVideo.size === 0) return null;
+ const { plan, facts } = loaded;
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 done = await readCopyDone(opts.kind, opts.paths, opts.settings, toRead, facts, now);
const inFlight = new Set<string>();
for (const u of opts.inFlight) inFlight.add(copyVideoKey(u.channelSlug, u.videoId));
return applyCopyHolds({
diff --git a/common/controller/copiesScan.ts b/common/controller/copiesScan.ts
@@ -34,21 +34,26 @@ import {
classifyCandidate,
copyCandidates,
cuesToWords,
+ prepareCopyText,
textEvidence,
type CopyRecord,
+ type CopyText,
type TextEvidence,
- type Word,
} 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 { readCopiesFile, readCopiesReleases, writeCopiesFile } from "../lib/copies/file-server";
+import { readCopiesDecisions, readCopiesFile, updateCopiesDecisions, 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";
@@ -56,10 +61,15 @@ export const COPIES_SCAN_JOB_KIND = "copies-scan";
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;
+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 are kept while a scan walks its candidates.
+// 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<SiteSettings, "sourceGroups">, id: string): SourceGroup | null {
return (settings.sourceGroups ?? []).find((g) => g.id === id) ?? null;
@@ -89,15 +99,23 @@ export async function copiesScanRefusal(
type CuesFileShape = { cues?: { start: number; end?: number; text: string }[] };
-async function readWords(paths: Paths, channel: string, dir: string): Promise<Word[] | null> {
+async function readText(paths: Paths, channel: string, dir: string): Promise<CopyText | 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;
+ return Array.isArray(raw.cues) ? prepareCopyText(cuesToWords(raw.cues)) : null;
} catch {
return null;
}
}
+const yieldToLoop = () => new Promise<void>((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 };
}
@@ -107,6 +125,8 @@ export type CopiesScanOptions = {
jobId?: string;
onLog?: (line: string) => void;
now?: () => Date;
+ // A cancelled scan stops between pairs and writes nothing.
+ signal?: AbortSignal;
};
export type CopiesScanOutcome = {
@@ -128,6 +148,19 @@ export async function runCopiesScan(
opts: CopiesScanOptions = {},
): Promise<CopiesScanOutcome> {
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)!;
@@ -138,6 +171,7 @@ export async function runCopiesScan(
const videos: Record<string, number> = {};
let undated = 0;
for (const slug of group.channels) {
+ checkCancel();
if (!(await readChannelConfig(paths, slug))) {
missing.push(slug);
continue;
@@ -156,9 +190,10 @@ export async function runCopiesScan(
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> => {
+ // A small cache of words and their phrase index: candidates come grouped
+ // by their `a` side, so each is built once per run of its candidates.
+ const cache = new Map<string, CopyText | null>();
+ const wordsOf = async (r: CopyRecord): Promise<CopyText | null> => {
const k = `${r.channel}/${r.dir}`;
if (cache.has(k)) {
const v = cache.get(k)!;
@@ -166,7 +201,7 @@ export async function runCopiesScan(
cache.set(k, v);
return v;
}
- const v = await readWords(paths, r.channel, r.dir);
+ 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;
@@ -180,29 +215,34 @@ export async function runCopiesScan(
candidates: candidates.length,
confirmed: 0,
metadata: 0,
- partial: 0,
+ partOf: 0,
+ overlaps: 0,
rejected: 0,
withinChannel: 0,
};
const pairs: CopyPairRecord[] = [];
for (const c of 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 link = classifyCandidate(c, usable);
- if (!link) {
+ const cls = classifyCandidate(c, usable);
+ if (!cls) {
if (usable) totals.rejected++;
continue;
}
+ const { link } = cls;
const key = copyPairKey(c.a, c.b);
const withinChannel = c.a.channel === c.b.channel;
- totals[link]++;
+ 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",
@@ -231,9 +271,11 @@ export async function runCopiesScan(
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)` : ""}`,
+ `${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 };
}
@@ -282,12 +324,13 @@ export async function enqueueCopiesScan(
queueKey: COPIES_SCAN_QUEUE,
paths: deps.paths,
network: false,
- fn: async (onLog, _signal, _setProgress, ctx) => {
+ 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}`);
@@ -297,54 +340,238 @@ export async function enqueueCopiesScan(
});
}
-// --- The release: a person's word that a held or skipped copy runs ----------
+// --- A person's word: release a video, confirm or reject a pair ------------
-export type CopiesReleaseBody = { group: string; videos: string[]; undo: boolean; note?: string };
+const BY_VALUES: readonly CopyDecisionBy[] = ["operator", "agent"];
-const VIDEO_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[^/\s]{1,200}$/;
+// `by` is the caller's word, as judge-trending takes it: the route cannot tell
+// who is asking. Default "agent".
+function parseBy(raw: Record<string, unknown>): 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;
+}
-export function parseCopiesReleaseBody(raw: Record<string, unknown>): CopiesReleaseBody {
+function parseCommon(raw: Record<string, unknown>): { 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');
- 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');
+ 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<string, unknown>, 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<string, unknown>): CopiesReleaseBody {
+ const common = parseCommon(raw);
+ const list = listOf(raw, "video", "videos");
+ if (list.length === 0) throw new Error('"video" ("<channel>/<dir>" or "<channel>/<id>") 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 (!validVideoRef(v)) {
+ throw new Error(`not a video key: ${JSON.stringify(v)} — "<channel>/<dir>" (or "<channel>/<id>"), 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 } : {}) };
+ return { ...common, videos };
+}
+
+export type CopiesDecideBody = { group: string; pairs: string[]; undo: boolean; note?: string; by: CopyDecisionBy };
+
+export function parseCopiesDecideBody(raw: Record<string, unknown>): CopiesDecideBody {
+ const common = parseCommon(raw);
+ const list = listOf(raw, "pair", "pairs");
+ if (list.length === 0) throw new Error('"pair" ("<channel>/<dir>|<channel>/<dir>", 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)} — "<channel>/<dir>|<channel>/<dir>" (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 `<channel>/<dir>`, 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<SiteSettings, "sourceGroups">,
+ action: CopiesDecisionAction,
+ raw: Record<string, unknown>,
+ deps: { now?: () => Date } = {},
+): Promise<CopiesDecisionResult> {
+ 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[];
};
- // Cross-channel pairs the lanes act on, by link; inside-one-channel ones apart.
- pairs: { confirmed: number; metadata: number; partial: number; withinChannel: number };
+ // 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<string, CopiesMemberBytes> };
- released: string[];
+ // 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[];
};
@@ -359,31 +586,59 @@ async function audioBytesOf(dir: string): Promise<number> {
return total;
}
+const DAY_MS = 86_400_000;
+
export async function copiesReport(
paths: Paths,
settings: Pick<SiteSettings, "sourceGroups">,
- opts: { group?: string | null; pairs?: boolean } = {},
+ opts: { group?: string | null; pairs?: boolean; now?: number } = {},
): Promise<CopiesGroupReport[]> {
+ 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, releases] = await Promise.all([
+ const [file, decisions] = await Promise.all([
readCopiesFile(paths.transcriptsDir, g.id),
- readCopiesReleases(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, metadata: 0, partial: 0, withinChannel: 0 };
+ const pairs = { confirmed: 0, confirmedByDecision: 0, metadata: 0, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0 };
+ const metadataPairs: CopiesMetadataPairView[] = [];
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;
+ 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,
+ 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;
@@ -392,6 +647,7 @@ export async function copiesReport(
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<string, CopiesMemberBytes> = {};
for (const [slug, dirs] of copiesByChannel) {
@@ -405,12 +661,15 @@ export async function copiesReport(
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,
@@ -421,7 +680,15 @@ export async function copiesReport(
: null,
pairs,
duplicated: { seconds, byChannel },
- released: Object.keys(releases.released),
+ metadataPairs,
+ confirmHint:
+ `pnpm ops copies-confirm --json '{"group":"${g.id}","pairs":["<key>", …],"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 ?? [] } : {}),
});
}
diff --git a/common/lib/copies/file-server.ts b/common/lib/copies/file-server.ts
@@ -1,19 +1,20 @@
// The disk half of lib/copies/file.ts: `<transcriptsDir>/copies/<group>.json`
-// and `<group>.releases.json`, read and written. SERVER-ONLY (node:fs).
+// and `<group>.decisions.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_DECISIONS_FORMAT,
COPIES_DIRNAME,
- COPIES_RELEASES_FORMAT,
COPIES_VERSION,
+ isCopiesDecisionsFile,
isCopiesFile,
- isCopiesReleasesFile,
+ type CopiesDecisionsFile,
type CopiesFile,
- type CopiesReleasesFile,
- type CopyRelease,
+ type CopyDecision,
+ type CopyDecisionBy,
} from "./file";
export function copiesDirOf(transcriptsDir: string): string {
@@ -29,8 +30,8 @@ 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`);
+export function copiesDecisionsPath(transcriptsDir: string, group: string): string {
+ return path.join(copiesDirOf(transcriptsDir), `${checkedId(group)}.decisions.json`);
}
// The group's scan, or null (none yet, unreadable, or another format).
@@ -49,42 +50,82 @@ export async function writeCopiesFile(transcriptsDir: string, file: CopiesFile):
return p;
}
-export function emptyReleases(group: string): CopiesReleasesFile {
- return { format: COPIES_RELEASES_FORMAT, version: COPIES_VERSION, group, released: {} };
+export function emptyDecisions(group: string): CopiesDecisionsFile {
+ return { format: COPIES_DECISIONS_FORMAT, version: COPIES_VERSION, group, released: {}, confirmed: {}, rejected: {} };
}
-// The group's releases; none (or an unreadable file) is an empty set.
-export async function readCopiesReleases(transcriptsDir: string, group: string): Promise<CopiesReleasesFile> {
+// The group's decisions; none (or an unreadable file) is an empty set.
+export async function readCopiesDecisions(transcriptsDir: string, group: string): Promise<CopiesDecisionsFile> {
try {
- const v = JSON.parse(await readFile(copiesReleasesPath(transcriptsDir, group), "utf8")) as unknown;
- if (isCopiesReleasesFile(v) && v.group === group) return v;
+ const v = JSON.parse(await readFile(copiesDecisionsPath(transcriptsDir, group), "utf8")) as unknown;
+ if (isCopiesDecisionsFile(v) && v.group === group) return v;
} catch {
// none yet
}
- return emptyReleases(group);
+ return emptyDecisions(group);
}
+export type CopiesDecisionChange = {
+ // `<channel>/<dir>` keys to release (or, with undo, un-release).
+ release?: readonly string[];
+ // Pair keys to confirm / reject (or, with undo, take back).
+ confirm?: readonly string[];
+ reject?: readonly string[];
+ undo?: boolean;
+ by: CopyDecisionBy;
+ note?: string;
+ now?: () => Date;
+};
+
+const sortedMap = (m: Record<string, CopyDecision>) =>
+ Object.fromEntries(Object.entries(m).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)));
+
/**
- * 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.
+ * THE ONE WRITER of a group's decisions, under the file's lock, atomically:
+ * release videos, confirm or reject pairs, or (`undo`) take any of those back.
+ * A pair is confirmed or rejected, never both: the later word replaces the
+ * earlier one. Answers the file as written.
*/
-export async function updateCopiesReleases(
+export async function updateCopiesDecisions(
transcriptsDir: string,
group: string,
- keys: readonly string[],
- opts: { undo?: boolean; note?: string; now?: () => Date } = {},
-): Promise<CopiesReleasesFile> {
- const p = copiesReleasesPath(transcriptsDir, group);
+ change: CopiesDecisionChange,
+): Promise<CopiesDecisionsFile> {
+ const p = copiesDecisionsPath(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 file = await readCopiesDecisions(transcriptsDir, group);
+ const entry: CopyDecision = {
+ at: (change.now?.() ?? new Date()).toISOString(),
+ by: change.by,
+ ...(change.note ? { note: change.note } : {}),
+ };
+ const released = { ...file.released };
+ const confirmed = { ...file.confirmed };
+ const rejected = { ...file.rejected };
+ for (const k of change.release ?? []) {
+ if (change.undo) delete released[k];
+ else released[k] = entry;
+ }
+ for (const k of change.confirm ?? []) {
+ if (change.undo) delete confirmed[k];
+ else {
+ confirmed[k] = entry;
+ delete rejected[k];
+ }
+ }
+ for (const k of change.reject ?? []) {
+ if (change.undo) delete rejected[k];
+ else {
+ rejected[k] = entry;
+ delete confirmed[k];
+ }
}
- const next: CopiesReleasesFile = { ...file, released: Object.fromEntries(Object.entries(released).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))) };
+ const next: CopiesDecisionsFile = {
+ ...file,
+ released: sortedMap(released),
+ confirmed: sortedMap(confirmed),
+ rejected: sortedMap(rejected),
+ };
await writeJsonAtomic(p, next, { mkdir: true });
return next;
});
diff --git a/common/lib/copies/file.ts b/common/lib/copies/file.ts
@@ -1,20 +1,25 @@
// 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`
+// transcripts/copies/<group>.json the scan's pairs, machine-written,
+// regenerated whole by each scan
+// transcripts/copies/<group>.decisions.json a person's (or an agent's) word:
+// pairs confirmed or rejected,
+// videos released — written only
+// by copies-confirm, copies-reject
+// and copies-release, never by
+// the scan
//
// PRIVATE: nothing under transcripts/copies/ is read by the export build or
-// shipped to a site. Deleting either file restores today's lane behaviour.
+// shipped to a site. Deleting the scan file restores today's lane behaviour;
+// the decisions only ever act on pairs the scan lists.
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 const COPIES_DECISIONS_FORMAT = "archilyzer-copies-decisions";
export type CopyMember = {
channel: string;
@@ -31,6 +36,8 @@ export type CopyPairRecord = {
a: CopyMember;
b: CopyMember;
link: CopyLink;
+ // On a part-of pair: which member is the part (inside the other).
+ part?: "a" | "b";
// Both members on one channel: report only, the lanes never act on it.
withinChannel: boolean;
evidence: {
@@ -41,7 +48,9 @@ export type CopyPairRecord = {
text?: TextEvidence;
};
// When a scan first recorded this pair (ISO-8601), carried across scans:
- // a held copy's wait is counted from here.
+ // a held copy's wait is counted from here (not from when a lane first held
+ // it), so a pair older than its group's wait never holds; re-ordering the
+ // group flips a and b, which is a new key and a new wait.
firstSeenAt: string;
};
@@ -51,7 +60,8 @@ export type CopiesTotals = {
candidates: number;
confirmed: number;
metadata: number;
- partial: number;
+ partOf: number;
+ overlaps: number;
// Candidates the words said were different recordings.
rejected: number;
withinChannel: number;
@@ -76,15 +86,23 @@ export type CopiesFile = {
totals: CopiesTotals;
};
-export type CopyRelease = { at: string; note?: string };
+// Who gave a decision: the caller's word, as judge-trending takes it (the
+// route cannot tell who is asking).
+export type CopyDecisionBy = "operator" | "agent";
+export type CopyDecision = { at: string; by: CopyDecisionBy; note?: string };
-export type CopiesReleasesFile = {
- format: typeof COPIES_RELEASES_FORMAT;
+export type CopiesDecisionsFile = {
+ format: typeof COPIES_DECISIONS_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>;
+ // `<channel>/<dir>` → released: the lanes treat that video as they did
+ // before the group existed.
+ released: Record<string, CopyDecision>;
+ // Pair key → a metadata-only pair a person says IS the same recording: the
+ // lanes treat it as text-confirmed.
+ confirmed: Record<string, CopyDecision>;
+ // Pair key → a pair a person says is NOT: the lanes never act on it again.
+ rejected: Record<string, CopyDecision>;
};
export function copyVideoKey(channel: string, dir: string): string {
@@ -101,15 +119,54 @@ export function isCopiesFile(v: unknown): v is 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 {
+export function isCopiesDecisionsFile(v: unknown): v is CopiesDecisionsFile {
if (!v || typeof v !== "object") return false;
- const f = v as Partial<CopiesReleasesFile>;
+ const f = v as Partial<CopiesDecisionsFile>;
+ const isMap = (m: unknown) => !!m && typeof m === "object" && !Array.isArray(m);
return (
- f.format === COPIES_RELEASES_FORMAT &&
+ f.format === COPIES_DECISIONS_FORMAT &&
f.version === COPIES_VERSION &&
typeof f.group === "string" &&
- !!f.released &&
- typeof f.released === "object" &&
- !Array.isArray(f.released)
+ isMap(f.released) &&
+ isMap(f.confirmed) &&
+ isMap(f.rejected)
);
}
+
+// A member named `<channel>/<dir>` or `<channel>/<id>`: a Rumble video's dir
+// (the URL slug, what the lanes' pending lists and units carry) is not its
+// id (the embed id the cues and the index carry), and a person may give
+// either. Both resolve to the member's DIR key, which is what pairs are kept
+// under.
+function memberMatches(m: CopyMember, ref: string): boolean {
+ const slash = ref.indexOf("/");
+ if (slash <= 0) return false;
+ const channel = ref.slice(0, slash);
+ const name = ref.slice(slash + 1);
+ return m.channel === channel && (m.dir === name || m.id === name);
+}
+
+/** The `<channel>/<dir>` key of a video the scan lists, named by dir or by id; null when it lists none. */
+export function resolveCopyVideoRef(file: Pick<CopiesFile, "pairs"> | null, ref: string): string | null {
+ for (const p of file?.pairs ?? []) {
+ for (const m of [p.a, p.b]) if (memberMatches(m, ref)) return copyVideoKey(m.channel, m.dir);
+ }
+ return null;
+}
+
+/**
+ * The pair a reference names: its key as the report prints it, or
+ * `<channel>/<dir-or-id>|<channel>/<dir-or-id>` in either order. Null when the
+ * scan lists no such pair.
+ */
+export function resolveCopyPairRef(file: Pick<CopiesFile, "pairs"> | null, ref: string): CopyPairRecord | null {
+ const bar = ref.indexOf("|");
+ if (bar <= 0) return null;
+ const x = ref.slice(0, bar);
+ const y = ref.slice(bar + 1);
+ for (const p of file?.pairs ?? []) {
+ if (p.key === ref) return p;
+ if ((memberMatches(p.a, x) && memberMatches(p.b, y)) || (memberMatches(p.a, y) && memberMatches(p.b, x))) return p;
+ }
+ return null;
+}
diff --git a/common/lib/copies/laneHold.test.ts b/common/lib/copies/laneHold.test.ts
@@ -9,22 +9,44 @@ 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 {
+// Channels by rank: pref-chan 0, mirror-chan 1, third-chan 2. A video's
+// channel is its id's first letter (p, m, t).
+const CHANNEL: Record<string, [string, number]> = { p: ["pref-chan", 0], m: ["mirror-chan", 1], t: ["third-chan", 2] };
+const chan = (id: string) => CHANNEL[id[0]];
+
+type PairSpec = { x: string; y: string; link: CopyPartner["link"]; firstSeenAt?: string; waitDays?: number; confirmedBy?: string };
+
+function planOf(pairs: PairSpec[], 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 });
+ for (const s of pairs) {
+ const [xc, xr] = chan(s.x);
+ const [yc, yr] = chan(s.y);
+ const pair = `${xc}/${s.x}|${yc}/${s.y}`;
+ const common = {
+ group: "g",
+ pair,
+ link: s.link,
+ firstSeenAt: s.firstSeenAt ?? RECENT,
+ waitDays: s.waitDays ?? 7,
+ ...(s.confirmedBy ? { confirmedBy: s.confirmedBy } : {}),
+ };
+ add(`${xc}/${s.x}`, { ...common, channel: yc, dir: s.y, rank: yr, selfRank: xr });
+ add(`${yc}/${s.y}`, { ...common, channel: xc, dir: s.x, rank: xr, selfRank: yr });
}
return { byVideo, released: new Set(released) };
}
+// pref-chan is preferred over mirror-chan.
+function plan(
+ pairs: { pref: string; mirror: string; link: CopyPartner["link"]; firstSeenAt?: string; waitDays?: number }[],
+ released: string[] = [],
+): CopyPlan {
+ return planOf(pairs.map((x) => ({ ...x, x: x.pref, y: x.mirror })), released);
+}
+
function owner(ids: string[]): Map<string, string> {
- return new Map(ids.map((id) => [id, id.startsWith("p") ? "pref-chan" : "mirror-chan"]));
+ return new Map(ids.map((id) => [id, chan(id)[0]]));
}
function run(
@@ -90,27 +112,93 @@ test("the copy that already has the transcript keeps it whatever the order", ()
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, []);
+ const held = run(["m1", "p1"], recent);
+ assert.deepEqual(held.pending.all, ["p1"]);
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-confirm/);
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"]);
+ const released = run(["m1", "p1"], old);
+ assert.deepEqual(released.pending.all, ["m1", "p1"]);
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 metadata hold ALWAYS ends: the other copy done is held only until the wait, then runs (fails against the open-ended hold)", () => {
+ // Within the wait, the done copy holds it (a confirm would make it a skip).
+ const recent = run(["m1"], plan([{ pref: "p1", mirror: "m1", link: "metadata", firstSeenAt: RECENT }]), ["pref-chan/p1"]);
+ assert.equal(recent.decisions[0].action, "hold");
+ assert.equal(recent.decisions[0].until, "2026-03-25T00:00:00.000Z");
+ // After it: the lane does the work, whichever copy is the done one.
+ const old = plan([{ pref: "p1", mirror: "m1", link: "metadata", firstSeenAt: LONG_AGO }]);
+ assert.deepEqual(run(["m1"], old, ["pref-chan/p1"]).pending.all, ["m1"], "the preferred copy done");
+ assert.deepEqual(run(["p1"], old, ["mirror-chan/m1"]).pending.all, ["p1"], "the fallback copy done");
+});
+
+test("waitDays 0 means no hold at all; a confirmed skip is not a hold and still applies", () => {
+ const meta = plan([{ pref: "p1", mirror: "m1", link: "metadata", waitDays: 0 }]);
+ assert.deepEqual(run(["m1"], meta, ["pref-chan/p1"]).pending.all, ["m1"]);
+ assert.deepEqual(run(["p1", "m1"], meta).pending.all, ["p1", "m1"]);
+ const conf = plan([{ pref: "p1", mirror: "m1", link: "confirmed", waitDays: 0 }]);
+ assert.deepEqual(run(["p1", "m1"], conf).pending.all, ["p1", "m1"], "nobody waits");
+ assert.equal(run(["m1"], conf, ["pref-chan/p1"]).decisions[0].action, "skip");
+});
+
+test("a pair a person confirmed is a skip, and says whose word it was", () => {
+ const p = planOf([{ x: "p1", y: "m1", link: "confirmed", confirmedBy: "operator", firstSeenAt: LONG_AGO }]);
+ const out = run(["m1"], p, ["pref-chan/p1"]);
+ assert.deepEqual(out.pending.all, []);
+ assert.equal(out.decisions[0].action, "skip");
+ assert.match(out.decisions[0].reason, /by the operator's word/);
+});
+
+test("chains: a copy never waits behind a copy that is itself skipped or held (fails against the one-pass hold)", () => {
+ // p1 ~ m1 ~ t1, and p1, t1 not paired (dated two days apart).
+ const chain = [
+ { x: "p1", y: "m1", link: "confirmed" as const },
+ { x: "m1", y: "t1", link: "confirmed" as const },
+ ];
+ // p1 is done: m1 is skipped, and t1 resolves THROUGH m1 to p1 — skipped too,
+ // not held behind an m1 that will never run.
+ const done = run(["m1", "t1"], planOf(chain), ["pref-chan/p1"]);
+ assert.deepEqual(done.pending.all, []);
+ const t1 = done.decisions.find((d) => d.id === "t1")!;
+ assert.deepEqual([t1.action, t1.partner, t1.via], ["skip", "pref-chan/p1", "mirror-chan/m1"]);
+ // p1 queued: m1 waits for it, and so does t1 — for p1, the copy that will run.
+ const queued = run(["p1", "m1", "t1"], planOf(chain));
+ assert.deepEqual(queued.pending.all, ["p1"]);
+ assert.deepEqual(queued.decisions.map((d) => [d.id, d.partner]), [["m1", "pref-chan/p1"], ["t1", "pref-chan/p1"]]);
+ // A weaker link anywhere in the chain is the chain's link: metadata holds, never skips.
+ const weak = run(["m1", "t1"], planOf([chain[0], { ...chain[1], link: "metadata" }]), ["pref-chan/p1"]);
+ const t1w = weak.decisions.find((d) => d.id === "t1")!;
+ assert.deepEqual([t1w.action, t1w.link], ["hold", "metadata"]);
+ // m1 skipped because the FALLBACK t1 is done (work already done is kept):
+ // p1, preferred and pending, resolves through m1 to t1 and is not redone.
+ const back = run(["p1", "m1"], planOf([chain[0], chain[1]]), ["third-chan/t1"]);
+ assert.deepEqual(back.pending.all, []);
+});
+
+test("a preferred copy's job dying releases the copy held behind it", () => {
+ const p = plan([{ pref: "p1", mirror: "m1", link: "confirmed" }]);
+ // Tick 1: p1 in flight, m1 held behind it.
+ const t1 = run(["m1"], p, [], ["pref-chan/p1"]);
+ assert.deepEqual(t1.pending.all, []);
+ assert.match(t1.decisions[0].reason, /in flight/);
+ // p1's job failed: the runner retires it (neither in flight nor pending), and
+ // it left no transcript. Tick 2: m1 runs.
+ const t2 = run(["m1"], p, [], []);
+ assert.deepEqual(t2.pending.all, ["m1"]);
+ assert.deepEqual(t2.decisions, []);
+ // Failed and queued again for a retry: m1 waits again, within the wait.
+ assert.deepEqual(run(["p1", "m1"], p).pending.all, ["p1"]);
+});
+
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.
@@ -123,17 +211,14 @@ test("a preferred copy that is gone or unavailable does not block the mirror", (
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", () => {
+test("the preferred copy is never held by a fallback that is not done", () => {
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"]);
+ const out = run(["p1", "p2"], p);
+ assert.deepEqual(out.pending.all, ["p1", "p2"]);
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", () => {
diff --git a/common/lib/copies/laneHold.ts b/common/lib/copies/laneHold.ts
@@ -5,41 +5,62 @@
// 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):
+// ONLY WHOLE COPIES ACT. The plan holds a group's cross-channel pairs that are
+// CONFIRMED (by text and runtime, or by a person's copies-confirm) or
+// METADATA-only (date and runtime, no words on one side). A part-of or
+// overlapping pair, a rejected one and a pair inside one channel never reach
+// a lane. THE RULES, per pending video X (not released) and each other copy P:
//
-// 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.
+// CONFIRMED pair:
+// P's work is done (read off P's own files) → X is SKIPPED.
+// P is the PREFERRED copy (its channel earlier in the group) and P is in
+// flight, or queued and not itself held or skipped → X is HELD, until the
+// group's wait ends at the latest. Otherwise X runs (P gone, paused, never
+// downloaded, failed … never blocks X).
+// METADATA-only pair (3 % of them name the wrong copy):
+// the wait is over (or waitDays is 0) → nothing: X runs, WHATEVER P's
+// state — a metadata match is never a skip and never an open-ended hold.
+// Within the wait: P done → X HELD (a person's copies-confirm turns it
+// into a skip); P preferred and in flight or queued (not held) → X HELD.
//
-// 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.
+// CHAINS RESOLVE. When P is itself held or skipped, X is judged against the
+// copy P resolved to — the one that actually has or will get the work — with
+// the weaker of the two links, so X never waits behind a copy that will not
+// run. A preferred copy whose job ended without the work (failed and retired
+// by the runner, its channel paused) is neither queued nor in flight, and the
+// copy held behind it runs on the next tick.
+//
+// WORK ALREADY DONE IS NEVER REDONE OR DISCARDED: a done P skips (or, for a
+// metadata match, holds within the wait) 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;
+// Chain resolution settles in as many passes as the longest chain; this caps
+// a pathological plan.
+const MAX_PASSES = 8;
+
+export type CopyLaneLink = "confirmed" | "metadata";
export type CopyPartner = {
group: string;
+ // The pair's key as the scan lists it (`<a>|<b>`).
+ pair: 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;
+ link: CopyLaneLink;
+ // Who confirmed it, when a person's (or an agent's) copies-confirm made a
+ // metadata-only pair confirmed.
+ confirmedBy?: string;
+ // The partner's channel's rank in the group, and this video's (0 = preferred).
+ rank: number;
+ selfRank: number;
// ISO-8601: when the scan first saw the pair; the wait runs from here.
firstSeenAt: string;
waitDays: number;
@@ -57,12 +78,17 @@ export type CopyHoldDecision = {
id: string;
action: "skip" | "hold";
group: string;
- link: CopyLink;
- // The other copy, `<channel>/<dir>`.
+ link: CopyLaneLink;
+ // The copy that has or will get the work, `<channel>/<dir>`.
partner: string;
+ partnerRank: number;
+ // When the chain ran through another copy: the direct partner.
+ via?: string;
+ // The direct pair (what copies-confirm and copies-reject name).
+ pair: string;
// Why, in the lane's words.
reason: string;
- // A hold that ends by itself: when (ISO-8601).
+ // A hold ends by itself: when (ISO-8601).
until?: string;
};
@@ -95,8 +121,8 @@ function waitEnds(p: CopyPartner): number {
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}"}'`;
+function opsLine(action: string, body: Record<string, string>): string {
+ return `pnpm ops ${action} --json '${JSON.stringify(body)}'`;
}
/** The partners whose done state a decision needs: every partner of a pending video. */
@@ -119,68 +145,131 @@ export function copyPartnersToRead(
return out;
}
-function decideOne(
- key: string,
- slug: string,
- id: string,
- partners: readonly CopyPartner[],
- input: CopyHoldInput,
- pendingKeys: ReadonlySet<string>,
-): CopyHoldDecision | null {
+// One partner as a decision sees it: the direct copy, or the copy a decided
+// direct partner resolved to.
+type Effective = {
+ key: string;
+ rank: number;
+ link: CopyLaneLink;
+ ends: number;
+ via?: string;
+ p: CopyPartner;
+};
+
+type Ctx = {
+ input: CopyHoldInput;
+ // Every pending video's key, before any decision.
+ pendingKeys: ReadonlySet<string>;
+ // The previous pass's decisions.
+ prev: ReadonlyMap<string, CopyHoldDecision>;
+};
+
+function effective(key: string, p: CopyPartner, ctx: Ctx): Effective {
+ const pk = copyVideoKey(p.channel, p.dir);
+ const ends = waitEnds(p);
+ const d = ctx.prev.get(pk);
+ if (d && d.partner !== key) {
+ return {
+ key: d.partner,
+ rank: d.partnerRank,
+ link: p.link === "confirmed" && d.link === "confirmed" ? "confirmed" : "metadata",
+ ends,
+ via: pk,
+ p,
+ };
+ }
+ return { key: pk, rank: p.rank, link: p.link, ends, p };
+}
+
+function decideOne(key: string, slug: string, id: string, partners: readonly CopyPartner[], ctx: Ctx): CopyHoldDecision | null {
+ const { input, pendingKeys, prev } = ctx;
+ // DONE MEANS DONE ON DISK AND NOT STILL THE LANE'S WORK: a copy this lane
+ // still lists (queued, held or not) or is running is not done, whatever its
+ // files say — so two copies can never each skip the other.
+ const isDone = (k: string) => input.done.get(k) === true && !pendingKeys.has(k) && !input.inFlight.has(k);
+ // WILL RUN: in flight, or queued and not itself held or skipped.
+ const state = (k: string): "in flight" | "queued" | null =>
+ input.inFlight.has(k) ? "in flight" : pendingKeys.has(k) && !prev.has(k) ? "queued" : 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") {
+ for (const raw of partners) {
+ const e = effective(key, raw, ctx);
+ if (e.key === key) continue;
+ const via = e.via ? ` (through ${e.via})` : "";
+ const base = {
+ channel: slug,
+ id,
+ group: e.p.group,
+ link: e.link,
+ partner: e.key,
+ partnerRank: e.rank,
+ pair: e.p.pair,
+ ...(e.via ? { via: e.via } : {}),
+ };
+ const confirmHint = opsLine("copies-confirm", { group: e.p.group, pair: e.p.pair });
+ const releaseHint = opsLine("copies-release", { group: e.p.group, video: key });
+ if (e.link === "confirmed") {
+ if (isDone(e.key)) {
+ const how = e.p.confirmedBy ? `by the ${e.p.confirmedBy}'s word` : "by its words and runtime";
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)}`,
+ reason: `a confirmed copy (${how}) of ${e.key}${via}, whose ${input.work} is done — not done twice`,
};
}
- 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;
+ if (hold || e.rank >= raw.selfRank || input.now >= e.ends) continue;
+ const s = state(e.key);
+ if (!s) continue;
+ const until = new Date(e.ends).toISOString();
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`,
+ reason:
+ `held: waiting for the preferred copy ${e.key}${via} (${s} on this lane), until ${until.slice(0, 10)} ` +
+ `at the latest — release now: ${releaseHint}`,
};
- } else if (p.link === "metadata" && !hold) {
+ continue;
+ }
+ // METADATA ONLY: never past the wait, whatever the other copy's state.
+ if (hold || input.now >= e.ends) continue;
+ const until = new Date(e.ends).toISOString();
+ if (isDone(e.key)) {
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)}`,
+ `held until ${until.slice(0, 10)}: probably the same recording as ${e.key}${via} (date and runtime only, ` +
+ `not confirmed by text), whose ${input.work} is done; then released by itself — confirm to skip it: ` +
+ `${confirmHint}; release now: ${releaseHint}`,
};
+ continue;
}
+ if (e.rank >= raw.selfRank) continue;
+ const s = state(e.key);
+ if (!s) continue;
+ hold = {
+ ...base,
+ action: "hold",
+ until,
+ reason:
+ `held until ${until.slice(0, 10)}: probably the same recording as the preferred copy ${e.key}${via} ` +
+ `(date and runtime only; ${s} on this lane); then released by itself — confirm: ${confirmHint}; ` +
+ `release now: ${releaseHint}`,
+ };
}
return hold;
}
+const sameDecisions = (x: ReadonlyMap<string, CopyHoldDecision>, y: ReadonlyMap<string, CopyHoldDecision>) => {
+ if (x.size !== y.size) return false;
+ for (const [k, d] of x) {
+ const e = y.get(k);
+ if (!e || e.action !== d.action || e.partner !== d.partner || e.link !== d.link) return false;
+ }
+ return true;
+};
+
/**
* 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
@@ -193,30 +282,40 @@ export function applyCopyHolds(input: CopyHoldInput): {
const { plan, owner } = input;
if (plan.byVideo.size === 0) return { pending: input.pending, decisions: [] };
const pendingKeys = new Set<string>();
+ // Pending videos with partners, in pending order.
+ const subjects: { key: string; slug: string; id: string; partners: CopyPartner[] }[] = [];
+ const seen = 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));
+ if (!slug) continue;
+ const key = copyVideoKey(slug, id);
+ pendingKeys.add(key);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ if (plan.released.has(key)) continue;
+ const partners = plan.byVideo.get(key);
+ if (partners && partners.length > 0) subjects.push({ key, slug, id, partners });
+ }
+ }
+ let prev = new Map<string, CopyHoldDecision>();
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
+ const ctx: Ctx = { input, pendingKeys, prev };
+ const next = new Map<string, CopyHoldDecision>();
+ for (const s of subjects) {
+ const d = decideOne(s.key, s.slug, s.id, s.partners, ctx);
+ if (d) next.set(s.key, d);
}
+ const settled = sameDecisions(prev, next);
+ prev = next;
+ if (settled) break;
}
- const decided = new Map<string, CopyHoldDecision | null>();
- const decisions: CopyHoldDecision[] = [];
+ const decisions = subjects.map((s) => prev.get(s.key)).filter((d): d is CopyHoldDecision => !!d);
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 !slug || !prev.has(copyVideoKey(slug, id));
});
}
return { pending: out, decisions };
diff --git a/common/lib/copies/match.test.ts b/common/lib/copies/match.test.ts
@@ -34,7 +34,7 @@ test("the same recording on another clock is the same, with its offset as eviden
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.ok(e.aInB.fraction >= 0.9 && e.bInA.fraction >= 0.9, JSON.stringify(e));
assert.equal(e.offsetMedianSeconds, 30);
});
@@ -43,33 +43,105 @@ test("collisions at random offsets do not confirm (fails against a match-count v
// 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 usable = a.length - COPY_PHRASE_WORDS + 1;
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);
+ for (let k = 0; k < 12; k++) {
+ const pos = Math.floor((usable * k * 3) / 40);
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}`);
+ assert.ok(e.aInB.matched >= 10, `the collisions are found (${e.aInB.matched})`);
+ assert.equal(e.verdict, "different");
+ assert.equal(e.aInB.consistent, 0);
});
-test("a stepped pair is the same recording, with a second cluster", () => {
+test("a stepped pair is the same recording: its runs are summed", () => {
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}`);
+ assert.ok(e.aInB.runs >= 2, `runs ${e.aInB.runs}`);
});
-test("a part of the recording is partial, not the same", () => {
+test("one shared phrase counts once, however many probes could reach it (fails against the old probe search)", () => {
+ // A short side: every probe's old 300-word search reached the same phrase.
+ const a = stream(30, 400);
+ const b = stream(31, 3000).map((x) => ({ ...x }));
+ for (let j = 0; j < COPY_PHRASE_WORDS; j++) b[1500 + j] = { w: a[200 + j].w, t: b[1500 + j].t };
+ const e = textEvidence(a, b);
+ assert.ok(e.aInB.matched <= 1, `matched ${e.aInB.matched}`);
+ assert.equal(e.verdict, "different");
+});
+
+test("a passage of one recording inside another overlaps; it is 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));
+ assert.equal(e.verdict, "overlaps", JSON.stringify(e));
+});
+
+const cand = (aDur: number, bDur: number, durationOk: boolean) => ({
+ a: { channel: "pref-chan", dir: "p1", id: "p1", title: "p1", duration: aDur, date: "20260301" },
+ b: { channel: "mirror-chan", dir: "m1", id: "m1", title: "m1", duration: bDur, date: "20260301" },
+ dateDeltaDays: 0,
+ durationOk,
+});
+
+test("a short part of a long stream is part-of, never confirmed, even when the runtimes are read as agreeing", () => {
+ const whole = stream(40, 3000);
+ const part = retime(whole.slice(1000, 1600), 0);
+ const e = textEvidence(whole, part);
+ assert.equal(e.verdict, "b-part-of-a", JSON.stringify(e));
+ assert.deepEqual(classifyCandidate(cand(1200, 240, false), e), { link: "part-of", part: "b" });
+ assert.deepEqual(classifyCandidate(cand(1200, 1200, true), e), { link: "part-of", part: "b" });
+ // The other way round (the PREFERRED side is the part): the old one-way probe
+ // found every one of its phrases and confirmed.
+ const r = textEvidence(part, whole);
+ assert.equal(r.verdict, "a-part-of-b");
+ assert.deepEqual(classifyCandidate(cand(240, 1200, true), r), { link: "part-of", part: "a" });
+});
+
+test("a short sharing one passage with a different stream overlaps; it does not confirm", () => {
+ const other = stream(50, 3000);
+ const short = retime([...stream(51, 100), ...other.slice(2000, 2080), ...stream(52, 70)], 0);
+ const e = textEvidence(short, other);
+ assert.notEqual(e.verdict, "same");
+ assert.notEqual(e.verdict, "a-part-of-b");
+ assert.equal(classifyCandidate(cand(100, 1200, true), e)?.link, "overlaps");
+});
+
+test("two different streams that both play the same long third-party video only overlap", () => {
+ const video = stream(60, 1500);
+ const s1 = retime([...stream(61, 900), ...video, ...stream(62, 600)], 0);
+ const s2 = retime([...stream(63, 300), ...video, ...stream(64, 1200)], 0);
+ const e = textEvidence(s1, s2);
+ assert.equal(e.verdict, "overlaps", JSON.stringify(e));
+ assert.ok(e.aInB.fraction < 0.75 && e.bInA.fraction < 0.75);
+ assert.equal(classifyCandidate(cand(1200, 1200, true), e)?.link, "overlaps");
+});
+
+test("boilerplate two different streams share (intro, outro, a sponsor read) cannot confirm", () => {
+ const intro = stream(70, 150);
+ const sponsor = stream(71, 100);
+ const outro = stream(72, 150);
+ const s1 = retime([...intro, ...stream(73, 1300), ...sponsor, ...stream(74, 1300), ...outro], 0);
+ const s2 = retime([...intro, ...stream(75, 1300), ...sponsor, ...stream(76, 1300), ...outro], 0);
+ const e = textEvidence(s1, s2);
+ // At most a reported overlap (here every shared stretch sits at one offset).
+ assert.ok(e.verdict === "different" || e.verdict === "overlaps", JSON.stringify(e));
+ assert.ok(e.aInB.fraction < 0.75 && e.bInA.fraction < 0.75);
+ assert.notEqual(classifyCandidate(cand(1200, 1200, true), e)?.link, "confirmed");
+});
+
+test("a rerun inside a longer broadcast is part-of the broadcast: the words agree, the runtimes do not", () => {
+ const original = stream(80, 3000);
+ const rerun = retime([...stream(81, 900), ...original], 0);
+ const e = textEvidence(original, rerun);
+ assert.ok(e.aInB.fraction >= 0.9, JSON.stringify(e));
+ // 1200 s against 1560 s: apart by more than max(120 s, 2 %).
+ assert.deepEqual(classifyCandidate(cand(1200, 1560, false), e), { link: "part-of", part: "a" });
});
test("too few words on either side is no text", () => {
@@ -122,9 +194,14 @@ test("the adjacent day's stream with the closer runtime is not linked over the t
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");
+ // The words say same, the runtimes do not: a trim, never confirmed.
+ assert.deepEqual(classifyCandidate(sameDay, textEvidence(recorded, shift(recorded, -50))), { link: "part-of", part: "a" });
+ assert.deepEqual(
+ classifyCandidate({ ...sameDay, durationOk: true }, textEvidence(recorded, shift(recorded, -50))),
+ { link: "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.deepEqual(classifyCandidate(nextDay, null), { link: "metadata" });
assert.equal(classifyCandidate(sameDay, null), null);
});
diff --git a/common/lib/copies/match.ts b/common/lib/copies/match.ts
@@ -8,13 +8,28 @@
// 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.
+// work for a bounded wait, never to skip it.
+// TEXT — probes spread through EACH copy's words, looked up in the other: at
+// each, a 6-word phrase unique on both sides, and the signed offset between
+// where it sits in each. A probe searches only its own stretch of words and
+// a phrase the other side already gave is not counted again, so no phrase
+// counts twice. The offsets that agree — runs of at least COPY_RUN_MIN
+// inside one 20 s window, a stepped copy having several such runs — over
+// the probes placed is the share of that side the other copy holds. Never
+// the match count: two different streams of one speaker in one week share
+// 4–20 of 40 phrases, at random offsets.
+//
+// WHAT CONFIRMS. Both shares at least COPY_SAME_FRACTION AND runtimes that
+// agree: each copy holds the other, whole. Anything less is not a copy of the
+// whole recording, and the lanes never skip or hold work for it:
+// part-of — one side is (nearly) all inside the other but not the reverse,
+// or the words agree both ways while the runtimes do not (a trim,
+// a part, a muted stretch, a rerun inside a longer broadcast);
+// overlaps — each holds only a stretch of the other (a shared passage, a
+// third party's video both streams played, shared boilerplate).
+// Measured on run 2 of the design pass (one direction, 1,379 text-same pairs):
+// of the 1,031 whose runtimes agree, 1,025 reach 0.75 by summed runs, and no
+// text-different pair had a single run of 4. The lane's LOG.md has the table.
//
// 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
@@ -27,16 +42,23 @@ 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;
+// A run of agreeing offsets this long is a stretch the two copies share.
+export const COPY_RUN_MIN = 4;
+// Each side's share the other must hold, in both directions, to confirm.
+export const COPY_SAME_FRACTION = 0.75;
+// Below this on both sides the two share nothing worth reporting.
+export const COPY_OVERLAP_FRACTION = 0.1;
// 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.
+// How far past a probe's position a unique phrase is looked for (and never
+// past the next probe's position).
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).
+ // The lanes' pending lists and units name videos by this dir, so every pair
+ // is keyed by it.
dir: string;
id: string;
title: string;
@@ -50,24 +72,42 @@ export type Word = { w: string; t: number };
export type CueLike = { start: number; end?: number; text: string };
-export type TextVerdict = "same" | "partial" | "different" | "no-text";
+type GramIndex = Map<string, { t: number; n: number; i: number }>;
-export type TextEvidence = {
- verdict: TextVerdict;
+// One side's words with their phrase index, built once per video.
+export type CopyText = { words: readonly Word[]; idx: GramIndex };
+
+export type TextVerdict = "same" | "a-part-of-b" | "b-part-of-a" | "overlaps" | "different" | "no-text";
+
+// Probes spread through one side, looked up in the other.
+export type DirectionEvidence = {
probes: number;
- // Probes whose phrase was found, unique, on the other side.
+ // Probes whose phrase was found, unique, on the other side (each phrase once).
matched: number;
- // The largest set of those inside one 20 s window of offsets: the verdict.
+ // Those inside runs of at least COPY_RUN_MIN agreeing offsets.
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.
+ // How many such runs (more than one: a stepped copy).
+ runs: number;
+ // consistent / probes, rounded to 0.001.
+ fraction: number;
+};
+
+export type TextEvidence = {
+ verdict: TextVerdict;
+ // a's probes found in b (how much of a b holds), and the reverse.
+ aInB: DirectionEvidence;
+ bInA: DirectionEvidence;
+ // EVIDENCE ONLY, never a clock: the median and spread of the largest run of
+ // a→b offsets (b's seconds minus a's), rounded to 0.1 s.
offsetMedianSeconds: number | null;
offsetSpreadSeconds: number | null;
};
-export type CopyLink = "confirmed" | "metadata" | "partial";
+// confirmed — the same recording, whole, by text and runtime (or a person's word);
+// metadata — probably the same (date + runtime); one side has no words;
+// part-of — one copy is inside the other (`part` says which);
+// overlaps — they share a stretch, nothing more.
+export type CopyLink = "confirmed" | "metadata" | "part-of" | "overlaps";
export type CopyCandidate = {
a: CopyRecord;
@@ -76,6 +116,8 @@ export type CopyCandidate = {
durationOk: boolean;
};
+export type CopyClassification = { link: CopyLink; part?: "a" | "b" } | null;
+
// 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[] = [];
@@ -93,8 +135,6 @@ export function cuesToWords(cues: readonly CueLike[]): Word[] {
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;
@@ -107,81 +147,114 @@ function gramIndex(ws: readonly Word[]): GramIndex {
const key = gramAt(ws, i);
const e = idx.get(key);
if (e) e.n++;
- else idx.set(key, { t: ws[i].t, n: 1 });
+ else idx.set(key, { t: ws[i].t, n: 1, i });
}
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;
+/** One side's words, indexed once: the scan keeps these per video. */
+export function prepareCopyText(words: readonly Word[]): CopyText {
+ return { words, idx: gramIndex(words) };
+}
+
+const asText = (x: readonly Word[] | CopyText): CopyText =>
+ Array.isArray(x) ? prepareCopyText(x as readonly Word[]) : (x as CopyText);
+
+const round1 = (x: number) => Math.round(x * 10) / 10;
+const round3 = (x: number) => Math.round(x * 1000) / 1000;
+
+// Runs of at least COPY_RUN_MIN sorted values inside one window, taken
+// greedily largest first: each value belongs to one run at most.
+function runsOf(sorted: readonly number[]): number[][] {
+ const left = [...sorted];
+ const runs: number[][] = [];
+ for (;;) {
+ let bi = 0;
+ let bj = -1;
+ for (let i = 0, j = 0; i < left.length; i++) {
+ while (left[i] - left[j] > COPY_OFFSET_WINDOW_SECONDS) j++;
+ if (i - j > bj - bi) {
+ bi = j;
+ bj = i;
+ }
}
+ if (bj - bi + 1 < COPY_RUN_MIN) break;
+ runs.push(left.splice(bi, bj - bi + 1));
}
- return [bi, bj];
+ return runs;
}
-const round1 = (x: number) => Math.round(x * 10) / 10;
+function direction(from: CopyText, to: CopyText, wanted: number): { ev: DirectionEvidence; runs: number[][] } {
+ const ws = from.words;
+ const usable = ws.length - COPY_PHRASE_WORDS + 1;
+ // A short side gets fewer probes, never two inside one phrase's stretch.
+ const probes = Math.max(1, Math.min(wanted, Math.floor(usable / COPY_PHRASE_WORDS)));
+ const offsets: number[] = [];
+ const usedTo = new Set<number>();
+ for (let k = 0; k < probes; k++) {
+ const pos = Math.floor((usable * k) / probes);
+ const next = Math.floor((usable * (k + 1)) / probes);
+ const lim = Math.min(next, pos + PROBE_SEARCH_WORDS, usable);
+ for (let i = pos; i < lim; i++) {
+ const key = gramAt(ws, i);
+ if (from.idx.get(key)?.n !== 1) continue;
+ const hit = to.idx.get(key);
+ if (!hit || hit.n !== 1) continue;
+ // EACH PHRASE ONCE: a place on the other side already counted is not
+ // counted again.
+ if (usedTo.has(hit.i)) continue;
+ usedTo.add(hit.i);
+ offsets.push(hit.t - ws[i].t);
+ break;
+ }
+ }
+ const runs = runsOf([...offsets].sort((x, y) => x - y));
+ const consistent = runs.reduce((n, r) => n + r.length, 0);
+ return {
+ ev: { probes, matched: offsets.length, consistent, runs: runs.length, fraction: round3(consistent / probes) },
+ runs,
+ };
+}
/**
- * 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.
+ * Whether `a` and `b` are the same recording by their words, probed in both
+ * directions. "same" here is the words only; `classifyCandidate` adds the
+ * runtimes before anything is confirmed.
*/
export function textEvidence(
- a: readonly Word[],
- b: readonly Word[],
+ a: readonly Word[] | CopyText,
+ b: readonly Word[] | CopyText,
opts: { probes?: number; minWords?: number } = {},
): TextEvidence {
- const probes = opts.probes ?? COPY_PROBES;
+ const wanted = 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 ta = asText(a);
+ const tb = asText(b);
+ const empty: DirectionEvidence = { probes: 0, matched: 0, consistent: 0, runs: 0, fraction: 0 };
+ if (ta.words.length < minWords || tb.words.length < minWords) {
+ return { verdict: "no-text", aInB: empty, bInA: empty, offsetMedianSeconds: null, offsetSpreadSeconds: null };
}
- 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;
+ const ab = direction(ta, tb, wanted);
+ const ba = direction(tb, ta, wanted);
+ const fa = ab.ev.fraction;
+ const fb = ba.ev.fraction;
+ const verdict: TextVerdict =
+ fa >= COPY_SAME_FRACTION && fb >= COPY_SAME_FRACTION
+ ? "same"
+ : fa >= COPY_SAME_FRACTION
+ ? "a-part-of-b"
+ : fb >= COPY_SAME_FRACTION
+ ? "b-part-of-a"
+ : Math.max(fa, fb) >= COPY_OVERLAP_FRACTION
+ ? "overlaps"
+ : "different";
+ const main = ab.runs[0] ?? null;
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]),
+ verdict,
+ aInB: ab.ev,
+ bInA: ba.ev,
+ offsetMedianSeconds: main ? round1(main[Math.floor(main.length / 2)]) : null,
+ offsetSpreadSeconds: main ? round1(main[main.length - 1] - main[0]) : null,
};
}
@@ -246,23 +319,32 @@ export function copyCandidates(
}
}
}
- return out.sort(
- (x, y) =>
- order(x.a, y.a) || order(x.b, y.b),
- );
+ 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.
+ * What a candidate is, given its text evidence (null = one side has no text).
+ * With words on both sides they decide, and CONFIRMED needs the runtimes to
+ * agree as well: the words the same both ways and the runtimes apart is a trim
+ * or a part — the shorter side `part-of` the longer. With no words, agreeing
+ * runtimes make a METADATA-only pair and anything else no pair. Null: not a
+ * pair (the words say different recordings, or there is nothing to go on).
*/
-export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): CopyLink | null {
+export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null): CopyClassification {
if (text && text.verdict !== "no-text") {
- if (text.verdict === "same") return "confirmed";
- if (text.verdict === "partial") return "partial";
- return null;
+ switch (text.verdict) {
+ case "same":
+ if (c.durationOk) return { link: "confirmed" };
+ return { link: "part-of", part: c.a.duration > 0 && c.a.duration <= c.b.duration ? "a" : "b" };
+ case "a-part-of-b":
+ return { link: "part-of", part: "a" };
+ case "b-part-of-a":
+ return { link: "part-of", part: "b" };
+ case "overlaps":
+ return { link: "overlaps" };
+ default:
+ return null;
+ }
}
- return c.durationOk ? "metadata" : null;
+ return c.durationOk ? { link: "metadata" } : null;
}
diff --git a/common/lib/copies/settings.test.ts b/common/lib/copies/settings.test.ts
@@ -18,6 +18,7 @@ test("a group keeps its order and gets its defaults", () => {
channels: ["b-chan", "a-chan"],
lanes: true,
waitDays: 7,
+ captionsCountAsDone: false,
dateWindowDays: 1,
durationToleranceSeconds: 120,
durationToleranceRatio: 0.02,
diff --git a/common/lib/copies/settings.ts b/common/lib/copies/settings.ts
@@ -23,9 +23,15 @@ export type SourceGroup = {
// 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.
+ // How long a held copy waits (days, from when the scan first saw the pair),
+ // after which it is released and its lane does the work, whatever the other
+ // copy's state. 0 = never held.
waitDays: number;
+ // Whether the other copy's PLATFORM captions count as the transcription
+ // done (a YouTube ASR track still does not when the transcription lane
+ // would replace it). false: only a transcript of our own engine counts, so
+ // a fallback copy holding the audio still gets one.
+ captionsCountAsDone: boolean;
// The metadata stage: recorded dates at most this many days apart …
dateWindowDays: number;
// … and runtimes within max(seconds, ratio × the longer runtime).
@@ -60,11 +66,23 @@ export const SOURCE_GROUP_FIELD_DOCS: FieldDocs<SourceGroup> = {
"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.",
+ "Whether the transcription and Speakers lanes act on the group's pairs: skip a CONFIRMED copy (by text and " +
+ "runtime, or by `copies-confirm`) whose other copy has the work done, and hold a metadata-only one or one " +
+ "waiting on its preferred copy for at most `waitDays`. A part-of or overlapping pair is reported, never acted " +
+ "on. 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.",
+ "How long a held copy waits, in days from when the scan FIRST SAW the pair (not from when a lane held it: a " +
+ "pair older than this never holds; re-ordering the group makes new pairs and a new wait). After it the copy " +
+ "is released and its lane does the work, whatever the other copy's state — a metadata-only match is never " +
+ "held longer, even when the other copy is done (`copies-confirm` makes it a skip). 0 = no hold at all. " +
+ "Clamped to [0, 365]; default 7.",
+ captionsCountAsDone:
+ "Whether the other copy's platform captions (a VTT track) count as its transcription done. Default false: " +
+ "only a transcript of our own engine (`transcript.json`) counts, so the fallback copy still gets its own when " +
+ "the preferred copy has captions only. With true a caption track counts, except a YouTube ASR track while the " +
+ "transcription lane would replace it (`replaceAutoSubs`, or a rule on the auto-captions buckets). Either way " +
+ "a transcript counts only with real words for its length (at least max(50, 10 per minute of runtime), " +
+ "bracketed non-speech like [Music] left out).",
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.",
@@ -132,6 +150,7 @@ export function sanitizeSourceGroups(value: unknown): SourceGroup[] {
channels,
lanes: r.lanes === false ? false : true,
waitDays: num(r.waitDays, SOURCE_GROUP_DEFAULT_WAIT_DAYS, 0, SOURCE_GROUP_MAX_WAIT_DAYS, false),
+ captionsCountAsDone: r.captionsCountAsDone === true,
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),
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -2104,7 +2104,7 @@ export const siteSettingsSchema = z.object({
"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.",
+ "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, probed both ways) 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 CONFIRMED copy (each holding 75 % of the other's words and runtimes that agree, or confirmed by `pnpm ops copies-confirm`) whose other copy has the work done, and HOLD a metadata-only one, or one waiting on its preferred copy, visibly and for at most `waitDays` — then it runs, whatever the other copy's state. A part-of or overlapping pair is reported, never acted on; `pnpm ops copies-reject` takes a pair off the lanes and `pnpm ops copies-release` runs a copy. The copy that already has the work 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/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -6,15 +6,23 @@
preferred source first. `pnpm ops settings --json '{"patch":{"sourceGroups":[{"id":"…","channels":["<preferred>",
"<fallback>"]}]}}'`.
- `pnpm ops copies-scan --json '{"group":"…"}'` pairs the members' videos by recorded date and runtime, then by their
- words where both have a cue file, into `transcripts/copies/<group>.json` (never published). Each pair says how it
- was matched (confirmed by text, metadata only, partial) and its evidence. A second scan that finds nothing new
- leaves the file as it was.
- - The transcription and Speakers lanes skip a text-confirmed copy when the other copy's work is done and readable,
- and hold a metadata-only match, with its reason, until the wait ends (`waitDays`, default 7) or `pnpm ops
- copies-release` releases it. The copy that already has a transcript keeps it whatever the order. A lane whose
- only work is held copies says so ("copies-held"), and `pnpm ops get copies` lists each skip and hold.
- - Downloads, files, records and the published sites are unchanged, and no time is mapped between copies. Removing
- the group, or a channel from it, restores the lanes at once.
+ words where both have a cue file, probed both ways, into `transcripts/copies/<group>.json` (never published). A
+ pair is **confirmed** only when each copy holds at least 75 % of the other's probed phrases and the runtimes agree
+ within the group's tolerance; one copy inside the other (a part, a trim, a rerun inside a longer broadcast) is
+ **part-of**, a shared stretch (a passage, a video both streams played) is **overlaps**, and both are reported only.
+ Where one side has no words, agreeing runtimes make a **metadata-only** pair. A cancelled scan writes nothing.
+ - The transcription and Speakers lanes skip a confirmed copy when the other copy's work is done: for transcription a
+ transcript of our own engine with real words for its length (captions count only with the group's
+ `captionsCountAsDone`, default off, and never a YouTube ASR track the lane would replace); for Speakers the
+ Speakers outputs. A copy waiting on its preferred copy, and every metadata-only match, is held, with its reason,
+ for at most `waitDays` (default 7, `0` = never held) and then released, whatever the other copy's state.
+ - `pnpm ops copies-confirm` turns metadata-only pairs into confirmed ones (then skipped instead of done twice) and
+ `pnpm ops copies-reject` takes a pair off the lanes for good; `pnpm ops copies-release` runs a held or skipped
+ copy. All three take one or a list, record who and when, and report what the scan does not list. `pnpm ops get
+ copies` lists the metadata pairs in their wait with titles, dates and runtimes, for confirming in bulk.
+ - The copy that already has the work keeps it whatever the order, and a copy never waits behind one that is itself
+ held or skipped. Downloads, files, records and the published sites are unchanged, and no time is mapped between
+ copies. Removing the group, or a channel from it, restores the lanes at once.
- **umtool: the gap mark's border is the deck's accent colour.**
- The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule
and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text
diff --git a/editor/app/api/ops/_copies.test.ts b/editor/app/api/ops/_copies.test.ts
@@ -15,6 +15,8 @@ const corpus = await setupOpsCorpus(null);
const { GET } = await import("./copies/route");
const { POST: SCAN } = await import("./copies-scan/route");
const { POST: RELEASE } = await import("./copies-release/route");
+const { POST: CONFIRM } = await import("./copies-confirm/route");
+const { POST: REJECT } = await import("./copies-reject/route");
test.after(() => corpus.cleanup());
const GROUP = { id: "stream-copies", channels: ["pref-chan", "mirror-chan"] };
@@ -49,7 +51,37 @@ test("copies-scan refuses before any job: no group, an unknown group, too few ch
assert.deepEqual(await corpus.listJobIds(), []);
});
-test("get copies with a group, and copies-release writes the one releases file", async () => {
+// The scan's file, as a scan writes it: one metadata-only pair whose mirror
+// video's dir (the URL slug) is not its id (the embed id).
+async function scanFile() {
+ const member = (channel: string, dir: string, id: string, duration: number) => ({ channel, dir, id, title: `${dir} title`, duration, date: "20260301" });
+ await mkdir(path.join(corpus.transcripts, "copies"), { recursive: true });
+ await writeFile(
+ path.join(corpus.transcripts, "copies", "stream-copies.json"),
+ JSON.stringify({
+ format: "archilyzer-copies",
+ version: 1,
+ group: "stream-copies",
+ channels: GROUP.channels,
+ generatedAt: "2026-03-01T00:00:00.000Z",
+ rules: { dateWindowDays: 1, durationToleranceSeconds: 120, durationToleranceRatio: 0.02, withinChannels: false },
+ pairs: [
+ {
+ key: "pref-chan/p1|mirror-chan/slug-m1",
+ a: member("pref-chan", "p1", "p1", 7200),
+ b: member("mirror-chan", "slug-m1", "m1embed", 7230),
+ link: "metadata",
+ withinChannel: false,
+ evidence: { kind: "metadata", dateDeltaDays: 0, durationOk: true },
+ firstSeenAt: "2026-03-01T00:00:00.000Z",
+ },
+ ],
+ totals: { videos: {}, undated: 0, candidates: 1, confirmed: 0, metadata: 1, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0 },
+ }),
+ );
+}
+
+test("get copies with a group, and copies-release / -confirm / -reject write the one decisions file", async () => {
await corpus.writeSettings({ minFreeDiskGB: 0, sourceGroups: [GROUP] });
await channels();
const r = await callGet(GET!, "http://localhost/api/ops/copies?group=stream-copies&pairs=1");
@@ -64,16 +96,37 @@ test("get copies with a group, and copies-release writes the one releases file",
const bad = await callPost(RELEASE!, { group: "stream-copies", video: "no-slash" });
assert.equal(bad.status, 400);
assert.equal((await callPost(RELEASE!, { group: "other", video: "mirror-chan/m1" })).status, 404);
- const ok = await callPost(RELEASE!, { group: "stream-copies", videos: ["mirror-chan/m1", "mirror-chan/m2"], note: "listened" });
+ // No scan yet: nothing is known, nothing is stored.
+ const none = await callPost(RELEASE!, { group: "stream-copies", video: "mirror-chan/slug-m1" });
+ assert.deepEqual([none.body.applied, none.body.unknown], [[], ["mirror-chan/slug-m1"]]);
+
+ await scanFile();
+ // By the embed id, and an unknown key reported beside it.
+ const ok = await callPost(RELEASE!, { group: "stream-copies", videos: ["mirror-chan/m1embed", "mirror-chan/m2"], note: "listened", by: "operator" });
assert.equal(ok.status, 200, JSON.stringify(ok.body));
- assert.deepEqual(ok.body.released, ["mirror-chan/m1", "mirror-chan/m2"]);
- const undo = await callPost(RELEASE!, { group: "stream-copies", video: "mirror-chan/m1", undo: true });
- assert.deepEqual(undo.body.released, ["mirror-chan/m2"]);
- const file = JSON.parse(await readFile(path.join(corpus.transcripts, "copies", "stream-copies.releases.json"), "utf8"));
- assert.equal(file.released["mirror-chan/m2"].note, "listened");
- const again = await callGet(GET!, "http://localhost/api/ops/copies");
- assert.deepEqual((again.body.groups as { released: string[] }[])[0].released, ["mirror-chan/m2"]);
- await writeFile(path.join(corpus.transcripts, "copies", "stream-copies.releases.json"), "{broken");
+ assert.deepEqual([ok.body.applied, ok.body.unknown, ok.body.now], [["mirror-chan/slug-m1"], ["mirror-chan/m2"], ["mirror-chan/slug-m1"]]);
+ const file = JSON.parse(await readFile(path.join(corpus.transcripts, "copies", "stream-copies.decisions.json"), "utf8"));
+ assert.equal(file.released["mirror-chan/slug-m1"].note, "listened");
+ assert.equal(file.released["mirror-chan/slug-m1"].by, "operator");
+ const undo = await callPost(RELEASE!, { group: "stream-copies", video: "mirror-chan/slug-m1", undo: true });
+ assert.deepEqual(undo.body.now, []);
+
+ const listed = await callGet(GET!, "http://localhost/api/ops/copies");
+ const lg = (listed.body.groups as { metadataPairs: { key: string }[] }[])[0];
+ assert.deepEqual(lg.metadataPairs.map((x) => x.key), [], "first seen long ago: past its wait, nothing held");
+
+ assert.equal((await callPost(CONFIRM!, { group: "stream-copies", pair: "nope" })).status, 400);
+ assert.equal((await callPost(CONFIRM!, { group: "stream-copies", pair: "a/b|c/d", by: "someone" })).status, 400);
+ const conf = await callPost(CONFIRM!, { group: "stream-copies", pairs: ["mirror-chan/m1embed|pref-chan/p1"], by: "operator" });
+ assert.deepEqual(conf.body.applied, ["pref-chan/p1|mirror-chan/slug-m1"]);
+ const rej = await callPost(REJECT!, { group: "stream-copies", pair: "pref-chan/p1|mirror-chan/slug-m1" });
+ assert.deepEqual([rej.body.applied, rej.body.now], [["pref-chan/p1|mirror-chan/slug-m1"], ["pref-chan/p1|mirror-chan/slug-m1"]]);
+ const after = await callGet(GET!, "http://localhost/api/ops/copies");
+ const ag = (after.body.groups as { decisions: { confirmed: unknown[]; rejected: { key: string; by: string }[] } }[])[0];
+ assert.deepEqual(ag.decisions.confirmed, [], "the reject replaced the confirm");
+ assert.deepEqual(ag.decisions.rejected.map((d) => [d.key, d.by]), [["pref-chan/p1|mirror-chan/slug-m1", "agent"]]);
+
+ await writeFile(path.join(corpus.transcripts, "copies", "stream-copies.decisions.json"), "{broken");
const broken = await callGet(GET!, "http://localhost/api/ops/copies");
- assert.deepEqual((broken.body.groups as { released: string[] }[])[0].released, [], "an unreadable releases file releases nothing");
+ assert.deepEqual((broken.body.groups as { decisions: { released: string[] } }[])[0].decisions.released, [], "an unreadable decisions file decides nothing");
});
diff --git a/editor/app/api/ops/copies-confirm/route.ts b/editor/app/api/ops/copies-confirm/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { COPIES_DECIDE_BODY_KEYS, applyCopiesDecision } from "yt-dlp-transcript-common/controller/copiesScan";
+import { ops, opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { group, pair: "<channel>/<dir>|<channel>/<dir>" | pairs: [...], undo?, note?, by? }
+// -> { ok, group, action: "confirm", undo, applied, unknown, skipped, now }
+//
+// A METADATA-ONLY PAIR CONFIRMED AS ONE RECORDING (lane cross-source-dupes):
+// the lanes then treat it as a text-confirmed pair — the copy is skipped once
+// the other copy's work is done, instead of being held until the group's wait
+// ends and then done twice. Only a metadata-only pair takes it: a part-of or
+// overlapping pair (the words said it is not a copy of the whole) and a pair
+// inside one channel are named in `skipped` with the reason. A pair is named
+// as `get copies` prints its key, or by its two videos (dir or id) in either
+// order; one the scan does not list is reported in `unknown`. `by` is
+// "operator" or "agent" (the default), recorded with the time and the note in
+// `transcripts/copies/<group>.decisions.json`. A confirm replaces a reject of
+// the same pair; `undo: true` takes the confirm back. Synchronous.
+export async function POST(request: Request) {
+ return ops(request, COPIES_DECIDE_BODY_KEYS, async (body) => {
+ const out = await applyCopiesDecision(getPaths(), getSettings(), "confirm", body);
+ if (!out.ok) return opsFail(out.error, out.status);
+ return NextResponse.json(out);
+ });
+}
diff --git a/editor/app/api/ops/copies-reject/route.ts b/editor/app/api/ops/copies-reject/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { COPIES_DECIDE_BODY_KEYS, applyCopiesDecision } from "yt-dlp-transcript-common/controller/copiesScan";
+import { ops, opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { group, pair: "<channel>/<dir>|<channel>/<dir>" | pairs: [...], undo?, note?, by? }
+// -> { ok, group, action: "reject", undo, applied, unknown, skipped, now }
+//
+// A PAIR THAT IS NOT ONE RECORDING (lane cross-source-dupes): removed from the
+// lanes for good — it never holds or skips a copy again, whatever its link,
+// and later scans do not bring it back (the decision is kept by the pair's
+// key). The pair stays in the scan's file and the report counts it under
+// `rejected`. Named as copies-confirm names it; recorded with who, when and
+// the note in `transcripts/copies/<group>.decisions.json`. A reject replaces a
+// confirm of the same pair; `undo: true` takes it back. Synchronous.
+export async function POST(request: Request) {
+ return ops(request, COPIES_DECIDE_BODY_KEYS, async (body) => {
+ const out = await applyCopiesDecision(getPaths(), getSettings(), "reject", body);
+ if (!out.ok) return opsFail(out.error, out.status);
+ return NextResponse.json(out);
+ });
+}
diff --git a/editor/app/api/ops/copies-release/route.ts b/editor/app/api/ops/copies-release/route.ts
@@ -1,41 +1,30 @@
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
-import { COPIES_RELEASE_BODY_KEYS, parseCopiesReleaseBody } from "yt-dlp-transcript-common/controller/copiesScan";
-import { updateCopiesReleases } from "yt-dlp-transcript-common/lib/copies/file-server";
-import { OpsInputError, ops, opsFail } from "../_lib";
+import { COPIES_RELEASE_BODY_KEYS, applyCopiesDecision } from "yt-dlp-transcript-common/controller/copiesScan";
+import { ops, opsFail } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { group, video: "<channel>/<dir>" | videos: [...], undo?, note? }
-// -> { ok, group, released: ["<channel>/<dir>", ...] }
+// POST { group, video: "<channel>/<dir>" | videos: [...], undo?, note?, by? }
+// -> { ok, group, action: "release", undo, applied, unknown, skipped, now }
//
// A PERSON'S RELEASE (lane cross-source-dupes, slice 1): the transcription
// and Speakers lanes treat each named video as they did before its source
-// group existed — a held copy (a metadata-only match, or one waiting on its
-// preferred copy) and a skipped one alike are queued again by their lane's
-// own rules. `undo: true` takes the release back. Written to
-// `transcripts/copies/<group>.releases.json`, the one writer, under its lock;
-// the scan never touches it. Synchronous.
+// group existed — a held copy and a skipped one alike are queued again by
+// their lane's own rules. A video is named by its dir or its id (a Rumble
+// video's differ: the lanes key by dir); one the group's scan does not list
+// is reported in `unknown` and not stored. `undo: true` takes the release
+// back. `by` is "operator" or "agent" (the default): the caller's word, as
+// judge-trending takes it. Written with the time and the note to
+// `transcripts/copies/<group>.decisions.json` by its one writer, under its
+// lock; the scan never touches it. Synchronous.
+//
+// AN ADAPTER: the checks are the controller's (applyCopiesDecision).
export async function POST(request: Request) {
return ops(request, COPIES_RELEASE_BODY_KEYS, async (body) => {
- let parsed;
- try {
- parsed = parseCopiesReleaseBody(body);
- } catch (e) {
- throw new OpsInputError((e as Error).message);
- }
- const settings = getSettings();
- if (!settings.sourceGroups.some((g) => g.id === parsed.group)) {
- return opsFail(
- `no source group "${parsed.group}" — settings.sourceGroups names ${settings.sourceGroups.map((g) => g.id).join(", ") || "none"}`,
- 404,
- );
- }
- const file = await updateCopiesReleases(getPaths().transcriptsDir, parsed.group, parsed.videos, {
- undo: parsed.undo,
- ...(parsed.note ? { note: parsed.note } : {}),
- });
- return NextResponse.json({ ok: true, group: parsed.group, released: Object.keys(file.released) });
+ const out = await applyCopiesDecision(getPaths(), getSettings(), "release", body);
+ if (!out.ok) return opsFail(out.error, out.status);
+ return NextResponse.json(out);
});
}
diff --git a/editor/app/operations/status.ts b/editor/app/operations/status.ts
@@ -75,7 +75,9 @@ export async function buildAutoQueueStatusPayload(): Promise<AutoQueueStatusPayl
// are folded from, so an edit to a policy, a tree or a priority recomputes
// them at once; only what changes without a settings write (a snapshot, the
// runner's in-flight set) can be up to 3 s behind.
- const memoKey = JSON.stringify([settings.autoQueue, settings.channelPriority]);
+ // sourceGroups too: the transcription and Speakers lanes' pending lists
+ // drop the copies a source group skips or holds (lane cross-source-dupes).
+ const memoKey = JSON.stringify([settings.autoQueue, settings.channelPriority, settings.sourceGroups]);
const [priority, state, { briefs, pendingByKind }] = await Promise.all([
readPriorityView(),
readAutoQueueState(paths),
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -796,10 +796,15 @@ const ACTIONS = [
"mirror-scan",
// SOURCE GROUPS (lane cross-source-dupes): a group's channels paired video
// by video into transcripts/copies/<group>.json ({group, dryRun?}), as a
- // copies-scan job; and a held or skipped copy released to its lanes again
- // ({group, video | videos, undo?, note?}), synchronous.
+ // copies-scan job; a held or skipped copy released to its lanes again
+ // ({group, video | videos, undo?, note?, by?}); a metadata-only pair
+ // confirmed as one recording, or any pair rejected ({group, pair | pairs,
+ // undo?, note?, by?}) — the three synchronous, into
+ // transcripts/copies/<group>.decisions.json.
"copies-scan",
"copies-release",
+ "copies-confirm",
+ "copies-reject",
// RECURRING REPORTS (umtool R5): a living report or a dated series on a
// cadence the editor keeps ({action: list | create | update | pause |
// resume | delete | tick-now | reset-triage, …}); tick-now is a
@@ -1409,12 +1414,16 @@ export function usage() {
"get copies [<group>] is the source groups' copies report (settings.sourceGroups,",
" SETTINGS.md), read only: each group's channels in order of preference,",
" whether the lanes act on it, its last scan (transcripts/copies/<group>.json:",
- " when, the totals), its pairs by link (confirmed by text, metadata only,",
- " partial, inside one channel), what the fallback copies of confirmed",
- " recordings hold (seconds; audio bytes through tier links, null with the",
- " reason when a channel's media cannot be read now) and the released videos;",
- " and `lanes`: what the transcription and Speakers lanes skip and hold right",
- " now, each video with its reason. With <group>, every pair and its evidence.",
+ " when, the totals), its pairs by link (confirmed, metadata only, part-of,",
+ " overlapping, rejected, inside one channel), what the fallback copies of",
+ " confirmed recordings hold (seconds; audio bytes through tier links, null",
+ " with the reason when a channel's media cannot be read now), the",
+ " metadata-only pairs still in their wait (titles, dates, runtimes and",
+ " their difference, when each wait ends) for copies-confirm or",
+ " copies-reject in bulk, the decisions given (released, confirmed,",
+ " rejected, with who and when), and `lanes`: what the transcription and",
+ " Speakers lanes skip and hold right now, each video with its reason. With",
+ " <group>, every pair and its evidence.",
"get lookout-run <id> [--run <runId>] is one lookout's latest run (or the",
" one named), whole: its window, the selection it read, calls, seconds,",
" the reading counts (read, reused from fresh notes, failed), its ideas and",
@@ -3035,24 +3044,46 @@ export function usage() {
' "dryRun"?} -> {jobId}. The group is settings.sourceGroups\' (an ordered',
" list of channels holding the same recordings, the preferred source first;",
" pnpm ops settings sets it). Two videos are candidates when their recorded",
- " dates are at most dateWindowDays apart; where both have a cue file their",
- " words decide (40 phrases probed, the largest set at one consistent offset:",
- " 8 or more confirmed, 4-7 partial, fewer not a pair), and where one has no",
- " words agreeing runtimes make a metadata-only pair. No media, no network.",
- " Written to transcripts/copies/<group>.json (private: never published),",
- " each pair with its link, its evidence and when it was first seen; a scan",
- " that finds what the file says leaves it as it was. With the group's lanes",
- " on, the transcription and Speakers lanes skip a confirmed copy whose other",
- " copy has the work done and hold a metadata-only one (get copies says each",
- " one's reason). dryRun writes nothing. The log ends with @@copies-scan",
- " {group, dryRun, unchanged, file?, channels, missing?, totals}.",
+ " dates are at most dateWindowDays apart. Where both have a cue file their",
+ " words decide, probed both ways (40 phrases each way, each counted once):",
+ " each copy holding at least 75 % of the other AND runtimes within the",
+ " group's tolerance is confirmed; one inside the other, or the words the",
+ " same and the runtimes apart, is part-of; a shared stretch is overlaps;",
+ " less is not a pair. Where one has no words, agreeing runtimes make a",
+ " metadata-only pair. No media, no network. Written to",
+ " transcripts/copies/<group>.json (private: never published), each pair",
+ " with its link, its evidence and when it was first seen; a scan that finds",
+ " what the file says leaves it as it was. With the group's lanes on, the",
+ " transcription and Speakers lanes skip a confirmed copy whose other copy",
+ " has the work done, and hold a metadata-only one (or one waiting on its",
+ " preferred copy) for at most waitDays; part-of and overlapping pairs are",
+ " reported only (get copies says each one's reason). Cancelling the job",
+ " stops it with nothing written; dryRun writes nothing. The log ends with",
+ " @@copies-scan {group, dryRun, unchanged, file?, channels, missing?,",
+ " totals}.",
"",
'copies-release releases copies to their lanes: {"group", "video":',
- ' "<channel>/<dir>" | "videos": [...], "undo"?, "note"?} -> {group,',
- " released}. A released video is queued by its lanes as if it had no source",
- " group, whether it was held (a metadata-only match, or waiting on its",
- " preferred copy) or skipped; undo takes the release back. Written to",
- " transcripts/copies/<group>.releases.json, which the scan never touches.",
+ ' "<channel>/<dir>" | "videos": [...], "undo"?, "note"?, "by"?} ->',
+ " {group, action, undo, applied, unknown, skipped, now}. A released video is",
+ " queued by its lanes as if it had no source group, whether it was held or",
+ " skipped; undo takes the release back. A video may be named by its dir or",
+ " its id (a Rumble video's differ); one the scan does not list is reported",
+ " in unknown and not stored. by is \"operator\" or \"agent\" (the default),",
+ " the caller's word, recorded with the time and the note in",
+ " transcripts/copies/<group>.decisions.json, which the scan never touches.",
+ "",
+ 'copies-confirm confirms metadata-only pairs as the same recording: {"group",',
+ ' "pair": "<channel>/<dir>|<channel>/<dir>" | "pairs": [...], "undo"?,',
+ ' "note"?, "by"?} -> {group, action, undo, applied, unknown, skipped, now}.',
+ " A confirmed pair acts as one confirmed by text: the copy is skipped once",
+ " the other copy's work is done. Only a metadata-only pair takes it; a",
+ " part-of or overlapping one is skipped with the reason. get copies lists",
+ " the metadata pairs in their wait, with titles, dates and runtimes, for",
+ " confirming in bulk. Recorded with who and when, as copies-release.",
+ "",
+ 'copies-reject rejects pairs: the same body as copies-confirm. A rejected',
+ " pair never holds or skips again, whatever its link; undo takes it back,",
+ " and a later confirm replaces it.",
"",
'report-schedule keeps a recurring report on a cadence the editor ticks:',
' {"action": "list" | "create" | "update" | "pause" | "resume" | "delete" |',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1196,7 +1196,7 @@ test("watch-trending posts its body; its help says a watch runs only on a fresh
// Lane cross-source-dupes: the copies scan is a job whose --wait prints its
// result line, the release a synchronous POST, the report a read.
-test("copies-scan and copies-release are POSTs; get copies reads the report, one group with its pairs", () => {
+test("copies-scan, copies-release, copies-confirm and copies-reject are POSTs; get copies reads the report, one group with its pairs", () => {
const scan = parseArgs(["copies-scan", "--json", '{"group":"stream-copies","dryRun":true}', "--wait"]);
assert.equal(scan.path, "/api/ops/copies-scan");
assert.equal(scan.resultMarker, COPIES_SCAN_RESULT_MARKER);
@@ -1204,6 +1204,12 @@ test("copies-scan and copies-release are POSTs; get copies reads the report, one
const release = parseArgs(["copies-release", "--json", '{"group":"stream-copies","video":"mirror-chan/m1"}']);
assert.equal(release.path, "/api/ops/copies-release");
assert.deepEqual(release.body, { group: "stream-copies", video: "mirror-chan/m1" });
+ for (const action of ["copies-confirm", "copies-reject"]) {
+ const d = parseArgs([action, "--json", '{"group":"stream-copies","pairs":["pref-chan/p1|mirror-chan/m1"],"by":"operator"}']);
+ assert.equal(d.path, `/api/ops/${action}`);
+ assert.deepEqual(d.body, { group: "stream-copies", pairs: ["pref-chan/p1|mirror-chan/m1"], by: "operator" });
+ }
+ assert.match(usage(), /copies-confirm confirms metadata-only pairs/);
assert.equal(parseArgs(["get", "copies"]).path, "/api/ops/copies");
assert.equal(parseArgs(["get", "copies", "stream-copies"]).path, "/api/ops/copies?group=stream-copies&pairs=1");
assert.match(usage(), /get copies \[<group>\]/);