commit 16734ac058e1931f0fc8752fe7a1e5b0c2aa1e3c
parent e1c45c6f2d337d4b22ae61f2c618ac0bd5a377f9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 05:18:26 -0500
Merge main (8d503bf3) into lane/model-log: editor/CHANGELOG.md keeps both sides; umtool/docs/cli.md and the generated docs regenerated
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
157 files changed, 6409 insertions(+), 258 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -91,6 +91,8 @@ yarn-error.log*
/export/.compose-cache/
# per-site docker build outputs (out/, .next, public/, caches) — one dir per site
/export/.export-builds/
+# remote archives' documents cached on disk (common/lib/archiveCache-server.ts)
+/export/.archive-cache/
/transcripts/index.mdb/
# homepage (hub) generated public data (regenerate with `pnpm build:homepage`)
diff --git a/AGENTS.md b/AGENTS.md
@@ -165,9 +165,15 @@ The high-value loop: point the MCP at a public instance, ask about a subject, th
fetching cheap. Clip media for a cited moment goes through the `fetch_clip` MCP tool
(→ the editor's `POST /api/media/fetch-window`, paced, cookie-aware and provenanced),
never `yt-dlp --download-sections` by hand; that command is only the fallback for a
-machine with no editor. The editor fetches only for a channel it already archives (a
-`transcripts/channels/<slug>/`), so an MCP pointed at a public site with a fresh editor
-gets a 404 `Channel "<slug>" not found` on every clip.
+machine with no editor. The editor fetches for a channel it archives (a
+`transcripts/channels/<slug>/`) — or, when the ask names a **connected archive**
+(`settings.remoteArchives`: /sites → Connected archives, `pnpm ops archives`;
+TRANSCRIPT_SITE_URL's is connected by default), for that archive's channel, which it
+registers on first need as a **remote-only** channel (config only, no `url`; inert to
+every sync, lane, cleanup and build — CHANNEL.md `remoteOnly`). `fetch_clip` over a
+`remote:` source and umtool's chain name the archive; an archive not connected still
+answers 404 `Channel "<slug>" not found`, naming the connect. A remote-only channel's
+Rumble window (a whole recording) is refused with its size until `allowWholeRecording`.
**`full: true` and "Persist source video" download the source even when a transcript or
captions exist** (`forceMedia` on `downloadOneManaged`, release 10 slice N; "Persist kept
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -39,6 +39,9 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `lastFullDownloadAt` | sync state | SYNC STATE. When a full download pass last completed (ISO time). |
| `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. |
| `excludeFromBuild` | config | Leave this channel out of every site build. |
+| `remoteOnly` | config | A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name (settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the recording's size until the ask says `allowWholeRecording`. |
+| `remoteArchive` | config | A remote-only channel's archive: the origin whose corpus.json names it. |
+| `remoteUrl` | config | A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: a remote-only channel has no `url`, so nothing syncs it. |
| `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. |
| `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. |
| `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. |
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -131,6 +131,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
| `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` |
| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
+| `archives` | archives connects a published archive as a source: {"connect": "<origin>"} reads <origin>/corpus.json once (its title, totals and channels) and saves it in settings.remoteArchives; "dryRun"? answers the probe and writes nothing; an origin connected already writes nothing. A federation hub, a cited-only site, one with no channels or one that does not answer is refused. {"remove": "<id or origin>"} drops one. Create, research and the MCP offer each connected archive; a sweep over it cites it. | `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
@@ -178,7 +179,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` |
-| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
+| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. "archive" (items only) names the CONNECTED archive the items cite (settings.remoteArchives): a channel this editor does not hold is registered as a remote-only channel of it (config only, no listing; answered in "registered"; a dry run registers nothing), and a remote-only channel's page URL comes from the archive's record. Its window on a whole-recording platform is refused with the recording's estimated size unless "allowWholeRecording": true. Another origin registers nothing. A media URL's transient 403 (googlevideo's) is asked once more after a pause before it counts toward the two-403 stop. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
| `amend-release` | amend-release rewrites the LATEST release of one changelog: {"workspace": "editor" \| "export", "release": "<its version, as you saw it>", "version": "patch" \| "minor" \| "major" (a bump of the release BEFORE it) \| "X.Y.Z", "date": "YYYY-MM-DD", "fold": true (the \[Unreleased\] bullets move into it), "commit": boolean (default false)} -- or {"uncut": true} to withdraw it, its bullets back under \[Unreleased\]. An older release is refused. A version change commits as that version's release ("Release editor 0.12.0") with the amend in the body; history is never rewritten. The same amend again changes nothing. With no editor running, `archilyzer release amend` does the same locally. | `pnpm ops amend-release --json '{"workspace":"editor","release":"0.11.1","version":"minor","commit":true}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
@@ -304,6 +305,8 @@ get saved-alternates [<slug>] lists every saved video holding two copies:
get sites lists every site: id, title, siteUrl, Pages project, audience,
listed, search, publish policy, channels, citedChannels. (`get publish`
is the status.)
+get archives lists the connected archives: id, origin, title, addedAt;
+ TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.
get workers, get auto-queue and get scheduler are /workers, the four lanes
of /operations, and /operations/sync — the payloads those pages poll.
get services is the dashboard's cookie refresh alerts: each service
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -98,7 +98,11 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs) |
| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does). | common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs) |
| `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts |
-| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts |
+| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it. | mcp/src/sources.ts |
+| `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES` | off | `1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only). | common/controller/remoteArchives.ts |
+| `ARCHIVE_CACHE_DIR` | `.archive-cache` beside EXPORT_BUILDS_DIR | Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume. | common/lib/archiveCache-server.ts |
+| `ARCHIVE_CACHE_MAX_MB` | 512 | The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped. | common/lib/archiveCache-server.ts |
+| `ARCHIVE_CACHE` | on (off under node's test runner) | `0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off. | common/lib/archiveCache-server.ts |
| `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts |
| `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts |
| `TRANSCRIPT_PLATFORM_LINKS` | off | `1` cites platform watch pages instead of the archive's own pages. | common/lib/archive/reader-fs.ts |
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -49,6 +49,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`attribution`](#attribution) | object — see below |
| [`archiveOrg`](#archiveorg) | object — see below |
| [`archives`](#archives) | object — see below |
+| [`remoteArchives`](#remotearchives) | `[]` |
| [`publish`](#publish) | object — see below |
| [`reportSchedule`](#reportschedule) | object — see below |
| [`seeder`](#seeder) | object — see below |
@@ -909,6 +910,27 @@ Default:
}
```
+## `remoteArchives`
+
+The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.
+
+#### `remoteArchives[]`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `id` | A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is free, else one made from its host. What `pnpm ops archives` removes by. |
+| `origin` | The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says. |
+| `title` | The archive's `site.title`, as its corpus.json said when it was connected. |
+| `addedAt` | When it was connected (ISO-8601). |
+
+Default:
+
+```json
+[]
+```
+
## `publish`
The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.
diff --git a/common/bin/compose-site.channelFacts.test.ts b/common/bin/compose-site.channelFacts.test.ts
@@ -0,0 +1,42 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { channelFactsOf } from "./compose-site";
+
+// corpus.json spec 6 (demo epic D1): each channel's platform and its page,
+// read from its config.
+test("channel facts: the configured platform, else the URL's; the URL only when public http(s)", async () => {
+ const root = mkdtempSync(path.join(tmpdir(), "compose-facts-"));
+ try {
+ const put = (slug: string, config: Record<string, unknown>) => {
+ mkdirSync(path.join(root, slug), { recursive: true });
+ writeFileSync(path.join(root, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", ...config }));
+ };
+ put("yt", { url: "https://www.youtube.com/@alpha" });
+ put("rum", { url: "https://rumble.com/c/beta", platform: "rumble" });
+ put("mix", {}); // a curated mix: no url, no platform
+ put("odd", { url: "file:///x" });
+ // Not a channel's page to publish (review of 9fddc3bb): a playlist, a feed
+ // with a token, a fragment, credentials. The platform is still said.
+ put("playlist", { url: "https://www.youtube.com/playlist?list=PLabc" });
+ put("feed", { url: "https://feeds.example.test/rss", platform: "youtube" });
+ put("tokenfeed", { url: "https://feeds.example.test/rss?token=s3cret", platform: "youtube" });
+ put("frag", { url: "https://www.youtube.com/@gamma#videos" });
+ put("creds", { url: "https://user:pw@www.youtube.com/@delta" });
+ const facts = await channelFactsOf({ channelsDir: root } as Parameters<typeof channelFactsOf>[0], ["yt", "rum", "mix", "odd", "missing", "playlist", "feed", "tokenfeed", "frag", "creds"]);
+ assert.deepEqual(facts, {
+ yt: { platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ rum: { platform: "rumble", url: "https://rumble.com/c/beta" },
+ playlist: { platform: "youtube" },
+ feed: { platform: "youtube", url: "https://feeds.example.test/rss" },
+ tokenfeed: { platform: "youtube" },
+ frag: { platform: "youtube" },
+ creds: { platform: "youtube" },
+ });
+ assert.equal(JSON.stringify(facts).includes("s3cret"), false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -71,6 +71,7 @@ import {
type ArchiveManifestEntry,
} from "../lib/archiveOptions";
import { readChannelConfig } from "../controller/channels";
+import { detectPlatform } from "../lib/platform";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { builtSiteIdIn } from "../lib/builtExport";
import { publishedMemberSlugs } from "../lib/postsVisibility";
@@ -220,6 +221,42 @@ async function composeCitedSite(
// environment variable the build passes it to compose as.
export const ALLOW_MISSING_MEDIA_ENV = "REPORTS_ALLOW_MISSING_MEDIA";
+// corpus.json's per-channel `platform` and `url` (spec 6): the configured
+// platform, else the one its URL names; the URL only when it is a plain public
+// http(s) page — NO query, fragment or userinfo (publicChannelUrl): a config's
+// url may be a playlist or a single video (`?list=`, `?v=`), or a feed with a
+// token in its query, and none of that is a channel's page to publish. The
+// platform is kept either way. Read from each channel's config.json; an
+// unreadable one is simply unknown.
+/** A config url fit to publish as a channel's page: http(s), no userinfo, query or fragment; else undefined. */
+export function publicChannelUrl(raw: string): string | undefined {
+ let u: URL;
+ try {
+ u = new URL(raw);
+ } catch {
+ return undefined;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return undefined;
+ if (u.username || u.password || u.search || u.hash || raw.includes("?") || raw.includes("#")) return undefined;
+ return raw;
+}
+
+export async function channelFactsOf(
+ paths: Parameters<typeof readChannelConfig>[0],
+ slugs: readonly string[],
+): Promise<Record<string, { platform?: string; url?: string }>> {
+ const out: Record<string, { platform?: string; url?: string }> = {};
+ for (const slug of slugs) {
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ if (!config) continue;
+ const raw = typeof config.url === "string" ? config.url.trim() : "";
+ const url = publicChannelUrl(raw);
+ const platform = config.platform ?? detectPlatform(raw || undefined) ?? undefined;
+ if (platform || url) out[slug] = { ...(platform ? { platform } : {}), ...(url ? { url } : {}) };
+ }
+ return out;
+}
+
// Emit the AI-discovery surface — a small FIXED set of site-root files
// (llms.txt, corpus.json, robots.txt, sitemap.xml). These document how to
// navigate the already-served paginated shards; they never enumerate per-video
@@ -290,6 +327,11 @@ export async function emitAiFiles(
if (config && isWaybackPagesChannel(config)) channelKinds[slug] = "wayback-pages";
}
+ // Where each channel is (spec 6, demo epic D1): its platform and its page
+ // there, from its config — what a machine with no copy of the channel needs
+ // to fetch a cited moment's media. A channel with neither says nothing.
+ const channelFacts = await channelFactsOf(paths, descriptor.channels.map((c) => c.slug));
+
// Whether this site published a curated vocabulary. Presence of the file is
// the fact — it was written (or removed) just above, by the same rule that
// decides whether any tag means anything on this site.
@@ -306,6 +348,7 @@ export async function emitAiFiles(
private: isPrivateSite(site),
reportCount: composed.reports.length,
cited: isCitedSite(site),
+ channelFacts,
});
await writePublicFile(
path.join(paths.exportPublicDir, "corpus.json"),
diff --git a/common/bin/reports-delete.ts b/common/bin/reports-delete.ts
@@ -18,6 +18,7 @@
// refused, or a path could not be removed; 2 for usage, or no such article or
// iteration.
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
import os from "node:os";
import path from "node:path";
import type { GenerationSettings } from "../lib/generationSettings";
@@ -103,7 +104,7 @@ const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/")
// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles
// (controller/reportDraft.ts projectsRootOf, which a bin does not import).
export const projectsRootOf = (gen: Pick<GenerationSettings, "projectsRoot">): string =>
- gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles");
+ projectsRootFrom(gen.projectsRoot);
// The CLI row's options, from the flags and the settings.
export async function deleteRow(
diff --git a/common/bin/reports-import-local-runs.ts b/common/bin/reports-import-local-runs.ts
@@ -34,6 +34,7 @@
// Exit 0 when every run is importable (dry run) or imported (apply), or was
// imported before; 1 when any is refused or fails; 2 for a usage error.
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -761,7 +762,7 @@ export function defaultGenerationWriter(env: NodeJS.ProcessEnv = process.env, fe
const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p);
// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles
// (controller/reportDraft.ts projectsRootOf, which a bin does not import).
-const projectsRootOf = (gen: GenerationSettings) => (gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles"));
+const projectsRootOf = (gen: GenerationSettings) => (projectsRootFrom(gen.projectsRoot));
// The CLI row's options, from the flags and the settings.
export async function importRow(flags: { apply?: boolean; runs?: string; only?: string; "move-projects"?: boolean; generation?: string }): Promise<number> {
diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts
@@ -926,3 +926,38 @@ test("a manual-downloads channel projects no download work but keeps its transcr
"side by side, only the automatic channel's backlog counts",
);
});
+
+// --- Remote-only: on no lane (demo epic D1) --------------------------------
+//
+// A remote-only channel holds a connected archive's clip windows. Even with a
+// video dir on disk and a report that lists work, no lane draws it.
+
+test("a remote-only channel is no lane's work, whatever its report lists", async () => {
+ const paths = pendingFixture();
+ const transcribeOp = bucketLaneOperationId("transcription");
+ const downloadOp = bucketLaneOperationId("download");
+ const slug = "remote";
+ const channelDir = path.join(paths.channelsDir, slug);
+ mkdirSync(path.join(channelDir, "data", `${slug}-on-disk`), { recursive: true });
+ const config = { handling: "youtube", platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" };
+ writeFileSync(path.join(channelDir, "config.json"), JSON.stringify(config));
+ writeFileSync(
+ path.join(channelDir, "snapshot.json"),
+ JSON.stringify({
+ generatedAt: new Date().toISOString(),
+ totals: { videos: 1, downloaded: 1, transcribed: 0 },
+ buckets: { downloadedNoTranscript: [`${slug}-on-disk`] },
+ undownloadedIds: [`${slug}-listed`],
+ backfill: {
+ ...(downloadOp ? { [downloadOp]: { ids: [`${slug}-listed`] } } : {}),
+ ...(transcribeOp ? { [transcribeOp]: { ids: [`${slug}-on-disk`] } } : {}),
+ },
+ }),
+ );
+ forgetChannelMedia(slug);
+ const ch = { slug, config: config as never };
+ // Every lane there is (main's Speakers work runs inside them), not a list that can fall behind.
+ for (const lane of LANES) {
+ assert.equal(await laneTotal(lane, paths, [ch]), 0, `the ${lane} lane skips a remote-only channel`);
+ }
+});
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -3,7 +3,7 @@ import { readdir, stat } from "node:fs/promises";
import { audioFilesToRemove } from "../lib/mediaFiles";
import { audioBytesPerHour, spaceComparator } from "../lib/spaceOrder";
import type { Paths } from "../lib/paths";
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import { mapConcurrent } from "../lib/concurrency";
import { getPaths } from "../lib/paths";
import { getSettings, type SiteSettings } from "../lib/settings";
@@ -400,6 +400,9 @@ async function listChannelMeta(
return {
meta: configs
.filter(({ slug }) => !isChannelPaused(priority, slug, kind))
+ // A REMOTE-ONLY channel (demo epic D1) is on no lane at all: it holds a
+ // connected archive's clip windows and nothing a lane could work on.
+ .filter(({ config }) => !isRemoteOnlyChannel(config))
// A MANUAL-DOWNLOADS CHANNEL is not on the download lane's list at all
// (lib/manualDownloads.ts): its listing's backlog, its retries, its
// metadata scan and its chat backlog are all things nobody asked for.
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -150,7 +150,7 @@ import {
readPostAvailability,
postsAvailabilityPath,
} from "../lib/posts-server";
-import { isSocialChannel } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel } from "../lib/channelConfig";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import {
DIGESTS_MANIFEST_VERSION,
@@ -448,6 +448,12 @@ async function scanSource(
log(`Skipping channel ${ch.name}: excluded from build`);
continue;
}
+ // A remote-only channel (demo epic D1) holds an archive's clip windows,
+ // not a corpus of its own: it is in no index build.
+ if (isRemoteOnlyChannel(cfg)) {
+ log(`Skipping channel ${ch.name}: remote-only`);
+ continue;
+ }
channels.set(ch.name, cfg);
// A social channel carries posts, not videos: it has no data/ dir to walk,
// and routing it through the video scan would only ever produce noise. Its
diff --git a/common/controller/buildStats.test.ts b/common/controller/buildStats.test.ts
@@ -814,3 +814,27 @@ test("(z) no write this file caused landed outside its temp root", () => {
assert.deepEqual(outside, []);
assert.ok(fsCalls.some((c) => c.write), "the spy saw the writes");
});
+
+// demo epic D1: a remote-only channel's clip-window dirs are no corpus — in no
+// index build and no stats build.
+test("a remote-only channel is in no index and no stats build", async () => {
+ resetCorpus();
+ seedVideo("own1");
+ addCaptions("own1", "2026-07-11T12:00:00Z");
+ writeJson(path.join(paths.channelsDir, "remote-ch", "config.json"), {
+ handling: "youtube",
+ name: "Remote",
+ platform: "youtube",
+ remoteOnly: true,
+ remoteArchive: "https://stub.test",
+ downloadMode: "manual",
+ });
+ seedVideo("r1", "2026-07-11T11:00:00Z", {}, "remote-ch");
+ addCaptions("r1", "2026-07-11T12:00:00Z", "remote-ch");
+ const indexLog: string[] = [];
+ await buildIndex({ paths, onLog: (s) => indexLog.push(s) });
+ assert.ok(indexLog.some((l) => /Skipping channel remote-ch: remote-only/.test(l)), indexLog.join("\n"));
+ const { byId } = await runStats();
+ assert.ok(byId.has("own1"));
+ assert.equal(byId.has("r1"), false);
+});
diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts
@@ -63,7 +63,7 @@ import {
readVideoFiles,
} from "../lib/videoStatus";
import type { VideoStatus } from "../lib/stats";
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import { readChannelConfigFile } from "./channels";
import { inspectChannelMedia } from "../lib/channelMedia";
import {
@@ -309,6 +309,8 @@ async function scanSource(
continue;
}
if (cfg.excludeFromBuild) continue;
+ // A remote-only channel (demo epic D1) is in no build.
+ if (isRemoteOnlyChannel(cfg)) continue;
channels.set(ch.name, cfg);
// An unreadable text tier is not an empty channel (lib/channelMedia.ts):
// the readdir below would fail and every one of its stats would be removed.
diff --git a/common/controller/curatedTagsBuild.test.ts b/common/controller/curatedTagsBuild.test.ts
@@ -217,7 +217,7 @@ test("compose 1: the site publishes /tags.json and corpus.json points at it", as
const corpus = JSON.parse(
readFileSync(path.join(paths.exportPublicDir, "corpus.json"), "utf8"),
);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.tags.videoField, "curatedTags");
assert.match(corpus.tags.url, /\/tags\.json$/);
assert.match(
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -33,11 +33,20 @@ process.env.FAKE_ARGS_LOG = ARGS_LOG;
await writeFile(
BIN,
`#!/usr/bin/env node
-import { appendFileSync, writeFileSync } from "node:fs";
+import { appendFileSync, existsSync, writeFileSync } from "node:fs";
const args = process.argv.slice(2);
appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n");
const url = args[args.length - 1];
const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); };
+if (url.includes("/m403once")) {
+ // The media URL refuses the first ask of this URL only (demo epic D1).
+ const mark = process.env.FAKE_ARGS_LOG + "." + Buffer.from(url).toString("hex");
+ if (!existsSync(mark)) {
+ writeFileSync(mark, "1");
+ fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1");
+ }
+}
+if (url.includes("/m403always")) fail("[https @ 0x1] HTTP error 403 Forbidden\\nhttps://rr1.googlevideo.example/videoplayback Server returned 403 Forbidden (access denied)\\nERROR: ffmpeg exited with code 1");
if (url.includes("/403")) fail("ERROR: [download] Got error: HTTP Error 403: Forbidden");
if (url.includes("/429")) fail("ERROR: [youtube] x: HTTP Error 429: Too Many Requests");
if (url.includes("/gone")) fail("ERROR: [youtube] x: Video unavailable. This video has been removed by the uploader");
@@ -837,6 +846,31 @@ test("one clock: a window held ON the map's clock is answered from the cache", a
assert.equal(c.cuts.length, 0);
});
+// demo epic D1: a transient media 403 (googlevideo's) is asked once more after a pause.
+test("a media URL's 403 is asked once more after a pause, and then fetched", async () => {
+ const h = harness();
+ const before = await spawns();
+ const r = await go(await corpus(), [item("v1", "/m403once")], h);
+ assert.equal(r.failed.length, 0);
+ assert.equal(r.fetched.length, 1);
+ assert.equal((await spawns()) - before, 2, "one retry");
+ assert.deepEqual(h.rec.sleeps, [1000], "the pause before the retry (the run's gap here)");
+ assert.deepEqual(h.rec.backoffs, []);
+});
+
+test("a media 403 that persists fails once, counts once toward the streak; a Rumble 403 is never retried", async () => {
+ const h = harness();
+ const before = await spawns();
+ const r = await go(await corpus(), [item("v1", "/m403always"), item("v2", "/ok")], h);
+ assert.equal(r.stopped, undefined, "one failed window is not a streak");
+ assert.deepEqual(r.failed.map((f) => [f.item.id, f.class]), [["v1", "network"]]);
+ assert.equal((await spawns()) - before, 3, "v1 twice, v2 once");
+ const { isTransientMedia403 } = await import("./fetchWindows");
+ assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "youtube"), true);
+ assert.equal(isTransientMedia403("x Server returned 403 Forbidden (access denied)", "rumble"), false);
+ assert.equal(isTransientMedia403("ERROR: [download] Got error: HTTP Error 403: Forbidden", "youtube"), false);
+});
+
// lane/local-media: the job-level backstop. A local library channel's item and
// a local recording's are failed "local-media" before any URL is looked up.
test("a local media library channel and a local recording fail local-media, and the run goes on", async () => {
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -196,6 +196,21 @@ function testGapMs(): number | undefined {
return Number.isFinite(raw) && raw > 0 ? raw : undefined;
}
+// A TRANSIENT MEDIA 403 (demo epic D1): the page answered and gave a media URL,
+// and that URL refused the stream — ffmpeg's "Server returned 403 Forbidden"
+// (googlevideo above all, measured in D0: one in ten windows, fine on a manual
+// re-ask). That is the media host, not the platform turning us away and not a
+// cookie that went stale (lib/serviceCookies.ts raises no alert for it): the
+// window is asked ONCE more after a pause, before it counts toward the
+// network streak. A Rumble 403 is its Cloudflare (and a removed video answers
+// 403 too): never retried here.
+const MEDIA_403 = /Server returned 403 Forbidden|HTTP error 403 Forbidden/;
+export const MEDIA_403_RETRY_MS = 20_000;
+
+export function isTransientMedia403(message: string, platform: string): boolean {
+ return platform !== "rumble" && MEDIA_403.test(message) && !/\[Rumble/.test(message);
+}
+
export type FetchWindowsItem = {
slug: string;
id: string;
@@ -1159,6 +1174,23 @@ export async function fetchWindows({
out = await attempt({ ...stored, why: "rate-limited" });
}
+ // A TRANSIENT MEDIA 403 (the header above FetchWindowsItem): once more,
+ // after a pause, before it counts.
+ if (!out.ok && !usedStored && classOf(out.e) === "network" && isTransientMedia403((out.e as Error).message, platform)) {
+ const pause = gapMs ?? testGapMs() ?? Math.max(gap, MEDIA_403_RETRY_MS);
+ log(` ${label}: the media URL answered 403 — asking once more in ${Math.round(pause / 1000)}s.`);
+ await deps.sleep(pause, signal);
+ const after = interrupted();
+ if (after) {
+ fail(item, "network", (out.e as Error).message);
+ done += 1;
+ progress();
+ stop(after, i + 1);
+ break;
+ }
+ out = await attempt(null);
+ }
+
if (out.ok) {
networkStreak = 0;
// THE SYNC CHECK on what the fetch produced (the header): a desynced
diff --git a/common/controller/remoteArchives.test.ts b/common/controller/remoteArchives.test.ts
@@ -0,0 +1,122 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectRemoteArchive, removeRemoteArchive, RemoteArchiveError, type RemoteArchiveDeps } from "./remoteArchives";
+import type { RemoteArchive } from "../lib/remoteArchives";
+import type { FetchLike } from "../lib/remoteArchives-server";
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T00:00:00.000Z",
+ site: { id: "stubalyzer", title: "Stubalyzer" },
+ totals: { channels: 1, videos: 3 },
+ channels: [{ slug: "alpha", name: "Alpha", videoCount: 3 }],
+};
+
+function world(initial: RemoteArchive[] = [], env: Record<string, string> = {}) {
+ let stored: unknown = initial;
+ const writes: RemoteArchive[][] = [];
+ const asked: string[] = [];
+ const fetch: FetchLike = async (url) => {
+ asked.push(url);
+ return new Response(JSON.stringify(CORPUS), { status: 200 });
+ };
+ const deps: RemoteArchiveDeps = {
+ stored: () => stored,
+ save: async (next) => {
+ writes.push(next);
+ stored = next;
+ },
+ fetch,
+ now: () => new Date("2026-11-11T12:00:00Z"),
+ env,
+ // No real DNS in a test: every name is a public address unless a test says.
+ lookup: async () => [{ address: "93.184.216.34" }],
+ };
+ return { deps, writes, asked, stored: () => stored };
+}
+
+test("connect: probed once, saved with the archive's own id and title", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test/" }, w.deps);
+ assert.deepEqual(w.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(r.already, false);
+ assert.deepEqual(w.writes, [[{ id: "stubalyzer", origin: "https://stub.test", title: "Stubalyzer", addedAt: "2026-11-11T12:00:00.000Z" }]]);
+ // Again: nothing written, it says so.
+ const again = await connectRemoteArchive({ origin: "stub.test" }, w.deps);
+ assert.equal(again.already, true);
+ assert.equal(w.writes.length, 1);
+});
+
+test("a dry run reads and writes nothing", async () => {
+ const w = world();
+ const r = await connectRemoteArchive({ origin: "https://stub.test", dryRun: true }, w.deps);
+ assert.equal(r.already, null);
+ assert.equal(r.probe.totals.videos, 3);
+ assert.equal(w.writes.length, 0);
+});
+
+test("the environment's archive can be connected (stored) but not removed", async () => {
+ const w = world([], { TRANSCRIPT_SITE_URL: "https://stub.test" });
+ await assert.rejects(removeRemoteArchive("https://stub.test", w.deps), (e: unknown) => e instanceof RemoteArchiveError && /TRANSCRIPT_SITE_URL/.test((e as Error).message));
+ const r = await connectRemoteArchive({ origin: "https://stub.test" }, w.deps);
+ assert.equal(r.already, false);
+ assert.equal(w.writes.length, 1);
+});
+
+test("remove by id or by origin; an unknown one is refused, naming what is connected", async () => {
+ const a: RemoteArchive = { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" };
+ const b: RemoteArchive = { id: "b", origin: "https://b.test", title: "B", addedAt: "2026-11-11T00:00:00.000Z" };
+ const w = world([a, b]);
+ assert.deepEqual(await removeRemoteArchive("a", w.deps), a);
+ assert.deepEqual(await removeRemoteArchive("https://b.test/", w.deps), b);
+ assert.deepEqual(w.stored(), []);
+ await assert.rejects(removeRemoteArchive("zzz", w.deps), /no connected archive "zzz" — connected: none/);
+});
+
+// demo epic D1 review, blocker 2c: this machine or its network is not connected unless decided here.
+test("a local or private archive host is refused before anything is asked of it; the operator's own word allows it", async () => {
+ for (const origin of ["http://127.0.0.1:4100", "http://[::1]:8080", "http://localhost:3000", "http://nas.local", "http://10.0.0.7", "http://192.168.1.20/archive"]) {
+ const w = world();
+ await assert.rejects(connectRemoteArchive({ origin }, w.deps), /an archive on this machine or its network is connected only when/, origin);
+ assert.deepEqual(w.asked, [], `${origin}: nothing asked`);
+ }
+ // A public name that resolves to a private address.
+ const sneaky = world();
+ sneaky.deps.lookup = async () => [{ address: "93.184.216.34" }, { address: "192.168.1.9" }];
+ await assert.rejects(connectRemoteArchive({ origin: "https://rebind.example" }, sneaky.deps), /a name for a local or private address \(192\.168\.1\.9\)/);
+ assert.deepEqual(sneaky.asked, []);
+ // Decided on this machine: the editor's environment, TRANSCRIPT_SITE_URL, or settings.json.
+ const allowed = world([], { ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1" });
+ assert.equal((await connectRemoteArchive({ origin: "http://127.0.0.1:4100" }, allowed.deps)).already, false);
+ const fromEnv = world([], { TRANSCRIPT_SITE_URL: "http://127.0.0.1:4100" });
+ assert.equal((await connectRemoteArchive({ origin: "http://127.0.0.1:4100" }, fromEnv.deps)).already, false);
+ const stored = world([{ id: "lan", origin: "http://10.0.0.7", title: "LAN", addedAt: "2026-11-11T00:00:00.000Z" }]);
+ assert.equal((await connectRemoteArchive({ origin: "http://10.0.0.7" }, stored.deps)).already, true);
+});
+
+// demo epic D1 re-review, must-fix 2: the address forms a URL may spell, and a redirect at connect.
+test("a local address in any spelling is refused at connect, nothing asked; allowed only by the operator's own word", async () => {
+ for (const origin of ["http://[::ffff:7f00:1]", "http://[::ffff:127.0.0.1]:3001", "http://[::1]", "http://0.0.0.0:3001", "http://2130706433", "http://0x7f000001", "http://0177.0.0.1", "http://127.1"]) {
+ const w = world();
+ await assert.rejects(connectRemoteArchive({ origin }, w.deps), /an archive on this machine or its network is connected only when/, origin);
+ assert.deepEqual(w.asked, [], `${origin}: nothing asked`);
+ assert.equal(w.writes.length, 0, `${origin}: nothing written`);
+ const allowed = world([], { ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1" });
+ assert.equal((await connectRemoteArchive({ origin }, allowed.deps)).already, false, `${origin}: allowed when decided here`);
+ }
+});
+
+test("a public archive that redirects its corpus.json to a private address is not followed and not connected", async () => {
+ for (const location of ["http://127.0.0.1:3001/corpus.json", "http://[::ffff:7f00:1]/corpus.json", "http://169.254.169.254/latest/meta-data/", "http://2130706433/corpus.json", "//localhost:3001/corpus.json"]) {
+ const w = world();
+ const asked: string[] = [];
+ w.deps.fetch = async (url) => {
+ asked.push(url);
+ return new Response(null, { status: 302, headers: { location } });
+ };
+ await assert.rejects(connectRemoteArchive({ origin: "https://stub.test" }, w.deps), /an archive's documents are read from its own origin only/, location);
+ assert.deepEqual(asked, ["https://stub.test/corpus.json"], `${location}: the redirect is not followed`);
+ assert.equal(w.writes.length, 0, `${location}: nothing written`);
+ }
+});
diff --git a/common/controller/remoteArchives.ts b/common/controller/remoteArchives.ts
@@ -0,0 +1,76 @@
+// CONNECT AN ARCHIVE (demo epic D1, item 1): the one place
+// settings.remoteArchives is changed. The editor's ops action
+// (`pnpm ops archives`) and its /sites form call these; umtool's Source chip
+// asks the editor's action — so every connect is probed the same way and
+// written by the editor's one settings writer.
+//
+// connect probe `<origin>/corpus.json` (lib/remoteArchives-server.ts) and,
+// unless `dryRun`, add { id, origin, title, addedAt }. An origin
+// already connected answers what it is and writes nothing.
+// remove drop the entry by id (or origin). The TRANSCRIPT_SITE_URL entry
+// is not stored, so it cannot be removed here: it goes with the
+// variable.
+
+import { connectedArchives, findConnectedArchive, freeArchiveId, sanitizeRemoteArchives, archiveOriginOf, type ConnectedArchive, type RemoteArchive } from "../lib/remoteArchives";
+import { ArchiveProbeError, probeArchive, type ArchiveProbe, type FetchLike } from "../lib/remoteArchives-server";
+import { privateHostRefusal, type LookupAll } from "../lib/archiveHosts-server";
+
+export type RemoteArchiveDeps = {
+ // The stored list (settings.remoteArchives).
+ stored: () => unknown;
+ // Write the whole list (the editor's saveSettings({ remoteArchives })).
+ save: (next: RemoteArchive[]) => Promise<void>;
+ fetch?: FetchLike;
+ now?: () => Date;
+ env?: Record<string, string | undefined>;
+ // The host check's name lookup (archiveHosts-server.ts); a test's fake.
+ lookup?: LookupAll;
+};
+
+export type ConnectResult = {
+ probe: ArchiveProbe;
+ archive: ConnectedArchive;
+ // true: it was connected already (nothing written); false: added now; null: a dry run.
+ already: boolean | null;
+};
+
+export async function connectRemoteArchive(o: { origin: string; dryRun?: boolean }, deps: RemoteArchiveDeps): Promise<ConnectResult> {
+ // This machine or its network: refused before anything is asked of it,
+ // unless decided here (archiveHosts-server.ts).
+ const origin = archiveOriginOf(o.origin);
+ const env = deps.env ?? process.env;
+ if (origin && env.ARCHILYZER_ALLOW_PRIVATE_ARCHIVES !== "1" && !findConnectedArchive(connectedArchives(deps.stored(), env), origin)) {
+ const refused = await privateHostRefusal(origin, { lookup: deps.lookup });
+ if (refused) throw new ArchiveProbeError(refused);
+ }
+ const probe = await probeArchive(o.origin, { fetch: deps.fetch });
+ const list = connectedArchives(deps.stored(), deps.env);
+ const have = findConnectedArchive(list, probe.origin);
+ if (have && !have.fromEnv) return { probe, archive: have, already: true };
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const archive: RemoteArchive = {
+ id: freeArchiveId(probe.origin, stored.map((a) => a.id), probe.siteId),
+ origin: probe.origin,
+ title: probe.title,
+ addedAt: (deps.now?.() ?? new Date()).toISOString(),
+ };
+ if (o.dryRun) return { probe, archive, already: null };
+ await deps.save([...stored, archive]);
+ return { probe, archive, already: false };
+}
+
+export class RemoteArchiveError extends Error {}
+
+/** Remove a stored archive by id or origin; answers the removed entry. */
+export async function removeRemoteArchive(which: string, deps: RemoteArchiveDeps): Promise<RemoteArchive> {
+ const stored = sanitizeRemoteArchives(deps.stored());
+ const origin = archiveOriginOf(which);
+ const hit = stored.find((a) => a.id === which || (origin !== null && a.origin === origin));
+ if (!hit) {
+ const env = connectedArchives(deps.stored(), deps.env).find((a) => a.fromEnv && (a.id === which || a.origin === origin));
+ if (env) throw new RemoteArchiveError(`${env.origin} comes from TRANSCRIPT_SITE_URL, not settings.json — unset the variable to stop offering it`);
+ throw new RemoteArchiveError(`no connected archive "${which}" — connected: ${stored.map((a) => a.id).join(", ") || "none"}`);
+ }
+ await deps.save(stored.filter((a) => a !== hit));
+ return hit;
+}
diff --git a/common/controller/remoteOnlyChannel.test.ts b/common/controller/remoteOnlyChannel.test.ts
@@ -0,0 +1,162 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ WHOLE_RECORDING_REFUSED,
+ archiveRecordOf,
+ archiveRecordPageHref,
+ ensureRemoteOnlyChannel,
+ estimateRecordingBytes,
+ wholeRecordingRefusal,
+} from "./remoteOnlyChannel";
+import type { GetJson } from "../lib/remoteArchives-server";
+import { detectPlatform } from "../lib/detectPlatform.mjs";
+import type { Paths } from "../lib/paths";
+import { isRemoteOnlyChannel, remoteOnlyRefusal } from "../lib/channelConfig";
+
+// demo epic D1 item 5: a channel cited from a connected archive is registered
+// remote-only on first need — config only — and its records come from the archive.
+
+const ORIGIN = "https://stub.test";
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ site: { id: "stub", title: "Stub" },
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 2, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: { transcripts: `${ORIGIN}/transcripts/alpha/manifest.json` } },
+ { slug: "rum", name: "Rum", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rum/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/alpha/manifest.json`]: { pageCount: 1, slugToPage: { a1: 0, a2: 0 } },
+ [`${ORIGIN}/transcripts/alpha/page-0000.json`]: [
+ { id: "a1", title: "One", duration: 600, webpageUrl: "https://www.youtube.com/watch?v=a1" },
+ { id: "a2", title: "Two", duration: 7980, webpageUrl: "https://www.youtube.com/watch?v=a2" },
+ ],
+};
+
+function fake(): GetJson & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ if (!(url in DOCS)) throw new Error(`${url} answered HTTP 404`);
+ return DOCS[url];
+ }) as GetJson & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+function pool(): { paths: Paths; root: string } {
+ const root = mkdtempSync(path.join(tmpdir(), "remote-only-"));
+ return { root, paths: { channelsDir: path.join(root, "channels") } as unknown as Paths };
+}
+
+test("first need registers config only: remote-only, manual, the platform, no url", async () => {
+ const { paths, root } = pool();
+ try {
+ const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() });
+ assert.equal(r.registered, true);
+ const onDisk = JSON.parse(readFileSync(path.join(paths.channelsDir, "alpha", "config.json"), "utf8"));
+ assert.deepEqual(onDisk, {
+ name: "Alpha",
+ handling: "youtube",
+ platform: "youtube",
+ remoteOnly: true,
+ remoteArchive: ORIGIN,
+ remoteUrl: "https://www.youtube.com/@alpha",
+ downloadMode: "manual",
+ });
+ assert.equal("url" in onDisk, false, "nothing that syncs by url can sync it");
+ assert.equal(isRemoteOnlyChannel(r.config), true);
+ assert.match(remoteOnlyRefusal("alpha", r.config)!, /alpha is a remote-only channel of https:\/\/stub\.test/);
+ // Second need: the one on disk, nothing read.
+ const f = fake();
+ const again = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: f });
+ assert.equal(again.registered, false);
+ assert.deepEqual(f.asked, []);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("a channel held here is never touched; one the archive does not list is refused, nothing written", async () => {
+ const { paths, root } = pool();
+ try {
+ mkdirSync(path.join(paths.channelsDir, "alpha"), { recursive: true });
+ writeFileSync(path.join(paths.channelsDir, "alpha", "config.json"), JSON.stringify({ name: "Mine", handling: "youtube", url: "https://www.youtube.com/@alpha" }));
+ const r = await ensureRemoteOnlyChannel(paths, "alpha", { origin: ORIGIN }, { getJson: fake() });
+ assert.equal(r.registered, false);
+ assert.equal(r.config.name, "Mine");
+ assert.equal(isRemoteOnlyChannel(r.config), false);
+ await assert.rejects(ensureRemoteOnlyChannel(paths, "nope", { origin: ORIGIN }, { getJson: fake() }), /lists no channel "nope"/);
+ assert.throws(() => readFileSync(path.join(paths.channelsDir, "nope", "config.json")));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("a cited record's page URL and length come from the archive", async () => {
+ const f = fake();
+ assert.deepEqual(await archiveRecordOf(ORIGIN, "alpha", "a2", { getJson: f }), {
+ webpageUrl: "https://www.youtube.com/watch?v=a2",
+ duration: 7980,
+ title: "Two",
+ });
+ assert.deepEqual(f.asked, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/alpha/manifest.json`, `${ORIGIN}/transcripts/alpha/page-0000.json`]);
+ assert.equal(await archiveRecordOf(ORIGIN, "alpha", "zz", { getJson: fake() }), null);
+ assert.equal(await archiveRecordOf(ORIGIN, "rum", "r1", { getJson: fake() }), null);
+});
+
+test("a whole recording is refused with its length and estimated size, and the key that allows it", () => {
+ assert.equal(estimateRecordingBytes(3600, 720), 1_125_000_000);
+ assert.equal(estimateRecordingBytes(3600, 360), 360_000_000);
+ const msg = wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1", duration: 7980 });
+ assert.ok(msg.startsWith(WHOLE_RECORDING_REFUSED));
+ assert.match(msg, /Rumble windows are cut from the WHOLE recording/);
+ assert.match(msg, /rum\/r1 is 2:13:00 long, about 2\.5 GB \(estimated\)/);
+ assert.match(msg, /"allowWholeRecording": true/);
+ assert.match(wholeRecordingRefusal({ platform: "rumble", slug: "rum", id: "r1" }), /length is not known to its archive/);
+});
+
+// demo epic D1 review, blocker 2b: an archive is read on its own origin only.
+test("a manifest the corpus names on another origin is not followed: the archive's own is read", async () => {
+ const asked: string[] = [];
+ const docs: Record<string, unknown> = {
+ "https://stub.test/corpus.json": { channels: [{ slug: "a", manifests: { transcripts: "http://192.168.1.1/admin.json" } }] },
+ "https://stub.test/transcripts/a/manifest.json": { slugToPage: { v1: 0 } },
+ "https://stub.test/transcripts/a/page-0000.json": [{ id: "v1", webpageUrl: "https://www.youtube.com/watch?v=v1" }],
+ };
+ const getJson = async (url: string) => {
+ asked.push(url);
+ if (!(url in docs)) throw new Error("404");
+ return docs[url];
+ };
+ assert.equal((await archiveRecordOf("https://stub.test", "a", "v1", { getJson }))?.webpageUrl, "https://www.youtube.com/watch?v=v1");
+ assert.equal(asked.some((u) => u.includes("192.168")), false);
+});
+
+// demo epic D1 re-check: what umtool's chain sends the editor for a record is the URL the check parsed.
+test("a record's page for an ask is the normalised href; one two parsers read differently, or off its platform, is no page", async () => {
+ const docs: Record<string, unknown> = {
+ "https://stub.test/corpus.json": { channels: [{ slug: "a" }] },
+ "https://stub.test/transcripts/a/manifest.json": { slugToPage: { ok: 0, loud: 0, slash: 0, tab: 0, dot: 0, off: 0, none: 0 } },
+ "https://stub.test/transcripts/a/page-0000.json": [
+ { id: "ok", webpageUrl: "https://www.youtube.com/watch?v=ok" },
+ { id: "loud", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=loud" },
+ { id: "slash", webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" },
+ { id: "tab", webpageUrl: "https://you\ttube.com/watch?v=x" },
+ { id: "dot", webpageUrl: "https://rumble.com\\.evil.example/v1" },
+ { id: "off", webpageUrl: "http://169.254.169.254/latest/meta-data/" },
+ { id: "none" },
+ ],
+ };
+ const getJson = async (url: string) => {
+ if (!(url in docs)) throw new Error("404");
+ return docs[url];
+ };
+ const href = (id: string) => archiveRecordPageHref("https://stub.test", "a", id, detectPlatform, { getJson });
+ assert.equal(await href("ok"), "https://www.youtube.com/watch?v=ok");
+ assert.equal(await href("loud"), "https://www.youtube.com/watch?v=loud");
+ for (const id of ["slash", "tab", "dot", "off", "none", "not-held"]) assert.equal(await href(id), null, id);
+});
diff --git a/common/controller/remoteOnlyChannel.ts b/common/controller/remoteOnlyChannel.ts
@@ -0,0 +1,180 @@
+// A REMOTE-ONLY CHANNEL, registered on first need (demo epic D1 item 5).
+//
+// A sweep over a connected archive (settings.remoteArchives) cites moments of
+// channels this editor does not hold. Its clip windows are still fetched HERE —
+// the editor's paced queues, cookie policy and provenance — so the editor needs
+// a channel to put them under. The first time a window of such a channel is
+// asked for, with the archive named, the editor registers it:
+//
+// config only (`remoteOnly: true`, `remoteArchive`, `remoteUrl`, the
+// platform, `downloadMode: "manual"`), and NO `url` — nothing that syncs a
+// channel by its url can sync this one; no listing sweep is run.
+//
+// Every place a real channel is active skips it (lib/channelConfig.ts
+// isRemoteOnlyChannel): the lanes, the sync scheduler, Sync all and every
+// pipeline action, the metadata scan, cleanup, the storage watch, index and
+// stats builds, the site writer, a research run's channel list. The channel
+// list shows it as "remote only".
+//
+// A cited recording's page URL — what a window is fetched from — comes from
+// the archive's own record (archiveRecordOf), since the editor holds no
+// metadata for it; the ask may carry it too (umtool's chain sends it).
+//
+// A WHOLE-RECORDING PLATFORM (settings.clips.wholeRecordingPlatforms, Rumble):
+// a window there is cut from the saved whole recording — for a channel this
+// editor does not archive that is a whole download nobody planned. It is
+// refused with the recording's size (wholeRecordingRefusal) until the ask says
+// `allowWholeRecording: true` (one press: umtool's chain offers it).
+
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { PLATFORM_VALUES, type Platform } from "../lib/platform";
+import { corpusUrl, manifestUrl, pageUrl } from "../lib/archive/contract";
+import { WHOLE_RECORDING_REFUSED, archiveOriginOf, recordPage, sameOrigin, type ConnectedArchive } from "../lib/remoteArchives";
+import { archiveChannelFacts, plainGetJson, type ArchiveChannelFacts, type GetJson } from "../lib/remoteArchives-server";
+import { createChannel, readChannelConfig } from "./channels";
+
+export type RemoteOnlyDeps = {
+ // One JSON document over HTTP (the cached reader, item 6); a test's fake.
+ getJson?: GetJson;
+ facts?: (origin: string, slug: string, opts: { getJson?: GetJson }) => Promise<ArchiveChannelFacts>;
+};
+
+export class RemoteOnlyChannelError extends Error {}
+
+/** The config a remote-only channel is registered with, from its archive's facts. */
+export function remoteOnlyConfigOf(archive: Pick<ConnectedArchive, "origin">, facts: ArchiveChannelFacts): ChannelConfig {
+ const platform = facts.platform && (PLATFORM_VALUES as readonly string[]).includes(facts.platform) ? (facts.platform as Platform) : undefined;
+ return {
+ name: facts.name,
+ handling: platform === "youtube" ? "youtube" : "transcribe",
+ ...(platform ? { platform } : {}),
+ remoteOnly: true,
+ remoteArchive: archive.origin,
+ ...(facts.url ? { remoteUrl: facts.url } : {}),
+ downloadMode: "manual",
+ } as ChannelConfig;
+}
+
+/**
+ * The channel's config: the one on disk, or — when there is none — a
+ * remote-only channel registered now from `archive`'s corpus.json. A channel
+ * the archive does not list is refused.
+ */
+export async function ensureRemoteOnlyChannel(
+ paths: Paths,
+ slug: string,
+ archive: Pick<ConnectedArchive, "origin">,
+ deps: RemoteOnlyDeps = {},
+): Promise<{ config: ChannelConfig; registered: boolean }> {
+ const have = await readChannelConfig(paths, slug);
+ if (have) return { config: have, registered: false };
+ const facts = await (deps.facts ?? archiveChannelFacts)(archive.origin, slug, { getJson: deps.getJson });
+ const config = remoteOnlyConfigOf(archive, facts);
+ try {
+ await createChannel(paths, slug, config);
+ } catch (e) {
+ // Two asks at once: the other registered it first.
+ const again = await readChannelConfig(paths, slug);
+ if (again) return { config: again, registered: false };
+ throw e;
+ }
+ return { config: (await readChannelConfig(paths, slug)) ?? config, registered: true };
+}
+
+export type ArchiveRecord = { webpageUrl?: string; duration?: number; platform?: string; title?: string };
+
+/**
+ * A recording's own record in its archive: the transcripts manifest's page for
+ * the id, then the record whose id matches — its page URL and duration. Null
+ * when the archive does not hold it. At most three documents, in order.
+ */
+export async function archiveRecordOf(origin: string, slug: string, id: string, deps: { getJson?: GetJson } = {}): Promise<ArchiveRecord | null> {
+ const base = archiveOriginOf(origin);
+ if (!base) return null;
+ const getJson = deps.getJson ?? plainGetJson();
+ const corpus = (await getJson(corpusUrl(base)).catch(() => null)) as { channels?: { slug?: string; manifests?: { transcripts?: string } }[] } | null;
+ const entry = corpus?.channels?.find((c) => c?.slug === slug);
+ // Only the archive's own origin is read (an archive is untrusted input): a
+ // manifest its corpus.json names elsewhere is not followed.
+ const named = entry?.manifests?.transcripts;
+ const at = typeof named === "string" && sameOrigin(named, base) ? named : manifestUrl("transcripts", slug, base);
+ const manifest = (await getJson(at).catch(() => null)) as { slugToPage?: Record<string, number> } | null;
+ const page = manifest?.slugToPage?.[id] ?? manifest?.slugToPage?.[`${slug}/${id}`];
+ if (typeof page !== "number") return null;
+ const records = (await getJson(pageUrl("transcripts", slug, page, base)).catch(() => null)) as Record<string, unknown>[] | null;
+ const r = (Array.isArray(records) ? records : []).find((x) => x?.id === id);
+ if (!r) return null;
+ const s = (k: string) => (typeof r[k] === "string" && (r[k] as string).trim() ? (r[k] as string).trim() : undefined);
+ const duration = typeof r.duration === "number" && Number.isFinite(r.duration) ? r.duration : undefined;
+ const webpageUrl = s("webpageUrl");
+ return {
+ ...(webpageUrl && /^https?:\/\//i.test(webpageUrl) ? { webpageUrl } : {}),
+ ...(duration !== undefined ? { duration } : {}),
+ ...(s("platform") ? { platform: s("platform") } : {}),
+ ...(s("title") ? { title: s("title") } : {}),
+ };
+}
+
+/**
+ * The page URL an ask for a window carries for a recording of `origin`'s
+ * channel: its archive record's, JUDGED AND NORMALISED (lib/remoteArchives.ts
+ * recordPage) — the URL the check parsed, written back — or null when the
+ * archive holds no record, names no page, or names one that is refused. Never
+ * the record's own string (umtool's chain sends this to the editor, which
+ * judges it again).
+ */
+export async function archiveRecordPageHref(
+ origin: string,
+ slug: string,
+ id: string,
+ detect: (u: string) => string | null,
+ deps: { getJson?: GetJson } = {},
+): Promise<string | null> {
+ const record = await archiveRecordOf(origin, slug, id, deps).catch(() => null);
+ if (!record?.webpageUrl) return null;
+ const page = recordPage(record.webpageUrl, null, detect);
+ return "refused" in page ? null : page.href;
+}
+
+// A whole recording's size, ESTIMATED from its length: what the saved-video
+// store's copy weighs at about this height. Approximate on purpose (no request
+// is made to learn it): video of this kind runs ~0.8 Mb/s at 360p up to ~5 Mb/s
+// at 1080p, audio included.
+const MBPS_BY_HEIGHT: [number, number][] = [
+ [360, 0.8],
+ [480, 1.2],
+ [720, 2.5],
+ [1080, 5],
+];
+
+export function estimateRecordingBytes(durationSec: number, maxHeight = 720): number {
+ const mbps = (MBPS_BY_HEIGHT.find(([h]) => maxHeight <= h) ?? MBPS_BY_HEIGHT[MBPS_BY_HEIGHT.length - 1])[1];
+ return Math.round((durationSec * mbps * 1e6) / 8);
+}
+
+const clock = (s: number) => {
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = Math.floor(s % 60);
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+};
+const gb = (bytes: number) => (bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1e6))} MB`);
+
+export { WHOLE_RECORDING_REFUSED };
+
+/**
+ * The refusal of a remote-only channel's window on a whole-recording platform:
+ * the recording's length and estimated size, and the one key that fetches it.
+ */
+export function wholeRecordingRefusal(o: { platform: string; slug: string; id: string; duration?: number; maxHeight?: number }): string {
+ const name = o.platform.charAt(0).toUpperCase() + o.platform.slice(1);
+ const size =
+ o.duration !== undefined
+ ? `${o.slug}/${o.id} is ${clock(o.duration)} long, about ${gb(estimateRecordingBytes(o.duration, o.maxHeight))} (estimated)`
+ : `${o.slug}/${o.id}'s length is not known to its archive`;
+ return (
+ `${WHOLE_RECORDING_REFUSED} ${name} windows are cut from the WHOLE recording, and ${o.slug} is a remote-only channel: ` +
+ `${size}. Send "allowWholeRecording": true to download it whole (once; its windows are cut from it).`
+ );
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -62,6 +62,9 @@
import { modelLogged } from "./jobModelLog";
import os from "node:os";
+import { projectsRootFrom } from "../lib/projectsRoot.mjs";
+import { originOfHandle } from "../lib/remoteArchives";
+import { isRemoteOnlyChannel } from "../lib/channelConfig";
import path from "node:path";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import type { JobProgress } from "../jobs/registry";
@@ -75,6 +78,7 @@ import { webTools } from "../lib/web/tools";
import {
copyIteration,
createIteration,
+ lineageSource,
readIteration,
readIterationFile,
reportSourceOf,
@@ -501,7 +505,7 @@ export function expandHome(p: string): string {
}
export function projectsRootOf(gen: GenerationSettings): string {
- return gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles");
+ return projectsRootFrom(gen.projectsRoot);
}
// The model a task runs on: the asked one, else the route's.
@@ -555,7 +559,10 @@ export type ReportDraftDeps = {
// The editor's channels, as a research run lists them.
async function editorChannelsOf(paths: Paths): Promise<EditorChannel[]> {
- return (await listChannelConfigs(paths)).map(({ slug, config }) => {
+ // A remote-only channel (demo epic D1) is no channel of the editor's own —
+ // it holds an archive's clip windows — so a research run never lists it, or
+ // imports into it.
+ return (await listChannelConfigs(paths)).filter(({ config }) => !isRemoteOnlyChannel(config)).map(({ slug, config }) => {
const c = config as Record<string, unknown>;
const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined);
const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling"));
@@ -572,15 +579,28 @@ async function channelsOfReport(article: string, n: number, paths: Paths): Promi
return [...new Set(Object.values(cites).map((c) => c.channel).filter((c): c is string => !!c))];
}
-// The corpus and the origin the run cites on.
+// The origin a run over a named corpus cites on (demo epic D1 item 3): a
+// published archive's own origin — its moments are its pages — unless
+// settings.generation.citationOrigin is set, which overrides; a hub (whose
+// members each have their own) or a local dir, the citation origin or the
+// project's site, as before.
+export function citationOriginFor(source: string, gen: Pick<GenerationSettings, "citationOrigin">): string {
+ return gen.citationOrigin || originOfHandle(source) || PROJECT_URL;
+}
+
+// The corpus and the origin the run cites on. `inherited`: the corpus the
+// iteration's lineage read (lineageSource) — a revision, a media draft or a
+// refresh of a sweep over an archive reads that archive, not a local build.
export async function resolveCorpus(
body: Pick<ReportDraftBody, "source" | "build">,
channels: string[],
paths: Pick<Paths, "exportBuildsDir" | "sitesDir">,
gen: GenerationSettings,
+ inherited?: string | null,
): Promise<{ source: string; origin: string; build?: string }> {
const fallback = gen.citationOrigin || PROJECT_URL;
- if (body.source) return { source: body.source, origin: fallback };
+ const named = body.source ?? (body.build ? undefined : (inherited ?? undefined));
+ if (named) return { source: named, origin: citationOriginFor(named, gen) };
const b = await pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) });
return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build };
}
@@ -674,7 +694,9 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
})
: null;
const warnings: string[] = [];
- if (cont && !body.source) {
+ // A continuation of a research run over an archive reads that archive
+ // (the run inherits it: lineageSource), so no local build is asked for.
+ if (cont && !body.source && !(await lineageSource(body.article, cont.research.n, paths).catch(() => null))) {
// The sweep reads a composed build: one must hold the widened channels
// (a channel on no site is in none until the operator puts it on one
// and builds it), and an acquisition after the build is not in it.
@@ -716,7 +738,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
model,
parent: cont.research.n,
question: cont.question,
- scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) },
+ scope: { channels: cont.channels, ...(body.source ? { source: body.source } : {}), ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) },
},
paths,
)
@@ -729,7 +751,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
kind: kindOf(body.task),
model,
...(body.task === "sweep" || body.task === "research"
- ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } }
+ ? { question: body.question, scope: { ...(body.source ? { source: body.source } : {}), ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } }
: { parent: body.iteration!, feedback: body.feedback }),
},
paths,
@@ -795,7 +817,7 @@ async function runReportDraft(
let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
let result: TaskResult | null = null;
try {
- const where = await resolveCorpus(body, channels, paths, gen);
+ const where = await resolveCorpus(body, channels, paths, gen, await lineageSource(body.article, n, paths).catch(() => null));
onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`);
corpus = await deps.corpusTools(where.source);
const disk = paths.channelsDir;
diff --git a/common/controller/reportDraftSource.test.ts b/common/controller/reportDraftSource.test.ts
@@ -0,0 +1,41 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { citationOriginFor, projectsRootOf, resolveCorpus } from "./reportDraft";
+import { defaultProjectsRoot } from "../lib/projectsRoot.mjs";
+import { defaults } from "../lib/settingsSchema";
+import { PROJECT_URL } from "../lib/project";
+
+// demo epic D1 item 3: a sweep over a published archive cites that archive.
+const gen = (over: Record<string, unknown> = {}) => ({ ...defaults().generation, ...over });
+const paths = { exportBuildsDir: "/nonexistent/builds", sitesDir: "/nonexistent/sites" };
+
+test("a remote source's citations are on its own origin; citationOrigin overrides only when set", () => {
+ assert.equal(citationOriginFor("remote:https://stub.test/", gen()), "https://stub.test");
+ assert.equal(citationOriginFor("remote:https://stub.test", gen({ citationOrigin: "https://mirror.test" })), "https://mirror.test");
+ // A hub's members each have their own origin; a local dir has none: as before.
+ assert.equal(citationOriginFor("hub:https://hub.test", gen()), PROJECT_URL);
+ assert.equal(citationOriginFor("local:/x", gen()), PROJECT_URL);
+});
+
+test("the corpus: the body's source, else the lineage's, before any local build", async () => {
+ assert.deepEqual(await resolveCorpus({ source: "remote:https://stub.test" }, ["alpha"], paths, gen()), { source: "remote:https://stub.test", origin: "https://stub.test" });
+ // A revision with no source of its own reads (and cites) what its sweep read.
+ assert.deepEqual(await resolveCorpus({}, ["alpha"], paths, gen(), "remote:https://stub.test"), { source: "remote:https://stub.test", origin: "https://stub.test" });
+ // A named build wins over the inherited source; with none on disk it is refused as before.
+ await assert.rejects(resolveCorpus({ build: "mine" }, ["alpha"], paths, gen(), "remote:https://stub.test"));
+ await assert.rejects(resolveCorpus({}, ["alpha"], paths, gen(), null));
+});
+
+test("projectsRoot blank: <REPORTS_DIR>/articles when set (a container's volume), else ~/reports/articles", () => {
+ assert.equal(defaultProjectsRoot({ REPORTS_DIR: "/data/reports" }), "/data/reports/articles");
+ assert.match(defaultProjectsRoot({}), /\/reports\/articles$/);
+ const saved = process.env.REPORTS_DIR;
+ process.env.REPORTS_DIR = "/data/reports";
+ try {
+ assert.equal(projectsRootOf(gen()), "/data/reports/articles");
+ assert.equal(projectsRootOf(gen({ projectsRoot: "/elsewhere" })), "/elsewhere");
+ } finally {
+ if (saved === undefined) delete process.env.REPORTS_DIR;
+ else process.env.REPORTS_DIR = saved;
+ }
+});
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -47,6 +47,7 @@ import { readAllPosts } from "../lib/posts-server";
import {
createIteration,
currentIteration,
+ lineageSource,
listIterations,
readIteration,
readIterationFile,
@@ -69,6 +70,7 @@ import { jobOfPaths } from "./researchRuns";
import {
REPORT_DRAFT_JOB_KIND,
REPORT_DRAFT_RESULT_MARKER,
+ citationOriginFor,
llmConfigOf,
type ReportDraftBody,
type ReportDraftDeps,
@@ -401,13 +403,16 @@ async function runRefreshJob(
const hooks: RefreshHooks = {
...fetchHooksOf(deps),
openCorpus: async (channels, prefer) => {
- const b = body.source ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths);
- const source = body.source ?? (b ? `local:${b.dir}` : null);
+ // A refresh of a sweep over a published archive reads (and cites) that
+ // archive (demo epic D1): the source named, else the lineage's.
+ const named = body.source ?? (body.build ? null : await lineageSource(body.article, n, paths).catch(() => null));
+ const b = named ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths);
+ const source = named ?? (b ? `local:${b.dir}` : null);
if (!source) throw new Error(`no composed build holds ${channels.join(", ")} — publish build the site that carries them`);
const missing = b ? channels.filter((c) => !b.channels.includes(c)) : [];
if (missing.length) onLog(`the build ${b!.build} does not hold ${missing.join(", ")}: those are not searched`);
await holder.swap(await deps.corpusTools(source));
- const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : fallback;
+ const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : citationOriginFor(source, gen);
return { source, origin, ...(b ? { build: b.build } : {}) };
},
recordOf: async (channel, id) => {
diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts
@@ -1,3 +1,4 @@
+import { isRemoteOnlyChannel } from "../lib/channelConfig";
import { getPaths, type Paths } from "../lib/paths";
import { withJsonFileLock } from "../lib/jsonFile-server";
import {
@@ -212,6 +213,9 @@ export async function runStorageWatchPass(
const pauseCauses = new Map<string, AutoPauseCause>();
for (const { slug, config } of configs) {
+ // A remote-only channel (demo epic D1) has no media drive to watch and no
+ // lane a pause would hold.
+ if (isRemoteOnlyChannel(config)) continue;
const wasAutoPaused = Boolean(model.channels[slug]?.autoPaused);
// ONE TIER PER CHANNEL (release 17): the drive its MEDIA is on —
// `mediaDir`, or on a channel not yet migrated off the retired
diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts
@@ -287,3 +287,10 @@ test("nextEligibleAfterFailure: the backoff only grows with the jitter", () => {
assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 0), 30 * 60_000);
assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 1), Math.ceil(30 * 60_000 * 1.25));
});
+
+test("a remote-only channel never syncs, even with a url, and the console says so (demo epic D1)", () => {
+ const channels = [channel("own", 1 * DAY), channel("remote", 1 * DAY, { remoteOnly: true, remoteArchive: "https://stub.test" })];
+ assert.deepEqual(due(channels).due, ["own"]);
+ const view = buildScheduleView({ channels, scheduler: scheduler(), state: emptySchedulerState(), now: NOW, priority: NO_MODEL });
+ assert.deepEqual(view.map((v) => [v.slug, v.autoSyncEligible]), [["own", true], ["remote", false]]);
+});
diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts
@@ -1,4 +1,4 @@
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, type ChannelConfig } from "../lib/channelConfig";
import type { SyncSchedulerSettings } from "../lib/settings";
import {
type ChannelPriority,
@@ -141,6 +141,8 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult {
for (const { slug, config } of channels) {
if (!config.url) continue; // not auto-sync material; no noise in the log
+ // A remote-only channel (demo epic D1) never syncs: it has no listing.
+ if (isRemoteOnlyChannel(config)) continue;
// ONE SKIP. `excludeFromSync` is gone (S5); the document's `sync` tier is
// what it became, and the migration turned each of the 15 channels that
// carried the flag into `overrides: {sync: "paused"}`. Silent `continue` —
@@ -280,6 +282,7 @@ export function buildScheduleView(input: {
autoSyncEligible:
scheduler.enabled &&
!!config.url &&
+ !isRemoteOnlyChannel(config) &&
!isChannelPaused(priority, slug, "sync") &&
interval > 0,
intervalMinutes: interval,
diff --git a/common/lib/archive/contract.test.ts b/common/lib/archive/contract.test.ts
@@ -164,7 +164,7 @@ test("shipsPwa: the site flag, or hub mode", () => {
test("CONTRACT is frozen where it is published", () => {
// These are on the wire. A change here is a change to every deployed archive's
// machine contract, so it belongs in a slice that says so, not in a refactor.
- assert.equal(CONTRACT.corpusSpec, 5);
+ assert.equal(CONTRACT.corpusSpec, 6);
assert.equal(CONTRACT.siteDescriptor, 1);
assert.equal(CONTRACT.manifest, 3);
assert.equal(CONTRACT.transcriptsManifest, 1);
diff --git a/common/lib/archive/contract.ts b/common/lib/archive/contract.ts
@@ -33,8 +33,10 @@ export const CONTRACT = {
// /corpus.json's own `spec`. `generator` is deliberately unversioned; see the
// note in lib/corpus.ts for why a credit line did not bump the spec. 5: a
// site may publish reports (`reports`), and a CITED site (`site.scope:
- // "cited"`) publishes only them — no channels, no shards.
- corpusSpec: 5,
+ // "cited"`) publishes only them — no channels, no shards. 6: each channel
+ // names its `platform` and its `url` on that platform (demo epic D1), so a
+ // client with no local copy of the channel can fetch its recordings' media.
+ corpusSpec: 6,
// /site.json's `contract` (siteDescriptor.ts).
siteDescriptor: 1,
// The four manifest versions (manifest.ts). Each is the version field of one
diff --git a/common/lib/archive/reader-fs.ts b/common/lib/archive/reader-fs.ts
@@ -43,6 +43,7 @@ import {
PageCache,
PromiseMap,
buildDuplicateIndex,
+ channelPlace,
buildStatsIndex,
buildVideoIndex,
coerceReportIndex,
@@ -295,6 +296,7 @@ export class LocalSource implements ArchiveReader {
name: c.name ?? c.slug,
videoCount: c.videoCount,
groupId: c.groupId,
+ ...channelPlace(c),
}));
}
} catch {
diff --git a/common/lib/archive/reader.test.ts b/common/lib/archive/reader.test.ts
@@ -452,3 +452,37 @@ test("PageCache coalesces concurrent callers and drops a rejection", async () =>
await assert.rejects(() => cache.take("bad", boom));
assert.equal(fails, 2);
});
+
+test("spec 6: a channel's platform and page ride on its ref; an older corpus.json is read as before", async () => {
+ const a = makeArchive({
+ [`${ORIGIN}/corpus.json`]: {
+ ...CORPUS,
+ spec: 6,
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 3, platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ { slug: "beta", name: "Beta", videoCount: 1, platform: "", url: "javascript:alert(1)" },
+ ],
+ },
+ });
+ const restore = installFetch(a);
+ try {
+ const channels = await new RemoteSource(ORIGIN).listChannels();
+ assert.equal(channels[0].platform, "youtube");
+ assert.equal(channels[0].url, "https://www.youtube.com/@alpha");
+ // Junk is not carried.
+ assert.equal("platform" in channels[1], false);
+ assert.equal("url" in channels[1], false);
+ } finally {
+ restore();
+ }
+ // spec 3 (the CORPUS fixture): no platform, no url, nothing else changes.
+ const old = fullArchive();
+ const restoreOld = installFetch(old);
+ try {
+ const [alpha] = await new RemoteSource(ORIGIN).listChannels();
+ assert.equal(alpha.slug, "alpha");
+ assert.equal("platform" in alpha, false);
+ } finally {
+ restoreOld();
+ }
+});
diff --git a/common/lib/archive/reader.ts b/common/lib/archive/reader.ts
@@ -73,6 +73,10 @@ export type ChannelRef = {
siteId?: string;
siteTitle?: string;
siteUrl?: string;
+ // Spec 6 (corpus.json): the channel's platform and its page there, when the
+ // archive names them.
+ platform?: string;
+ url?: string;
};
// The site's channel-group definitions, as read from summaries/manifest.json —
@@ -492,7 +496,18 @@ export type CorpusJsonChannel = {
name?: string;
videoCount?: number;
groupId?: string;
+ // Spec 6.
+ platform?: string;
+ url?: string;
};
+
+// A corpus.json channel's spec-6 facts as a ChannelRef carries them: each
+// only when it is a non-empty string.
+export function channelPlace(c: CorpusJsonChannel): { platform?: string; url?: string } {
+ const platform = typeof c.platform === "string" && c.platform.trim() ? c.platform.trim() : undefined;
+ const url = typeof c.url === "string" && /^https?:\/\//i.test(c.url.trim()) ? c.url.trim() : undefined;
+ return { ...(platform ? { platform } : {}), ...(url ? { url } : {}) };
+}
export type SiteCorpusJson = {
channels?: CorpusJsonChannel[];
// The composed site's own declared public origin — the deployed archilyzer
@@ -677,7 +692,13 @@ export class RemoteSource implements ArchiveReader {
// `budgetBytes` lets a hub divide one memory ceiling across its members
// instead of granting each member the full budget (N members × 48 MB is not a
// budget, it's N budgets).
- constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes()) {
+ // The fetch every read goes through: the global one by default (a browser,
+ // a test that stubs it), the disk cache on a server (demo epic D1:
+ // common/lib/archiveCache-server.ts, passed by mcp/src/sources.ts).
+ private fetchImpl: typeof fetch;
+
+ constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes(), opts: { fetch?: typeof fetch } = {}) {
+ this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
this.base = baseUrl.replace(/\/+$/, "");
this.label = `remote:${this.base}`;
this.subsPages = new PageCache<SubsDetail[]>(budgetBytes);
@@ -864,7 +885,7 @@ export class RemoteSource implements ArchiveReader {
p: string,
kind?: string,
): Promise<{ value: T; bytes: number }> {
- const res = await fetch(`${this.base}${p}`);
+ const res = await this.fetchImpl(`${this.base}${p}`);
if (!res.ok) {
throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText);
}
@@ -953,7 +974,7 @@ export class RemoteSource implements ArchiveReader {
slug: string,
): Promise<ChannelDigestsManifest | null> {
const p = manifestUrl("digests", slug);
- const res = await fetch(`${this.base}${p}`);
+ const res = await this.fetchImpl(`${this.base}${p}`);
if (res.status === 404) return null;
if (!res.ok) {
throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText);
@@ -989,6 +1010,7 @@ export class RemoteSource implements ArchiveReader {
videoCount: c.videoCount,
groupId: c.groupId,
siteUrl: this.base,
+ ...channelPlace(c),
}));
}
diff --git a/common/lib/archiveCache-server.test.ts b/common/lib/archiveCache-server.test.ts
@@ -0,0 +1,200 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { ArchiveDiskCache, archiveCacheEnabled } from "./archiveCache-server";
+import type { FetchLike } from "./remoteArchives-server";
+import { RemoteSource } from "./archive/reader";
+
+// demo epic D1 item 6: a remote archive's documents on disk, by build; one
+// request at a time, paced. A fake archive only.
+
+const ORIGIN = "https://stub.test";
+
+function archive() {
+ const docs = new Map<string, { body: unknown; etag: string }>();
+ const put = (p: string, body: unknown, etag: string) => docs.set(`${ORIGIN}${p}`, { body, etag });
+ const asked: { url: string; ifNoneMatch?: string }[] = [];
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const fetch: FetchLike = async (url, init) => {
+ const ifNoneMatch = init?.headers?.["if-none-match"];
+ asked.push({ url, ...(ifNoneMatch ? { ifNoneMatch } : {}) });
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((r) => setTimeout(r, 5));
+ inFlight -= 1;
+ const d = docs.get(url);
+ if (!d) return new Response("nope", { status: 404 });
+ if (ifNoneMatch === d.etag) return new Response(null, { status: 304 });
+ return new Response(JSON.stringify(d.body), { status: 200, headers: { etag: d.etag } });
+ };
+ return { put, asked, fetch, maxInFlight: () => maxInFlight };
+}
+
+function cacheOn(a: ReturnType<typeof archive>, clock: { t: number }, sleeps: number[] = []) {
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ const cache = new ArchiveDiskCache({
+ dir,
+ fetch: a.fetch,
+ now: () => clock.t,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ clock.t += ms;
+ },
+ gapMs: 250,
+ corpusTtlMs: 60_000,
+ });
+ return { cache, dir };
+}
+
+test("a shard read twice under one build is read from the network once", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"');
+ const clock = { t: 1_000_000 };
+ const { cache, dir } = cacheOn(a, clock);
+ try {
+ const url = `${ORIGIN}/transcripts/alpha/page-0000.json`;
+ assert.deepEqual(await (await cache.fetch(url)).json(), [{ id: "a1" }]);
+ assert.deepEqual(a.asked.map((x) => x.url), [url, `${ORIGIN}/corpus.json`]);
+ // A second process (a new cache on the same dir) reads it from disk too: one corpus check, no shard.
+ const again = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ const res = await again.fetch(url);
+ assert.equal(res.headers.get("x-archive-cache"), "disk");
+ assert.deepEqual(await res.json(), [{ id: "a1" }]);
+ assert.deepEqual(a.asked.slice(2).map((x) => x.url), [], "corpus.json within its TTL is the disk's too");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a new build: the shard is asked conditionally, a 304 keeps the bytes, a change replaces them", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"');
+ const clock = { t: 1_000_000 };
+ const { cache, dir } = cacheOn(a, clock);
+ try {
+ const url = `${ORIGIN}/transcripts/alpha/page-0000.json`;
+ await cache.fetch(url);
+ // The archive is rebuilt; the corpus check is due.
+ a.put("/corpus.json", { generatedAt: "g2" }, '"c2"');
+ clock.t += 61_000;
+ const fresh = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ const before = a.asked.length;
+ assert.deepEqual(await (await fresh.fetch(url)).json(), [{ id: "a1" }]);
+ const asked = a.asked.slice(before);
+ assert.deepEqual(asked, [
+ { url: `${ORIGIN}/corpus.json`, ifNoneMatch: '"c1"' },
+ { url, ifNoneMatch: '"p1"' },
+ ]);
+ assert.equal(fresh.stats.notModified, 1);
+ // Unchanged since: the disk again, nothing asked.
+ const n = a.asked.length;
+ await fresh.fetch(url);
+ assert.equal(a.asked.length, n);
+ // The page changed in a third build: replaced.
+ a.put("/corpus.json", { generatedAt: "g3" }, '"c3"');
+ a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }, { id: "a2" }], '"p2"');
+ clock.t += 61_000;
+ const third = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 });
+ assert.deepEqual(await (await third.fetch(url)).json(), [{ id: "a1" }, { id: "a2" }]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("one request at a time, the gap between them; an archive that does not answer is served from disk", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ for (let i = 0; i < 4; i++) a.put(`/transcripts/alpha/page-000${i}.json`, [{ id: `a${i}` }], `"p${i}"`);
+ const clock = { t: 1_000_000 };
+ const sleeps: number[] = [];
+ const { cache, dir } = cacheOn(a, clock, sleeps);
+ try {
+ // Through the reader, as a sweep reads: its 8-wide page window is serialized here.
+ const reader = new RemoteSource(ORIGIN, undefined, { fetch: cache.fetch as unknown as typeof fetch });
+ await Promise.all([0, 1, 2, 3].map((i) => reader.transcriptPage({ key: "alpha", slug: "alpha", name: "alpha" }, i)));
+ assert.equal(a.maxInFlight(), 1, "never two at once");
+ assert.ok(sleeps.length >= 4 && sleeps.every((ms) => ms > 0 && ms <= 250), JSON.stringify(sleeps));
+ // The host goes away: what is on disk still answers (a new process, past the corpus TTL).
+ clock.t += 120_000;
+ const down: FetchLike = async () => {
+ throw new Error("ECONNREFUSED");
+ };
+ const offline = new ArchiveDiskCache({ dir, fetch: down, now: () => clock.t, sleep: async () => {} });
+ assert.deepEqual(await (await offline.fetch(`${ORIGIN}/transcripts/alpha/page-0002.json`)).json(), [{ id: "a2" }]);
+ await assert.rejects(offline.fetch(`${ORIGIN}/transcripts/alpha/page-0009.json`), /ECONNREFUSED/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("past the size cap the least recently used documents go", async () => {
+ const a = archive();
+ a.put("/corpus.json", { generatedAt: "g1" }, '"c1"');
+ a.put("/a.json", "x".repeat(400), '"a"');
+ a.put("/b.json", "y".repeat(400), '"b"');
+ const clock = { t: 1_000_000 };
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ try {
+ const cache = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, maxBytes: 600 });
+ await cache.fetch(`${ORIGIN}/a.json`);
+ clock.t += 1000;
+ await cache.fetch(`${ORIGIN}/b.json`);
+ await cache.prune();
+ const n = a.asked.length;
+ await cache.fetch(`${ORIGIN}/b.json`);
+ assert.equal(a.asked.length, n, "the newest is kept");
+ await cache.fetch(`${ORIGIN}/a.json`);
+ assert.equal(a.asked.length, n + 1, "the oldest was dropped");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("on by default on a server; off under node's test runner and with ARCHIVE_CACHE=0", () => {
+ assert.equal(archiveCacheEnabled({}), true);
+ assert.equal(archiveCacheEnabled({ ARCHIVE_CACHE: "0" }), false);
+ assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8" }), false);
+ assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8", ARCHIVE_CACHE: "1" }), true);
+});
+
+// demo epic D1 review follow-up: no archive document past 32 MB is read or kept.
+test("a document over the bound is refused: by its Content-Length, or as it streams; nothing is kept", async () => {
+ const { MAX_ARCHIVE_DOCUMENT_BYTES, OversizeError, readBounded, probeArchive } = await import("./remoteArchives-server");
+ const declared = new Response("{}", { headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(readBounded(declared, "https://stub.test/a.json"), (e: unknown) => e instanceof OversizeError && /is over 32 MB/.test((e as Error).message));
+ // No length said: counted as it streams, refused at the bound (a small one here).
+ const streamed = new Response(new ReadableStream({ start(c) { for (let i = 0; i < 10; i++) c.enqueue(new Uint8Array(100)); c.close(); } }));
+ await assert.rejects(readBounded(streamed, "https://stub.test/b.json", 500), OversizeError);
+ assert.equal(await readBounded(new Response('{"ok":1}'), "https://stub.test/c.json"), '{"ok":1}');
+ // The probe says so, and the cache keeps nothing.
+ const big: FetchLike = async () => new Response("{}", { status: 200, headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } });
+ await assert.rejects(probeArchive("https://stub.test", { fetch: big }), /is over 32 MB/);
+ const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-"));
+ try {
+ const cache = new ArchiveDiskCache({ dir, fetch: big, sleep: async () => {} });
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError);
+ await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError, "nothing was kept to answer from");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("the cache's cap is 512 MB unless ARCHIVE_CACHE_MAX_MB says otherwise", async () => {
+ const { ARCHIVE_CACHE_DEFAULT_MB } = await import("./archiveCache-server");
+ assert.equal(ARCHIVE_CACHE_DEFAULT_MB, 512);
+ const saved = process.env.ARCHIVE_CACHE_MAX_MB;
+ delete process.env.ARCHIVE_CACHE_MAX_MB;
+ try {
+ assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 512 * 1024 * 1024);
+ process.env.ARCHIVE_CACHE_MAX_MB = "64";
+ assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 64 * 1024 * 1024);
+ } finally {
+ if (saved === undefined) delete process.env.ARCHIVE_CACHE_MAX_MB;
+ else process.env.ARCHIVE_CACHE_MAX_MB = saved;
+ }
+});
diff --git a/common/lib/archiveCache-server.ts b/common/lib/archiveCache-server.ts
@@ -0,0 +1,307 @@
+// REMOTE ARCHIVE READS, CACHED ON DISK (demo epic D1 item 6).
+//
+// A sweep over a published archive reads its shards — transcript pages of up
+// to 8 MB each — and D0 measured every sweep downloading them again: the
+// readers kept them in memory only, for the life of one process. This is the
+// fetch every server-side reader of a remote archive goes through (the MCP's
+// RemoteSource — so the editor's sweeps and umtool's research — the editor's
+// remote-only registration and umtool's chain): a GET of an archive's JSON is
+// answered from disk while the archive's BUILD has not changed.
+//
+// WHAT "NOT CHANGED" MEANS. A published archive is a static build; its
+// `/corpus.json` `generatedAt` names the build. Every document is kept with
+// the generation it was read under and its ETag (and Last-Modified):
+//
+// corpus.json answered from disk for CORPUS_TTL_MS after it was last
+// checked; then asked again CONDITIONALLY (If-None-Match /
+// If-Modified-Since) — a 304 is a few hundred bytes.
+// anything else answered from disk while its generation is the archive's
+// current one; under a new build it is asked again
+// conditionally, and a 304 keeps the bytes (a shard that did
+// not change between two builds is not downloaded twice).
+//
+// When the archive does not answer, a document on disk is served as it is
+// (a cached read beats a failed sweep); only a 200 is ever kept.
+//
+// ONE REQUEST AT A TIME, PACED. Every network request this process makes
+// through the cache waits for the one before it to end, then for GAP_MS more
+// — a sweep's page reads never burst an archive's host. The disk answers are
+// not paced.
+//
+// WHERE. ARCHIVE_CACHE_DIR, else `.archive-cache` beside the export builds
+// (EXPORT_BUILDS_DIR's parent: /data/builds in a container — the builds
+// volume both the editor and umtool mount — export/ on a checkout). Bounded:
+// past ARCHIVE_CACHE_MAX_MB (default 512: the host's disk is nearly full) the least recently used documents
+// are dropped. Never transcripts/ (it is the corpus), never /tmp (it is RAM).
+
+import { createHash } from "node:crypto";
+import { mkdir, readdir, readFile, rm, stat, utimes } from "node:fs/promises";
+import path from "node:path";
+import { getPaths } from "./paths";
+import { writeFileAtomic } from "./atomicFile.mjs";
+import { OffOriginError, fetchOnOrigin, plainGetJson, readBounded, type FetchLike, type GetJson } from "./remoteArchives-server";
+
+export const CORPUS_TTL_MS = 10 * 60_000;
+export const GAP_MS = 250;
+export const ARCHIVE_CACHE_DEFAULT_MB = 512;
+const DEFAULT_MAX_BYTES = ARCHIVE_CACHE_DEFAULT_MB * 1024 * 1024;
+
+type Meta = {
+ url: string;
+ etag?: string;
+ lastModified?: string;
+ // The archive's corpus generatedAt this copy was read (or revalidated) under.
+ generation?: string | null;
+ // When it was last read or revalidated over the network (ms).
+ checkedAt: number;
+ bytes: number;
+};
+
+export type ArchiveCacheOpts = {
+ dir?: string;
+ fetch?: FetchLike;
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+ gapMs?: number;
+ corpusTtlMs?: number;
+ maxBytes?: number;
+};
+
+export function archiveCacheDir(env: Record<string, string | undefined> = process.env): string {
+ const set = env.ARCHIVE_CACHE_DIR?.trim();
+ if (set) return path.resolve(/* turbopackIgnore: true */ set);
+ return path.join(path.dirname(getPaths().exportBuildsDir), ".archive-cache");
+}
+
+const isCorpus = (url: string) => /\/corpus\.json$/.test(new URL(url).pathname);
+
+type Init = { signal?: AbortSignal; headers?: Record<string, string>; method?: string };
+
+export class ArchiveDiskCache {
+ readonly dir: string;
+ private doFetch: FetchLike;
+ private now: () => number;
+ private sleep: (ms: number) => Promise<void>;
+ private gapMs: number;
+ private corpusTtlMs: number;
+ readonly maxBytes: number;
+ // One network request at a time: each waits on this.
+ private line: Promise<void> = Promise.resolve();
+ private lastEnd = 0;
+ // base (origin[/path]) -> the generation its corpus.json last said.
+ private generations = new Map<string, string | null>();
+ private bases = new Set<string>();
+ private writes = 0;
+ // Counters, for the tests and a log line.
+ readonly stats = { network: 0, disk: 0, notModified: 0 };
+
+ constructor(opts: ArchiveCacheOpts = {}) {
+ this.dir = opts.dir ?? archiveCacheDir();
+ // The global fetch, looked up per call (a test that stubs it is obeyed).
+ this.doFetch = opts.fetch ?? (((u: string, i?: Init) => fetch(u, i)) as unknown as FetchLike);
+ this.now = opts.now ?? Date.now;
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ this.gapMs = opts.gapMs ?? GAP_MS;
+ this.corpusTtlMs = opts.corpusTtlMs ?? CORPUS_TTL_MS;
+ const mb = Number(process.env.ARCHIVE_CACHE_MAX_MB);
+ this.maxBytes = opts.maxBytes ?? (Number.isFinite(mb) && mb > 0 ? mb * 1024 * 1024 : DEFAULT_MAX_BYTES);
+ }
+
+ private fileOf(url: string): string {
+ const h = createHash("sha256").update(url).digest("hex");
+ return path.join(this.dir, h.slice(0, 2), h);
+ }
+
+ private async readMeta(file: string): Promise<Meta | null> {
+ try {
+ return JSON.parse(await readFile(`${file}.meta.json`, "utf8")) as Meta;
+ } catch {
+ return null;
+ }
+ }
+
+ // The archive base a URL belongs to: a base whose corpus.json was read
+ // (an archive served under a path), else its origin.
+ private baseOf(url: string): string {
+ const u = new URL(url);
+ const s = `${u.protocol}//${u.host}${u.pathname}`;
+ let best = `${u.protocol}//${u.host}`;
+ for (const b of this.bases) if (s.startsWith(`${b}/`) && b.length > best.length) best = b;
+ return best;
+ }
+
+ /** The archive's current build, by its corpus.json (read through this cache); undefined when it cannot be told. */
+ private async generationOf(base: string): Promise<string | null | undefined> {
+ if (!this.generations.has(base)) {
+ const res = await this.fetch(`${base}/corpus.json`).catch(() => null);
+ if (!res?.ok) return undefined;
+ }
+ return this.generations.get(base);
+ }
+
+ /** Run `fn` as the only network request in flight, after the gap. */
+ private paced<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.line.then(async () => {
+ const wait = this.lastEnd + this.gapMs - this.now();
+ if (this.lastEnd > 0 && wait > 0) await this.sleep(wait);
+ try {
+ return await fn();
+ } finally {
+ this.lastEnd = this.now();
+ }
+ });
+ this.line = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+ }
+
+ private respond(body: string, meta: Meta, from: "disk" | "network"): Response {
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "application/json", "x-archive-cache": from, ...(meta.etag ? { etag: meta.etag } : {}) },
+ });
+ }
+
+ private async keep(file: string, body: string, meta: Meta): Promise<void> {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFileAtomic(file, body);
+ await writeFileAtomic(`${file}.meta.json`, JSON.stringify(meta));
+ if (++this.writes % 20 === 1) await this.prune().catch(() => {});
+ }
+
+ /** A fetch: a GET of an http(s) URL goes through the cache; anything else straight on. */
+ fetch = async (input: string | URL | Request, init?: Init): Promise<Response> => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
+ if (method !== "GET" || !/^https?:\/\//i.test(url)) return this.doFetch(url, init);
+ const file = this.fileOf(url);
+ const meta = await this.readMeta(file);
+ const corpus = isCorpus(url);
+ const base = corpus ? url.replace(/\/corpus\.json$/, "") : this.baseOf(url);
+ let generation: string | null | undefined;
+ if (meta) {
+ if (corpus) {
+ if (this.now() - meta.checkedAt < this.corpusTtlMs) return this.fromDisk(file, meta, base, true);
+ } else {
+ generation = await this.generationOf(base);
+ if (generation !== undefined && generation !== null && meta.generation === generation) return this.fromDisk(file, meta, base, false);
+ }
+ }
+ const headers: Record<string, string> = { accept: "application/json" };
+ if (meta?.etag) headers["if-none-match"] = meta.etag;
+ if (meta?.lastModified) headers["if-modified-since"] = meta.lastModified;
+ let res: Response;
+ try {
+ // On the archive's own origin only: a redirect elsewhere is refused (fetchOnOrigin).
+ res = await this.paced(() => fetchOnOrigin(this.doFetch, url, { ...(init?.signal ? { signal: init.signal } : {}), headers }));
+ } catch (e) {
+ // An off-origin redirect is a refusal, never an outage: nothing on disk answers it.
+ if (e instanceof OffOriginError) throw e;
+ // The archive did not answer: what is on disk is the answer.
+ if (meta) return this.fromDisk(file, meta, base, corpus);
+ throw e;
+ }
+ this.stats.network += 1;
+ if (res.status === 304 && meta) {
+ this.stats.notModified += 1;
+ const g = corpus ? undefined : (generation ?? (await this.generationOf(base)));
+ const next: Meta = { ...meta, checkedAt: this.now(), ...(corpus ? {} : { generation: g ?? meta.generation ?? null }) };
+ await writeFileAtomic(`${file}.meta.json`, JSON.stringify(next)).catch(() => {});
+ return this.fromDisk(file, next, base, corpus, true);
+ }
+ if (!res.ok) {
+ if (meta && res.status >= 500) return this.fromDisk(file, meta, base, corpus);
+ return res;
+ }
+ // Bounded: a document past MAX_ARCHIVE_DOCUMENT_BYTES is refused, never kept.
+ const body = await readBounded(res, url);
+ if (corpus) this.noteCorpus(base, body);
+ const next: Meta = {
+ url,
+ ...(res.headers.get("etag") ? { etag: res.headers.get("etag")! } : {}),
+ ...(res.headers.get("last-modified") ? { lastModified: res.headers.get("last-modified")! } : {}),
+ generation: corpus ? (this.generations.get(base) ?? null) : (generation ?? (await this.generationOf(base)) ?? null),
+ checkedAt: this.now(),
+ bytes: body.length,
+ };
+ await this.keep(file, body, next).catch(() => {});
+ return this.respond(body, next, "network");
+ };
+
+ private noteCorpus(base: string, body: string): void {
+ this.bases.add(base);
+ try {
+ const gen = (JSON.parse(body) as { generatedAt?: unknown }).generatedAt;
+ this.generations.set(base, typeof gen === "string" && gen ? gen : null);
+ } catch {
+ this.generations.set(base, null);
+ }
+ }
+
+ private async fromDisk(file: string, meta: Meta, base: string, corpus: boolean, counted = false): Promise<Response> {
+ const body = await readFile(file, "utf8");
+ if (corpus) this.noteCorpus(base, body);
+ if (!counted) this.stats.disk += 1;
+ // Recently used: the prune drops the oldest first.
+ const t = new Date(this.now());
+ await utimes(file, t, t).catch(() => {});
+ return this.respond(body, meta, "disk");
+ }
+
+ /** Drop the least recently used documents past the size cap. */
+ async prune(): Promise<void> {
+ const files: { file: string; bytes: number; at: number }[] = [];
+ for (const sub of await readdir(this.dir).catch(() => [] as string[])) {
+ const d = path.join(this.dir, sub);
+ for (const name of await readdir(d).catch(() => [] as string[])) {
+ if (name.endsWith(".meta.json") || name.includes(".tmp-")) continue;
+ const st = await stat(path.join(d, name)).catch(() => null);
+ if (st?.isFile()) files.push({ file: path.join(d, name), bytes: st.size, at: st.mtimeMs });
+ }
+ }
+ let total = files.reduce((n, f) => n + f.bytes, 0);
+ if (total <= this.maxBytes) return;
+ files.sort((a, b) => a.at - b.at);
+ for (const f of files) {
+ if (total <= this.maxBytes) break;
+ await rm(f.file, { force: true });
+ await rm(`${f.file}.meta.json`, { force: true });
+ total -= f.bytes;
+ }
+ }
+}
+
+// One cache per directory per process (every route bundle shares it), so
+// "one request at a time" holds across every reader in the process.
+const g = globalThis as { __archiveDiskCaches?: Map<string, ArchiveDiskCache> };
+const caches = (g.__archiveDiskCaches ??= new Map());
+
+/**
+ * Whether the server-side readers use the disk cache: yes, unless
+ * ARCHIVE_CACHE=0 — or the process is a unit test under node's runner
+ * (NODE_TEST_CONTEXT), whose fakes must never meet another test's cached
+ * bytes; such a test builds its own ArchiveDiskCache on a temp dir.
+ */
+export function archiveCacheEnabled(env: Record<string, string | undefined> = process.env): boolean {
+ if (env.ARCHIVE_CACHE === "0") return false;
+ if (env.ARCHIVE_CACHE === "1") return true;
+ return !env.NODE_TEST_CONTEXT;
+}
+
+/** This process's disk cache of archive documents (ARCHIVE_CACHE_DIR, else the default). */
+export function archiveCache(): ArchiveDiskCache {
+ const dir = archiveCacheDir();
+ let c = caches.get(dir);
+ if (!c) {
+ c = new ArchiveDiskCache({ dir });
+ caches.set(dir, c);
+ }
+ return c;
+}
+
+/** The archive documents' reader for the editor's registration and umtool's chain: through the disk cache. */
+export function cachedArchiveGetJson(): GetJson {
+ return archiveCacheEnabled() ? plainGetJson(archiveCache().fetch as unknown as FetchLike) : plainGetJson();
+}
diff --git a/common/lib/archiveHosts-server.test.ts b/common/lib/archiveHosts-server.test.ts
@@ -0,0 +1,112 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { isPrivateAddress, privateHostRefusal } from "./archiveHosts-server";
+
+// demo epic D1 review, blocker 2c: an archive host on this machine or its network.
+
+test("private addresses: loopback, private, link-local, CGNAT, unspecified, IPv6 local, v4-mapped", () => {
+ for (const a of ["127.0.0.1", "10.1.2.3", "172.20.0.1", "192.168.0.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fd00::1", "fe80::1", "::ffff:127.0.0.1", "[::1]"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of ["93.184.216.34", "172.32.0.1", "2606:4700::1", "8.8.8.8"]) assert.equal(isPrivateAddress(a), false, a);
+});
+
+test("an IPv6 address carrying a private IPv4 is private, in the spelling the URL parser writes (re-review, must-fix 2)", () => {
+ // What `new URL("http://[::ffff:127.0.0.1]")` makes of its host.
+ assert.equal(new URL("http://[::ffff:127.0.0.1]/").hostname, "[::ffff:7f00:1]");
+ for (const a of [
+ "[::ffff:7f00:1]", // 127.0.0.1
+ "[::ffff:a00:1]", // 10.0.0.1
+ "[::ffff:a9fe:a9fe]", // 169.254.169.254
+ "::ffff:c0a8:1", // 192.168.0.1
+ "0:0:0:0:0:ffff:7f00:1",
+ "::ffff:10.0.0.1",
+ "::7f00:1", // IPv4-compatible 127.0.0.1
+ "64:ff9b::7f00:1", // NAT64 of 127.0.0.1
+ "64:ff9b::10.0.0.1",
+ "64:ff9b::a9fe:a9fe",
+ "fec0::1", // site-local
+ "feff::1",
+ "fe80::1%eth0",
+ "ff02::1",
+ "fc00::1",
+ "::",
+ "0:0:0:0:0:0:0:1",
+ ]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of [
+ "[::ffff:5db8:d822]", // 93.184.216.34
+ "::ffff:8.8.8.8",
+ "64:ff9b::808:808", // NAT64 of 8.8.8.8
+ "2606:4700::1",
+ "2001:db8::fe80:1",
+ "fe00::1",
+ ]) {
+ assert.equal(isPrivateAddress(a), false, a);
+ }
+});
+
+test("a mapped literal in an origin is refused at connect, and a name resolving to one too", async () => {
+ const lookup = async (h: string) => (h === "mapped.example" ? [{ address: "::ffff:a00:2" }] : [{ address: "93.184.216.34" }]);
+ assert.match((await privateHostRefusal("http://[::ffff:127.0.0.1]:3001", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("http://[64:ff9b::a9fe:a9fe]", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("https://mapped.example", { lookup }))!, /\(::ffff:a00:2\)/);
+ assert.equal(await privateHostRefusal("http://[::ffff:5db8:d822]", { lookup }), null);
+});
+
+test("the other ways an IPv6 literal carries a private IPv4: NAT64's local-use prefix, IPv4-translated, 6to4", () => {
+ for (const a of ["::ffff:0:7f00:1", "::ffff:0:10.0.0.1", "2002:7f00:1::", "2002:c0a8:101::1", "2002:a9fe:a9fe::"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ for (const a of ["::ffff:0:808:808", "2002:808:808::1"]) assert.equal(isPrivateAddress(a), false, a);
+ // 64:ff9b:1::/48 is local-use whole: private wherever an IPv4 sits in it, and when it carries a public one.
+ for (const a of ["64:ff9b:1::7f00:1", "64:ff9b:1::808:808", "64:ff9b:1:7f00:0:1::", "64:ff9b:1:a00:0:1::", "64:ff9b:1:ffff:ffff:ffff:ffff:ffff", "64:ff9b:1::"]) {
+ assert.equal(isPrivateAddress(a), true, a);
+ }
+ // Its neighbours are not it.
+ for (const a of ["64:ff9b:2::808:808", "64:ff9b:10::1"]) assert.equal(isPrivateAddress(a), false, a);
+});
+
+test("every spelling of a local address in an origin is refused: decimal, hex, octal, short, a trailing dot, bracketed IPv6", async () => {
+ const { archiveOriginOf } = await import("./remoteArchives");
+ // The names' answers are what a resolver gives for them; nothing here is asked of the network.
+ const lookup = async (h: string) => (/^localhost\.?$/.test(h) || /\.local\.?$/.test(h) ? [{ address: "127.0.0.1" }] : [{ address: "93.184.216.34" }]);
+ for (const typed of [
+ "http://[::ffff:7f00:1]",
+ "http://[::ffff:127.0.0.1]",
+ "http://[0:0:0:0:0:ffff:127.0.0.1]",
+ "http://[::1]",
+ "http://[::]",
+ "http://0.0.0.0",
+ "http://0",
+ "http://2130706433", // 127.0.0.1 as one decimal number
+ "http://3232235777", // 192.168.1.1
+ "http://0x7f000001",
+ "http://0x7f.0.0.1",
+ "http://017700000001",
+ "http://0177.0.0.1",
+ "http://127.1",
+ "http://127.0.0.1.",
+ "http://169.254.169.254.",
+ "http://LOCALHOST",
+ "http://localhost.",
+ "http://nas.local.",
+ "http://router.lan",
+ "http://[64:ff9b:1::7f00:1]",
+ "http://[2002:7f00:1::]",
+ ]) {
+ const origin = archiveOriginOf(typed);
+ assert.ok(origin, `${typed} is an origin`);
+ assert.match((await privateHostRefusal(origin, { lookup })) ?? "", /a local or private address|a local name/, typed);
+ }
+});
+
+test("a host's refusal: literal, by name, by what the name resolves to; a public one passes", async () => {
+ const lookup = async (h: string) => (h === "inside.example" ? [{ address: "10.0.0.2" }] : [{ address: "93.184.216.34" }]);
+ assert.match((await privateHostRefusal("http://169.254.169.254", { lookup }))!, /a local or private address/);
+ assert.match((await privateHostRefusal("http://box.localhost:3000", { lookup }))!, /a local name/);
+ assert.match((await privateHostRefusal("https://inside.example", { lookup }))!, /\(10\.0\.0\.2\)/);
+ assert.equal(await privateHostRefusal("https://jeralyzer.pages.dev", { lookup }), null);
+});
+
diff --git a/common/lib/archiveHosts-server.ts b/common/lib/archiveHosts-server.ts
@@ -0,0 +1,121 @@
+// WHICH HOSTS AN ARCHIVE MAY BE (demo epic D1 review, blocker 2c).
+//
+// Connecting an archive makes this machine read the origin's documents — and
+// umtool, which can connect one, is open on the LAN. So an origin whose host is
+// this machine or the local network (loopback, private, link-local, CGNAT, a
+// `.localhost`/`.local`/`.internal` name, or a name that RESOLVES to such an
+// address) is refused at connect, before its corpus.json is asked for —
+// unless the operator decided otherwise ON THIS MACHINE:
+//
+// - ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1 in the editor's own environment
+// (a stub archive in a test, an archive served on the LAN on purpose);
+// - the origin is TRANSCRIPT_SITE_URL's (the environment's archive);
+// - the origin is already in settings.json (written there by hand).
+//
+// Nothing else checks: once connected, an archive is read on its own origin
+// only (remoteArchives-server.ts fetchOnOrigin). A name re-pointed at a
+// private address after it was connected is not re-checked.
+
+import { lookup as dnsLookup } from "node:dns/promises";
+import { isIP } from "node:net";
+
+export type LookupAll = (host: string) => Promise<{ address: string }[]>;
+
+const defaultLookup: LookupAll = (host) => dnsLookup(host, { all: true });
+
+function v4Private(a: string): boolean {
+ const p = a.split(".").map(Number);
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
+ const [x, y] = p;
+ return (
+ x === 0 ||
+ x === 10 ||
+ x === 127 ||
+ (x === 100 && y >= 64 && y <= 127) ||
+ (x === 169 && y === 254) ||
+ (x === 172 && y >= 16 && y <= 31) ||
+ (x === 192 && y === 168) ||
+ x >= 224
+ );
+}
+
+/**
+ * An IPv6 address as its eight 16-bit groups, or null. The URL parser writes
+ * an IPv4-mapped literal in hex (`[::ffff:127.0.0.1]` becomes
+ * `[::ffff:7f00:1]`), so the groups are what is compared, never the text.
+ */
+function v6Groups(address: string): number[] | null {
+ let a = address;
+ // A dotted IPv4 tail is two groups.
+ const tail = /^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(a);
+ if (tail) {
+ const b = tail.slice(2).map(Number);
+ if (b.some((n) => n > 255)) return null;
+ a = `${tail[1]}${((b[0] << 8) | b[1]).toString(16)}:${((b[2] << 8) | b[3]).toString(16)}`;
+ }
+ const halves = a.split("::");
+ if (halves.length > 2) return null;
+ const parse = (part: string) => (part === "" ? [] : part.split(":").map((g) => (/^[0-9a-f]{1,4}$/.test(g) ? parseInt(g, 16) : NaN)));
+ const head = parse(halves[0]);
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;
+ if (fill < 0) return null;
+ const groups = [...head, ...new Array<number>(fill).fill(0), ...rest];
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g)) ? groups : null;
+}
+
+const v4Of = (hi: number, lo: number) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
+
+/**
+ * Whether an IP address is loopback, private, link-local, site-local, CGNAT,
+ * unspecified or multicast — in IPv6 also when it only CARRIES such an IPv4
+ * address: IPv4-mapped (`::ffff:a.b.c.d`, in either spelling), the old
+ * IPv4-compatible form (`::a.b.c.d`), NAT64 (`64:ff9b::/96`), IPv4-translated
+ * (`::ffff:0:a.b.c.d`) and 6to4 (`2002::/16`). NAT64's local-use block
+ * `64:ff9b:1::/48` is private whole.
+ */
+export function isPrivateAddress(address: string): boolean {
+ const a = address.replace(/^\[|\]$/g, "").toLowerCase();
+ const kind = isIP(a);
+ if (kind === 4) return v4Private(a);
+ if (kind !== 6) return false;
+ const g = v6Groups(a.split("%")[0]);
+ if (!g) return true; // an IPv6 literal this cannot read is not vouched for
+ const zero = (from: number, to: number) => g.slice(from, to).every((n) => n === 0);
+ if (zero(0, 7) && (g[7] === 0 || g[7] === 1)) return true; // ::, ::1
+ if (zero(0, 5) && g[5] === 0xffff) return v4Private(v4Of(g[6], g[7])); // IPv4-mapped
+ if (zero(0, 6)) return v4Private(v4Of(g[6], g[7])); // IPv4-compatible (deprecated)
+ if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6)) return v4Private(v4Of(g[6], g[7])); // NAT64
+ if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 1) return true; // 64:ff9b:1::/48, NAT64's local-use block: never globally routable, whatever it carries
+ if (zero(0, 4) && g[4] === 0xffff && g[5] === 0) return v4Private(v4Of(g[6], g[7])); // IPv4-translated ::ffff:0:a.b.c.d
+ if (g[0] === 0x2002) return v4Private(v4Of(g[1], g[2])); // 6to4 2002:a.b.c.d::/48
+ return (
+ (g[0] & 0xfe00) === 0xfc00 || // fc00::/7 unique local
+ (g[0] & 0xffc0) === 0xfe80 || // fe80::/10 link-local
+ (g[0] & 0xffc0) === 0xfec0 || // fec0::/10 site-local (deprecated)
+ (g[0] & 0xff00) === 0xff00 // ff00::/8 multicast
+ );
+}
+
+const PRIVATE_NAME = /(^|\.)(localhost|local|internal|lan|home\.arpa)$/i;
+
+/**
+ * Why `origin`'s host may not be connected, or null: a private address
+ * literally, a private name, or a name resolving to a private address. A name
+ * that does not resolve is left to the probe, which says it did not answer.
+ */
+export async function privateHostRefusal(origin: string, opts: { lookup?: LookupAll } = {}): Promise<string | null> {
+ let host: string;
+ try {
+ host = new URL(origin).hostname.replace(/^\[|\]$/g, "");
+ } catch {
+ return null;
+ }
+ const say = (why: string) =>
+ `${origin} is ${why} — an archive on this machine or its network is connected only when the editor runs with ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1, or names it in TRANSCRIPT_SITE_URL or settings.json`;
+ if (isIP(host)) return isPrivateAddress(host) ? say("a local or private address") : null;
+ if (PRIVATE_NAME.test(host)) return say("a local name");
+ const found = await (opts.lookup ?? defaultLookup)(host).catch(() => [] as { address: string }[]);
+ const inside = found.find((f) => isPrivateAddress(f.address));
+ return inside ? say(`a name for a local or private address (${inside.address})`) : null;
+}
diff --git a/common/lib/archiveTrust.test.ts b/common/lib/archiveTrust.test.ts
@@ -0,0 +1,157 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectedArchives, disconnectedArchiveRefusal, isPlatformHost, recordPage, recordPageRefusal, sameOrigin } from "./remoteArchives";
+import { fetchOnOrigin, OffOriginError, plainGetJson, type FetchLike } from "./remoteArchives-server";
+import { detectPlatform } from "./detectPlatform.mjs";
+
+// demo epic D1 review, blocker 2: an archive is untrusted input.
+
+test("a record's page URL: only a video platform's host, the channel's own platform, no credentials", () => {
+ const r = (u: string | undefined, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ assert.equal(r("https://www.youtube.com/watch?v=a1", "youtube"), null);
+ assert.equal(r("https://rumble.com/v9-x.html"), null);
+ assert.match(r("http://127.0.0.1:3001/api/ops/settings")!, /127\.0\.0\.1:3001 is not a video platform's host/);
+ assert.match(r("http://10.0.0.5/threads/123/")!, /is not a video platform's host/, "xenforo is a path on any host: never a window's page");
+ assert.match(r("https://evil.example/watch?v=a1")!, /is not a video platform's host/);
+ assert.match(r("https://rumble.com/v9-x.html", "youtube")!, /rumble\.com is rumble, and the channel is youtube's/);
+ assert.match(r("https://user:pw@www.youtube.com/watch?v=a1")!, /is not a page URL a window is fetched from/);
+ assert.match(r("file:///etc/passwd")!, /is not a page URL a window is fetched from/);
+ assert.equal(r(undefined), "no page URL");
+});
+
+test("a record's page URL: a look-alike of a platform's host is not that platform (re-review, must-fix 1)", () => {
+ const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ // detectPlatform says "youtube" of each of these (a bare endsWith); the host table does not.
+ for (const u of [
+ "https://evilyoutube.com/watch?v=a1",
+ "https://notrumble.com/v9-x.html",
+ "https://fakeodysee.com/@a/b",
+ "https://xtwitch.tv/videos/1",
+ "https://akick.com/video/1",
+ "https://www.youtube.com.evil.example/watch?v=a1",
+ "https://youtu.be.evil.example/a1",
+ "https://web.archive.org/web/2020/https://www.youtube.com/watch?v=a1",
+ "https://notbitchute.com/video/a/",
+ "https://notyoutube.com/watch?v=a1",
+ "https://evil-rumble.com/v9-x.html",
+ "https://rumble.comevil.example/v9-x.html",
+ "https://evil.example/youtube.com/watch?v=a1",
+ "https://youtube.com%2eevil.example/watch?v=a1",
+ "https://youtubе.com/watch?v=a1", // a Cyrillic е
+ ]) {
+ assert.match(r(u)!, /is not a video platform's host/, u);
+ }
+ assert.match(r("https://evilyoutube.com/watch?v=a1", "youtube")!, /^evilyoutube\.com is not a video platform's host/);
+ // The platforms' own hosts, bare and under a subdomain.
+ for (const u of [
+ "https://youtube.com/watch?v=a1",
+ "https://m.youtube.com/watch?v=a1",
+ "https://music.youtube.com/watch?v=a1",
+ "https://youtu.be/a1",
+ "https://rumble.com/v9-x.html",
+ "https://www.rumble.com/v9-x.html",
+ "https://odysee.com/@a/b",
+ "https://www.twitch.tv/videos/1",
+ "https://kick.com/video/1",
+ "https://archive.org/details/x",
+ "https://www.archive.org/details/x",
+ "https://www.bitchute.com/video/a/",
+ "https://old.bitchute.com/video/a/",
+ ]) {
+ assert.equal(r(u), null, u);
+ }
+ assert.equal(isPlatformHost("youtube", "YOUTUBE.com"), true);
+ assert.equal(isPlatformHost("youtube", "youtube.com.evil.example"), false);
+ assert.equal(isPlatformHost("twitter", "x.com"), false, "not a video platform: no table, no host");
+});
+
+// demo epic D1 re-check: the host judged must be the host fetched. Node's URL
+// parser and Python's urlsplit (yt-dlp's) read these differently.
+test("a page URL two parsers read differently is refused unparsed: a backslash, whitespace, a control character", () => {
+ const r = (u: string, p: string | null = null) => recordPageRefusal(u, p, detectPlatform);
+ // What Node makes of the first: the platform's own host. Python's urlsplit says evil.example.
+ assert.equal(new URL("https://youtube.com\\@evil.example/watch?v=x").hostname, "youtube.com");
+ assert.equal(new URL("https://you\ttube.com/watch?v=x").hostname, "youtube.com");
+ for (const u of [
+ "https://youtube.com\\@evil.example/watch?v=x",
+ "https://youtube.com\\@127.0.0.1/x",
+ "https://rumble.com\\.evil.example/v1",
+ "https://you\ttube.com/watch?v=x",
+ " https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x ",
+ "https://youtube.com/watch?v=x\n",
+ "https://youtube.com\r\n@evil.example/",
+ "https://youtube.com/\\evil.example",
+ "https:\\\\youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x\u0000",
+ "https://youtube.com/wa tch?v=x",
+ "https://youtube.com /watch?v=x",
+ "https://youtube.com @evil.example/",
+ "https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x",
+ "https://youtube.com/watch?v=x\u007f",
+ ]) {
+ assert.match(r(u) ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u));
+ assert.match(r(u, "youtube") ?? "(allowed)", /carries a backslash, whitespace or a control character/, JSON.stringify(u));
+ }
+});
+
+test("a page URL that passes is handed on as the parser wrote it back, never as it was given", () => {
+ const page = (u: string, p: string | null = null) => recordPage(u, p, detectPlatform);
+ for (const [given, href, platform] of [
+ ["https://www.youtube.com/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"],
+ ["HTTPS://WWW.YouTube.com:443/watch?v=a1", "https://www.youtube.com/watch?v=a1", "youtube"],
+ ["https:youtube.com/watch?v=a1", "https://youtube.com/watch?v=a1", "youtube"],
+ ["https:///youtu.be/a1", "https://youtu.be/a1", "youtube"],
+ ["http://RUMBLE.com", "http://rumble.com/", "rumble"],
+ ["https://rumble.com/a/../v9-x.html", "https://rumble.com/v9-x.html", "rumble"],
+ ["https://youtube.com./watch?v=a1", "https://youtube.com./watch?v=a1", "youtube"],
+ ] as const) {
+ const got = page(given);
+ if ("refused" in got) {
+ // A spelling the platform table does not vouch for is refused, not passed raw.
+ assert.equal(given, "https://youtube.com./watch?v=a1", `${given}: ${got.refused}`);
+ continue;
+ }
+ assert.deepEqual(got, { href, platform }, given);
+ assert.equal(got.href, new URL(given).href);
+ // And the href is its own fixed point: judged again it is the same URL.
+ assert.deepEqual(page(got.href), got);
+ }
+ assert.deepEqual(page("https://rumble.com/v9-x.html", "youtube"), { refused: "rumble.com is rumble, and the channel is youtube's: the archive's page URL is not fetched" });
+});
+
+test("an archive removed from settings is not read for the channel registered from it (re-review, item 6)", () => {
+ const list = connectedArchives([{ id: "stub", origin: "https://stub.test", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }], {});
+ assert.equal(disconnectedArchiveRefusal("https://stub.test", list), null);
+ assert.equal(disconnectedArchiveRefusal("https://stub.test/", list), null);
+ assert.equal(disconnectedArchiveRefusal(undefined, list), null, "a channel naming no archive has none to lose");
+ assert.match(disconnectedArchiveRefusal("https://stub.test", [])!, /^its archive https:\/\/stub\.test is no longer connected/);
+ // The environment's archive counts as connected.
+ assert.equal(disconnectedArchiveRefusal("https://env.test", connectedArchives([], { TRANSCRIPT_SITE_URL: "https://env.test" })), null);
+});
+
+function redirecting(map: Record<string, { status: number; location?: string; body?: unknown }>): FetchLike & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ const d = map[url];
+ if (!d) return new Response("nope", { status: 404 });
+ return new Response(d.body === undefined ? null : JSON.stringify(d.body), { status: d.status, headers: d.location ? { location: d.location } : {} });
+ }) as FetchLike & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+test("an archive's documents are read on its own origin: a same-origin redirect is followed, one elsewhere refused unfollowed", async () => {
+ const f = redirecting({
+ "https://stub.test/corpus.json": { status: 301, location: "/v2/corpus.json" },
+ "https://stub.test/v2/corpus.json": { status: 200, body: { ok: 1 } },
+ "https://stub.test/transcripts/a/manifest.json": { status: 302, location: "http://127.0.0.1:3001/api/ops/settings" },
+ });
+ assert.deepEqual(await plainGetJson(f)("https://stub.test/corpus.json"), { ok: 1 });
+ await assert.rejects(fetchOnOrigin(f, "https://stub.test/transcripts/a/manifest.json"), (e: unknown) => e instanceof OffOriginError && /redirects to http:\/\/127\.0\.0\.1:3001/.test((e as Error).message));
+ assert.equal(f.asked.includes("http://127.0.0.1:3001/api/ops/settings"), false);
+ assert.equal(sameOrigin("https://stub.test:443/x", "https://stub.test"), true);
+ assert.equal(sameOrigin("https://stub.test:8443/x", "https://stub.test"), false);
+});
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -36,6 +36,30 @@ export function isSocialChannel(
return config?.sourceKind === "social";
}
+// A REMOTE-ONLY channel (demo epic D1): one the editor holds ONLY to fetch
+// clip windows a connected archive's citations name — config only, no
+// listing, no transcripts of its own. Inert everywhere a real channel is
+// active: no sync, no lane, no cleanup, no auto-download, on no site, in no
+// index build (every guard asks this predicate).
+export function isRemoteOnlyChannel(
+ config: Pick<ChannelConfig, "remoteOnly"> | null | undefined,
+): boolean {
+ return config?.remoteOnly === true;
+}
+
+// The sentence every door that would list, sync or download a channel
+// answers a remote-only one with; null for any other channel.
+export function remoteOnlyRefusal(
+ slug: string,
+ config: Pick<ChannelConfig, "remoteOnly" | "remoteArchive"> | null | undefined,
+): string | null {
+ if (!isRemoteOnlyChannel(config)) return null;
+ return (
+ `${slug} is a remote-only channel${config?.remoteArchive ? ` of ${config.remoteArchive}` : ""}: ` +
+ "it holds that archive's clip windows only, and is never listed, synced or downloaded here"
+ );
+}
+
export type AudioFormat = "m4a" | "mp3" | "opus";
// Who owns audio extraction for a transcribe-handling download:
@@ -245,6 +269,13 @@ export type ChannelConfig = {
lastFullDownloadAt?: string;
lastFullSweepAt?: string;
excludeFromBuild?: boolean;
+ // A remote-only channel (isRemoteOnlyChannel): registered on first need for
+ // a connected archive's clip windows; `remoteArchive` is that archive's
+ // origin and `remoteUrl` the channel's page on its platform, as the archive
+ // named it (never `url`, so nothing that syncs a channel by its url can).
+ remoteOnly?: boolean;
+ remoteArchive?: string;
+ remoteUrl?: string;
excludeFromCleanup?: boolean;
cleanAfterCaptureUnverified?: boolean;
syncIntervalMinutes?: number;
@@ -319,6 +350,16 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
lastFullSweepAt:
"SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk.",
excludeFromBuild: "Leave this channel out of every site build.",
+ remoteOnly:
+ "A REMOTE-ONLY channel: held only to fetch clip windows that a connected archive's citations name " +
+ "(settings.remoteArchives). Registered by the editor the first time a window of it is asked for, with no " +
+ "listing sweep. Inert: no sync, no lane, no cleanup, no auto-download, on no site, in no index build; the " +
+ "channel list shows it as remote-only. A whole-recording platform's window (Rumble) is refused with the " +
+ "recording's size until the ask says `allowWholeRecording`.",
+ remoteArchive: "A remote-only channel's archive: the origin whose corpus.json names it.",
+ remoteUrl:
+ "A remote-only channel's page on its platform, as its archive's corpus.json named it (spec 6). Informational: " +
+ "a remote-only channel has no `url`, so nothing syncs it.",
excludeFromCleanup:
"Leave this channel's reclaimable bytes out of the aggregate \"cleanable data\" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes.",
cleanAfterCaptureUnverified:
@@ -546,6 +587,9 @@ export const CHANNEL_CONFIG_COERCIONS: {
lastFullDownloadAt: str,
lastFullSweepAt: str,
excludeFromBuild: bool,
+ remoteOnly: (v) => (v === true ? true : undefined),
+ remoteArchive: trimmedNonBlank,
+ remoteUrl: trimmedNonBlank,
excludeFromCleanup: bool,
cleanAfterCaptureUnverified: bool,
syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES),
diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts
@@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it",
assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]);
assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]);
- assert.equal(CHANNEL_CONFIG_KEYS.length, 44); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 47); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl`
assert.equal(sameKeys, true);
assert.equal(fits, true);
for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k);
diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts
@@ -68,6 +68,9 @@ export const channelConfigObjectSchema = z.object({
lastFullDownloadAt: field("lastFullDownloadAt"),
lastFullSweepAt: field("lastFullSweepAt"),
excludeFromBuild: field("excludeFromBuild"),
+ remoteOnly: field("remoteOnly"),
+ remoteArchive: field("remoteArchive"),
+ remoteUrl: field("remoteUrl"),
excludeFromCleanup: field("excludeFromCleanup"),
cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"),
syncIntervalMinutes: field("syncIntervalMinutes"),
diff --git a/common/lib/corpus.test.ts b/common/lib/corpus.test.ts
@@ -190,15 +190,36 @@ test("Use with AI is the homepage's AI and MCP doc; the chat is the instance's /
}
});
-test("the spec is 5, and `generator` is still not why", () => {
- // Guard on the reasoning, not just the number: a bump announces a new
- // FETCHABLE document. spec 4 is /tags.json, spec 5 the reports index (and a
- // cited site that publishes only reports). The informational credit string
- // added at spec 3's time breaks no reader and did not bump anything — if
- // either assertion is ever updated, the version-history comment in corpus.ts
- // must justify why.
- assert.equal(CORPUS_SPEC_VERSION, 5);
- assert.equal(buildSiteCorpus(descriptor(), { hasArchives: false }).spec, 5);
+test("the spec is 6, and `generator` is still not why", () => {
+ // Guard on the reasoning, not just the number: a bump announces something a
+ // reader can FETCH that it could not before. spec 4 is /tags.json, spec 5 the
+ // reports index (and a cited site that publishes only reports), spec 6 each
+ // channel's platform and page — where a cited moment's MEDIA is fetched from,
+ // which a machine with no copy of the channel had no way to learn (demo epic
+ // D1). The informational credit string added at spec 3's time breaks no
+ // reader and did not bump anything — if either assertion is ever updated,
+ // the version-history comment in corpus.ts must justify why.
+ assert.equal(CORPUS_SPEC_VERSION, 6);
+ assert.equal(buildSiteCorpus(descriptor(), { hasArchives: false }).spec, 6);
+});
+
+test("spec 6: a channel names its platform and its page there, only when known; llms.txt says so", () => {
+ const corpus = buildSiteCorpus(descriptor({ siteUrl: "https://demo.example" }), {
+ hasArchives: false,
+ channelFacts: { [descriptor().channels[0].slug]: { platform: "youtube", url: "https://www.youtube.com/@demo" } },
+ });
+ const [first, ...rest] = corpus.channels;
+ assert.equal(first.platform, "youtube");
+ assert.equal(first.url, "https://www.youtube.com/@demo");
+ for (const c of rest) {
+ assert.equal("platform" in c, false);
+ assert.equal("url" in c, false);
+ }
+ // Without facts the entries are shaped as at spec 5.
+ for (const c of buildSiteCorpus(descriptor(), { hasArchives: false }).channels) assert.deepEqual(Object.keys(c).filter((k) => k === "platform" || k === "url"), []);
+ const llms = renderSiteLlmsTxt(corpus);
+ assert.match(llms, new RegExp(`- ${first.name} \\(youtube: https://www\\.youtube\\.com/@demo\\) — `));
+ assert.match(llms, /Each channel names its `platform` and its `url` there when known \(spec 6\)/);
});
test("the tags pointer is present only when the site published one", () => {
diff --git a/common/lib/corpus.ts b/common/lib/corpus.ts
@@ -43,6 +43,15 @@ import {
// An older reader sees an empty corpus there, which is the safe reading: there
// is no shard to fetch.
//
+// v6: each channel names WHERE IT IS — `platform` (youtube, rumble, …) and
+// `url`, the channel's own page on that platform, when the archive's operator
+// configured one (demo epic D1). A machine with no copy of the channel (a
+// fresh clone pointed at this archive) needs both to fetch a cited moment's
+// media: the platform decides the pacing and whether a window is a seek or a
+// whole recording. Additive: an older reader ignores both; a reader of an
+// older archive falls back to a shard record's `webpageUrl` / `platform`
+// (common/lib/remoteArchives-server.ts channelFactsOf).
+//
// NOT a v4: the `generator` field added below is deliberately unversioned. Every
// prior bump announced a new FETCHABLE LAYER — a reader that ignored it would
// miss data it could otherwise have retrieved. `generator` is an informational
@@ -166,6 +175,10 @@ export type CorpusChannel = {
name: string;
videoCount: number;
groupId?: string;
+ // Spec 6: the channel's platform and its page there. Each present only when
+ // known: a curated mix of several platforms' videos has no url.
+ platform?: string;
+ url?: string;
manifests: {
transcripts: string;
subs: string;
@@ -279,6 +292,9 @@ export function buildSiteCorpus(
// A CITED site's build: `site.scope: "cited"` and `site.audience` always.
// Its descriptor carries no channels, so the corpus has none.
cited?: boolean;
+ // slug -> where the channel is (spec 6): its platform and its page there,
+ // from its config. A channel absent here, or a field left out, is unknown.
+ channelFacts?: Record<string, { platform?: string; url?: string }>;
},
): SiteCorpus {
const base = descriptor.siteUrl;
@@ -292,6 +308,8 @@ export function buildSiteCorpus(
name: c.name,
videoCount: c.count,
...(c.groupId ? { groupId: c.groupId } : {}),
+ ...(opts.channelFacts?.[c.slug]?.platform ? { platform: opts.channelFacts[c.slug].platform } : {}),
+ ...(opts.channelFacts?.[c.slug]?.url ? { url: opts.channelFacts[c.slug].url } : {}),
...(postCount ? { postCount } : {}),
...(opts.channelKinds?.[c.slug] ? { kind: opts.channelKinds[c.slug] } : {}),
...(digestCount ? { digestCount } : {}),
@@ -459,7 +477,9 @@ export function renderSiteLlmsTxt(
out.push("## Corpus");
out.push(
`- [corpus.json](${corpusUrl(base)}): machine-readable index — ` +
- `channels and how to fetch any transcript from the paginated JSON shards.`,
+ `channels and how to fetch any transcript from the paginated JSON shards. ` +
+ `Each channel names its \`platform\` and its \`url\` there when known (spec 6): ` +
+ `where a cited moment's media is fetched from.`,
);
if (corpus.digestScheme) {
const digested = corpus.channels.reduce(
@@ -499,7 +519,8 @@ export function renderSiteLlmsTxt(
out.push("## Channels");
const shown = corpus.channels.slice(0, LLMS_INLINE_LIMIT);
for (const c of shown) {
- out.push(`- ${c.name} — ${c.videoCount} transcripts: ${c.manifests.transcripts}`);
+ const where = c.url ? ` (${c.platform ? `${c.platform}: ` : ""}${c.url})` : c.platform ? ` (${c.platform})` : "";
+ out.push(`- ${c.name}${where} — ${c.videoCount} transcripts: ${c.manifests.transcripts}`);
}
if (corpus.channels.length > shown.length) {
out.push(
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -134,7 +134,11 @@ const DECLARED: EnvVarDecl[] = [
{ name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." },
{ name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does)." },
{ name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." },
- { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." },
+ { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it." },
+ { name: "ARCHILYZER_ALLOW_PRIVATE_ARCHIVES", audience: "runtime", default: "off", readBy: "common/controller/remoteArchives.ts", doc: "`1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only)." },
+ { name: "ARCHIVE_CACHE_DIR", audience: "runtime", default: "`.archive-cache` beside EXPORT_BUILDS_DIR", readBy: "common/lib/archiveCache-server.ts", doc: "Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume." },
+ { name: "ARCHIVE_CACHE_MAX_MB", audience: "runtime", default: "512", readBy: "common/lib/archiveCache-server.ts", doc: "The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped." },
+ { name: "ARCHIVE_CACHE", audience: "runtime", default: "on (off under node's test runner)", readBy: "common/lib/archiveCache-server.ts", doc: "`0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off." },
{ name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." },
{ name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." },
{ name: "TRANSCRIPT_PLATFORM_LINKS", audience: "runtime", default: "off", readBy: "common/lib/archive/reader-fs.ts", doc: "`1` cites platform watch pages instead of the archive's own pages." },
diff --git a/common/lib/projectsRoot.mjs b/common/lib/projectsRoot.mjs
@@ -0,0 +1,37 @@
+// WHERE AN ARTICLE'S VIDEO PROJECTS LIVE when settings.generation.projectsRoot
+// is blank: `<REPORTS_DIR>/articles` when REPORTS_DIR is set — a container
+// sets it to its reports volume (/data/reports, Dockerfile), so a fresh
+// container's projects land on the volume and not in its writable layer —
+// else `~/reports/articles`, the host default since release 27 S6 (demo epic
+// D1 item 3; D0 found a container's projects outside the reports volume).
+//
+// Plain JS (with JSDoc) so umtool's plain-node chain planner
+// (umtool/lib/report/chain.mjs) reads the same rule as the editor's TS.
+
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * @param {Record<string, string | undefined>} [env]
+ * @returns {string}
+ */
+export function defaultProjectsRoot(env = process.env) {
+ const reports = env.REPORTS_DIR?.trim();
+ if (reports) return path.join(path.resolve(/* turbopackIgnore: true */ reports), "articles");
+ return path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
+}
+
+/** `~` and `~/` expanded against the home directory. */
+export function expandHomeDir(p) {
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
+}
+
+/**
+ * The projects root a settings value names: `~` expanded; blank = the default.
+ * @param {unknown} configured settings.generation.projectsRoot
+ * @param {Record<string, string | undefined>} [env]
+ */
+export function projectsRootFrom(configured, env = process.env) {
+ if (typeof configured !== "string" || !configured.trim()) return defaultProjectsRoot(env);
+ return expandHomeDir(configured.trim());
+}
diff --git a/common/lib/remoteArchives-server.ts b/common/lib/remoteArchives-server.ts
@@ -0,0 +1,264 @@
+// THE REMOTE-ARCHIVE RESOLVER's network half (./remoteArchives.ts is the pure
+// one): what a published archive says about itself, read from its
+// `/corpus.json` — the title, the totals and the channels the Connect form
+// shows before anything is saved.
+//
+// One request per probe, sequential, never in a loop. The fetch is injectable
+// (every test passes a fake; no test calls a real site).
+
+import { archiveOriginOf, sameOrigin } from "./remoteArchives";
+import { corpusUrl, manifestUrl, pageUrl } from "./archive/contract";
+import { detectPlatform } from "./detectPlatform.mjs";
+
+export type FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record<string, string> }) => Promise<Response>;
+
+export type ArchiveProbeChannel = {
+ slug: string;
+ name: string;
+ videoCount: number | null;
+ // Spec 6 (corpus.json carries them); absent from an older archive's entry.
+ platform?: string;
+ url?: string;
+};
+
+export type ArchiveProbe = {
+ origin: string;
+ // corpus.json's own: site.id, site.title, spec, generatedAt.
+ siteId: string | null;
+ title: string;
+ description: string;
+ spec: number | null;
+ generatedAt: string | null;
+ totals: { channels: number; videos: number };
+ channels: ArchiveProbeChannel[];
+};
+
+export class ArchiveProbeError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ this.name = "ArchiveProbeError";
+ }
+}
+
+const PROBE_TIMEOUT_MS = 15_000;
+const MAX_REDIRECTS = 3;
+
+// The largest archive document read (demo epic D1 review follow-up): a shard
+// page is up to 8 MB; anything past 32 MB is refused, not buffered.
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+
+export class OversizeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OversizeError";
+ }
+}
+
+/** A response's body as text, refused past `max` bytes (by its Content-Length, then as it streams). */
+export async function readBounded(res: Response, url: string, max = MAX_ARCHIVE_DOCUMENT_BYTES): Promise<string> {
+ const declared = Number(res.headers.get("content-length"));
+ const over = () => new OversizeError(`${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel().catch(() => {});
+ throw over();
+ }
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ await reader.cancel().catch(() => {});
+ throw over();
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+export class OffOriginError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OffOriginError";
+ }
+}
+
+/**
+ * A GET that stays on `url`'s own origin (demo epic D1 review, blocker 2): a
+ * redirect is followed (up to three) only to the same scheme, host and port;
+ * one that leaves it is refused before it is followed. An archive is someone
+ * else's server, and nothing it answers may send this machine elsewhere.
+ */
+export async function fetchOnOrigin(doFetch: FetchLike, url: string, init: { signal?: AbortSignal; headers?: Record<string, string> } = {}): Promise<Response> {
+ let at = url;
+ for (let hop = 0; ; hop++) {
+ const res = await doFetch(at, { ...init, redirect: "manual" } as never);
+ if (res.status < 300 || res.status > 399 || res.status === 304) return res;
+ const location = res.headers.get("location");
+ if (!location) return res;
+ const next = new URL(location, at).href;
+ if (!sameOrigin(next, url)) throw new OffOriginError(`${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`);
+ if (hop >= MAX_REDIRECTS) throw new OffOriginError(`${url} redirects more than ${MAX_REDIRECTS} times`);
+ at = next;
+ }
+}
+
+const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null);
+const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
+
+/**
+ * Read `<origin>/corpus.json` and say what the archive is. Refused, with a
+ * sentence: not an origin, unreachable, not JSON, a federation hub (connect
+ * one of its sites), a cited-only site (it publishes reports, no corpus), or
+ * a site listing no channels.
+ */
+export async function probeArchive(rawOrigin: string, opts: { fetch?: FetchLike; timeoutMs?: number } = {}): Promise<ArchiveProbe> {
+ const origin = archiveOriginOf(rawOrigin);
+ if (!origin) throw new ArchiveProbeError(`"${rawOrigin}" is not an archive's address — type its origin, e.g. https://jeralyzer.pages.dev`);
+ const doFetch = opts.fetch ?? (fetch as unknown as FetchLike);
+ const url = `${origin}/corpus.json`;
+ let res: Response;
+ try {
+ res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(opts.timeoutMs ?? PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
+ } catch (e) {
+ if (e instanceof OffOriginError) throw new ArchiveProbeError(e.message, 502);
+ throw new ArchiveProbeError(`${url} did not answer: ${(e as Error).message}`, 502);
+ }
+ if (!res.ok) throw new ArchiveProbeError(`${url} answered HTTP ${res.status} — is ${origin} a published archive?`, 502);
+ let j: Record<string, unknown>;
+ try {
+ j = JSON.parse(await readBounded(res, url)) as Record<string, unknown>;
+ } catch (e) {
+ if (e instanceof OversizeError) throw new ArchiveProbeError(e.message, 502);
+ throw new ArchiveProbeError(`${url} is not JSON — ${origin} does not serve an archive's contract`, 502);
+ }
+ if (!j || typeof j !== "object" || Array.isArray(j)) throw new ArchiveProbeError(`${url} is not an archive's corpus.json`, 502);
+ if (j.kind === "hub" || Array.isArray(j.sites)) {
+ const sites = Array.isArray(j.sites) ? (j.sites as Record<string, unknown>[]) : [];
+ const names = sites
+ .map((s) => str(s?.url))
+ .filter((u): u is string => !!u)
+ .slice(0, 6);
+ throw new ArchiveProbeError(
+ `${origin} is a federation hub of ${sites.length} site(s), not one archive — connect one of its sites${names.length ? `: ${names.join(", ")}` : ""}`,
+ );
+ }
+ const site = (j.site && typeof j.site === "object" ? j.site : {}) as Record<string, unknown>;
+ if (site.scope === "cited") {
+ throw new ArchiveProbeError(`${origin} publishes only its reports and the moments they cite — it has no corpus to search`);
+ }
+ const rawChannels = Array.isArray(j.channels) ? (j.channels as Record<string, unknown>[]) : [];
+ const channels: ArchiveProbeChannel[] = [];
+ for (const c of rawChannels) {
+ const slug = str(c?.slug);
+ if (!slug) continue;
+ const platform = str(c.platform);
+ const curl = str(c.url);
+ channels.push({
+ slug,
+ name: str(c.name) ?? slug,
+ videoCount: num(c.videoCount),
+ ...(platform ? { platform } : {}),
+ ...(curl ? { url: curl } : {}),
+ });
+ }
+ if (channels.length === 0) throw new ArchiveProbeError(`${origin}'s corpus.json lists no channels — there is nothing to search`);
+ const totals = (j.totals && typeof j.totals === "object" ? j.totals : {}) as Record<string, unknown>;
+ return {
+ origin,
+ siteId: str(site.id),
+ title: str(site.title) ?? origin.replace(/^https?:\/\//, ""),
+ description: str(site.description) ?? "",
+ spec: num(j.spec),
+ generatedAt: str(j.generatedAt),
+ totals: {
+ channels: num(totals.channels) ?? channels.length,
+ videos: num(totals.videos) ?? channels.reduce((n, c) => n + (c.videoCount ?? 0), 0),
+ },
+ channels,
+ };
+}
+
+// ─── A channel's facts: where it is (demo epic D1 item 4) ───
+
+export type ArchiveChannelFacts = {
+ slug: string;
+ name: string;
+ // The platform its recordings are on, or null when the archive does not say
+ // and no record names one.
+ platform: string | null;
+ // Its page on that platform (corpus.json spec 6), or null.
+ url: string | null;
+ // Where the facts came from: corpus.json's channel entry (spec 6), the
+ // channel's first shard record (an older archive), or nowhere.
+ from: "corpus" | "record" | "none";
+ // A record's own page (the fallback's evidence), when one was read.
+ sampleVideoUrl?: string;
+};
+
+export class ArchiveChannelError extends Error {
+ constructor(
+ message: string,
+ readonly status = 404,
+ ) {
+ super(message);
+ this.name = "ArchiveChannelError";
+ }
+}
+
+// One JSON document over HTTP: a throw on anything but a 200. Injectable as
+// `getJson` so the cached reader (item 6) is the one every lookup goes through.
+export type GetJson = (url: string) => Promise<unknown>;
+
+export function plainGetJson(doFetch: FetchLike = fetch as unknown as FetchLike): GetJson {
+ return async (url) => {
+ const res = await fetchOnOrigin(doFetch, url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), headers: { accept: "application/json" } });
+ if (!res.ok) throw new ArchiveChannelError(`${url} answered HTTP ${res.status}`, res.status === 404 ? 404 : 502);
+ return JSON.parse(await readBounded(res, url));
+ };
+}
+
+/**
+ * Where an archive's channel is: corpus.json's `platform` and `url` (spec 6);
+ * for an OLDER archive whose entry has no platform, the channel's first shard
+ * record — the transcripts manifest's lowest page, its first record with a
+ * `webpageUrl` — gives the platform (the record's own, else its page's host).
+ * Sequential: at most three documents, one after another. A slug the archive
+ * does not list is refused.
+ */
+export async function archiveChannelFacts(origin: string, slug: string, opts: { getJson?: GetJson; fetch?: FetchLike } = {}): Promise<ArchiveChannelFacts> {
+ const base = archiveOriginOf(origin);
+ if (!base) throw new ArchiveChannelError(`"${origin}" is not an archive's address`, 400);
+ const getJson = opts.getJson ?? plainGetJson(opts.fetch);
+ const corpus = (await getJson(corpusUrl(base))) as { channels?: Record<string, unknown>[] } | null;
+ const entry = (Array.isArray(corpus?.channels) ? corpus!.channels : []).find((c) => c?.slug === slug);
+ if (!entry) throw new ArchiveChannelError(`${base} lists no channel "${slug}"`);
+ const name = str(entry.name) ?? slug;
+ const platform = str(entry.platform);
+ const url = str(entry.url);
+ if (platform) return { slug, name, platform, url: url && /^https?:\/\//i.test(url) ? url : null, from: "corpus" };
+ // An older archive: the first record's page.
+ const manifests = (entry.manifests && typeof entry.manifests === "object" ? entry.manifests : {}) as Record<string, unknown>;
+ // Only the archive's own origin is read: a manifest the corpus names elsewhere is not followed.
+ const named = str(manifests.transcripts);
+ const manifestAt = named && sameOrigin(named, base) ? named : manifestUrl("transcripts", slug, base);
+ const manifest = (await getJson(manifestAt).catch(() => null)) as { slugToPage?: Record<string, unknown> } | null;
+ const pages = Object.values(manifest?.slugToPage ?? {}).filter((n): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0);
+ if (pages.length > 0) {
+ const first = Math.min(...pages);
+ const records = (await getJson(pageUrl("transcripts", slug, first, base)).catch(() => null)) as Record<string, unknown>[] | null;
+ for (const r of Array.isArray(records) ? records : []) {
+ const page = str(r?.webpageUrl);
+ if (!page) continue;
+ const p = str(r.platform) ?? detectPlatform(page);
+ return { slug, name, platform: p, url: url && /^https?:\/\//i.test(url) ? url : null, from: p ? "record" : "none", sampleVideoUrl: page };
+ }
+ }
+ return { slug, name, platform: null, url: url && /^https?:\/\//i.test(url) ? url : null, from: "none" };
+}
diff --git a/common/lib/remoteArchives.test.ts b/common/lib/remoteArchives.test.ts
@@ -0,0 +1,165 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ archiveHandle,
+ archiveOriginOf,
+ connectedArchives,
+ findConnectedArchive,
+ freeArchiveId,
+ originOfHandle,
+ sanitizeRemoteArchives,
+} from "./remoteArchives";
+import { ArchiveChannelError, ArchiveProbeError, archiveChannelFacts, probeArchive, type FetchLike } from "./remoteArchives-server";
+import { defaults } from "./settingsSchema";
+
+test("an archive origin is normalized: https assumed, trailing slash and /corpus.json dropped", () => {
+ assert.equal(archiveOriginOf("jeralyzer.pages.dev"), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf(" https://Jeralyzer.pages.dev/ "), "https://jeralyzer.pages.dev");
+ assert.equal(archiveOriginOf("https://x.test/corpus.json"), "https://x.test");
+ assert.equal(archiveOriginOf("http://127.0.0.1:4100/arch/"), "http://127.0.0.1:4100/arch");
+ for (const bad of ["", "ftp://x.test", "https://u:p@x.test", "https://x.test/?q=1", "https://x.test/#a", 7, null]) {
+ assert.equal(archiveOriginOf(bad), null, String(bad));
+ }
+});
+
+test("a handle names its archive and back", () => {
+ assert.equal(archiveHandle("https://a.test"), "remote:https://a.test");
+ assert.equal(originOfHandle("remote:https://a.test/"), "https://a.test");
+ assert.equal(originOfHandle("local:/x"), null);
+ assert.equal(originOfHandle(undefined), null);
+});
+
+test("ids: the archive's own site id when free, else from the host, made unique", () => {
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "jeralyzer"), "jeralyzer");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", ["jeralyzer"], "jeralyzer"), "jeralyzer-2");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], null), "jeralyzer-pages-dev");
+ assert.equal(freeArchiveId("https://jeralyzer.pages.dev", [], "Not A Slug"), "jeralyzer-pages-dev");
+});
+
+test("the stored list is sanitized: bad entries and later duplicates dropped", () => {
+ const out = sanitizeRemoteArchives([
+ { id: "a", origin: "https://a.test/", title: "A", addedAt: "2026-11-11T00:00:00Z" },
+ { id: "b", origin: "https://a.test" }, // same origin
+ { id: "a", origin: "https://other.test" }, // same id
+ { id: "BAD", origin: "https://c.test" },
+ { id: "d", origin: "not a url at all ::" },
+ "junk",
+ { id: "e", origin: "https://e.test" },
+ ]);
+ assert.deepEqual(out, [
+ { id: "a", origin: "https://a.test", title: "A", addedAt: "2026-11-11T00:00:00.000Z" },
+ { id: "e", origin: "https://e.test", title: "e.test", addedAt: "1970-01-01T00:00:00.000Z" },
+ ]);
+ assert.deepEqual(sanitizeRemoteArchives({ not: "an array" }), []);
+ assert.deepEqual(defaults().remoteArchives, []);
+});
+
+test("TRANSCRIPT_SITE_URL is the default archive, listed but never stored, and not twice", () => {
+ const none = connectedArchives([], {});
+ assert.deepEqual(none, []);
+ const env = connectedArchives([], { TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev/" });
+ assert.equal(env.length, 1);
+ assert.equal(env[0].origin, "https://jeralyzer.pages.dev");
+ assert.equal(env[0].fromEnv, true);
+ const stored = connectedArchives([{ id: "jeralyzer", origin: "https://jeralyzer.pages.dev", title: "Jeralyzer", addedAt: "2026-11-11T00:00:00Z" }], {
+ TRANSCRIPT_SITE_URL: "https://jeralyzer.pages.dev",
+ });
+ assert.equal(stored.length, 1);
+ assert.equal(stored[0].fromEnv, undefined);
+ assert.equal(findConnectedArchive(stored, "jeralyzer.pages.dev/")?.id, "jeralyzer");
+ assert.equal(findConnectedArchive(stored, "https://elsewhere.test"), null);
+});
+
+// ─── probeArchive, against a fake fetch only ───
+
+const respond = (body: unknown, status = 200): Response =>
+ new Response(typeof body === "string" ? body : JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+function fakeFetch(map: Record<string, () => Response>): FetchLike & { asked: string[] } {
+ const asked: string[] = [];
+ const f = (async (url: string) => {
+ asked.push(url);
+ const r = map[url];
+ if (!r) return respond({ error: "nope" }, 404);
+ return r();
+ }) as FetchLike & { asked: string[] };
+ f.asked = asked;
+ return f;
+}
+
+const CORPUS = {
+ spec: 6,
+ kind: "site",
+ generatedAt: "2026-11-08T08:26:37.854Z",
+ site: { id: "stubalyzer", title: "Stubalyzer", description: "A stub", url: "https://stub.test" },
+ totals: { channels: 2, videos: 30 },
+ channels: [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha", manifests: {} },
+ { slug: "beta", name: "Beta", videoCount: 10, manifests: {} },
+ ],
+};
+
+test("a probe reads corpus.json once and says what the archive holds", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond(CORPUS) });
+ const p = await probeArchive("stub.test/", { fetch: f });
+ assert.deepEqual(f.asked, ["https://stub.test/corpus.json"]);
+ assert.equal(p.origin, "https://stub.test");
+ assert.equal(p.siteId, "stubalyzer");
+ assert.equal(p.title, "Stubalyzer");
+ assert.equal(p.spec, 6);
+ assert.deepEqual(p.totals, { channels: 2, videos: 30 });
+ assert.deepEqual(p.channels, [
+ { slug: "alpha", name: "Alpha", videoCount: 20, platform: "youtube", url: "https://www.youtube.com/@alpha" },
+ { slug: "beta", name: "Beta", videoCount: 10 },
+ ]);
+});
+
+test("a probe refuses what is not one searchable archive, with a sentence", async () => {
+ const cases: [string, () => Response, RegExp][] = [
+ ["https://a.test/corpus.json", () => respond("<html>", 200), /is not JSON/],
+ ["https://b.test/corpus.json", () => respond({}, 500), /answered HTTP 500/],
+ ["https://c.test/corpus.json", () => respond({ kind: "hub", sites: [{ url: "https://m1.test" }] }), /federation hub of 1 site.*https:\/\/m1\.test/],
+ ["https://d.test/corpus.json", () => respond({ ...CORPUS, site: { scope: "cited" }, channels: [] }), /publishes only its reports/],
+ ["https://e.test/corpus.json", () => respond({ ...CORPUS, channels: [] }), /lists no channels/],
+ ];
+ for (const [url, r, re] of cases) {
+ await assert.rejects(probeArchive(url.replace("/corpus.json", ""), { fetch: fakeFetch({ [url]: r }) }), (e: unknown) => e instanceof ArchiveProbeError && re.test((e as Error).message));
+ }
+ await assert.rejects(probeArchive("ftp://x", { fetch: fakeFetch({}) }), /not an archive's address/);
+ const down = (async () => {
+ throw new Error("ECONNREFUSED");
+ }) as FetchLike;
+ await assert.rejects(probeArchive("https://f.test", { fetch: down }), /did not answer: ECONNREFUSED/);
+});
+
+// ─── archiveChannelFacts (item 4): where a channel is, from corpus.json or its first record ───
+
+test("a spec-6 archive names a channel's platform and page in corpus.json: one read", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond(CORPUS) });
+ const facts = await archiveChannelFacts("https://stub.test", "alpha", { fetch: f });
+ assert.deepEqual(facts, { slug: "alpha", name: "Alpha", platform: "youtube", url: "https://www.youtube.com/@alpha", from: "corpus" });
+ assert.deepEqual(f.asked, ["https://stub.test/corpus.json"]);
+});
+
+test("an older archive: the platform from the first shard's record, read in order, the lowest page", async () => {
+ const f = fakeFetch({
+ "https://stub.test/corpus.json": () => respond({ ...CORPUS, spec: 5 }),
+ "https://stub.test/transcripts/beta/manifest.json": () => respond({ pageCount: 3, slugToPage: { v9: 2, v1: 1, v2: 1 } }),
+ "https://stub.test/transcripts/beta/page-0001.json": () =>
+ respond([{ id: "v1", title: "no url" }, { id: "v2", webpageUrl: "https://rumble.com/v2-x.html" }]),
+ });
+ const facts = await archiveChannelFacts("https://stub.test", "beta", { fetch: f });
+ assert.deepEqual(facts, { slug: "beta", name: "Beta", platform: "rumble", url: null, from: "record", sampleVideoUrl: "https://rumble.com/v2-x.html" });
+ assert.deepEqual(f.asked, [
+ "https://stub.test/corpus.json",
+ "https://stub.test/transcripts/beta/manifest.json",
+ "https://stub.test/transcripts/beta/page-0001.json",
+ ]);
+});
+
+test("a channel the archive does not list is refused; one with no readable record is unknown", async () => {
+ const f = fakeFetch({ "https://stub.test/corpus.json": () => respond({ ...CORPUS, spec: 5 }) });
+ await assert.rejects(archiveChannelFacts("https://stub.test", "nope", { fetch: f }), (e: unknown) => e instanceof ArchiveChannelError && /lists no channel "nope"/.test((e as Error).message));
+ const facts = await archiveChannelFacts("https://stub.test", "beta", { fetch: f });
+ assert.deepEqual(facts, { slug: "beta", name: "Beta", platform: null, url: null, from: "none" });
+});
diff --git a/common/lib/remoteArchives.ts b/common/lib/remoteArchives.ts
@@ -0,0 +1,288 @@
+// settings.remoteArchives — the PUBLISHED ARCHIVES this machine reads as
+// sources (demo epic D1: "a public archive is a first-class source").
+//
+// A published archive is any origin serving the machine contract at
+// `/corpus.json` (common/lib/corpus.ts): jeralyzer.pages.dev, or a friend's.
+// Connecting one is the operator typing its origin once; from then on the
+// editor's Create form, umtool's Source chip and the MCP all offer it, its
+// sweeps cite it, and its clip windows are fetched for its channels — with no
+// local corpus and no site.json made by hand.
+//
+// THE ONE RESOLVER. This module is the pure half (the shape, the sanitizer, the
+// origin rule, the env default); remoteArchives-server.ts reads corpus.json and
+// a channel's facts over HTTP. The editor (settings + its ops action), umtool's
+// source picker (umtool/lib/research/sources.ts) and the MCP's list_sources all
+// list archives through `connectedArchives`, so the three never disagree about
+// what is connected.
+//
+// NOT `settings.archives`: that key was taken first, by the page-import sources
+// (archive.today, release 37 lane F — lib/archives/settings.ts).
+//
+// Pure, browser-safe: no node:* import.
+
+import type { FieldDocs } from "./fieldDocs";
+
+export type RemoteArchive = {
+ // A slug, unique among the connected archives: the archive's own site id
+ // when its corpus.json names one, else made from its host.
+ id: string;
+ // The archive's origin, normalized (archiveOriginOf): http(s), no trailing
+ // slash, no query or fragment. `<origin>/corpus.json` is its contract.
+ origin: string;
+ // What its corpus.json calls it (site.title) when it was connected.
+ title: string;
+ // When it was connected, ISO-8601.
+ addedAt: string;
+};
+
+// A connected archive as the pickers list it: the stored ones, then the one the
+// environment names (TRANSCRIPT_SITE_URL) when no stored entry has its origin.
+export type ConnectedArchive = RemoteArchive & {
+ // From TRANSCRIPT_SITE_URL, not settings.json: listed, never written, and
+ // gone when the variable is.
+ fromEnv?: true;
+};
+
+export const REMOTE_ARCHIVE_FIELD_DOCS: FieldDocs<RemoteArchive> = {
+ id:
+ "A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is " +
+ "free, else one made from its host. What `pnpm ops archives` removes by.",
+ origin:
+ "The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is " +
+ "served. Sweeps over it cite it (`remote:<origin>`), whatever `generation.citationOrigin` says.",
+ title: "The archive's `site.title`, as its corpus.json said when it was connected.",
+ addedAt: "When it was connected (ISO-8601).",
+};
+
+const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+/** Whether `v` is an archive id (a lowercase slug, at most 64 characters). */
+export function isArchiveId(v: unknown): v is string {
+ return typeof v === "string" && ID_RE.test(v);
+}
+
+/**
+ * An archive origin, normalized — `https://host[/path]` with no trailing
+ * slash — or null when `v` is not one: not http(s), carries credentials, a
+ * query or a fragment, or does not parse. A path is kept (an archive may be
+ * served under one); `/corpus.json` typed on the end is taken off.
+ */
+export function archiveOriginOf(v: unknown): string | null {
+ if (typeof v !== "string") return null;
+ let s = v.trim();
+ if (!s) return null;
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `https://${s}`;
+ let u: URL;
+ try {
+ u = new URL(s);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (u.username || u.password || u.search || u.hash || !u.hostname) return null;
+ const p = u.pathname.replace(/\/corpus\.json$/i, "").replace(/\/+$/, "");
+ return `${u.protocol}//${u.host}${p}`;
+}
+
+/** The source handle a sweep over an archive names (mcp/src/sourceRegistry.ts). */
+export function archiveHandle(origin: string): string {
+ return `remote:${origin}`;
+}
+
+/** The origin a `remote:<origin>` handle names, normalized, or null for any other handle. */
+export function originOfHandle(handle: string | null | undefined): string | null {
+ const m = /^remote:(.+)$/s.exec(handle?.trim() ?? "");
+ return m ? archiveOriginOf(m[1]) : null;
+}
+
+/** A slug for an archive from its host (and path): `jeralyzer.pages.dev` → `jeralyzer-pages-dev`. */
+export function archiveIdFromOrigin(origin: string): string {
+ const bare = origin.replace(/^https?:\/\//, "").toLowerCase();
+ const slug = bare.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
+ return slug && ID_RE.test(slug) ? slug : "archive";
+}
+
+/**
+ * The id a newly connected archive gets: `preferred` (its corpus.json's site
+ * id) when that is a free slug, else one from its origin, made unique with a
+ * numeric suffix.
+ */
+export function freeArchiveId(origin: string, taken: Iterable<string>, preferred?: string | null): string {
+ const used = new Set(taken);
+ const base = preferred && ID_RE.test(preferred) ? preferred : archiveIdFromOrigin(origin);
+ if (!used.has(base)) return base;
+ for (let n = 2; ; n++) {
+ const id = `${base.slice(0, 60)}-${n}`;
+ if (!used.has(id)) return id;
+ }
+}
+
+/**
+ * settings.json's `remoteArchives`, sanitized: an array of entries each with a
+ * valid id and origin; a later duplicate (same origin or id) is dropped; a
+ * missing title becomes the origin's host, a missing date the epoch. Total over
+ * `unknown` (the settings reader never throws).
+ */
+export function sanitizeRemoteArchives(v: unknown): RemoteArchive[] {
+ if (!Array.isArray(v)) return [];
+ const out: RemoteArchive[] = [];
+ const ids = new Set<string>();
+ const origins = new Set<string>();
+ for (const raw of v) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
+ const r = raw as Record<string, unknown>;
+ const origin = archiveOriginOf(r.origin);
+ if (!origin || origins.has(origin)) continue;
+ const id = isArchiveId(r.id) ? r.id : null;
+ if (!id || ids.has(id)) continue;
+ const title = typeof r.title === "string" && r.title.trim() ? r.title.trim().slice(0, 200) : origin.replace(/^https?:\/\//, "");
+ const addedAt =
+ typeof r.addedAt === "string" && !Number.isNaN(Date.parse(r.addedAt)) ? new Date(r.addedAt).toISOString() : new Date(0).toISOString();
+ ids.add(id);
+ origins.add(origin);
+ out.push({ id, origin, title, addedAt });
+ }
+ return out;
+}
+
+type Env = Record<string, string | undefined>;
+
+/**
+ * Every connected archive, as the pickers list them: the stored ones in order,
+ * then — when it names an origin no stored entry has — TRANSCRIPT_SITE_URL's
+ * (the MCP's own remote, AGENTS.md "Working this repo with no local corpus"),
+ * marked `fromEnv`. That is the default a fresh clone gets: one archive, from
+ * the variable it was told to set.
+ */
+export function connectedArchives(stored: unknown, env: Env = typeof process !== "undefined" ? (process.env as Env) : {}): ConnectedArchive[] {
+ const list: ConnectedArchive[] = sanitizeRemoteArchives(stored);
+ const fromEnv = archiveOriginOf(env.TRANSCRIPT_SITE_URL);
+ if (fromEnv && !list.some((a) => a.origin === fromEnv)) {
+ list.push({
+ id: freeArchiveId(fromEnv, list.map((a) => a.id)),
+ origin: fromEnv,
+ title: fromEnv.replace(/^https?:\/\//, ""),
+ addedAt: new Date(0).toISOString(),
+ fromEnv: true,
+ });
+ }
+ return list;
+}
+
+/** The connected archive at `origin` (normalized first), or null. */
+export function findConnectedArchive(list: readonly ConnectedArchive[], origin: string | null | undefined): ConnectedArchive | null {
+ const want = archiveOriginOf(origin);
+ return want ? (list.find((a) => a.origin === want) ?? null) : null;
+}
+
+/**
+ * Why a remote-only channel's archive is not read any more, or null: the
+ * origin its config names (`remoteArchive`) is no longer among the connected
+ * archives — removed from settings since the channel was registered. Its
+ * record is not asked for and no window is fetched for it (demo epic D1
+ * re-review, item 6).
+ */
+export function disconnectedArchiveRefusal(origin: string | null | undefined, list: readonly ConnectedArchive[]): string | null {
+ if (!origin) return null;
+ if (findConnectedArchive(list, origin)) return null;
+ return `its archive ${origin} is no longer connected — connect it again (the editor's /sites, "Connected archives") to fetch its windows`;
+}
+
+/**
+ * The marker a remote-only channel's whole-recording refusal starts with
+ * (controller/remoteOnlyChannel.ts wholeRecordingRefusal): umtool's chain
+ * looks for it to offer the one-press override (`allowWholeRecording`).
+ */
+export const WHOLE_RECORDING_REFUSED = "whole recording refused:";
+
+// ─── An archive is untrusted input (demo epic D1 review, blocker 2) ───
+
+// The platforms a clip window of an archive's channel may be fetched from:
+// the video platforms, each recognised by its HOST (lib/detectPlatform.mjs).
+// Never the post platforms, and never xenforo, which is recognised by a
+// thread path on any host.
+export const RECORD_PAGE_PLATFORMS = ["youtube", "rumble", "odysee", "twitch", "kick", "archiveorg", "bitchute"] as const;
+
+// Each platform's own domains, matched EXACTLY or as a parent (`host === d` or
+// `host` ends in `.d`). lib/detectPlatform.mjs answers "which platform is
+// this", loosely (`host.endsWith("youtube.com")` is true of evilyoutube.com);
+// here the question is "may this machine fetch from that host", so the answer
+// it gives is checked against this table (demo epic D1 re-review, must-fix 1).
+export const RECORD_PAGE_HOSTS: Record<(typeof RECORD_PAGE_PLATFORMS)[number], readonly string[]> = {
+ youtube: ["youtube.com", "youtu.be"],
+ rumble: ["rumble.com"],
+ odysee: ["odysee.com"],
+ twitch: ["twitch.tv"],
+ kick: ["kick.com"],
+ archiveorg: ["archive.org"],
+ bitchute: ["bitchute.com"],
+};
+
+/** Whether `host` is one of `platform`'s own domains or a subdomain of one. */
+export function isPlatformHost(platform: string, host: string): boolean {
+ const domains = (RECORD_PAGE_HOSTS as Record<string, readonly string[] | undefined>)[platform];
+ const h = host.toLowerCase().replace(/\.$/, "");
+ return !!domains && domains.some((d) => h === d || h.endsWith(`.${d}`));
+}
+
+// A page URL is refused when it carries a backslash, whitespace or a control
+// character ANYWHERE — before it is parsed. URL parsers disagree about exactly
+// these: Node reads `https://youtube.com\@evil.example/` as host youtube.com
+// (a backslash is a slash to it), Python's urlsplit — what yt-dlp reads it
+// with — as host evil.example; Node drops a tab or newline inside a host and
+// trims the ends. So the host judged here would not be the host fetched
+// (demo epic D1 re-check, the parser differential).
+const UNSAFE_PAGE_CHARS = /[\\\s\u0000-\u001f\u007f-\u009f\u00a0\u1680\u2000-\u200f\u2028-\u202f\u205f-\u2060\u3000\ufeff]/;
+
+export type RecordPage = { href: string; platform: string } | { refused: string };
+
+/**
+ * A remote-only channel's page URL — an archive record's `webpageUrl`, or one
+ * an ask carried for it — judged, and NORMALISED: `{href, platform}` when a
+ * window may be fetched from it, `{refused}` with the sentence when not. The
+ * archive is someone else's JSON: a URL is accepted only when it has no
+ * backslash, whitespace or control character, is http(s) with no credentials,
+ * its host names a known video platform, and that is the channel's own
+ * platform when the channel has one. Refused before any request.
+ *
+ * `href` is what the parser that judged the host wrote back (`new URL().href`:
+ * the host lowercased, a default port dropped, an IDN in punycode), and it is
+ * THE ONLY string a caller hands on — never the one it was given.
+ */
+export function recordPage(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): RecordPage {
+ if (!url) return { refused: "no page URL" };
+ if (UNSAFE_PAGE_CHARS.test(url)) {
+ return { refused: `${JSON.stringify(url)} is not a page URL: it carries a backslash, whitespace or a control character, which URL parsers read differently — the archive's page URL is not fetched` };
+ }
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { refused: `"${url}" is not a page URL` };
+ }
+ if ((u.protocol !== "https:" && u.protocol !== "http:") || u.username || u.password) return { refused: `${u.protocol}//${u.host} is not a page URL a window is fetched from` };
+ const href = u.href;
+ const platform = detect(href);
+ if (!platform || !(RECORD_PAGE_PLATFORMS as readonly string[]).includes(platform) || !isPlatformHost(platform, u.hostname)) {
+ return { refused: `${u.host} is not a video platform's host (${RECORD_PAGE_PLATFORMS.join(", ")}): the archive's page URL is not fetched` };
+ }
+ if (channelPlatform && channelPlatform !== platform) {
+ return { refused: `${u.host} is ${platform}, and the channel is ${channelPlatform}'s: the archive's page URL is not fetched` };
+ }
+ return { href, platform };
+}
+
+/** Why a remote-only channel's page URL is not fetched, or null when it may be (recordPage's sentence). */
+export function recordPageRefusal(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): string | null {
+ const page = recordPage(url, channelPlatform, detect);
+ return "refused" in page ? page.refused : null;
+}
+
+/** Whether `url` is on `origin`'s own scheme, host and port. */
+export function sameOrigin(url: string, origin: string): boolean {
+ try {
+ return new URL(url).origin === new URL(origin).origin;
+ } catch {
+ return false;
+ }
+}
diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts
@@ -29,6 +29,7 @@ import {
iterationDir,
iterationUsd,
lineage,
+ lineageSource,
listIterations,
makeCurrent,
parseIteration,
@@ -285,3 +286,19 @@ test("an article may not be called `new` (umtool's /articles/new is a page)", as
/reserved/,
);
});
+
+// demo epic D1: a sweep over a published archive records it; its revisions read it.
+test("a sweep's source is kept in its scope and inherited down its lineage", async () => {
+ const paths = store();
+ await createIteration("arc", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "remote:https://stub.test" } }, paths, NOW);
+ await done(paths, "arc", 1, doc("arc"));
+ await createIteration("arc", { kind: "revise-report", model: "m", parent: 1, feedback: "tighter" }, paths, NOW);
+ assert.equal(await lineageSource("arc", 2, paths), "remote:https://stub.test");
+ assert.equal((await readIteration("arc", 1, paths))?.scope?.source, "remote:https://stub.test");
+ // A sweep of the editor's own build has none.
+ await createIteration("own", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"] } }, paths, NOW);
+ assert.equal(await lineageSource("own", 1, paths), null);
+ assert.equal(await lineageSource("nope", 1, paths), null);
+ // Not a handle: refused at the schema.
+ await assert.rejects(createIteration("bad", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "https://stub.test" } }, paths, NOW));
+});
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -144,6 +144,10 @@ export const iterationScopeSchema = z.looseObject({
ids: z.array(z.string().min(1)).optional(),
// The triage run this sweep escalates (umtool R6): reports/.triage/<owner>/<k>/.
triage: z.looseObject({ owner: z.string().min(1), k: z.number().int().positive() }).optional(),
+ // The corpus the sweep read when it was not the editor's own build (demo epic
+ // D1): a handle, `remote:<archive origin>` or `hub:<url>`. Its revisions,
+ // media drafts and video chain read and cite the same one (lineageSource).
+ source: z.string().regex(/^(local|remote|hub):\S+/).optional(),
});
export type IterationScope = z.infer<typeof iterationScopeSchema>;
@@ -380,6 +384,19 @@ export async function lineage(id: string, n: number, paths: StorePaths = getPath
return out;
}
+// The corpus handle an iteration's lineage read (demo epic D1): the newest
+// `scope.source` from n back to its root, or null — the editor's own build.
+export async function lineageSource(id: string, n: number, paths: StorePaths = getPaths()): Promise<string | null> {
+ let at: number | null = n;
+ while (at !== null) {
+ const it: Iteration | null = await readIteration(id, at, paths);
+ if (!it) return null;
+ if (it.scope?.source) return it.scope.source;
+ at = it.parent;
+ }
+ return null;
+}
+
// A file of an iteration as text, or null when it has none.
export async function readIterationFile(
id: string,
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -48,6 +48,7 @@ import {
GENERATION_VERDICT_BAR_FIELD_DOCS,
GENERATION_VERDICT_WINDOW_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
+ REMOTE_ARCHIVE_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
XENFORO_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -218,6 +219,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS },
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
+ remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }],
savedVideoBackup: [
{
path: "savedVideoBackup",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -33,6 +33,7 @@ import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
import type { ArchivesSettings } from "./archives/settings";
+import type { RemoteArchive } from "./remoteArchives";
import type { ClipsSettings } from "./clipSettings";
import type { JobsSettings } from "./jobsSettings";
import type { ServiceCookiesSettings } from "./serviceCookieSettings";
@@ -115,6 +116,8 @@ type PreSchemaSiteSettings = {
// How archive.org files are fetched: BitTorrent with seeding, else direct.
archiveOrg: ArchiveOrgFetchSettings;
archives: ArchivesSettings;
+ // The connected published archives (demo epic D1).
+ remoteArchives: RemoteArchive[];
// The publish lane (release 18).
publish: PublishSettings;
// The recurring reports' lane (umtool R5).
@@ -181,6 +184,7 @@ test("SiteSettings keeps its 47 fields, in file order", () => {
"attribution",
"archiveOrg",
"archives",
+ "remoteArchives",
"publish",
"reportSchedule",
"seeder",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -82,6 +82,7 @@ export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSetting
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
import { sanitizeVoice, type VoiceSettings } from "./voiceSettings";
import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
+import { sanitizeRemoteArchives, type RemoteArchive } from "./remoteArchives";
import { sanitizeClips, type ClipsSettings } from "./clipSettings";
import { sanitizeJobs, type JobsSettings } from "./jobsSettings";
import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings";
@@ -110,6 +111,7 @@ export {
type VoiceSettings,
} from "./voiceSettings";
export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
+export { REMOTE_ARCHIVE_FIELD_DOCS, type RemoteArchive } from "./remoteArchives";
export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings";
export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings";
export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings";
@@ -2046,6 +2048,9 @@ export const siteSettingsSchema = z.object({
archives: settingsField((v): ArchivesSettings => sanitizeArchives(v)).describe(
"The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings.",
),
+ remoteArchives: settingsField((v): RemoteArchive[] => sanitizeRemoteArchives(v)).describe(
+ "The PUBLISHED ARCHIVES this machine reads as sources (demo epic D1, lib/remoteArchives.ts): each a site serving `/corpus.json`, connected once by its origin (the editor's /sites → Connect an archive, umtool's Source chip, or `pnpm ops archives`). Create, research and the MCP offer each one; a sweep over one cites that origin; a clip window cited from one registers a REMOTE-ONLY channel (CHANNEL.md `remoteOnly`) to fetch it. TRANSCRIPT_SITE_URL, when set and not listed here, is offered too without being written. Empty = none. See RemoteArchive.",
+ ),
publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe(
"The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.",
),
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -11,7 +11,7 @@ import {
type SocialLink,
} from "./settings";
import { socialLinksForSave } from "./socialLinks";
-import { parseChannelConfig } from "./channelConfig";
+import { isRemoteOnlyChannel, parseChannelConfig } from "./channelConfig";
import { isXSearchChannel } from "./xSearch/config";
import { readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
import {
@@ -231,6 +231,25 @@ function storedSocialLinks(file: string): SocialLink[] {
export const X_SEARCH_NOT_ON_A_SITE = (slug: string) =>
`${slug} is an X search channel: it is never put on a site.`;
+export const REMOTE_ONLY_NOT_ON_A_SITE = (slug: string) =>
+ `${slug} is a remote-only channel (a connected archive's clip windows): it is never put on a site.`;
+
+// The first member of `site` (or of its cited scope) that is a remote-only
+// channel (demo epic D1), by its config.json — or null.
+export function remoteOnlyChannelOnSite(
+ site: Pick<Site, "channels" | "citedChannels">,
+ paths: Paths,
+): string | null {
+ if (!paths.channelsDir) return null;
+ const slugs = [...site.channels.map((c) => c.slug), ...(site.citedChannels ?? []).map((c) => c.slug)];
+ for (const slug of slugs) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug)) continue;
+ const raw = readJsonFileSync(path.join(paths.channelsDir, slug, "config.json"));
+ if (raw.ok && isRemoteOnlyChannel(parseChannelConfig(raw.value))) return slug;
+ }
+ return null;
+}
+
// The first member of `site` (or of its cited scope) that is an X search
// channel, by its config.json — or null. One small read per member.
export function xSearchChannelOnSite(
@@ -278,6 +297,9 @@ export async function writeSite(
// the one writer every site edit goes through.
const searchChannel = xSearchChannelOnSite(site, paths);
if (searchChannel) throw new Error(X_SEARCH_NOT_ON_A_SITE(searchChannel));
+ // Nor a remote-only channel (demo epic D1): it has no corpus to publish.
+ const remoteOnly = remoteOnlyChannelOnSite(site, paths);
+ if (remoteOnly) throw new Error(REMOTE_ONLY_NOT_ON_A_SITE(remoteOnly));
// undefined socialLinks = inherit the global default; only validate/persist a
// key when the site explicitly overrides (an array, even empty).
// A link whose SVG is unchanged from the file on disk is kept as it is; a new
diff --git a/common/lib/siteRemoteOnly.test.ts b/common/lib/siteRemoteOnly.test.ts
@@ -0,0 +1,41 @@
+// demo epic D1: a remote-only channel is never put on a site (writeSite, the
+// one writer every site edit goes through).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "site-remote-only-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+
+const { getPaths } = await import("./paths");
+const { writeSite, REMOTE_ONLY_NOT_ON_A_SITE } = await import("./site");
+const paths = getPaths();
+
+async function channel(slug: string, config: Record<string, unknown>) {
+ await mkdir(path.join(paths.channelsDir, slug), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ name: slug, handling: "youtube", ...config }));
+}
+
+test("no site may carry a remote-only channel, as a member or a cited channel", async () => {
+ await channel("own", { url: "https://www.youtube.com/@own" });
+ await channel("remote", { platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" });
+ const site = {
+ siteId: "demo-site",
+ siteTitle: "Demo",
+ siteDescription: "",
+ headerTitle: "Demo",
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [{ slug: "own", groupId: "default" }],
+ };
+ await writeSite(site as never, paths);
+ await assert.rejects(writeSite({ ...site, channels: [...site.channels, { slug: "remote", groupId: "default" }] } as never, paths), {
+ message: REMOTE_ONLY_NOT_ON_A_SITE("remote"),
+ });
+ await assert.rejects(writeSite({ ...site, citedChannels: [{ slug: "remote" }] } as never, paths), { message: REMOTE_ONLY_NOT_ON_A_SITE("remote") });
+});
diff --git a/common/package.json b/common/package.json
@@ -42,6 +42,7 @@
"./lib/atomicFile.mjs": "./lib/atomicFile.mjs",
"./lib/cueWiden.mjs": "./lib/cueWiden.mjs",
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
+ "./lib/projectsRoot.mjs": "./lib/projectsRoot.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/recordingClock.mjs": "./lib/recordingClock.mjs",
"./lib/recordingClock-read.mjs": "./lib/recordingClock-read.mjs",
diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts
@@ -342,7 +342,7 @@ test("a cited site: exactly its reports, moments, cited media and contract — t
assert.ok(!JSON.stringify(readJson(pub("m", "index.json"))).includes("40.00"));
});
-test("a cited site's contract: site.json without channels, corpus.json scope cited at spec 5, the cited llms.txt and sitemap", () => {
+test("a cited site's contract: site.json without channels, corpus.json scope cited at spec 6, the cited llms.txt and sitemap", () => {
const site = readJson<{ siteId: string; channels: unknown[]; pwa: boolean }>(pub("site.json"));
assert.equal(site.siteId, "cited");
assert.deepEqual(site.channels, []);
@@ -355,7 +355,7 @@ test("a cited site's contract: site.json without channels, corpus.json scope cit
reports?: { index: string; count: number };
}>(pub("corpus.json"));
assert.equal(corpus.spec, CONTRACT.corpusSpec);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.site.id, "cited");
assert.equal(corpus.site.scope, "cited");
assert.equal(corpus.site.audience, "public");
@@ -640,7 +640,7 @@ test("a full site with reports keeps its corpus and links each moment into it",
const corpus = readJson<{ spec: number; site: { scope?: string; audience?: string }; channels: unknown[]; reports?: { count: number } }>(
pub("corpus.json"),
);
- assert.equal(corpus.spec, 5);
+ assert.equal(corpus.spec, 6);
assert.equal(corpus.site.scope, undefined);
assert.equal(corpus.site.audience, undefined);
assert.equal(corpus.channels.length, 2);
diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts
@@ -181,3 +181,13 @@ test("channelVolumeOf: no mediaDir is internal, a named root wins, else unnamed"
label: "Big disk",
});
});
+
+test("a remote-only channel's row says so, with its archive, and is not 'manual dl' (demo epic D1)", () => {
+ const remote = buildChannelRowView(
+ input({ config: { handling: "youtube", name: "Remote", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" } as ChannelConfig }),
+ );
+ assert.equal(remote.remoteOnly, "https://stub.test");
+ assert.equal(remote.manualDownloads, false);
+ assert.equal(remote.hasUrl, false);
+ assert.equal(buildChannelRowView(input()).remoteOnly, null);
+});
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -1,5 +1,5 @@
import { channelDownloadsAreManual } from "../lib/manualDownloads";
-import { isSocialChannel, type ChannelConfig } from "../lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel, type ChannelConfig } from "../lib/channelConfig";
import type { ChannelSnapshot } from "../controller/channelSnapshot";
import type { ChannelMediaLocation } from "../lib/channelMedia";
import { mediaHoldText } from "../lib/channelMediaHold";
@@ -122,6 +122,10 @@ export type ChannelRowView = {
// the channel by design and its `work.undownloaded` is 0 — the rack says so,
// so a long, mostly undownloaded listing is not read as a stalled channel.
manualDownloads: boolean;
+ // A REMOTE-ONLY channel (lib/channelConfig.ts isRemoteOnlyChannel, demo epic
+ // D1): the archive it holds clip windows for — its origin — or null for any
+ // other channel. The list says so; nothing syncs or downloads it.
+ remoteOnly: string | null;
// WHICH VOLUME THE MEDIA IS ON, as an id a filter can name: a location id,
// "internal" for the corpus volume, or "" for a mediaDir under a root nobody
// named. (The text is on the corpus volume whatever this says.)
@@ -234,7 +238,8 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
}
: null,
mediaHold: i.media ? mediaHoldText(i.media.status) : null,
- manualDownloads: channelDownloadsAreManual(i.config),
+ manualDownloads: channelDownloadsAreManual(i.config) && !isRemoteOnlyChannel(i.config),
+ remoteOnly: isRemoteOnlyChannel(i.config) ? (i.config.remoteArchive ?? "") : null,
volumeId: i.volume.id,
volumeLabel: i.volume.label,
mediaBytes: snap?.totalMediaBytes ?? null,
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,6 +3,18 @@
## [Unreleased]
- **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). A log holds 20,000 calls or 32 MB; past that the panel says the log is full, and later calls are not recorded. The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run.
- **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, anything shaped like a credential (a URL's user and password, a token in a query string, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, and a failed call's message has its URLs and addresses removed. Links are kept.
+- **A published archive is a source: connect it once, sweep it, and fetch its cited clips with no local corpus.** A fresh clone pointed at jeralyzer.pages.dev could search it through the MCP and do nothing else: Create had no corpus to offer, and every clip of a channel the editor did not archive was a 404 `Channel "<slug>" not found`. An archive is now connected by its origin — `/sites` → **Connected archives**, or `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev"}'` (`"dryRun": true` reads it and writes nothing; `pnpm ops get archives` lists them) — and kept in `settings.remoteArchives`. `TRANSCRIPT_SITE_URL`'s archive is offered without being connected, so a clone set up as AGENTS.md says starts with one. Create offers each connected archive as a sweep's source, preselected when this machine has no corpus of its own, the MCP's `list_sources` lists them and `generate` passes the choice. A sweep over an archive cites that archive's origin, whatever `generation.citationOrigin` says, and its revisions, drafts and refreshes inherit it. A clip window cited from one registers its channel **remote-only** on first need (`fetch-windows` and `fetch-window` take `"archive"`, and the MCP's `fetch_clip` names it): a `config.json` and nothing else, shown as "remote only" in the channel list, skipped by every sync, lane, scan and site build, and left out of the site form's channel picker. On a whole-recording platform (Rumble) a window means downloading the whole recording, which nobody planned for a channel that is not archived here: it is refused with the recording's length and estimated size until the ask carries `"allowWholeRecording": true`. The archive's documents are cached on disk by its build (512 MB by default), read one at a time and paced. `corpus.json` is spec 6 (the export's changelog): each channel names its platform and its page there; an older archive's platform is read from a record's `webpageUrl`.
+- **A connected archive is untrusted input.** umtool can connect one and is open on the LAN, and everything an archive serves is someone else's JSON. An archive on this machine or its network — loopback, private, link-local and CGNAT addresses in any spelling (decimal, hex, IPv4 carried inside IPv6), a `.local`/`.internal`/`.lan` name, or a name that resolves to one — is refused at connect, before anything is asked of it, unless the editor runs with `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1` or the origin is `TRANSCRIPT_SITE_URL`'s or already in `settings.json`; the check is made once, at connect. Its documents are read on its own origin only: a redirect elsewhere is refused unfollowed, a manifest its `corpus.json` names on another origin is not followed, and no document past 32 MB is read or kept. A record's page URL is fetched only when its host is its channel's video platform's own domain or a subdomain (`evilyoutube.com` and `youtube.com.evil.example` are not YouTube); a URL carrying a backslash, whitespace or a control character is refused unparsed, because Node and yt-dlp's Python read its host differently; and what reaches yt-dlp is the URL the check parsed, never the archive's own string. A remote-only channel whose archive was removed from settings is refused before its record is read.
+- **umtool: the Source chip connects an archive, and an article swept over one is cut from it.** The Source chip takes an archive's address, reads it and connects it through the editor; a connected archive is offered as the source of **Article from a question** and of a new article, first when this machine has no corpus. The chain of an article swept over an archive asks the editor for its windows with the archive named and each record's page URL, so the cited channels are registered remote-only and fetched; a manifest with no sweep naming an origin takes the archive as its QR origin. A Rumble window fails the step with every recording's size, nothing fetched, until **Fetch the whole recordings** (`umtool chain <article> <n> --allow-whole-recording`). `--stop-before-render` ends Draft everything before the voices, and its new `cut-windows` step fetches the drafted cut's windows, asking the editor only for those not on disk. The cue walk, the link check and a source's build identity read an archive under the same rules as the editor (its own origin, 32 MB), and a chain whose archive is no longer connected stops and says to connect it again.
+- **umtool e2e: the Inbox spec waits for the list after a Park, Mute or Undo.** Three runs failed where the list had not changed 5 seconds after Reactivate, Unmute or Undo. In each the write had been saved and the page's refresh had been asked for; the server was slow for those seconds (a neighbouring suite was building) and the check gave up first. The first look at the list after such a write now waits up to 20 seconds. Nothing in the app changed: the lifecycle and the mutes are read from disk on every render, and the rail's count is memoised for 10 seconds by design and cleared by those writes.
+- **umtool: the trail no longer draws a 0 lb point for a row with no number.** A measure event whose value was empty was read as 0 and plotted at the foot of the trail. Such a row is now left off; a real 0 is still drawn.
+- **umtool: `posts attach` finds captures in the archive too.** On a project with its own channels tree (a `.shadow-channels`), `umtool posts attach` and `posts repeats` looked for a post's capture only there, so media captured into the real archive's `channels/<slug>/posts-media/<id>/` was not seen. They now look in the project's tree first and then the archive's, as the other readers do. The archive is only read: the files are copied into the project as before. `--dry-run` prints which tree each file would come from. A capture whose file name is not a plain name (`../../x`, `a/b`, `..`) is refused before any file is read or any folder made.
+- **umtool: an entry's chapter name is set from a terminal.** An entry's `chapter` names it in the chapter list (the YouTube text, `umtool export --format chapters`) in place of its on-screen title, and it could only be written by editing the manifest by hand. `umtool set <p> <entry> chapter='The weigh-in'` writes it for any entry (a clip, a post item, a still), `chapter=` clears it, and `--take <t>` writes it on that take alone. One line, at most 100 characters.
+- **umtool: a windowed take preview no longer fails on an effect that names a clip outside the window.** `umtool take <p> --id <t> --preview --at S --dur S` on a cut with `render.chrome.fx.glitch.clips` or `fx.thenNow.pairs` was refused with "names k06, which is not a clip of the cut". The window's manifest now keeps only the named clips inside it (a glitch's only when a clip stands right before it in the window, a then/now pair only with both ends), as it already did for markers and claim checks; an effect left naming no clip is off in that window. A glitch in another mode (`on: "year"`) does not read its list and is left as it is. The same for `fx.kineticQuote.clips` and `fx.redact.clips`.
+- **umtool: `quote-check` works on a project whose `out/` is on the media drive.** The check asked the editor to write its word files under `<project>/out/quote-check/`; when `out/` is a link onto a media drive, that is inside the corpus and the editor refuses to write there, so every clip failed. The work files now go to `<project>/.quote-check/`, and if the editor refuses that too (the project itself is inside the corpus) to `<reports>/.umtool/quote-check/<project>/`, then `~/.cache/umtool/quote-check/<project>/`. The rows are still the project's `quote-check.json`; the editor's refusal is unchanged. A directory the editor refuses is removed again if the check made it, so no empty `.quote-check/` is left on the media drive.
+- **umtool: the words under the promise clock's REFUNDED stamp can be the record's own.** The stamp always read "by <date> · no video" under REFUNDED or WITHDRAWN, whatever the outcome row said. A `promise_outcome` row may now carry `stampNote` (`umtool ledger <p> set <row> --stampNote "by her account · no receipt"`, `--stampNote null` to take it off): it is the stamp's second line, and the one-line strip over a post's card shows its first clause. Without one the words are as before. `umtool lint` warns when a note is longer than the stamp's line holds (26 characters).
+- **umtool: a loss goal no longer takes its base from a weight said years before.** A goal such as "lose 100" is shown against the latest weight he had given by then, however old: on the weight video that put "(FROM 368)" on a goal set eight years after he said 368. `deck.goals.baseMaxDays` (unset: as before) keeps a base only when its weight was said at most that many days before the goal; an older one is no base, so the note carries no "(FROM …)" and the dial draws no goal weight or tick from it. `umtool look <p> deck.goals.baseMaxDays=365`, and `umtool look` now takes `--take <t>` for the deck's keys, which sets them on that take alone.
+- **umtool: the dial's finale no longer shows the callout's labels over its hub.** With `deck.dial.rememberedAs: "callout"` the finale's dial drew every remembered weight's label box and the ghost needle and never hid them, so the boxes sat on the hub for the whole finale (take rev9-a9). They are hidden there now; the rim's marker and flag for the last remembered weight stay.
- **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it** (its synthetic preset's voice), which plays the read kept from before when there is one and asks the editor only when pressed. Cancel stops the editor's job too. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page))
- **umtool: a convert made from a take uses its character's voice, not the editor's default.** On 11 Nov `umtool posts narrate <p> <item> --derive <n> --op convert` with no flags made a take in the wrong voice: it asked the editor with nothing, and the editor used its own default target. A convert now takes its engine, stock voice, pitch and semitones from the recorded preset of the character the read is made as (`--as`, else the item's own, this video's for the author, the cast's, the narrator); a flag overrides its own key. With no character and no `--voice` it is refused in one sentence. The post bench's **run AI on take** does the same on the server.
- **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published.
diff --git a/editor/app/api/media/fetch-window/route.remote.test.ts b/editor/app/api/media/fetch-window/route.remote.test.ts
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/media/fetch-window/route.remote.test.ts"
+//
+// demo epic D1: the single window (the MCP's fetch_clip over a remote source)
+// of a channel this editor does not hold, named with its connected archive —
+// registered remote-only; its Rumble whole recording refused with the size
+// (409, no job). The archive is a fake fetch.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-remote-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+delete process.env.TRANSCRIPT_SITE_URL;
+// yt-dlp is a fake that writes down what it was asked for: no test here reaches a platform.
+const ARGS_LOG = path.join(ROOT, "argv.jsonl");
+const YTDLP = path.join(ROOT, "fake-ytdlp.mjs");
+await writeFile(
+ YTDLP,
+ `#!/usr/bin/env node
+import { appendFileSync, writeFileSync } from "node:fs";
+const args = process.argv.slice(2);
+appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n");
+const o = args.indexOf("-o");
+if (o >= 0) writeFileSync(args[o + 1], "mp4");
+`,
+);
+await chmod(YTDLP, 0o755);
+process.env.YTDLP_BIN = YTDLP;
+process.env.E2E_CLIP_WINDOW_GAP_MS = "0";
+const ORIGIN = "https://stub.test";
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0, remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }));
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ channels: [
+ { slug: "rb-remote", name: "RB Remote", platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rb-remote/manifest.json` } },
+ { slug: "yt-evil", name: "Evil", platform: "youtube", manifests: { transcripts: `${ORIGIN}/transcripts/yt-evil/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/yt-evil/manifest.json`]: { slugToPage: { e1: 0, d1: 0, d2: 0, n1: 0 } },
+ [`${ORIGIN}/transcripts/yt-evil/page-0000.json`]: [
+ { id: "e1", webpageUrl: "http://169.254.169.254/latest/meta-data/" },
+ // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential).
+ { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" },
+ { id: "d2", webpageUrl: "https://you\ttube.com/watch?v=d2" },
+ // The platform's own page, spelled loudly.
+ { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" },
+ ],
+ [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { slugToPage: { rb9: 0 } },
+ [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 600, webpageUrl: "https://rumble.com/vrb9-x.html" }],
+};
+const asked: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ asked.push(url);
+ return url in DOCS ? new Response(JSON.stringify(DOCS[url]), { status: 200 }) : new Response("nope", { status: 404 });
+}) as typeof fetch;
+const { POST } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const post = async (body: Record<string, unknown>) => {
+ const res = await POST(
+ new Request("http://localhost/api/media/fetch-window", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as { error?: string } };
+};
+
+test("a single window of an archive's channel registers it remote-only, and its Rumble whole recording is refused with the size", async () => {
+ const r = await post({ channelSlug: "rb-remote", videoId: "rb9", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN });
+ assert.equal(r.status, 409, r.json.error);
+ assert.match(r.json.error ?? "", /^whole recording refused: Rumble windows are cut from the WHOLE recording, and rb-remote is a remote-only channel: rb-remote\/rb9 is 10:00 long/);
+ const config = JSON.parse(await readFile(path.join(ROOT, "channels", "rb-remote", "config.json"), "utf8"));
+ assert.equal(config.remoteOnly, true);
+ assert.equal(config.remoteArchive, ORIGIN);
+});
+
+test("without its archive named, a channel not held is a 404 as before", async () => {
+ const r = await post({ channelSlug: "nope-remote", videoId: "x1", from: 10, to: 20, requestedBy: "test", reason: "a test" });
+ assert.equal(r.status, 404);
+});
+
+test("a single window whose archive record points at a non-platform host is refused (400), nothing fetched", async () => {
+ const r = await post({ channelSlug: "yt-evil", videoId: "e1", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN });
+ assert.equal(r.status, 400);
+ assert.match(r.json.error ?? "", /^yt-evil\/e1: 169\.254\.169\.254 is not a video platform's host/);
+});
+
+test("a page URL two parsers read differently is refused (400) before any request, from the record or from the ask", async () => {
+ const ask = (videoId: string, webpageUrl?: string) => post({ channelSlug: "yt-evil", videoId, from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN, ...(webpageUrl ? { webpageUrl } : {}) });
+ for (const r of [
+ await ask("d1"),
+ await ask("d2"),
+ await ask("a1", "https://youtube.com\\@evil.example/watch?v=x"),
+ await ask("a2", "https://youtube.com\\@127.0.0.1/x"),
+ await ask("a3", "https://rumble.com\\.evil.example/v1"),
+ await ask("a4", "https://you\ttube.com/watch?v=x"),
+ ]) {
+ assert.equal(r.status, 400, r.json.error);
+ assert.match(r.json.error ?? "", /carries a backslash, whitespace or a control character/);
+ }
+ assert.equal(await readFile(ARGS_LOG, "utf8").catch(() => ""), "", "yt-dlp was never run");
+});
+
+test("what reaches yt-dlp is the URL the check parsed, written back — never the record's own string", async () => {
+ const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+ const res = await POST(
+ new Request("http://localhost/api/media/fetch-window", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify({ channelSlug: "yt-evil", videoId: "n1", from: 10, to: 20, requestedBy: "test", reason: "a test", archive: ORIGIN }),
+ }),
+ );
+ const body = (await res.json()) as { jobId?: string; error?: string };
+ assert.equal(res.status, 202, body.error);
+ const reg = getRegistry();
+ for (let i = 0; i < 200; i++) {
+ const s = reg.get(body.jobId!)?.status;
+ if (s !== "queued" && s !== "running") break;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ const runs = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").map((l) => JSON.parse(l) as string[]);
+ assert.ok(runs.length > 0, "yt-dlp was asked");
+ for (const args of runs) {
+ assert.equal(args.at(-1), "https://www.youtube.com/watch?v=n1");
+ assert.equal(args.some((a) => /YouTube|:443/.test(a)), false, "the record's own spelling is nowhere in the command");
+ }
+});
+
+// LAST: it disconnects the archive for the rest of the file.
+test("a remote-only channel whose archive was removed from settings is refused (400), and the archive is not read", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] }));
+ asked.length = 0;
+ const r = await post({ channelSlug: "rb-remote", videoId: "rb9", from: 10, to: 20, requestedBy: "test", reason: "a test" });
+ assert.equal(r.status, 400, r.json.error);
+ assert.match(r.json.error ?? "", /^rb-remote is a remote-only channel, and its archive https:\/\/stub\.test is no longer connected/);
+ assert.deepEqual(asked, [], "nothing asked of an archive that is not connected");
+});
diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts
@@ -18,6 +18,20 @@ import {
type FetchMediaOutcome,
} from "../../../channels/[slug]/videos/[id]/videoActions";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { wholeRecordingFor } from "yt-dlp-transcript-common/controller/fetchWindows";
+import {
+ archiveRecordOf,
+ ensureRemoteOnlyChannel,
+ wholeRecordingRefusal,
+} from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+
export const dynamic = "force-dynamic";
// SOURCE MEDIA FOR ANOTHER TOOL, fetched through the editor's managed download
@@ -59,6 +73,10 @@ type Body = {
full?: unknown;
maxHeight?: unknown;
storedUrl?: unknown;
+ // demo epic D1: the connected archive the clip is cited from, and the
+ // allowance for a remote-only channel's whole recording.
+ archive?: unknown;
+ allowWholeRecording?: unknown;
};
const str = (v: unknown): string | undefined =>
@@ -186,6 +204,62 @@ export async function POST(request: Request) {
);
}
+ // A CONNECTED ARCHIVE'S CLIP (demo epic D1; `archive`, the MCP's fetch_clip
+ // over a remote source): a channel this editor does not hold is registered
+ // remote-only of it (controller/remoteOnlyChannel.ts), as fetch-windows does.
+ // A remote-only channel's page URL is the ask's, else its archive's record;
+ // its whole recording — `full`, or a window on a whole-recording platform —
+ // is refused with the recording's size (409) unless `allowWholeRecording`.
+ let webpageUrl = str(body.webpageUrl);
+ {
+ const paths = getPaths();
+ const getJson = cachedArchiveGetJson();
+ const named = str(body.archive);
+ let config = await readChannelConfig(paths, channelSlug);
+ if (!config && named) {
+ const archive = findConnectedArchive(connectedArchives(getSettings().remoteArchives), named);
+ if (archive) {
+ try {
+ config = (await ensureRemoteOnlyChannel(paths, channelSlug, archive, { getJson })).config;
+ } catch (e) {
+ return NextResponse.json({ error: `Channel "${channelSlug}" not found, and it could not be registered from ${archive.origin}: ${(e as Error).message}` }, { status: 404 });
+ }
+ }
+ }
+ if (config && isRemoteOnlyChannel(config)) {
+ // An archive removed from settings is not read any more, for a channel
+ // registered while it was connected either.
+ const gone = disconnectedArchiveRefusal(config.remoteArchive, connectedArchives(getSettings().remoteArchives));
+ if (gone) return NextResponse.json({ error: `${channelSlug} is a remote-only channel, and ${gone}` }, { status: 400 });
+ const record = config.remoteArchive ? await archiveRecordOf(config.remoteArchive, channelSlug, videoId, { getJson }).catch(() => null) : null;
+ webpageUrl ||= record?.webpageUrl;
+ // An archive is untrusted input (demo epic D1 review): its page URL must
+ // name the channel's own video platform's host, before any request.
+ const page = recordPage(webpageUrl, config.platform ?? null, detectPlatform);
+ if ("refused" in page) return NextResponse.json({ error: `${channelSlug}/${videoId}: ${page.refused}` }, { status: 400 });
+ // From here on the URL is the one the check parsed, written back — never
+ // the string the archive or the ask gave (another parser may read that
+ // one as another host).
+ webpageUrl = page.href;
+ const platform = page.platform;
+ const whole = body.full === true || wholeRecordingFor(getSettings(), platform, {}, undefined);
+ if (whole && body.allowWholeRecording !== true) {
+ return NextResponse.json(
+ {
+ error: wholeRecordingRefusal({
+ platform,
+ slug: channelSlug,
+ id: videoId,
+ ...(record?.duration !== undefined ? { duration: record.duration } : {}),
+ ...(typeof body.maxHeight === "number" ? { maxHeight: body.maxHeight } : {}),
+ }),
+ },
+ { status: 409 },
+ );
+ }
+ }
+ }
+
if (body.full === true) {
// A cap at or under 720 asks for "video_720"; one above it asks for
// "original" in so many words. No cap: the channel's, else the global,
@@ -233,7 +307,7 @@ export async function POST(request: Request) {
await fetchWindowAction({
slug: channelSlug,
videoId,
- webpageUrl: str(body.webpageUrl),
+ webpageUrl,
from,
to,
provenance,
diff --git a/editor/app/api/ops/archives/route.ts b/editor/app/api/ops/archives/route.ts
@@ -0,0 +1,61 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { ArchiveProbeError } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import {
+ RemoteArchiveError,
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../../../settings/saveSettings";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// THE CONNECTED ARCHIVES (demo epic D1; lib/remoteArchives.ts): the published
+// archives this machine reads as sources — Create, research and the MCP offer
+// each, a sweep over one cites it, and a window it cites registers a
+// remote-only channel to fetch it.
+//
+// GET /api/ops/archives
+// -> { ok, archives: [{ id, origin, title, addedAt, fromEnv? }] }
+// (`fromEnv`: TRANSCRIPT_SITE_URL's, listed and never stored)
+// POST { connect: "<origin>", dryRun? }
+// -> { ok, archive, probe: { origin, siteId, title, spec, generatedAt,
+// totals, channels }, already }
+// reads <origin>/corpus.json once; a hub, a cited-only site, a site with
+// no channels or an origin that does not answer is refused (400/502).
+// dryRun answers the probe and writes nothing (already: null); an origin
+// connected already writes nothing (already: true).
+// POST { remove: "<id or origin>" } -> { ok, removed }
+
+const deps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => ({ archives: connectedArchives(getSettings().remoteArchives) }));
+}
+
+export async function POST(request: Request) {
+ return ops(request, ["connect", "remove", "dryRun"], async (body) => {
+ const connect = optString(body, "connect")?.trim();
+ const remove = optString(body, "remove")?.trim();
+ if (!!connect === !!remove) throw new OpsInputError('send "connect" (an origin) or "remove" (an id or origin)');
+ try {
+ if (connect) {
+ const r = await connectRemoteArchive({ origin: connect, dryRun: optBool(body, "dryRun") === true }, deps());
+ return NextResponse.json({ ok: true, ...r });
+ }
+ if (optBool(body, "dryRun") !== undefined) throw new OpsInputError('"dryRun" goes with "connect"');
+ return NextResponse.json({ ok: true, removed: await removeRemoteArchive(remove!, deps()) });
+ } catch (e) {
+ if (e instanceof ArchiveProbeError) return opsFail(e.message, e.status);
+ if (e instanceof RemoteArchiveError) return opsFail(e.message);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/api/ops/channels/route.ts b/editor/app/api/ops/channels/route.ts
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
-import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { isRemoteOnlyChannel, isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { siteChannelIndex } from "yt-dlp-transcript-common/lib/site";
import { opsAuth } from "../_lib";
@@ -32,13 +32,15 @@ export async function GET(request: Request) {
channels: rows.map(({ slug, config }) => ({
slug,
name: config.name ?? slug,
- kind: isSocialChannel(config) ? "social" : "video",
+ // "remote-only" (demo epic D1): a connected archive's clip windows only.
+ kind: isRemoteOnlyChannel(config) ? "remote-only" : isSocialChannel(config) ? "social" : "video",
platform: config.platform ?? null,
handling: config.handling,
url: config.url ?? null,
sites: sitesOf.get(slug) ?? [],
...(config.excludeFromBuild ? { excludeFromBuild: true } : {}),
...(config.excludeFromCleanup ? { excludeFromCleanup: true } : {}),
+ ...(isRemoteOnlyChannel(config) && config.remoteArchive ? { remoteArchive: config.remoteArchive } : {}),
})),
});
}
diff --git a/editor/app/api/ops/fetch-windows/route.remote.test.ts b/editor/app/api/ops/fetch-windows/route.remote.test.ts
@@ -0,0 +1,178 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/fetch-windows/route.remote.test.ts"
+//
+// demo epic D1 item 5: a window cited from a CONNECTED archive, of a channel
+// this editor does not hold. The archive is a fake fetch (no request leaves
+// the process); no job is queued — every run here ends refused or unresolved.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-windows-remote-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+delete process.env.TRANSCRIPT_SITE_URL;
+const ORIGIN = "https://stub.test";
+await writeFile(
+ process.env.SETTINGS_FILE,
+ JSON.stringify({ remoteArchives: [{ id: "stub", origin: ORIGIN, title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }),
+);
+
+const DOCS: Record<string, unknown> = {
+ [`${ORIGIN}/corpus.json`]: {
+ spec: 6,
+ site: { id: "stub", title: "Stub" },
+ channels: [
+ { slug: "yt-remote", name: "YT Remote", videoCount: 1, platform: "youtube", url: "https://www.youtube.com/@ytr", manifests: { transcripts: `${ORIGIN}/transcripts/yt-remote/manifest.json` } },
+ { slug: "rb-remote", name: "RB Remote", videoCount: 1, platform: "rumble", manifests: { transcripts: `${ORIGIN}/transcripts/rb-remote/manifest.json` } },
+ { slug: "evil-remote", name: "Evil", videoCount: 1, platform: "youtube", manifests: { transcripts: `${ORIGIN}/transcripts/evil-remote/manifest.json` } },
+ ],
+ },
+ [`${ORIGIN}/transcripts/rb-remote/manifest.json`]: { pageCount: 1, slugToPage: { rb9: 0 } },
+ [`${ORIGIN}/transcripts/rb-remote/page-0000.json`]: [{ id: "rb9", duration: 5400, webpageUrl: "https://rumble.com/vrb9-x.html" }],
+ // An archive pointing the editor at its own API (review of 9fddc3bb, blocker 2).
+ [`${ORIGIN}/transcripts/evil-remote/manifest.json`]: { slugToPage: { e1: 0, e2: 0, e3: 0, d1: 0, d2: 0, d3: 0, n1: 0 } },
+ [`${ORIGIN}/transcripts/evil-remote/page-0000.json`]: [
+ { id: "e1", webpageUrl: "http://127.0.0.1:3001/api/ops/settings" },
+ { id: "e2", webpageUrl: "https://rumble.com/ve2-x.html" },
+ // A look-alike of the channel's platform (re-review, must-fix 1).
+ { id: "e3", webpageUrl: "https://evilyoutube.com/watch?v=e3" },
+ // Read as youtube.com by Node's URL parser, as another host by Python's (re-check, the parser differential).
+ { id: "d1", webpageUrl: "https://youtube.com\\@evil.example/watch?v=d1" },
+ { id: "d2", webpageUrl: "https://youtube.com\\@127.0.0.1/x" },
+ { id: "d3", webpageUrl: "https://you\ttube.com/watch?v=d3" },
+ // The platform's own page, spelled loudly: handed on as the parser wrote it back.
+ { id: "n1", webpageUrl: "HTTPS://WWW.YouTube.com:443/watch?v=n1" },
+ ],
+};
+const asked: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ asked.push(url);
+ if (!(url in DOCS)) return new Response("not found", { status: 404 });
+ return new Response(JSON.stringify(DOCS[url]), { status: 200 });
+}) as typeof fetch;
+
+const { POST } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function post(body: Record<string, unknown>) {
+ const res = await POST(
+ new Request("http://localhost/api/ops/fetch-windows", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, json: (await res.json()) as Record<string, unknown> & { error?: string } };
+}
+
+type Unresolved = { item: { slug: string }; error: string }[];
+
+test("a dry run names the channel it would register, and registers nothing", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5, webpageUrl: "https://www.youtube.com/watch?v=v1" }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, ["yt-remote"]);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /would register it as a remote-only channel of https:\/\/stub\.test/);
+ await assert.rejects(readFile(path.join(ROOT, "channels", "yt-remote", "config.json")));
+ assert.deepEqual(asked, [], "a dry run reads no archive either");
+});
+
+test("an origin not connected registers nothing, and the refusal names the connect", async () => {
+ const r = await post({ requestedBy: "test", archive: "https://elsewhere.test", dryRun: true, items: [{ slug: "yt-remote", id: "v1", from: 1, to: 5 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, []);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /not found — https:\/\/elsewhere\.test is not a connected archive: connect it/);
+});
+
+test("a run registers the remote-only channel from the archive, and refuses its Rumble whole recording with the size", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.registered, ["rb-remote"]);
+ assert.deepEqual(r.json.jobIds, [], "nothing queued");
+ const error = (r.json.unresolved as Unresolved)[0].error;
+ assert.match(error, /^whole recording refused: Rumble windows are cut from the WHOLE recording/);
+ assert.match(error, /rb-remote\/rb9 is 1:30:00 long, about 1\.7 GB \(estimated\)/);
+ const config = JSON.parse(await readFile(path.join(ROOT, "channels", "rb-remote", "config.json"), "utf8"));
+ assert.deepEqual(config, { name: "RB Remote", handling: "transcribe", platform: "rumble", remoteOnly: true, remoteArchive: ORIGIN, downloadMode: "manual" });
+ // Its page URL came from the archive's record (the item had none).
+ assert.ok(asked.includes(`${ORIGIN}/transcripts/rb-remote/page-0000.json`));
+ // The allowance, as a dry run: planned on Rumble's download queue, the archive's URL.
+ const allowed = await post({ requestedBy: "test", archive: ORIGIN, allowWholeRecording: true, dryRun: true, items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(allowed.status, 200, allowed.json.error);
+ const groups = allowed.json.groups as { platform: string; queueKey: string; items: { webpageUrl: string }[] }[];
+ assert.equal(groups.length, 1);
+ assert.equal(groups[0].platform, "rumble");
+ assert.equal(groups[0].items[0].webpageUrl, "https://rumble.com/vrb9-x.html");
+});
+
+test("an archive's record pointing anywhere but its channel's video platform is refused before any request", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "evil-remote", id: "e1", from: 1, to: 5 }, { slug: "evil-remote", id: "e2", from: 1, to: 5 }] });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.match(errors[0], /127\.0\.0\.1:3001 is not a video platform's host/);
+ assert.match(errors[1], /rumble\.com is rumble, and the channel is youtube's/);
+ assert.deepEqual(r.json.jobIds, []);
+ assert.equal(asked.some((u) => u.startsWith("http://127.0.0.1")), false);
+});
+
+test("a look-alike of the channel's platform host is refused before any request", async () => {
+ const r = await post({ requestedBy: "test", archive: ORIGIN, items: [{ slug: "evil-remote", id: "e3", from: 1, to: 5 }, { slug: "evil-remote", id: "e4", from: 1, to: 5, webpageUrl: "https://www.youtube.com.evil.example/watch?v=e4" }] });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.match(errors[0], /^evilyoutube\.com is not a video platform's host/);
+ assert.match(errors[1], /^www\.youtube\.com\.evil\.example is not a video platform's host/);
+ assert.deepEqual(r.json.jobIds, []);
+});
+
+test("a page URL two parsers read differently is refused before any request, from the record or from the ask", async () => {
+ const r = await post({
+ requestedBy: "test",
+ archive: ORIGIN,
+ items: [
+ { slug: "evil-remote", id: "d1", from: 1, to: 5 },
+ { slug: "evil-remote", id: "d2", from: 1, to: 5 },
+ { slug: "evil-remote", id: "d3", from: 1, to: 5 },
+ { slug: "evil-remote", id: "a1", from: 1, to: 5, webpageUrl: "https://youtube.com\\@evil.example/watch?v=x" },
+ { slug: "evil-remote", id: "a2", from: 1, to: 5, webpageUrl: "https://rumble.com\\.evil.example/v1" },
+ { slug: "evil-remote", id: "a3", from: 1, to: 5, webpageUrl: "https://you\ttube.com/watch?v=x" },
+ { slug: "evil-remote", id: "a4", from: 1, to: 5, webpageUrl: "https://youtube.com/watch?v=x\nhttps://evil.example/" },
+ ],
+ });
+ assert.equal(r.status, 200, r.json.error);
+ const errors = (r.json.unresolved as Unresolved).map((u) => u.error);
+ assert.equal(errors.length, 7);
+ for (const e of errors) assert.match(e, /carries a backslash, whitespace or a control character/);
+ assert.deepEqual(r.json.jobIds, []);
+});
+
+test("what is planned for the fetcher is the URL the check parsed, written back — the record's and the ask's", async () => {
+ const r = await post({
+ requestedBy: "test",
+ archive: ORIGIN,
+ dryRun: true,
+ items: [
+ { slug: "evil-remote", id: "n1", from: 1, to: 5 },
+ { slug: "evil-remote", id: "n2", from: 1, to: 5, webpageUrl: " https:YOUTUBE.com:443/watch?v=n2 " },
+ ],
+ });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.unresolved, []);
+ const urls = (r.json.groups as { items: { id: string; webpageUrl: string }[] }[]).flatMap((g) => g.items).map((i) => i.webpageUrl).sort();
+ assert.deepEqual(urls, ["https://www.youtube.com/watch?v=n1", "https://youtube.com/watch?v=n2"]);
+});
+
+// LAST: it disconnects the archive for the rest of the file.
+test("a remote-only channel whose archive was removed from settings is refused, and the archive is not read", async () => {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ remoteArchives: [] }));
+ asked.length = 0;
+ const r = await post({ requestedBy: "test", items: [{ slug: "rb-remote", id: "rb9", from: 60, to: 70 }] });
+ assert.equal(r.status, 200, r.json.error);
+ assert.deepEqual(r.json.jobIds, []);
+ assert.match((r.json.unresolved as Unresolved)[0].error, /^rb-remote is a remote-only channel, and its archive https:\/\/stub\.test is no longer connected/);
+ assert.deepEqual(asked, [], "nothing asked of an archive that is not connected");
+});
diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts
@@ -35,7 +35,8 @@ export const dynamic = "force-dynamic";
// POST { siteId, maxHeight?, storedUrl?, wholeRecording?, dryRun? }
// | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …],
-// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?, dryRun? }
+// requestedBy, manifest?, maxHeight?, storedUrl?, minGapSeconds?, wholeRecording?,
+// archive?, allowWholeRecording?, dryRun? }
// dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }],
// cached, inFlight, unresolved[, onDisk, unfetchable] }
// else -> { ok, dryRun: false, jobs: [{ platform, queueKey, jobId, items }],
@@ -75,6 +76,16 @@ export const dynamic = "force-dynamic";
// `"wholeRecording": false` fetches every window of this run by a remote seek
// instead, as before.
//
+// `archive` (items only; demo epic D1): the connected archive the items cite
+// (settings.remoteArchives — any other origin is refused). A channel this
+// editor does not hold is then REGISTERED as a remote-only channel of it
+// (config only, no listing; answered in `registered`) and its windows fetched
+// on the paced queue as any other; a remote-only channel's page URL comes
+// from the archive's record when the item has none. A remote-only channel's
+// window on a whole-recording platform (Rumble) is unresolved with the
+// recording's estimated size unless `"allowWholeRecording": true`. A dry run
+// registers nothing (it names who would be).
+//
// A big list goes in a file: `pnpm ops fetch-windows --file list.json`.
const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"];
@@ -182,7 +193,7 @@ function optMaxHeight(body: OpsBody): number | undefined {
export async function POST(request: Request) {
return ops(
request,
- ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "dryRun"],
+ ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "minGapSeconds", "wholeRecording", "archive", "allowWholeRecording", "dryRun"],
async (body) => {
const maxHeight = optMaxHeight(body);
const storedUrl = optStoredUrl(body);
@@ -196,7 +207,7 @@ export async function POST(request: Request) {
let result: Awaited<ReturnType<typeof fetchWindowsAction>>;
if (body.siteId !== undefined) {
// A site's windows say who asked themselves (the reports, by site).
- for (const k of ["requestedBy", "manifest", "minGapSeconds"]) {
+ for (const k of ["requestedBy", "manifest", "minGapSeconds", "archive", "allowWholeRecording"]) {
if (body[k] !== undefined) {
throw new OpsInputError(`"${k}" goes with "items"; a site's windows name the site`);
}
@@ -221,6 +232,8 @@ export async function POST(request: Request) {
storedUrl,
dryRun,
...(minGapSeconds !== undefined ? { minGapSeconds } : {}),
+ ...(optString(body, "archive")?.trim() ? { archive: optString(body, "archive")!.trim() } : {}),
+ ...(optBool(body, "allowWholeRecording") === true ? { allowWholeRecording: true } : {}),
...seek,
});
} else {
diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts
@@ -8,6 +8,7 @@
// - autoQueue: a lane's tree is its policy editor's, or compiled from the
// channel priorities — and the editor refuses a tree edit while they rule.
// - workers: /workers validates each worker (templates, URLs) on save.
+// - remoteArchives: an archive's corpus.json is read when it is connected.
// - storage: a location is probed and its volume recorded when added or
// re-pointed (/storage); a raw root would skip both.
export const OWNED_KEYS: Readonly<Record<string, string>> = {
@@ -15,6 +16,7 @@ export const OWNED_KEYS: Readonly<Record<string, string>> = {
autoQueue:
"a lane's switch, hold and runner are `pnpm ops lane`; its tree is the policy editor's on /operations, or compiled from channel priorities",
workers: "workers are saved on /workers; `pnpm ops workers` enables and disables them",
+ remoteArchives: "an archive is probed (its corpus.json read) when it is connected — use `pnpm ops archives` or /sites → Connect an archive",
storage: "locations are added and re-pointed on /storage, which probes them; a channel's media moves with `pnpm ops relocate`",
};
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -2,7 +2,7 @@
import { localMediaMetadataRefusal } from "yt-dlp-transcript-common/lib/localMedia";
import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads";
-import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { isSocialChannel, remoteOnlyRefusal } from "yt-dlp-transcript-common/lib/channelConfig";
import { fetchPostsAction } from "./socialActions";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
@@ -155,6 +155,9 @@ async function runPipelineAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ // A REMOTE-ONLY channel (demo epic D1) is never listed, synced or downloaded.
+ const remoteOnly = remoteOnlyRefusal(slug, channelConfig);
+ if (remoteOnly) return { ok: false, info: true, error: remoteOnly };
if (!channelConfig.url) {
return { ok: false, error: "Channel has no `url` configured" };
}
@@ -446,6 +449,8 @@ export async function runMetadataScanAction(
if (!channelConfig) {
return { ok: false, error: `Channel "${slug}" not found` };
}
+ const remoteOnly = remoteOnlyRefusal(slug, channelConfig);
+ if (remoteOnly) return { ok: false, info: true, error: remoteOnly };
const localRefusal = localMediaMetadataRefusal(slug, channelConfig);
if (localRefusal) return { ok: false, error: localRefusal };
if (!channelConfig.url) {
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -62,6 +62,14 @@ import {
type StreamActionResult,
} from "yt-dlp-transcript-common/jobs/streamCommand";
import { safeRevalidate } from "../../../lib/safeRevalidate";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { connectedArchives, disconnectedArchiveRefusal, findConnectedArchive, recordPage, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import {
+ archiveRecordOf,
+ ensureRemoteOnlyChannel,
+ wholeRecordingRefusal,
+} from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
// FETCH A LIST OF CLIP WINDOWS through the managed path, as ONE JOB PER
// PLATFORM QUEUE (controller/fetchWindows.ts walks each one, paced).
@@ -123,6 +131,15 @@ export type FetchWindowsRequest = {
minGapSeconds?: number;
// false: every window by a remote seek, the whole-recording platforms' too.
wholeRecording?: boolean;
+ // THE ARCHIVE THE ITEMS CITE (demo epic D1): a connected archive's origin
+ // (settings.remoteArchives). A channel this editor does not hold is then
+ // registered as a REMOTE-ONLY channel of it (controller/remoteOnlyChannel.ts)
+ // instead of refused, and a remote-only channel's page URL comes from the
+ // archive's record. A dry run registers nothing.
+ archive?: string;
+ // A remote-only channel's window on a whole-recording platform (Rumble) is
+ // refused with the recording's size unless this is true.
+ allowWholeRecording?: boolean;
};
export type FetchWindowsUnresolved = { item: FetchWindowsItem; error: string };
@@ -153,6 +170,9 @@ export type FetchWindowsActionResult =
// Windows a queued or running job will already write, and that job.
inFlight: FetchWindowsInFlight[];
unresolved: FetchWindowsUnresolved[];
+ // Channels registered as remote-only for these windows (a dry run: the
+ // ones that would be), each once.
+ registered: string[];
};
export type FetchWindowsInFlight = { item: FetchWindowsItem; jobId: string };
@@ -186,11 +206,13 @@ async function planFetchWindows(
maxHeight: number | undefined,
storedMode: StoredUrlMode,
wholeRecording?: boolean,
+ remote: { archive?: ConnectedArchive | null; unconnected?: string; allowWholeRecording?: boolean; dryRun?: boolean } = {},
): Promise<{
groups: FetchWindowsGroup[];
cached: FetchWindowsItem[];
inFlight: FetchWindowsInFlight[];
unresolved: FetchWindowsUnresolved[];
+ registered: string[];
// The planned items (as grouped) whose record stores a trusted media URL.
stored: Set<FetchWindowsItem>;
}> {
@@ -202,6 +224,10 @@ async function planFetchWindows(
const inFlight: FetchWindowsInFlight[] = [];
const unresolved: FetchWindowsUnresolved[] = [];
const stored = new Set<FetchWindowsItem>();
+ const registered: string[] = [];
+ // A slug the archive could not register, with why (asked once per run).
+ const unregistrable = new Map<string, string>();
+ const getJson = cachedArchiveGetJson();
const live = getRegistry().list();
for (const item of dedupeFetchWindowsItems(items)) {
const problem = itemProblem(item);
@@ -212,9 +238,36 @@ async function planFetchWindows(
if (!configs.has(item.slug)) {
configs.set(item.slug, await readChannelConfig(paths, item.slug));
}
- const config = configs.get(item.slug);
+ let config = configs.get(item.slug);
+ // NOT HELD HERE, CITED FROM A CONNECTED ARCHIVE (demo epic D1): registered
+ // as a remote-only channel of it, config only — or, in a dry run, said.
+ if (!config && remote.archive && !unregistrable.has(item.slug)) {
+ if (remote.dryRun) {
+ if (!registered.includes(item.slug)) registered.push(item.slug);
+ unresolved.push({ item, error: `Channel "${item.slug}" is not held here: the run would register it as a remote-only channel of ${remote.archive.origin}` });
+ continue;
+ }
+ try {
+ const r = await ensureRemoteOnlyChannel(paths, item.slug, remote.archive, { getJson });
+ config = r.config;
+ configs.set(item.slug, config);
+ if (r.registered && !registered.includes(item.slug)) registered.push(item.slug);
+ } catch (e) {
+ unregistrable.set(item.slug, (e as Error).message);
+ }
+ }
if (!config) {
- unresolved.push({ item, error: `Channel "${item.slug}" not found` });
+ const why = unregistrable.get(item.slug);
+ unresolved.push({
+ item,
+ error:
+ `Channel "${item.slug}" not found` +
+ (why
+ ? `, and it could not be registered from its archive: ${why}`
+ : remote.unconnected
+ ? ` — ${remote.unconnected} is not a connected archive: connect it (/sites → Connected archives, or pnpm ops archives {"connect": …}) to fetch its windows here`
+ : ""),
+ });
continue;
}
const localRefusal = localMediaFetchRefusal(item.slug, config, item.id);
@@ -298,9 +351,40 @@ async function planFetchWindows(
continue;
}
}
- const url =
+ // An archive removed from settings is not read any more, for a channel
+ // registered while it was connected either: nothing is asked of it.
+ if (isRemoteOnlyChannel(config)) {
+ const gone = disconnectedArchiveRefusal(config.remoteArchive, connectedArchives(settings.remoteArchives));
+ if (gone) {
+ unresolved.push({ item, error: `${item.slug} is a remote-only channel, and ${gone}` });
+ continue;
+ }
+ }
+ // A REMOTE-ONLY channel has no metadata or playlist of its own: the page
+ // URL is the ask's, else its archive's record.
+ const record =
+ isRemoteOnlyChannel(config) && config.remoteArchive
+ ? await archiveRecordOf(config.remoteArchive, item.slug, item.id, { getJson }).catch(() => null)
+ : null;
+ let url =
item.webpageUrl?.trim() ||
- (await findVideoSourceUrl(paths, item.slug, dirId, config));
+ record?.webpageUrl ||
+ (isRemoteOnlyChannel(config) ? null : await findVideoSourceUrl(paths, item.slug, dirId, config));
+ // An archive is untrusted input (demo epic D1 review): a remote-only
+ // channel's page URL must name its own video platform's host, or nothing
+ // is asked of it. What goes on is the URL the check parsed, written back
+ // — never the string the archive or the ask gave.
+ if (isRemoteOnlyChannel(config)) {
+ const raw = item.webpageUrl?.trim() || record?.webpageUrl;
+ if (raw) {
+ const page = recordPage(raw, config.platform ?? null, detectPlatform);
+ if ("refused" in page) {
+ unresolved.push({ item, error: page.refused });
+ continue;
+ }
+ url = page.href;
+ }
+ }
if (!url) {
unresolved.push({
item,
@@ -316,6 +400,15 @@ async function planFetchWindows(
// only itself.
const platform = detectPlatform(url) ?? "unknown";
const whole = wholeRecordingFor(settings, platform, item, wholeRecording);
+ // A remote-only channel's whole recording is a download nobody planned:
+ // refused with its size until the ask allows it (one press in umtool).
+ if (whole && isRemoteOnlyChannel(config) && !remote.allowWholeRecording) {
+ unresolved.push({
+ item,
+ error: wholeRecordingRefusal({ platform, slug: item.slug, id: item.id, ...(record?.duration !== undefined ? { duration: record.duration } : {}), ...(maxHeight ? { maxHeight } : {}) }),
+ });
+ continue;
+ }
const queueKey = resolveQueueKey(
whole ? queueKeyForUrl(url) : clipWindowQueueKey(queueKeyForUrl(url)),
queueOverride,
@@ -334,7 +427,7 @@ async function planFetchWindows(
}
groups.set(queueKey, group);
}
- return { groups: [...groups.values()], cached, inFlight, unresolved, stored };
+ return { groups: [...groups.values()], cached, inFlight, unresolved, stored, registered };
}
// The door each group passes before its job is queued: the platform's hold,
@@ -461,14 +554,28 @@ export async function fetchWindowsAction(
};
}
const storedMode = req.storedUrl ?? "never";
- const { groups, cached, inFlight, unresolved, stored } = await planFetchWindows(
+ // The archive the items cite: only a CONNECTED one registers anything. Any
+ // other origin (a site's own, an archive not connected) registers nothing —
+ // a channel held here is fetched as always, one not held is refused, naming
+ // the connect that would register it.
+ const archive: ConnectedArchive | null = req.archive?.trim()
+ ? findConnectedArchive(connectedArchives(getSettings().remoteArchives), req.archive)
+ : null;
+ const { groups, cached, inFlight, unresolved, stored, registered } = await planFetchWindows(
req.items,
req.queueKey,
req.maxHeight,
storedMode,
req.wholeRecording,
+ {
+ archive,
+ ...(req.archive?.trim() && !archive ? { unconnected: req.archive.trim() } : {}),
+ allowWholeRecording: req.allowWholeRecording === true,
+ dryRun: req.dryRun === true,
+ },
);
- const base = { groups, cached, inFlight, unresolved, jobs: [], refused: [] };
+ if (registered.length && !req.dryRun) safeRevalidate(["/channels"]);
+ const base = { groups, cached, inFlight, unresolved, registered, jobs: [], refused: [] };
if (req.dryRun) return { ok: true, dryRun: true, ...base };
if (groups.length === 0) return { ok: true, dryRun: false, ...base };
@@ -542,7 +649,7 @@ export async function fetchWindowsAction(
error: refused.map((r) => `${r.platform}: ${r.error}`).join("; "),
};
}
- return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, jobs, refused };
+ return { ok: true, dryRun: false, groups, cached, inFlight, unresolved, registered, jobs, refused };
}
export type FetchMissingEvidenceResult =
@@ -606,6 +713,7 @@ async function fetchMissingFor(
cached: [],
inFlight: [],
unresolved: [],
+ registered: [],
...extra,
};
}
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -1,5 +1,6 @@
"use server";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel";
import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults";
import { revalidatePath } from "next/cache";
@@ -645,6 +646,7 @@ export async function syncAllChannelsAction(
skip: async (slug) => {
const config = bySlug.get(slug);
if (!config?.url) return "no url";
+ if (isRemoteOnlyChannel(config)) return "remote-only";
if (isChannelPaused(priority, slug, "sync")) return "paused for sync";
if (active.has(slug)) return "already running";
const media = await inspectChannelMedia(paths, slug, config);
diff --git a/editor/app/channels/components/ChannelTierSelect.tsx b/editor/app/channels/components/ChannelTierSelect.tsx
@@ -67,6 +67,8 @@ export type ChannelTierSelectProps = {
// A manual-downloads channel (lib/manualDownloads.ts): the download lane
// skips it by design, so its rack row says so rather than looking stalled.
manualDownloads?: boolean;
+ // A remote-only channel's archive origin (demo epic D1), else null/undefined.
+ remoteOnly?: string | null;
disabled?: boolean;
};
@@ -98,6 +100,7 @@ export default function ChannelTierSelect({
autoPausedReason = null,
mediaHold = null,
manualDownloads = false,
+ remoteOnly = null,
disabled = false,
}: ChannelTierSelectProps): React.ReactNode {
const [pending, startTransition] = useTransition();
@@ -213,6 +216,17 @@ export default function ChannelTierSelect({
<span className="sr-only"> — {mediaHold}</span>
</span>
)}
+ {remoteOnly !== null && remoteOnly !== undefined && (
+ <span
+ role="note"
+ aria-label={`remote-only channel ${slug}`}
+ title={`Remote-only: holds clip windows of ${remoteOnly || "a connected archive"}; never listed, synced or downloaded here.`}
+ className="rounded-full border border-border px-1.5 text-[10px] uppercase tracking-wide text-muted-foreground"
+ >
+ remote only
+ <span className="sr-only"> — holds clip windows of {remoteOnly || "a connected archive"}</span>
+ </span>
+ )}
{manualDownloads && (
<span
role="note"
diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx
@@ -180,6 +180,7 @@ export const CHANNEL_COLUMNS: Record<
autoPausedReason={c.priority.autoPausedReason}
mediaHold={c.mediaHold}
manualDownloads={c.manualDownloads}
+ remoteOnly={c.remoteOnly}
/>
),
}),
diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts
@@ -1,3 +1,4 @@
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import type { Paths } from "yt-dlp-transcript-common/lib/paths";
import type { ChannelBrief } from "yt-dlp-transcript-common/controller/channels";
import { getChannelBriefs } from "../../lib/requestCache";
@@ -247,6 +248,8 @@ export async function cleanableChannels(
const channels = await getChannelBriefs(paths);
const rows = channels.map((channel) => {
if (channel.config.excludeFromCleanup) return null;
+ // A remote-only channel (demo epic D1) has nothing a cleanup sweeps.
+ if (isRemoteOnlyChannel(channel.config)) return null;
const snap = channel.snapshot;
const bytes = transcribedBytesOf(snap);
const count = snap?.buckets.transcribedWithAudio?.length ?? 0;
diff --git a/editor/app/sites/[siteId]/page.tsx b/editor/app/sites/[siteId]/page.tsx
@@ -1,6 +1,6 @@
import { notFound } from "next/navigation";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { siteChannelOptions } from "../lib/channelOptions";
import { listSites } from "yt-dlp-transcript-common/lib/site";
import {
SiteForm,
@@ -21,10 +21,7 @@ export default async function EditSitePage({
const paths = getPaths();
const site = getSiteCached(siteId);
if (!site) notFound();
- const channels: ChannelOption[] = (await listChannelConfigs(paths)).map((c) => ({
- slug: c.slug,
- name: c.config.name ?? c.slug,
- }));
+ const channels: ChannelOption[] = await siteChannelOptions(paths);
const allSites: SiteOption[] = listSites(paths)
.filter((s) => s.siteId !== siteId)
.map((s) => ({ siteId: s.siteId, siteTitle: s.siteTitle }));
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -10,6 +10,14 @@ import {
siteDeleteBlocked,
type SiteDeletePlan,
} from "yt-dlp-transcript-common/publish/siteDelete";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ connectRemoteArchive,
+ removeRemoteArchive,
+ type ConnectResult,
+ type RemoteArchiveDeps,
+} from "yt-dlp-transcript-common/controller/remoteArchives";
+import { saveSettings } from "../settings/saveSettings";
import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm";
export type { SaveResult } from "./lib/saveSiteForm";
@@ -81,3 +89,36 @@ export async function migrateToSitesAction(): Promise<DeleteResult> {
// /settings is dynamic, rendered afresh on the next visit.
return { ok: true };
}
+
+// CONNECT AN ARCHIVE (demo epic D1): the /sites panel's two presses — Read it
+// (a dry run: corpus.json read, nothing written) and Connect — and Remove, all
+// through the one controller `pnpm ops archives` uses.
+export type ArchiveActionResult =
+ | { ok: true; result: ConnectResult }
+ | { ok: false; error: string };
+
+const archiveDeps = (): RemoteArchiveDeps => ({
+ stored: () => getSettings().remoteArchives,
+ save: (next) => saveSettings({ remoteArchives: next }),
+});
+
+export async function connectArchiveAction(origin: string, dryRun: boolean): Promise<ArchiveActionResult> {
+ try {
+ const result = await connectRemoteArchive(
+ { origin, dryRun },
+ archiveDeps(),
+ );
+ return { ok: true, result };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+export async function removeArchiveAction(id: string): Promise<{ ok: true } | { ok: false; error: string }> {
+ try {
+ await removeRemoteArchive(id, archiveDeps());
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/sites/components/ConnectArchive.tsx b/editor/app/sites/components/ConnectArchive.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import type { ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import type { ArchiveProbe } from "yt-dlp-transcript-common/lib/remoteArchives-server";
+import { connectArchiveAction, removeArchiveAction } from "../actions";
+
+// CONNECTED ARCHIVES (demo epic D1): the published archives this machine reads
+// as sources. Type an origin → Read it (its corpus.json: title, channels,
+// videos, nothing saved) → Connect. Each row's Remove drops it; the one
+// TRANSCRIPT_SITE_URL names is listed and cannot be removed here.
+
+const nf = new Intl.NumberFormat("en-US");
+
+export function ConnectArchive({ archives }: { archives: ConnectedArchive[] }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<ArchiveProbe | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+
+ const read = () =>
+ start(async () => {
+ setError(null);
+ setSaid(null);
+ setProbe(null);
+ const r = await connectArchiveAction(origin, true);
+ if (r.ok) setProbe(r.result.probe);
+ else setError(r.error);
+ });
+ const connect = () =>
+ start(async () => {
+ setError(null);
+ const r = await connectArchiveAction(probe?.origin ?? origin, false);
+ if (!r.ok) return setError(r.error);
+ setSaid(r.result.already ? `${r.result.archive.title} was connected already.` : `Connected ${r.result.archive.title}.`);
+ setProbe(null);
+ setOrigin("");
+ router.refresh();
+ });
+ const remove = (id: string) =>
+ start(async () => {
+ setError(null);
+ const r = await removeArchiveAction(id);
+ if (!r.ok) setError(r.error);
+ else router.refresh();
+ });
+
+ return (
+ <div className="flex flex-col gap-3" data-connected-archives="">
+ {archives.length > 0 ? (
+ <ul className="flex flex-col divide-y divide-border" aria-label="connected archives">
+ {archives.map((a) => (
+ <li key={a.origin} className="flex items-center justify-between gap-3 py-2" data-archive={a.id}>
+ <div className="min-w-0">
+ <div className="font-medium">{a.title}</div>
+ <div className="text-xs text-muted-foreground">
+ <code>{a.origin}</code>
+ {a.fromEnv ? " · from TRANSCRIPT_SITE_URL" : ` · connected ${a.addedAt.slice(0, 10)}`}
+ </div>
+ </div>
+ {!a.fromEnv && (
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => remove(a.id)}
+ aria-label={`remove ${a.title}`}
+ className="px-2 py-1 rounded border border-border text-xs disabled:opacity-50"
+ >
+ Remove
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-sm italic text-muted-foreground">No archive connected.</p>
+ )}
+ <form
+ className="flex flex-wrap items-center gap-2"
+ aria-label="connect an archive"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (probe && probe.origin) connect();
+ else read();
+ }}
+ >
+ <input
+ type="text"
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className="w-80 rounded-md border border-border bg-background px-2 py-1 text-sm"
+ />
+ <button
+ type="button"
+ disabled={pending || !origin.trim()}
+ onClick={read}
+ className="px-3 py-1 rounded-md border border-border text-sm disabled:opacity-50"
+ >
+ {pending && !probe ? "Reading…" : "Read it"}
+ </button>
+ {probe && (
+ <button type="button" disabled={pending} onClick={connect} className="px-3 py-1 rounded-md bg-primary text-primary-foreground text-sm disabled:opacity-50">
+ Connect
+ </button>
+ )}
+ </form>
+ {probe && (
+ <div className="rounded-md border border-border px-3 py-2 text-sm" data-archive-probe={probe.origin}>
+ <div className="font-medium">{probe.title}</div>
+ <div className="text-xs text-muted-foreground">
+ {nf.format(probe.totals.channels)} channel{probe.totals.channels === 1 ? "" : "s"} · {nf.format(probe.totals.videos)} videos
+ {probe.generatedAt ? ` · built ${probe.generatedAt.slice(0, 10)}` : ""}
+ {probe.spec !== null ? ` · corpus spec ${probe.spec}` : ""}
+ </div>
+ <ul className="mt-1 flex flex-wrap gap-x-3 text-xs" aria-label="its channels">
+ {probe.channels.slice(0, 40).map((c) => (
+ <li key={c.slug}>
+ {c.name}
+ {c.videoCount !== null ? <span className="text-muted-foreground"> {nf.format(c.videoCount)}</span> : null}
+ </li>
+ ))}
+ {probe.channels.length > 40 && <li className="text-muted-foreground">…and {probe.channels.length - 40} more</li>}
+ </ul>
+ </div>
+ )}
+ {said && <p className="text-sm text-muted-foreground">{said}</p>}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/editor/app/sites/lib/channelOptions.test.ts b/editor/app/sites/lib/channelOptions.test.ts
@@ -0,0 +1,24 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { siteChannelOptions } from "./channelOptions";
+
+// Run with: pnpm -C editor exec tsx --test "app/sites/lib/channelOptions.test.ts"
+
+test("the site form's channel picker leaves remote-only channels out", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "site-channel-options-"));
+ try {
+ const put = async (slug: string, config: Record<string, unknown>) => {
+ await mkdir(path.join(root, slug), { recursive: true });
+ await writeFile(path.join(root, slug, "config.json"), JSON.stringify({ handling: "youtube", ...config }));
+ };
+ await put("own", { name: "Own", url: "https://www.youtube.com/@own" });
+ await put("remote", { name: "Remote", platform: "youtube", remoteOnly: true, remoteArchive: "https://stub.test", downloadMode: "manual" });
+ assert.deepEqual(await siteChannelOptions({ channelsDir: root } as unknown as Paths), [{ slug: "own", name: "Own" }]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/editor/app/sites/lib/channelOptions.ts b/editor/app/sites/lib/channelOptions.ts
@@ -0,0 +1,13 @@
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import type { ChannelOption } from "../components/SiteForm";
+
+// The channels a site form offers: every channel but a REMOTE-ONLY one (demo
+// epic D1) — it holds a connected archive's clip windows, has no corpus to
+// publish, and the site writer refuses it anyway (lib/site.ts).
+export async function siteChannelOptions(paths: Paths): Promise<ChannelOption[]> {
+ return (await listChannelConfigs(paths))
+ .filter((c) => !isRemoteOnlyChannel(c.config))
+ .map((c) => ({ slug: c.slug, name: c.config.name ?? c.slug }));
+}
diff --git a/editor/app/sites/new/page.tsx b/editor/app/sites/new/page.tsx
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { siteChannelOptions } from "../lib/channelOptions";
import {
DEFAULT_GROUP_FALLBACK_ID,
FALLBACK_GROUP,
@@ -18,10 +18,7 @@ export const metadata: Metadata = { title: "New site — Sites" };
export default async function NewSitePage() {
const paths = getPaths();
- const channels: ChannelOption[] = (await listChannelConfigs(paths)).map((c) => ({
- slug: c.slug,
- name: c.config.name ?? c.slug,
- }));
+ const channels: ChannelOption[] = await siteChannelOptions(paths);
const allSites: SiteOption[] = listSites(paths).map((s) => ({
siteId: s.siteId,
siteTitle: s.siteTitle,
diff --git a/editor/app/sites/page.tsx b/editor/app/sites/page.tsx
@@ -22,6 +22,9 @@ import { AmendReleaseForm } from "./components/AmendReleaseForm";
import { HomepageConfigForm } from "./components/HomepageConfigForm";
import { PublishPanel, type PanelRow } from "./components/PublishPanel";
import { DeleteSiteButton, MigrateButton } from "./components/SiteListActions";
+import { ConnectArchive } from "./components/ConnectArchive";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Sites" };
@@ -129,6 +132,19 @@ export default async function SitesPage() {
</ul>
</section>
+ {/* Connected archives (demo epic D1): published archives read as
+ sources — Create, research and the MCP offer each one. */}
+ <section className="flex flex-col gap-3 border-t border-border pt-6" aria-labelledby="archives-heading">
+ <div>
+ <h2 id="archives-heading" className="text-lg font-semibold">Connected archives</h2>
+ <p className="text-sm text-muted-foreground">
+ Published archives this machine reads as sources: a sweep over one
+ cites it, and a clip it cites is fetched as a remote-only channel.
+ </p>
+ </div>
+ <ConnectArchive archives={connectedArchives(getSettings().remoteArchives)} />
+ </section>
+
{/* Release: stage the changelog before shipping anything. */}
<section className="flex flex-col gap-3 border-t border-border pt-6">
<div>
diff --git a/editor/e2e/remote-archive.spec.ts b/editor/e2e/remote-archive.spec.ts
@@ -0,0 +1,213 @@
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { spawnSync } from "node:child_process";
+import { createServer, type Server } from "node:http";
+import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import { dirname, extname, join, normalize, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { startFakeOllama, type FakeOllama } from "../../common/testing/llm/fakeOllama.mjs";
+import { writeDraftCorpus } from "../../common/testing/draft/corpus.mjs";
+import { baseUrl } from "./baseUrl";
+import { resetData, testPaths } from "./helpers";
+
+// A PUBLIC ARCHIVE IS A FIRST-CLASS SOURCE (demo epic D1, item 7): a fresh
+// editor with NO channels of its own, a STUB ARCHIVE (the synthetic draft
+// corpus served over loopback HTTP as a published site serves it — an older
+// corpus.json, no per-channel platform, so the resolver's record fallback is
+// what names the platform), and nothing fetched from the network:
+//
+// connect /sites → Connected archives: Read it (the probe), Connect
+// sweep a question over the archive on the local model (the fake ollama,
+// the recorded pipeline run): its links on the STUB's origin
+// project umtool's chain, step by step as its job runs them (current,
+// windows, manifest): the editor registers the cited channel
+// REMOTE-ONLY and fetches its windows (the fake yt-dlp); the
+// project's QR origin is the stub
+// link a citation's link opens on the stub at its second
+//
+// The stub's own page at `/` says which moment it was asked for.
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const RUNS = join(REPO, "common", "testing", "draft", "runs");
+const CHAIN_RUN = join(REPO, "umtool", "lib", "report", "chain-run.mjs");
+
+const TYPES: Record<string, string> = { ".json": "application/json", ".html": "text/html" };
+
+async function startStubArchive(dir: string): Promise<{ url: string; asked: string[]; close: () => Promise<void> }> {
+ const asked: string[] = [];
+ const server: Server = createServer(async (req, res) => {
+ const u = new URL(req.url ?? "/", "http://stub");
+ asked.push(u.pathname);
+ if (u.pathname === "/" || u.pathname === "/index.html") {
+ // The archive's viewer, as far as a link needs it: which moment.
+ const v = u.searchParams.get("v") ?? "";
+ const t = u.searchParams.get("t") ?? "";
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end(`<!doctype html><title>stub archive</title><p id="moment" data-v="${v.replace(/"/g, "")}" data-t="${t.replace(/"/g, "")}">v=${v} t=${t}</p>`);
+ return;
+ }
+ const file = normalize(join(dir, decodeURIComponent(u.pathname)));
+ if (!file.startsWith(dir)) {
+ res.writeHead(403).end();
+ return;
+ }
+ try {
+ const body = await readFile(file);
+ res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream", "access-control-allow-origin": "*" });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end("not found");
+ }
+ });
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
+ const port = (server.address() as { port: number }).port;
+ return { url: `http://127.0.0.1:${port}`, asked, close: () => new Promise((r) => server.close(() => r())) };
+}
+
+async function jobUntil(request: APIRequestContext, id: string, ms = 120_000) {
+ const t0 = Date.now();
+ let last = "";
+ while (Date.now() - t0 < ms) {
+ const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=60`, { headers: AUTH });
+ const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] };
+ last = body.job?.status ?? body.status ?? "";
+ if (["done", "failed", "cancelled"].includes(last)) return body;
+ await new Promise((r) => setTimeout(r, 400));
+ }
+ throw new Error(`job ${id} is still ${last}`);
+}
+
+test.describe.configure({ mode: "serial" });
+
+let stub: Awaited<ReturnType<typeof startStubArchive>>;
+let ol: FakeOllama;
+let scratch: string;
+
+test.beforeAll(async () => {
+ scratch = await mkdtemp(join(os.tmpdir(), "e2e-remote-archive-"));
+ const dir = join(scratch, "archive");
+ await writeDraftCorpus(dir);
+ // A build of its own, so no other run's cached copy answers for it.
+ const corpus = JSON.parse(await readFile(join(dir, "corpus.json"), "utf8"));
+ await writeFile(join(dir, "corpus.json"), JSON.stringify({ ...corpus, spec: 5, generatedAt: new Date().toISOString() }));
+ // A record's page is a video platform's (an archive's own URL is refused
+ // otherwise): YouTube's watch pages, which the fake yt-dlp answers.
+ for (const c of corpus.channels as { slug: string }[]) {
+ const page = join(dir, "transcripts", c.slug, "page-0000.json");
+ const records = JSON.parse(await readFile(page, "utf8")) as { id: string; webpageUrl?: string }[];
+ await writeFile(page, JSON.stringify(records.map((r) => ({ ...r, webpageUrl: `https://www.youtube.com/watch?v=${r.id}` }))));
+ }
+ stub = await startStubArchive(dir);
+ ol = await startFakeOllama();
+});
+
+test.afterAll(async () => {
+ await stub?.close();
+ await ol?.close();
+ await rm(scratch, { recursive: true, force: true });
+});
+
+test("a fresh editor with no channels: connect the stub archive, sweep it on the local model, fetch the cut's windows as a remote-only channel, open a link at its second", async ({ page, request }) => {
+ test.setTimeout(300_000);
+ await resetData(null);
+ const paths = testPaths();
+ expect(await readdir(join(paths.transcriptsDir, "channels"))).toEqual([]);
+ const settings = JSON.parse(await readFile(paths.settingsFile, "utf8"));
+ const projects = join(scratch, "projects");
+ await writeFile(paths.settingsFile, JSON.stringify({ ...settings, minFreeDiskGB: 0, generation: { ...(settings.generation ?? {}), ollamaUrl: ol.url, projectsRoot: projects } }, null, 2));
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ // ─── connect, in the UI ───
+ await page.goto(`${baseUrl}/sites`);
+ const panel = page.locator("[data-connected-archives]");
+ await expect(panel.getByText("No archive connected.")).toBeVisible();
+ await panel.getByLabel("archive origin").fill(`${stub.url}/`);
+ await panel.getByRole("button", { name: "Read it" }).click();
+ const probe = panel.locator(`[data-archive-probe="${stub.url}"]`);
+ await expect(probe).toContainText("Synth Kitchen");
+ await expect(probe).toContainText(/2 channels · \d+ videos/);
+ await panel.getByRole("button", { name: "Connect" }).click();
+ await expect(panel.getByRole("list", { name: "connected archives" }).locator("li")).toHaveCount(1);
+ const listed = await (await request.get(`${baseUrl}/api/ops/archives`, { headers: AUTH })).json();
+ expect(listed.archives).toEqual([expect.objectContaining({ origin: stub.url })]);
+
+ // ─── a question, swept over the archive on the local model ───
+ const run = JSON.parse(await readFile(join(RUNS, "sweep-pipeline.json"), "utf8"));
+ for (const turn of run.turns) ol.push(turn);
+ const draft = await request.post(`${baseUrl}/api/ops/report-draft`, {
+ headers: AUTH,
+ data: { task: "sweep", article: "remote-e2e", model: run.model, question: run.question, channels: run.channels, source: `remote:${stub.url}` },
+ });
+ const started = (await draft.json()) as { ok?: boolean; error?: string; jobId?: string };
+ expect(draft.status(), started.error).toBe(200);
+ const job = await jobUntil(request, started.jobId!);
+ expect(job.job?.status ?? job.status, (job.tail ?? []).join("\n")).toBe("done");
+ const itDir = join(paths.transcriptsDir, "reports", "remote-e2e", "iterations", "1");
+ const iteration = JSON.parse(await readFile(join(itDir, "iteration.json"), "utf8"));
+ expect(iteration.scope.source).toBe(`remote:${stub.url}`);
+ const report = JSON.parse(await readFile(join(itDir, "report.json"), "utf8"));
+ const cited = Object.values(report.citations as Record<string, { kind: string; channel: string; id: string; start: number }>).filter((c) => c.kind === "video");
+ expect(cited.length).toBeGreaterThan(0);
+ const sweep = await readFile(join(itDir, "sweep.md"), "utf8");
+ const links = [...sweep.matchAll(/\((https?:\/\/[^)\s]+\?v=[^)\s]+)\)/g)].map((m) => m[1]);
+ expect(links.length).toBeGreaterThan(0);
+ for (const l of links) expect(l.startsWith(`${stub.url}/?v=`), l).toBe(true);
+ // Nothing was asked of the editor's own corpus (it has none), and the stub was read.
+ expect(stub.asked).toContain("/corpus.json");
+ expect(stub.asked.some((p) => p.startsWith("/transcripts/synth-kitchen/"))).toBe(true);
+
+ // ─── the project: the chain's steps as its job runs them ───
+ const env: Record<string, string> = {
+ ...(process.env as Record<string, string>),
+ TRANSCRIPTS_DIR: paths.transcriptsDir,
+ SETTINGS_FILE: paths.settingsFile,
+ EXPORT_PUBLIC_DIR: join(scratch, "public"),
+ EXPORT_INDEX_DIR: join(scratch, ".export-index"),
+ EXPORT_BUILDS_DIR: join(scratch, ".export-builds"),
+ ARCHIVE_CACHE_DIR: join(scratch, ".archive-cache"),
+ ARCHILYZER_EDITOR_URL: baseUrl,
+ WORKER_TOKEN: "test-worker-token",
+ };
+ delete env.ARTICLES_DIR;
+ const step = (name: string) => {
+ const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "remote-e2e", "1", name, "--projects-root", projects], {
+ cwd: REPO,
+ env: env as NodeJS.ProcessEnv,
+ encoding: "utf8",
+ timeout: 180_000,
+ });
+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };
+ };
+ for (const name of ["current", "windows", "manifest"]) {
+ const r = step(name);
+ expect(r.code, `${name}: ${r.out}`).toBe(0);
+ }
+ // The cited channel is registered REMOTE-ONLY: config only, its platform from the archive's record.
+ const config = JSON.parse(await readFile(join(paths.transcriptsDir, "channels", "synth-kitchen", "config.json"), "utf8"));
+ expect(config).toMatchObject({ remoteOnly: true, remoteArchive: stub.url, platform: "youtube", downloadMode: "manual" });
+ expect(config.url).toBeUndefined();
+ // Every cited window is on disk under it.
+ for (const c of cited) {
+ const clips = await readdir(join(paths.transcriptsDir, "channels", c.channel, "data", c.id, "clips")).catch(() => [] as string[]);
+ expect(clips.filter((f) => f.endsWith(".mp4")).length, `${c.channel}/${c.id}`).toBeGreaterThan(0);
+ }
+ const manifest = JSON.parse(await readFile(join(projects, "remote-e2e", "i1", "video.manifest.json"), "utf8"));
+ expect(manifest.provenance.siteOrigin).toBe(stub.url);
+
+ // The channel list says what it is.
+ await page.goto(`${baseUrl}/channels`);
+ await expect(page.getByRole("note", { name: "remote-only channel synth-kitchen" })).toBeVisible();
+
+ // ─── a citation's link opens on the stub at its second ───
+ const link = links[0];
+ const at = new URL(link);
+ const t = at.searchParams.get("t");
+ expect(t, link).not.toBeNull();
+ const [channel, id] = (at.searchParams.get("v") ?? "").split("/");
+ // The second is the cited moment's: a citation of that recording starts there.
+ expect(cited.some((c) => c.channel === channel && c.id === id && Math.floor(c.start) === Number(t)), `${link} against ${JSON.stringify(cited)}`).toBe(true);
+ await page.goto(link);
+ await expect(page.locator("#moment")).toHaveAttribute("data-t", t!);
+ await expect(page.locator("#moment")).toHaveAttribute("data-v", `${channel}/${id}`);
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -40,6 +40,9 @@ export const E2E_SERVER_ENV: Record<string, string> = {
E2E_AUDIO_CHECK_RECOVER_AFTER: "2",
E2E_BACKOFF_BASE_MS: "20000",
E2E_CLIP_WINDOW_GAP_MS: "2000",
+ // remote-archive.spec's stub archive is on loopback (demo epic D1): the
+ // editor connects a local archive only when told so on its own machine.
+ ARCHILYZER_ALLOW_PRIVATE_ARCHIVES: "1",
E2E_AVAILABILITY_PROBE_GAP_MS: "0",
// The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on
// the test server — a spec's two fake X fetches would otherwise sit five
diff --git a/export/CHANGELOG.md b/export/CHANGELOG.md
@@ -1,5 +1,8 @@
# Changelog
+## [Unreleased]
+- **`corpus.json` is spec 6: each channel says where it is.** A channel's entry adds `platform` (youtube, rumble, …) and `url`, its page on that platform, when the archive's operator configured them, and `llms.txt` shows them beside the channel's name — what a machine with no copy of the channel needs to fetch a cited moment's media (a fresh Archilyzer clone pointed at the archive). Additive: a reader that does not know spec 6 reads the archive as before, and a reader of an older archive takes the platform from a transcript record's `webpageUrl`. Needs a rebuild and deploy of each site.
+
## [0.11.2] - 2026-10-21
- **A link to a moment of a removed YouTube video opens the transcript at that moment.** `?v=…&t=<seconds>` for a video YouTube no longer plays used to open its transcript at the start: the reader followed only the player, which never got there. The transcript now starts at the linked moment on every platform, and a player that cannot play leaves it there. Needs a rebuild and deploy of each site.
- **A report can keep a timeline, and a reader can subscribe to it.** `report.json` `entries` (each `{ "id", "date", "title", "body" }`, optionally `updated`) shows as **Timeline** after In brief: dated entries, newest first, each date linking to the entry's own place on the page (`#<id>`), each body citing as a section's does. The report counts as updated at its newest entry, in its header and the report list. Each entry is a slide too, and the HTML, PDF and Markdown downloads carry the Timeline. On a site with a public URL, the report publishes its timeline as feeds — `feed.xml` (RSS) and `feed.json` (JSON Feed) beside its page — and its header reads **Subscribe: RSS · JSON**; a feed reader finds them from the page too. A site with no public URL publishes no feed. The MCP's `get_report` reads the timeline, and its `section` may name an entry. Needs a rebuild and deploy of each site with reports.
diff --git a/mcp/src/connectedArchives.test.ts b/mcp/src/connectedArchives.test.ts
@@ -0,0 +1,27 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { connectedArchivesHere } from "./sources";
+
+// list_sources offers the archives the editor connected (demo epic D1): read
+// from settings.json through the one resolver, TRANSCRIPT_SITE_URL's added.
+test("the MCP lists the connected archives from settings.json, the environment's after them", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "mcp-archives-"));
+ try {
+ const file = path.join(dir, "settings.json");
+ await writeFile(file, JSON.stringify({ remoteArchives: [{ id: "stub", origin: "https://stub.test/", title: "Stub", addedAt: "2026-11-11T00:00:00Z" }] }));
+ const list = connectedArchivesHere(file, { TRANSCRIPT_SITE_URL: "https://other.test" });
+ assert.deepEqual(
+ list.map((a) => [a.id, a.origin, a.fromEnv ?? false]),
+ [
+ ["stub", "https://stub.test", false],
+ ["other-test", "https://other.test", true],
+ ],
+ );
+ assert.deepEqual(connectedArchivesHere(path.join(dir, "missing.json"), {}), []);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/mcp/src/fetchClip.ts b/mcp/src/fetchClip.ts
@@ -178,6 +178,10 @@ export type FetchClipRequest =
reason: string;
report?: string;
waitSeconds: number;
+ // The published archive the clip is cited from (demo epic D1): the
+ // editor registers a channel it does not hold as remote-only of it, when
+ // it is a connected archive. Set by the server from a remote source.
+ archive?: string;
};
const trimmed = (v: unknown): string =>
@@ -549,6 +553,7 @@ export async function fetchClip(
pad: target.pad,
...capped,
...(target.storedUrl ? { storedUrl: target.storedUrl } : {}),
+ ...(request.archive ? { archive: request.archive } : {}),
...provenance,
};
const res = await call(`${editor.url}/api/media/fetch-window`, {
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -576,3 +576,21 @@ test("generate propose-groups: a project (words optional); routed to code, the p
assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused/);
assert.match(b.text, /Nothing in the cut changed/);
});
+
+// demo epic D1: a sweep over a published archive names it to the editor.
+test("generate carries source for a sweep or research run, refuses it elsewhere", async () => {
+ const { generateArgsWithSource } = await import("./server");
+ const ok = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "remote:https://stub.test" });
+ assert.equal(ok.ok, true);
+ assert.equal((ok as { request: { body: Record<string, unknown> } }).request.body.source, "remote:https://stub.test");
+ const bad = validateGenerateArgs({ task: "revise-report", article: "a", iteration: 1, feedback: "x", source: "remote:https://stub.test" });
+ assert.match(String((bad as { error: string }).error), /source is a sweep's or a research run's/);
+ assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "nope" }) as { error: string }).error), /corpus handle/);
+ // The server's resolution: the canonical handle of a remote or hub, never a local dir; only sweep and research.
+ const remote = { handle: "remote:https://stub.test", spec: { kind: "remote" as const, url: "https://stub.test" } };
+ assert.equal(generateArgsWithSource({ task: "sweep", source: "https://stub.test/" }, remote).source, "remote:https://stub.test");
+ assert.equal(generateArgsWithSource({ task: "research" }, remote).source, "remote:https://stub.test");
+ assert.equal("source" in generateArgsWithSource({ task: "narrate", source: "x" }, remote), false);
+ const local = { handle: "local:/x", spec: { kind: "local" as const, dir: "/x" } };
+ assert.equal("source" in generateArgsWithSource({ task: "sweep" }, local), false);
+});
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -254,6 +254,12 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
if (n === null) return bad(`${k} is an iteration number (1, 2, …)`);
if (n !== undefined) body[k] = n;
}
+ if (args.source !== undefined && args.source !== null) {
+ const src = trimmed(args.source);
+ if (!/^(local|remote|hub):\S+/.test(src)) return bad("source is a corpus handle: remote:<url>, hub:<url> or local:<dir>");
+ if (task !== "sweep" && task !== "research") return bad("source is a sweep's or a research run's (the corpus it reads)");
+ body.source = src;
+ }
for (const k of ["model", "extractorModel", "feedback", "question", "from", "to"] as const) {
if (args[k] === undefined) continue;
const v = trimmed(args[k]);
@@ -960,6 +966,12 @@ export const GENERATION_TOOLS = [
},
question: { type: "string", description: "sweep / research: the question, in words." },
channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." },
+ source: {
+ type: "string",
+ description:
+ "sweep / research: the corpus the editor reads and the sweep cites — a handle (remote:<archive origin>, hub:<url>). " +
+ "Omitted: this server's default corpus when it is a published archive or a hub, else the editor's own build holding the channels.",
+ },
from: { type: "string", description: "sweep: only videos on or after this date (YYYY-MM-DD)." },
to: { type: "string", description: "sweep: only videos on or before this date (YYYY-MM-DD)." },
feedback: { type: "string", description: "A revision's feedback: what to change, concretely." },
diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts
@@ -369,7 +369,9 @@ function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; mode
`${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}${r.model ? ` (${r.model})` : ""} by ${r.by}. ` +
`Call \`generate\` with task: "sweep", ${article}, ${question}, ${channels}${model}, ` +
`wait: true (add from/to, YYYY-MM-DD, when I named a period). The editor runs ` +
- `it as a report-draft job on its own corpus build and caps; the article's ` +
+ `it as a report-draft job, under its caps, over the corpus the call names in \`source\` — ` +
+ `omitted, this server's default when that is a published archive (remote:<origin>) or a hub, ` +
+ `else the editor's own build holding the channels — and the sweep cites that archive; the article's ` +
`iteration is what it makes, never its published report. If the answer ` +
`says it is still running, call \`generate\` again with the job, article ` +
`and iteration it names and wait: true — never enqueue the same sweep ` +
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -45,7 +45,7 @@ import {
type HubSite,
type ShardSource,
} from "./source";
-import type { SourceSpec } from "./sources";
+import { connectedArchivesHere, type SourceSpec } from "./sources";
import { SourceRegistry, type ResolvedSource } from "./sourceRegistry";
import type { Post } from "yt-dlp-transcript-common/lib/posts";
import {
@@ -1210,7 +1210,10 @@ async function handleFetchClip(
const { note, ctx } = await resolveClipTarget(source, resolved.handle, request);
- const outcome = await fetchClip(request, deps, { onPoll });
+ // A clip cited from a published archive names it (demo epic D1): the editor
+ // registers its channel remote-only when the archive is connected there.
+ const archived = "target" in request && resolved.spec.kind === "remote" ? { ...request, archive: resolved.spec.url } : request;
+ const outcome = await fetchClip(archived, deps, { onPoll });
const rendered = renderFetchClip(outcome, ctx);
const body = `${note}${rendered.text}`;
return rendered.isError ? errorText(body) : text(body);
@@ -1354,7 +1357,7 @@ export function createServer(
case "generate":
return fromAnswer(
await generateTool(
- args,
+ generateArgsWithSource(args, resolved),
fetchClipDeps,
progressNotifier(ctx.mcpReq._meta?.progressToken, ctx.mcpReq.notify),
),
@@ -2662,6 +2665,21 @@ async function describeDigest(
return out.length > 1 ? out.join("\n") : "";
}
+// generate's `source` (demo epic D1): the corpus a sweep or a research run
+// reads and cites. The call's own `source`, resolved to its canonical handle,
+// when it names a published archive or a hub — and, when it names none, this
+// server's default if that is one: an MCP pointed at jeralyzer.pages.dev asks
+// the editor to sweep jeralyzer.pages.dev, not whatever build it holds. A
+// LOCAL corpus is not sent: the editor picks its own build holding the
+// channels, as before. Only a sweep or a research run carries it.
+export function generateArgsWithSource(args: Record<string, unknown>, resolved: Pick<ResolvedSource, "handle" | "spec">): Record<string, unknown> {
+ const { source: _asked, ...rest } = args;
+ const task = typeof args.task === "string" ? args.task.trim() : "";
+ if (task !== "sweep" && task !== "research") return rest;
+ if (resolved.spec.kind === "local") return rest;
+ return { ...rest, source: resolved.handle };
+}
+
// ─── Source discovery: list_sources / resolve_source ───
// A one-line human description of a source spec's target (kind + where it
@@ -2740,6 +2758,18 @@ async function handleListSources(
);
}
+ // The archives this machine's editor connected (demo epic D1): each a
+ // handle to pass, offered beside the default.
+ const connected = connectedArchivesHere();
+ if (connected.length > 0) {
+ lines.push(
+ `\nArchives connected on this machine (${connected.length}):\n` +
+ connected
+ .map((a) => ` - ${a.title} · ${a.origin}${a.fromEnv ? " (TRANSCRIPT_SITE_URL)" : ""}\n source: remote:${a.origin}`)
+ .join("\n"),
+ );
+ }
+
lines.push(
`\nPass a corpus per call, in each tool's own \`source\` argument — ` +
`'default', 'local:<dir>', 'remote:<url>', 'hub:<url>', or ` +
diff --git a/mcp/src/sources.ts b/mcp/src/sources.ts
@@ -1,3 +1,7 @@
+import { readFileSync } from "node:fs";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { connectedArchives, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { archiveCache, archiveCacheEnabled } from "yt-dlp-transcript-common/lib/archiveCache-server";
import {
LocalSource,
RemoteSource,
@@ -54,7 +58,9 @@ export function buildSource(spec: SourceSpec): ShardSource {
case "hub":
return new HubSource(spec.url, spec.sites);
case "remote":
- return new RemoteSource(spec.url);
+ // Its shards cached on disk while the archive's build is unchanged, read
+ // one at a time, paced (demo epic D1: common/lib/archiveCache-server.ts).
+ return archiveCacheEnabled() ? new RemoteSource(spec.url, undefined, { fetch: archiveCache().fetch as typeof fetch }) : new RemoteSource(spec.url);
case "local":
return new LocalSource(spec.dir);
}
@@ -64,3 +70,21 @@ export function buildSource(spec: SourceSpec): ShardSource {
export function resolveSource(argv: string[]): ShardSource {
return buildSource(resolveSourceSpec(argv));
}
+
+// The archives this machine's editor has CONNECTED (settings.remoteArchives,
+// plus TRANSCRIPT_SITE_URL's — the one resolver, common/lib/remoteArchives.ts),
+// for list_sources: each one a `remote:<origin>` handle a call can pass. Read
+// from settings.json (SETTINGS_FILE, else the checkout's); a clone with none, or
+// no readable file, has only the environment's.
+export function connectedArchivesHere(
+ settingsFile: string = getPaths().settingsFile,
+ env: Record<string, string | undefined> = process.env,
+): ConnectedArchive[] {
+ let stored: unknown = [];
+ try {
+ stored = (JSON.parse(readFileSync(settingsFile, "utf8")) as { remoteArchives?: unknown })?.remoteArchives ?? [];
+ } catch {
+ stored = [];
+ }
+ return connectedArchives(stored, env);
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -135,6 +135,8 @@
// tag exists on, absent = every site — included)
// pnpm ops tag-videos --file ids.json
// pnpm ops persist-videos --file list.json --wait
+// pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev","dryRun":true}'
+// pnpm ops get archives
// pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'
// pnpm ops fetch-windows --file windows.json --wait
// pnpm ops get tags eva-collab
@@ -290,6 +292,9 @@ const GETTERS = {
slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates",
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
+ // The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's,
+ // marked fromEnv): the published archives this machine reads as sources.
+ archives: () => "/api/ops/archives",
// The transcription workers and what each is running.
workers: () => "/api/ops/workers",
// The four lanes: runner, policy, cooldowns, picks, pending.
@@ -362,6 +367,7 @@ const GET_ARG_OPTIONAL = new Set([
"storage",
"saved-alternates",
"sites",
+ "archives",
"workers",
"auto-queue",
"scheduler",
@@ -420,6 +426,10 @@ const ACTIONS = [
// Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its
// publish state and its staging. Channel data is never touched. Synchronous.
"delete-site",
+ // Connect a published archive as a source ({connect: "<origin>", dryRun?}:
+ // its corpus.json read once, then saved) or remove one ({remove: "<id>"}).
+ // Synchronous; no job.
+ "archives",
// The channel's lifecycle: the New channel form, and the channel page's
// Danger → Rename and Danger → Delete. Synchronous; no job.
"create-channel",
@@ -1152,6 +1162,8 @@ export function usage() {
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
+ "get archives lists the connected archives: id, origin, title, addedAt;",
+ " TRANSCRIPT_SITE_URL's, when set and not stored, is listed with fromEnv.",
"get workers, get auto-queue and get scheduler are /workers, the four lanes",
" of /operations, and /operations/sync — the payloads those pages poll.",
"get services is the dashboard's cookie refresh alerts: each service",
@@ -1583,6 +1595,14 @@ export function usage() {
" own. Refused, force or not: no such site (404), a site dir that is a link,",
" a publish stage running.",
"",
+ 'archives connects a published archive as a source: {"connect": "<origin>"}',
+ " reads <origin>/corpus.json once (its title, totals and channels) and saves",
+ ' it in settings.remoteArchives; "dryRun"? answers the probe and writes',
+ " nothing; an origin connected already writes nothing. A federation hub, a",
+ " cited-only site, one with no channels or one that does not answer is",
+ ' refused. {"remove": "<id or origin>"} drops one. Create, research and the',
+ " MCP offer each connected archive; a sweep over it cites it.",
+ "",
'create-channel is the New channel form: {"fields": {"name", "handling":',
' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,',
' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else',
@@ -1947,6 +1967,15 @@ export function usage() {
" fetches in place of the platform's floor (Rumble's 120 s); still jittered",
" up to half again. Shorter than the default risks Rumble's IP-wide",
" Cloudflare challenge; a Retry keeps it.",
+ ' "archive" (items only) names the CONNECTED archive the items cite',
+ " (settings.remoteArchives): a channel this editor does not hold is",
+ ' registered as a remote-only channel of it (config only, no listing;',
+ ' answered in "registered"; a dry run registers nothing), and a remote-only',
+ " channel's page URL comes from the archive's record. Its window on a",
+ " whole-recording platform is refused with the recording's estimated size",
+ ' unless "allowWholeRecording": true. Another origin registers nothing.',
+ " A media URL's transient 403 (googlevideo's) is asked once more after a",
+ " pause before it counts toward the two-403 stop.",
' A window on a whole-recording platform (settings.clips',
' .wholeRecordingPlatforms, default Rumble) is not seeked: the video is',
' saved whole once, as "Persist source video" saves it, on the platform\'s',
diff --git a/settings.json.example b/settings.json.example
@@ -217,6 +217,7 @@
"archiveTodayCooldownMinutes": 30,
"archiveTodayBrowser": true
},
+ "remoteArchives": [],
"publish": {
"enabled": false,
"held": false,
diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts
@@ -13,7 +13,7 @@ export const dynamic = "force-dynamic";
// `from`. The projects root is the editor's policy's (generation.projectsRoot).
//
// GET ?article=<id>&n=<n>[&mode=draft-all][&deck=1] -> { chain } the steps, where it resumes, its job
-// POST { article, n, from?, draftAll?, model?, deck? } -> { ok, job } started
+// POST { article, n, from?, draftAll?, model?, deck?, stopBeforeRender?, allowWholeRecording? } -> { ok, job } started
// POST { cancel: <jobId> } -> { cancelled }
//
// `draftAll` is Draft everything (release 28 M9): the chain with its
@@ -21,6 +21,10 @@ export const dynamic = "force-dynamic";
// route) — and the fast build; a job of its own kind, resumed as the chain is.
// `deck` (release 29 G1, Draft everything's option, off by default) adds the
// deck step before the flips: the minimal on-screen deck on a cut with none.
+// `stopBeforeRender` (demo epic D1) ends the run before the voices: nothing
+// voiced or built; the next run resumes there. `allowWholeRecording` (the
+// windows step's one press) lets a remote-only channel's Rumble windows
+// download their whole recording, refused with its size otherwise.
function parse(article: unknown, n: unknown): { article: string; n: number } | string {
const a = String(article ?? "");
const k = Number(n);
@@ -52,7 +56,17 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown; deck?: unknown };
+ const body = (await request.json().catch(() => ({}))) as {
+ article?: unknown;
+ n?: unknown;
+ from?: unknown;
+ cancel?: unknown;
+ draftAll?: unknown;
+ model?: unknown;
+ deck?: unknown;
+ stopBeforeRender?: unknown;
+ allowWholeRecording?: unknown;
+ };
if (body.cancel !== undefined) {
const id = String(body.cancel);
if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 });
@@ -73,7 +87,18 @@ export async function POST(request: Request) {
if (model && mode !== "draft-all") return Response.json({ error: "a model is Draft everything's (draftAll): the model its drafts run on" }, { status: 400 });
const deck = body.deck === true;
if (deck && mode !== "draft-all") return Response.json({ error: "the deck is Draft everything's option (draftAll)" }, { status: 400 });
- const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(deck ? { deck } : {}), ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) });
+ const plan = planChain({
+ articlesDir: ARTICLES_DIR,
+ article: p.article,
+ n: p.n,
+ from,
+ mode,
+ ...(deck ? { deck } : {}),
+ ...(model ? { model } : {}),
+ ...(projectsRoot ? { projectsRoot } : {}),
+ ...(body.stopBeforeRender === true ? { stopBeforeRender: true } : {}),
+ ...(body.allowWholeRecording === true ? { allowWholeRecording: true } : {}),
+ });
if (plan.steps.length === 0) return Response.json({ error: `every step of ${mode === "draft-all" ? "Draft everything" : "the chain"} is done — pick a step to run from` }, { status: 400 });
const job = startJob(chainKind(p.article, p.n, mode), plan.steps);
return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode, deck) });
diff --git a/umtool/app/api/articles/channels/route.ts b/umtool/app/api/articles/channels/route.ts
@@ -1,12 +1,28 @@
-import { errorResponse, listEditorChannels } from "@/lib/articles/generation";
+import { errorResponse, listEditorChannels, type EditorChannel } from "@/lib/articles/generation";
+import { SourceError, openSource } from "@/lib/research/sources";
export const dynamic = "force-dynamic";
-// The editor's channels, for /articles/new's picker (GET /api/ops/channels).
-export async function GET() {
+// The channels /articles/new's picker offers (GET /api/ops/channels): the
+// editor's own, or — `?source=remote:<origin>` (demo epic D1 item 2) — that
+// published archive's, from its corpus.json. Only an offered source opens
+// (lib/research/sources.ts openSource refuses any other handle). A remote-only
+// channel is not offered as the editor's own: it holds no transcripts.
+export async function GET(request: Request) {
try {
- return Response.json({ channels: await listEditorChannels() }, { headers: { "cache-control": "no-store" } });
+ const source = new URL(request.url).searchParams.get("source")?.trim();
+ if (!source) {
+ const channels = (await listEditorChannels()).filter((c) => c.kind !== "remote-only");
+ return Response.json({ channels }, { headers: { "cache-control": "no-store" } });
+ }
+ const opened = await openSource(source);
+ const refs = await opened.source.listChannels();
+ const channels: EditorChannel[] = refs
+ .map((c) => ({ slug: c.slug, name: c.name ?? c.slug, kind: "video", platform: c.platform ?? null, sites: [] }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ return Response.json({ channels, source: opened.option.handle }, { headers: { "cache-control": "no-store" } });
} catch (err) {
+ if (err instanceof SourceError) return Response.json({ error: err.message }, { status: err.status });
return errorResponse(err);
}
}
diff --git a/umtool/app/api/articles/sources/route.ts b/umtool/app/api/articles/sources/route.ts
@@ -0,0 +1,21 @@
+import { errorResponse, listEditorChannels } from "@/lib/articles/generation";
+import { createSourcesOf } from "@/lib/articles/createSources";
+import { listSources } from "@/lib/research/sources";
+
+export const dynamic = "force-dynamic";
+
+// The corpora "Article from a question" may sweep (demo epic D1 item 2): the
+// editor's own (its channels and the build holding them; handle "") and every
+// published archive the source picker offers (connected archives first). With
+// no local corpus — the editor holds no channel of its own — and an archive to
+// offer, the first archive is preselected.
+//
+// GET -> { sources: [{ handle, label, detail? }], preselect }
+export async function GET() {
+ try {
+ const [sources, channels] = await Promise.all([listSources(), listEditorChannels().catch(() => null)]);
+ return Response.json(createSourcesOf(sources, channels), { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
diff --git a/umtool/app/api/research/archives/route.ts b/umtool/app/api/research/archives/route.ts
@@ -0,0 +1,21 @@
+import { askEditor } from "@/lib/articles/generation";
+import { fail, ok } from "../_respond";
+
+export const dynamic = "force-dynamic";
+
+// CONNECT AN ARCHIVE from the Source chip (demo epic D1): forwarded to the
+// editor's `archives` action, which reads the archive's corpus.json and — unless
+// `dryRun` — saves it in settings.remoteArchives (the one writer). The chip then
+// lists it (lib/research/sources.ts reads the same list).
+//
+// POST { origin, dryRun? } -> the editor's { ok, archive, probe, already }
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as { origin?: unknown; dryRun?: unknown } | null;
+ if (!body || typeof body.origin !== "string" || !body.origin.trim()) return Response.json({ error: "send { origin }: the archive's address" }, { status: 400 });
+ const answer = await askEditor("/api/ops/archives", { method: "POST", body: { connect: body.origin.trim(), ...(body.dryRun === true ? { dryRun: true } : {}) } });
+ return ok(answer);
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -46,11 +46,15 @@
// umtool build <project> [--preset preview|fast|final] [--only ID] [--dry]
// [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels
// umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]
-// [--draft-all [--model M] [--deck]]
+// [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]
// an iteration's pipeline: current, windows, prepare, posts, manifest,
// voices, video, podcast, attach, dedupe (resumes at the first step not done);
-// --draft-all is Draft everything: the drafts between manifest and the fast build;
-// --deck adds the on-screen deck to a cut with none before the flips
+// --draft-all is Draft everything: the drafts between manifest and the fast build,
+// the cut's windows after the cut is drafted (cut-windows);
+// --deck adds the on-screen deck to a cut with none before the flips;
+// --stop-before-render ends it before the voices (nothing voiced or built);
+// --allow-whole-recording lets a remote-only channel's windows download
+// their whole recording (Rumble), which is refused with its size otherwise
// umtool index [--rebuild] [--prune] [--since MS] [--json]
// umtool new <slug> | <folder>/<slug> [--folder <folder>] [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
// [--site-origin URL] [--seed chapters|frames [--target S]] [--brand archilyzer-media]
@@ -1427,7 +1431,7 @@ async function cmdChain() {
const article = positional[0];
const n = Number(positional[1]);
if (!article || !Number.isInteger(n) || n < 1) {
- die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]");
+ die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]");
}
const draftAll = has("--draft-all");
if (val("--model") && !draftAll) die("--model is Draft everything's (--draft-all): the model its drafts run on");
@@ -1445,12 +1449,14 @@ async function cmdChain() {
...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}),
final: has("--final"),
...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}), ...(deck ? { deck: true } : {}) } : {}),
+ ...(has("--stop-before-render") ? { stopBeforeRender: true } : {}),
+ ...(has("--allow-whole-recording") ? { allowWholeRecording: true } : {}),
});
} catch (err) {
die(err.message);
}
const { start, steps } = plan;
- const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}`;
+ const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}${has("--stop-before-render") ? " --stop-before-render" : ""}`;
if (json && has("--dry")) return out({ article, n, start, steps });
if (steps.length === 0) {
console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`);
diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { JobProgress, type JobStep, type JobStepState } from "@/components/ui/job-progress";
import type { ChainMode, ChainView } from "@/lib/articles/generation";
import { spendFromLog } from "@/lib/running.mjs";
+import { WHOLE_RECORDING_REFUSED } from "yt-dlp-transcript-common/lib/remoteArchives";
// MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten
// steps (lib/report/chain.mjs) as a umtool job — what each step last did, where
@@ -36,6 +37,8 @@ export default function ChainPanel({
const [from, setFrom] = useState<string>("");
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
+ // Stop before render (demo epic D1): this run ends before the voices.
+ const [stopBefore, setStopBefore] = useState(false);
const load = useCallback(async () => {
const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? `&mode=draft-all${deck ? "&deck=1" : ""}` : ""}`, { cache: "no-store" });
@@ -58,13 +61,21 @@ export default function ChainPanel({
return () => clearInterval(t);
}, [running, load]);
- const start = useCallback(async () => {
+ const start = useCallback(async (extra: { from?: string; allowWholeRecording?: boolean } = {}) => {
setError("");
setSending(true);
try {
+ const at = extra.from ?? from;
const r = await fetch("/api/articles/chain", {
method: "POST",
- body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}) }),
+ body: JSON.stringify({
+ article,
+ n,
+ ...(at ? { from: at } : {}),
+ ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}),
+ ...(stopBefore ? { stopBeforeRender: true } : {}),
+ ...(extra.allowWholeRecording ? { allowWholeRecording: true } : {}),
+ }),
});
const b = await r.json();
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
@@ -75,7 +86,7 @@ export default function ChainPanel({
} finally {
setSending(false);
}
- }, [article, n, from, draftAll, model, deck, load]);
+ }, [article, n, from, draftAll, model, deck, stopBefore, load]);
useEffect(() => {
if (!autoStart || started.current) return;
@@ -102,6 +113,9 @@ export default function ChainPanel({
attrs: { "data-chain-step": s.name, "data-step-status": s.status },
}));
const job = chain?.job ?? null;
+ // A windows step a remote-only channel's whole recording refused, with its
+ // size (demo epic D1): one press fetches them and goes on from there.
+ const wholeRefused = chain?.steps.find((s) => s.status === "failed" && (s.detail ?? "").startsWith(WHOLE_RECORDING_REFUSED)) ?? null;
const done = job ? chain!.steps.filter((s) => s.status === "done" || s.status === "skipped" || s.status === "failed").length : 0;
return (
<section
@@ -143,6 +157,14 @@ export default function ChainPanel({
)}
</JobProgress>
)}
+ {!running && wholeRefused && (
+ <div className="flex flex-wrap items-center gap-2 rounded-[3px] border border-seam-2 p-2" data-whole-recording-refused={wholeRefused.name}>
+ <p className="min-w-0 flex-1 text-text-2">{wholeRefused.detail}</p>
+ <Button size="sm" variant="outline" disabled={sending} onClick={() => void start({ from: wholeRefused.name, allowWholeRecording: true })}>
+ Fetch the whole recordings
+ </Button>
+ </div>
+ )}
{!running && (
<div className="flex flex-wrap items-center gap-2">
<label className="flex items-center gap-1">
@@ -161,6 +183,10 @@ export default function ChainPanel({
))}
</select>
</label>
+ <label className="flex items-center gap-1 text-muted" title="end this run before the voices: nothing voiced or built; the next run resumes there">
+ <input type="checkbox" aria-label={`${label} stop before render`} checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} />
+ stop before render
+ </label>
<Button size="sm" variant="outline" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}>
{draftAll ? "Run Draft everything" : "Run the chain"}
</Button>
diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx
@@ -43,19 +43,23 @@ const AUTONOMY_SAYS: Record<Autonomy, string> = {
};
// Exported for Create's recurring form (R5): the same picker, the same channels.
-export function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
+// `source` (demo epic D1): a published archive's handle lists ITS channels
+// (its corpus.json); none, the editor's own.
+export function ChannelPicker({ value, onChange, source = "" }: { value: string[]; onChange: (v: string[]) => void; source?: string }) {
const [all, setAll] = useState<EditorChannel[] | null>(null);
const [error, setError] = useState("");
const [q, setQ] = useState("");
useEffect(() => {
- fetch("/api/articles/channels", { cache: "no-store" })
+ setAll(null);
+ setError("");
+ fetch(source ? `/api/articles/channels?source=${encodeURIComponent(source)}` : "/api/articles/channels", { cache: "no-store" })
.then(async (r) => {
const b = await r.json();
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
setAll(b.channels);
})
.catch((e) => setError((e as Error).message));
- }, []);
+ }, [source]);
const shown = useMemo(() => {
const k = q.trim().toLowerCase();
return (all ?? []).filter((c) => !k || c.slug.includes(k) || c.name.toLowerCase().includes(k)).slice(0, 80);
@@ -97,7 +101,7 @@ export function ChannelPicker({ value, onChange }: { value: string[]; onChange:
<button
type="button"
aria-pressed={value.includes(c.slug)}
- title={`${c.slug}${c.sites.length ? ` · on ${c.sites.join(", ")}` : " · on no site"}`}
+ title={`${c.slug}${source ? "" : c.sites.length ? ` · on ${c.sites.join(", ")}` : " · on no site"}`}
className={`rounded border px-1.5 py-0.5 text-[12px] hover:bg-[var(--color-panel-2)] ${value.includes(c.slug) ? "border-[var(--color-muted)] bg-[var(--color-panel-2)] text-[var(--color-text)]" : "border-[var(--color-line)]"}`}
onClick={() => toggle(c.slug)}
>
@@ -157,6 +161,21 @@ export default function NewArticleForm({
const [id, setId] = useState("");
const [question, setQuestion] = useState("");
const [channels, setChannels] = useState<string[]>([]);
+ // The corpus the sweep reads and cites (demo epic D1): "" the editor's own,
+ // else a published archive's handle. Preselected when the editor holds no
+ // channel and an archive is connected (/api/articles/sources).
+ const [sources, setSources] = useState<{ handle: string; label: string; detail?: string }[] | null>(null);
+ const [source, setSource] = useState("");
+ useEffect(() => {
+ fetch("/api/articles/sources", { cache: "no-store" })
+ .then(async (r) => {
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setSources(b.sources);
+ if (b.preselect) setSource(b.preselect);
+ })
+ .catch(() => setSources([]));
+ }, []);
const [from, setFrom] = useState("");
const [to, setTo] = useState("");
const [title, setTitle] = useState("");
@@ -205,6 +224,7 @@ export default function NewArticleForm({
article: id,
question,
...(channels.length ? { channels } : {}),
+ ...(source ? { source } : {}),
model,
...(begin === "sweep" ? extractorBody(model, extractor, policy?.generation.models.extractor) : {}),
...(from ? { from } : {}),
@@ -288,10 +308,33 @@ export default function NewArticleForm({
</div>
</fieldset>
) : (
- <div className="flex flex-col gap-1">
- <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span>
- <ChannelPicker value={channels} onChange={setChannels} />
- </div>
+ <>
+ {sources && sources.length > 1 && (
+ <label className="flex flex-col gap-1">
+ <span className="micro">source</span>
+ <select
+ className={`${field} max-w-md`}
+ aria-label="source"
+ value={source}
+ onChange={(e) => {
+ setSource(e.target.value);
+ setChannels([]);
+ }}
+ >
+ {sources.map((s) => (
+ <option key={s.handle || "local"} value={s.handle}>
+ {s.label}
+ {s.detail ? ` · ${s.detail}` : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <div className="flex flex-col gap-1">
+ <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span>
+ <ChannelPicker value={channels} onChange={setChannels} source={source} />
+ </div>
+ </>
)}
<div className="flex flex-wrap items-end gap-4">
diff --git a/umtool/components/create/forms.tsx b/umtool/components/create/forms.tsx
@@ -214,6 +214,7 @@ export function ArticleVideoForm({
const [chain, setChain] = useState<ChainView | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
+ const [stopBefore, setStopBefore] = useState(false);
// The article's iterations: those with a report (done) are what a chain runs over.
useEffect(() => {
@@ -255,10 +256,17 @@ export function ArticleVideoForm({
const start = async () => {
if (!article || n === null) return;
+ // stopBefore (demo epic D1): the run ends before the voices.
setBusy(true);
setError(null);
try {
- await json(await fetch("/api/articles/chain", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ article, n }) }));
+ await json(
+ await fetch("/api/articles/chain", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ article, n, ...(stopBefore ? { stopBeforeRender: true } : {}) }),
+ }),
+ );
router.push(articleHref({ site: "articles", id: article }, { tab: "iterations" }));
} catch (e) {
setError((e as Error).message);
@@ -303,6 +311,10 @@ export function ArticleVideoForm({
))}
</Select>
</Field>
+ <label className="flex items-center gap-1 self-center text-[12px] text-text-2" title="end the run before the voices: nothing voiced or built; the next run resumes there">
+ <input type="checkbox" aria-label="stop before render" checked={stopBefore} onChange={(e) => setStopBefore(e.target.checked)} />
+ stop before render
+ </label>
<Actions error={error}>
<Button type="submit" variant="go" disabled={busy || n === null || !chain || chain.resumeAt === null || chain.job?.state === "running"}>
{busy ? "Starting…" : "Make the video"}
diff --git a/umtool/components/research/ConnectArchive.tsx b/umtool/components/research/ConnectArchive.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { controlClass } from "@/components/ui/field";
+import { cn } from "@/lib/utils";
+
+// CONNECT AN ARCHIVE (demo epic D1), from the Source chip: type an origin, Read
+// it (its corpus.json: title, channels, videos — nothing saved), Connect. The
+// editor's `archives` action does both (POST /api/research/archives forwards),
+// so a connect here is the one /sites and `pnpm ops archives` make. Connected,
+// the page reloads its sources and the scope moves to the new one.
+
+type Probe = { origin: string; title: string; totals: { channels: number; videos: number }; channels: { slug: string; name: string; videoCount: number | null }[] };
+
+const nf = new Intl.NumberFormat("en-US");
+
+export default function ConnectArchive({ onConnected, onCancel }: { onConnected: (handle: string) => void; onCancel: () => void }) {
+ const router = useRouter();
+ const [origin, setOrigin] = useState("");
+ const [probe, setProbe] = useState<Probe | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ async function ask(dryRun: boolean) {
+ setBusy(true);
+ setError("");
+ try {
+ const r = await fetch("/api/research/archives", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ origin: probe?.origin ?? origin, dryRun }),
+ });
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ if (dryRun) setProbe(b.probe);
+ else {
+ router.refresh();
+ onConnected(`remote:${b.archive.origin}`);
+ }
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <form
+ aria-label="connect an archive"
+ className="flex basis-full flex-col gap-1.5 rounded-[3px] border border-seam-2 bg-panel p-2.5 text-[12.5px]"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void ask(!probe);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ autoFocus
+ aria-label="archive origin"
+ placeholder="https://jeralyzer.pages.dev"
+ value={origin}
+ onChange={(e) => {
+ setOrigin(e.target.value);
+ setProbe(null);
+ }}
+ className={cn(controlClass, "w-72 py-[3px] text-[12px]")}
+ />
+ <Button type="submit" size="sm" variant={probe ? "go" : "outline"} disabled={busy || !origin.trim()}>
+ {busy ? "Reading…" : probe ? "Connect" : "Read it"}
+ </Button>
+ <Button type="button" size="sm" variant="quiet" onClick={onCancel}>
+ Cancel
+ </Button>
+ </div>
+ {probe && (
+ <p data-archive-probe={probe.origin} className="text-text-2">
+ <span className="font-medium text-text">{probe.title}</span> · {nf.format(probe.totals.channels)} channels · {nf.format(probe.totals.videos)} videos
+ <span className="text-muted">
+ {" "}
+ — {probe.channels.slice(0, 8).map((c) => c.name).join(", ")}
+ {probe.channels.length > 8 ? `, and ${probe.channels.length - 8} more` : ""}
+ </span>
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="text-bad">
+ {error}
+ </p>
+ )}
+ </form>
+ );
+}
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -1,11 +1,15 @@
"use client";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { VIDEO_STATES, VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
import { badgeVariants } from "@/components/ui/badge";
import { controlClass } from "@/components/ui/field";
import { cn } from "@/lib/utils";
import type { Scope, ScopeSummary, SourceOption } from "@/lib/research/types";
+import ConnectArchive from "./ConnectArchive";
+
+// The Source select's last option: not a source, the Connect form (demo epic D1).
+const CONNECT = "connect:";
// ---------------------------------------------------------------------------
// The scope chips and the "holds …" line under them (canvas `.scope`): which
@@ -58,6 +62,7 @@ export default function ScopeBar({
onChange: (next: Scope) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
+ const [connecting, setConnecting] = useState(false);
// One click outside closes an open chip.
useEffect(() => {
const close = (e: MouseEvent) => {
@@ -92,7 +97,10 @@ export default function ScopeBar({
aria-label="Source"
disabled={disabled}
value={source?.handle ?? ""}
- onChange={(e) => onChange({ source: e.target.value })}
+ onChange={(e) => {
+ if (e.target.value === CONNECT) setConnecting(true);
+ else onChange({ source: e.target.value });
+ }}
className={cn(controlClass, "max-w-[260px] py-[3px] text-[12px]")}
>
{sources.map((s) => (
@@ -101,6 +109,7 @@ export default function ScopeBar({
{s.detail ? ` · ${s.detail}` : ""}
</option>
))}
+ <option value={CONNECT}>Connect an archive…</option>
</select>
<Pop
@@ -207,6 +216,15 @@ export default function ScopeBar({
</>
)}
</div>
+ {connecting && (
+ <ConnectArchive
+ onCancel={() => setConnecting(false)}
+ onConnected={(handle) => {
+ setConnecting(false);
+ onChange({ source: handle });
+ }}
+ />
+ )}
</div>
);
}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -27,7 +27,7 @@ Inbox cannot disagree about what is wrong with one.
| `cast project <project> add <id> [--name "…"] [--voice <engine:voice>] [--handles a,b] [--anonymous [--shown "…"]] [the preset flags]` · `set <id> … [--no-voice] [--no-anonymous]` · `rm <id>` · `undo` · `pool <id>` · `keep <character\|@handle> [--anonymous]` `[--json]` | **THIS VIDEO's OWN CHARACTERS** (`<project>/narration/characters.json`, [knobs.md](knobs.md#this-videos-own-characters-and-an-items-own)): the cast's shape and the cast's writer (a token, an undo point a write, atomic, a broken file never overwritten), for people who must not enter the pool. `--anonymous`: it goes by a **shown name** (`--shown`; default the next of `Anon 1`, `Anon 2` …) on the Voices page, in `cast project` and in a recording's note, and never enters the pool; **the on-screen card is not anonymised yet** (it still shows the post's author). `--voice` is optional here: a character with none leaves the voice to the layers under it. `narration/voices.json` keeps working under it (a handle in it reads as a character with only a synthetic voice) and is never rewritten by these. `pool <id>` (**Add to the pool**) moves one into the cast -- an anonymous one, or an id the cast has, is refused; `keep` (**Keep in this video only**) copies a cast character here (its presets changed for this video alone), or gives an author with no character one, in the voice they read in now. A refusal: **exit 1**, nothing written |
| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
-| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
+| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) |
| `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)) |
@@ -46,14 +46,14 @@ Inbox cannot disagree about what is wrong with one.
| `review-pass <project> [ls] [--json]` · `review-pass <project> mark <block> keep\|fix\|clear [--note T]` | the workspace's **review pass** (`?mode=review`): every block but the intro and a clip rejected for a cut reason, its answer and the block the pass resumes on; a Fix ("needs work", saying what) is a mark in `<project>/review-pass.json` on any block, a clip too — never a clip's verdict (`incorrect` is the bench's fact-error ruling, never written or overwritten here); a clip's Keep is its walk verdict (`window --verdict confirmed`), a post's or a card's a mark — `mark` writes one (a Fix needs `--note`; a clip takes `fix` and `clear`) ([knobs.md](knobs.md#the-review-pass)) |
| `review-pass <project> verdict like\|maybe\|no\|clear [--note T] [--json]` | the pass's **verdict on the draft**, one locked call: a draft that differs from its parent version only by what the walk and the review pass write (verdict, correction, reason, reject note, walk note, ★) judges the PARENT and saves nothing; otherwise the draft is saved as the next version and that is judged (`takes/verdicts.json`) |
| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
-| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks)) |
+| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks)) |
| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
-| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
+| `look <project> key=value … [--unset render.<key>]… [--take <t>]` | the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) |
| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
-| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
+| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise) |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused |
| `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters |
@@ -91,7 +91,7 @@ Inbox cannot disagree about what is wrong with one.
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) |
| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
-| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
+| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn), `stampNote` (a `promise_outcome`'s: the words under its stamp on the promise clock in place of "by <date> · no video" -- `ledger <p> set <row> --stampNote "…"`, `--stampNote null` for the clock's own words again; one line, the strip over a post's card shows its first clause, and `umtool lint` warns past 26 characters); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]` | the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
@@ -148,7 +148,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). An x.com/twitter.com **status link** in its words (or its row's links) is a quote: the post it names, from any channel's archive, fills `quoted` (`via: "link"`) when it has none; the row's `threadId` is snapshotted as the item's `conversation` (the thread walk reads it). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) |
| `posts picture-reply <project> [on=on\|off] [image=<s>] [min=<s>] [max=<s>] [maxSound=<s>] [--in-take <take>] [--json]` | the cut's **PICTURE-ONLY RULE** ([knobs.md](knobs.md#picture-only-posts-a-reply-that-is-its-picture)): `render.posts.pictureReply` (`updatePostPictureReplyRender`, one undo point) -- `on` the rule at all; a beat's length: an image `image` s (2), a GIF's or a silent video's own length clamped to `min`–`max` (1.5–4 s), a video with its sound its whole length up to `maxSound` (8 s). `k=` the default again; none: the rule as it stands. `--in-take` writes it into a take's patch. Refused in the build's words (**exit 1**) |
| `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only |
-| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words |
+| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from -- looked for in the project's channels tree first, a `.shadow-channels` or `provenance.channelsDir`, then the archive's `CHANNELS_DIR` behind it, read only; `--dry-run` says which tree each file comes from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words |
| `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) |
| `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
| `ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]` | **one recording's life cycle**, the twin of `/ingredients/<channel>/<video>` ([knobs.md](knobs.md#an-ingredients-life-cycle-the-rail)): nine stages — found, downloaded, transcribed, clock, windows, used in, checked, rendered, published — each **✓**, a count, **!** or **—**, and its line, then every project clip that cuts from it (the draft and each saved version, from the usage index `<REPORTS_ROOT>/.umtool/usage-index.json`). A Rumble recording answers to its folder slug or its embed id; both are printed. `--window`: one clip window, the stages after it narrowed to the clips it plays. `--used-in`: the clips alone. `--json`: the page's object. Read-only over the corpus. **Exit 0 · 1 failed · 2 usage** |
@@ -212,7 +212,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `variants <project> [--take TAKE] [--list]` | make the encode ladder of a build | form · queued · *project* |
| `corrections <project>` | what the report got wrong, as markdown | form · *project* |
| `build <project> [--preset preview\|fast\|final] [--only ONLY] [--dry]` | the build's chain, printed (the Cut tab's Build runs it) | form · *project* |
-| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck]` | an article iteration's pipeline to a video | form · queued · *corpus* |
+| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck] [--stop-before-render] [--allow-whole-recording]` | an article iteration's pipeline to a video | form · queued · *corpus* |
| `model-log [<article>] [<n>] [--job JOB] [--phase PHASE] [--outcome kept\|dropped\|rewritten\|n/a] [--task TASK] [--run N] [--call CALL] [--json]` | the model's side of a run: every call, what was asked, what came back, what code did and why | form · *corpus* |
| `index [--rebuild] [--prune] [--since N]` | the project index (the cache) | form · *corpus* |
| `new <slug> [--folder FOLDER] [--from FROM] [--site-origin SITE-ORIGIN] [--seed chapters\|frames\|phrase\|reactions] [--target N] [--phrase PHRASE] [--channels CHANNELS] [--prefer PREFER] [--exclude EXCLUDE] [--max N] [--from-posts FROM-POSTS] [--brand BRAND]` | a new project (scaffold) | form · *corpus* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -37,6 +37,7 @@ that generates it ([notes.md](notes.md)).
| `chat` — `on`: the clip's live chat (its video's `live_chat.cues.json`, for the clip's source span, timed through its gaps) in a column beside the footage; `off` or `chat=` (the default): none. A video with no chat draws nothing and the build log says so ([Live chat](#live-chat)) | — | `umtool set <p> <clip> chat=on` (`chat=` clears it) | — |
| `hideModules` — `["diet","streak",…]`: the measure extras (`goals` `peak` `promise` `diet` `streak`) hidden over THIS entry's span, each with its own fade, whatever it would otherwise do there -- for text in the footage no dodge can know of (a DM screenshot's refund email under the diet badge). Any entry, a post item too; an id no entry can hide is refused | — | `umtool set <p> <entry> hideModules=diet,streak` (`hideModules=` clears it; `--take <t>` writes the take's patch, the project's manifest untouched) | — |
| `shelfNote` — one line of at most 80 characters on the shelf (`render.chrome.deck.shelf`, its `note` slot) over THIS entry's span, coming and going with it -- a short fact beside the footage for any video, with or without a measure slice ([Shelf](#shelf)). Any entry, a post item too | — | `umtool set <p> <entry> shelfNote='Weighed in on camera'` (`shelfNote=` clears it; `--take <t>` writes the take's patch) | — |
+| `chapter` — the entry's name in the chapter list (`out/…chapters`, `youtube.txt`, `umtool export --format chapters`): one line of at most 100 characters. An authored `chapter` wins over the entry's on-screen title (under the deck) and the line derived from its record; without one the list is as before. Any entry, a post item too | — | `umtool set <p> <entry> chapter='The weigh-in'` (`chapter=` clears it; `--take <t>` writes the take's patch, the project's manifest untouched) | — |
| `fx.zoom` — `{shot, focus, at?, hold?}`: a screenshot (a file in the project; a bare name under its `shots/` is written as `shots/<name>`) that comes up over the footage and pushes in on `focus` (`[left, top, right, bottom]`, fractions of the shot) — drawn once `render.chrome.fx.zoom` is on ([Effects](#effects)). **How long it stays**: up 0.2 s into the clip's clean span (rising in over 0.38 s), its focus box drawn 0.55 s later, the push at `at` (seconds into the clip; default as soon as the box has drawn) over 1 s, then a slow drift on the detail; it leaves with a 0.3 s fade 0.3 s before the clip's clean span ends — or, with `hold` (0.5–10 s), that long after the push lands (never past the clip's own leave) | — | `umtool set <p> <clip> fx.zoom='{"shot":"shots/x.png","focus":[0.1,0.2,0.9,0.4],"at":5.9,"hold":4}'` (`fx.zoom=` clears it) | `PUT /api/report/window {project, clip, "fx.zoom": {…} \| null}` |
| `fx.receipts`, `fx.punch`, `fx.quote`, `fx.punchIn`, `fx.speakers` — the clip's other effect fields (`[{shot, mark?, at?, hold?, label?}]` 1–4, `at` the source second a receipt flies in at (default: as the clip comes up), `hold` 0.5–10 s it stays once landed (on every one: they leave then, not with the clip), `label` a line of at most 80 characters in a band under the screenshot (when it was taken, what it is); the words to punch; `false`: no line; 1–8 source seconds inside the clip; `[{at, who: 0\|1}]`), each inert until its effect is on; `fx` is all of them at once. Checked by the build's own `validateFxEntries` | — | `fx.punch="the words"` `fx.punchIn='[231.4]'` · `fx='{…}'` sets them all, `fx=` clears every one | `PUT /api/report/window {project, clip, fx}` (or one `"fx.<field>"`) |
| `gaps` — `[{from, to}]`, SOURCE seconds cut out of the clip's middle: it renders as ONE segment of jump cuts (one pip, one card), not two clips with a crossfade ([below](#gaps-inside-a-clip)) | clip bench (Edit this clip), the waveform: **Select a gap** (`g`) or Alt + drag a span, **Cut gap** (`g`), **Hear it**; a click on a gap's band puts it back (`G`: the one at the playhead); **Undo** | `umtool window <p> <clip> --gap 12.3-15.1` (repeatable) · `--gap-remove 12.3` · `--gaps '12.3-15.1,20-20.6'` (`--gaps ''` clears) · `umtool set <p> <clip> gap.add=12.3-15.1 gap.remove=12.3 gaps=` | `PUT /api/report/window {project, clip, token, gapAdd \| gapRemove \| gaps}` |
@@ -107,7 +108,10 @@ misclip), and only listening caught it. `umtool quote-check <p> [--clips a,b]` l
clip's cut ±15 s (`--pad`) of the source the render would use is transcribed by the editor (its
transcription lane, words on), and the quote is found in those words — numbers one token however they
are written, a word one letter off still a match, an ellipsis splitting it into fragments found in
-order — and in the recording's cues. The rows (`quote-check.json`, one per clip, with the cut, the
+order — and in the recording's cues. The editor's work files (`<clip>.words.json`) go to
+`<project>/.quote-check/` — never under `out/`, which may be a link onto a media drive, where the editor
+refuses to write (inside the corpus); refused there too, `<reports>/.umtool/quote-check/<project>/`, then
+`~/.cache/umtool/quote-check/<project>/`. The rows (`quote-check.json`, one per clip, with the cut, the
quote and the source judged):
| row | means | what settles it |
@@ -1747,7 +1751,7 @@ in the build's words (`validatePostCombos`). `k=` (empty) takes the default (the
| | In umtool | From a terminal | Route |
|---|---|---|---|
| the repeats: each attachment played more than once, its posts in the cut's order with their dates, the tier that matched (`X media id`, `same file`, `same sound`) and the badge each draws; a post whose capture holds the same file but whose entry carries none, marked | the post bench's **combo** block (this item's group) | `umtool posts repeats <p> [--match id\|file\|audio] [--json]` | `GET /api/report/post-combo?project` |
-| attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — |
+| attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts. The capture is looked for in the project's channels tree (a `.shadow-channels`, `provenance.channelsDir`), then the archive's behind it -- read only, the files are copied into the project; `--dry-run` says which tree each file comes from | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — |
| the badge on the item's clock | Play the cut, the post bench (the player) | the build: `segments/<id>.mp4` (the plain one `<id>.plain.mp4`, the record `<id>.combo.json`) | — |
## Media scenes (one attachment, several messages)
@@ -2569,11 +2573,12 @@ A sticky note per goal on a pile in a corner of the footage box, read off the sc
| Knob | Range · default | From a terminal |
|---|---|---|
-| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
+| `deck.goals` | `true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays}` · default on with a measure slice | `umtool look <p> deck.goals=false` |
| `deck.goals.position`, `.x`/`.y`, `.scale` | `top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1 | `umtool look <p> deck.goals.position=bottom-left` |
| `deck.goals.position=shelf` | its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs `goalsAt(goalBoard(schedule.measure), t)`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with "+N more" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial | `umtool look <p> deck.shelf.items='["diet","goals"]' deck.goals.position=shelf` |
| `deck.goals.max`, `.color`, `.countdown` | 1–8 notes · #hex paper · bool · default 4, the palette's amber, `true` | `umtool look <p> deck.goals.max=6` |
| `deck.goals.base` | bool · default `false`: each note also says the weight he had stated when he set the goal -- "LOSE 100 (FROM 346.7)", its qualifier kept ("(FROM ≈390)") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as "250 LB", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label | `umtool look <p> deck.goals.base=true` |
+| `deck.goals.baseMaxDays` | whole days 0–36500 · unset (default): every base counts. A loss goal's base is a weight he gave by the goal's date, however long before; with this set, a base counts only when its weight was SAID (its row's date, never a remembered weight's as-of) at most that many days before the goal's date. A staler one is no base: the note carries no "(FROM …)", and the slice resolves no target from it -- the dial draws no goal weight and no tick for that goal, his words ("LOSE 100") stay. It is the slice's rule (measure-slice.mjs `goalBaseMaxDays`), so the notes, the shelf and the dial agree; it needs `deck.goals` as settings (`deck.goals.base=true deck.goals.baseMaxDays=365`), and `baseMaxDays=null` takes it off | `umtool look <p> deck.goals.baseMaxDays=365` (`--take <t>` for a take) |
| `deck.goals.hold`, `.finale` | 0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide` | `umtool look <p> deck.goals.hold=0` |
| `deck.goals.flash` | bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away | `umtool look <p> deck.goals.flash=false` |
| `deck.goals.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.goals.onPosts=hide` |
@@ -2694,6 +2699,7 @@ A days-since counter for a promise (`render.chrome.deck.promise`, measure-extras
| `deck.promise.position`, `.x`/`.y`, `.scale` | an anchor in the footage box · design px · 0.5–2 · default `top-center`, unset, 1 | `umtool look <p> deck.promise.position=bottom-center` |
| `deck.promise.hold`, `.finale` | 0 (stays up) or 2–600 s · `hide` `show` · default 0, `show` | `umtool look <p> deck.promise.finale=hide` |
| `deck.promise.label`, `.verb`, `.kept`, `.broken`, `.checks` | ≤40 each · `label` `quote` · default the row's display, "offered", "Posted", "None posted", `label` | `umtool look <p> deck.promise.label='scale video'` |
+| a `promise_outcome` row's `stampNote` | one line, 1–80 characters · unset (default): the clock's own words under the stamp, "by <date> · no video". The row's note is that second line instead (REFUNDED / "by her account · no receipt"); the strip over a post's card, which has one line for everything, shows its first clause (to its first `·`, `;`, `—`, `, ` or ` -- `: "refunded · by her account"). It is the ledger row's, so every take of the project reads it. `umtool lint` warns past 26 characters (the stamp's line is never wrapped: a longer one runs past its border) | `umtool ledger <p> set <row> --stampNote "by her account · no receipt"` · off again: `--stampNote null` |
| `deck.promise.speakers`, `.claimVerb`, `.claimColor` | `{<speaker>: {handle, color}}` · ≤40 · #hex · default `{}` (the postAvatars handle), "paid", #E37AB8 | `umtool look <p> deck.promise.speakers='{"madamsavvy":{"handle":"MadamSavvy"}}'` |
| `deck.promise.onPosts`, `.onChapters` | `dodge` `hide` `show` · default `dodge`: while a post item's card (its card, slot and strip as postLayout lays them: the schedule's `covers`) or a chapter band is up where it stands, it moves to a free anchor of the footage box -- a size down to half if it must, never onto another measure extra that is up -- and hides when none fits; `hide` hides, `show` stays over it | `umtool look <p> deck.promise.onPosts=hide` |
| a timeline entry's `hideModules` | `["promise", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=promise` (`--take <t>` for a take) |
diff --git a/umtool/e2e/fixtures/editor-stub-archives.mjs b/umtool/e2e/fixtures/editor-stub-archives.mjs
@@ -0,0 +1,109 @@
+// demo epic D1: a published archive served by the stub editor's own port,
+// under /archive-stub (the synthetic draft corpus — common/testing/draft — as
+// a site serves it), and the editor's `archives` action (POST
+// /api/ops/archives): `connect` reads the origin's corpus.json and, unless
+// `dryRun`, writes settings.remoteArchives into E2E_UMTOOL_SETTINGS_FILE (the
+// fixture's copy, which umtool's source picker reads); `remove` drops one.
+// Nothing leaves loopback.
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+
+export const ARCHIVE_PREFIX = "/archive-stub";
+
+/** Write the stub archive's files under `dir` (once, at the stub's start). */
+export async function prepareArchiveStub(dir) {
+ mkdirSync(dir, { recursive: true });
+ await writeDraftCorpus(dir);
+ const corpus = JSON.parse(readFileSync(path.join(dir, "corpus.json"), "utf8"));
+ writeFileSync(
+ path.join(dir, "corpus.json"),
+ JSON.stringify({ ...corpus, spec: 6, generatedAt: new Date().toISOString(), site: { id: "stubalyzer", title: "Stubalyzer" } }),
+ );
+}
+
+/**
+ * GET /archive-stub/<file>: the archive's static files, written on the first
+ * ask (make-fixture.mjs empties the fixture root while the stub starts, so
+ * nothing is written before a spec asks). True when answered.
+ */
+export function archiveStubRoute(req, res, url, { dir }) {
+ if (req.method !== "GET" || !url.pathname.startsWith(`${ARCHIVE_PREFIX}/`)) return false;
+ const rel = decodeURIComponent(url.pathname.slice(ARCHIVE_PREFIX.length));
+ const file = path.normalize(path.join(dir, rel));
+ if (!file.startsWith(dir)) {
+ res.writeHead(403).end();
+ return true;
+ }
+ const ready = existsSync(path.join(dir, "corpus.json")) ? Promise.resolve() : prepareArchiveStub(dir);
+ ready.then(
+ () => {
+ try {
+ const body = readFileSync(file);
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(body);
+ } catch {
+ res.writeHead(404).end("not found");
+ }
+ },
+ (e) => res.writeHead(500).end(String(e?.message ?? e)),
+ );
+ return true;
+}
+
+const settingsOf = (file) => {
+ try {
+ return JSON.parse(readFileSync(file, "utf8"));
+ } catch {
+ return {};
+ }
+};
+
+/** POST /api/ops/archives. True when answered. */
+export function archivesRoute(req, res, url, { json, readBody, settingsFile }) {
+ if (url.pathname !== "/api/ops/archives") return false;
+ if (req.method === "GET") {
+ json(res, 200, { ok: true, archives: settingsOf(settingsFile).remoteArchives ?? [] });
+ return true;
+ }
+ if (req.method !== "POST") return false;
+ readBody(req, async (body) => {
+ const settings = settingsOf(settingsFile);
+ const list = Array.isArray(settings.remoteArchives) ? settings.remoteArchives : [];
+ if (typeof body?.remove === "string") {
+ const next = list.filter((a) => a.id !== body.remove && a.origin !== body.remove);
+ writeFileSync(settingsFile, JSON.stringify({ ...settings, remoteArchives: next }, null, 2));
+ return json(res, 200, { ok: true, removed: list.find((a) => !next.includes(a)) ?? null });
+ }
+ const origin = String(body?.connect ?? "").trim().replace(/\/+$/, "");
+ if (!/^https?:\/\//.test(origin)) return json(res, 400, { ok: false, error: `"${origin}" is not an archive's address` });
+ let corpus;
+ try {
+ const r = await fetch(`${origin}/corpus.json`);
+ if (!r.ok) return json(res, 502, { ok: false, error: `${origin}/corpus.json answered HTTP ${r.status}` });
+ corpus = await r.json();
+ } catch (e) {
+ return json(res, 502, { ok: false, error: `${origin}/corpus.json did not answer: ${e.message}` });
+ }
+ const channels = (corpus.channels ?? []).map((c) => ({ slug: c.slug, name: c.name ?? c.slug, videoCount: c.videoCount ?? null }));
+ const probe = {
+ origin,
+ siteId: corpus.site?.id ?? null,
+ title: corpus.site?.title ?? origin,
+ description: "",
+ spec: corpus.spec ?? null,
+ generatedAt: corpus.generatedAt ?? null,
+ totals: { channels: channels.length, videos: channels.reduce((n, c) => n + (c.videoCount ?? 0), 0) },
+ channels,
+ };
+ const have = list.find((a) => a.origin === origin);
+ const archive = have ?? { id: probe.siteId ?? "archive", origin, title: probe.title, addedAt: new Date().toISOString() };
+ if (!have && body?.dryRun !== true) {
+ mkdirSync(path.dirname(settingsFile), { recursive: true });
+ writeFileSync(settingsFile, JSON.stringify({ ...settings, remoteArchives: [...list, archive] }, null, 2));
+ }
+ return json(res, 200, { ok: true, probe, archive, already: have ? true : body?.dryRun === true ? null : false });
+ });
+ return true;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -27,6 +27,7 @@ import { fileURLToPath } from "node:url";
import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs";
import { importPageRoute } from "./editor-stub-import-page.mjs";
import { caseStagesRoute } from "./editor-stub-case-stages.mjs";
+import { archiveStubRoute, archivesRoute } from "./editor-stub-archives.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
@@ -36,6 +37,11 @@ import { checkGroupProposals, cutSections, groupProposalsDocOf, writeGroupPropos
const PORT = portFor("EDITOR_STUB_PORT");
const CHANNELS = process.env.CHANNELS_DIR ?? "";
const TOKEN = process.env.WORKER_TOKEN ?? "";
+// demo epic D1: the published archive this stub serves (/archive-stub) and the
+// settings file its `archives` action writes — the fixture's, which umtool's
+// source picker reads (playwright.config.ts E2E_UMTOOL_SETTINGS_FILE).
+const ARCHIVE_STUB_DIR = path.join(path.dirname(CHANNELS || process.cwd()), "archive-stub");
+const SETTINGS = process.env.E2E_UMTOOL_SETTINGS_FILE ?? path.join(path.dirname(CHANNELS || process.cwd()), "settings.json");
// Where the spec reads what was asked for.
const LOG = process.env.E2E_EDITOR_STUB_LOG ?? path.join(process.cwd(), "editor-stub.requests.json");
@@ -1263,6 +1269,8 @@ const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`);
if (url.pathname === "/health") return json(res, 200, { ok: true });
+ // A published archive's files (demo epic D1): public, like a site's.
+ if (archiveStubRoute(req, res, url, { dir: ARCHIVE_STUB_DIR })) return;
// A job's log is ungated on the editor (GET /api/jobs/<id>/log).
if (url.pathname.startsWith("/api/jobs/") && fetchWindowsRoute(req, res, url, fwCtx)) return;
@@ -1305,6 +1313,8 @@ const server = http.createServer((req, res) => {
// Release 37 S4: Import this capture (editor-stub-import-page.mjs).
if (importPageRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return;
if ((url.pathname === "/api/ops/fetch-windows" || url.pathname.startsWith("/api/ops/job/")) && fetchWindowsRoute(req, res, url, fwCtx)) return;
+ // demo epic D1: Connect an archive (the Source chip).
+ if (archivesRoute(req, res, url, { json, readBody, settingsFile: SETTINGS })) return;
if (url.pathname.startsWith("/api/ops/") && generationRoute(req, res, url, auth) !== null) return;
// THE OPS DOOR, stubbed alongside the media one.
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -21,6 +21,7 @@ import {
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import path from "node:path";
+import { fileURLToPath } from "node:url";
import { SONG_DATA } from "../../song/paths.mjs";
import { songCapabilities } from "./song-capabilities.mjs";
import { makeSitesFixture } from "./sites-fixture.mjs";
@@ -2613,6 +2614,14 @@ makeDeleteFixture({ dest, articles: ARTICLES, reports });
// R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the
// held channels its inventory reads on disk.
const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
+// demo epic D1: the settings file the app and the editor stub read
+// (playwright.config.ts SETTINGS_FILE) -- a copy of the checkout's, so every
+// spec reads what it read before, and Connect an archive (remote-archive.spec)
+// writes the fixture's, never the checkout's. A clone with none: {}.
+{
+ const checkout = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "settings.json");
+ writeFileSync(path.join(dest, "settings.json"), existsSync(checkout) ? readFileSync(checkout, "utf8") : "{}\n");
+}
// Two channel context notes to review (digest-context.spec.ts), on channels already made above.
makeDigestContextFixture({ dest, channels: CHANNELS });
// R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest).
diff --git a/umtool/e2e/inbox.spec.ts b/umtool/e2e/inbox.spec.ts
@@ -32,6 +32,15 @@ const setLife = (request: APIRequestContext, piece: string, state: string) =>
request.post("/api/pieces/lifecycle", { data: { piece, state } });
const card = (page: Page, piece: string, kind: string) => page.locator(`[data-lit-line][data-piece='${piece}'][data-card='${kind}']`);
+// A WRITE, THEN THE LIST AGAIN. Park, Mark done, Reactivate, Mute, Unmute and Undo POST, then router.refresh(): the
+// list changes when the refreshed page has been rendered and streamed whole. Three failures of this spec (11 Nov:
+// :122 Reactivate, :178 Unmute, and Undo after Mark done) were all that step late, not wrong: the POST had answered
+// 200 and the refresh's request had gone out and been answered, the lifecycle and the mutes are read from disk on
+// every render (never memoised), and in the one trace that shows it a HEAD of the same page, sent in the same
+// second, took 5.8 s to answer -- the server was that slow for those seconds (another suite's build beside it) and
+// the default 5 s expect gave up first. So the FIRST look at the list after such a write waits this long.
+const SETTLES = { timeout: 20_000 };
+
test.beforeAll(async ({ playwright }) => {
test.setTimeout(WARM_TIMEOUT);
await warm(playwright, ["/", "/?hidden=1", "/api/browse/decisions", "/api/rail", "/settings/system", "/projects"]);
@@ -95,6 +104,7 @@ test("j lights the next card, and only the lit card's action wears Signal", asyn
});
test("Park hides a piece's calls, Undo brings them back; Show hidden lists them with Reactivate", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
try {
await page.goto(urls.homeHref());
const ready = card(page, ZETA, "iteration-ready");
@@ -104,12 +114,12 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
await ready.click();
await ready.locator("[data-lifecycle-to=parked]").click();
await expect(page.locator(`[data-undo='${ZETA}']`)).toContainText("Parked");
- await expect(page.locator(`[data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0);
+ await expect(page.locator(`[data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0, SETTLES);
await expect(page.locator("[data-inbox-count]")).not.toHaveAttribute("data-inbox-count", String(before));
await expect(page.locator("[data-show-hidden]")).toContainText(/^Show hidden \d+$/);
await page.locator(`[data-undo='${ZETA}']`).getByRole("button", { name: "Undo" }).click();
- await expect(ready).toBeVisible();
+ await expect(ready).toBeVisible(SETTLES);
await expect(page.locator("[data-inbox-count]")).toHaveAttribute("data-inbox-count", String(before));
// Parked again, it is listed under Hidden, and Reactivate is its action.
@@ -119,7 +129,7 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
await expect(hidden).toBeVisible();
await hidden.click();
await hidden.locator("[data-lifecycle-to=active]").click();
- await expect(page.locator(`[data-group=hidden] [data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0);
+ await expect(page.locator(`[data-group=hidden] [data-lit-line][data-piece='${ZETA}']`)).toHaveCount(0, SETTLES);
await expect(card(page, ZETA, "iteration-ready")).toBeVisible();
} finally {
await setLife(request, ZETA, "active");
@@ -127,6 +137,7 @@ test("Park hides a piece's calls, Undo brings them back; Show hidden lists them
});
test("Mark done on a piece that looks done takes it off the Inbox; Undo puts it back", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
try {
await page.goto(urls.homeHref());
const done = page.locator(`[data-group=ready-to-finish] [data-piece='${ALPHA}'][data-card='looks-done']`);
@@ -134,15 +145,16 @@ test("Mark done on a piece that looks done takes it off the Inbox; Undo puts it
await done.click();
await done.locator("[data-lifecycle-to=done]").click();
await expect(page.locator(`[data-undo='${ALPHA}']`)).toContainText("Marked done");
- await expect(done).toHaveCount(0);
+ await expect(done).toHaveCount(0, SETTLES);
await page.locator(`[data-undo='${ALPHA}']`).getByRole("button", { name: "Undo" }).click();
- await expect(done).toBeVisible();
+ await expect(done).toBeVisible(SETTLES);
} finally {
await setLife(request, ALPHA, "active");
}
});
test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Muted N lists it with Unmute", async ({ page, request }) => {
+ test.slow(); // room for SETTLES on a loaded machine
const rows = async () =>
((await (await request.get("/api/browse/decisions")).json()) as { items: { piece?: string; kind: string; hidden: boolean; hiddenBy?: string }[]; muted: number })
try {
@@ -153,7 +165,7 @@ test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Mute
await ready.click();
await ready.locator("[data-mute=mute]").click();
await expect(page.locator(`[data-undo='${ZETA}']`)).toContainText("Muted");
- await expect(ready).toHaveCount(0);
+ await expect(ready).toHaveCount(0, SETTLES);
// Never dropped: every row is still in the API, hidden, and says why.
const after = await rows();
@@ -175,7 +187,7 @@ test("Mute is the server's: the card leaves, its rows stay hidden-by-muted, Mute
await expect(muted).toHaveAttribute("data-muted", "");
await muted.click();
await muted.locator("[data-mute=unmute]").click();
- await expect(muted).toHaveCount(0);
+ await expect(muted).toHaveCount(0, SETTLES);
await expect(page.locator(`[data-group=review] [data-lit-line][data-piece='${ZETA}'][data-card='iteration-ready']`)).toBeVisible();
expect((await rows()).items.filter((d) => d.piece === ZETA && d.kind === "iteration-ready").every((d) => !d.hidden)).toBe(true);
} finally {
diff --git a/umtool/e2e/remote-archive.spec.ts b/umtool/e2e/remote-archive.spec.ts
@@ -0,0 +1,79 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+import { WARM_TIMEOUT, warm } from "./warm";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A PUBLIC ARCHIVE IS A FIRST-CLASS SOURCE (demo epic D1), umtool's half: the
+// Source chip's "Connect an archive…" (Read it → Connect, through the editor's
+// `archives` action — the stub's, which writes the fixture's settings) and
+// "Article from a question"'s Source field, which lists the archive's own
+// channels. The archive is the editor stub's /archive-stub (the synthetic
+// draft corpus, served as a published site serves it); nothing leaves
+// loopback. The engine — the sweep over it, the remote-only channel, the
+// links — is the editor suite's remote-archive.spec.ts.
+//
+// WRITES the fixture's settings.json remoteArchives (removed after)
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`;
+const ORIGIN = `${STUB}/archive-stub`;
+const HANDLE = `remote:${ORIGIN}`;
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, ["/research", urls.newArticleHref(), "/api/articles/sources"]);
+});
+
+test.afterAll(async () => {
+ await fetch(`${STUB}/api/ops/archives`, {
+ method: "POST",
+ headers: { authorization: "Bearer umtool-e2e-token", "content-type": "application/json" },
+ body: JSON.stringify({ remove: ORIGIN }),
+ }).catch(() => {});
+});
+
+test("the Source chip connects an archive by its address: read it, connect, and the scope is that archive's", async ({ page }) => {
+ await page.goto("/research");
+ const source = page.getByRole("combobox", { name: "Source" });
+ await expect(source.locator("option", { hasText: "Connect an archive…" })).toHaveCount(1);
+ await source.selectOption({ label: "Connect an archive…" });
+ const form = page.getByRole("form", { name: "connect an archive" });
+ await form.getByRole("textbox", { name: "archive origin" }).fill(`${ORIGIN}/`);
+ await form.getByRole("button", { name: "Read it" }).click();
+ const probe = form.locator(`[data-archive-probe="${ORIGIN}"]`);
+ await expect(probe).toContainText("Stubalyzer");
+ await expect(probe).toContainText("2 channels");
+ await expect(probe).toContainText("Synth Kitchen");
+ // Read, not saved.
+ expect(JSON.parse(readFileSync(path.join(FIXTURE, "settings.json"), "utf8")).remoteArchives ?? []).toEqual([]);
+
+ await form.getByRole("button", { name: "Connect" }).click();
+ await expect(form).toHaveCount(0);
+ await expect(source).toHaveValue(HANDLE);
+ await expect(source.locator("option:checked")).toContainText("Stubalyzer · connected");
+ // The scope is the archive's: its two channels.
+ await expect(page.locator("[data-scope]")).toContainText("All 2 channels");
+ const saved = JSON.parse(readFileSync(path.join(FIXTURE, "settings.json"), "utf8")).remoteArchives;
+ expect(saved).toEqual([expect.objectContaining({ id: "stubalyzer", origin: ORIGIN, title: "Stubalyzer" })]);
+});
+
+test("Article from a question offers the connected archive as its source, and lists that archive's channels", async ({ page }) => {
+ await page.goto(urls.newArticleHref());
+ const form = page.getByRole("form", { name: "new article" });
+ const source = form.getByRole("combobox", { name: "source" });
+ await expect(source.locator(`option[value="${HANDLE}"]`)).toHaveCount(1);
+ // The fixture's editor holds channels of its own: the local corpus stays the default.
+ await expect(source).toHaveValue("");
+ await source.selectOption(HANDLE);
+ await form.getByRole("textbox", { name: "find a channel" }).fill("synth");
+ await expect(form.getByRole("button", { name: /^Synth Kitchen/ })).toBeVisible();
+ await expect(form.getByRole("button", { name: /^Synth Other Kitchen/ })).toBeVisible();
+ await form.getByRole("button", { name: /^Synth Kitchen/ }).click();
+ await expect(form.locator("[data-picked='synth-kitchen']")).toBeVisible();
+});
diff --git a/umtool/lib/articles/createSources.test.ts b/umtool/lib/articles/createSources.test.ts
@@ -0,0 +1,26 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createSourcesOf } from "./createSources";
+import type { SourceOption } from "../research/types";
+
+const SOURCES: SourceOption[] = [
+ { handle: "local:/x/export/public", kind: "local", label: "Local corpus" },
+ { handle: "remote:https://stub.test", kind: "remote", label: "Stubalyzer", detail: "connected · stub.test" },
+ { handle: "hub:https://hub.test", kind: "hub", label: "Hub" },
+];
+const ch = (slug: string, kind = "video") => ({ slug, name: slug, kind, platform: null, sites: [] });
+
+test("Create offers the editor's corpus and each published archive, hubs aside", () => {
+ const r = createSourcesOf(SOURCES, [ch("alpha")]);
+ assert.deepEqual(r.sources.map((s) => s.handle), ["", "remote:https://stub.test"]);
+ assert.equal(r.preselect, "");
+});
+
+test("with no local corpus the first archive is preselected; a remote-only channel is not a corpus", () => {
+ assert.equal(createSourcesOf(SOURCES, []).preselect, "remote:https://stub.test");
+ assert.equal(createSourcesOf(SOURCES, [ch("stub-alpha", "remote-only")]).preselect, "remote:https://stub.test");
+ // The editor did not answer: nothing is assumed.
+ assert.equal(createSourcesOf(SOURCES, null).preselect, "");
+ // No archive to offer: the local corpus, empty or not.
+ assert.equal(createSourcesOf(SOURCES.slice(0, 1), []).preselect, "");
+});
diff --git a/umtool/lib/articles/createSources.ts b/umtool/lib/articles/createSources.ts
@@ -0,0 +1,20 @@
+import type { SourceOption } from "@/lib/research/types";
+import type { EditorChannel } from "./generation";
+
+// THE CREATE FORM'S SOURCES (demo epic D1 item 2), pure so it is tested
+// without an editor: the editor's own corpus (handle "") first, then each
+// published archive (`remote:<origin>`) the source picker offers. The first
+// archive is preselected when the editor holds no channel of its own — a
+// fresh clone with an archive connected sweeps that archive by default. A
+// remote-only channel (held only to fetch an archive's clips) is not a local
+// corpus. An editor that did not answer (null) preselects nothing: the form
+// says it is down.
+export type CreateSource = { handle: string; label: string; detail?: string };
+
+export function createSourcesOf(sources: SourceOption[], editorChannels: EditorChannel[] | null): { sources: CreateSource[]; preselect: string } {
+ const local: CreateSource = { handle: "", label: "Local corpus", detail: "the editor's channels" };
+ const remote = sources.filter((s) => s.kind === "remote").map((s) => ({ handle: s.handle, label: s.label, ...(s.detail ? { detail: s.detail } : {}) }));
+ const ownChannels = editorChannels?.filter((c) => c.kind !== "remote-only").length ?? null;
+ const preselect = ownChannels === 0 && remote.length > 0 ? remote[0].handle : "";
+ return { sources: [local, ...remote], preselect };
+}
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -105,7 +105,7 @@ export const GROUPS = [
],
docs: [
["`quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status`",
- "**is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays))"],
+ "**is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; the editor's work files go to `<project>/.quote-check/`, never under `out/` (a link onto a media drive the editor will not write in); `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays))"],
],
},
{
@@ -301,7 +301,7 @@ export const GROUPS = [
],
docs: [
["`set <project> <clip> key=value …`",
- "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks))"],
+ "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); on ANY entry (a post item, a still, a clip) `hideModules=diet,streak`, `shelfNote='…'` and `chapter='…'` (its name in the chapter list, one line of at most 100 characters; `chapter=` none); `--take <t>` writes the entry knobs into that take's patch; `key=` clears one ([knobs.md](knobs.md#marks))"],
],
},
{
@@ -325,8 +325,8 @@ export const GROUPS = [
" variants=<json>, and the look's keys (transition=0.3, …)",
],
docs: [
- ["`look <project> key=value … [--unset render.<key>]…`",
- "the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"],
+ ["`look <project> key=value … [--unset render.<key>]… [--take <t>]`",
+ "the cut's **knobs** (`--take <t>`: the `deck.*` keys given are set on that take -- its patch, an undo point of its own, the project's manifest untouched; the other knobs are the project's): `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"],
],
},
{
@@ -376,16 +376,19 @@ export const GROUPS = [
{
cmd: "chain",
usage: [
- " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
+ " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]] [--stop-before-render] [--allow-whole-recording]",
" an article iteration's pipeline, one step a process: {chainSteps}",
" (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
" --draft-all (Draft everything): {draftAllSteps} —",
" each draft a report-draft job on --model (else its route); a draft that fails does not stop it;",
" --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
+ " --stop-before-render ends it before the voices: nothing voiced or built",
+ " --allow-whole-recording: a remote-only channel's Rumble windows may download",
+ " their whole recording (refused with its size otherwise)",
],
docs: [
- ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]`",
- "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything)"],
+ ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]] [--stop-before-render] [--allow-whole-recording]`",
+ "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything, which fetches the windows of the clips the drafted cut kept, `cut-windows`); `--stop-before-render` is **Stop before render** (it ends before the voices); `--allow-whole-recording` is **Fetch the whole recordings** (a remote-only channel's Rumble windows, refused with their size otherwise)"],
],
},
{
@@ -726,7 +729,7 @@ export const GROUPS = [
],
docs: [
["`ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>`",
- "a **measure ledger's rows** (`ledgerSchema.kind \"measure\"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
+ "a **measure ledger's rows** (`ledgerSchema.kind \"measure\"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn), `stampNote` (a `promise_outcome`'s: the words under its stamp on the promise clock in place of \"by <date> · no video\" -- `ledger <p> set <row> --stampNote \"…\"`, `--stampNote null` for the clock's own words again; one line, the strip over a post's card shows its first clause, and `umtool lint` warns past 26 characters); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
],
},
{
@@ -1069,7 +1072,7 @@ export const GROUPS = [
["`posts repeats <project> [--match id\\|file\\|audio] [--json]`",
"the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only"],
["`posts attach <project> [<item> … \\| --all] [--dry-run] [--json]`",
- "a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words"],
+ "a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from -- looked for in the project's channels tree first, a `.shadow-channels` or `provenance.channelsDir`, then the archive's `CHANNELS_DIR` behind it, read only; `--dry-run` says which tree each file comes from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words"],
["`posts combo <project> [on=on\\|off] [label=L] [position=top-right\\|top-left\\|bottom-right\\|bottom-left\\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\\|hit\\|coin] [minCount=2-20] [match=id\\|file\\|audio] [--json]` · `posts combo <project> <item> off\\|on\\|auto\\|label=…\\|position=…\\|color=…\\|scale=…\\|sfx=… [--json]`",
"the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**)"],
],
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -220,6 +220,8 @@ export const VERBS = Object.freeze([
form("chain", "corpus", "an article iteration's pipeline to a video", [
arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"),
opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"),
+ bool("--stop-before-render", "end before the voices: nothing voiced or built"),
+ bool("--allow-whole-recording", "a remote-only channel's windows may download their whole recording (Rumble)"),
], Q),
form("model-log", "corpus", "the model's side of a run: every call, what was asked, what came back, what code did and why", [
arg("article", { required: false }), num("n", { help: "the iteration" }), opt("--job", { help: "a job with no iteration" }), opt("--phase", { help: "terms, reading, meaning-check, grouping, draft, agent, …" }),
diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs
@@ -3,6 +3,7 @@
//
// node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step>
// [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]
+// [--mode draft-all] [--allow-whole-recording]
//
// — under tsx, because the article registry, the iterations store and the
// reports CLIs it calls are common's TypeScript. The Next app never imports
@@ -34,6 +35,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { articleDir, articleFile } from "yt-dlp-transcript-common/lib/report/registry";
import {
lineage,
+ lineageSource,
makeCurrent,
projectOf,
readIteration,
@@ -49,16 +51,22 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar
import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert";
import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video";
import { checkMain } from "yt-dlp-transcript-common/bin/reports-check";
-import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs";
+import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, cutWindows, originFromSweep } from "./chain.mjs";
import { deckChrome, deckRefusedDetail, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs";
import { ChromeRefused, addDeckChrome } from "./manifest.mjs";
import { socialTexts } from "umtool-report-to-video/social";
import { PIPELINE_DIR } from "./driver.mjs";
+import { resolveLocalSource } from "umtool-report-to-video/sources";
import { dedupeMedia, seedFromParent } from "./iterations.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
+import { WHOLE_RECORDING_REFUSED, connectedArchives, disconnectedArchiveRefusal, originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs";
+import { archiveRecordPageHref } from "yt-dlp-transcript-common/controller/remoteOnlyChannel";
+import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server";
const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs");
const SCREENSHOT_MISSING = /no captured screenshot/;
+const CLIP_MISSING = /fetch the window or persist the video in the editor/;
/** A step that ends early with a reason: failed, with that line. */
class StepFailed extends Error {}
@@ -98,7 +106,58 @@ async function ownProblems(paths, article) {
const index = await readStoreMediaIndex(articleReportStore(paths));
const own = (index?.problems ?? []).filter((p) => isArticleProblem(p, article));
const shots = own.filter((p) => p.kind === "missing-media" && SCREENSHOT_MISSING.test(p.message) && p.moment);
- return { own, shots, rest: own.filter((p) => !shots.includes(p)) };
+ // An evidence clip whose window is not on disk (publish/reportMedia.ts).
+ const clips = own.filter((p) => p.kind === "missing-media" && CLIP_MISSING.test(p.message) && !shots.includes(p));
+ return { own, shots, clips, rest: own.filter((p) => !shots.includes(p) && !clips.includes(p)) };
+}
+
+/**
+ * Ask the editor for a step's windows (demo epic D1 adds the archive): when
+ * the lineage read a connected archive (`scope.source`), the body names it and
+ * each item carries its page URL from the archive's record, so the editor
+ * registers a channel it does not hold as remote-only. Then a DRY RUN first:
+ * a remote-only channel's whole recording (Rumble) refused with its size fails
+ * the step with every such refusal — nothing fetched — until the chain runs
+ * again with `allowWholeRecording` (umtool's one press). Then the run, waited on.
+ */
+async function fetchWindowsStep(ctx, body, what) {
+ const origin = originOfHandle(await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null));
+ if (origin) {
+ // An archive removed from settings is not read any more (the editor
+ // refuses its channels' windows too): nothing is asked of it, and the step
+ // says to connect it again. The connected ones are settings.json's and
+ // TRANSCRIPT_SITE_URL's, as the source picker lists them (lib/research/sources.ts).
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(REPO_ROOT, "settings.json");
+ const stored = await readFile(settingsFile, "utf8").then((t) => JSON.parse(t)?.remoteArchives, () => null);
+ const gone = disconnectedArchiveRefusal(origin, connectedArchives(stored));
+ if (gone) throw new StepFailed(`this article was swept over a published archive, and ${gone}`);
+ const getJson = cachedArchiveGetJson();
+ body.archive = origin;
+ for (const item of body.items) {
+ if (item.webpageUrl) continue;
+ // Only a video platform's page (the editor refuses any other, too), and
+ // as the URL the check parsed — never the record's own string.
+ const href = await archiveRecordPageHref(origin, item.slug, item.id, detectPlatform, { getJson });
+ if (href) item.webpageUrl = href;
+ }
+ if (ctx.allowWholeRecording) body.allowWholeRecording = true;
+ const dry = await editorCall(await editorEnv(), "POST", "/api/ops/fetch-windows", { ...body, dryRun: true });
+ if (!dry.ok) throw new StepFailed(`the editor refused the windows: ${dry.error}`);
+ const whole = (dry.body?.unresolved ?? []).filter((u) => String(u?.error ?? "").startsWith(WHOLE_RECORDING_REFUSED));
+ if (whole.length > 0) {
+ const sizes = whole.map((u) => /: (\S+ is [^.]+|\S+'s length is not known to its archive)\./.exec(String(u.error))?.[1] ?? `${u.item?.slug}/${u.item?.id}`);
+ throw new StepFailed(
+ `${WHOLE_RECORDING_REFUSED} ${whole.length} window(s) need their whole recording downloaded — ${[...new Set(sizes)].join("; ")}. ` +
+ "Allow the whole recordings to fetch them (the chain again, allowWholeRecording).",
+ );
+ }
+ }
+ await mkdir(ctx.project, { recursive: true });
+ const file = path.join(ctx.project, "windows.json");
+ await writeJson(file, body);
+ const code = await ops("fetch-windows", ["--file", file]);
+ if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`);
+ return `${body.items.length} window(s) ${what} on disk${origin ? ` (archive ${origin})` : ""}`;
}
const describe = (problems) =>
@@ -121,24 +180,51 @@ const STEPS = {
const report = JSON.parse(await readFile(articleFile(ctx.paths, ctx.article), "utf8"));
const body = chainWindows(report, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n}` });
if (body.items.length === 0) return "no clip windows cited";
- await mkdir(ctx.project, { recursive: true });
- const file = path.join(ctx.project, "windows.json");
- await writeJson(file, body);
- const code = await ops("fetch-windows", ["--file", file]);
- if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`);
- return `${body.items.length} window(s) on disk`;
+ return fetchWindowsStep(ctx, body, "cited");
+ },
+
+ // Draft everything's (demo epic D1): the windows of the clips the cut kept.
+ async ["cut-windows"](ctx) {
+ const file = path.join(ctx.project, "video.manifest.json");
+ const manifest = await readJsonOr(file);
+ if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`);
+ const body = cutWindows(manifest, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n} cut` });
+ if (body.items.length === 0) return "the cut has no clip";
+ // What the build would find on disk is not asked for: the project's own
+ // out/clips-raw, the corpus's windows, a saved recording (sources.mjs, the
+ // build's lookup order).
+ const rawDir = path.join(ctx.project, "out", "clips-raw");
+ const missing = [];
+ for (const item of body.items) {
+ const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir }).catch(() => null);
+ if (!hit) missing.push(item);
+ }
+ if (missing.length === 0) return `the cut's ${body.items.length} window(s) are on disk already`;
+ const held = body.items.length - missing.length;
+ const said = await fetchWindowsStep(ctx, { ...body, items: missing }, "of the cut's");
+ return held ? `${said}; ${held} on disk already` : said;
},
async prepare(ctx) {
const code = await prepareMain({ article: ctx.article, only: true });
if (code === 0) return "the evidence media is complete; the article is exported";
- const { own, shots, rest } = await ownProblems(ctx.paths, ctx.article);
- if (own.length > 0 && rest.length === 0) return `${shots.length} post screenshot(s) to capture (the next step)`;
- throw new StepFailed(rest.length ? describe(rest) : `reports prepare ended ${code}`);
+ const { own, shots, clips, rest } = await ownProblems(ctx.paths, ctx.article);
+ // Draft everything fetches the CUT's windows later (cut-windows): an
+ // evidence clip not fetched yet does not stop it.
+ const later = ctx.mode === "draft-all" ? clips : [];
+ const blocking = ctx.mode === "draft-all" ? rest : [...clips, ...rest];
+ if (own.length > 0 && blocking.length === 0) {
+ return [
+ shots.length ? `${shots.length} post screenshot(s) to capture (the next step)` : "",
+ later.length ? `${later.length} evidence clip(s) not fetched: the cut's are fetched after the cut is drafted; the rest by Fetch missing evidence` : "",
+ ].filter(Boolean).join("; ");
+ }
+ throw new StepFailed(blocking.length ? describe(blocking) : `reports prepare ended ${code}`);
},
async posts(ctx) {
- const { shots, rest } = await ownProblems(ctx.paths, ctx.article);
+ const { shots, clips, rest: others } = await ownProblems(ctx.paths, ctx.article);
+ const rest = ctx.mode === "draft-all" ? others : [...clips, ...others];
if (rest.length > 0) throw new StepFailed(`prepare has this article's other problems first: ${describe(rest)}`);
if (shots.length === 0) return "no post screenshot to capture";
const bySlug = new Map();
@@ -155,7 +241,9 @@ const STEPS = {
const code = await prepareMain({ article: ctx.article, only: true });
if (code !== 0) {
const again = await ownProblems(ctx.paths, ctx.article);
- throw new StepFailed(again.own.length ? describe(again.own) : `reports prepare ended ${code}`);
+ const left = ctx.mode === "draft-all" ? [...again.shots, ...again.rest] : again.own;
+ if (left.length === 0) return `${shots.length} post screenshot(s) captured; ${again.clips.length} evidence clip(s) not fetched yet`;
+ throw new StepFailed(left.length ? describe(left) : `reports prepare ended ${code}`);
}
return `${shots.length} post screenshot(s) captured; the evidence media is complete`;
},
@@ -437,13 +525,17 @@ async function writeJson(file, value) {
// The archive the sweep's moment links name — the QR codes' origin: the
// newest sweep.md in the iteration's lineage that names one.
+// When none does (a hand-made iteration, a sweep.md without moment links),
+// the published archive the lineage read (demo epic D1: `scope.source`,
+// remote:<origin>) — the editor cited it there.
async function sweepOrigin(ctx) {
const line = await lineage(ctx.article, ctx.n, ctx.paths).catch(() => [ctx.n]);
for (const n of [...line].reverse()) {
const origin = originFromSweep(await readIterationFile(ctx.article, n, "sweep.md", ctx.paths));
if (origin) return origin;
}
- return undefined;
+ const source = await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null);
+ return originOfHandle(source) ?? undefined;
}
/**
@@ -481,6 +573,8 @@ export async function runChainStep(article, n, name, opts = {}) {
siteOrigin: opts.siteOrigin,
final: opts.final === true,
model: opts.model,
+ mode: opts.mode === "draft-all" ? "draft-all" : "video",
+ allowWholeRecording: opts.allowWholeRecording === true,
cancels: [],
onCancel(fn) {
this.cancels.push(fn);
@@ -552,6 +646,8 @@ function parseArgs(argv) {
siteOrigin: flag("--site-origin"),
final: rest.includes("--final"),
model: flag("--model"),
+ mode: flag("--mode"),
+ allowWholeRecording: rest.includes("--allow-whole-recording"),
};
}
@@ -559,7 +655,7 @@ const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToP
if (isMain) {
const a = parseArgs(process.argv.slice(2));
if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) {
- console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]");
+ console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] [--mode draft-all] [--allow-whole-recording]");
process.exit(2);
}
runChainStep(a.article, a.n, a.name, a).then(
diff --git a/umtool/lib/report/chain-run.test.mjs b/umtool/lib/report/chain-run.test.mjs
@@ -156,3 +156,57 @@ test("refusals: a queued iteration, an unknown step, no such iteration", () => {
assert.equal(none.code, 2);
assert.match(none.out, /has no iteration i9/);
});
+
+test("manifest: with no sweep.md naming an origin, the archive the sweep read (scope.source) is the QR origin (demo epic D1)", () => {
+ const dir = path.join(ARTICLES, "synth-remote", "iterations", "1");
+ put(path.join(dir, "iteration.json"), iteration(1, { article: "synth-remote", scope: { channels: ["synth-kitchen"], source: "remote:https://stub.test" } }));
+ put(path.join(dir, "report.json"), { ...basic, id: "synth-remote" });
+ const run = (name) =>
+ spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-remote", "1", name, "--projects-root", PROJECTS], {
+ cwd: REPO_ROOT,
+ env: ENV,
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ for (const name of ["current", "manifest"]) {
+ const r = run(name);
+ assert.equal(r.status, 0, `${name}: ${r.stdout}\n${r.stderr}`);
+ }
+ const m = json(path.join(PROJECTS, "synth-remote", "i1", "video.manifest.json"));
+ assert.equal(m.provenance.siteOrigin, "https://stub.test");
+});
+
+test("windows: an article swept over an archive that is no longer connected asks nothing of it, and says to connect it again (demo epic D1 re-check)", () => {
+ // synth-remote's lineage read remote:https://stub.test (the test above); settings.json names no archive.
+ const env = { ...ENV };
+ delete env.TRANSCRIPT_SITE_URL;
+ const r = spawnSync(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-remote", "1", "windows", "--projects-root", PROJECTS], {
+ cwd: REPO_ROOT,
+ env,
+ encoding: "utf8",
+ timeout: 120_000,
+ });
+ assert.equal(r.status, 1, `${r.stdout}\n${r.stderr}`);
+ const s = Object.fromEntries(json(path.join(ARTICLES, "synth-remote", "iterations", "1", "iteration.json")).steps.map((x) => [x.task, x]))["chain:windows"];
+ assert.equal(s.status, "failed");
+ assert.match(s.detail, /swept over a published archive, and its archive https:\/\/stub\.test is no longer connected — connect it again/);
+ // Refused before the plan is written or the editor asked.
+ assert.equal(existsSync(path.join(PROJECTS, "synth-remote", "i1", "windows.json")), false);
+});
+
+test("cut-windows (Draft everything, demo epic D1): the cut's windows the project already holds are not asked of the editor", () => {
+ // i2's project: its manifest (from the manifest test) and the cut's window in out/clips-raw.
+ const project = path.join(PROJECTS, "synth-basic", "i2");
+ const m = json(path.join(project, "video.manifest.json"));
+ const clips = (m.timeline ?? []).filter((e) => e.type === "clip");
+ assert.ok(clips.length > 0);
+ for (const c of clips) {
+ const from = Math.max(0, Math.floor((c.start - 3) * 100) / 100);
+ const to = Math.ceil((c.end + 3) * 100) / 100;
+ put(path.join(project, "out", "clips-raw", `${c.video}_${from.toFixed(2)}-${to.toFixed(2)}.mp4`), Buffer.alloc(64, 1));
+ }
+ // The editor is a closed port: had the step asked it, it would have failed.
+ const r = step(2, "cut-windows", "--mode", "draft-all");
+ assert.equal(r.code, 0, r.out);
+ assert.match(recorded(2)["chain:cut-windows"].detail, /the cut's \d+ window\(s\) are on disk already/);
+});
diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs
@@ -5,7 +5,8 @@
// current make the iteration current (the article's report.json)
// windows the editor fetches every cited clip window, padded to the
// video build's fetchPad, so one fetch serves both the article's
-// evidence clips and the cut
+// evidence clips and the cut (in "make the video" the cut IS every
+// cited clip: to-manifest makes one of each)
// prepare `reports prepare --article <id> --only`
// posts the editor captures THIS article's missing post screenshots,
// then prepare again
@@ -24,11 +25,28 @@
// steps in it, each OPTIONAL — `draft-<task>` runs one `report-draft` job on
// the iteration through the editor and waits for it:
//
-// current → windows → prepare → posts → manifest → draft-cut →
+// current → prepare → posts → manifest → draft-cut → cut-windows →
// draft-onscreen → draft-teaser → draft-flips → draft-threads →
// draft-narrate → voices → video (fast, never --final) → podcast →
// draft-youtube → draft-social
//
+// WINDOWS FOR THE CUT, NOT FOR EVERY CITATION (demo epic D1): Draft
+// everything has no early `windows`; `cut-windows` fetches the windows of the
+// clips the drafted cut kept (cutWindows, from the manifest), so a 37-citation
+// report whose cut keeps 9 asks the editor for 9. Its prepare and posts steps
+// go on past evidence clips not fetched yet (the article's remaining evidence
+// is the site's Fetch missing evidence, never the chain's).
+//
+// STOP BEFORE RENDER (demo epic D1, `stopBeforeRender`, off by default): the
+// chain ends before `voices` — nothing voiced, built or attached — so the cut
+// can be walked first; the next run resumes at `voices`.
+//
+// A connected archive's sweep (its iteration's `scope.source`, demo epic D1):
+// the windows steps name the archive and each clip's page URL from its record,
+// so the editor registers the channel remote-only; a remote-only channel's
+// whole recording (Rumble) is refused with its size until the chain is run
+// again with `allowWholeRecording` (umtool's one press).
+//
// The drafts go after `manifest` (a media task drafts the project's manifest)
// and before `voices` (narration is voiced) and the build (the drafts are in
// it); YouTube's after the build, which then re-muxes its chapters so
@@ -64,6 +82,7 @@ import { existsSync, readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { UMTOOL_DIR } from "./driver.mjs";
+import { defaultProjectsRoot } from "yt-dlp-transcript-common/lib/projectsRoot.mjs";
// `draft`: the report-draft task an optional generation step runs.
// `modes`: the chains a step is in ("video" — make the video; "draft-all").
@@ -74,11 +93,12 @@ const DRAFT_TIMEOUT = 3 * 60 * 60_000;
export const CHAIN_STEPS = [
{ name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000, modes: BOTH },
- { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: BOTH },
+ { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: VIDEO_ONLY },
{ name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000, modes: BOTH },
{ name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000, modes: BOTH },
{ name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000, modes: BOTH },
{ name: "draft-cut", label: "draft the cut: which clips, in what order", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "cut" },
+ { name: "cut-windows", label: "fetch the cut's clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: DRAFT_ONLY },
{ name: "draft-onscreen", label: "draft the on-screen titles", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "onscreen" },
{ name: "draft-teaser", label: "draft the teaser", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "teaser" },
{ name: "deck", label: "add the on-screen deck when the cut has none", timeoutMs: 5 * 60_000, modes: DRAFT_ONLY, optional: true, option: "deck" },
@@ -97,19 +117,26 @@ export const CHAIN_STEPS = [
/** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */
export const CHAIN_MODES = ["video", "draft-all"];
-/** The chains' options: `deck` (Draft everything's deck step, release 29 G1). Each is off by default. */
-export const CHAIN_OPTIONS = ["deck"];
+/** The chains' options: `deck` (Draft everything's deck step, release 29 G1), `stopBeforeRender` (demo epic D1). Each is off by default. */
+export const CHAIN_OPTIONS = ["deck", "stopBeforeRender"];
+
+/** The step a `stopBeforeRender` chain ends before: nothing is voiced or built. */
+export const RENDER_STEP = "voices";
/**
* A chain's steps, in order. A step with an `option` is in it only when that
- * option is on (`{ deck: true }`); with none on, the chain is as it always was.
+ * option is on (`{ deck: true }`); `stopBeforeRender` ends it before
+ * RENDER_STEP; with none on, the chain is as it always was.
*
* @param {string} [mode]
- * @param {{ deck?: boolean }} [options]
+ * @param {{ deck?: boolean, stopBeforeRender?: boolean }} [options]
*/
export function chainStepsOf(mode = "video", options = {}) {
if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`);
- return CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true));
+ const steps = CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true));
+ if (options?.stopBeforeRender !== true) return steps;
+ const at = steps.findIndex((s) => s.name === RENDER_STEP);
+ return at < 0 ? steps : steps.slice(0, at);
}
/** Every step's name, either chain's (what the executor runs). */
@@ -131,8 +158,10 @@ export const chainTask = (name) => `chain:${name}`;
// STARTER_RENDER): the windows are fetched this wide so the cut finds them.
export const CHAIN_WINDOW_PAD = 3;
-// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this.
-export const DEFAULT_PROJECTS_ROOT = path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
+// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this —
+// `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports
+// volume), else ~/reports/articles (common/lib/projectsRoot.mjs, the one rule).
+export const DEFAULT_PROJECTS_ROOT = defaultProjectsRoot();
// From driver.mjs's package root, which is found from the module (or, under
// the Next server, the cwd) — never this module's URL alone.
@@ -171,8 +200,8 @@ export function chainProject(projectsRoot, article, n) {
* has not recorded finished (`done`: the step names recorded finished,
* doneSteps), else nothing (the whole chain is done: null).
*/
-export function chainStart({ from = null, done = [], mode = "video", deck = false } = {}) {
- const names = chainStepsOf(mode, { deck }).map((s) => s.name);
+export function chainStart({ from = null, done = [], mode = "video", deck = false, stopBeforeRender = false } = {}) {
+ const names = chainStepsOf(mode, { deck, stopBeforeRender }).map((s) => s.name);
if (from !== null && from !== undefined) {
if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`);
return from;
@@ -217,7 +246,7 @@ export function readIterationRecord(articlesDir, article, n) {
* `final` says, and `model` rides on the draft steps (else each task's route);
* `deck` adds its deck step (G1).
*
- * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean }} o
+ * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o
* @returns {import("../trim").Step[]}
*/
export function chainSteps(o) {
@@ -225,7 +254,7 @@ export function chainSteps(o) {
chainProject(projectsRoot, o.article, o.n);
const mode = o.mode ?? "video";
if (o.deck === true && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)");
- const defs = chainStepsOf(mode, { deck: o.deck === true });
+ const defs = chainStepsOf(mode, { deck: o.deck === true, stopBeforeRender: o.stopBeforeRender === true });
const start = o.start === undefined ? defs[0].name : o.start;
if (start === null) return [];
const at = defs.findIndex((s) => s.name === start);
@@ -238,6 +267,8 @@ export function chainSteps(o) {
projectsRoot,
...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []),
...(o.final && mode === "video" ? ["--final"] : []),
+ ...(mode !== "video" ? ["--mode", mode] : []),
+ ...(o.allowWholeRecording === true ? ["--allow-whole-recording"] : []),
];
return defs.slice(at).map((s, i) => ({
label: `${at + i + 1}/${defs.length} ${s.label}`,
@@ -256,7 +287,7 @@ export function chainSteps(o) {
* iteration not done, or an unknown `from`. `steps` is empty when every step
* is done.
*
- * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean }} o
+ * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o
*/
export function planChain(o) {
const record = readIterationRecord(o.articlesDir, o.article, o.n);
@@ -265,19 +296,22 @@ export function planChain(o) {
const mode = o.mode ?? "video";
const deck = o.deck === true;
if (deck && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)");
- const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck });
+ const stopBeforeRender = o.stopBeforeRender === true;
+ const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck, stopBeforeRender });
const steps = chainSteps({
article: o.article,
n: o.n,
start,
mode,
...(deck ? { deck } : {}),
+ ...(stopBeforeRender ? { stopBeforeRender } : {}),
+ ...(o.allowWholeRecording === true ? { allowWholeRecording: true } : {}),
...(o.model ? { model: o.model } : {}),
...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}),
...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}),
final: o.final === true,
});
- return { record, start, steps, mode, deck };
+ return { record, start, steps, mode, deck, stopBeforeRender };
}
const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100;
@@ -318,6 +352,39 @@ export function chainWindows(report, { pad = CHAIN_WINDOW_PAD, requestedBy = "um
return { items, requestedBy };
}
+/**
+ * The windows of the clips a CUT keeps (demo epic D1): its manifest's clip
+ * entries, each its span widened by `pad` and rounded outward to the
+ * hundredth, one per distinct moment — the same body chainWindows makes from
+ * a report, for the cut a draft (or a person) narrowed.
+ */
+export function cutWindows(manifest, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) {
+ const items = [];
+ const byMoment = new Map();
+ const fallbackChannel = manifest?.provenance?.channelSlug;
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const slug = e.channel ?? fallbackChannel;
+ if (!slug || !e.video || typeof e.start !== "number" || typeof e.end !== "number") continue;
+ const from = floor2(Math.max(0, e.start - pad));
+ const to = ceil2(e.end + pad);
+ const key = `${slug}/${e.video}`;
+ if ((byMoment.get(key) ?? []).some((w) => w.from <= from && w.to >= to)) continue;
+ const item = {
+ slug,
+ id: e.video,
+ from,
+ to,
+ clipId: `${manifest.slug ?? "cut"}#${e.id}`,
+ reason: `cut ${manifest.slug ?? ""} ${e.id}`.trim(),
+ pad,
+ };
+ items.push(item);
+ byMoment.set(key, [...(byMoment.get(key) ?? []), item]);
+ }
+ return { items, requestedBy };
+}
+
/** The archive origin a sweep's moment links name (`https://host/?v=…`), or null. */
export function originFromSweep(text) {
const m = /(https?:\/\/[^/\s)"']+)\/?\?v=/.exec(String(text ?? ""));
diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs
@@ -23,6 +23,7 @@ import {
chainWindows,
chainStepsOf,
CHAIN_OPTIONS,
+ cutWindows,
DRAFT_STEP_TASKS,
doneSteps,
originFromSweep,
@@ -55,7 +56,7 @@ test("the steps, in order, each one process of the executor under tsx, from the
});
test("the deck option (release 29 G1): a step before the flips, off by default — without it the chain is as it was", () => {
- assert.deepEqual(CHAIN_OPTIONS, ["deck"]);
+ assert.deepEqual(CHAIN_OPTIONS, ["deck", "stopBeforeRender"]);
const plain = chainStepsOf("draft-all").map((s) => s.name);
assert.ok(!plain.includes("deck"));
const withDeck = chainStepsOf("draft-all", { deck: true }).map((s) => s.name);
@@ -77,7 +78,7 @@ test("the deck option (release 29 G1): a step before the flips, off by default
);
assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", deck: true }), /the deck is Draft everything's option/);
// Resume: a chain that ran to the threads without the deck starts again at the deck with it.
- const ran = ["current", "windows", "prepare", "posts", "manifest", "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"];
+ const ran = ["current", "prepare", "posts", "manifest", "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"];
assert.equal(chainStart({ done: ran, mode: "draft-all", deck: true }), "deck");
assert.equal(chainStart({ done: ran, mode: "draft-all" }), "draft-narrate");
assert.ok(doneSteps({ steps: [{ task: "chain:deck", status: "failed" }] }).includes("deck"), "optional: a failed deck step is passed");
@@ -103,8 +104,8 @@ test("resume: the first step not recorded done; --from names one; all done is no
test("Draft everything: the drafts between the manifest and the fast build, YouTube after it; the default chain unchanged", () => {
const names = chainStepsOf("draft-all").map((s) => s.name);
assert.deepEqual(names, [
- "current", "windows", "prepare", "posts", "manifest",
- "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate",
+ "current", "prepare", "posts", "manifest",
+ "draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate",
"voices", "video", "podcast", "draft-youtube", "draft-social",
]);
assert.deepEqual(chainStepsOf("video").map((s) => s.name), CHAIN_STEP_NAMES);
@@ -114,14 +115,16 @@ test("Draft everything: the drafts between the manifest and the fast build, YouT
const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", final: true });
assert.equal(steps.length, 16);
- assert.equal(steps[5].label, "6/16 draft the cut: which clips, in what order");
+ assert.equal(steps[4].label, "5/16 draft the cut: which clips, in what order");
+ // demo epic D1: the cut's windows right after the cut is drafted, not every citation's before it.
+ assert.equal(steps[5].label, "6/16 fetch the cut's clip windows (editor)");
// The model rides on the draft steps only; the build is the fast one (--final is ignored).
for (const s of steps) {
const draft = s.argv[7].startsWith("draft-");
assert.equal(s.argv.includes("--model"), draft, s.argv[7]);
assert.ok(!s.argv.includes("--final"), s.argv[7]);
}
- assert.deepEqual(steps[5].argv.slice(8), ["--projects-root", "/p", "--model", "qwen3:8b"]);
+ assert.deepEqual(steps[4].argv.slice(8), ["--projects-root", "/p", "--mode", "draft-all", "--model", "qwen3:8b"]);
// No model: each task's route chooses.
assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all" }).every((s) => !s.argv.includes("--model")));
assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", model: "a b" }), /not a model name/);
@@ -133,18 +136,19 @@ test("Draft everything resumes past a draft that ran — done, skipped or failed
const it = {
steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done" })).concat([
{ task: "chain:draft-cut", status: "done" },
+ { task: "chain:cut-windows", status: "done" },
{ task: "chain:draft-onscreen", status: "failed" },
{ task: "chain:draft-teaser", status: "skipped" },
{ task: "chain:draft-flips", status: "cancelled" },
]),
};
const done = doneSteps(it);
- assert.deepEqual(done.slice(5), ["draft-cut", "draft-onscreen", "draft-teaser"]);
+ assert.deepEqual(done.slice(5), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser"]);
assert.equal(chainStart({ done, mode: "draft-all" }), "draft-flips");
// The default chain never sees the drafts: it resumes at voices.
assert.equal(chainStart({ done }), "voices");
- const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "failed" }] };
- assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "windows");
+ const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:prepare", status: "failed" }] };
+ assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "prepare");
assert.equal(chainStart({ from: "draft-threads", mode: "draft-all" }), "draft-threads");
assert.throws(() => chainStart({ from: "draft-threads" }), /--from must be one of/);
const all = chainStepsOf("draft-all").map((s) => s.name);
@@ -203,14 +207,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus
// --draft-all: the same resume point, the drafts in the plan, the model on them.
const all = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--model", "claude-sonnet-5-5", "--projects-root", path.join(ROOT, "projects")));
assert.equal(all.start, "prepare");
- assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate"]);
+ assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "cut-windows", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]);
assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(-2), ["draft-youtube", "draft-social"]);
assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5"));
assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr)));
assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr)));
// --deck (release 29 G1): the deck step before the flips; Draft everything's only.
const deck = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--deck", "--projects-root", path.join(ROOT, "projects")));
- assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(6, 8), ["deck", "draft-flips"]);
+ assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(7, 9), ["deck", "draft-flips"]);
assert.throws(() => run("art", "2", "--dry", "--deck"), (e) => /--deck is Draft everything's option/.test(String(e.stderr)));
});
@@ -249,3 +253,43 @@ test("the projects root comes from settings.generation.projectsRoot (release 27
rmSync(dir, { recursive: true, force: true });
}
});
+
+// demo epic D1: windows for the cut; stop before render; the whole-recording allowance.
+test("cutWindows: the manifest's clips, padded and rounded outward, once per moment", () => {
+ const body = cutWindows(
+ {
+ slug: "art-i2",
+ provenance: { channelSlug: "fallback" },
+ timeline: [
+ { type: "card", id: "t0" },
+ { type: "clip", id: "c1", channel: "alpha", video: "v1", start: 10.004, end: 20 },
+ { type: "clip", id: "c2", channel: "alpha", video: "v1", start: 12, end: 18 }, // inside c1's window
+ { type: "clip", id: "c3", video: "v2", start: 1, end: 4 }, // the manifest's channel
+ { type: "clip", id: "bad", channel: "alpha", video: "v3" },
+ ],
+ },
+ { pad: 3, requestedBy: "t" },
+ );
+ assert.deepEqual(body, {
+ requestedBy: "t",
+ items: [
+ { slug: "alpha", id: "v1", from: 7, to: 23, clipId: "art-i2#c1", reason: "cut art-i2 c1", pad: 3 },
+ { slug: "fallback", id: "v2", from: 0, to: 7, clipId: "art-i2#c3", reason: "cut art-i2 c3", pad: 3 },
+ ],
+ });
+});
+
+test("stopBeforeRender ends either chain before the voices; the allowance rides on every step", () => {
+ const video = chainStepsOf("video", { stopBeforeRender: true }).map((s) => s.name);
+ assert.deepEqual(video, ["current", "windows", "prepare", "posts", "manifest"]);
+ const all = chainStepsOf("draft-all", { stopBeforeRender: true }).map((s) => s.name);
+ assert.equal(all.at(-1), "draft-narrate");
+ assert.ok(!all.includes("voices") && !all.includes("video"));
+ // All done before the render: nothing to run; without the option, it resumes at the voices.
+ assert.equal(chainStart({ done: video, stopBeforeRender: true }), null);
+ assert.equal(chainStart({ done: video }), "voices");
+ const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", stopBeforeRender: true, allowWholeRecording: true });
+ assert.equal(steps.length, 5);
+ assert.ok(steps.every((s) => s.argv.includes("--allow-whole-recording")));
+ assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node" }).every((s) => !s.argv.includes("--allow-whole-recording") && !s.argv.includes("--mode")));
+});
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -63,7 +63,7 @@ export const isMontage = (manifest) =>
*
* @param {Record<string, any>} manifest
* @param {{ manifestPath: string, project: string, rulings?: { rulings: Record<string, { verdict: string }> } | null, reason?: string | null }} opts
- * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }}
+ * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", archive?: string, items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }}
*/
export function fetchWindowsBody(manifest, { manifestPath, project, rulings = null, reason = null }) {
const montage = isMontage(manifest);
@@ -106,8 +106,18 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu
});
}
}
+ // The archive the cut cites (demo epic D1): its provenance.siteOrigin. The
+ // editor registers a channel it does not hold as remote-only only when that
+ // origin is a CONNECTED archive; any other origin changes nothing.
+ const site = typeof manifest?.provenance?.siteOrigin === "string" ? manifest.provenance.siteOrigin.trim().replace(/\/+$/, "") : "";
return {
- body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", items },
+ body: {
+ requestedBy: `umtool:${project}`,
+ manifest: path.resolve(manifestPath),
+ storedUrl: "fallback",
+ ...(/^https?:\/\//.test(site) ? { archive: site } : {}),
+ items,
+ },
skipped,
};
}
diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs
@@ -59,7 +59,7 @@ export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "ve
export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]);
const SET_KEYS = [
"claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS,
- ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote",
+ ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", "chapter",
// The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post.
...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS,
];
@@ -105,6 +105,8 @@ export const SET_USAGE = [
" footage no dodge can know of; any entry, a post item too): goals peak promise diet streak; `hideModules=` none.",
" shelfNote='Weighed in on camera' puts one line (≤ 80 characters) on the shelf (render.chrome.deck.shelf, its",
" `note` slot) over this entry's span, coming and going with it; any entry; `shelfNote=` none.",
+ " chapter='The weigh-in' names this entry in the chapter list (out/chapters, youtube.txt) in place of its on-screen",
+ " title or the line derived from its record: one line, ≤ 100 characters; any entry; `chapter=` none.",
" --take <t>: the entry knobs (not claim.* or marks) land in takes/<t>/take.json's patch, an undo point first",
" (`umtool timeline <p> --take <t> undo`); the project's manifest is untouched.",
" vertical.crop='[x,y,w,h]' (fractions of the source: the 9:16 box a vertical render cuts; vertical.aspect the",
@@ -119,7 +121,9 @@ export const SET_USAGE = [
].join("\n");
export const LOOK_USAGE = [
- "usage: umtool look <project> key=value … [--unset render.<key>]… [--json]",
+ "usage: umtool look <project> key=value … [--unset render.<key>]… [--take <t>] [--json]",
+ " --take <t>: the deck.* keys given are set on THAT TAKE (its patch, an undo point of its own:",
+ " umtool timeline <p> --take <t> undo); the project's manifest is untouched. deck.* keys only",
" chrome.layout=deck: the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck)",
" --unset render.<key>: drop a legacy render key (rail chromeEngine railEngine chromeRegions claimSchedule wordmark",
" title finale cut) -- with chrome.layout=deck in ONE write (the deck refuses the old rail beside it), an undo point first",
@@ -245,6 +249,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
entryPatch.shelfNote = value === null || value === undefined ? null : String(value);
continue;
}
+ if (key === "chapter") {
+ // The entry's name in the chapter list (manifest.mjs parseEntryChapter checks it); words whatever they parse as.
+ entryPatch.chapter = value === null || value === undefined ? null : String(value);
+ continue;
+ }
if (key === "hideModules") {
// The modules hidden over this entry's span (deck.mjs parseHideModules checks the ids); `hideModules=` none.
entryPatch.hideModules = value === null || value === undefined ? null : value;
@@ -334,6 +343,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if (take) results.take = { id: take, undo: result.revision?.rel ? `takes/${take}/${result.revision.rel}` : null };
if ("hideModules" in entryPatch) results.hideModules = result.entry.hideModules ?? null;
if ("shelfNote" in entryPatch) results.shelfNote = result.entry.shelfNote ?? null;
+ if ("chapter" in entryPatch) results.chapter = result.entry.chapter ?? null;
if ("audio" in entryPatch) results.audio = result.entry.audio ?? null;
if ("blur" in entryPatch) results.blur = result.entry.blur ?? null;
if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip";
@@ -371,6 +381,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso
if ("layout" in results) out(`${clipId}: layout ${results.layout}`);
if ("hideModules" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: hideModules ${results.hideModules ? `${results.hideModules.join(", ")} (hidden over its span)` : "none"}`);
if ("shelfNote" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: shelfNote ${results.shelfNote ? JSON.stringify(results.shelfNote) + " (on the shelf over its span)" : "none"}`);
+ if ("chapter" in results) out(`${clipId}${results.take ? ` (take ${results.take.id})` : ""}: chapter ${results.chapter ? JSON.stringify(results.chapter) + " (its name in the chapter list)" : "none (named by its on-screen title, else its record)"}`);
if (results.take?.undo) out(` undo point: ${results.take.undo} (umtool timeline ${project.id} --take ${results.take.id} undo)`);
if ("chat" in results) out(`${clipId}: chat ${results.chat === true ? "on (its video's live_chat.cues.json beside the footage; the build says if there is none)" : results.chat === false ? "off" : "default (off)"}`);
if ("fx" in results) out(`${clipId}: fx ${results.fx ? JSON.stringify(results.fx) : "none"}`);
@@ -480,6 +491,45 @@ export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => cons
}
const project = await projectOf(projectArg, root);
const pairs = parseAssignments(rest);
+ // A TAKE'S DECK KEYS (`--take <t>`, 12 Nov: `deck.goals.baseMaxDays` for one take): the same write over the take's
+ // manifest, landing in its patch with an undo point of the take's own (takeScope.mjs) -- the project's manifest
+ // untouched. The deck's keys only: the other knobs here are the project's.
+ if (flags.has("--take")) {
+ const take = typeof flags.get("--take") === "string" && flags.get("--take") ? String(flags.get("--take")) : null;
+ if (!take) throw new CliError("--take needs a take id");
+ const other = pairs.filter(([k]) => !k.startsWith("deck."));
+ if (other.length || flags.has("--unset")) {
+ throw new CliError(`--take sets a take's deck keys (deck.<key>=…); ${other.length ? other.map(([k]) => k).join(", ") : "--unset"} is the project's (set it without --take)`);
+ }
+ const { isTakeId, takesDirOf, TAKE_FILE } = await import("./takes.mjs");
+ if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id (lower-case letters, digits, dashes)`);
+ const { stat } = await import("node:fs/promises");
+ const { default: nodePath } = await import("node:path");
+ if (!(await stat(nodePath.join(takesDirOf(project.dir), take, TAKE_FILE)).catch(() => null))) {
+ err(`${project.id} has no take ${take} (no takes/${take}/${TAKE_FILE})`);
+ return 1;
+ }
+ const busy = await (await import("./takeImport.mjs")).takeRenderingNow(project.dir, take);
+ if (busy) {
+ err(`not edited: ${busy}`);
+ return 1;
+ }
+ const { withTakeScope } = await import("./takeScope.mjs");
+ const lines = [];
+ const code = await withTakeScope(project.dir, take, () =>
+ lookCommand([projectArg, ...rest, ...(json ? ["--json"] : [])], { root, out: (l) => lines.push(l), err }));
+ if (json && code === 0) {
+ for (const l of lines) {
+ let doc = null;
+ try { doc = JSON.parse(l); } catch { /* a line of prose */ }
+ out(doc && typeof doc === "object" ? JSON.stringify({ ...doc, take: { id: take, undo: `umtool timeline ${project.id} --take ${take} undo` } }, null, 2) : l);
+ }
+ } else {
+ for (const l of lines) out(l);
+ if (code === 0) out(`take ${take}: written to its patch (undo: umtool timeline ${project.id} --take ${take} undo)`);
+ }
+ return code;
+ }
// THE DECK ON, LEGACY KEYS OFF (updateRenderKeys): `chrome.layout=deck` (render.chrome created when the cut has
// none) and `--unset render.<key>`, in one write with an undo point -- before any deck.* key, which needs the chrome.
const chromeOn = pairs.filter(([k]) => k === "chrome.layout" || k === "chrome.engine");
diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs
@@ -342,3 +342,60 @@ test("umtool look chrome.layout=deck --unset render.<key>: the deck turned on an
assert.equal(await run("fresh", "chrome.layout=deck", "deck.sectionTitle=true"), 0, lines.join("\n"));
assert.deepEqual((await read(fresh)).render.chrome.deck, { sectionTitle: true });
});
+
+test("umtool look deck.<key>=… --take <t>: the take's patch, an undo point of the take's, the project's manifest untouched; deck keys only", async () => {
+ const dir = await project("looktake");
+ const { lines, run } = runner(lookCommand);
+ const { draftTake } = await import("./takeMaker.mjs");
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ await draftTake(dir, { id: "a9", label: "A9", patch: {} });
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ assert.equal(await run("looktake", "deck.goals.base=true", "deck.goals.baseMaxDays=365", "--take", "a9"), 0, lines.join("\n"));
+ assert.match(lines.join("\n"), /deck\.goals: \{"base":true,"baseMaxDays":365\}/);
+ assert.match(lines.at(-1), /take a9: written to its patch \(undo: umtool timeline looktake --take a9 undo\)/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+ assert.deepEqual((await resolveTakeManifest(dir, "a9")).manifest.render.chrome.deck.goals, { base: true, baseMaxDays: 365 });
+ // One field off again keeps the rest.
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=", "--take", "a9"), 0, lines.join("\n"));
+ assert.deepEqual((await resolveTakeManifest(dir, "a9")).manifest.render.chrome.deck.goals, { base: true });
+ // The build's rules still refuse; other knobs and a take that is not there are refused.
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=-3", "--take", "a9"), 1);
+ assert.match(lines.at(-1), /baseMaxDays must be null \(every base counts\) or whole days/);
+ assert.equal(await run("looktake", "transition=0.3", "--take", "a9"), 2);
+ assert.match(lines.at(-1), /--take sets a take's deck keys/);
+ assert.equal(await run("looktake", "deck.goals.baseMaxDays=365", "--take", "nope"), 1);
+ assert.match(lines.at(-1), /has no take nope/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+});
+
+test("umtool set chapter='…': an entry's name in the chapter list, any entry; chapter= clears; --take writes the take's patch", async () => {
+ const dir = await project("chapter");
+ const m = await read(dir);
+ m.timeline.push({ type: "post", id: "x01", item: "123" });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ const { lines, run } = runner(setCommand);
+ assert.equal(await run("chapter", "c02", "chapter= The weigh-in "), 0, lines.join("\n"));
+ assert.equal((await read(dir)).timeline[1].chapter, "The weigh-in", "trimmed");
+ assert.match(lines.at(-1), /c02: chapter "The weigh-in" \(its name in the chapter list\)/);
+ assert.equal(await run("chapter", "x01", "chapter=2026"), 0, lines.join("\n"));
+ assert.equal((await read(dir)).timeline[2].chapter, "2026", "a post item too; words whatever they parse as");
+ // Beside a clip's other knobs in one command.
+ assert.equal(await run("chapter", "c01", "chapter=Arrival", "audio.gain=2"), 0, lines.join("\n"));
+ assert.deepEqual([(await read(dir)).timeline[0].chapter, (await read(dir)).timeline[0].audio], ["Arrival", { gain: 2 }]);
+ assert.equal(await run("chapter", "c02", `chapter=${"x".repeat(101)}`), 1);
+ assert.match(lines.at(-1), /chapter is 101 characters \(at most 100\)/);
+ assert.equal((await read(dir)).timeline[1].chapter, "The weigh-in", "a refused write changes nothing");
+ assert.equal(await run("chapter", "c02", "chapter="), 0);
+ assert.equal("chapter" in (await read(dir)).timeline[1], false);
+ assert.match(lines.at(-1), /c02: chapter none/);
+ const { draftTake } = await import("./takeMaker.mjs");
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ await draftTake(dir, { id: "a9", label: "A9", patch: {} });
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ assert.equal(await run("chapter", "c02", "chapter=Day 41", "--take", "a9"), 0, lines.join("\n"));
+ assert.match(lines.join("\n"), /c02 \(take a9\): chapter "Day 41"/);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before);
+ assert.equal((await resolveTakeManifest(dir, "a9")).manifest.timeline[1].chapter, "Day 41");
+ assert.equal(await run("chapter", "x01", "chapter=", "--take", "a9"), 0, lines.join("\n"));
+ assert.equal("chapter" in (await resolveTakeManifest(dir, "a9")).manifest.timeline[2], false);
+});
diff --git a/umtool/lib/report/ledgerCli.mjs b/umtool/lib/report/ledgerCli.mjs
@@ -28,7 +28,9 @@ export const LEDGER_USAGE = [
"instruments' own: run (a loss claim's run, his words placing it), retro (a loss told in the past with no asOf:",
"off the odometer), promise (a promise_check's or promise_claim's promise), kept, due (YYYY-MM-DD), speaker (another",
"party's key: a promise_claim's -- her rows move none of his numbers), paidOn (YYYY-MM-DD), outcome (a",
- "promise_outcome's: kept, refunded, withdrawn)) or a declared field; `null`",
+ "promise_outcome's: kept, refunded, withdrawn), stampNote (a promise_outcome's: the words under its stamp on the",
+ "promise clock in place of \"by <date> · no video\" -- one line; the strip shows its first clause; `umtool lint` warns",
+ "past 26 characters)) or a declared field; `null`",
"clears a value. rm refuses a row a timeline entry pins or another row names.",
].join("\n");
diff --git a/umtool/lib/report/ledgerCli.test.mjs b/umtool/lib/report/ledgerCli.test.mjs
@@ -118,6 +118,15 @@ test("umtool ledger: add, set, unset, rm -- through the writers, on the file", a
assert.equal(await run(ledgerCommand, "weigh", "add", "o02", "--date", "2026-10-31", "--scope", "weight", "--population", "promise_outcome",
"--promise", "p01", "--outcome", "forgotten", "--scopeBasis", "x"), 1);
assert.match(lines.at(-1), /outcome kept, refunded, withdrawn/);
+ // The words under its stamp (`stampNote`): a promise_outcome's, one line; null takes them off again.
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "by her account · no receipt"), 0, lines.join("\n"));
+ assert.equal((await manifestOf(dir)).ledger.find((r) => r.id === "o01").stampNote, "by her account · no receipt");
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "x".repeat(81)), 1);
+ assert.match(lines.at(-1), /stampNote is one line of 1–80 characters/);
+ assert.equal(await run(ledgerCommand, "weigh", "set", "p01", "--stampNote", "nope"), 1);
+ assert.match(lines.at(-1), /stampNote is a promise_outcome's/);
+ assert.equal(await run(ledgerCommand, "weigh", "set", "o01", "--stampNote", "null"), 0, lines.join("\n"));
+ assert.equal((await manifestOf(dir)).ledger.find((r) => r.id === "o01").stampNote ?? null, null);
assert.equal(await run(ledgerCommand, "weigh", "rm", "o01"), 0);
assert.equal(await run(ledgerCommand, "weigh", "rm", "s01"), 0);
// A loss told in the past: off the odometer; then put back on it.
diff --git a/umtool/lib/report/ledgerRows.mjs b/umtool/lib/report/ledgerRows.mjs
@@ -18,7 +18,7 @@
// subject) is a lower-case key; another speaker's row moves none of his
// numbers (measure-slice.mjs).
import {
- EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
+ EVENTS, LEDGER_BUILTIN_KEYS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, measureDisplay, measureGaps, measureSchema, validateFields,
} from "umtool-report-to-video/ledger-totals";
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -35,7 +35,7 @@ export const LEDGER_KEY_TYPES = Object.freeze({
display: "text?", label: "text?", quote: "text?", deadline: "text?", src: "text?", channel: "text?", video: "text?",
cite: "seconds?", citeFrom: "text?", scopeBasis: "text", scopeConfidence: "text", valueKind: "text", flags: "list",
hedged: "bool?", unsourced: "bool?", plotted: "bool?", hidden: "bool?", entryId: "text?", authorNote: "text?",
- run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?",
+ run: "run?", retro: "bool?", promise: "text?", kept: "bool?", due: "day?", speaker: "speaker?", paidOn: "day?", outcome: "text?", stampNote: "text?",
});
/** Is this manifest's ledger a measure ledger (the one these writers write)? */
@@ -143,6 +143,13 @@ export function ledgerRowOf(manifest, base, patch, { unset = [] } = {}) {
if (row.population === "promise_outcome") {
if (!PROMISE_OUTCOMES.includes(row.outcome)) errors.push(`a promise_outcome says how it ended: outcome ${PROMISE_OUTCOMES.join(", ")}`);
} else if (row.outcome !== undefined && row.outcome !== null) errors.push("outcome is a promise_outcome's");
+ // The words under the outcome's stamp on the promise clock (measure-extras.mjs STAMP_NOTE): one line of text.
+ if (row.stampNote !== undefined && row.stampNote !== null) {
+ if (row.population !== "promise_outcome") errors.push("stampNote is a promise_outcome's (the words under its stamp)");
+ else if (typeof row.stampNote !== "string" || !row.stampNote.trim() || /[\n\r]/.test(row.stampNote) || row.stampNote.trim().length > STAMP_NOTE.max) {
+ errors.push(`stampNote is one line of 1–${STAMP_NOTE.max} characters (the stamp's second line; past ${STAMP_NOTE.fit} the lint warns it may not fit)`);
+ }
+ }
if (["promise_check", "promise_claim", "promise_outcome"].includes(row.population)) {
const p = ledger.find((r) => r?.id === row.promise);
if (!row.promise) errors.push(`a ${row.population} names its promise (--promise <row id>)`);
diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs
@@ -28,7 +28,7 @@
// Plain ESM: the CLI runs it under bare node.
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
-import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues";
+import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom, transcriptsManifestUrl } from "umtool-report-to-video/cues";
import { qrsOf } from "umtool-report-to-video/lint";
import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
@@ -213,11 +213,13 @@ export async function checkLinks(
});
continue;
}
- const manifestUrl = ch.manifests?.transcripts;
- if (typeof manifestUrl !== "string" || !manifestUrl) {
+ if (typeof ch.manifests?.transcripts !== "string" || !ch.manifests.transcripts) {
out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` });
continue;
}
+ // The manifest the corpus names, when it is on the archive's own origin;
+ // one named elsewhere is not followed (report-to-video/archive-fetch.mjs).
+ const manifestUrl = transcriptsManifestUrl(a.origin, ch);
const man = await channelManifest(manifestUrl);
if (!man.doc) {
out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` });
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -328,8 +328,41 @@ function applyShelfNote(entry, value) {
else delete entry.shelfNote;
}
+/** The most characters an entry's `chapter` may have: one line of a chapter list (a YouTube title's own limit). */
+export const ENTRY_CHAPTER_MAX = 100;
+
+/**
+ * An entry's `chapter` as written: its name in the chapter list (build-video.mjs chapterTitle: an authored `chapter`
+ * wins over the on-screen title and the line derived from the record). One line, at most ENTRY_CHAPTER_MAX
+ * characters, trimmed; null, "" or blank is none.
+ * @param {unknown} v
+ * @returns {{ value: string | null, error: string | null }}
+ */
+export function parseEntryChapter(v) {
+ if (v === null || v === undefined || v === "" || v === false) return { value: null, error: null };
+ if (typeof v !== "string") return { value: null, error: `chapter is words, not ${JSON.stringify(v)}` };
+ const s = v.trim();
+ if (!s) return { value: null, error: null };
+ if (/[\r\n]/.test(s)) return { value: null, error: "chapter must be one line" };
+ if ([...s].length > ENTRY_CHAPTER_MAX) return { value: null, error: `chapter is ${[...s].length} characters (at most ${ENTRY_CHAPTER_MAX})` };
+ return { value: s, error: null };
+}
+
+/**
+ * Set an entry's `chapter` (parseEntryChapter); null or "" removes it -- the chapter list names the entry by its
+ * on-screen title or its record again.
+ * @param {Record<string, unknown>} entry
+ * @param {unknown} value
+ */
+function applyChapter(entry, value) {
+ const { value: text, error } = parseEntryChapter(value);
+ if (error) throw new Error(error);
+ if (text) entry.chapter = text;
+ else delete entry.chapter;
+}
+
/** The patch keys any timeline entry may carry (a post item, a still, a clip): applied before the clip-only rules. */
-const ANY_ENTRY_KEYS = Object.freeze(["hideModules", "shelfNote"]);
+const ANY_ENTRY_KEYS = Object.freeze(["hideModules", "shelfNote", "chapter"]);
/**
* updateClip's rules over a manifest held in memory: the ONE place a clip
@@ -358,8 +391,9 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
// So may its note on the shelf (`shelfNote`, deck.mjs entryShelfNotes).
if (patch !== RESTORE_PATCH && Object.keys(patch).length && Object.keys(patch).every((k) => ANY_ENTRY_KEYS.includes(k))) {
if (patch.hideModules !== undefined) applyHideModules(entry, patch.hideModules);
- if (patch.shelfNote !== undefined) applyShelfNote(entry, patch.shelfNote);
if (patch.shelfNote !== undefined) applyShelfNote(entry, patch.shelfNote);
+ // Its name in the chapter list (`chapter`, build-video.mjs chapterTitle).
+ if (patch.chapter !== undefined) applyChapter(entry, patch.chapter);
return { entry, before: { start: entry.start, end: entry.end } };
}
// `!== "clip"`, not `=== "card"`. The timeline's vocabulary is open -- one
@@ -781,6 +815,8 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n
}
if (patch.hideModules !== undefined) applyHideModules(entry, patch.hideModules);
+ // A clip's chapter name beside its other knobs in one patch.
+ if (patch.chapter !== undefined) applyChapter(entry, patch.chapter);
// The live-chat column beside this clip (chat.mjs): true shows it, false is
// the explicit no, null/"" removes the key (the default: off).
diff --git a/umtool/lib/report/postComboCli.mjs b/umtool/lib/report/postComboCli.mjs
@@ -16,7 +16,7 @@
// Plain ESM: the CLI runs it under bare node.
import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, comboKnobs, repeatGroups } from "umtool-report-to-video/post-combo";
import { captureOnlyMedia, projectCombos } from "umtool-report-to-video/post-combo-prints";
-import { channelsDirFor, readManifest } from "../projects/report.mjs";
+import { channelsDirFor, channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { copyFile, mkdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
@@ -45,6 +45,8 @@ export const REPEATS_USAGE = [
" umtool posts attach <project> [<item> … | --all] [--dry-run] [--json]",
" a post item with no attachment whose capture holds one (captured after it went in): its media copied in and",
" set, as posts reel would have made it -- nothing else of the entry changes. One write (one undo point).",
+ " The capture is looked for in the project's channels tree, then the archive's (read only: the files are",
+ " copied into the project); --dry-run prints the tree each file would come from.",
].join("\n");
const OFF = new Set(["off", "no", "false", "0"]);
@@ -95,7 +97,7 @@ export async function repeatsView(project, { match = null, cacheDir = undefined,
const opts = { channelsDir: corpus, ...(match ? { match } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) };
const cut = await projectCombos(project.dir, manifest, opts);
// The posts whose capture has a file their entry does not carry: in the cut's order, as if they played it.
- const captured = await captureOnlyMedia(manifest, { channelsDir: corpus });
+ const captured = await captureOnlyMedia(manifest, { channelsDirs: await captureTrees(project, manifest, channelsDir) });
const tl = (manifest.timeline ?? []).map((e) => (captured[e?.id] ? { ...e, media: captured[e.id].map((m) => ({ src: `@capture/${m.slug}/${m.name}`, kind: "capture" })) } : e));
const prints = (id, i) => (captured[id] ? { mediaId: captured[id][i]?.mediaId ?? null, sha256: captured[id][i]?.sha256 ?? null } : cut.prints[`${id}:${i}`]);
const all = repeatGroups(tl, prints, { match: cut.match });
@@ -148,8 +150,17 @@ export async function scenesView(project, { channelsDir = null } = {}) {
const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" };
const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" };
+/**
+ * Is this ONE path segment -- a capture's file name, a post id, a channel slug as a capture or a manifest gives them?
+ * Not empty, not `.` or `..`, no separator (either slash) and no NUL: a name is joined into a path in a channels tree
+ * and in the project, and `../../x` would read, and write, outside both.
+ */
+export const isPathSegment = (v) => typeof v === "string" && v !== "" && v !== "." && v !== ".." && !/[/\\\0]/.test(v);
+
/** Copy a capture's file into the project (never through a link out of it); the same size already there is left. */
async function copyIn(projectDir, from, rel) {
+ // Before anything is made: every segment a plain name (attachFromCaptures checks them too -- this is the writer's own).
+ if (!rel.split("/").every(isPathSegment)) throw new ComboError(`${JSON.stringify(rel)} is not a path inside the project — not copying`);
const to = path.join(projectDir, ...rel.split("/"));
const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]);
if (a && b && a.size === b.size) return;
@@ -160,20 +171,40 @@ async function copyIn(projectDir, from, rel) {
}
/**
+ * THE CHANNELS TREES A CAPTURE IS LOOKED FOR IN (12 Nov: a project with a `.shadow-channels` tree saw only that, and
+ * the captures in the real archive's `channels/<slug>/posts-media/<id>/` were invisible): the project's own tree
+ * first, then the archive behind it -- as the other readers resolve them (projects/report.mjs channelsLayersFor;
+ * `provenance.channelsFallback: false` or CHANNELS_FALLBACK=0 keeps it to the project's). READ ONLY toward both:
+ * attach copies into the project.
+ * @returns {Promise<string[]>}
+ */
+async function captureTrees(project, manifest, channelsDir = null, channelsDirs = null) {
+ if (Array.isArray(channelsDirs) && channelsDirs.length) return channelsDirs;
+ if (channelsDir) return [channelsDir];
+ return channelsLayersFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+}
+
+/** A tree in words: the first is the project's own, any after it the archive's. */
+const treeKindOf = (trees, tree) => (trees.indexOf(tree) <= 0 ? "project" : "archive");
+
+/**
* ATTACH WHAT THE CAPTURES HOLD (`umtool posts attach`): each post item with no
* attachment whose capture has one (captured after it went in) gets its media
* as `posts reel` would have made it -- the files copied into the project's
* posts-media/, measured -- and nothing else of the entry changes (its
* paraphrases, narration, knobs kept). One write. `ids` narrows it.
+ * A capture is looked for in the project's channels tree, then the archive's (captureTrees); each planned item
+ * says which it came from (`tree`, `treeKind`: project | archive), and `--dry-run` prints it per file.
*
* @param {{ id: string, dir: string }} project
- * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null }} [o]
+ * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null, channelsDirs?: string[] | null }} [o]
+ * `channelsDirs`: the trees to look in, in order (default: the project's, then the archive's)
*/
-export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null } = {}) {
+export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null, channelsDirs = null } = {}) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new ComboError(`${project.id} has no manifest`);
- const corpus = channelsDir ?? channelsDirFor(project.dir, manifest);
- const captured = await captureOnlyMedia(manifest, { channelsDir: corpus });
+ const trees = await captureTrees(project, manifest, channelsDir, channelsDirs);
+ const captured = await captureOnlyMedia(manifest, { channelsDirs: trees });
const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
const want = ids ? ids.map((r) => tl.find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r))?.id ?? r) : null;
if (want) for (const id of want) if (!tl.some((e) => e?.id === id && e.type === "post")) throw new ComboError(`no post item ${id} in ${project.id}`);
@@ -184,7 +215,11 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
const postId = String(tl.find((e) => e?.id === id)?.post ?? "").split("/")[1];
const media = [];
for (const m of list) {
- const from = path.join(corpus, m.slug, "posts-media", postId, m.name);
+ // A capture's names are data: refused before any file is looked at, in whichever tree it was found.
+ for (const [what, v] of [["file name", m.name], ["post id", postId], ["channel", m.slug]]) {
+ if (!isPathSegment(v)) throw new ComboError(`${id}: its capture's ${what} ${JSON.stringify(v ?? null)} is not a plain name (a path separator, "." or "..", or empty) — nothing attached`);
+ }
+ const from = path.join(m.tree, m.slug, "posts-media", postId, m.name);
if (!(await stat(from).catch(() => null))) continue;
const rel = `posts-media/${m.slug}/${postId}/${m.name}`;
const probe = await probeMediaFile(from);
@@ -202,7 +237,7 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
}
if (!media.length) continue;
patches[id] = media.map((x) => x.item);
- plan.push({ id, media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) });
+ plan.push({ id, tree: list[0].tree, treeKind: treeKindOf(trees, list[0].tree), media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) });
}
if (dryRun || !plan.length) return { dryRun, attached: plan, result: null, editNotes: null };
for (const p of plan) for (const m of p.media) await copyIn(project.dir, m.from, m.src);
@@ -210,6 +245,19 @@ export async function attachFromCaptures(project, { ids = null, dryRun = false,
return { dryRun, attached: plan.filter((p) => result.ids.includes(p.id)), result, editNotes };
}
+/** What `posts attach` prints: each item's media, and the channels tree each file is read from (a dry run: per file). */
+export function attachLines(r, projectId) {
+ const out = [`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${projectId}`];
+ for (const a of r.attached) {
+ const whose = a.treeKind === "archive" ? "the archive's" : "the project's";
+ out.push(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`);
+ if (r.dryRun) for (const m of a.media) out.push(` from ${whose} channels tree: ${m.from}`);
+ else out.push(` from ${whose} channels tree (${a.tree})`);
+ }
+ if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out.push(` undo point: ${r.result.snapshot.rel} (umtool timeline ${projectId} undo)`);
+ return out;
+}
+
/** The repeats view as lines. */
export function repeatsLines(v) {
const out = [];
@@ -262,9 +310,7 @@ async function comboRun(verb, words, flags, { root, json, out, err }) {
const r = await attachFromCaptures(project, { ids: items.length ? items : null, dryRun: flags.has("--dry-run") });
if (json) out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2));
else {
- out(`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${project.id}`);
- for (const a of r.attached) out(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`);
- if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`);
+ for (const l of attachLines(r, project.id)) out(l);
}
return 0;
}
diff --git a/umtool/lib/report/postComboCli.test.mjs b/umtool/lib/report/postComboCli.test.mjs
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { postsCommand } from "./postsCli.mjs";
-import { repeatsView } from "./postComboCli.mjs";
+import { attachFromCaptures, attachLines, isPathSegment, repeatsView } from "./postComboCli.mjs";
const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-combo-"));
after(() => rm(ROOT, { recursive: true, force: true }));
@@ -125,3 +125,96 @@ test("posts attach: the capture's media onto the item that carries none, nothing
assert.deepEqual(v.groups[0].members.map((m) => `${m.id}:${m.attached ? m.badge : "-"}`), ["p-1:1", "p-2:2", "p-3:3", "p-5:4"]);
assert.equal((await run(["attach", "att"])).code, 2, "names the items, or --all");
});
+
+test("posts attach reads every channels tree: the project's first, then the archive's -- read only; a dry run says which tree each file came from", async () => {
+ const { execFileSync } = await import("node:child_process");
+ const { readdir, stat } = await import("node:fs/promises");
+ const p = await project("trees");
+ // The project's own tree (a .shadow-channels) holds no capture of post 3; the ARCHIVE's does.
+ const shadow = path.join(p.dir, ".shadow-channels");
+ await mkdir(path.join(shadow, "obv-x"), { recursive: true });
+ const archive = path.join(ROOT, "archive-channels");
+ const capDir = path.join(archive, "obv-x", "posts-media", "3");
+ await mkdir(capDir, { recursive: true });
+ const gif = path.join(capDir, "3_1.mp4");
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", gif]);
+ await writeFile(path.join(capDir, "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", url: "https://video.twimg.com/tweet_video/C.mp4" }] }));
+ const listing = async () => (await readdir(archive, { recursive: true })).sort().join("\n");
+ const archiveBefore = await listing();
+ const mtimeBefore = (await stat(gif)).mtimeMs;
+
+ // Only the project's tree, as before: nothing to attach.
+ assert.deepEqual((await attachFromCaptures(p, { channelsDirs: [shadow], dryRun: true })).attached, []);
+ // Both: found in the archive, and said so.
+ const dry = await attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun: true });
+ assert.deepEqual(dry.attached.map((a) => [a.id, a.treeKind, a.tree]), [["p-3", "archive", archive]]);
+ assert.equal(dry.attached[0].media[0].from, gif);
+ const lines = attachLines(dry, "trees");
+ assert.match(lines[0], /would attach the capture's media to 1 post item\(s\) in trees/);
+ assert.ok(lines.includes(` from the archive's channels tree: ${gif}`), lines.join("\n"));
+ assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-3").media, undefined, "a dry run writes nothing");
+
+ // The project's own capture wins when both hold one.
+ const own = path.join(shadow, "obv-x", "posts-media", "3");
+ await mkdir(own, { recursive: true });
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", path.join(own, "3_9.mp4")]);
+ await writeFile(path.join(own, "capture.json"), JSON.stringify({ media: [{ name: "3_9.mp4", url: "https://video.twimg.com/tweet_video/D.mp4" }] }));
+ const both = await attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun: true });
+ assert.deepEqual(both.attached.map((a) => [a.treeKind, a.media[0].src]), [["project", "posts-media/obv-x/3/3_9.mp4"]]);
+ assert.ok(attachLines(both, "trees").some((l) => l.startsWith(" from the project's channels tree: ")));
+ await rm(own, { recursive: true, force: true });
+
+ // The write: copied INTO the project; the archive is exactly as it was.
+ const done = await attachFromCaptures(p, { channelsDirs: [shadow, archive] });
+ assert.deepEqual(done.attached.map((a) => a.id), ["p-3"]);
+ assert.ok(attachLines(done, "trees").includes(` from the archive's channels tree (${archive})`));
+ const e = (await manifest(p)).timeline.find((x) => x.id === "p-3");
+ assert.equal(e.media[0].src, "posts-media/obv-x/3/3_1.mp4");
+ const copied = await stat(path.join(p.dir, "posts-media", "obv-x", "3", "3_1.mp4"));
+ assert.ok(copied.isFile() && !copied.isSymbolicLink());
+ assert.equal(await listing(), archiveBefore, "nothing added to the archive");
+ assert.equal((await stat(gif)).mtimeMs, mtimeBefore, "its file untouched");
+});
+
+test("posts attach refuses a capture whose file name is not a plain name, before any file is touched -- in either tree", async () => {
+ const { readdir } = await import("node:fs/promises");
+ for (const bad of ["../../x", "a/b", "..", ".", "a\\b"]) assert.equal(isPathSegment(bad), false, bad);
+ assert.equal(isPathSegment(""), false);
+ assert.equal(isPathSegment("3_1.mp4"), true);
+ let n = 0;
+ for (const bad of ["../../x", "a/b", ".."]) {
+ for (const where of ["project", "archive"]) {
+ n += 1;
+ const p = await project(`bad${n}`);
+ const shadow = path.join(p.dir, ".shadow-channels");
+ const archive = path.join(ROOT, `bad-archive-${n}`);
+ const tree = where === "project" ? shadow : archive;
+ const capDir = path.join(tree, "obv-x", "posts-media", "3");
+ await mkdir(capDir, { recursive: true });
+ await mkdir(shadow, { recursive: true });
+ await mkdir(archive, { recursive: true });
+ // A file where the name points, so only the check stands between it and a read.
+ await writeFile(path.join(tree, "x"), "OUTSIDE");
+ await writeFile(path.join(capDir, "capture.json"), JSON.stringify({ media: [{ name: bad, url: "https://video.twimg.com/tweet_video/C.mp4" }] }));
+ const before = (await readdir(p.dir, { recursive: true })).sort().join("\n");
+ const manifestBefore = await readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+ for (const dryRun of [true, false]) {
+ await assert.rejects(attachFromCaptures(p, { channelsDirs: [shadow, archive], dryRun }), (e) => {
+ assert.match(e.message, /p-3: its capture's file name .* is not a plain name/, `${bad} in the ${where}'s tree`);
+ return true;
+ });
+ }
+ assert.equal((await readdir(p.dir, { recursive: true })).sort().join("\n"), before, "no directory made in the project");
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), manifestBefore);
+ // The CLI says it and exits 2.
+ if (where === "project") {
+ const m = JSON.parse(manifestBefore);
+ m.provenance.channelsDir = shadow;
+ await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m, null, 2));
+ const r = await run(["attach", `bad${n}`, "--all", "--dry-run"]);
+ assert.equal(r.code, 2, r.out + r.err);
+ assert.match(r.err, /is not a plain name/);
+ }
+ }
+ }
+});
diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs
@@ -23,7 +23,8 @@
// --quote-ruled`: heard and ruled by a person).
//
// Plain ESM: the CLI runs under bare node; the app reads the file.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { mkdir, readFile, realpath, rename, rmdir, writeFile } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
import { createCueSource, siteOriginFromManifest } from "umtool-report-to-video/cues";
import { cueWords, findQuote, ON_TIME_S, quoteOffset } from "umtool-report-to-video/quote-in-audio";
@@ -234,16 +235,90 @@ async function editorWords(req, { emit }) {
}
/**
+ * WHERE THE EDITOR WRITES THE WORDS (12 Nov): the work files were `<project>/out/quote-check/<clip>.words.json`, and
+ * a project's `out/` may be a symlink onto the media drive -- inside a corpus location, where the editor rightly
+ * refuses to write (transcribeFile.ts: `"out" … is inside the corpus`). So the work dir is never under `out/`:
+ * these, in order, each by its REAL path (a link in the way is followed here, not found out by the editor), the
+ * next one taken when the editor refuses the one before as inside the corpus --
+ *
+ * <project>/.quote-check/ beside the manifest
+ * <reports>/.umtool/quote-check/<project>/ umtool's own state, when the project dir itself is in a location
+ * $XDG_CACHE_HOME|~/.cache/umtool/quote-check/<project>/
+ *
+ * The rows are the project's whichever it is: quote-check.json, beside the manifest.
+ * @param {string} dir the project's dir
+ * @param {{ reportsRoot?: string | null, env?: Record<string, string | undefined>, home?: string }} [opts]
+ * @returns {Promise<string[]>}
+ */
+export async function quoteCheckWorkDirs(dir, { reportsRoot = null, env = process.env, home = os.homedir() } = {}) {
+ const real = async (p) => {
+ // The deepest ancestor that exists, resolved; the rest as named (the dir may not be made yet).
+ const rest = [];
+ let cur = path.resolve(p);
+ for (;;) {
+ const r = await realpath(cur).catch(() => null);
+ if (r) return path.join(r, ...rest);
+ const up = path.dirname(cur);
+ if (up === cur) return path.resolve(p);
+ rest.unshift(path.basename(cur));
+ cur = up;
+ }
+ };
+ const name = path.basename(path.resolve(dir));
+ const cache = env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(home, ".cache");
+ const all = [
+ path.join(dir, ".quote-check"),
+ path.join(reportsRoot ?? path.dirname(path.resolve(dir)), ".umtool", "quote-check", name),
+ path.join(cache, "umtool", "quote-check", name),
+ ];
+ const out = [];
+ for (const p of all) {
+ const r = await real(p);
+ if (!out.includes(r)) out.push(r);
+ }
+ return out;
+}
+
+/**
+ * Is this the editor's refusal of an `out` inside the corpus? The controller's sentence is
+ * `"out" <path> is inside the corpus (<root>) — this command never writes there; pick a path outside it`
+ * (common/controller/transcribeFile.ts checkTranscribeFileRequest), answered at once as HTTP 400 `{ error }` by
+ * POST /api/ops/transcribe (the route's jobResponse), which askEditorOp throws as `the editor refused it (<route>,
+ * HTTP 400): <error>`. Matched on the part that says what it is -- `"out" … is inside the corpus` -- not on the path,
+ * the root or the advice after the dash (quoteCheck.test.mjs holds the controller's source to these words).
+ */
+export const OUT_INSIDE_CORPUS = /"out" .* is inside the corpus\b/;
+const insideCorpus = (e) => OUT_INSIDE_CORPUS.test(e instanceof Error ? e.message : String(e));
+
+/**
+ * Take back the directories a refused work dir cost: `dir` and every parent made for it, up to `first` (what
+ * mkdir's `recursive` says it made first) -- each only when empty (rmdir), so nothing that was there is touched
+ * and no empty `.quote-check/` is left inside a corpus location.
+ */
+async function unmake(dir, first) {
+ if (!first) return;
+ const stop = path.resolve(first);
+ let cur = path.resolve(dir);
+ for (;;) {
+ if (cur !== stop && !cur.startsWith(stop + path.sep)) return;
+ if (!(await rmdir(cur).then(() => true, () => false))) return;
+ if (cur === stop) return;
+ cur = path.dirname(cur);
+ }
+}
+
+/**
* Check the planned clips; merge the rows into quote-check.json.
* @param {string} dir
* @param {Record<string, any>} manifest
* @param {Awaited<ReturnType<typeof planQuoteCheck>>} plan
* @param {{ transcribe?: typeof editorWords, cuesOf?: (slug: string, video: string) => Promise<any[] | null>, log?: (l: string) => void, now?: () => Date }} [opts]
*/
-export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date() } = {}) {
+export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWords, cuesOf = null, log = () => {}, now = () => new Date(), workDirs = null, reportsRoot = null } = {}) {
const doc = await readQuoteCheck(dir);
- const work = path.join(dir, "out", "quote-check");
- await mkdir(work, { recursive: true });
+ // Never under out/ (quoteCheckWorkDirs): the first the editor does not refuse as inside the corpus.
+ const works = workDirs ?? (await quoteCheckWorkDirs(dir, { reportsRoot }));
+ let wi = 0;
const cueSource = cuesOf
? null
: createCueSource({ channelsDirs: channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }), siteOrigin: siteOriginFromManifest(manifest) });
@@ -271,10 +346,24 @@ export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWo
log(rowLine(p.id, results[p.id]));
continue;
}
- const out = path.join(work, `${p.id}.words.json`);
let words;
try {
- words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} });
+ for (;;) {
+ // The editor needs the directory to be there (it refuses an `out` whose directory is not), so it is made
+ // -- and taken back, with any parent made for it, the moment the editor says it is inside the corpus.
+ const made = await mkdir(works[wi], { recursive: true });
+ const out = path.join(works[wi], `${p.id}.words.json`);
+ try {
+ words = await transcribe({ path: p.source.path, start: p.file.start, end: p.file.end, out }, { emit: () => {} });
+ break;
+ } catch (e) {
+ if (!insideCorpus(e)) throw e;
+ await unmake(works[wi], made);
+ if (wi + 1 >= works.length) throw e;
+ log(`quote-check: the editor will not write in ${works[wi]} (inside the corpus) -- its work files go to ${works[wi + 1]}`);
+ wi += 1;
+ }
+ }
} catch (e) {
log(`${p.id}: the transcription failed: ${e instanceof Error ? e.message : String(e)}`);
continue;
@@ -287,7 +376,7 @@ export async function runQuoteCheck(dir, manifest, plan, { transcribe = editorWo
}
const merged = { version: 1, checkedAt: now().toISOString(), clips: { ...doc.clips, ...results } };
const file = await writeQuoteCheck(dir, merged);
- return { file, doc: merged, results };
+ return { file, doc: merged, results, work: works[wi] };
}
// ---------------------------------------------------------------------------
@@ -301,6 +390,9 @@ export const QUOTE_CHECK_USAGE = [
`Each clip's cut ±${SEARCH_PAD_S} s (--pad) of the source the render would cut it from is transcribed by the`,
"editor (its transcription lane, words on), and the quote is found in those words and in the recording's",
`cues: ok (within ${ON_TIME_S} s), moved (heard elsewhere: umtool window <p> <clip> --align), not-found.`,
+ "The editor's work files (<clip>.words.json) go to <project>/.quote-check/ -- never under out/, which may be a link",
+ "onto a media drive the editor will not write in; were the project itself inside the corpus, to umtool's own",
+ "<reports>/.umtool/quote-check/<project>/, then ~/.cache/umtool/quote-check/<project>/.",
`Rows go to <project>/${QUOTE_CHECK_FILE}; umtool check reads them, and a take refuses a moved or`,
"missing quote unless the clip is ruled (umtool window <p> <clip> --quote-ruled).",
].join("\n");
@@ -351,12 +443,13 @@ export async function quoteCheckCommand(args, { reportsRoot = REPORTS_ROOT, log
if (!channelsDirs.length) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from");
const plan = await planQuoteCheck(project.dir, manifest, { channelsDirs, clipIds, pad });
if (clipIds.length && !plan.length) throw new CliError(`none of ${clipIds.join(", ")} is a clip of ${project.id}`);
- const { file, results } = await runQuoteCheck(project.dir, manifest, plan, {
+ const { file, results, work } = await runQuoteCheck(project.dir, manifest, plan, {
...(transcribe ? { transcribe } : {}),
...(cuesOf ? { cuesOf } : {}),
+ reportsRoot,
log: json ? () => {} : log,
});
- if (json) log(JSON.stringify({ project: project.id, file, clips: results }, null, 1));
+ if (json) log(JSON.stringify({ project: project.id, file, work, clips: results }, null, 1));
else {
const count = (s) => Object.values(results).filter((x) => x.status === s).length;
log(`→ ${file}: ${count("ok")} ok, ${count("moved")} moved, ${count("not-found")} not found, ${count("no-window")} with no window`);
diff --git a/umtool/lib/report/quoteCheck.test.mjs b/umtool/lib/report/quoteCheck.test.mjs
@@ -185,3 +185,135 @@ test("prep --status says the quote check's verdicts on the clips as they are now
await rm(p.root, { recursive: true, force: true });
}
});
+
+test("the editor's work files are never under out/: <project>/.quote-check by its real path, and the next dir when the editor refuses one as inside the corpus", async () => {
+ const { quoteCheckWorkDirs } = await import("./quoteCheck.mjs");
+ const { realpath, symlink, stat } = await import("node:fs/promises");
+ const p = await project();
+ try {
+ const root = await realpath(p.root);
+ // out/ linked onto "the media drive" (rev9-a9's project): nothing of the check is written through it.
+ const drive = path.join(root, "drive", "diet-out");
+ await mkdir(path.dirname(drive), { recursive: true });
+ const { rename } = await import("node:fs/promises");
+ await rename(path.join(p.dir, "out"), drive);
+ await symlink(drive, path.join(p.dir, "out"));
+ const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(root, "cache") } });
+ assert.deepEqual(dirs, [
+ path.join(root, "diet", ".quote-check"),
+ path.join(root, ".umtool", "quote-check", "diet"),
+ path.join(root, "cache", "umtool", "quote-check", "diet"),
+ ]);
+ const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] });
+ const outs = [];
+ const seen = async (req) => { outs.push(req.out); return fakeTranscribe(req); };
+ const first = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: seen, cuesOf: fakeCues, workDirs: dirs });
+ assert.equal(first.work, dirs[0]);
+ assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[0]), outs.join("\n"));
+ assert.equal(await stat(path.join(drive, "quote-check")).catch(() => null), null, "nothing under out/");
+ assert.equal(first.doc.clips.c44.status, "ok");
+
+ // The project dir itself inside a location: the editor refuses the first dir, the check moves on and still lands its rows.
+ const lines = [];
+ const refused = [];
+ const picky = async (req) => {
+ if (path.dirname(req.out) === dirs[0]) {
+ refused.push(req.out);
+ throw new Error(`the editor refused it (/api/ops/transcribe, HTTP 400): "out" ${req.out} is inside the corpus (/mnt/media) — this command never writes there; pick a path outside it`);
+ }
+ outs.push(req.out);
+ return fakeTranscribe(req);
+ };
+ outs.length = 0;
+ const second = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: picky, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(refused.length, 1, "asked once, not once per clip");
+ assert.equal(second.work, dirs[1]);
+ assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[1]));
+ assert.match(lines.join("\n"), /the editor will not write in .*\.quote-check \(inside the corpus\) -- its work files go to .*\.umtool\/quote-check\/diet/);
+ assert.equal(second.doc.clips.c43.status, "moved");
+ assert.deepEqual(await readQuoteCheck(p.dir), second.doc);
+ // Any other failure is that clip's, as before -- no hopping dirs.
+ const broken = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: async () => { throw new Error("no engine"); }, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(broken.work, dirs[0]);
+ assert.match(lines.join("\n"), /c43: the transcription failed: no engine/);
+ } finally {
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
+
+test("through the real editor client: the editor's own refusal reaches the fall-through, and the refused work dir is taken back -- no empty .quote-check left in the corpus", async () => {
+ const http = await import("node:http");
+ const { stat, readdir } = await import("node:fs/promises");
+ const { OUT_INSIDE_CORPUS, quoteCheckWorkDirs } = await import("./quoteCheck.mjs");
+ // The controller's sentence, as the editor's source has it: the words the fall-through matches are there.
+ const controller = await readFile(path.join(HERE, "..", "..", "..", "common", "controller", "transcribeFile.ts"), "utf8");
+ const sentence = /error: `("out" \$\{req\.out\} is inside the corpus \(\$\{root\}\)[^`]*)`/.exec(controller);
+ assert.ok(sentence, "transcribeFile.ts still refuses an out inside the corpus in these words");
+ const refusalFor = (out, root) => sentence[1].replace("${req.out}", out).replace("${root}", root);
+ assert.match(refusalFor("/mnt/media/x/.quote-check/c43.words.json", "/mnt/media"), OUT_INSIDE_CORPUS);
+ assert.doesNotMatch('"out": the directory /x does not exist', OUT_INSIDE_CORPUS);
+ assert.doesNotMatch("editor job abc failed — out of memory inside the corpus reader", OUT_INSIDE_CORPUS);
+
+ const p = await project();
+ const corpus = p.dir; // the project itself sits in a "location": its .quote-check is refused
+ const asked = [];
+ // The editor, stood in for over HTTP: /api/ops/transcribe answers as ops' jobResponse does (400 { ok: false, error }
+ // for a refusal, { ok: true, jobId } and the words written to `out` otherwise), /api/ops/job/<id> a finished job.
+ const server = http.createServer((req, res) => {
+ let text = "";
+ req.on("data", (d) => (text += d));
+ req.on("end", async () => {
+ const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
+ if (req.method === "POST" && req.url === "/api/ops/transcribe") {
+ const body = JSON.parse(text);
+ asked.push(body.out);
+ if (body.out.startsWith(corpus + path.sep)) return send(400, { ok: false, error: refusalFor(body.out, corpus) });
+ if (!(await stat(path.dirname(body.out)).catch(() => null))) return send(400, { ok: false, error: `"out": the directory ${path.dirname(body.out)} does not exist` });
+ const words = await fakeTranscribe(body);
+ await writeFile(body.out, JSON.stringify({ words }));
+ return send(200, { ok: true, jobId: `j${asked.length}` });
+ }
+ if (req.method === "GET" && req.url.startsWith("/api/ops/job/")) return send(200, { ok: true, job: { status: "done" }, tail: [] });
+ return send(404, { ok: false, error: "no such route" });
+ });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const env = { url: process.env.ARCHILYZER_EDITOR_URL, token: process.env.WORKER_TOKEN };
+ process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${server.address().port}`;
+ process.env.WORKER_TOKEN = "test-token";
+ try {
+ const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(p.root, "cache") } });
+ const plan = (await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] })).filter((r) => r.id !== "c43");
+ const lines = [];
+ // No `transcribe` given: runQuoteCheck's own editorWords, askEditorOp and all.
+ const r = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) });
+ assert.equal(asked[0], path.join(dirs[0], "c44.words.json"), "the project's .quote-check is asked first");
+ assert.equal(asked[1], path.join(dirs[1], "c44.words.json"));
+ assert.equal(r.work, dirs[1]);
+ assert.equal(r.doc.clips.c44.status, "ok", lines.join("\n"));
+ assert.match(lines.join("\n"), /the editor will not write in .* \(inside the corpus\)/);
+ assert.equal(await stat(dirs[0]).catch(() => null), null, "the refused .quote-check is not left behind");
+ assert.ok((await readdir(dirs[1])).includes("c44.words.json"));
+
+ // Every dir refused: each one made is taken back, with the parents made for it; the clip's failure says why.
+ await rm(dirs[1], { recursive: true, force: true });
+ await rm(path.join(p.root, ".umtool"), { recursive: true, force: true });
+ const inCorpus = [dirs[0], path.join(p.dir, "deep", "er", "work")];
+ lines.length = 0;
+ const none = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: inCorpus, log: (l) => lines.push(l) });
+ assert.match(lines.join("\n"), /c44: the transcription failed: the editor refused it \(\/api\/ops\/transcribe, HTTP 400\): "out" .* is inside the corpus/);
+ assert.equal(await stat(dirs[0]).catch(() => null), null);
+ assert.equal(await stat(path.join(p.dir, "deep")).catch(() => null), null, "the parents made for it too");
+ assert.equal(none.results.c44, undefined);
+ // A work dir that was already there, with a file in it, is never removed.
+ await mkdir(dirs[0], { recursive: true });
+ await writeFile(path.join(dirs[0], "kept.txt"), "x");
+ await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: [dirs[0]], log: () => {} });
+ assert.ok((await readdir(dirs[0])).includes("kept.txt"));
+ } finally {
+ if (env.url === undefined) delete process.env.ARCHILYZER_EDITOR_URL; else process.env.ARCHILYZER_EDITOR_URL = env.url;
+ if (env.token === undefined) delete process.env.WORKER_TOKEN; else process.env.WORKER_TOKEN = env.token;
+ await new Promise((r) => server.close(r));
+ await rm(p.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -366,6 +366,9 @@ export function withPatchEntries(takeTimeline, baseTimeline, ids) {
* CLIPPED to the steps inside it -- the window keeps a straddling clip
* (windowEntries), so it keeps the part of the claim that clip carries;
* a goalpost with no step inside is dropped.
+ * - an effect's clip list (`render.chrome.fx`): `kineticQuote.clips`, `redact.clips` and `glitch.clips` keep the
+ * clips inside (a glitch's only with a clip right before it: it tears at that cut), `thenNow.pairs` the pairs
+ * with both ends inside; an effect left with none is off in the window.
*
* The kept ones need no re-timing: each names a clip by id, and its `t` is a
* source second of that clip, which the window renders whole.
@@ -391,6 +394,35 @@ export function windowManifest(manifest, ids) {
});
}
}
+ // The effects that name clips (fx.mjs validateFxEntries refuses a name the cut does not hold -- rev9-a9, 12 Nov:
+ // `take --preview --at … --dur …` was refused with "render.chrome.fx.glitch.clips names k06, which is not a clip
+ // of the cut"). A list keeps the clips inside; an effect left naming none is off in the window (an empty list is
+ // not one fx.mjs takes). The glitch tears at the cut INTO a clip, so a named clip stays only with a clip right
+ // before it in the window; a then/now pair needs both its ends.
+ const fx = m.render?.chrome?.fx;
+ if (isObj(fx)) {
+ const at = new Map(m.timeline.map((e, i) => [e?.id, i]));
+ const isClip = (id) => typeof id === "string" && m.timeline[at.get(id)]?.type === "clip";
+ for (const k of ["kineticQuote", "redact"]) {
+ if (!isObj(fx[k]) || !Array.isArray(fx[k].clips)) continue;
+ const clips = fx[k].clips.filter(isClip);
+ if (clips.length) fx[k].clips = clips;
+ else delete fx[k];
+ }
+ // Only a glitch on "clips" reads its list (fx.mjs); in another mode the list is not looked at, so it is left
+ // alone -- and the glitch with it.
+ if (isObj(fx.glitch) && fx.glitch.on === "clips" && Array.isArray(fx.glitch.clips)) {
+ const clips = fx.glitch.clips.filter((id) => isClip(id) && m.timeline[at.get(id) - 1]?.type === "clip");
+ if (clips.length) fx.glitch.clips = clips;
+ else delete fx.glitch;
+ }
+ if (isObj(fx.thenNow) && Array.isArray(fx.thenNow.pairs)) {
+ const pairs = fx.thenNow.pairs.filter((p) => !isObj(p) || (isClip(p.then) && isClip(p.now)));
+ if (pairs.length) fx.thenNow.pairs = pairs;
+ else delete fx.thenNow;
+ }
+ if (!Object.keys(fx).length) delete m.render.chrome.fx;
+ }
return m;
}
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -32,6 +32,7 @@ import {
} from "./takeMaker.mjs";
import { listTakes, readVerdicts, setTakeVerdict } from "./takes.mjs";
import { validateDeckClaims, validateDeckMarkers } from "umtool-report-to-video/deck";
+import { validateFxEntries } from "umtool-report-to-video/fx";
import { PROJECT_KINDS } from "../projects/kinds.mjs";
// The kind takes are made of, from the registry (never its id spelled here).
@@ -562,6 +563,54 @@ test("windowManifest: markers and claim checks outside the window are dropped; a
assert.equal(all.render.chrome.deck.claims[2].steps.length, 2);
});
+test("windowManifest: an effect's clip list keeps the window's clips -- a glitch's with a clip before it, a then/now pair with both ends -- and an effect left with none is off", () => {
+ const clipIds = ["k01", "k02", "k03", "k04", "k05", "k06"];
+ const manifest = {
+ ...MANIFEST,
+ timeline: clipIds.map((id, i) => clip(id, 10 * i, 10 * i + 5)),
+ render: {
+ ...MANIFEST.render,
+ chrome: {
+ engine: "hyperframes", layout: "deck", deck: {},
+ fx: {
+ glitch: { on: "clips", clips: ["k02", "k03", "k06"] },
+ thenNow: { pairs: [{ then: "k02", now: "k03" }, { then: "k05", now: "k06" }] },
+ kineticQuote: { clips: ["k01", "k03"] },
+ redact: { clips: ["k06"] },
+ wipe: {},
+ },
+ },
+ },
+ };
+ const before = JSON.stringify(manifest);
+ // The whole manifest windowed as-was is what the build refused (rev9-a9: "names k06, which is not a clip of the cut").
+ const naive = { ...manifest, timeline: manifest.timeline.filter((e) => ["k02", "k03", "k04"].includes(e.id)) };
+ assert.match(validateFxEntries(naive, { schedule: null }).join("\n"), /render\.chrome\.fx\.glitch\.clips names k06, which is not a clip of the cut/);
+ const m = windowManifest(manifest, ["k02", "k03", "k04"]);
+ const fx = m.render.chrome.fx;
+ // k02 opens the window: no clip before it, no cut to tear at.
+ assert.deepEqual(fx.glitch, { on: "clips", clips: ["k03"] });
+ assert.deepEqual(fx.thenNow.pairs, [{ then: "k02", now: "k03" }]);
+ assert.deepEqual(fx.kineticQuote.clips, ["k03"]);
+ assert.equal("redact" in fx, false, "it named only a clip outside: off in the window");
+ assert.deepEqual(fx.wipe, {}, "an effect that names no clip is as it was");
+ assert.deepEqual(validateFxEntries(m, { schedule: null }), []);
+ assert.equal(JSON.stringify(manifest), before, "the project's manifest is not touched");
+ // A window with none of them: the effects are off, the rest of the chrome as it was.
+ const none = windowManifest(manifest, ["k04"]);
+ assert.deepEqual(none.render.chrome.fx, { wipe: {} });
+ assert.deepEqual(validateFxEntries(none, { schedule: null }), []);
+ // The full window keeps every one.
+ assert.deepEqual(windowManifest(manifest, clipIds).render.chrome.fx, manifest.render.chrome.fx);
+ // A glitch in another mode never reads its list (fx.mjs): the window leaves it, and the glitch, as they were.
+ const byYear = { ...manifest, render: { ...manifest.render, chrome: { ...manifest.render.chrome, fx: { glitch: { on: "year", clips: ["k06"] } } } } };
+ assert.deepEqual(windowManifest(byYear, ["k02", "k03", "k04"]).render.chrome.fx, { glitch: { on: "year", clips: ["k06"] } });
+ const noMode = { ...manifest, render: { ...manifest.render, chrome: { ...manifest.render.chrome, fx: { glitch: { clips: ["k06"] } } } } };
+ assert.deepEqual(windowManifest(noMode, ["k02", "k03", "k04"]).render.chrome.fx, { glitch: { clips: ["k06"] } });
+ // A pair cut by the window's edge is dropped, the other kept.
+ assert.deepEqual(windowManifest(manifest, ["k03", "k04", "k05", "k06"]).render.chrome.fx.thenNow.pairs, [{ then: "k05", now: "k06" }]);
+});
+
test("withPatchEntries: a clip only the take's patch adds stays in the window beside the covered clip before it", () => {
const base = [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "d" }];
// The patch adds x after b (covered), y after x, z after d (not covered).
diff --git a/umtool/lib/research/sources.test.ts b/umtool/lib/research/sources.test.ts
@@ -0,0 +1,89 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// The source picker (demo epic D1): connected archives are offered through
+// the one resolver; with no local build, the first archive is the default.
+const root = await mkdtemp(path.join(os.tmpdir(), "umtool-sources-"));
+const local = path.join(root, "public");
+const settingsFile = path.join(root, "settings.json");
+await mkdir(path.join(root, "sites", "mysite"), { recursive: true });
+await writeFile(path.join(root, "sites", "mysite", "site.json"), JSON.stringify({ siteUrl: "https://stub.test/", siteTitle: "From site.json" }));
+await writeFile(settingsFile, JSON.stringify({ remoteArchives: [{ id: "stub", origin: "https://stub.test", title: "Stubalyzer", addedAt: "2026-11-11T00:00:00Z" }] }));
+process.env.SITES_DIR = path.join(root, "sites");
+process.env.SETTINGS_FILE = settingsFile;
+process.env.TRANSCRIPT_LOCAL_DIR = local;
+process.env.TRANSCRIPT_HUB_URL = "";
+process.env.TRANSCRIPT_SITE_URL = "https://env.test";
+const { listSources, buildIdentity } = await import("./sources");
+
+test.after(() => rm(root, { recursive: true, force: true }));
+
+test("no local build: the connected archives come first, site.json's duplicate is dropped, the env's is offered", async () => {
+ const s = await listSources();
+ assert.deepEqual(
+ s.map((x) => [x.handle, x.label]),
+ [
+ ["remote:https://stub.test", "Stubalyzer"],
+ ["remote:https://env.test", "env.test"],
+ [`local:${local}`, "Local corpus"],
+ ],
+ );
+ assert.equal(s[2].detail, "this machine · no build");
+});
+
+test("with a local build the local corpus is the default, the archives after it", async () => {
+ await mkdir(local, { recursive: true });
+ await writeFile(path.join(local, "corpus.json"), JSON.stringify({ site: { title: "Mine" } }));
+ const s = await listSources();
+ assert.equal(s[0].handle, `local:${local}`);
+ assert.deepEqual(s.slice(1).map((x) => x.handle), ["remote:https://stub.test", "remote:https://env.test"]);
+});
+
+// demo epic D1 re-review, item 4: a source's build is read from its own origin, bounded.
+test("a remote source's build identity: corpus.json on its own origin; a redirect elsewhere or an oversize answer is no identity", async () => {
+ const option = { handle: "remote:https://stub.test", kind: "remote", label: "Stub" } as never;
+ const asked: { url: string; redirect?: string }[] = [];
+ const fake = (answers: Record<string, () => Response>) =>
+ (async (url: string, init?: { redirect?: string }) => {
+ asked.push({ url, redirect: init?.redirect });
+ return (answers[url] ?? (() => new Response("nope", { status: 404 })))();
+ }) as never;
+
+ assert.equal(await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "2026-11-01T00:00:00Z" })) })), "2026-11-01T00:00:00Z");
+ assert.deepEqual(asked, [{ url: "https://stub.test/corpus.json", redirect: "manual" }]);
+
+ // A same-origin redirect is followed.
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 301, headers: { location: "/v2/corpus.json" } }),
+ "https://stub.test/v2/corpus.json": () => new Response(JSON.stringify({ generatedAt: "g2" })),
+ }),
+ ),
+ "g2",
+ );
+
+ // One that leaves the origin is not: nothing is asked of the other host.
+ asked.length = 0;
+ assert.equal(
+ await buildIdentity(
+ option,
+ fake({
+ "https://stub.test/corpus.json": () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1:3001/api/ops/settings" } }),
+ "http://127.0.0.1:3001/api/ops/settings": () => new Response(JSON.stringify({ generatedAt: "leaked" })),
+ }),
+ ),
+ null,
+ );
+ assert.deepEqual(asked.map((a) => a.url), ["https://stub.test/corpus.json"]);
+
+ // An answer declaring more than the document bound is not read.
+ assert.equal(
+ await buildIdentity(option, fake({ "https://stub.test/corpus.json": () => new Response(JSON.stringify({ generatedAt: "big" }), { headers: { "content-length": String(64 * 1024 * 1024) } }) })),
+ null,
+ );
+});
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -1,6 +1,8 @@
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
+import { connectedArchives } from "yt-dlp-transcript-common/lib/remoteArchives";
+import { fetchOnOrigin, readBounded, type FetchLike } from "yt-dlp-transcript-common/lib/remoteArchives-server";
import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
import { readCensus } from "./census.mjs";
import type { SourceOption } from "./types";
@@ -12,8 +14,11 @@ import type { SourceOption } from "./types";
// local the composed public dir on this machine, resolved as the MCP
// server's default resolves it: TRANSCRIPT_LOCAL_DIR, else
// EXPORT_PUBLIC_DIR, else <repo>/export/public
-// remote a published site: every transcripts/sites/*/site.json with a
-// `siteUrl` (a private site has none, and is not offered)
+// remote a published archive: every CONNECTED archive (settings.json
+// `remoteArchives`, plus TRANSCRIPT_SITE_URL's — the one resolver,
+// yt-dlp-transcript-common/lib/remoteArchives.ts), then every
+// transcripts/sites/*/site.json with a `siteUrl` not already
+// listed (a private site has none, and is not offered)
// hub TRANSCRIPT_HUB_URL, else settings.json `homepageUrl`
//
// Only an OFFERED handle opens: a request naming any other directory or origin
@@ -50,7 +55,7 @@ async function readJson<T>(file: string): Promise<T | null> {
}
}
-/** Every corpus the ask bar may read, the local one first. */
+/** Every corpus the ask bar may read, the default first: the local one, unless it has no build and an archive is offered. */
export async function listSources(): Promise<SourceOption[]> {
const dir = localDir();
const corpus = await readJson<{ site?: { title?: string } }>(path.join(/* turbopackIgnore: true */ dir, "corpus.json"));
@@ -62,13 +67,24 @@ export async function listSources(): Promise<SourceOption[]> {
detail: corpus?.site?.title ? `this machine · ${corpus.site.title} build` : "this machine",
},
];
- const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
+ const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+ const settings = await readJson<{ homepageUrl?: unknown; remoteArchives?: unknown }>(settingsFile);
const sites: SourceOption[] = [];
+ for (const a of connectedArchives(settings?.remoteArchives)) {
+ sites.push({
+ handle: `remote:${a.origin}`,
+ kind: "remote",
+ label: a.title,
+ detail: `connected · ${a.origin.replace(/^https?:\/\//, "")}`,
+ });
+ }
+ const ids = await readdir(/* turbopackIgnore: true */ SITES_DIR).catch(() => [] as string[]);
for (const id of ids.sort()) {
if (id.startsWith("_") || id.startsWith(".")) continue;
const site = await readJson<{ siteUrl?: unknown; siteTitle?: unknown }>(path.join(/* turbopackIgnore: true */ SITES_DIR, id, "site.json"));
const url = typeof site?.siteUrl === "string" ? site.siteUrl.trim().replace(/\/+$/, "") : "";
if (!/^https?:\/\//.test(url)) continue;
+ if (sites.some((x) => x.handle === `remote:${url}`)) continue;
sites.push({
handle: `remote:${url}`,
kind: "remote",
@@ -76,9 +92,15 @@ export async function listSources(): Promise<SourceOption[]> {
detail: `published · ${url.replace(/^https?:\/\//, "")}`,
});
}
- out.push(...sites);
- const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
- const hub = hubUrl(await readJson<{ homepageUrl?: unknown }>(settingsFile));
+ // NO LOCAL CORPUS (no composed corpus.json on this machine — a fresh
+ // clone) and an archive to read: the archives come first, so the default
+ // source (`sources[0]` everywhere, and openSource with no handle) is the
+ // first archive (demo epic D1 item 2). The local entry stays offered, last.
+ if (!corpus && sites.length > 0) {
+ out[0] = { ...out[0], detail: "this machine · no build" };
+ out.unshift(...sites);
+ } else out.push(...sites);
+ const hub = hubUrl(settings);
if (hub) out.push({ handle: `hub:${hub}`, kind: "hub", label: "Hub", detail: `every listed site · ${hub.replace(/^https?:\/\//, "")}` });
return out;
}
@@ -128,7 +150,7 @@ const IDENTITY_TIMEOUT_MS = 10_000;
* file's mtime and size (a recomposed export/public changes both). Null when
* it cannot be told -- then the census is counted but not kept.
*/
-export async function buildIdentity(option: SourceOption): Promise<string | null> {
+export async function buildIdentity(option: SourceOption, doFetch: FetchLike = fetch as unknown as FetchLike): Promise<string | null> {
if (option.kind === "local") {
const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json");
const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
@@ -138,9 +160,12 @@ export async function buildIdentity(option: SourceOption): Promise<string | null
}
const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, "");
try {
- const res = await fetch(`${url}/corpus.json`, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
+ // An archive is untrusted input: read on its own origin (no redirect
+ // elsewhere is followed) and never past the document bound.
+ const at = `${url}/corpus.json`;
+ const res = await fetchOnOrigin(doFetch, at, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
if (!res.ok) return null;
- const j = (await res.json()) as { generatedAt?: unknown };
+ const j = JSON.parse(await readBounded(res, at)) as { generatedAt?: unknown };
return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null;
} catch {
return null;
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,7 +8,7 @@
"build": "next build",
"start": "next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
- "test": "tsx --test lib/brandIcon.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
+ "test": "tsx --test lib/brandIcon.test.ts lib/articles/*.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts components/projects/bench/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -14,6 +14,9 @@ import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs";
// it was asked (e2e/fixtures/editor-stub.mjs)
// E2E_GEN_PROJECTS set below on the editor stub: where a stubbed video
// revision writes its project (release 27)
+// E2E_UMTOOL_SETTINGS_FILE set below on the editor stub: the settings file its
+// `archives` action writes (demo epic D1) -- the
+// fixture's copy the app reads as SETTINGS_FILE
// E2E_UMTOOL_EXTRA_KINDS set by projects.spec.ts on the CLI it runs: a kind
// injected into the registry (lib/projects/kinds.mjs)
// E2E_MODEL_LOG_SHOTS a directory: model-log.spec.ts saves its
@@ -167,6 +170,11 @@ export default defineConfig({
// article store, and a video revision's project under gen-projects.
ARTICLES_DIR: `${FIXTURE}/articles`,
E2E_GEN_PROJECTS: `${FIXTURE}/gen-projects`,
+ // demo epic D1: the file the archives action writes -- the fixture's
+ // settings, which the app reads. NOT the stub's own SETTINGS_FILE: the
+ // stub starts beside make-fixture.mjs, before that copy exists, and its
+ // in-process common code (the real verdict-review) reads settings.
+ E2E_UMTOOL_SETTINGS_FILE: `${FIXTURE}/settings.json`,
},
},
{
@@ -195,6 +203,11 @@ export default defineConfig({
// Research's local corpus (R1): the fixture's composed public dir, read as
// the MCP's --local reads one -- never the checkout's export/public.
`TRANSCRIPT_LOCAL_DIR=${FIXTURE}/research-public TRANSCRIPT_HUB_URL= ` +
+ // The settings the app reads (demo epic D1): the fixture's copy of the
+ // checkout's (make-fixture.mjs), so Connect an archive writes there; no
+ // archive from the shell's TRANSCRIPT_SITE_URL; the archive cache the
+ // fixture's own (common/lib/archiveCache-server.ts).
+ `SETTINGS_FILE=${FIXTURE}/settings.json TRANSCRIPT_SITE_URL= ARCHIVE_CACHE_DIR=${FIXTURE}/archive-cache ` +
// The generation usage ledger (release 27): the fixture's, never the
// checkout's .generation/usage.jsonl.
`GENERATION_USAGE_FILE=${FIXTURE}/generation-usage.jsonl ` +
diff --git a/umtool/report-to-video/archive-fetch.mjs b/umtool/report-to-video/archive-fetch.mjs
@@ -0,0 +1,106 @@
+// READING A PUBLISHED ARCHIVE, AS UNTRUSTED INPUT (demo epic D1 re-review, item 3).
+//
+// An archive is someone else's server and someone else's JSON. The editor
+// reads one through common/lib/remoteArchives-server.ts (fetchOnOrigin,
+// readBounded, and archiveRecordOf's "a manifest the corpus names elsewhere is
+// not followed"); this is the same three rules for the render's cue walk and
+// the other readers of createJsonCache (cues.mjs), in plain JS because these
+// scripts run under bare node with no tsx. Change one, change the other.
+//
+// - a document is read on the origin it was asked on: a redirect is followed
+// by hand, up to three, and only to the same scheme, host and port;
+// - no document past 32 MB is read (a shard page is up to 8 MB);
+// - a channel's transcripts manifest is the one corpus.json names only when
+// that is on the corpus's own origin; otherwise the contract's URL.
+
+export const MAX_ARCHIVE_DOCUMENT_BYTES = 32 * 1024 * 1024;
+const MAX_REDIRECTS = 3;
+
+/** Whether `url` is on `origin`'s own scheme, host and port. */
+export function sameOrigin(url, origin) {
+ try {
+ return new URL(url).origin === new URL(origin).origin;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A GET that stays on `url`'s origin. `fetchImpl(url, init)` is asked with
+ * `redirect: "manual"`; a 3xx with a Location is followed only on the same
+ * origin, at most three times, and one that leaves it throws before it is
+ * followed.
+ */
+export async function fetchOnOrigin(fetchImpl, url, init = {}) {
+ let at = url;
+ for (let hop = 0; ; hop += 1) {
+ const res = await fetchImpl(at, { ...init, redirect: "manual" });
+ const status = Number(res?.status);
+ if (!(status >= 300 && status <= 399) || status === 304) return res;
+ const location = res.headers?.get?.("location");
+ if (!location) return res;
+ const next = new URL(location, at).href;
+ if (!sameOrigin(next, url)) {
+ throw new Error(`GET ${at} redirects to ${new URL(next).origin}: an archive's documents are read from its own origin only`);
+ }
+ if (hop >= MAX_REDIRECTS) throw new Error(`GET ${url} redirects more than ${MAX_REDIRECTS} times`);
+ at = next;
+ }
+}
+
+/**
+ * A response's JSON, refused past `max` bytes: by its Content-Length first,
+ * then as the body streams. A response with no stream (a test's stub) is read
+ * as it offers itself, its text measured when it has one.
+ */
+export async function readJsonBounded(res, url, max = MAX_ARCHIVE_DOCUMENT_BYTES) {
+ const over = () => new Error(`GET ${url} is over ${Math.round(max / 1024 / 1024)} MB: an archive document that large is not read`);
+ const declared = Number(res.headers?.get?.("content-length"));
+ if (Number.isFinite(declared) && declared > max) {
+ await res.body?.cancel?.().catch(() => {});
+ throw over();
+ }
+ if (res.body && typeof res.body.getReader === "function") {
+ const reader = res.body.getReader();
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > max) {
+ await reader.cancel().catch(() => {});
+ throw over();
+ }
+ chunks.push(value);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ }
+ if (typeof res.text === "function") {
+ const text = await res.text();
+ if (Buffer.byteLength(text) > max) throw over();
+ return JSON.parse(text);
+ }
+ return res.json();
+}
+
+/**
+ * Where a channel's transcripts manifest is read: the URL its corpus.json
+ * entry names when that is on `origin` itself (a relative one is resolved
+ * against it), else the contract's `<origin>/transcripts/<slug>/manifest.json`
+ * — a manifest named on another origin is never followed.
+ */
+export function transcriptsManifestUrl(origin, entry) {
+ const base = new URL(origin).origin;
+ const contract = `${base}/transcripts/${encodeURIComponent(String(entry?.slug ?? ""))}/manifest.json`;
+ const named = entry?.manifests?.transcripts;
+ if (typeof named !== "string" || !named.trim()) return contract;
+ let resolved;
+ try {
+ resolved = new URL(named.trim(), `${base}/`);
+ } catch {
+ return contract;
+ }
+ if (resolved.origin !== base || resolved.username || resolved.password) return contract;
+ return resolved.href;
+}
diff --git a/umtool/report-to-video/chrome-instruments.mjs b/umtool/report-to-video/chrome-instruments.mjs
@@ -581,7 +581,8 @@ export const CALLOUT_HOLD = 2.2;
* The remembered weight's cues in the looks other than the long needle (dialParts, `deck.dial.rememberedAs`): its
* rim marker and its flag (or its readout line) up while it is the latest remembered; with "callout", first the
* ghost needle sweeping from where the needle stands to the value and the label held CALLOUT_HOLD s. In the finale,
- * the last one's, all at once.
+ * the last one's, all at once. The finale never plays the callout: its labels and its ghost needle are hidden there, the
+ * rim's marker and flag stay.
*/
function rememberedCues(L, { track, scale, cfg, k, finale }) {
const M = INSTRUMENT_MOTION;
@@ -594,7 +595,9 @@ function rememberedCues(L, { track, scale, cfg, k, finale }) {
R.forEach((g, j) => {
L.set(k(`gk${j}`), { rotation: dialAngle(g.value, scale), autoAlpha: 0 });
L.set(k(`${label}${j}`), { autoAlpha: 0 });
- if (call) L.set(k(`gc${j}`), { autoAlpha: 0 });
+ // The callout's label is drawn whenever the look is "callout" (dialParts), so it is hidden whenever it is drawn:
+ // in the finale too, where nothing calls it up (rev9-a9: every box sat at its CSS default over the hub).
+ if (mode === "callout") L.set(k(`gc${j}`), { autoAlpha: 0 });
if (finale && j !== R.length - 1) return;
const next = finale ? null : R[j + 1];
for (const key of [`gk${j}`, `${label}${j}`]) {
@@ -602,9 +605,10 @@ function rememberedCues(L, { track, scale, cfg, k, finale }) {
if (next) L.add(k(key), startOf(next), M.fade * 0.6, { autoAlpha: 0 }, "power1.in");
}
});
+ // The ghost needle likewise: drawn with the look, hidden with it -- the finale never sweeps it.
+ if (mode === "callout") L.set(k("gn"), { rotation: dialAngle(R[0].value, scale), autoAlpha: 0 });
if (!call) return;
const a0 = dialAngle(scale.min, scale);
- L.set(k("gn"), { rotation: dialAngle(R[0].value, scale), autoAlpha: 0 });
R.forEach((g, j) => {
// From where the needle stands as he says it (his stated weight in force then; the scale's foot before one).
const cur = [...track.current].filter((c) => c.t <= g.t + 1e-9 && Number.isFinite(c.value)).pop();
diff --git a/umtool/report-to-video/chrome-measure-extras.mjs b/umtool/report-to-video/chrome-measure-extras.mjs
@@ -17,7 +17,7 @@ import { rgba } from "./chrome-deck.mjs";
import { compileCues, cuePageHtml, esc, INSTANT, joinSpans, r4, spanEvents } from "./chrome-cues.mjs";
import {
daysBetween, daysLeftText, daysText, DIET_TAG, dietDays, dietStates, dietTagStep, goalStates, goalText, GOALS_SHELF, jitter, measureBox, measureExtraGeometry, measureOf, MEASURE_BOXES, promiseStripRect, promiseStripType,
- MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, streakStates, upSpans, weightText,
+ MEASURE_DODGE_MOVE, measurePlacements, monthYear, peakStates, promiseStates, shortDate, stampNoteClause, stampNoteLine, streakStates, upSpans, weightText,
} from "./measure-extras.mjs";
import { dietTagWidth, MEASURE_RED, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
import { dialFinaleGeometry, dialFinaleHandoff } from "./chrome-instruments.mjs";
@@ -643,7 +643,7 @@ function promiseStrip(states, place, cfg, render, opts, items) {
const claim = r.claim ? `<span class="sp">·</span><span>${esc(cfg.claimVerb)} ${esc(shortDate(r.claim.paidOn ?? r.claim.date))} by @${esc(handleOf(r.claim.speaker, cfg, opts))}</span>` : "";
const o = r.outcome;
const status = o && o.kind !== "kept"
- ? `<span class="no">${o.kind === "refunded" ? "refunded" : "withdrawn"} · no video</span>`
+ ? `<span class="no">${o.kind === "refunded" ? "refunded" : "withdrawn"} · ${esc(stampNoteClause(o))}</span>`
: r.kept ? `<span class="ok">${esc(cfg.kept)}</span>` : `<span class="no">${esc(cfg.broken)}</span>`;
const html = `<div class="sl" data-k="${k}"><span>${esc(r.what)} ${esc(cfg.verb)} ${esc(shortDate(r.said))}</span>${claim}<span class="sp">·</span><b>${esc(days)}</b><span class="sp">·</span>${status}</div>`;
items.push({ key: k, gate: [k, "autoAlpha"], html });
@@ -725,7 +725,7 @@ export function promiseHtml(schedule, render, opts = {}) {
const o = r.outcome;
if (o && o.kind !== "kept") {
const word = o.kind === "refunded" ? "Refunded" : "Withdrawn";
- status = `<div class="stamp ${esc(o.kind)}" data-k="${k}o"><div class="sw">${word}</div><div class="ss">${o.date ? `by ${esc(shortDate(o.date))} · ` : ""}no video</div></div>`;
+ status = `<div class="stamp ${esc(o.kind)}" data-k="${k}o"><div class="sw">${word}</div><div class="ss">${esc(stampNoteLine(o))}</div></div>`;
} else status = `<div class="pill">${esc(r.kept ? cfg.kept : cfg.broken)}</div>`;
let q;
if (r.word) {
diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs
@@ -64,6 +64,10 @@ import os from "node:os";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
+
+// For the other readers of an archive that come through this module (linkCheck.mjs).
+export { transcriptsManifestUrl };
// This file lives at <repo>/umtool/report-to-video/, so the corpus a plain
// checkout would have is two levels up. Previously this defaulted to an absolute
@@ -244,9 +248,11 @@ export function createJsonCache({
if (inflight.has(flight)) return inflight.get(flight);
const pending = (async () => {
log(`fetch ${url}`);
- const res = await fetchImpl(url);
+ // An archive is untrusted input (archive-fetch.mjs): the document is
+ // read on the origin it was asked on, and never past 32 MB.
+ const res = await fetchOnOrigin(fetchImpl, url);
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
- const json = await res.json();
+ const json = await readJsonBounded(res, url);
mem.set(url, { version, body: json });
fetchedAt.set(url, Date.now());
if (disk) {
@@ -324,10 +330,11 @@ export function createCueSource({
// terrible one to pay silently, so the direct lookup fails with instructions
// instead and this runs only when asked.
async function resolveSiteId(origin, entry, wanted) {
- const manifest = await getJson(entry.manifests.transcripts);
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`);
for (let n = 0; n < manifest.pageCount; n += 1) {
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, n), { version: pagesVersionOf(manifest) });
const hit = page.find(
(r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted),
);
@@ -348,7 +355,10 @@ export function createCueSource({
const siteChannel = hints.siteChannel ?? channelSlug;
const siteVideo = hints.siteVideo ?? videoId;
const entry = await channelEntry(origin, siteChannel);
- const manifest = await getJson(entry.manifests.transcripts);
+ // The manifest corpus.json names, when it is on the archive's own origin;
+ // one named elsewhere is not followed — the contract's URL is read instead.
+ const manifestAt = transcriptsManifestUrl(origin, entry);
+ const manifest = await getJson(manifestAt);
const pageNumber = manifest.slugToPage?.[siteVideo];
if (pageNumber === undefined) {
@@ -365,17 +375,17 @@ export function createCueSource({
` up to 8 MB per shard until it matches).\n` +
` Note that a clip's citeUrl is NOT usable here — it may deliberately cite a\n` +
` different recording (a mirror that reads better), whose clock is not the same.`,
- { channelSlug, videoId, tried: [entry.manifests.transcripts] },
+ { channelSlug, videoId, tried: [manifestAt] },
);
}
- const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) });
+ const page = await getJson(pageUrlFrom(manifestAt, pageNumber), { version: pagesVersionOf(manifest) });
const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo);
if (!record) {
throw new CueLookupError(
`${siteChannel}/${siteVideo} is on shard ${pageNumber} per the manifest, but no record ` +
`there has that id — the published archive is inconsistent`,
- { channelSlug, videoId, tried: [pageUrlFrom(entry.manifests.transcripts, pageNumber)] },
+ { channelSlug, videoId, tried: [pageUrlFrom(manifestAt, pageNumber)] },
);
}
return { ...record, from: "http" };
diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs
@@ -19,6 +19,7 @@ import {
pageUrlFrom,
siteOriginFromManifest,
} from "./cues.mjs";
+import { readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
const ORIGIN = "https://example.pages.dev";
@@ -91,6 +92,17 @@ test("a page URL replaces only the manifest's last segment", () => {
);
});
+test("a shard's URL stays on the manifest's origin, whatever the manifest says its page number is", () => {
+ // slugToPage is the archive's own JSON: a "page number" may be any value.
+ const at = "https://x.dev/transcripts/some-chan/manifest.json";
+ for (const n of ["//evil.example/x", "/../../../../etc/passwd", "@evil.example/", "\\\\evil.example\\x", "https://evil.example/x", "?x=1#y", "$`$'$&", "\n", -1, 1.5, NaN, null, {}, [], "0000.json/../../../corpus"]) {
+ const url = new URL(pageUrlFrom(at, n));
+ assert.equal(url.origin, "https://x.dev", String(n));
+ assert.equal(url.search, "", String(n));
+ assert.equal(url.hash, "", String(n));
+ }
+});
+
test("resolves a video over HTTP with cues intact", async () => {
const got = await source().load("chan", "vid1");
assert.equal(got.from, "http");
@@ -567,6 +579,106 @@ test("prefer:local refuses to fall back rather than cut from other cues", async
});
});
+// --- an archive is untrusted input (demo epic D1 re-review, item 3) ----------
+
+test("a manifest corpus.json names on another origin is not followed: the contract's URL on the archive's own origin is read", async () => {
+ const seen = [];
+ const routes = {
+ ...ROUTES,
+ [`${ORIGIN}/corpus.json`]: { channels: [{ slug: "chan", manifests: { transcripts: "http://127.0.0.1:3001/api/ops/settings" } }] },
+ "http://127.0.0.1:3001/api/ops/settings": { pageCount: 1, slugToPage: { vid1: 0 } },
+ "http://127.0.0.1:3001/api/ops/page-0000.json": [{ ...RECORD, title: "from the other host" }],
+ };
+ const rec = await source({ fetchImpl: stubFetch(routes, seen) }).load("chan", "vid1");
+ assert.equal(rec.title, "A Title");
+ assert.deepEqual(seen, [`${ORIGIN}/corpus.json`, `${ORIGIN}/transcripts/chan/manifest.json`, `${ORIGIN}/transcripts/chan/page-0000.json`]);
+ // The opt-in shard scan walks the same manifest.
+ const seen2 = [];
+ const hit = await source({ fetchImpl: stubFetch(routes, seen2), resolveSiteIds: true }).load("chan", "v94hyv");
+ assert.equal(hit.id, "other");
+ assert.equal(seen2.some((u) => !u.startsWith(ORIGIN)), false);
+});
+
+test("transcriptsManifestUrl: the named manifest on the origin (absolute or relative), else the contract's", () => {
+ const at = (transcripts, slug = "chan") => transcriptsManifestUrl(ORIGIN, { slug, manifests: { transcripts } });
+ assert.equal(at(`${ORIGIN}/transcripts/chan/manifest.json`), `${ORIGIN}/transcripts/chan/manifest.json`);
+ assert.equal(at(`${ORIGIN}/shared/chan/manifest.json`), `${ORIGIN}/shared/chan/manifest.json`, "a same-origin manifest elsewhere in the tree is the archive's to name");
+ assert.equal(at("/transcripts/chan/manifest.json"), `${ORIGIN}/transcripts/chan/manifest.json`);
+ for (const off of [
+ "https://evil.example/transcripts/chan/manifest.json",
+ "http://example.pages.dev/transcripts/chan/manifest.json", // another scheme is another origin
+ "https://example.pages.dev:8443/transcripts/chan/manifest.json",
+ "https://user:pw@example.pages.dev/transcripts/chan/manifest.json",
+ "//evil.example/m.json",
+ "file:///etc/passwd",
+ "",
+ undefined,
+ 42,
+ ]) {
+ assert.equal(at(off), `${ORIGIN}/transcripts/chan/manifest.json`, String(off));
+ }
+ assert.equal(at(undefined, "../../x"), `${ORIGIN}/transcripts/..%2F..%2Fx/manifest.json`, "a slug cannot climb out of the tree");
+ assert.equal(transcriptsManifestUrl(`${ORIGIN}/`, { slug: "chan" }), `${ORIGIN}/transcripts/chan/manifest.json`);
+});
+
+test("the cache reads a document on its own origin: a same-origin redirect is followed, one elsewhere refused unfollowed, more than three refused", async () => {
+ const asked = [];
+ const answers = {
+ [`${ORIGIN}/a.json`]: { status: 301, location: "/b.json" },
+ [`${ORIGIN}/b.json`]: { status: 200, body: { ok: 1 } },
+ [`${ORIGIN}/leave.json`]: { status: 302, location: "http://169.254.169.254/latest/meta-data/" },
+ "http://169.254.169.254/latest/meta-data/": { status: 200, body: { leaked: true } },
+ [`${ORIGIN}/loop.json`]: { status: 302, location: "/loop.json" },
+ };
+ const fetchImpl = async (url, init) => {
+ asked.push(url);
+ assert.equal(init?.redirect, "manual", "every request is asked not to follow redirects");
+ const a = answers[url];
+ if (!a) return new Response("nope", { status: 404 });
+ return new Response(a.body === undefined ? null : JSON.stringify(a.body), { status: a.status, headers: a.location ? { location: a.location } : {} });
+ };
+ const { getJson } = createJsonCache({ cacheDir: null, fetchImpl });
+ assert.deepEqual(await getJson(`${ORIGIN}/a.json`), { ok: 1 });
+ await assert.rejects(() => getJson(`${ORIGIN}/leave.json`), /redirects to http:\/\/169\.254\.169\.254: an archive's documents are read from its own origin only/);
+ assert.equal(asked.includes("http://169.254.169.254/latest/meta-data/"), false);
+ await assert.rejects(() => getJson(`${ORIGIN}/loop.json`), /redirects more than 3 times/);
+ assert.equal(asked.filter((u) => u.endsWith("/loop.json")).length, 4);
+});
+
+test("the cache reads no document past the bound: by its declared length, and as it streams", async () => {
+ const big = 33 * 1024 * 1024;
+ const declared = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () => new Response("{}", { headers: { "content-length": String(big) } }),
+ });
+ await assert.rejects(() => declared.getJson(`${ORIGIN}/big.json`), /is over 32 MB: an archive document that large is not read/);
+ // No Content-Length: counted as it arrives, and the stream cancelled.
+ let sent = 0;
+ let cancelled = false;
+ const chunk = new Uint8Array(1024 * 1024).fill(0x20);
+ const streaming = createJsonCache({
+ cacheDir: null,
+ fetchImpl: async () =>
+ new Response(
+ new ReadableStream({
+ pull(c) {
+ sent += 1;
+ c.enqueue(chunk);
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ ),
+ });
+ await assert.rejects(() => streaming.getJson(`${ORIGIN}/endless.json`), /is over 32 MB/);
+ assert.equal(cancelled, true);
+ assert.ok(sent < 40, `stopped reading soon after the bound (${sent} MB sent)`);
+ // A document under it is read as before.
+ assert.deepEqual(await readJsonBounded(new Response(JSON.stringify({ a: 1 })), `${ORIGIN}/x.json`), { a: 1 });
+ await assert.rejects(() => readJsonBounded(new Response("x".repeat(64)), `${ORIGIN}/x.json`, 16), /is over 0 MB/);
+});
+
// --- origin discovery -------------------------------------------------------
test("the archive origin comes from the manifest, in priority order", () => {
diff --git a/umtool/report-to-video/fetch-via-editor.mjs b/umtool/report-to-video/fetch-via-editor.mjs
@@ -292,6 +292,9 @@ if (wantAll) {
items: local.items,
requestedBy: "umtool",
manifest: manifestId,
+ // The archive the cut cites (demo epic D1): a CONNECTED one registers a
+ // channel the editor does not hold as remote-only; any other is ignored.
+ ...(/^https?:\/\//.test(String(provenance.siteOrigin ?? "")) ? { archive: String(provenance.siteOrigin).trim().replace(/\/+$/, "") } : {}),
...(maxHeight !== undefined ? { maxHeight } : {}),
...storedUrl,
}),
diff --git a/umtool/report-to-video/goal-base-max-days.test.mjs b/umtool/report-to-video/goal-base-max-days.test.mjs
@@ -0,0 +1,89 @@
+// `deck.goals.baseMaxDays` (rev9-a9, 12 Nov): a loss goal's base is the latest weight he gave by the goal's date --
+// however long before. On the real record that put "(FROM 368)" on a goal set eight years after he said 368. With
+// the knob a base counts only when its weight was SAID at most that many days before the goal; a staler one is no
+// base -- no "(FROM …)" on the note, no target and no tick on the dial. Unset, every base counts, as before.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { goalMarks, goalWords } from "./chrome-instruments.mjs";
+import { estimateSchedule, validateChrome } from "./deck.mjs";
+import { goalStates } from "./measure-extras.mjs";
+import { goalBoard } from "./measure-goals.mjs";
+import { goalBaseMaxDays, measureSlice } from "./measure-slice.mjs";
+
+const PAL = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const render = (goals) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PAL,
+ chrome: { engine: "hyperframes", layout: "deck", deck: { measure: { scopes: ["weight"], scale: { min: 100, max: 400 }, asOf: "2026-11-12" }, ...(goals === undefined ? {} : { goals }) } } });
+const schema = { kind: "measure", unit: "lb", yMin: 100, yMax: 400, bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current", "past", "delta", "goal", "goal_loss"] };
+const row = (o) => ({ scope: "weight", scopeBasis: "his words", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o });
+// The gaps the real record has: 8 years, 0 days, 279 days, 434 days.
+const LEDGER = [
+ row({ id: "a1", date: "2015-01-10", population: "current", value: 368, display: "368 lb", entryId: "c1" }),
+ row({ id: "g8y", date: "2023-01-08", population: "goal_loss", value: -100, display: "lose 100", entryId: "c2" }),
+ row({ id: "b1", date: "2023-03-01", population: "current", value: 350, display: "350 lb", entryId: "c3" }),
+ row({ id: "g0", date: "2023-03-01", population: "goal_loss", value: -50, display: "lose 50", entryId: "c4" }),
+ row({ id: "g279", date: "2023-12-05", population: "goal_loss", value: -60, display: "lose 60", entryId: "c5" }),
+ row({ id: "g434", date: "2024-05-08", population: "goal_loss", value: -70, display: "lose 70", entryId: "c6" }),
+];
+
+function sliced(r, ledger = LEDGER) {
+ const timeline = Array.from({ length: 7 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + 8, cite: 1, section: 0, quote: "q", onscreen: { title: `Clip ${i + 1}` } }));
+ const manifest = { slug: "m", title: "M", provenance: {}, render: r, timeline, ledgerSchema: schema, ledger };
+ const doc = estimateSchedule(manifest);
+ const m = measureSlice(manifest, doc, {});
+ const goalAfter = (id) => m.state[m.events.findIndex((e) => e.row === id) + 1].goal;
+ return { m, schedule: { ...doc, measure: m }, goalAfter };
+}
+
+test("unset: every base counts, however old -- and each carries the date its weight was said", () => {
+ assert.equal(goalBaseMaxDays({ render: render(undefined) }), null);
+ assert.equal(goalBaseMaxDays({ render: render(true) }), null);
+ const { goalAfter } = sliced(render({ base: true }));
+ assert.deepEqual(goalAfter("g8y").base, { value: 368, row: "a1", from: "stated", date: "2015-01-10" });
+ assert.equal(goalAfter("g8y").value, 268);
+ assert.deepEqual(["g0", "g279", "g434"].map((id) => [goalAfter(id).base.row, goalAfter(id).base.date, goalAfter(id).value]),
+ [["b1", "2023-03-01", 300], ["b1", "2023-03-01", 290], ["b1", "2023-03-01", 280]]);
+});
+
+test("365: a base said 0 or 279 days before the goal stays; 434 days and eight years are no base -- no target, his words", () => {
+ const r = render({ base: true, baseMaxDays: 365 });
+ assert.deepEqual(validateChrome(r.chrome, r), []);
+ const { m, schedule, goalAfter } = sliced(r);
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map((id) => goalAfter(id).base?.row ?? null), [null, "b1", "b1", null]);
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map((id) => goalAfter(id).value), [null, 300, 290, null]);
+ assert.equal(goalWords(goalAfter("g8y")), "LOSE 100");
+ assert.equal(goalWords(goalAfter("g434")), "LOSE 70");
+ assert.match(goalWords(goalAfter("g279")), /^GOAL 290 · LOSE 60/);
+ // The notes: "(FROM …)" only where the base stands.
+ const states = goalStates(schedule, r);
+ const baseOf = (text) => states[states.length - 1].notes.find((n) => n.text === text)?.base ?? null;
+ assert.deepEqual([baseOf("LOSE 100"), baseOf("LOSE 50"), baseOf("LOSE 60"), baseOf("LOSE 70")], [null, "(FROM 350)", "(FROM 350)", null]);
+ // The dial: a goal with no base has no weight to mark -- no tick from a base it does not have.
+ const marks = goalMarks(goalBoard(m), m.scale);
+ const tick = (id) => marks.find((x) => x.goal.row === id).angle !== null;
+ assert.deepEqual(["g8y", "g0", "g279", "g434"].map(tick), [false, true, true, false]);
+ // Unset, all four are marked.
+ const before = sliced(render({ base: true })).m;
+ assert.deepEqual(goalMarks(goalBoard(before), before.scale).map((x) => x.angle !== null), [true, true, true, true]);
+});
+
+test("the day counts from when the weight was SAID, never a remembered weight's as-of; the edge day is inside", () => {
+ const ledger = [
+ row({ id: "p1", date: "2024-06-01", asOf: "2016-01-01", population: "past", value: 390, display: "≈390 lb", entryId: "c1" }),
+ row({ id: "g", date: "2024-06-10", population: "goal_loss", value: -100, display: "lose 100", entryId: "c2" }),
+ ];
+ const kept = sliced(render({ baseMaxDays: 30 }), ledger).goalAfter("g");
+ assert.deepEqual([kept.base.row, kept.base.from, kept.base.date, kept.value], ["p1", "remembered", "2024-06-01", 290]);
+ assert.equal(sliced(render({ baseMaxDays: 9 }), ledger).goalAfter("g").base.row, "p1", "9 days before, 9 allowed");
+ assert.equal(sliced(render({ baseMaxDays: 8 }), ledger).goalAfter("g").base, null);
+ // 0: only a weight said on the goal's own day.
+ assert.equal(sliced(render({ baseMaxDays: 0 })).goalAfter("g0").base.row, "b1");
+ assert.equal(sliced(render({ baseMaxDays: 0 })).goalAfter("g279").base, null);
+});
+
+test("the setting is checked: whole days from 0, or null", () => {
+ const problems = (v) => validateChrome(render({ baseMaxDays: v }).chrome, render({ baseMaxDays: v })).join("\n");
+ assert.equal(problems(null), "");
+ assert.equal(problems(0), "");
+ for (const bad of [-1, 1.5, "365", 40000]) assert.match(problems(bad), /deck\.goals\.baseMaxDays must be null \(every base counts\) or whole days from 0 to 36500/, String(bad));
+});
diff --git a/umtool/report-to-video/ledger-shared.mjs b/umtool/report-to-video/ledger-shared.mjs
@@ -102,6 +102,16 @@ export const LEDGER_BUILTIN_KEYS = new Set([
// who said it, when it is not the subject (a promise_claim's counterparty;
// such a row never moves the subject's numbers), and the day she says she paid
"speaker", "paidOn",
- // how a promise ended (a promise_outcome's: kept, refunded, withdrawn)
- "outcome",
+ // how a promise ended (a promise_outcome's: kept, refunded, withdrawn), and the words under its stamp
+ // (`stampNote`: the promise clock's second line in place of "by <date> · no video")
+ "outcome", "stampNote",
]);
+
+/**
+ * THE WORDS UNDER AN OUTCOME'S STAMP (a promise_outcome row's `stampNote`, 12 Nov): the promise clock wrote
+ * "by <date> · no video" under REFUNDED whatever the record said. A row's own note is that line instead; the strip
+ * (one line over a post's card) has room for its first clause only. `fit`: the characters the stamp's line holds
+ * beside the count and the as-of at the card's design width -- the longest the clock's own words come to ("by 26 Oct
+ * 2025 · no video" is 25) -- past it the lint warns; `max`: what a row may carry at all.
+ */
+export const STAMP_NOTE = Object.freeze({ fit: 26, max: 80 });
diff --git a/umtool/report-to-video/ledger-totals.mjs b/umtool/report-to-video/ledger-totals.mjs
@@ -46,7 +46,7 @@ import {
// Re-exported rather than redefined: every consumer already imports these from
// here, and two files owning one vocabulary is the divergence this module was
// written to stop.
-export { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, VALUE_KINDS, addDays, chronological, dateKey, dayOf, daysBetween } from "./ledger-shared.mjs";
+export { LEDGER_BUILTIN_KEYS, SCOPE_CONFIDENCE, STAMP_NOTE, VALUE_KINDS, addDays, chronological, dateKey, dayOf, daysBetween } from "./ledger-shared.mjs";
export {
EVENTS,
MEASURE_PREDICATES,
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -53,6 +53,8 @@
// and validateTeasers refuses it.)
// - a QR under WARN_QR_PX_PER_MODULE_720P pixels per module at 720p: it
// scans on a good screen with a steady hand, not reliably.
+// - a promise outcome's `stampNote` (a ledger row's words under its stamp on the promise clock) longer than
+// the stamp's one line holds (measure-extras.mjs STAMP_NOTE.fit);
// - a tally label wider than its cell: drawn smaller, down to
// TALLY_LABEL_FLOOR, then cut with an ellipsis (factcheck.mjs
// fitTallyLabel) -- the chrome is never refused for it.
@@ -85,6 +87,7 @@ import {
validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, deckClaimNotes, validateDeckClaims,
} from "./deck.mjs";
import { tallyLabelNotes, validateClaims } from "./factcheck.mjs";
+import { stampNoteWarnings } from "./measure-extras.mjs";
import { validateClipAudioEntries } from "./clip-audio.mjs";
import { validateClipBlurEntries } from "./clip-blur.mjs";
import { validateGapEntries } from "./gaps.mjs";
@@ -457,6 +460,8 @@ export function lintManifest(manifest, {
// A tally label wider than its cell, drawn smaller or cut (factcheck.mjs fitTallyLabel): said, never refused.
if (!only) warnings.push(...tallyLabelNotes(render));
warnings.push(...stackedLintWarnings(manifest, { only }));
+ // A promise outcome's own stamp words (a ledger row's `stampNote`) longer than the stamp's line holds.
+ if (!only) warnings.push(...stampNoteWarnings(whole));
for (const { where, src } of imageSrcsOf(manifest, { only })) {
if (path.isAbsolute(src) || src.startsWith("~")) {
diff --git a/umtool/report-to-video/measure-extras.mjs b/umtool/report-to-video/measure-extras.mjs
@@ -28,6 +28,7 @@
import { deckGeometry, feedGeometry, instrumentsGeometry, overlayBox, pictureK } from "./deck.mjs";
import { chapterCover, chapterWindows } from "./chrome-story.mjs";
import { dietTagWidth, MEASURE_EXTRAS, MEASURE_POSITIONS, resolveMeasureExtra, SHELF_POSITION } from "./modules/measure-extras-settings.mjs";
+import { STAMP_NOTE } from "./ledger-shared.mjs";
import { resolveShelf } from "./modules/shelf-settings.mjs";
import { stackedOn, stackedStandDowns } from "./vertical-deck.mjs";
@@ -353,6 +354,38 @@ export const PROMISE_SETTLE = 4;
/** The count-up to the render date: a day a step, over at most this long. */
export const PROMISE_COUNT_UP = 1.2;
+export { STAMP_NOTE };
+
+/** The stamp's second line: the outcome's own note, else the clock's words ("by 26 Oct · no video"). */
+export function stampNoteLine(outcome) {
+ if (typeof outcome?.note === "string" && outcome.note.trim()) return outcome.note.trim();
+ return `${outcome?.date ? `by ${shortDate(outcome.date)} · ` : ""}no video`;
+}
+
+/** The strip's words after the outcome's: a note's first clause (to its first · , ; — or " -- "), else "no video". */
+export function stampNoteClause(outcome) {
+ const note = typeof outcome?.note === "string" ? outcome.note.trim() : "";
+ if (!note) return "no video";
+ return note.split(/\s+--\s+|\s*[·;—]\s*|,\s+/)[0].trim() || note;
+}
+
+/**
+ * The lint's warnings for the stamp notes (lint.mjs): a `stampNote` longer than the stamp's line holds -- it is one
+ * line, never wrapped, so it runs past the stamp's border and into the as-of beside it.
+ * @returns {string[]}
+ */
+export function stampNoteWarnings(manifest) {
+ const out = [];
+ for (const row of Array.isArray(manifest?.ledger) ? manifest.ledger : []) {
+ if (row?.population !== "promise_outcome" || typeof row.stampNote !== "string") continue;
+ const note = row.stampNote.trim();
+ if (note.length > STAMP_NOTE.fit) {
+ out.push(`ledger ${row.id}.stampNote "${note}" is ${note.length} characters: the promise clock's stamp holds about ${STAMP_NOTE.fit} on its second line (it is one line, never wrapped) -- it will run past the stamp; shorten it (umtool ledger <p> set ${row.id} --stampNote "…")`);
+ }
+ }
+ return out;
+}
+
/** The promise outcomes the clock draws (CONTRACT addendum 2): kept stops the count; refunded and withdrawn do not. */
export const PROMISE_OUTCOMES = Object.freeze(["kept", "refunded", "withdrawn"]);
@@ -387,7 +420,8 @@ export function promiseStates(schedule, render) {
const lastWord = new Map();
const outcomeOf = (p) => {
const o = isObj(p.outcome) && PROMISE_OUTCOMES.includes(p.outcome.kind) ? p.outcome : null;
- return o ? { kind: o.kind, date: o.date ?? null } : p.kept === true ? { kind: "kept", date: null } : null;
+ const note = typeof o?.note === "string" && o.note.trim() ? o.note.trim() : null;
+ return o ? { kind: o.kind, date: o.date ?? null, ...(note ? { note } : {}) } : p.kept === true ? { kind: "kept", date: null } : null;
};
const rowsAt = (s, freshRow) => (Array.isArray(s?.promises) ? s.promises : [])
.filter((p) => p && p.said)
diff --git a/umtool/report-to-video/measure-slice.mjs b/umtool/report-to-video/measure-slice.mjs
@@ -115,6 +115,19 @@ export function resolveMeasure(manifest, { asOf = null } = {}) {
};
}
+/**
+ * `render.chrome.deck.goals.baseMaxDays` as the slice reads it: whole days (0 = the goal's own day), or null when
+ * unset (or the goal stack is a bare true/false): how long before a loss goal a weight may have been said and still
+ * be the goal's base (measureSlice `goalBase`). The goal stack's settings check its shape (measure-extras-settings.mjs).
+ */
+export function goalBaseMaxDays(manifest) {
+ const v = manifest?.render?.chrome?.deck?.goals?.baseMaxDays;
+ return Number.isInteger(v) && v >= 0 ? v : null;
+}
+
+/** A promise_outcome row's `stampNote` -- the words under its stamp on the promise clock -- trimmed, or null. */
+export const stampNoteOf = (row) => (typeof row?.stampNote === "string" && row.stampNote.trim() ? row.stampNote.trim() : null);
+
// ---------------------------------------------------------------------------
// The odometer
// ---------------------------------------------------------------------------
@@ -493,17 +506,24 @@ export function measureSlice(manifest, schedule, opts = {}) {
const starts = readings.filter((r) => r.population === "past" && r.asOf && dateKey(r.date) <= dateKey(d) &&
dateKey(r.asOf) <= dateKey(run.start) && Math.round(daysBetween(r.asOf, run.start)) <= s.bandGapDays);
const last = starts[starts.length - 1];
- if (last) return { value: Number(last.value), row: last.id, from: "runStart" };
+ if (last) return { value: Number(last.value), row: last.id, from: "runStart", date: last.date ?? null };
}
const known = readings
.filter((r) => dateKey(r.date) <= dateKey(d))
.sort((a, b) => dateKey(plotDate(a)).localeCompare(dateKey(plotDate(b))) || dateKey(a.date).localeCompare(dateKey(b.date)));
const last = known[known.length - 1];
- return last ? { value: Number(last.value), row: last.id, from: last.population === "past" ? "remembered" : "stated" } : null;
+ return last ? { value: Number(last.value), row: last.id, from: last.population === "past" ? "remembered" : "stated", date: last.date ?? null } : null;
};
+ // `deck.goals.baseMaxDays` (rev9-a9, 12 Nov: "LOSE 100 (FROM 368)" off a weight he gave eight years before): a
+ // base counts only when its weight was SAID -- its row's date, never a remembered one's asOf -- at most that many
+ // days before the goal's date. A staler one is no base: his words stay the goal, no weight, no tick, no "(FROM …)".
+ // Unset: every base counts, as before.
+ const baseMaxDays = goalBaseMaxDays(manifest);
+ const fresh = (base, row) => baseMaxDays === null || !base || (base.date && Math.round(daysBetween(base.date, row.date)) <= baseMaxDays);
const scaleMin = Number.isFinite(settings.scale?.min) ? settings.scale.min : -Infinity;
const goalOf = (row) => {
let base = row.population === "goal_loss" ? goalBase(row) : null;
+ if (!fresh(base, row)) base = null;
let cell = goalCell(row, base, s);
if (base && Number.isFinite(cell.value) && cell.value < scaleMin) {
base = null;
@@ -515,7 +535,7 @@ export function measureSlice(manifest, schedule, opts = {}) {
/** A promise_claim as a promise carries it: who, when said, the day she says she paid, his-or-her words. */
/** A promise_outcome as a promise carries it. */
- const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id });
+ const outcomeOf = (row) => ({ kind: row.outcome, date: row.date ?? null, row: row.id, ...(stampNoteOf(row) ? { note: stampNoteOf(row) } : {}) });
const claimOf = (row) => ({ row: row.id, speaker: speakerOf(row), date: row.date ?? null, paidOn: isIso(row.paidOn) ? row.paidOn : null, label: row.label ?? row.display ?? null });
// ---- the state after each event -------------------------------------------
diff --git a/umtool/report-to-video/measure-slice.test.mjs b/umtool/report-to-video/measure-slice.test.mjs
@@ -175,7 +175,7 @@ test("state: after each event, from the shown rows only", () => {
assert.deepEqual(last.lost, { total: 49, runs: [{ run: 0, start: "2024-01-05", peak: 9, row: "w02" }, { run: 1, start: "2025-04-01", peak: 40, row: "w09" }] });
for (let i = 1; i < sl.state.length; i += 1) assert.ok(sl.state[i].lost.total >= sl.state[i - 1].lost.total, "the odometer only goes up");
// "Lose 65" against the start of its run: the 349 he remembers (asOf 20 March, 12 days before).
- assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart" } });
+ assert.deepEqual(last.goal, { value: 284, loss: 65, deadline: "by Christmas", due: "2025-12-25", row: "w11", display: "284 lb", base: { value: 349, row: "w07", from: "runStart", date: "2025-05-01" } });
assert.deepEqual(last.goals, ["w11"]);
assert.deepEqual(last.remembered.map((r) => r.row), ["w01", "w07"]);
assert.deepEqual(last.promises, [{ row: "p01", said: "2025-06-05", what: "post a video of the scale", due: null, kept: false, checks: [], claims: [], outcome: null }]);
diff --git a/umtool/report-to-video/modules/goals.mjs b/umtool/report-to-video/modules/goals.mjs
@@ -23,16 +23,18 @@ export default measureExtraModule({
{ key: "color", type: "color", label: "Paper (default the palette's amber)" },
{ key: "countdown", type: "boolean", label: "Count a deadline down to the render date", default: true },
{ key: "base", type: "boolean", label: "Say the weight he had stated when he set it", default: false },
+ { key: "baseMaxDays", type: "number", min: MEASURE_LIMITS.baseMaxDays[0], max: MEASURE_LIMITS.baseMaxDays[1], label: "A base weight said at most this many days before the goal (unset: any age)" },
{ key: "flash", type: "boolean", label: "Flash its outline when its value changes (unset: deck.measure.flash)" },
],
docs: {
intro: "A sticky note per goal on a pile in a corner of the footage box, read off the schedule's `measure` slice (`render.chrome.deck.goals`, measure-extras.mjs): each goal or goalLoss event drops one, turned a little, onto the pile; the same goal in the same words (\"lose 100\") merges into its note with a count (\"×8\") and comes to the front; `max` notes show, the newest in front, with the goals set so far under them. A goal with a `deadline` counts down to `measure.asOfRender` (\"by Christmas · 50 days left · needs 226.5\"): Christmas is the next 25 Dec from the day he said it, \"next year\" a year on, a named year that year; words that name no date (\"by my birthday\") keep their label and no countdown. On whenever the cut has a measure slice with a goal on camera; `false` turns it off. Up for `hold` seconds after each goal (default 20), the pile as it stands each time. The four measure extras sit at anchors of the footage box by default, clear of the instrument panel's right column and of the top-left, where the streams' face cam most often is (the diet badge bottom-left, the goal stack bottom-right, the moving start top-right, the promise clock top-centre); `position` or `x`/`y` move one.",
rows: [
- ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
+ ["`deck.goals`", "`true` · `false` · `{show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays}` · default on with a measure slice", "`umtool look <p> deck.goals=false`"],
["`deck.goals.position`, `.x`/`.y`, `.scale`", "`top-left` `top-right` `bottom-left` `bottom-right` `top-center` `bottom-center` · design px · 0.5–2 · default `bottom-right`, unset, 1", "`umtool look <p> deck.goals.position=bottom-left`"],
["`deck.goals.position=shelf`", "its shelf form (`deck.shelf`): the count of goals set in a column, then the notes fanned sideways like the diet's tags -- ordered by the dial's goal board (measure-goals.mjs \`goalsAt(goalBoard(schedule.measure), t)\`, so the shelf and the dial always agree): its headline -- the closest goal in force -- in front with \"+N more\" for the others in force, the rest by recency; a goal the board misses struck in red, MISSED on it, for the dial's 6 s; with no goal in force, the newest in front; a new goal landing from above as on the pile; each older one showing its goal's words in the strip beside it (all of each when there is room); a repeat comes to the front with its ×n. The fan takes the shelf's spare width (shelfLayout), up to its notes side by side. On the shelf it stays up from the first goal (`hold` unset). What the dial draws of the goal stays on the dial", "`umtool look <p> deck.shelf.items='[\"diet\",\"goals\"]' deck.goals.position=shelf`"],
["`deck.goals.max`, `.color`, `.countdown`", "1–8 notes · #hex paper · bool · default 4, the palette's amber, `true`", "`umtool look <p> deck.goals.max=6`"],
["`deck.goals.base`", "bool · default `false`: each note also says the weight he had stated when he set the goal -- \"LOSE 100 (FROM 346.7)\", its qualifier kept (\"(FROM ≈390)\") -- the slice's own base for that goal, the one the gauge reckons its target from (measure-slice.mjs `goalBase`: the start of the run open when he set it, else the latest weight he gave by the goal's date, stated or remembered). A goal with no base (no weight by then, a target goal such as \"250 LB\", a base the scale's foot refuses) shows none -- never one made up. On a back card it is a line of its own, right-aligned like the label", "`umtool look <p> deck.goals.base=true`"],
+ ["`deck.goals.baseMaxDays`", "whole days 0–36500 · unset (default): every base counts. A loss goal's base is a weight he gave by the goal's date, however long before; with this set, a base counts only when its weight was SAID (its row's date, never a remembered weight's as-of) at most that many days before the goal's date. A staler one is no base: the note carries no \"(FROM …)\", and the slice resolves no target from it -- the dial draws no goal weight and no tick for that goal, his words (\"LOSE 100\") stay. It is the slice's rule (measure-slice.mjs `goalBaseMaxDays`), so the notes, the shelf and the dial agree; it needs `deck.goals` as settings (`deck.goals.base=true deck.goals.baseMaxDays=365`), and `baseMaxDays=null` takes it off", "`umtool look <p> deck.goals.baseMaxDays=365` (`--take <t>` for a take)"],
["`deck.goals.hold`, `.finale`", "0 (up from the first goal on) or 2–600 s after each · `hide` `show` · default 20, `hide`", "`umtool look <p> deck.goals.hold=0`"],
["`deck.goals.flash`", "bool · unset (default): follows `deck.measure.flash` -- THE UPDATE FLASH (update-flash.mjs): the note that lands lights as a goal is set -- not the first note (the stack coming up), not the board's own changes; a thin outline in its own colour, up over 0.15 s and gone over 0.7 s, no size change, never on frame 0 or while the deck is away", "`umtool look <p> deck.goals.flash=false`"],
],
diff --git a/umtool/report-to-video/modules/measure-extras-settings.mjs b/umtool/report-to-video/modules/measure-extras-settings.mjs
@@ -6,7 +6,7 @@
// SETTINGS), so it imports only instruments.mjs (a leaf too: whether the
// instruments' column is on decides two defaults here).
//
-// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown, base, flash }
+// render.chrome.deck.goals { show, position, x, y, scale, hold, finale, max, color, countdown, base, baseMaxDays, flash }
// render.chrome.deck.peak { show, position, x, y, scale, hold, finale, title, color, values }
// render.chrome.deck.promise { show, position, x, y, scale, hold, finale, label, verb, kept, broken, checks, speakers, claimVerb, claimColor }
// render.chrome.deck.diet { show, position, x, y, scale, hold, finale, colors, labels, form, tags, overlap, days, flash }
@@ -110,6 +110,7 @@ export const MEASURE_LIMITS = Object.freeze({
x: Object.freeze([0, 1920]),
y: Object.freeze([0, 1080]),
max: Object.freeze([1, 8]),
+ baseMaxDays: Object.freeze([0, 36500]),
text: 40,
quote: 160,
});
@@ -123,8 +124,10 @@ export const MEASURE_DEFAULTS = Object.freeze({
// after each goal; `max` notes show, the newest in front; `color` is the
// paper (default the palette's amber).
// `base`: each note also says the weight he had stated when he set it, "(FROM 346.7)" (the slice's goal base).
+ // `baseMaxDays`: a weight said more than this many days before a loss goal is not its base (measure-slice.mjs
+ // goalBase reads it): no "(FROM …)", no target, no tick from it. null: every base counts.
// `flash`: the update flash (update-flash.mjs) -- null follows deck.measure.flash, true/false for this module.
- goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true, base: false, flash: null }),
+ goals: Object.freeze({ ...COMMON, position: "bottom-right", hold: 20, max: 4, color: null, countdown: true, base: false, baseMaxDays: null, flash: null }),
// The moving start: up for `hold` seconds after each retelling.
peak: Object.freeze({ ...COMMON, position: "top-right", hold: 12, title: "The start keeps moving", color: null, values: "drift" }),
// The promise clock: up from the promise on, through the finale.
@@ -265,6 +268,9 @@ export function validateMeasureExtra(id, v, where = `render.chrome.deck.${id}`,
color(v.color, `${where}.color`, errors);
if (v.countdown !== undefined && typeof v.countdown !== "boolean") errors.push(`${where}.countdown must be true or false`);
if (v.base !== undefined && typeof v.base !== "boolean") errors.push(`${where}.base must be true or false`);
+ if (v.baseMaxDays !== undefined && v.baseMaxDays !== null && !(Number.isInteger(v.baseMaxDays) && numIn(v.baseMaxDays, L.baseMaxDays[0], L.baseMaxDays[1]))) {
+ errors.push(`${where}.baseMaxDays must be null (every base counts) or whole days from ${L.baseMaxDays[0]} to ${L.baseMaxDays[1]}`);
+ }
}
if (id === "goals" || id === "diet") {
if (v.flash !== undefined && v.flash !== null && typeof v.flash !== "boolean") errors.push(`${where}.flash must be true, false or null (deck.measure.flash)`);
diff --git a/umtool/report-to-video/modules/promise.mjs b/umtool/report-to-video/modules/promise.mjs
@@ -69,6 +69,7 @@ export default measureExtraModule({
["`deck.promise.position`, `.x`/`.y`, `.scale`", "an anchor in the footage box · design px · 0.5–2 · default `top-center`, unset, 1", "`umtool look <p> deck.promise.position=bottom-center`"],
["`deck.promise.hold`, `.finale`", "0 (stays up) or 2–600 s · `hide` `show` · default 0, `show`", "`umtool look <p> deck.promise.finale=hide`"],
["`deck.promise.label`, `.verb`, `.kept`, `.broken`, `.checks`", "≤40 each · `label` `quote` · default the row's display, \"offered\", \"Posted\", \"None posted\", `label`", "`umtool look <p> deck.promise.label='scale video'`"],
+ ["a `promise_outcome` row's `stampNote`", "one line, 1–80 characters · unset (default): the clock's own words under the stamp, \"by <date> · no video\". The row's note is that second line instead (REFUNDED / \"by her account · no receipt\"); the strip over a post's card, which has one line for everything, shows its first clause (to its first `·`, `;`, `—`, `, ` or ` -- `: \"refunded · by her account\"). It is the ledger row's, so every take of the project reads it. `umtool lint` warns past 26 characters (the stamp's line is never wrapped: a longer one runs past its border)", "`umtool ledger <p> set <row> --stampNote \"by her account · no receipt\"` · off again: `--stampNote null`"],
["`deck.promise.speakers`, `.claimVerb`, `.claimColor`", "`{<speaker>: {handle, color}}` · ≤40 · #hex · default `{}` (the postAvatars handle), \"paid\", #E37AB8", "`umtool look <p> deck.promise.speakers='{\"madamsavvy\":{\"handle\":\"MadamSavvy\"}}'`"],
],
},
diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs
@@ -198,27 +198,36 @@ export async function projectCombos(dir, manifest, o = {}) {
* the cut whose capture holds one (captured after the item went in -- its
* media was never copied). Its capture is looked for under its own channel,
* then every channel the cut's posts come from (a reply captured under the
- * replies channel). `{ <itemId>: [{ name, slug, mediaId, sha256, url }] }`.
+ * replies channel). `{ <itemId>: [{ name, slug, tree, mediaId, sha256, url }] }`.
+ *
+ * `channelsDirs`: the channels trees to look in, in order (the project's own first, then the archive behind it:
+ * sources.mjs channelsLayersFor) -- the first tree that holds the post's capture wins, and each file says which
+ * (`tree`). Read only: nothing is written into any of them.
*
* @param {Record<string, any>} manifest
- * @param {{ channelsDir?: string|null }} [o]
+ * @param {{ channelsDir?: string|null, channelsDirs?: string[]|null }} [o]
*/
-export async function captureOnlyMedia(manifest, { channelsDir = null } = {}) {
- if (!channelsDir) return {};
+export async function captureOnlyMedia(manifest, { channelsDir = null, channelsDirs = null } = {}) {
+ const trees = (Array.isArray(channelsDirs) && channelsDirs.length ? channelsDirs : [channelsDir]).filter((d) => typeof d === "string" && d);
+ if (!trees.length) return {};
const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
- const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))];
+ const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter((c) => c && c !== "." && c !== ".." && !/[\\\0]/.test(c)))];
const out = {};
for (const e of tl) {
if (e?.type !== "post" || typeof e.post !== "string" || (Array.isArray(e.media) && e.media.length)) continue;
const [own, postId] = e.post.split("/");
if (!own || !postId) continue;
- for (const slug of [own, ...channels.filter((c) => c !== own)]) {
- const dirOf = path.join(channelsDir, slug, "posts-media", postId);
- const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null);
- const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : [];
- if (!media.length) continue;
- out[e.id] = media.map((m) => ({ name: m.name, slug, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null }));
- break;
+ // A post id of dots is no folder of a capture: never joined into a tree's path.
+ if ([own, postId].some((v) => v === "." || v === ".." || /[\\\0]/.test(v))) continue;
+ found: for (const tree of trees) {
+ for (const slug of [own, ...channels.filter((c) => c !== own)]) {
+ const dirOf = path.join(tree, slug, "posts-media", postId);
+ const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null);
+ const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : [];
+ if (!media.length) continue;
+ out[e.id] = media.map((m) => ({ name: m.name, slug, tree, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null }));
+ break found;
+ }
}
}
return out;
diff --git a/umtool/report-to-video/post-links.mjs b/umtool/report-to-video/post-links.mjs
@@ -64,7 +64,8 @@ export function createPostChannelResolver({
refreshAfterMs = Infinity,
now = Date.now,
} = {}) {
- const timed = (url) => fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
+ // `init` is the cache's (archive-fetch.mjs asks with `redirect: "manual"`).
+ const timed = (url, init) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
const get = getJson ?? createJsonCache({ ...(cacheDir !== undefined ? { cacheDir } : {}), fetchImpl: timed, log, refreshAfterMs }).getJson;
// ONE memo of failed reads, `url -> { err, at, refresh }`, consulted by both
// passes (the cached read and the fresh one): a URL that failed is not asked
diff --git a/umtool/report-to-video/remembered-looks.test.mjs b/umtool/report-to-video/remembered-looks.test.mjs
@@ -7,9 +7,10 @@ import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-import { CALLOUT_HOLD, dialHtml, heaviestOf, rememberedMode, rememberedWords } from "./chrome-instruments.mjs";
+import { CALLOUT_HOLD, dialFinaleHtml, dialHtml, heaviestOf, rememberedMode, rememberedWords } from "./chrome-instruments.mjs";
import { estimateSchedule } from "./deck.mjs";
import { validateDial } from "./instruments.mjs";
+import { moduleById } from "./modules/index.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures", "measure-remembered", "measure.json"), "utf8"));
@@ -80,3 +81,29 @@ test("one at a time, the latest remembered; the callout sweeps a ghost needle an
assert.ok(gn.some((c) => c.at === 3 && c.to.autoAlpha === 0.9), "the ghost needle comes up where the needle stands");
assert.ok(gn.some((c) => Math.abs(c.at - (3 + CALLOUT_HOLD)) < 1e-6 && c.to.autoAlpha === 0), "and goes after the hold");
});
+
+// rev9-a9 (12 Nov): in the finale the callout's label boxes and its ghost needle are drawn (dialParts draws them
+// whenever the look is "callout") but nothing hid them -- every box sat at its CSS default over the dial's hub.
+test("the finale never shows the callout: every label box and the ghost needle hidden from the first frame, the last one's rim flag up", () => {
+ const r = renderAs("callout");
+ r.chrome.deck = { ...r.chrome.deck, qr: { show: false }, finale: { video: "side", totals: false } };
+ const timeline = Array.from({ length: 4 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + (i === 3 ? 14 : 8), cite: 1, section: 0,
+ quote: "q", onscreen: { title: `Clip ${i + 1}` }, ...(i === 3 ? { layout: "finale" } : {}) }));
+ const schedule = { ...estimateSchedule({ slug: "m", title: "M", provenance: {}, render: r, timeline }), measure: MEASURE };
+ const win = moduleById("dial-finale").window(schedule, { fps: 30, total: schedule.total });
+ const html = dialFinaleHtml(schedule, r, win, { fonts: {} });
+ const data = JSON.parse(/<script id="dial-finale-data" type="application\/json">(.*?)<\/script>/s.exec(html)[1]);
+ const drawn = [...html.matchAll(/class="rcall" data-k="(fgc\d+)"/g)].map((m) => m[1]);
+ assert.ok(drawn.length >= 2, "the fixture's remembered weights each draw a callout box");
+ for (const k of drawn) {
+ assert.equal(data.init[k]?.autoAlpha, 0, `${k} is hidden at load`);
+ assert.ok(!data.cues.some((c) => c.k === k && c.to.autoAlpha > 0), `${k} is never called up`);
+ }
+ assert.match(html, /data-k="fgn"/);
+ assert.equal(data.init.fgn?.autoAlpha, 0, "the ghost needle is hidden at load");
+ assert.ok(!data.cues.some((c) => c.k === "fgn" && c.to.autoAlpha > 0), "and never sweeps");
+ // The rim's marker and flag stay: the last remembered one's, all at once.
+ const last = drawn.length - 1;
+ assert.ok(data.cues.some((c) => c.k === `fgl${last}` && c.to.autoAlpha === 1));
+ assert.ok(data.cues.some((c) => c.k === `fgk${last}` && c.to.autoAlpha === 1));
+});
diff --git a/umtool/report-to-video/stamp-note.test.mjs b/umtool/report-to-video/stamp-note.test.mjs
@@ -0,0 +1,91 @@
+// THE WORDS UNDER AN OUTCOME'S STAMP (a promise_outcome row's `stampNote`, 12 Nov): the promise clock wrote
+// "by <date> · no video" under REFUNDED whatever the record said. A row's own note is that line; the strip over a
+// post's card shows its first clause; with none, the clock's words as they were.
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { promiseHtml } from "./chrome-measure-extras.mjs";
+import { estimateSchedule } from "./deck.mjs";
+import { lintManifest } from "./lint.mjs";
+import { promiseStates, STAMP_NOTE, stampNoteClause, stampNoteLine, stampNoteWarnings } from "./measure-extras.mjs";
+import { measureSlice } from "./measure-slice.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const MEASURE = JSON.parse(readFileSync(path.join(HERE, "fixtures/measure-extras/measure.json"), "utf8"));
+const PAL = { bg: "#0F1312", fg: "#EDF0EC", muted: "#98A29B", accent: "#22AB83", amber: "#E8A33F" };
+const render = (deck = {}) => ({ width: 1920, height: 1080, fps: 30, transition: 0.4, palette: PAL, chrome: { engine: "hyperframes", layout: "deck", deck } });
+const schedule = (measure, extra = {}) => ({ kind: "deck", fps: 30, total: 740, transition: 0.4, segments: [{ id: "a", start: 0, duration: 740, end: 740 }], measure, ...extra });
+const clone = (v) => JSON.parse(JSON.stringify(v));
+const noted = (note) => {
+ const m = clone(MEASURE);
+ for (const s of m.state) for (const p of s.promises ?? []) if (p.outcome) p.outcome.note = note;
+ return m;
+};
+
+test("the words: the note when the row has one, the clock's own otherwise; the strip takes the first clause", () => {
+ assert.equal(stampNoteLine({ kind: "refunded", date: "2026-10-31" }), "by 31 Oct · no video");
+ assert.equal(stampNoteLine({ kind: "refunded", date: null }), "no video");
+ assert.equal(stampNoteLine({ kind: "refunded", date: "2026-10-31", note: " her word · no receipt " }), "her word · no receipt");
+ assert.equal(stampNoteClause({ kind: "refunded" }), "no video");
+ assert.equal(stampNoteClause({ note: "her word · no receipt" }), "her word");
+ assert.equal(stampNoteClause({ note: "by her account, 31 Oct" }), "by her account");
+ assert.equal(stampNoteClause({ note: "she says -- nothing shown" }), "she says");
+ assert.equal(stampNoteClause({ note: "partly; the rest owed" }), "partly");
+ assert.equal(stampNoteClause({ note: "one clause only" }), "one clause only");
+});
+
+test("the slice carries a promise_outcome row's stampNote on the promise's outcome; a row without one is as before", () => {
+ const schema = { kind: "measure", unit: "lb", yMin: 100, yMax: 400, bandGapDays: 60, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current"] };
+ const row = (o) => ({ scope: "weight", scopeBasis: "x", scopeConfidence: "read", valueKind: "uttered", flags: [], asOf: null, ...o });
+ const ledger = (note) => [
+ row({ id: "p01", date: "2026-10-23", population: "promise", display: "scale video", entryId: "c1" }),
+ row({ id: "o01", date: "2026-10-31", population: "promise_outcome", promise: "p01", outcome: "refunded", speaker: "madamsavvy", entryId: "c2", ...(note === undefined ? {} : { stampNote: note }) }),
+ ];
+ const r = render({ measure: { scopes: ["weight"], asOf: "2026-11-12" } });
+ const timeline = Array.from({ length: 3 }, (_, i) => ({ type: "clip", id: `c${i + 1}`, video: "v", start: 10 * i, end: 10 * i + 8, cite: 1, section: 0, quote: "q", onscreen: { title: `Clip ${i + 1}` } }));
+ const slice = (note) => {
+ const manifest = { slug: "m", title: "M", provenance: {}, render: r, timeline, ledgerSchema: schema, ledger: ledger(note) };
+ return measureSlice(manifest, estimateSchedule(manifest), {});
+ };
+ assert.deepEqual(slice(" by her account ").state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01", note: "by her account" });
+ assert.deepEqual(slice(undefined).state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01" });
+ assert.deepEqual(slice(" ").state.at(-1).promises[0].outcome, { kind: "refunded", date: "2026-10-31", row: "o01" });
+ // ... and the clock's states keep it.
+ assert.equal(promiseStates(schedule(slice("by her account")), r).find((s) => s.rows[0].outcome)?.rows[0].outcome.note, "by her account");
+});
+
+test("the page: the stamp's second line is the note (escaped); the column's compact stamp too; the strip its first clause", () => {
+ const r = render({ promise: { speakers: { madamsavvy: { handle: "MadamSavvy" } } } });
+ assert.match(promiseHtml(schedule(MEASURE), r, { fonts: {} }).html, /<div class="sw">Refunded<\/div><div class="ss">by 31 Oct · no video<\/div>/);
+ const html = promiseHtml(schedule(noted("her word · <no> receipt")), r, { fonts: {} }).html;
+ assert.match(html, /<div class="sw">Refunded<\/div><div class="ss">her word · <no> receipt<\/div>/);
+ assert.doesNotMatch(html, /no video/);
+ // The column's compact form (beside the instruments) draws the same stamp.
+ const col = render({ dial: true, promise: { label: "scale video" } });
+ assert.match(promiseHtml(schedule(noted("her word · no receipt")), col, { fonts: {} }).html, /<div class="ss">her word · no receipt<\/div>/);
+ // The strip (the footage slot, a post's card over the clock): "refunded · <first clause>".
+ const f = render({ promise: { label: "scale video" } });
+ const covered = (m) => schedule(m, { covers: [{ segment: "p", from: 715, to: 739, rects: [{ x: 300, y: 100, width: 700, height: 600 }] }] });
+ assert.match(promiseHtml(covered(MEASURE), f, { fonts: {} }).html, /<span class="no">refunded · no video<\/span>/);
+ const strip = promiseHtml(covered(noted("her word · no receipt")), f, { fonts: {} }).html;
+ assert.match(strip, /<span class="no">refunded · her word<\/span>/);
+ assert.doesNotMatch(strip, /<span class="no">refunded · no video<\/span>/);
+});
+
+test("the lint warns when a note is longer than the stamp's line holds -- never refuses", () => {
+ const manifest = (note) => ({ slug: "m", title: "M", provenance: {}, render: render({}), timeline: [{ type: "clip", id: "c1", video: "v", start: 0, end: 8 }],
+ ledger: [{ id: "o01", population: "promise_outcome", outcome: "refunded", stampNote: note }, { id: "w1", population: "current", stampNote: "x".repeat(60) }] });
+ assert.deepEqual(stampNoteWarnings(manifest("by her account")), []);
+ assert.deepEqual(stampNoteWarnings(manifest("x".repeat(STAMP_NOTE.fit))), []);
+ const long = "refunded in full by her account on 31 Oct";
+ const w = stampNoteWarnings(manifest(long));
+ assert.equal(w.length, 1);
+ assert.match(w[0], new RegExp(`ledger o01\\.stampNote "${long}" is ${long.length} characters: the promise clock's stamp holds about ${STAMP_NOTE.fit}`));
+ const lint = lintManifest(manifest(long), { validators: false });
+ assert.ok(lint.warnings.some((x) => x.startsWith("ledger o01.stampNote")), lint.warnings.join("\n"));
+ assert.ok(!lint.errors.some((x) => /stampNote/.test(x)));
+ assert.ok(!lintManifest(manifest("short"), { validators: false }).warnings.some((x) => /stampNote/.test(x)));
+});
diff --git a/umtool/report-to-video/trail-plan.mjs b/umtool/report-to-video/trail-plan.mjs
@@ -37,7 +37,8 @@ const r2 = (v) => Math.round(v * 100) / 100;
export function trailPoints(measure, { remembered = true } = {}) {
const out = [];
for (const e of measure?.events ?? []) {
- if (!Number.isFinite(e.t) || !Number.isFinite(Number(e.value))) continue;
+ // A row with no number is no point: `Number(null)` and `Number("")` are 0, which drew a 0 lb point (12 Nov).
+ if (!Number.isFinite(e.t) || e.value === null || e.value === undefined || e.value === "" || typeof e.value === "boolean" || !Number.isFinite(Number(e.value))) continue;
if (e.kind !== "stated" && !(remembered && e.kind === "remembered")) continue;
const day = dayNumber(e.asOf ?? e.date);
if (!Number.isFinite(day)) continue;
diff --git a/umtool/report-to-video/trail-plan.test.mjs b/umtool/report-to-video/trail-plan.test.mjs
@@ -116,3 +116,21 @@ test("the page: points pop in where their moment puts them and move with every r
assert.match(validateTrail({ gap: 10 }).join(), /gap must be "auto", 0 \(no breaks\) or 30 to 3650 days/);
assert.match(validateTrail({ bounds: "loose" }).join(), /bounds must be "fit" or "fixed"/);
});
+
+test("a row with no number is no point: a null, missing, empty or non-numeric value never becomes a 0 lb point", () => {
+ const ev = (o) => ({ t: 10, kind: "stated", date: "2026-01-01", row: "w", ...o });
+ const pts = trailPoints({ events: [
+ ev({ t: 1, row: "a", value: 300 }),
+ ev({ t: 2, row: "null", value: null }),
+ ev({ t: 3, row: "missing" }),
+ ev({ t: 4, row: "empty", value: "" }),
+ ev({ t: 5, row: "words", value: "about three hundred" }),
+ ev({ t: 6, row: "bool", value: false }),
+ ev({ t: 7, row: "zero", value: 0 }),
+ ev({ t: 8, row: "text", value: "291.5" }),
+ ev({ t: 9, row: "nan", value: NaN }),
+ ] });
+ // A real 0 and a number written as text are still points.
+ assert.deepEqual(pts.map((p) => [p.row, p.value]), [["a", 300], ["zero", 0], ["text", 291.5]]);
+ assert.deepEqual(pts.map((p) => p.n), [0, 1, 2]);
+});