commit 2f1bbb67226075a08065129e0a28f60aef0f4991
parent bedbb057dc812fa7ec3040c8ebafd5825648f8da
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 02:03:11 -0500
umtool: a per-project link policy -- cite via site X, these channels direct -- that the inserters and the check enforce (UI notes #10)
- provenance.linkPolicy {via?, direct?} (lib/report/linkPolicy.mjs): via the archive every QR opens (default provenance.siteOrigin), direct the channels whose clips link the platform's own page at the cite (watchUrlAt over the record's webpage_url)
- one writer, updateLinkPolicy (manifest.mjs): the Overview's Link policy panel (PUT /api/report/link-policy), `umtool link-policy <p> --via <site id|url> --direct a,b [--clear] [--fix] [--json]`
- the inserters write by it: addClip (the strip's selection, the clip finder, a live share) and insertEntry (`umtool timeline insert`, the Cut tab) give a new clip the policy's citeUrl when its own -- a neighbour's copied link included -- would break it
- the check: clip-link-policy (open, one row per clip), its one press the window writer's citeUrl ("Link via site.test" / "Link its YouTube page"), its fix `umtool window <p> <clip> --cite-url '…'`
- unit tests; docs: knobs.md "The link policy", inbox.md, cli.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 759 insertions(+), 4 deletions(-)
diff --git a/umtool/app/api/report/link-policy/route.ts b/umtool/app/api/report/link-policy/route.ts
@@ -0,0 +1,71 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken, updateLinkPolicy } from "@/lib/report/manifest.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { linkPolicyOf } from "@/lib/report/linkPolicy.mjs";
+import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
+import { SITES_DIR } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10; lib/report/linkPolicy.mjs):
+// "cite via site X; these channels direct", `provenance.linkPolicy`.
+//
+// GET ?project=<id> the policy, the cut's channels (with their clip counts),
+// the sites a policy may cite via (SITES_DIR, each with a
+// siteUrl), provenance.siteOrigin, the token
+// PUT { project, token, policy: { via?, direct? } | null } set it (null clears)
+//
+// Setting it rewrites no clip: what breaks it is the check's clip-link-policy
+// rows, each with its one-press fix through the window writer; new clips are
+// written by it (the inserters). `umtool link-policy <p> …` is the same writer.
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const m = r.manifest as { provenance?: Record<string, unknown>; timeline?: { type?: string; channel?: string }[] };
+ const counts = new Map<string, number>();
+ const fallback = typeof m.provenance?.channelSlug === "string" ? m.provenance.channelSlug : null;
+ for (const e of m.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const c = e.channel ?? fallback;
+ if (c) counts.set(c, (counts.get(c) ?? 0) + 1);
+ }
+ return Response.json(
+ {
+ policy: linkPolicyOf(m),
+ siteOrigin: typeof m.provenance?.siteOrigin === "string" ? m.provenance.siteOrigin : null,
+ channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)),
+ sites: [...sitesByOrigin(SITES_DIR)].map(([origin, s]) => ({ origin, siteId: s.siteId, title: s.title })),
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ const refused = refuseCaller(request, "/api/report/link-policy");
+ if (refused) return refused;
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ if (!("policy" in body)) return Response.json({ error: "policy is required — { via?, direct? }, or null to clear it" }, { status: 400 });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updateLinkPolicy(r.project.dir, body.policy ?? null, { token: typeof body.token === "string" ? body.token : null }),
+ );
+ return Response.json({ ok: true, ...result, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) {
+ return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 });
+ }
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -15,6 +15,7 @@
// umtool show <project> [--json]
// umtool check [<project> | --all] [--json] exit 1 on anything blocking
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
+// umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct
// umtool decisions [--json]
// umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them
// umtool schedule list | show <id> [--json] the recurring reports (R5), read-only
@@ -776,6 +777,8 @@ function usage() {
" umtool check [<project>] [--json] exit 1 on anything blocking",
" umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage",
" -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead",
+ " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy",
+ " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it",
" umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a",
" clip not in the cut; --fix gives each the after of the cut's marker of the same label",
" umtool decisions [--json]",
@@ -997,6 +1000,8 @@ const COMMANDS = {
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
+ // The project's link policy (UI notes #10): lib/report/linksCli.mjs.
+ "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))),
// A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs.
"patch-markers": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).patchMarkersCommand(argv.slice(argv.indexOf("patch-markers") + 1))),
// The trailer's beats, edited (UI notes item 11): lib/report/trailerBeatsCli.mjs.
diff --git a/umtool/components/projects/report/LinkPolicyPanel.tsx b/umtool/components/projects/report/LinkPolicyPanel.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { buttonVariants } from "@/components/ui/button";
+
+// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10): "cite via site X;
+// these channels direct" -- `provenance.linkPolicy`, through the one writer
+// (PUT /api/report/link-policy; `umtool link-policy <p>` from a terminal).
+// New clips are written by it; the clips already in the cut that break it are
+// the check's clip-link-policy rows, each with its one-press fix.
+
+type View = {
+ policy: { via: string | null; direct: string[] } | null;
+ siteOrigin: string | null;
+ channels: { slug: string; clips: number }[];
+ sites: { origin: string; siteId: string; title: string | null }[];
+ token: string | null;
+};
+
+const DEFAULT = "";
+
+export default function LinkPolicyPanel({ project }: { project: string }) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [via, setVia] = useState(DEFAULT);
+ const [direct, setDirect] = useState<string[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/link-policy?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => null)) as View | null;
+ if (!r.ok || !j) return;
+ setView(j);
+ setVia(j.policy?.via ?? DEFAULT);
+ setDirect(j.policy?.direct ?? []);
+ }, [project]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ if (!view || !view.channels.length) return null;
+ const options = [...view.sites];
+ if (view.policy?.via && !options.some((s) => s.origin === view.policy?.via)) {
+ options.push({ origin: view.policy.via, siteId: new URL(view.policy.via).host, title: null });
+ }
+ const dirty = via !== (view.policy?.via ?? DEFAULT) || direct.join(",") !== (view.policy?.direct ?? []).join(",");
+
+ const save = async () => {
+ setBusy(true);
+ setErr(null);
+ setSaid(null);
+ try {
+ const policy = via || direct.length ? { ...(via ? { via } : {}), ...(direct.length ? { direct } : {}) } : null;
+ const r = await fetch("/api/report/link-policy", {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, token: view.token, policy }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; changed?: boolean };
+ if (!r.ok) {
+ setErr(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setSaid(j.changed ? "saved — the check names every clip that breaks it" : "unchanged");
+ await load();
+ router.refresh();
+ } catch (e) {
+ setErr(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const defaultHost = (() => {
+ try {
+ return view.siteOrigin ? new URL(view.siteOrigin).host : null;
+ } catch {
+ return view.siteOrigin;
+ }
+ })();
+
+ return (
+ <section data-link-policy={view.policy ? "set" : "none"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <h2 className="micro mb-1.5">Link policy</h2>
+ <label className="flex flex-wrap items-center gap-2 text-[12.5px] text-text-2">
+ Cite via
+ <select
+ data-link-policy-via=""
+ value={via}
+ onChange={(e) => setVia(e.target.value)}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12.5px]"
+ >
+ <option value={DEFAULT}>{defaultHost ? `the cut's site origin (${defaultHost})` : "the cut's site origin"}</option>
+ {options.map((s) => (
+ <option key={s.origin} value={s.origin}>
+ {s.siteId} — {new URL(s.origin).host}
+ </option>
+ ))}
+ </select>
+ </label>
+ <p className="mt-1.5 text-[12px] text-muted">These channels link their platform’s own page directly:</p>
+ <ul className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
+ {view.channels.map((c) => (
+ <li key={c.slug}>
+ <label className="flex items-center gap-1.5 text-[12.5px]">
+ <input
+ type="checkbox"
+ data-link-policy-direct={c.slug}
+ checked={direct.includes(c.slug)}
+ onChange={(e) => setDirect((d) => (e.target.checked ? [...d, c.slug].sort() : d.filter((x) => x !== c.slug)))}
+ />
+ <span className="font-mono text-[12px]">{c.slug}</span>
+ <span className="text-[11.5px] text-muted">
+ {c.clips} clip{c.clips === 1 ? "" : "s"}
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ data-link-policy-save=""
+ disabled={busy || !dirty}
+ onClick={() => void save()}
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ title="writes provenance.linkPolicy; new clips take its links, and the check names the clips that break it"
+ >
+ {busy ? "Saving…" : "Save link policy"}
+ </button>
+ <span className="font-mono text-[11px] text-muted">umtool link-policy {project} --via <site> --direct a,b</span>
+ {said && !err && (
+ <span data-link-policy-said="" className="text-[11.5px] text-text-2">
+ {said}
+ </span>
+ )}
+ {err && (
+ <span data-link-policy-error="" className="text-[11.5px] text-doubt-text">
+ {err}
+ </span>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx
@@ -16,6 +16,7 @@ import type { PieceFrame } from "@/lib/pieces/frame";
import { TONE, hms, type ReportTabProps } from "./shared";
import DecisionSettle from "./DecisionSettle";
import ProjectSites from "./ProjectSites";
+import LinkPolicyPanel from "./LinkPolicyPanel";
import { manifestToken } from "@/lib/report/manifest.mjs";
// The Overview tab (canvas "Piece · Overview"): the Next card, then the
@@ -119,6 +120,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP
</section>
<ProjectSites project={project} detail={detail} />
+ <LinkPolicyPanel project={project.id} />
{frame.board && (
<section data-piece-board={frame.board.id}>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -27,6 +27,7 @@ Inbox cannot disagree about what is wrong with one.
| `window <project> <clip> --verdict confirmed\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]` | what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said)) |
| `window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>` | what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip)) |
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
+| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
| `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) |
| `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at |
diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md
@@ -71,6 +71,7 @@ on (`decisionTab`, `songTabOfSection`).
| `links-unverified` | info | the link check could not reach a site (offline, a timeout, no corpus.json) | Check links again |
| `links-unchecked` | info | archive links never checked, or changed since the check | Check links |
| `site-deploy-behind` | open | a site the QRs open whose deploy (its recorded corpus.json `generatedAt`) is older than cited videos whose links the check did not find open — one row per site ([knobs.md](knobs.md#the-sites-the-links-depend-on)) | Publish <site> |
+| `clip-link-policy` | open | a clip whose QR breaks the project's link policy (`provenance.linkPolicy`): a direct channel's clip opening an archive, or another clip not opening the policy's site ([knobs.md](knobs.md#the-link-policy)) | Link it by the policy |
| `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows |
| `clip-cue-gap` | open | the cue file ends before a clip does (`cues end 880 s · c03 needs 897 s`), one row per source | Fix the window |
| `claim-unadjudicated` | blocking | a `ledger[]` entry missing any of the six adjudication fields — one row per entry | Adjudicate claim |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -100,6 +100,24 @@ videos are newer: …*. Its **Publish anilyzer** asks the editor to build and de
stage through the heavy slot); from a terminal, `pnpm ops build-deploy --json '{"siteId":"anilyzer"}'`.
A link the check opened is on the site, whatever its dates say.
+## The link policy
+
+"Cite via site X; these channels direct." `provenance.linkPolicy` — `{via?, direct?}`: `via` the archive
+every clip's QR opens (an origin; absent: `provenance.siteOrigin`), `direct` the channel slugs whose
+clips link the platform's own page at the cite (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble
+`start=<s>`, from the record's `webpage_url`). Set on the project page's Overview (**Link policy**:
+**Cite via**, a box per channel the cut cites, **Save link policy**), `umtool link-policy <p> --via
+<site id | https://…> --direct a,b` (`''` clears one, `--clear` the policy), or `PUT
+/api/report/link-policy {project, token, policy}`. Saving rewrites no clip. **New clips are written
+by it**: every inserter (`addClip` — the strip's selection, the clip finder, a live share — and
+`insertEntry` — `umtool timeline insert`, the Cut tab) gives a new clip the policy's link when its own
+would break it (a neighbour's copied citeUrl included). The clips already in the cut that break it are
+the check's `clip-link-policy` rows (open, one per clip), each with its one press — **Link via
+site.test** / **Link its YouTube page**, the citeUrl through the window writer — and its terminal twin
+(`umtool window <p> <clip> --cite-url '…'`); `umtool link-policy <p> --fix` does them all. A direct
+clip whose record names no `webpage_url` is a row without a fix. A clip with its own media (`src`) is
+not judged.
+
## Gaps inside a clip
A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -134,6 +134,7 @@ const ACTION_LABEL = {
"links-unverified": "Check links again",
"links-unchecked": "Check links",
"site-deploy-behind": (d) => (d.settle?.kind === "publish-site" ? d.settle.label : "Publish the site"),
+ "clip-link-policy": "Link it by the policy",
"no-punctuation": "Check the windows",
"manifest-invalid": "Fix the manifest",
"stale-build": "Rebuild the video",
diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs
@@ -39,6 +39,7 @@ export const WHAT = {
"links-unverified": "links not verified",
"links-unchecked": "links not checked",
"site-deploy-behind": "a cited site's deploy is behind the cut",
+ "clip-link-policy": "QR links that break the link policy",
"no-punctuation": "windows without punctuation",
"manifest-invalid": "manifest invalid",
"stale-build": "video out of date",
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -47,6 +47,7 @@ import { citeOffsets } from "../report/citeFollow.mjs";
import { PATCH_FILE_RE, stalePatchMarkers } from "../report/patchMarkers.mjs";
import { linkVerdicts, linksFile, readLinkCheck } from "../report/linkCheck.mjs";
import { deployBehindWhy, projectSites, sitesByOrigin } from "../report/siteDeploys.mjs";
+import { policyBreaks, policyFixLabel } from "../report/linkPolicy.mjs";
// widen() and the cache's window naming are IMPORTED, never reimplemented. The
// bench's "extend to sentence end" has to be the same function the CLI runs, or
@@ -1076,6 +1077,10 @@ export const REPORT_DECISION_KINDS = [
// is older than videos the cut cites there, and the check did not find
// those open (siteDeploys.mjs). `open`, with Publish <site>.
"site-deploy-behind",
+ // A clip whose QR breaks the project's link policy (provenance.linkPolicy,
+ // linkPolicy.mjs): a direct channel's clip opening an archive, or another
+ // clip not opening the policy's site. `open`, with the policy's link.
+ "clip-link-policy",
];
/**
@@ -1230,7 +1235,7 @@ export async function reportDecisions(ctx, summary) {
}
const unpunctuated = [];
- /** @type {Map<string, { uploadDate: string | null, landedAt: string | null }>} */
+ /** @type {Map<string, { uploadDate: string | null, landedAt: string | null, webpageUrl: string | null }>} */
const recordByClip = new Map();
for (const [key, list] of byVideo) {
const file = cuePathFor(m, list[0], channelsDir);
@@ -1259,7 +1264,7 @@ export async function reportDecisions(ctx, summary) {
// date and when its transcript landed here.
{
const st = await stat0(file);
- for (const e of list) recordByClip.set(e.id, { uploadDate: doc.uploadDate ?? null, landedAt: st ? new Date(st.mtimeMs).toISOString() : null });
+ for (const e of list) recordByClip.set(e.id, { uploadDate: doc.uploadDate ?? null, landedAt: st ? new Date(st.mtimeMs).toISOString() : null, webpageUrl: doc.webpageUrl ?? null });
}
for (const e of list) {
@@ -1631,6 +1636,21 @@ export async function reportDecisions(ctx, summary) {
}
}
+ // --- the project's link policy (linkPolicy.mjs) --------------------------
+ // "Cite via site X; these channels direct": one row per clip whose QR
+ // breaks it, the fix the window writer's citeUrl.
+ for (const b of policyBreaks(m, { webpageOf: (e) => recordByClip.get(e.id)?.webpageUrl ?? null })) {
+ add("clip-link-policy", b.clip, b.why, "open", {
+ href: clipHref(b.clip),
+ ...(b.fix
+ ? {
+ fix: `umtool window ${id} ${b.clip} --cite-url '${b.fix}'`,
+ settle: { kind: "patch", clip: b.clip, patch: { citeUrl: b.fix }, label: policyFixLabel(b) },
+ }
+ : {}),
+ });
+ }
+
// --- is each site's deploy recent enough? (siteDeploys.mjs) --------------
// From the same recorded check: the deploy's date is its corpus.json's
// generatedAt. A cited video newer than it, whose link the check did not
diff --git a/umtool/lib/report/linkPolicy.mjs b/umtool/lib/report/linkPolicy.mjs
@@ -0,0 +1,211 @@
+// A project's LINK POLICY (UI notes 2026-10-30, #10): "cite via site X; these
+// channels direct". On the Ember cut Ember's and Side Scrollers' clips linked
+// anilyzer while Harmful Opinions' linked YouTube, and the citeUrls were
+// rewritten by hand twice. The policy lives in the manifest, beside the other
+// link setting it qualifies (`provenance.siteOrigin`):
+//
+// provenance.linkPolicy = { via?: "<origin>", direct?: ["<channel slug>", …] }
+//
+// via the archive every clip's QR opens (default: provenance.siteOrigin)
+// direct the channels whose clips link the platform's own page at the cite
+// (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble `start=<s>` --
+// common/lib/clips/assist.mjs watchUrlAt over the record's webpage_url)
+//
+// Enforced in two places, both through the existing writers:
+//
+// - THE INSERTERS (manifest.mjs addClip: the strip's selection, the clip
+// finder, a live share; `umtool timeline insert`): the citeUrl a new clip
+// is written with is the policy's (`policyCiteUrl`), never a neighbour's
+// link that breaks it.
+// - THE CHECK (lib/projects/report.mjs): `clip-link-policy`, one row per clip
+// whose QR breaks the policy, its settle the window writer's citeUrl patch
+// ("Link via site.test" / "Link its YouTube page").
+//
+// A clip with its own media (`src`) is not judged. Plain ESM: the CLI runs it
+// under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
+import { archiveLinkOf } from "./linkCheck.mjs";
+import { originOf } from "./siteDeploys.mjs";
+
+export const LINK_POLICY_KEY = "linkPolicy";
+const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i;
+
+/**
+ * A policy as written, checked and normalised: `{ via, direct }` (via an
+ * origin or null, direct sorted and unique), or null for "no policy". Throws
+ * on a policy the check could not apply.
+ * @param {unknown} raw
+ * @returns {{ via: string | null, direct: string[] } | null}
+ */
+export function normalizeLinkPolicy(raw) {
+ if (raw == null) return null;
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new Error("provenance.linkPolicy is { via?, direct? }");
+ const r = /** @type {Record<string, unknown>} */ (raw);
+ for (const k of Object.keys(r)) if (k !== "via" && k !== "direct") throw new Error(`provenance.linkPolicy has no key "${k}" (via, direct)`);
+ let via = null;
+ if (r.via != null && String(r.via).trim() !== "") {
+ via = originOf(String(r.via).trim());
+ if (!via) throw new Error(`linkPolicy.via is a site's http(s) address, not ${JSON.stringify(r.via)}`);
+ }
+ const list = r.direct == null ? [] : Array.isArray(r.direct) ? r.direct : String(r.direct).split(",");
+ const direct = [...new Set(list.map((s) => String(s).trim()).filter(Boolean))].sort();
+ for (const s of direct) if (!SLUG_RE.test(s)) throw new Error(`linkPolicy.direct names channel slugs, not ${JSON.stringify(s)}`);
+ return via || direct.length ? { via, direct } : null;
+}
+
+/** The manifest's policy, or null (none, or one that does not read). */
+export function linkPolicyOf(m) {
+ try {
+ return normalizeLinkPolicy(m?.provenance?.[LINK_POLICY_KEY]);
+ } catch {
+ return null;
+ }
+}
+
+const chanOf = (m, e) => e?.channel ?? m?.provenance?.channelSlug ?? null;
+const citeOf = (e) => Math.floor(Number(e?.cite ?? e?.cutStart ?? e?.start ?? 0) || 0);
+
+/**
+ * Where a clip's QR points now -- build-video's rule (lib/projects/report.mjs
+ * citeUrlFor): its own citeUrl, else its moment on the provenance's origin.
+ */
+export function currentLinkOf(m, e) {
+ if (typeof e?.citeUrl === "string" && e.citeUrl) return e.citeUrl;
+ return archiveMomentUrl({ ...e, channel: chanOf(m, e) }, m?.provenance, e?.start ?? 0, { origin: m?.provenance?.siteOrigin ?? "" });
+}
+
+/**
+ * What the policy wants of one clip: `{ want: "direct" | "via", url }`, the
+ * url null when it cannot be built (a direct clip whose record names no
+ * webpage_url, a via policy with no origin). Null when the policy has nothing
+ * to say about the clip.
+ * @param {Record<string, any>} m
+ * @param {Record<string, any>} e
+ * @param {{ webpageUrl?: string | null, policy?: ReturnType<typeof linkPolicyOf> }} [o]
+ */
+export function policyLinkFor(m, e, { webpageUrl = null, policy = linkPolicyOf(m) } = {}) {
+ if (!policy || e?.type !== "clip" || e.src != null) return null;
+ const chan = chanOf(m, e);
+ const cite = citeOf(e);
+ if (chan && policy.direct.includes(chan)) return { want: /** @type {const} */ ("direct"), url: watchUrlAt(webpageUrl, cite) };
+ const via = policy.via ?? originOf(m?.provenance?.siteOrigin);
+ if (!via) return null;
+ return { want: /** @type {const} */ ("via"), url: archiveMomentUrl({ ...e, channel: chan }, m?.provenance, cite, { origin: via }), via };
+}
+
+/**
+ * Whether the clip's QR keeps the policy: a direct channel's is not an
+ * archive link; any other's is an archive link on `via`. `null` when the
+ * policy says nothing about the clip.
+ */
+export function keepsPolicy(m, e, o = {}) {
+ const want = policyLinkFor(m, e, o);
+ if (!want) return null;
+ const a = archiveLinkOf(currentLinkOf(m, e));
+ if (want.want === "direct") return !a;
+ return !!a && a.origin === /** @type {any} */ (want).via;
+}
+
+/**
+ * Every clip whose QR breaks the policy, with the citeUrl that keeps it (null
+ * when it cannot be built). Pure over `webpageOf` (the record's webpage_url).
+ * @param {Record<string, any>} m
+ * @param {{ webpageOf?: (e: Record<string, any>) => string | null }} [o]
+ */
+export function policyBreaks(m, { webpageOf = () => null } = {}) {
+ const policy = linkPolicyOf(m);
+ if (!policy) return [];
+ const out = [];
+ for (const e of m?.timeline ?? []) {
+ if (e?.type !== "clip" || e.src != null) continue;
+ const webpageUrl = webpageOf(e);
+ const want = policyLinkFor(m, e, { webpageUrl, policy });
+ if (!want || keepsPolicy(m, e, { webpageUrl, policy }) !== false) continue;
+ const current = currentLinkOf(m, e);
+ let host = "";
+ try {
+ host = new URL(current).host;
+ } catch {
+ host = current;
+ }
+ out.push({
+ clip: e.id,
+ channel: chanOf(m, e),
+ current,
+ want: want.want,
+ fix: want.url,
+ why:
+ want.want === "direct"
+ ? `${chanOf(m, e)} links direct by the project's link policy, but its QR opens ${host}${want.url ? "" : " — and its record names no platform page to link (no webpage_url)"}`
+ : `the project's link policy cites via ${new URL(/** @type {any} */ (want).via).host}, but its QR opens ${host}`,
+ });
+ }
+ return out;
+}
+
+/** The settle button's words for a fix. */
+export function policyFixLabel(b) {
+ if (b.want === "direct") {
+ let host = "the platform";
+ try {
+ host = new URL(String(b.fix)).hostname.replace(/^(?:www|m)\./, "");
+ } catch {
+ /* keep the generic word */
+ }
+ const name = /youtu/.test(host) ? "YouTube" : /twitch/.test(host) ? "Twitch" : /rumble/.test(host) ? "Rumble" : host;
+ return `Link its ${name} page`;
+ }
+ try {
+ return `Link via ${new URL(String(b.fix)).host}`;
+ } catch {
+ return "Link via the site";
+ }
+}
+
+/**
+ * The record's webpage_url, read once per recording: the cue file's
+ * `webpageUrl`, else metadata.info.json's `webpage_url`. Null when neither
+ * says (or there is no channels dir).
+ * @param {string | null} channelsDir
+ */
+export function webpageReader(channelsDir) {
+ const memo = new Map();
+ return async (slug, video) => {
+ if (!channelsDir || !slug || !video) return null;
+ const key = `${slug}/${video}`;
+ if (!memo.has(key)) {
+ memo.set(key, (async () => {
+ const dir = await resolveVideoDir(channelsDir, slug, video).catch(() => path.join(channelsDir, slug, "data", video));
+ const read = (name) => readFile(path.join(/* turbopackIgnore: true */ dir, name), "utf8").then(JSON.parse, () => null);
+ const cues = await read("transcript.cues.json");
+ if (typeof cues?.webpageUrl === "string" && cues.webpageUrl) return cues.webpageUrl;
+ const meta = await read("metadata.info.json");
+ return typeof meta?.webpage_url === "string" && meta.webpage_url ? meta.webpage_url : null;
+ })());
+ }
+ return memo.get(key);
+ };
+}
+
+/**
+ * The citeUrl an inserter writes a NEW clip with under the policy: the
+ * policy's link when the clip's link would break it (a neighbour's copied
+ * citeUrl, or the default origin when `via` is another site), `undefined`
+ * when the clip keeps it as it is (so nothing is written), `null` when the
+ * link the policy wants cannot be built (the clip's citeUrl is dropped so the
+ * check names it, rather than a copied link that breaks the policy).
+ * @param {Record<string, any>} m
+ * @param {Record<string, any>} entry
+ * @param {string | null} webpageUrl
+ */
+export function policyCiteUrl(m, entry, webpageUrl) {
+ const policy = linkPolicyOf(m);
+ const want = policyLinkFor(m, entry, { webpageUrl, policy });
+ if (!want) return undefined;
+ if (keepsPolicy(m, entry, { webpageUrl, policy }) === true) return undefined;
+ return want.url;
+}
diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs
@@ -159,3 +159,111 @@ export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s)
return e instanceof CliError ? 2 : 1;
}
}
+
+export const LINK_POLICY_USAGE = [
+ "usage: umtool link-policy <project> [--via <site id | https://…>] [--direct <slug,slug…>] [--clear] [--fix] [--json]",
+ "",
+ "The project's link policy, provenance.linkPolicy: \"cite via site X; these channels direct\". --via names the",
+ "archive every clip's QR opens (a site id from transcripts/sites, or its address; '' goes back to",
+ "provenance.siteOrigin); --direct the channels whose clips link the platform's own page at the cite ('' none);",
+ "--clear removes the policy. New clips are written by it (the inserters); the clips already in the cut that",
+ "break it are `umtool check`'s clip-link-policy rows. --fix rewrites each of them that has a fix through the",
+ "window writer. With no flag, prints the policy and what breaks it. Exit 1 when a clip still breaks it.",
+].join("\n");
+
+/**
+ * `umtool link-policy …`
+ * @param {string[]} args the words after `link-policy`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function linkPolicyCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) {
+ try {
+ const { linkPolicyOf, normalizeLinkPolicy, policyBreaks, webpageReader } = await import("./linkPolicy.mjs");
+ const { sitesByOrigin } = await import("./siteDeploys.mjs");
+ const { updateLinkPolicy } = await import("./manifest.mjs");
+ const { channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs");
+ const { SITES_DIR } = await import("../paths.mjs");
+ const words = [];
+ /** @type {Map<string, string | true>} */
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--via" || a === "--direct") {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value ('' clears it)`);
+ flags.set(a, args[++i]);
+ } else if (["--clear", "--fix", "--json", "--help"].includes(a)) flags.set(a, true);
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else words.push(a);
+ }
+ if (!words[0] || flags.has("--help")) {
+ (flags.has("--help") ? out : err)(LINK_POLICY_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`);
+ let m = await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const notes = [];
+ if (flags.has("--clear") || flags.has("--via") || flags.has("--direct")) {
+ if (flags.has("--clear") && (flags.has("--via") || flags.has("--direct"))) throw new CliError("--clear takes no --via or --direct");
+ let next = null;
+ if (!flags.has("--clear")) {
+ const was = linkPolicyOf(m) ?? { via: null, direct: [] };
+ let via = was.via;
+ if (flags.has("--via")) {
+ const v = String(flags.get("--via")).trim();
+ if (!v) via = null;
+ else if (/^https?:\/\//i.test(v)) via = v;
+ else {
+ const hit = [...sitesByOrigin(sitesDir ?? SITES_DIR)].find(([, s]) => s.siteId === v);
+ if (!hit) throw new CliError(`--via ${v}: no site of that id has a siteUrl (transcripts/sites/<id>/site.json); pass its address`);
+ via = hit[0];
+ }
+ }
+ const direct = flags.has("--direct") ? String(flags.get("--direct")) : was.direct;
+ next = normalizeLinkPolicy({ via, direct });
+ }
+ const res = await withEditNotes(project, () => updateLinkPolicy(project.dir, next));
+ notes.push(res.result.changed ? "link policy saved" : "link policy unchanged");
+ m = await readManifest(project.dir);
+ }
+ const shadowExists = await hasShadowChannels(project.dir);
+ const read = webpageReader(channelsDirFor(project.dir, m, { shadowExists }));
+ const web = new Map();
+ for (const e of m.timeline ?? []) {
+ if (e?.type === "clip") web.set(e.id, await read(e.channel ?? m.provenance?.channelSlug, e.video));
+ }
+ let breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null });
+ const fixed = [];
+ if (flags.has("--fix")) {
+ for (const b of breaks) {
+ if (!b.fix) continue;
+ await withEditNotes(project, () => updateClip(project.dir, b.clip, { citeUrl: b.fix }));
+ fixed.push({ clip: b.clip, from: b.current, to: b.fix });
+ }
+ if (fixed.length) {
+ m = await readManifest(project.dir);
+ breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null });
+ }
+ }
+ const policy = linkPolicyOf(m);
+ if (flags.has("--json")) {
+ out(JSON.stringify({ ok: breaks.length === 0, project: project.id, policy, breaks, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2));
+ return breaks.length ? 1 : 0;
+ }
+ for (const n of notes) out(n);
+ for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`);
+ if (!policy) out(`${project.id}: no link policy (every QR opens provenance.siteOrigin, or the clip's own citeUrl)`);
+ else out(`${project.id}: cite via ${policy.via ?? `provenance.siteOrigin (${m.provenance?.siteOrigin ?? "unset"})`}; direct: ${policy.direct.length ? policy.direct.join(", ") : "none"}`);
+ for (const b of breaks) out(`BREAKS ${b.clip} ${b.why}${b.fix ? `\n fix: ${b.fix}` : ""}`);
+ if (policy && !breaks.length) out("every clip's QR keeps it");
+ return breaks.length ? 1 : 0;
+ } catch (e) {
+ err(`umtool link-policy: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -58,6 +58,9 @@ import {
} from "./knobs.mjs";
import { validateNarration } from "umtool-report-to-video/narration";
import { parseMuteFrom } from "./playback.mjs";
+import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs";
+import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
+import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs";
import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
import { createSnapshot, listSnapshots } from "./snapshots.mjs";
@@ -1051,6 +1054,7 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null
* @param {{ token?: string | null, now?: string | null }} [opts]
*/
export async function addClip(dir, spec, { token = null, now = null } = {}) {
+ const webpageUrl = await policyWebpage(dir, spec);
return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m) => {
if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }");
if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id");
@@ -1072,6 +1076,8 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) {
if (quote) entry.quote = quote.slice(0, 2000);
const title = typeof spec.title === "string" ? spec.title.trim() : "";
if (title) entry.title = title.slice(0, 300);
+ // The project's link policy (linkPolicy.mjs): the QR a new clip gets is the policy's.
+ applyPolicyLink(m, entry, webpageUrl);
const stamp = now ?? new Date().toISOString();
entry.assist = {
by: "operator",
@@ -2238,14 +2244,78 @@ function clipEntry(timeline, e) {
* @param {{ token?: string | null, at?: number | null }} [opts] `at` is afterId's index
*/
export async function insertEntry(dir, afterId, spec, { token = null, at = null } = {}) {
+ const webpageUrl = await policyWebpage(dir, typeof spec === "string" ? parseClipSpec(spec) : spec);
return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m) => {
const i = afterId ? entryIndex(m.timeline, afterId, at) + 1 : 0;
const entry = entryFromSpec(m.timeline, spec);
+ // A clip's QR is the project's link policy's (linkPolicy.mjs), not a copied link that breaks it.
+ if (entry.type === "clip") applyPolicyLink(m, entry, webpageUrl);
m.timeline.splice(i, 0, entry);
return { id: entry.id, at: i, entry };
}));
}
+// ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) -----------
+
+/**
+ * The record's webpage_url when the project's link policy links `spec`'s
+ * channel direct, else null: read BEFORE the write's lock (a file read), so
+ * the inserters can write the platform link in the same write.
+ * @param {string} dir
+ * @param {{ channel?: string, video?: string } | null | undefined} spec
+ */
+async function policyWebpage(dir, spec) {
+ let m;
+ try {
+ m = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ } catch {
+ return null;
+ }
+ const policy = linkPolicyOf(m);
+ if (!policy?.direct.length || !spec || typeof spec !== "object") return null;
+ const chan = typeof spec.channel === "string" && spec.channel ? spec.channel : m.provenance?.channelSlug;
+ if (!chan || !policy.direct.includes(chan) || typeof spec.video !== "string") return null;
+ const shadowExists = await stat(path.join(dir, POLICY_SHADOW)).then((st) => st.isDirectory(), () => false);
+ const channelsDir = policyChannelsDirFor(dir, m, { shadowExists, fallback: POLICY_CHANNELS_DIR });
+ return webpageReader(channelsDir)(chan, spec.video);
+}
+
+/** Write the policy's citeUrl on a new clip: its link when the clip's breaks it; a copied one it cannot replace is dropped. */
+function applyPolicyLink(m, entry, webpageUrl) {
+ const cu = policyCiteUrl(m, entry, webpageUrl);
+ if (typeof cu === "string" && cu) entry.citeUrl = cu;
+ else if (cu === null) delete entry.citeUrl;
+}
+
+/**
+ * Set (or with null, clear) the project's link policy,
+ * `provenance.linkPolicy = { via?, direct? }` (linkPolicy.mjs
+ * normalizeLinkPolicy: `via` an origin, `direct` channel slugs). A no-op
+ * writes nothing. The clips already in the cut are not rewritten here: what
+ * breaks the policy is the check's `clip-link-policy` rows, each with its fix.
+ *
+ * @param {string} dir
+ * @param {unknown} policy
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ linkPolicy: { via: string | null, direct: string[] } | null, token: string | null, changed: boolean }>}
+ */
+export async function updateLinkPolicy(dir, policy, { token = null } = {}) {
+ const next = normalizeLinkPolicy(policy);
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const was = manifest.provenance?.[LINK_POLICY_KEY] ?? null;
+ const written = next ? { ...(next.via ? { via: next.via } : {}), ...(next.direct.length ? { direct: next.direct } : {}) } : null;
+ if (JSON.stringify(was) === JSON.stringify(written)) return { linkPolicy: next, token: current, changed: false };
+ if (!isObj(manifest.provenance)) manifest.provenance = {};
+ if (written) manifest.provenance[LINK_POLICY_KEY] = written;
+ else delete manifest.provenance[LINK_POLICY_KEY];
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ return { linkPolicy: next, token: nextToken, changed: true };
+ });
+}
+
// ---- sections, edited as sections (UI notes 2026-10-30, item 1) -----------
//
// Under the deck a cut's sections are its markers (sectionEdit.mjs): these
diff --git a/umtool/lib/report/ui-ops.test.mjs b/umtool/lib/report/ui-ops.test.mjs
@@ -1,5 +1,6 @@
-// Operations UI (UI notes 2026-10-30): the sites a cut's links depend on and
-// their deploys (#9).
+// Operations UI (UI notes 2026-10-30, #9 #10 #15 #18): the sites a cut's
+// links depend on and their deploys, the per-project link policy, the speaker
+// check, the render queue and a take's ETA.
//
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
@@ -147,3 +148,99 @@ test("the check: site-deploy-behind, one row per site with newer videos, its set
await p.done();
}
});
+
+// ---- #10 the link policy ----------------------------------------------------
+
+const { normalizeLinkPolicy, policyBreaks, policyCiteUrl, policyFixLabel } = await import("./linkPolicy.mjs");
+const { addClip, insertEntry, updateLinkPolicy } = await import("./manifest.mjs");
+const { linkPolicyCommand } = await import("./linksCli.mjs");
+
+test("normalizeLinkPolicy: via an origin, direct slugs sorted; nothing is no policy; a stray key refuses", () => {
+ assert.deepEqual(normalizeLinkPolicy({ via: "https://site.test/x", direct: ["b", "a", "a"] }), { via: "https://site.test", direct: ["a", "b"] });
+ assert.deepEqual(normalizeLinkPolicy({ direct: "ho, side" }), { via: null, direct: ["ho", "side"] });
+ assert.equal(normalizeLinkPolicy({}), null);
+ assert.equal(normalizeLinkPolicy(null), null);
+ assert.throws(() => normalizeLinkPolicy({ via: "ftp://x" }), /a site's http\(s\) address/);
+ assert.throws(() => normalizeLinkPolicy({ sites: [] }), /has no key "sites"/);
+ assert.throws(() => normalizeLinkPolicy({ direct: ["no spaces"] }), /channel slugs/);
+});
+
+test("policyBreaks: a direct channel's archive link, another site's link, a platform link where the policy cites via; each with its fix", () => {
+ const m = manifestOf(
+ [
+ { type: "clip", id: "e1", channel: "ember", video: "v1", start: 10, end: 20, cite: 12 },
+ { type: "clip", id: "e2", channel: "ember", video: "v2", start: 10, end: 20, citeUrl: url("ember", "v2", 10, "https://other.test") },
+ { type: "clip", id: "e3", channel: "ember", video: "v3", start: 10, end: 20, citeUrl: "https://www.youtube.com/watch?v=v3&t=10s" },
+ { type: "clip", id: "h1", channel: "ho", video: "y1", start: 30, end: 40, cite: 31 },
+ { type: "clip", id: "h2", channel: "ho", video: "y2", start: 30, end: 40, citeUrl: "https://www.youtube.com/watch?v=y2&t=30s" },
+ { type: "clip", id: "h3", channel: "ho", video: "y3", start: 30, end: 40 },
+ { type: "clip", id: "s1", src: "media/own.mp4", start: 0, end: 4 },
+ ],
+ { provenance: { channelSlug: "ember", siteOrigin: SITE, linkPolicy: { direct: ["ho"] } } },
+ );
+ const web = { y1: "https://www.youtube.com/watch?v=y1", y2: "https://www.youtube.com/watch?v=y2" };
+ const b = policyBreaks(m, { webpageOf: (e) => web[e.video] ?? null });
+ assert.deepEqual(b.map((x) => [x.clip, x.want, x.fix]), [
+ ["e2", "via", url("ember", "v2", 10)],
+ ["e3", "via", url("ember", "v3", 10)],
+ ["h1", "direct", "https://www.youtube.com/watch?v=y1&t=31s"],
+ ["h3", "direct", null],
+ ]);
+ assert.match(b[0].why, /^the project's link policy cites via site\.test, but its QR opens other\.test$/);
+ assert.match(b[3].why, /^ho links direct by the project's link policy, but its QR opens site\.test — and its record names no platform page to link/);
+ assert.equal(policyFixLabel(b[0]), "Link via site.test");
+ assert.equal(policyFixLabel(b[2]), "Link its YouTube page");
+ // With no policy nothing breaks.
+ assert.deepEqual(policyBreaks({ ...m, provenance: { siteOrigin: SITE } }), []);
+});
+
+test("policyCiteUrl: a new clip of a direct channel gets its platform page; via another site gets that site; one that keeps it is left alone", () => {
+ const m = manifestOf([], { provenance: { channelSlug: "c", siteOrigin: SITE, linkPolicy: { via: "https://other.test", direct: ["ho"] } } });
+ assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9, cutStart: 6 }, "https://www.youtube.com/watch?v=y1"), "https://www.youtube.com/watch?v=y1&t=6s");
+ assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9 }, null), null);
+ assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9 }, null), url("c", "v1", 5, "https://other.test"));
+ assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9, citeUrl: url("c", "v1", 5, "https://other.test") }, null), undefined);
+});
+
+test("the inserters write the policy's link; the check's clip-link-policy rows and their one-press fix; the CLI", async () => {
+ const p = await project([
+ { id: "a", video: "v1", start: 10, end: 20, cite: 10 },
+ { id: "b", video: "v2", start: 10, end: 20, cite: 12 },
+ ]);
+ try {
+ // No policy: no rows.
+ assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0);
+ // "These channels direct": channel c links YouTube.
+ const res = await updateLinkPolicy(p.dir, { direct: ["c"] });
+ assert.equal(res.changed, true);
+ assert.deepEqual((await p.manifest()).provenance.linkPolicy, { direct: ["c"] });
+ assert.equal((await updateLinkPolicy(p.dir, { direct: ["c"] })).changed, false, "a no-op writes nothing");
+ const rows = (await p.decisions()).filter((d) => d.kind === "clip-link-policy");
+ assert.deepEqual(rows.map((d) => [d.target, d.severity]), [["a", "open"], ["b", "open"]]);
+ assert.deepEqual(rows[1].settle, { kind: "patch", clip: "b", patch: { citeUrl: "https://www.youtube.com/watch?v=v2&t=12s" }, label: "Link its YouTube page" });
+ assert.equal(rows[1].fix, "umtool window cut b --cite-url 'https://www.youtube.com/watch?v=v2&t=12s'");
+ // A new clip (the strip's selection, an insert) is written by the policy.
+ const added = await addClip(p.dir, { video: "v3", cutStart: 40, cutEnd: 44 });
+ assert.equal(added.entry.citeUrl, "https://www.youtube.com/watch?v=v3&t=40s");
+ const ins = await insertEntry(p.dir, "a", { type: "clip", video: "v1", start: 50, end: 55, citeUrl: url("c", "v1", 50) });
+ assert.equal(ins.entry.citeUrl, "https://www.youtube.com/watch?v=v1&t=50s", "a copied archive link that breaks the policy is replaced");
+ // The CLI: what breaks it, then --fix through the window writer.
+ const lines = [];
+ const code = await linkPolicyCommand(["cut"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s) });
+ assert.equal(code, 1);
+ assert.match(lines.join("\n"), /cut: cite via provenance\.siteOrigin \(https:\/\/site\.test\); direct: c/);
+ assert.match(lines.join("\n"), /BREAKS {2}a {2}c links direct/);
+ const fixed = [];
+ assert.equal(await linkPolicyCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => fixed.push(s), err: (s) => fixed.push(s) }), 0);
+ assert.match(fixed.join("\n"), /fixed a: https:\/\/site\.test\/\?v=c%2Fv1&t=10 -> https:\/\/www\.youtube\.com\/watch\?v=v1&t=10s/);
+ assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0);
+ // --via by site id; --clear.
+ assert.equal(await linkPolicyCommand(["cut", "--via", "other", "--direct", ""], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 1);
+ assert.deepEqual((await p.manifest()).provenance.linkPolicy, { via: "https://other.test" });
+ assert.equal(await linkPolicyCommand(["cut", "--via", "nope"], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 2);
+ assert.equal(await linkPolicyCommand(["cut", "--clear"], { root: p.reportsRoot, out: () => {}, err: () => {} }), 0);
+ assert.equal("linkPolicy" in (await p.manifest()).provenance, false);
+ } finally {
+ await p.done();
+ }
+});