commit 8ca58f052e5c4023967e933214154f1c8eca2ae3
parent 9d4267540dcb74cd494eb7d9ee42f29187753e82
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 19:26:22 -0400
Merge branch 'main' into r38/x-search
# Conflicts:
# COMMANDS.md
# common/lib/posts-server.ts
# editor/CHANGELOG.md
# editor/app/channels/[slug]/components/SocialChannelPanel.tsx
# editor/app/channels/[slug]/page.tsx
# plans/FACTS.md
# scripts/archilyzer-ops.mjs
Diffstat:
121 files changed, 9900 insertions(+), 519 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md
@@ -48,6 +48,13 @@ each task. Use the archilyzer MCP tools only; run no script for it.
send back with `generate` again (`answers: {"items": [{"id", "label", "why", "score"}]}`, at most six words a
label); the editor reads them as a model's answer and writes `clip-suggestions.json`. Never write that file, a
clip or the manifest yourself: the labels are suggestions the operator sorts by in the clip editor.
+ **And `video-assist`** (a small change to a umtool video project in words — "make the joins 0.15 s with less
+ smear on <dir>"): `generate` with task `video-assist`, `project` and `request` (or `note`, a note on the whole
+ project). It is local in every preset but `api`; routed to code, its answer is the request — the project's look,
+ clips and declared composition params — which you answer in this session and send back with `generate` again
+ (`answers: {"ops": [{"op", "id", "key", "value"}], "reply"}`); the editor checks them as a model's and writes
+ `assist-proposals.json`. They are proposals: the operator applies them in umtool's Ask box. Never edit the
+ manifest or that file yourself.
5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks
for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with
`task` and `route` — only when the operator asks.
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -65,9 +65,9 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer seed` | | the home seeder of last resort: seed the playable torrents of settings.seeder.sites, each only while no other seeder has it (standby otherwise, with hysteresis), TCP + WebRTC, no DHT; runs until interrupted — behind the VPN (docker compose profile `seeder`, docker-compose.seeder.yml) |
| `archilyzer tracker` | `[--host 127.0.0.1] [--port 8000]` | the self-hosted tracker (HTTP + WebSocket, no UDP) for the seeder's torrents only — any other infohash is refused; runs until interrupted |
| `archilyzer duplicates` | `[--threshold N] [--all-durations] [--blocking title\|duration\|both] [--near F] [--tolerance N] …` | on-demand duplicate detection (after index + stats) *(passthrough)* |
-| `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages) *(passthrough)* |
+| `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again) *(passthrough)* |
| `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched |
-| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source *(passthrough)* |
+| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* |
| `archilyzer diarize backfill` | `[--dry-run] [--scope transcribed\|channel:<slug>\|video:<slug>/<id>] [--limit N] [--force] …` | diarize videos whose audio is still on disk *(passthrough)* |
| `archilyzer digest plan` | `[--lane local\|remote] [--channels a,b] [--top N] [--json] [--census] …` | price the digest backfill; writes nothing *(passthrough)* |
| `archilyzer digest validate` | `<channel> [<channel> …]` | score digests already on disk *(passthrough)* |
@@ -125,7 +125,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | |
| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
-| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | |
+| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | |
| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | |
| `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "<branch>", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of <id> in <dir> — archilyzer publish build <id>". `get publish` is the status. | |
| `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` |
@@ -161,8 +161,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `import-page` | import-page imports ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel (platform "webpage"): {"slug", "url"} — a capture's replay URL (web.archive.org/web/<timestamp>/<page>) — or {"slug", "url": <the page>, "at": "YYYYMMDD\[hhmmss\]"} for the capture nearest that date (one CDX lookup). An import-page job on the archive.org queue, at archive.org's pace: the raw (id\_) body, at most 2 MB, html, plain text or JSON only, redirects followed inside the archive only and the FINAL capture recorded; stored under the channel's pages/, read by the first site extractor that claims it (else the generic one), its page records written to the channel's posts. Refused, before any job: no such channel, not a Wayback pages channel, a URL that names no capture, a video (use import-video), an X capture outside an X channel while social.x.visibility is "private". A capture already stored is not fetched again. "dryRun" answers what it would fetch and starts nothing. The log ends with @@import-page {ok, slug, url, captureTs, originalUrl, records, written, updated, unchanged, extractor, already?, error?}. | `pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait` |
| `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` |
| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -> {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -> {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` |
+| `check-post-availability` | check-post-availability checks which of a posts channel's archived posts are gone at their source: {"slug", "mode"?: "stale" (default) \| "unchecked" \| "all", "limit"?: 200}, as a check-post-availability job. A Wayback pages channel's records are checked by their ORIGINAL URL at its own site (never the Wayback Machine), one request per distinct URL through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD is refused or the platform has a "gone" page; available (2xx on the same site), deleted (404/410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page), account\_unavailable (suspended, not shared), error otherwise — with the status. A deleted original means the Wayback copy is the only copy. Verdicts go to posts-availability.json. | `pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait` |
+| `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now, with archive.org's S3 keys): {"url", "slug"?, "dryRun"?}. A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. Refused, before any job: no keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait` |
| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
-| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait` |
+| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` |
| `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -> {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` |
| `wayback-import` | wayback-import imports chosen rows of a Wayback pages channel's scan, one import-page job per row (the capture the content was first listed at), queued on archive.org's queue: {"slug", "keys"?: \["<digest> <url>", ...\]} or a range — "year"? (first seen), "prefix"? ("host/path/"), "q"? (text in the URL), "show"? (all \| new \| not-imported \| imported) — and "dryRun"? -> {ok, slug, dryRun, chosen, queued: \[{key, url, jobId?}\], skipped: \[{key, why}\], left}. Rows already imported are skipped; at most 500 are queued a call (left: how many remain). The Captures tab's Import selected and Import all in range. | `pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}'` |
| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -59,6 +59,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
|---|---|---|---|
| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs |
| `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts |
+| `ARCHIVE_ORG_S3_ACCESS` | unset (the S3 key file is read instead) | archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why. | common/lib/waybackPages/savePageNow-server.ts |
+| `ARCHIVE_ORG_S3_SECRET` | unset (the S3 key file is read instead) | archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above). | common/lib/waybackPages/savePageNow-server.ts |
| `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts |
| `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts |
| `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts |
@@ -213,6 +215,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_WORKERS` | 1 | How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker. | editor/playwright.config.ts (editor/e2e/servers.ts) |
| `E2E_SERIAL_LAST` | — | Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole. | editor/playwright.config.ts |
| `E2E_BUILD_CHECKED` | — | Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again. | editor/playwright.config.ts, umtool/playwright.config.ts |
+| `E2E_FORUM_FIXTURE_DIR` | unset (the forum fetcher opens its headless browser) | A directory of SYNTHETIC saved thread pages (`<dir>/<threadId>/page-<N>.html`) the forum-thread fetcher reads in place of a browser, with no pause between pages. The editor's e2e server names one in each slot's test data (`test-transcripts/.forum-fixture`; `forum-resume.spec`), and nothing else sets it. | common/social/forumFixtureLoader.ts (the forum-thread fetcher) |
| `E2E_QUEUE` | on | `0` skips the machine-global e2e queue (the port check still runs). | scripts/queue-lock.mjs |
| `E2E_PORT_CHECK` | on | `0` skips the pre-run check that the suite's ports are free. | scripts/queue-lock.mjs |
| `E2E_QUEUE_TIMEOUT` | wait forever | Seconds to wait for the queue before giving up. | scripts/queue-lock.mjs |
@@ -234,7 +237,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
-| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts |
+| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts |
| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -134,18 +134,60 @@ pnpm ops wayback-import --json '{"slug":"example-pages","year":"2014","show":"no
same pace. Off by default: nothing crawls a host unless its channel opts in.
- Offline, without the editor: `pnpm archilyzer wayback scan <slug> --dry-run`.
+### Is the original still up? Save it now; find a gone page's copy
+
+```sh
+pnpm ops check-post-availability --json '{"slug":"old-blog"}' --wait
+pnpm ops save-page-now --json '{"url":"https://blog.example/still-up.html","slug":"old-blog","dryRun":true}'
+pnpm ops save-page-now --json '{"url":"https://blog.example/still-up.html","slug":"old-blog"}' --wait
+pnpm ops find-copy --json '{"article":"<article>","pages":true,"dryRun":true}' --wait
+pnpm ops find-copy --json '{"siteId":"<site>","pages":true,"channel":"old-blog"}' --wait
+```
+
+- **Originals** (the channel page's **Check originals**, `check-post-availability`): each page record's ORIGINAL
+ URL asked at its own site — never the Wayback Machine — one request per distinct URL, through the editor's web
+ pacer (3 s apart). `available` (a 2xx on the same site), `deleted` (404/410, or X's, Tumblr's, Google Docs' or
+ YouTube's "does not exist" page), `account_unavailable` (suspended, not shared), `error` otherwise, with the
+ status. A deleted original means the Wayback copy is the only copy; the record reads as deleted everywhere a
+ deleted post does (`posts-availability.json`, merged by the index).
+- **Save Page Now** ("Ask the Wayback Machine to capture this now", on the channel page: any URL, or a record whose
+ original is still up): archive.org captures the page alone, the job waits for it, then imports the capture
+ into the channel. It needs archive.org's S3 keys (archive.org/account/s3.php): `ARCHIVE_ORG_S3_ACCESS` and
+ `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or two such lines in the mode-600 file
+ `settings.archiveOrg.s3KeyFile` names (default `~/.config/archilyzer/archive-org.env`). Without them the button is
+ off and says why. One capture at a time, on archive.org's queue. Other code starts one with
+ `startSavePageNowJob({url, slug})` (`common/controller/savePageNow.ts`).
+- **find-copy, page mode** (`"pages": true`): every `page` citation of a report whose original is gone gets the
+ Wayback capture nearest the citation's date imported into the Wayback pages channel named (`"channel"`), else
+ the one whose targets cover the page; a cited page record whose original is gone has its capture imported again
+ only when its body is not stored. A live page is left (save it now instead). The log's `@@find-copy` names, per
+ citation, the record to cite (`pointTo`) and the citation as a `post` citation of it (`as`); the report itself
+ is not rewritten. Dry run first: it asks the same paced questions and imports nothing.
+
## Fetch and capture posts
```sh
pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'
pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait
pnpm ops fetch-posts --json '{"slug":"example-x","older":true}' --wait
+pnpm ops fetch-posts --json '{"slug":"example-forum-thread","pages":20,"retryOnBlock":true}' --wait
pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait
```
- An X, Bluesky or XenForo URL makes a social channel (its handle derived from the URL). `"older": true` walks back below the oldest
archived post and resumes from its saved place; `"full": true` re-walks the timeline.
- `capture-posts` saves a screenshot and the attached media of named posts (and a linked X Article).
+- A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page
+ to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps
+ the pages that hold anything new (an all-held page is stepped past uncounted), and a capped catch-up never moves
+ the history position. **Full re-walk** (`"full": true`) re-reads every page, the last to page 1: edited posts are
+ updated, posts no page shows any more are counted in the log (kept, not marked). The channel page's status line
+ says where both stand (`pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)`). The
+ history position is re-derived from the archived posts' pages every run, so a lost one heals.
+- A browser check that will not clear, or a refusal (403/429), stops a forum walk. `"retryOnBlock": {"minutes": 30,
+ "max": 12}` waits it out and runs again (max tries in all; never a captcha or a login); the channel page's
+ **Retry after a block** sets the Fetch posts button's default (`settings.social.xenforo.retryOnBlock`), and
+ `"retryOnBlock": true` uses it from `pnpm ops`.
- Forum pages saved from a browser: `pnpm archilyzer posts import-html <slug> <file-or-dir> --dry-run`.
- Which archived posts were deleted at the source: `pnpm archilyzer posts check --slug <slug>`.
@@ -265,6 +307,7 @@ pnpm ops report-draft --json '{"task":"revise-report","article":"example-article
pnpm ops report-draft --json '{"task":"revise-video","article":"example-article","iteration":2,"feedback":"Trim the opening clip."}' --wait
pnpm ops report-draft --json '{"task":"narrate","article":"example-article","iteration":3}' --wait
pnpm ops report-draft --json '{"task":"sweep","article":"example-article","copyOf":1,"model":"qwen3:8b"}'
+pnpm ops report-draft --json '{"task":"video-assist","project":"/abs/project/dir","request":"make the joins 0.15 s with less smear","dryRun":true}'
pnpm ops job cancel <jobId>
pnpm archilyzer reports iterations example-article
umtool chain example-article 3
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -168,13 +168,14 @@ Default: `"when-required"`
## `social`
-Per-platform settings of the social posts. Today two keys, both X's, both chosen in the X account session section of /settings: where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`). See common/social/xCookieSource.ts.
+Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.
#### `social`
| Key | Default | Description |
|---|---|---|
| `x` | `{}` | X / Twitter. See `social.x` below. |
+| `xenforo` | absent | Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set. |
#### `social.x`
@@ -183,6 +184,14 @@ Per-platform settings of the social posts. Today two keys, both X's, both chosen
| `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. |
| `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. |
+#### `social.xenforo`
+
+Per entry — each entry spells its own values.
+
+| Key | Description |
+|---|---|
+| `retryOnBlock` | `{ "minutes": N, "max": M }` — what a forum thread's Fetch posts button does when the forum serves a browser check that will not clear, or refuses a page (403/429): the job waits N minutes and runs again, M tries in all (the first included; minutes 5–1440, tries 1–48). A captcha or a login wall is never retried — it needs a person. ABSENT (the default): off, the job stops at the block. Set on the forum channel page (Retry after a block); `fetch-posts` takes its own `retryOnBlock`. common/lib/forumWalk.ts. |
+
Default:
```json
@@ -812,6 +821,7 @@ How archive.org files are fetched (controller/archiveOrgDownload.ts). Over BitTo
| `maxPeers` | `30` | Most peers per torrent (aria2c --bt-max-peers). Clamped to [1, 500]; default 30. |
| `maxDownloadKiBps` | `0` | Download rate cap for a torrent fetch, KiB/s (aria2c --max-overall-download-limit). 0 = unlimited. |
| `maxUploadKiBps` | `0` | Upload rate cap while downloading and seeding, KiB/s (aria2c --max-overall-upload-limit). 0 = unlimited. |
+| `s3KeyFile` | `"~/.config/archilyzer/archive-org.env"` | Release 37: the file holding archive.org's S3 keys for Save Page Now ("Ask the Wayback Machine to capture this now"): two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the editor's environment win over the file. No keys: Save Page Now is off, and says why. |
Default:
@@ -823,7 +833,8 @@ Default:
"stallMinutes": 5,
"maxPeers": 30,
"maxDownloadKiBps": 0,
- "maxUploadKiBps": 0
+ "maxUploadKiBps": 0,
+ "s3KeyFile": "~/.config/archilyzer/archive-org.env"
}
```
@@ -973,7 +984,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| Key | Default | Description |
|---|---|---|
-| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. |
+| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task but the video assistant's, which stays local), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. |
| `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). |
| `models` | object — see below | The model each route runs (below). |
| `caps` | object — see below | The spend caps in USD (below). |
@@ -1008,6 +1019,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. |
| `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. |
| `clips-suggest` | `"local"` | The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`). |
+| `video-assist` | `"local"` | The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words ("make the joins 0.15 s with less smear") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). |
| `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. |
#### `generation.models`
@@ -1114,7 +1126,8 @@ Default:
"social": "local",
"verdicts": "local",
"frames": "api",
- "clips-suggest": "local"
+ "clips-suggest": "local",
+ "video-assist": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -833,7 +833,7 @@ export const COMMANDS: Command[] = [
script(["duplicates"], "duplicate-shorts.ts",
"[--threshold N] [--all-durations] [--blocking title|duration|both] [--near F] [--tolerance N] … on-demand duplicate detection (after index + stats)", 8192),
script(["posts", "fetch"], "fetch-posts.ts",
- "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages)"),
+ "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"),
{
path: ["posts", "import-html"],
usage:
@@ -854,7 +854,7 @@ export const COMMANDS: Command[] = [
},
},
script(["posts", "check"], "check-post-availability.ts",
- "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source"),
+ "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site)"),
script(["diarize", "backfill"], "diarize-backfill.ts",
"[--dry-run] [--scope transcribed|channel:<slug>|video:<slug>/<id>] [--limit N] [--force] … diarize videos whose audio is still on disk"),
script(["digest", "plan"], "digest-plan.ts",
diff --git a/common/bin/fetch-posts.ts b/common/bin/fetch-posts.ts
@@ -3,11 +3,19 @@
//
// pnpm --filter yt-dlp-transcript-common exec tsx bin/fetch-posts.ts \
// --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]
+// [--retry-on-block | --retry-minutes N --retry-tries M]
//
// --pages caps how many pages one run reads, for a source read page by page (a
// forum thread: its latest N pages, newest first; the next run continues where
// this one stopped).
//
+// A forum thread keeps two positions (lib/forumWalk.ts): a run catches up from
+// the last page, then continues the history where it stopped.
+//
+// --retry-minutes N --retry-tries M: a challenge or refusal page stops the
+// walk; wait N minutes and run again, M tries in all. --retry-on-block uses
+// settings.social.xenforo.retryOnBlock (nothing when unset).
+//
// --full re-walks the account's whole history instead of stopping at the
// stored watermark. New posts are still deduped against the posts-archive, so
// it repairs a gap rather than creating duplicates.
@@ -25,12 +33,13 @@ import { getPaths } from "../lib/paths";
import { getSettings } from "../lib/settings";
import { fetchPosts } from "../controller/fetchPosts";
import { parseFlags } from "./_parseFlags";
+import { retryOnBlockProblem, type RetryOnBlock } from "../lib/forumWalk";
const flags = parseFlags(process.argv.slice(2));
const slug = flags.slug;
if (!slug) {
console.error(
- "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]",
+ "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]",
);
process.exit(2);
}
@@ -47,6 +56,19 @@ const pages =
? Math.floor(pagesRaw)
: undefined;
+let retryOnBlock: RetryOnBlock | undefined;
+if (flags["retry-minutes"] !== undefined || flags["retry-tries"] !== undefined) {
+ retryOnBlock = { minutes: Number(flags["retry-minutes"]), max: Number(flags["retry-tries"]) };
+ const problem = retryOnBlockProblem(retryOnBlock);
+ if (problem) {
+ console.error(`${problem} (--retry-minutes and --retry-tries go together)`);
+ process.exit(2);
+ }
+} else if (flags["retry-on-block"] === "true") {
+ retryOnBlock = getSettings().social.xenforo?.retryOnBlock;
+ if (!retryOnBlock) console.log("No retry after a block is set (settings.social.xenforo.retryOnBlock); a block stops the run.");
+}
+
fetchPosts({
paths: getPaths(),
slug,
@@ -58,6 +80,7 @@ fetchPosts({
force: flags.force === "true",
limit,
pages,
+ ...(retryOnBlock ? { retryOnBlock } : {}),
onLog: (line) => console.log(line),
})
.then((result) => {
diff --git a/common/controller/checkPageAvailability.test.ts b/common/controller/checkPageAvailability.test.ts
@@ -0,0 +1,152 @@
+// Release 37 S5: check-post-availability on a Wayback pages channel — each
+// record's ORIGINAL URL asked at its own site (a stub fetch behind a web
+// pacer), ONE request per distinct URL however many records share it, the
+// verdicts and their status/reason in posts-availability.json, history only
+// on a change, modes and limits counted in URLs. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/checkPageAvailability.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Post } from "../lib/posts";
+import { readPostAvailability, upsertPosts } from "../lib/posts-server";
+import { WebPacer } from "../lib/web/pacer";
+import { checkPostAvailability } from "./checkPostAvailability";
+import { selectUrlsToCheck } from "./checkPageAvailability";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "check-pages-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT } as unknown as Paths;
+
+function record(slug: string, id: string, originalUrl: string, captureTs: string): Post {
+ return {
+ id,
+ slug: `${slug}/${id}`,
+ channelSlug: slug,
+ author: "blog.example",
+ createdAt: "2014-03-05T12:00:00.000Z",
+ uploadDate: "20140305",
+ text: `the words of ${id}`,
+ url: originalUrl,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page: {
+ originalUrl,
+ captureTs,
+ waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`,
+ rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`,
+ kind: "generic",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+ };
+}
+
+async function pagesChannel(slug: string, posts: Post[]) {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ name: slug,
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ }),
+ );
+ await upsertPosts(dir, posts);
+ return dir;
+}
+
+function stub(statusOf: (url: string) => number) {
+ const sent: string[] = [];
+ const pacer = new WebPacer(
+ {
+ fetch: async (url, init) => {
+ sent.push(`${init.method} ${url}`);
+ return new Response(null, { status: statusOf(url) });
+ },
+ sleep: async () => {},
+ },
+ { minGapMs: 0, maxAttempts: 1 },
+ );
+ return { sent, pageCheck: { pacer, resolve: async () => ["93.184.216.34"] } };
+}
+
+const GONE = "https://blog.example/2014/gone.html";
+const LIVE = "https://blog.example/2014/live.html";
+const DOWN = "https://blog.example/2014/down.html";
+
+test("one request per original URL; every record of it gets the verdict, with its status and reason", async () => {
+ const dir = await pagesChannel("old-blog", [
+ record("old-blog", "20140305120000-aaaa", GONE, "20140305120000"),
+ record("old-blog", "20150611090000-aaaa", GONE, "20150611090000"),
+ record("old-blog", "20140101000000-bbbb", LIVE, "20140101000000"),
+ record("old-blog", "20140202000000-cccc", DOWN, "20140202000000"),
+ ]);
+ const s = stub((url) => (url === GONE ? 404 : url === DOWN ? 500 : 200));
+ const lines: string[] = [];
+ const r = await checkPostAvailability({ paths, slug: "old-blog", pageCheck: s.pageCheck, onLog: (l) => lines.push(l) });
+ assert.equal(r.ok, true);
+ assert.deepEqual(s.sent.sort(), [`HEAD ${DOWN}`, `HEAD ${GONE}`, `HEAD ${LIVE}`]);
+ assert.equal(r.checked, 4);
+ assert.deepEqual(r.newlyDeleted.sort(), ["20140305120000-aaaa", "20150611090000-aaaa"]);
+ const av = await readPostAvailability(dir);
+ assert.deepEqual(
+ [av["20140305120000-aaaa"]!.availability, av["20140305120000-aaaa"]!.status, av["20140305120000-aaaa"]!.reason],
+ ["deleted", 404, "HTTP 404"],
+ );
+ assert.equal(av["20150611090000-aaaa"]!.availability, "deleted");
+ assert.equal(av["20140101000000-bbbb"]!.availability, "available");
+ // An error is an error, never a deletion.
+ assert.deepEqual([av["20140202000000-cccc"]!.availability, av["20140202000000-cccc"]!.status], ["error", 500]);
+ assert.ok(lines.some((l) => /3 of 3 original URL\(s\) \(4 page record\(s\)\)/.test(l)));
+ assert.ok(lines.some((l) => /newly GONE/.test(l)));
+
+ // Again, the down page back up: history appended for the change only.
+ const s2 = stub((url) => (url === GONE ? 404 : 200));
+ await checkPostAvailability({ paths, slug: "old-blog", mode: "all", pageCheck: s2.pageCheck });
+ const av2 = await readPostAvailability(dir);
+ assert.equal(av2["20140202000000-cccc"]!.availability, "available");
+ assert.deepEqual(av2["20140202000000-cccc"]!.history?.map((h) => h.availability), ["error"]);
+ assert.deepEqual(av2["20140305120000-aaaa"]!.history ?? [], []);
+
+ // `unchecked`: nothing left to ask.
+ const s3 = stub(() => 200);
+ const r3 = await checkPostAvailability({ paths, slug: "old-blog", mode: "unchecked", pageCheck: s3.pageCheck });
+ assert.equal(r3.checked, 0);
+ assert.equal(s3.sent.length, 0);
+});
+
+test("the limit counts URLs, least recently checked first", () => {
+ const groups = new Map([
+ ["https://a.example/", ["a1", "a2"]],
+ ["https://b.example/", ["b1"]],
+ ["https://c.example/", ["c1"]],
+ ]);
+ const av = {
+ a1: { availability: "available" as const, checkedAt: "2026-10-01T00:00:00Z" },
+ a2: { availability: "available" as const, checkedAt: "2026-10-02T00:00:00Z" },
+ b1: { availability: "available" as const, checkedAt: "2026-09-01T00:00:00Z" },
+ };
+ assert.deepEqual(selectUrlsToCheck(groups, av, "stale", 2), ["https://c.example/", "https://b.example/"]);
+ assert.deepEqual(selectUrlsToCheck(groups, av, "unchecked", 5), ["https://c.example/"]);
+ assert.deepEqual(selectUrlsToCheck(groups, av, "all", 5).length, 3);
+});
+
+test("a channel with no page records checks nothing", async () => {
+ await pagesChannel("empty-pages", []);
+ const s = stub(() => 200);
+ const r = await checkPostAvailability({ paths, slug: "empty-pages", pageCheck: s.pageCheck });
+ assert.deepEqual([r.ok, r.checked, s.sent.length], [true, 0, 0]);
+});
diff --git a/common/controller/checkPageAvailability.ts b/common/controller/checkPageAvailability.ts
@@ -0,0 +1,101 @@
+// IS EACH PAGE RECORD'S ORIGINAL STILL UP? (release 37 S5) — the Wayback
+// pages channel's branch of check-post-availability
+// (./checkPostAvailability.ts). A page record's availability is the state of
+// the ORIGINAL URL it was captured from, never the Wayback Machine's:
+// lib/waybackPages/liveness-server.ts checkOriginalUrl, through the process's
+// web pacer (one request at a time, 3 s apart, 429/503 backed off).
+//
+// ONE REQUEST PER DISTINCT URL: a capture split into many records (an X
+// profile's tweets, a Tumblr index's posts) and the versions of one page share
+// an original URL, and each of them gets the URL's verdict. `limit` counts
+// URLs. The verdicts land in the same sidecar every post channel uses
+// (posts-availability.json, mergePostAvailability: history appended only when
+// a verdict changes), with the answer's status and reason; the index merges
+// them in, so a record whose original is gone is `isDeleted` — the Wayback
+// copy is then the only copy.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { mergePostAvailability, readAllPosts, readPostAvailability, writePostAvailability } from "../lib/posts-server";
+import type { PostAvailability, PostAvailabilityMap } from "../lib/posts";
+import { groupByOriginalUrl, type OriginalCheck } from "../lib/waybackPages/liveness";
+import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import type { CheckPostAvailabilityMode, CheckPostAvailabilityResult } from "./checkPostAvailability";
+
+// Which original URLs to ask this run: `stale` (the default) the
+// never-checked first, then the least recently checked (by the oldest check
+// among the URL's records); `unchecked` only URLs with a record never
+// checked; `all` every URL. At most `limit`.
+export function selectUrlsToCheck(
+ groups: ReadonlyMap<string, readonly string[]>,
+ availability: PostAvailabilityMap,
+ mode: CheckPostAvailabilityMode,
+ limit: number,
+): string[] {
+ const oldest = (ids: readonly string[]) =>
+ ids.reduce((min, id) => {
+ const at = availability[id]?.checkedAt ?? "";
+ return at < min ? at : min;
+ }, "");
+ let urls = [...groups.keys()];
+ if (mode === "unchecked") urls = urls.filter((u) => groups.get(u)!.some((id) => !availability[id]));
+ if (mode === "stale") {
+ const at = new Map(urls.map((u) => [u, oldest(groups.get(u)!)]));
+ urls.sort((a, b) => at.get(a)!.localeCompare(at.get(b)!));
+ }
+ return urls.slice(0, Math.max(0, limit));
+}
+
+export async function checkPageAvailability(opts: {
+ paths: Paths;
+ slug: string;
+ mode: CheckPostAvailabilityMode;
+ limit: number;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ // Tests: the pacer, the fence's resolver, loopback allowed.
+ check?: CheckOriginalOptions;
+ now?: () => Date;
+}): Promise<CheckPostAvailabilityResult & { urls?: OriginalCheck[] }> {
+ const log = (line: string) => opts.onLog?.(line);
+ const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
+ const empty = { checked: 0, deleted: 0, newlyDeleted: [] as string[], changed: 0, remaining: 0 };
+ const records = (await readAllPosts(channelRoot)).filter((p) => p.page);
+ if (records.length === 0) return { ok: true, ...empty };
+ const availability = await readPostAvailability(channelRoot);
+ const groups = groupByOriginalUrl(records);
+ const batch = selectUrlsToCheck(groups, availability, opts.mode, opts.limit);
+ if (batch.length === 0) {
+ log(`Nothing to check for ${opts.slug} (mode: ${opts.mode}).`);
+ return { ok: true, ...empty };
+ }
+ log(
+ `Checking ${batch.length} of ${groups.size} original URL(s) (${records.length} page record(s)) of ${opts.slug} ` +
+ `at their own sites, not the Wayback Machine (mode: ${opts.mode}).`,
+ );
+ const observations = new Map<string, PostAvailability>();
+ const details = new Map<string, { status: number | null; reason: string }>();
+ const urls: OriginalCheck[] = [];
+ for (const url of batch) {
+ if (opts.signal?.aborted) break;
+ const verdict = await checkOriginalUrl(url, { ...opts.check, ...(opts.signal ? { signal: opts.signal } : {}) });
+ urls.push(verdict);
+ const ids = groups.get(url)!;
+ for (const id of ids) {
+ observations.set(id, verdict.availability);
+ details.set(id, { status: verdict.status, reason: verdict.reason });
+ }
+ log(` ${url}: ${verdict.availability} — ${verdict.reason}${ids.length > 1 ? ` (${ids.length} records)` : ""}`);
+ }
+ const checkedAt = (opts.now?.() ?? new Date()).toISOString();
+ const { map, newlyDeleted, changed } = mergePostAvailability(availability, observations, checkedAt, details);
+ await writePostAvailability(channelRoot, map);
+ const deleted = Object.values(map).filter((r) => r.availability === "deleted").length;
+ const remaining = records.filter((r) => !map[r.id]).length;
+ if (newlyDeleted.length > 0) {
+ log(`${newlyDeleted.length} page record(s) whose original is newly GONE (the Wayback copy is the only copy): ${newlyDeleted.slice(0, 10).join(", ")}${newlyDeleted.length > 10 ? ` (+${newlyDeleted.length - 10} more)` : ""}`);
+ }
+ log(`Done: ${urls.length} URL(s) checked (${observations.size} record(s)), ${changed} changed, ${deleted} gone overall, ${remaining} never checked.`);
+ if (opts.signal?.aborted) log("Cancelled; the rest are left for a later run.");
+ return { ok: true, checked: observations.size, deleted, newlyDeleted, changed, remaining, urls };
+}
diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts
@@ -37,6 +37,9 @@ import "../social/xenforoFetcher";
import "../social/xGalleryDlFetcher";
import "../social/xPlaywrightFetcher";
import "../social/xNitterFetcher";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import type { CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import { checkPageAvailability } from "./checkPageAvailability";
export type CheckPostAvailabilityMode = "stale" | "unchecked" | "all";
@@ -58,6 +61,9 @@ export type CheckPostAvailabilityOptions = {
limit?: number;
onLog?: (line: string) => void;
signal?: AbortSignal;
+ // A Wayback pages channel's check (release 37 S5): tests pass the pacer,
+ // the fence's resolver and loopback.
+ pageCheck?: CheckOriginalOptions;
};
export type CheckPostAvailabilityResult = {
@@ -119,6 +125,19 @@ export async function checkPostAvailability(
if (!isSocialChannel(config)) {
return { ok: false, ...empty, error: `${slug} is not a social channel.` };
}
+ // A Wayback pages channel (release 37 S5): each record's ORIGINAL URL,
+ // asked at its own site — no fetcher, never the Wayback Machine.
+ if (isWaybackPagesChannel(config)) {
+ return checkPageAvailability({
+ paths,
+ slug,
+ mode,
+ limit,
+ ...(onLog ? { onLog } : {}),
+ ...(signal ? { signal } : {}),
+ ...(opts.pageCheck ? { check: opts.pageCheck } : {}),
+ });
+ }
const fetcher = resolveSocialFetcher(config.postFetcher, config.url);
if (!fetcher) {
diff --git a/common/controller/fetchForumPosts.test.ts b/common/controller/fetchForumPosts.test.ts
@@ -0,0 +1,195 @@
+// fetchPosts over a FORUM THREAD (release 37 lane G), end to end through the
+// real XenForo fetcher reading SYNTHETIC saved pages (E2E_FORUM_FIXTURE_DIR,
+// social/forumFixtureLoader.ts): no browser, no network. The two positions in
+// posts-state.json, an old single cursor migrating, the full re-walk's edits,
+// and the retry on a block over a fake clock.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchForumPosts.test.ts
+
+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";
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchforum-"));
+const FIXTURES = path.join(ROOT, "forum-fixture");
+// getPaths() is resolved lazily and cached: set before the first call.
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.E2E_FORUM_FIXTURE_DIR = FIXTURES;
+
+const { THREAD_URL, CHALLENGE_PAGE } = await import("../social/__fixtures__/xenforoPages");
+const { FakeForumThread, FAKE_THREAD_ID } = await import("../social/__fixtures__/fakeForumThread");
+const { fetchPosts, sleepOrStop } = await import("./fetchPosts");
+const { readAllPosts, readPostFetchState, readSeenPostIds, writePostFetchState } = await import("../lib/posts-server");
+const { getPaths } = await import("../lib/paths");
+
+let n = 0;
+async function channel(): Promise<{ slug: string; root: string }> {
+ const slug = `forum-${++n}`;
+ const root = path.join(ROOT, "transcripts", "channels", slug);
+ await mkdir(root, { recursive: true });
+ await writeFile(
+ path.join(root, "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "xenforo",
+ postFetcher: "xenforo-thread",
+ socialHandle: "the-teapot-collectors-thread.4242",
+ name: "Teapot thread",
+ url: THREAD_URL,
+ }),
+ );
+ return { slug, root };
+}
+
+async function run(slug: string, over: Partial<Parameters<typeof fetchPosts>[0]> = {}) {
+ const log: string[] = [];
+ const result = await fetchPosts({ paths: getPaths(), slug, settings: {}, onLog: (l) => log.push(l), ...over });
+ return { result, log: log.join("\n") };
+}
+
+test("a capped catch-up leaves the history position alone; posts-state.json keeps both, and no cursor", async () => {
+ const { slug, root } = await channel();
+ const t = new FakeForumThread(30); // 10 pages
+ await t.writeTo(FIXTURES);
+ const first = await run(slug, { pages: 5 });
+ assert.equal(first.result.ok, true);
+ let state = await readPostFetchState(root);
+ assert.equal(state?.cursor, undefined);
+ assert.deepEqual(state?.forum, { newestPage: 10, oldestPageReached: 6, historyPage: 5, newestPostId: "9030" });
+
+ t.add(9);
+ await t.writeTo(FIXTURES);
+ const capped = await run(slug, { pages: 2 });
+ assert.match(capped.log, /caught up to page 10; history resumes at page 5/);
+ state = await readPostFetchState(root);
+ assert.equal(state?.forum?.historyPage, 5);
+ assert.equal(state?.forum?.catchUpPage, 11);
+
+ const rest = await run(slug);
+ assert.equal(rest.result.complete, true);
+ state = await readPostFetchState(root);
+ assert.equal(state?.forum?.complete, true);
+ assert.equal(state?.forum?.catchUpPage, undefined);
+ assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort());
+});
+
+test("an old state's single cursor migrates: read once as the history position, healed from the posts, then dropped", async () => {
+ const { slug, root } = await channel();
+ const t = new FakeForumThread(30);
+ await t.writeTo(FIXTURES);
+ // An old fetch read pages 10–5 (posts 13–30) and then a capped catch-up
+ // overwrote the cursor with its own page (9).
+ await run(slug, { pages: 6 });
+ await writePostFetchState(root, { lastFetchedAt: "2026-10-20T00:00:00.000Z", cursor: "9", lastFetchedCount: 3 });
+ const res = await run(slug);
+ assert.match(res.log, /Read the old single resume point \(page 9\) as the history position\./);
+ assert.match(res.log, /history resumes at page 6/);
+ assert.equal(res.result.complete, true);
+ const state = await readPostFetchState(root);
+ assert.equal(state?.cursor, undefined, "the old cursor is gone");
+ assert.equal(state?.forum?.complete, true);
+ assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort());
+});
+
+test("a full re-walk re-reads every page and appends a newer record of an edited post", async () => {
+ const { slug, root } = await channel();
+ const t = new FakeForumThread(9);
+ await t.writeTo(FIXTURES);
+ await run(slug);
+ // Post 9005 edited since; post 9002 deleted.
+ t.posts = t.posts.map((p) => (p.id === 9005 ? { ...p, body: "Edited words.", editedTs: p.ts + 60 } : p));
+ t.remove([9002]);
+ await t.writeTo(FIXTURES);
+ const res = await run(slug, { full: true });
+ assert.equal(res.result.ok, true);
+ assert.equal(res.result.updated, 1, "the edit, not the posts renumbered after the deletion");
+ assert.match(res.log, /a full re-walk/);
+ assert.match(res.log, /1 archived post\(s\) were on no page of the thread .*: 9002\. Kept as archived/);
+ const posts = await readAllPosts(root);
+ const edited = posts.filter((p) => p.id === "9005");
+ assert.match(edited[edited.length - 1].text, /Edited words\./);
+ assert.ok(posts.some((p) => p.id === "9002"), "a post no page shows is kept");
+ const state = await readPostFetchState(root);
+ assert.equal(state?.forum?.complete, true);
+});
+
+test("retry on a block: a challenge page is waited out, `minutes` on the fake clock, and the walk resumes", async () => {
+ const { slug, root } = await channel();
+ const t = new FakeForumThread(15); // 5 pages
+ await t.writeTo(FIXTURES);
+ const blocked = path.join(FIXTURES, FAKE_THREAD_ID, "page-3.200.html");
+ await writeFile(blocked, CHALLENGE_PAGE);
+ const waits: number[] = [];
+ const res = await run(slug, {
+ retryOnBlock: { minutes: 30, max: 12 },
+ sleep: async (ms) => {
+ waits.push(ms);
+ // Two waits, then the check clears.
+ if (waits.length === 2) await rm(blocked);
+ return "slept";
+ },
+ });
+ assert.deepEqual(waits, [30 * 60_000, 30 * 60_000]);
+ assert.match(res.log, /Waiting 30 min after a challenge page, try 2\/12\./);
+ assert.match(res.log, /Waiting 30 min after a challenge page, try 3\/12\./);
+ assert.equal(res.result.ok, true);
+ assert.equal(res.result.complete, true);
+ assert.equal(res.result.written, 15);
+ assert.deepEqual([...(await readSeenPostIds(root))].sort(), t.ids().sort());
+});
+
+test("retry on a block gives up after `max` tries, never retries a captcha, and a drain during the wait ends cleanly", async () => {
+ const { slug } = await channel();
+ const t = new FakeForumThread(6);
+ await t.writeTo(FIXTURES);
+ const p2 = path.join(FIXTURES, FAKE_THREAD_ID, "page-2.403.html");
+ await writeFile(p2, "<html><body>Access denied</body></html>");
+ const waits: number[] = [];
+ const res = await run(slug, {
+ retryOnBlock: { minutes: 5, max: 3 },
+ sleep: async (ms) => {
+ waits.push(ms);
+ return "slept";
+ },
+ });
+ assert.equal(waits.length, 2, "three tries in all");
+ assert.equal(res.result.ok, false);
+ assert.equal(res.result.block, "blocked");
+ assert.match(res.log, /Still refused after 3 tries; stopped\./);
+
+ const drained = await run(slug, { retryOnBlock: { minutes: 5, max: 3 }, sleep: async () => "drained" });
+ assert.equal(drained.result.ok, true);
+ assert.equal(drained.result.drained, true);
+ await rm(p2);
+
+ // A captcha needs a person: no wait at all.
+ const { slug: s2 } = await channel();
+ const p1 = path.join(FIXTURES, FAKE_THREAD_ID, "page-2.200.html");
+ await writeFile(p1, '<html><body><div class="h-captcha"></div></body></html>');
+ const none: number[] = [];
+ const cap = await run(s2, { retryOnBlock: { minutes: 5, max: 3 }, sleep: async (ms) => (none.push(ms), "slept") });
+ assert.equal(none.length, 0);
+ assert.equal(cap.result.block, "captcha");
+ await rm(p1);
+
+ // Bounds are the controller's too.
+ const bad = await run(s2, { retryOnBlock: { minutes: 1, max: 3 } });
+ assert.match(bad.result.error ?? "", /minutes/);
+ const older = await run(s2, { retryOnBlock: { minutes: 30, max: 3 }, older: true });
+ assert.match(older.result.error ?? "", /Retry on a block/);
+});
+
+test("the real wait ends on a cancel or a drain", async () => {
+ const cancel = new AbortController();
+ const p = sleepOrStop(60_000, cancel.signal);
+ cancel.abort();
+ assert.equal(await p, "aborted");
+ const drain = new AbortController();
+ const q = sleepOrStop(60_000, undefined, drain.signal);
+ drain.abort();
+ assert.equal(await q, "drained");
+ assert.equal(await sleepOrStop(1), "slept");
+});
diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts
@@ -27,6 +27,8 @@ import {
oldestPostCreatedAt,
readPostFetchState,
readSeenPostIds,
+ readAllPosts,
+ upsertPosts,
writePostFetchState,
writePosts,
type OlderBackfillPosition,
@@ -36,9 +38,17 @@ import {
import {
handleFromAccountUrl,
resolveSocialFetcher,
+ type PostFetchResult,
type SocialFetcher,
} from "../social/fetchers";
import {
+ deriveForumWalk,
+ forumWalkStartLine,
+ retryOnBlockProblem,
+ type ForumWalkState,
+ type RetryOnBlock,
+} from "../lib/forumWalk";
+import {
firstOlderWindow,
isUtcDay,
olderFloorDay,
@@ -62,6 +72,8 @@ import {
type XLoginSettings,
} from "../social/xBrowserLogin";
+type ChannelConfigRead = NonNullable<Awaited<ReturnType<typeof readChannelConfig>>>;
+
export type FetchPostsOptions = {
paths: Paths;
slug: string;
@@ -102,6 +114,14 @@ export type FetchPostsOptions = {
// The job's Drain: the fetch stops at its next resume point and keeps it,
// and the run ends as a success, not a failure.
drain?: AbortSignal;
+ // A challenge or refusal page stops the walk; wait `minutes` and run again,
+ // up to `max` tries in all (the first included). A forum thread's Fetch
+ // posts button passes `settings.social.xenforo.retryOnBlock`. Not with
+ // `older`.
+ retryOnBlock?: RetryOnBlock;
+ // The retry's wait (tests pass a fake clock). Default: a real timer that a
+ // cancel or a drain ends.
+ sleep?: (ms: number, signal?: AbortSignal, drain?: AbortSignal) => Promise<"slept" | "aborted" | "drained">;
};
// A Wayback pages channel (release 37) has no account to fetch: its captures
@@ -113,6 +133,8 @@ export const WAYBACK_PAGES_NOT_FETCHED =
// button, the ops route and this controller say the same thing.
export const OLDER_FROM_REFUSAL = "A start date (\"from\") applies only to an older-posts fetch.";
+export const RETRY_AND_OLDER_REFUSAL = "Retry on a block applies to a new-posts or full fetch, not an older-posts one.";
+
export const FULL_AND_OLDER_REFUSAL =
"A full re-fetch and an older-posts fetch are different walks — run one at a time.";
@@ -154,6 +176,11 @@ export type FetchPostsResult = {
needsCookies?: boolean;
// Stopped on the job's Drain, at a resume point the next run continues from.
drained?: boolean;
+ // A full re-walk of a forum thread: archived posts whose newer record (an
+ // edit) was appended.
+ updated?: number;
+ // What stopped the last try, when the source refused or challenged it.
+ block?: PostFetchResult["block"];
};
export async function fetchPosts(
@@ -171,6 +198,9 @@ export async function fetchPosts(
return { ok: false, written: 0, skipped: 0, complete: false, error: `"${day}" is not a date (YYYY-MM-DD) for "${name}"` };
}
}
+ if (opts.retryOnBlock && opts.older) {
+ return { ok: false, written: 0, skipped: 0, complete: false, error: RETRY_AND_OLDER_REFUSAL };
+ }
if (opts.from !== undefined && !opts.older) {
return { ok: false, written: 0, skipped: 0, complete: false, error: OLDER_FROM_REFUSAL };
}
@@ -285,13 +315,119 @@ export async function fetchPosts(
browserCookies: xLogin?.browserSpec,
});
}
- // A stored cursor means the previous run stopped early (hit its limit, or was
- // cancelled). Resume the backfill from there rather than applying the
- // watermark, which would otherwise leave that history permanently missing.
- // --full discards the cursor and re-walks from the top.
- const resumeCursor = opts.full ? undefined : priorState?.cursor;
+ // RETRY ON A BLOCK (release 37 lane G): a challenge or a refusal stops the
+ // walk; the job waits `minutes` and runs again, up to `max` tries in all.
+ // Never sooner than `minutes` (held to RETRY_MIN_MINUTES), never on a
+ // captcha or a login, which need a person.
+ const retry = opts.retryOnBlock;
+ const retryProblem = retryOnBlockProblem(retry);
+ if (retryProblem) return { ok: false, written: 0, skipped: 0, complete: false, error: retryProblem };
+ const sleep = opts.sleep ?? sleepOrStop;
+ let written = 0;
+ let skipped = 0;
+ let updated = 0;
+ for (let attempt = 1; ; attempt++) {
+ const r = await fetchTimeline({
+ opts,
+ fetcher,
+ channelRoot,
+ handle,
+ accountUrl,
+ seenIds: attempt === 1 ? seenIds : await readSeenPostIds(channelRoot),
+ priorState: attempt === 1 ? priorState : await readPostFetchState(channelRoot),
+ config,
+ });
+ written += r.written;
+ skipped += r.skipped;
+ updated += r.updated ?? 0;
+ const total = { ...r, written, skipped, ...(updated ? { updated } : {}) };
+ if (!retry || !r.block || !RETRYABLE_BLOCKS.has(r.block) || attempt >= retry.max) {
+ if (retry && r.block && RETRYABLE_BLOCKS.has(r.block)) {
+ log(`[error] Still ${r.block === "challenge" ? "challenged" : "refused"} after ${attempt} tries; stopped.`);
+ }
+ return total;
+ }
+ if (signal?.aborted) return total;
+ log(
+ `Waiting ${retry.minutes} min after ${r.block === "challenge" ? "a challenge page" : "a refusal"}, try ${attempt + 1}/${retry.max}.`,
+ );
+ const why = await sleep(retry.minutes * 60_000, signal, opts.drain);
+ if (why === "aborted") return total;
+ if (why === "drained") {
+ log("Drained while waiting out the block; the next run resumes at its saved positions.");
+ return { ...total, ok: true, error: undefined, drained: true };
+ }
+ }
+}
+
+// The blocks a wait can clear: a browser check, a 403/429 refusal.
+const RETRYABLE_BLOCKS = new Set<NonNullable<PostFetchResult["block"]>>(["challenge", "blocked"]);
+
+// Wait `ms`, or until the job is cancelled or drained.
+export function sleepOrStop(
+ ms: number,
+ signal?: AbortSignal,
+ drain?: AbortSignal,
+): Promise<"slept" | "aborted" | "drained"> {
+ return new Promise((resolve) => {
+ if (signal?.aborted) return resolve("aborted");
+ if (drain?.aborted) return resolve("drained");
+ const finish = (why: "slept" | "aborted" | "drained") => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ drain?.removeEventListener("abort", onDrain);
+ resolve(why);
+ };
+ const onAbort = () => finish("aborted");
+ const onDrain = () => finish("drained");
+ const timer = setTimeout(() => finish("slept"), ms);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ drain?.addEventListener("abort", onDrain, { once: true });
+ });
+}
+
+// The held pages of a forum thread: every archived post's page, as read.
+async function heldForumPages(channelRoot: string): Promise<number[]> {
+ const pages: number[] = [];
+ for (const p of await readAllPosts(channelRoot)) {
+ if (p.platform === "xenforo" && typeof p.forum?.page === "number") pages.push(p.forum.page);
+ }
+ return pages;
+}
+
+// ONE RUN of the timeline walk (a normal or full fetch): the fetcher, the
+// writes, the state.
+async function fetchTimeline(ctx: {
+ opts: FetchPostsOptions;
+ fetcher: SocialFetcher;
+ channelRoot: string;
+ handle: string;
+ accountUrl: string;
+ seenIds: ReadonlySet<string>;
+ priorState: PostFetchState | null;
+ config: ChannelConfigRead;
+}): Promise<FetchPostsResult & { block?: PostFetchResult["block"] }> {
+ const { opts, fetcher, channelRoot, handle, accountUrl, seenIds, priorState, config } = ctx;
+ const { paths, slug, settings, signal } = opts;
+ const log = (line: string) => opts.onLog?.(line);
+ const forum = fetcher.platform === "xenforo";
+
+ // A FORUM THREAD keeps two positions (lib/forumWalk.ts), re-derived from the
+ // archived posts' pages every run; its walk needs neither a cursor nor a
+ // watermark. Every other fetcher: a stored cursor means the previous run
+ // stopped early (hit its limit, or was cancelled) — resume the backfill from
+ // there rather than applying the watermark, which would otherwise leave that
+ // history permanently missing. --full discards the cursor and re-walks from
+ // the top.
+ let forumWalk: ForumWalkState | undefined;
+ if (forum) {
+ const derived = deriveForumWalk(priorState?.forum, priorState?.cursor, await heldForumPages(channelRoot));
+ forumWalk = derived.walk;
+ for (const note of derived.notes) log(note);
+ }
+ const resumeCursor = opts.full || forum ? undefined : priorState?.cursor;
const since =
- opts.full || resumeCursor
+ opts.full || resumeCursor || forum
? undefined
: ((await latestPostCreatedAt(channelRoot)) ?? undefined);
const policy = resolveCookiePolicy(settings, config);
@@ -306,11 +442,15 @@ export async function fetchPosts(
log(
`Fetching posts for ${slug} via ${fetcher.label} (@${handle})` +
- (resumeCursor
- ? " — resuming an unfinished backfill"
- : since
- ? ` since ${since}`
- : " — full history") +
+ (forum
+ ? opts.full
+ ? " — a full re-walk"
+ : ` — ${forumWalkStartLine(forumWalk ?? {})}`
+ : resumeCursor
+ ? " — resuming an unfinished backfill"
+ : since
+ ? ` since ${since}`
+ : " — full history") +
`; ${seenIds.size} already archived.`,
);
@@ -326,6 +466,21 @@ export async function fetchPosts(
// The older walk's position rides along untouched: a normal fetch neither
// reads it nor drops it.
if (priorState?.older) state.older = priorState.older;
+ // A forum thread's positions are written whole every time (a run that
+ // fails before its first page keeps the derived ones).
+ if (forumWalk) state.forum = forumWalk;
+
+ // A full re-walk of a forum thread re-reads archived posts for their edits:
+ // they come back with the new ones and are UPSERTED (a newer record of an
+ // archived post appended; readers take the last).
+ const upsert = forum && opts.full === true;
+ let updated = 0;
+ const write = async (posts: Post[]) => {
+ if (!upsert) return writePosts(channelRoot, posts);
+ const u = await upsertPosts(channelRoot, posts, { ignorePosition: true });
+ updated += u.updated;
+ return u;
+ };
// Progress a long run saves as it goes (a fetcher that streams calls this
// between pages): the posts so far, then the resume point they are safe
@@ -333,14 +488,15 @@ export async function fetchPosts(
let checkpointWritten = 0;
let checkpointSkipped = 0;
const shards = new Set<string>();
- const onCheckpoint = async (cp: { posts: Post[]; cursor: string }) => {
- const w = await writePosts(channelRoot, cp.posts);
+ const onCheckpoint = async (cp: { posts: Post[]; cursor: string; forumWalk?: ForumWalkState }) => {
+ const w = await write(cp.posts);
checkpointWritten += w.written;
checkpointSkipped += w.skipped;
for (const shard of w.shards) shards.add(shard);
+ if (forum && cp.forumWalk) state.forum = cp.forumWalk;
await writePostFetchState(channelRoot, {
...state,
- cursor: cp.cursor,
+ ...(forum ? {} : { cursor: cp.cursor }),
lastFetchedCount: checkpointWritten,
});
if (w.written > 0) {
@@ -348,7 +504,7 @@ export async function fetchPosts(
}
};
- let result;
+ let result: PostFetchResult;
try {
result = await fetcher.fetch({
accountUrl,
@@ -356,6 +512,7 @@ export async function fetchPosts(
channelSlug: slug,
since,
cursor: resumeCursor,
+ ...(forumWalk ? { forumWalk } : {}),
seenIds,
cookies,
cookieSource: xLogin?.source,
@@ -378,7 +535,8 @@ export async function fetchPosts(
// Whatever was checkpointed is on disk; keep the resume point that covers
// it rather than dropping back to the watermark.
const prior = await readPostFetchState(channelRoot);
- if (prior?.cursor) state.cursor = prior.cursor;
+ if (!forum && prior?.cursor) state.cursor = prior.cursor;
+ if (forum && prior?.forum) state.forum = prior.forum;
if (checkpointWritten > 0) state.lastFetchedCount = checkpointWritten;
await writePostFetchState(channelRoot, state);
return {
@@ -390,7 +548,7 @@ export async function fetchPosts(
};
}
- const final = await writePosts(channelRoot, result.posts);
+ const final = await write(result.posts);
for (const shard of final.shards) shards.add(shard);
const written = {
written: checkpointWritten + final.written,
@@ -398,12 +556,25 @@ export async function fetchPosts(
};
log(
`Wrote ${written.written} new post(s), skipped ${written.skipped} already archived` +
+ (upsert ? `, updated ${updated} edited` : "") +
(shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") +
(result.complete ? "." : " — more history remains."),
);
+ if (result.notSeen?.length) {
+ log(
+ `${result.notSeen.length} archived post(s) were on no page of the thread (deleted or moved since): ` +
+ result.notSeen.slice(0, 20).join(", ") +
+ (result.notSeen.length > 20 ? ", …" : "") +
+ ". Kept as archived; nothing is marked.",
+ );
+ }
state.lastFetchedCount = written.written;
- if (result.cursor && !result.complete) state.cursor = result.cursor;
+ if (forum) {
+ if (result.forumWalk) state.forum = result.forumWalk;
+ } else if (result.cursor && !result.complete) {
+ state.cursor = result.cursor;
+ }
if (result.needsCookies) state.needsCookies = true;
if (result.error) {
log(`[error] ${result.error}`);
@@ -431,6 +602,8 @@ export async function fetchPosts(
complete: result.complete,
needsCookies: result.needsCookies,
error: result.error,
+ ...(upsert ? { updated } : {}),
+ ...(result.block ? { block: result.block } : {}),
...(result.drained ? { drained: true } : {}),
};
}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -139,6 +139,10 @@ export const REPORT_DRAFT_BODY_KEYS = [
"proposals",
"note",
"answers",
+ // release 38 lane E: a `video-assist` job's request and scope (it shares
+ // "project", "note" and "answers" with clips-suggest).
+ "request",
+ "scope",
] as const;
// A seed's size: a board of a few hundred quotes, with room.
@@ -195,6 +199,10 @@ export type ReportDraftBody = {
proposals?: string[];
note?: string;
answers?: unknown;
+ // A video-assist job's (release 38 lane E, ./videoAssist.ts): what to
+ // change, in words, and what it may touch (look | clips | fx | all).
+ request?: string;
+ scope?: string;
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -217,10 +225,14 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
const task = b.task;
if (typeof task !== "string" || !TASKS.includes(task as ReportDraftTask)) fail(`"task" is one of ${TASKS.join(", ")}`);
const article = b.article;
- // A clips-suggest job (release 36 lane D) is on a umtool project, not an article.
- const onProject = task === "clips-suggest";
+ // A clips-suggest job (release 36 lane D) and a video-assist job (release 38
+ // lane E) are on a umtool project, not an article.
+ const onProject = task === "clips-suggest" || task === "video-assist";
+ const assist = task === "video-assist";
if (onProject) {
- if (article !== undefined && article !== null && article !== "") fail('a clips-suggest job names its "project" (the reactions project\'s directory), not an article');
+ if (article !== undefined && article !== null && article !== "") {
+ fail(assist ? 'a video-assist job names its "project" (the video project\'s directory), not an article' : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article');
+ }
} else if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)');
const int = (k: string) => {
const v = b[k];
@@ -362,7 +374,39 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
const clipsKeys = ["project", "proposals", "note", "answers"] as const;
const clipsGiven = clipsKeys.filter((k) => b[k] !== undefined && b[k] !== null);
if (clipsGiven.length && !onProject) fail(`${clipsGiven.map((k) => `"${k}"`).join(", ")} ${clipsGiven.length === 1 ? "is" : "are"} a clips-suggest job's`);
- if (onProject) {
+ // The video assistant's (release 38 lane E).
+ const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null);
+ if (assistGiven.length && !assist) fail(`${assistGiven.map((k) => `"${k}"`).join(", ")} ${assistGiven.length === 1 ? "is" : "are"} a video-assist job's`);
+ if (assist) {
+ const project = b.project;
+ if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory');
+ out.project = project as string;
+ if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s');
+ if (b.request !== undefined && b.request !== null) {
+ if (typeof b.request !== "string" || !b.request.trim()) fail('"request" is what to change, in words');
+ if (b.request.length > 2000) fail('"request" is at most 2,000 characters');
+ out.request = b.request.replace(/\s+/g, " ").trim();
+ }
+ if (b.scope !== undefined && b.scope !== null) {
+ if (!["look", "clips", "fx", "all"].includes(String(b.scope))) fail('"scope" is look, clips, fx or all');
+ out.scope = String(b.scope);
+ }
+ if (b.note !== undefined && b.note !== null) {
+ if (typeof b.note !== "string" || !/^n_[a-z0-9]{4,32}$/.test(b.note)) fail('"note" is a note id (n_…)');
+ out.note = b.note;
+ }
+ if (b.answers !== undefined && b.answers !== null) {
+ if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"ops": [{"op", "id", "key", "value"}], "reply"}');
+ if (JSON.stringify(b.answers).length > 100_000) fail('"answers" is at most 100,000 characters');
+ out.answers = b.answers;
+ }
+ if (!out.request && !out.note) fail('a video-assist job needs its "request" (what to change), or the "note" whose text is one');
+ if (out.request && out.note) fail('give "request" or "note", not both: a note\'s text is its request');
+ if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"');
+ if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"');
+ const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined);
+ if (extra.length) fail(`a video-assist job reads its project: it takes no ${extra.join(", ")}`);
+ } else if (onProject) {
const project = b.project;
if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the reactions project\'s absolute directory');
out.project = project as string;
@@ -424,7 +468,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] {
}
const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" =>
- isStepTask(task) || task === "clips-suggest" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep";
+ isStepTask(task) || task === "clips-suggest" || task === "video-assist" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep";
export function expandHome(p: string): string {
return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
@@ -553,6 +597,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return refuse((e as Error).message);
}
}
+ if (body.task === "video-assist") {
+ if (body.dryRun) return refuse('a video-assist plan is planVideoAssistJob\'s ("dryRun": true at the ops route)');
+ try {
+ const { enqueueVideoAssist } = await import("./videoAssist");
+ return await enqueueVideoAssist(body, deps);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ }
if (body.task === REFRESH_TASK) {
if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)');
try {
@@ -758,7 +811,8 @@ async function runReportDraft(
case "verdicts":
case "frames":
case "clips-suggest":
- // A refresh, a triage, verdict proposals, a frame scan and the clip finder's labels are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts), never this one.
+ case "video-assist":
+ // A refresh, a triage, verdict proposals, a frame scan, the clip finder's labels and the video assistant are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts, ./videoAssist.ts), never this one.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
diff --git a/common/controller/savePageNow.test.ts b/common/controller/savePageNow.test.ts
@@ -0,0 +1,197 @@
+// Release 37 S5: Save Page Now on the fake Wayback — the keys read (env, a
+// mode-600 file, refused when others can read it, never a setting), the
+// refusals before any request, the capture asked → pending → success → the
+// capture imported into the channel, and the error paths: no keys, wrong keys,
+// a 429 that does not clear, a refused URL, a failed capture, a capture still
+// pending. The keys never appear in a log line or a result. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/savePageNow.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { FAKE_SPN_ACCESS, FAKE_SPN_SECRET, SPN_CAPTURE_TS, startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import type { Paths } from "../lib/paths";
+import { WaybackClient } from "../lib/waybackClient";
+import { readAllPosts } from "../lib/posts-server";
+import { pageRecordId } from "../lib/waybackPages/types";
+import { parseSpnStatus, parseSpnSubmit, spnSaveBody } from "../lib/waybackPages/savePageNow";
+import { readSpnKeys } from "../lib/waybackPages/savePageNow-server";
+import { looksLikeS3Key } from "../lib/archiveOrgTorrent";
+import { sanitizeArchiveOrg } from "../lib/settingsSchema";
+import { importPage } from "./importPage";
+import { planSavePageNow, queueSavePageNow, savePageNow, savePageNowAvailability } from "./savePageNow";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "save-page-now-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths;
+const ENV = { ARCHIVE_ORG_S3_ACCESS: FAKE_SPN_ACCESS, ARCHIVE_ORG_S3_SECRET: FAKE_SPN_SECRET };
+const NO_KEYS = path.join(ROOT, "no-such-keys.env");
+const SETTINGS = { archiveOrg: { s3KeyFile: NO_KEYS }, social: { x: { visibility: "private" } } };
+const LIVE = "https://live.example/notes/today.html";
+
+async function channel(slug: string, config: Record<string, unknown>) {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config }));
+ return dir;
+}
+const pagesChannel = (slug: string, target: string) =>
+ channel(slug, {
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "live.example",
+ url: `https://web.archive.org/web/*/${target}*`,
+ wayback: { targets: [{ url: target, match: "prefix" }] },
+ });
+
+const noSleep = async () => {};
+
+test("the keys: the environment first, else a mode-600 file; a file others can read is refused; never a setting", () => {
+ assert.deepEqual(readSpnKeys({ keyFile: NO_KEYS, env: ENV }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "env" });
+ const none = readSpnKeys({ keyFile: NO_KEYS, env: {} });
+ assert.equal(none.ok, false);
+ assert.match(none.ok ? "" : none.reason, /Save Page Now needs archive\.org S3 keys/);
+ const file = path.join(ROOT, "keys.env");
+ writeFileSync(file, `# archive.org\nARCHIVE_ORG_S3_ACCESS="${FAKE_SPN_ACCESS}"\nexport ARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`);
+ chmodSync(file, 0o644);
+ const open = readSpnKeys({ keyFile: file, env: {} });
+ assert.match(open.ok ? "" : open.reason, /readable by others — chmod 600/);
+ chmodSync(file, 0o600);
+ assert.deepEqual(readSpnKeys({ keyFile: file, env: {} }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "file" });
+ const half = path.join(ROOT, "half.env");
+ writeFileSync(half, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\n`, { mode: 0o600 });
+ assert.match((r => (r.ok ? "" : r.reason))(readSpnKeys({ keyFile: half, env: {} })), /no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines/);
+ // The setting is a path; a key pasted there is refused, never stored.
+ assert.equal(looksLikeS3Key(FAKE_SPN_ACCESS), true);
+ assert.equal(looksLikeS3Key("~/.config/archilyzer/archive-org.env"), false);
+ assert.equal(sanitizeArchiveOrg({ s3KeyFile: FAKE_SPN_SECRET }).s3KeyFile, "~/.config/archilyzer/archive-org.env");
+ assert.equal(sanitizeArchiveOrg({ s3KeyFile: "/etc/keys/ia.env" }).s3KeyFile, "/etc/keys/ia.env");
+ assert.equal(sanitizeArchiveOrg({}).s3KeyFile, "~/.config/archilyzer/archive-org.env");
+ // The button: off, with the sentence; on with keys.
+ assert.deepEqual(savePageNowAvailability({ settings: SETTINGS, env: ENV }), { on: true });
+ const off = savePageNowAvailability({ settings: SETTINGS, env: {} });
+ assert.equal(off.on, false);
+});
+
+test("SPN's answers read: a job id, a refusal by status_ext, the keys refused; pending, success, a failed capture", () => {
+ assert.deepEqual(parseSpnSubmit(200, JSON.stringify({ url: LIVE, job_id: "spn2-1" })), { ok: true, jobId: "spn2-1" });
+ const blocked = parseSpnSubmit(200, JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "blocked" }));
+ assert.deepEqual([blocked.ok, blocked.ok ? "" : blocked.code], [false, "error:blocked-url"]);
+ assert.equal((parseSpnSubmit(401, "{}") as { code?: string }).code, "auth");
+ assert.deepEqual(parseSpnStatus(200, '{"status":"pending"}'), { state: "pending" });
+ assert.deepEqual(parseSpnStatus(200, JSON.stringify({ status: "success", timestamp: SPN_CAPTURE_TS, original_url: LIVE })), {
+ state: "success",
+ timestamp: SPN_CAPTURE_TS,
+ originalUrl: LIVE,
+ });
+ assert.equal(parseSpnStatus(200, '{"status":"success"}').state, "error");
+ assert.match((parseSpnStatus(200, '{"status":"error","status_ext":"error:not-found","message":"404"}') as { error: string }).error, /error:not-found/);
+ assert.equal(spnSaveBody(LIVE), `url=${encodeURIComponent(LIVE)}&capture_outlinks=0`);
+});
+
+test("refused before any request: no keys, not http(s), a Wayback URL, not a pages channel, a video, X while private", async () => {
+ await pagesChannel("live-notes", "live.example/");
+ await channel("a-video-channel", { url: "https://www.youtube.com/@x/videos" });
+ const ask = async (url: string, slug?: string, env: Record<string, string> = ENV) => {
+ const r = await planSavePageNow(paths, { url, ...(slug ? { slug } : {}), settings: SETTINGS, env });
+ return r.ok ? "" : r.error;
+ };
+ assert.match(await ask(LIVE, "live-notes", {}), /Save Page Now needs archive\.org S3 keys/);
+ assert.match(await ask("ftp://live.example/x"), /only http and https/);
+ assert.match(await ask(`https://web.archive.org/web/2014/${LIVE}`), /on the Wayback Machine already/);
+ assert.match(await ask(LIVE, "a-video-channel"), /not a Wayback pages channel/);
+ assert.match(await ask(LIVE, "nope"), /No such channel: nope/);
+ assert.match(await ask("https://www.youtube.com/watch?v=abcdefghijk", "live-notes"), /is a video/);
+ assert.match(await ask("https://x.com/someone", "live-notes"), /on X, whose posts are private here/);
+ assert.equal(await ask(LIVE, "live-notes"), "");
+ assert.equal(await ask(LIVE), "", "no channel: the capture alone");
+ // The job door refuses the same way and starts nothing.
+ const q = await queueSavePageNow({ paths, url: LIVE, slug: "live-notes", settings: SETTINGS });
+ assert.equal(q.ok, false);
+});
+
+test("asked → pending → success → the capture imported into the channel; the keys in no log line or result", async () => {
+ const wb = await startFakeWayback({ spn: { pendingPolls: 2 } });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0 });
+ const dir = await pagesChannel("live-notes-2", "live.example/");
+ const lines: string[] = [];
+ const dry = await savePageNow({ paths, url: LIVE, slug: "live-notes-2", dryRun: true, settings: SETTINGS, env: ENV, deps: { client, sleep: noSleep } });
+ assert.equal(dry.ok, true);
+ assert.match(dry.wouldAsk ?? "", /POST https:\/\/web\.archive\.org\/save .*then import the capture into live-notes-2/);
+ assert.equal(wb.requests.length, 0, "a dry run asks nothing");
+
+ const r = await savePageNow({
+ paths,
+ url: LIVE,
+ slug: "live-notes-2",
+ settings: SETTINGS,
+ env: ENV,
+ pollMs: 0,
+ deps: {
+ client,
+ sleep: noSleep,
+ importCapture: async (slug, url) => {
+ const imp = await importPage({ paths, slug, url, client, settings: SETTINGS });
+ assert.equal(imp.ok, true, imp.error);
+ return { jobId: "import-1" };
+ },
+ },
+ onLog: (l) => lines.push(l),
+ });
+ assert.equal(r.ok, true, r.error);
+ assert.deepEqual([r.captureTs, r.originalUrl, r.polls, r.importJobId], [SPN_CAPTURE_TS, LIVE, 3, "import-1"]);
+ assert.equal(r.waybackUrl, `https://web.archive.org/web/${SPN_CAPTURE_TS}/${LIVE}`);
+ assert.deepEqual(wb.spnForms, [{ url: LIVE, capture_outlinks: "0" }]);
+ assert.deepEqual(
+ wb.requests.map((q) => `${q.method} ${q.path.replace(/\?.*$/, "")}`).slice(0, 4),
+ ["POST /save", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1"],
+ );
+ const posts = await readAllPosts(dir);
+ assert.deepEqual(posts.map((p) => p.id), [pageRecordId(SPN_CAPTURE_TS, LIVE)]);
+ assert.match(posts[0]!.text, /captured by the fake Save Page Now/);
+ const all = JSON.stringify({ lines, r });
+ assert.ok(!all.includes(FAKE_SPN_SECRET) && !all.includes(FAKE_SPN_ACCESS), "the keys never leave");
+ } finally {
+ await wb.close();
+ }
+});
+
+test("error paths: wrong keys, a 429 that does not clear, a refused URL, a failed capture, still pending", async () => {
+ const wb = await startFakeWayback({ spn: { busyTimes: 9, failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"] } });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0, maxAttempts: 3 });
+ const run = (url: string, env: Record<string, string> = ENV, maxPolls?: number) =>
+ savePageNow({ paths, url, settings: SETTINGS, env, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } });
+ const wrong = await run(LIVE, { ARCHIVE_ORG_S3_ACCESS: "WRONGACCESS", ARCHIVE_ORG_S3_SECRET: "WRONGSECRET" });
+ assert.match(wrong.error ?? "", /refused the S3 keys \(HTTP 401\)/);
+ assert.ok(!(wrong.error ?? "").includes("WRONGSECRET"));
+ const busy = await run(LIVE);
+ assert.equal(busy.ok, false);
+ assert.match(busy.error ?? "", /did not answer .* after 3 attempts \(HTTP 429\); stopping/);
+ } finally {
+ await wb.close();
+ }
+ const wb2 = await startFakeWayback({ spn: { failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"], pendingPolls: 1 } });
+ try {
+ const client = new WaybackClient({ fetch: wb2.fetch, sleep: noSleep }, { minGapMs: 0 });
+ const run = (url: string, maxPolls?: number) =>
+ savePageNow({ paths, url, settings: SETTINGS, env: ENV, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } });
+ const blocked = await run("https://live.example/blocked");
+ assert.match(blocked.error ?? "", /refused the capture \(HTTP 200, error:blocked-url\)/);
+ const failed = await run("https://live.example/gone");
+ assert.match(failed.error ?? "", /the capture failed \(HTTP 200, error:not-found\)/);
+ assert.ok(failed.spnJobId);
+ const pending = await run("https://live.example/slow", 1);
+ assert.match(pending.error ?? "", /still pending after 1 status checks/);
+ // No slug: the capture is made, nothing imported.
+ const alone = await run("https://live.example/alone");
+ assert.deepEqual([alone.ok, alone.importJobId], [true, undefined]);
+ } finally {
+ await wb2.close();
+ }
+});
diff --git a/common/controller/savePageNow.ts b/common/controller/savePageNow.ts
@@ -0,0 +1,297 @@
+// SAVE PAGE NOW (release 37 S5, `save-page-now`): "Ask the Wayback Machine to
+// capture this now" — for a live page likely to be taken down. One page per
+// job: archive.org's SPN2 API (lib/waybackPages/savePageNow.ts) with the
+// operator's S3 keys, the capture waited for, then (when a Wayback pages
+// channel is named) an `import-page` job of the new capture into it
+// (controller/importPage.ts startImportPageJob), queued behind this one.
+//
+// {url, slug?} slug: the Wayback pages channel the capture is imported
+// into (absent: the capture is made and named, not
+// imported)
+//
+// Refused before any request, with the sentence a caller shows: no keys (the
+// button is off and says why), a URL that is not http(s), a page on the
+// Wayback Machine itself, a channel that is not a Wayback pages channel, a
+// video ("use import-video"), an X page outside an X-scoped channel while X
+// posts are private (importPage's own rule).
+//
+// POLITE: every request goes through the process's Wayback client (one
+// stream, the 2 s gap, 429/503 waited out, then stopped), on the
+// `platform:archive.org` queue — one capture asked at a time; the status is
+// polled every SPN_POLL_MS, at most SPN_MAX_POLLS times. The keys are sent in
+// the Authorization header only, and never logged.
+
+import { getPaths, type Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { readChannelConfig } from "./channels";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import { isWaybackHost, waybackPageUrl } from "../lib/wayback";
+import { videoPageOf } from "../lib/waybackPages/urls";
+import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
+import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import {
+ parseSpnStatus,
+ parseSpnSubmit,
+ SPN_SAVE_URL,
+ spnAuthorization,
+ spnSaveBody,
+ spnStatusUrl,
+ type SpnKeys,
+} from "../lib/waybackPages/savePageNow";
+import { readSpnKeys, redactSpnKeys } from "../lib/waybackPages/savePageNow-server";
+import { startImportPageJob, WAYBACK_PAGES_QUEUE, xCaptureRefusal } from "./importPage";
+
+export const SAVE_PAGE_NOW_JOB_KIND = "save-page-now";
+export const SAVE_PAGE_NOW_RESULT_MARKER = "@@save-page-now ";
+
+// SPN2 asks status pollers to wait a few seconds between polls; a capture
+// usually completes within a minute or two.
+export const SPN_POLL_MS = 10_000;
+export const SPN_MAX_POLLS = 30;
+
+type SpnSettings = { archiveOrg?: { s3KeyFile?: string }; social?: { x?: { visibility?: unknown } } };
+
+export type SavePageNowAvailability = { on: true } | { on: false; reason: string };
+
+// Whether the button is on, and why not: the keys' presence (never their
+// value).
+export function savePageNowAvailability(o: { settings?: SpnSettings; env?: Readonly<Record<string, string | undefined>> } = {}): SavePageNowAvailability {
+ const settings = o.settings ?? (getSettings() as SpnSettings);
+ const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) });
+ return read.ok ? { on: true } : { on: false, reason: read.reason };
+}
+
+export type SavePageNowPlan = { url: string; slug?: string; keys: SpnKeys };
+
+// Everything checked before a request: the plan, or the refusal.
+export async function planSavePageNow(
+ paths: Paths,
+ opts: { url: string; slug?: string; settings?: SpnSettings; env?: Readonly<Record<string, string | undefined>> },
+): Promise<{ ok: true; plan: SavePageNowPlan } | { ok: false; error: string }> {
+ const settings = opts.settings ?? (getSettings() as SpnSettings);
+ const url = opts.url.trim();
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { ok: false, error: `"${url}" is not a URL` };
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: `only http and https pages are captured (not ${u.protocol})` };
+ if (isWaybackHost(u.hostname)) return { ok: false, error: `${url} is on the Wayback Machine already: import it (import-page) instead` };
+ const slug = opts.slug?.trim() || undefined;
+ if (slug) {
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isWaybackPagesChannel(config)) {
+ return { ok: false, error: `${slug} is not a Wayback pages channel; a capture is imported into a channel on platform "webpage"` };
+ }
+ const video = videoPageOf(url);
+ if (video) return { ok: false, error: `${url} is a video (${video}), not a page: use import-video for a video` };
+ const x = xCaptureRefusal(config, slug, url, settings);
+ if (x) return { ok: false, error: x };
+ }
+ const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(opts.env ? { env: opts.env } : {}) });
+ if (!read.ok) return { ok: false, error: read.reason };
+ return { ok: true, plan: { url, ...(slug ? { slug } : {}), keys: read.keys } };
+}
+
+export type SavePageNowResult = {
+ ok: boolean;
+ url: string;
+ slug?: string;
+ dryRun?: boolean;
+ // What a dry run would ask.
+ wouldAsk?: string;
+ // SPN's job id.
+ spnJobId?: string;
+ captureTs?: string;
+ originalUrl?: string;
+ waybackUrl?: string;
+ // The import-page job of the capture.
+ importJobId?: string;
+ importError?: string;
+ polls?: number;
+ error?: string;
+};
+
+export type SavePageNowDeps = {
+ client: Pick<WaybackClient, "send">;
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
+ // The capture into the channel (default: an import-page job).
+ importCapture: (slug: string, waybackUrl: string) => Promise<{ jobId: string }>;
+};
+
+const defaultSleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(t);
+ reject(signal.reason ?? new Error("aborted"));
+ },
+ { once: true },
+ );
+ });
+
+// ONE CAPTURE ASKED, waited for, and (with a slug) imported.
+export async function savePageNow(opts: {
+ paths: Paths;
+ url: string;
+ slug?: string;
+ dryRun?: boolean;
+ settings?: SpnSettings;
+ env?: Readonly<Record<string, string | undefined>>;
+ pollMs?: number;
+ maxPolls?: number;
+ deps?: Partial<SavePageNowDeps>;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+}): Promise<SavePageNowResult> {
+ const base: SavePageNowResult = { ok: false, url: opts.url.trim(), ...(opts.slug?.trim() ? { slug: opts.slug.trim() } : {}) };
+ const planned = await planSavePageNow(opts.paths, opts);
+ if (!planned.ok) return { ...base, error: planned.error };
+ const { plan } = planned;
+ if (opts.dryRun) {
+ return {
+ ...base,
+ ok: true,
+ dryRun: true,
+ wouldAsk: `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`,
+ };
+ }
+ const deps: SavePageNowDeps = {
+ client: opts.deps?.client ?? defaultWaybackClient,
+ sleep: opts.deps?.sleep ?? defaultSleep,
+ importCapture:
+ opts.deps?.importCapture ??
+ ((slug, waybackUrl) => startImportPageJob({ slug, url: waybackUrl, requestedBy: "save-page-now", paths: opts.paths })),
+ };
+ const log = (line: string) => opts.onLog?.(redactSpnKeys(line, plan.keys));
+ const headers = { authorization: spnAuthorization(plan.keys) };
+ const pollMs = opts.pollMs ?? SPN_POLL_MS;
+ const maxPolls = opts.maxPolls ?? SPN_MAX_POLLS;
+ try {
+ log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now).`);
+ const sent = await deps.client.send(SPN_SAVE_URL, {
+ method: "POST",
+ headers: { ...headers, "content-type": "application/x-www-form-urlencoded" },
+ body: spnSaveBody(plan.url),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const submit = parseSpnSubmit(sent.status, sent.text);
+ if (!submit.ok) return { ...base, error: redactSpnKeys(submit.error, plan.keys) };
+ log(`Save Page Now job ${submit.jobId}: waiting for the capture.`);
+ let polls = 0;
+ for (;;) {
+ if (polls >= maxPolls) {
+ return {
+ ...base,
+ spnJobId: submit.jobId,
+ polls,
+ error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with wayback-lookup, then import-page it)`,
+ };
+ }
+ await deps.sleep(pollMs, opts.signal);
+ polls++;
+ const st = await deps.client.send(spnStatusUrl(submit.jobId), {
+ method: "GET",
+ headers,
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const status = parseSpnStatus(st.status, st.text);
+ if (status.state === "pending") continue;
+ if (status.state === "error") return { ...base, spnJobId: submit.jobId, polls, error: redactSpnKeys(status.error, plan.keys) };
+ const waybackUrl = waybackPageUrl({ captureTs: status.timestamp, originalUrl: status.originalUrl });
+ log(`Captured: ${waybackUrl}`);
+ const out: SavePageNowResult = {
+ ...base,
+ ok: true,
+ spnJobId: submit.jobId,
+ polls,
+ captureTs: status.timestamp,
+ originalUrl: status.originalUrl,
+ waybackUrl,
+ };
+ if (plan.slug) {
+ try {
+ const imp = await deps.importCapture(plan.slug, waybackUrl);
+ out.importJobId = imp.jobId;
+ log(`Import into ${plan.slug}: job ${imp.jobId}.`);
+ } catch (e) {
+ // The capture exists either way; the import is a click away.
+ out.importError = (e as Error).message;
+ log(`The import into ${plan.slug} was refused: ${out.importError}`);
+ }
+ }
+ return out;
+ }
+ } catch (e) {
+ if (opts.signal?.aborted) return { ...base, error: "cancelled" };
+ if (e instanceof ArchiveOrgRequestError) return { ...base, error: redactSpnKeys(e.message, plan.keys) };
+ throw e;
+ }
+}
+
+// THE JOB: a `save-page-now` job on the archive.org queue, refused (no job)
+// with the plan's sentence. The log ends with `@@save-page-now {…}`.
+export async function queueSavePageNow(opts: {
+ paths: Paths;
+ url: string;
+ slug?: string;
+ requestedBy?: string;
+ settings?: SpnSettings;
+ deps?: Partial<SavePageNowDeps>;
+ pollMs?: number;
+ onDone?: (result: SavePageNowResult) => void;
+}): Promise<StreamActionResult> {
+ const planned = await planSavePageNow(opts.paths, opts);
+ if (!planned.ok) return { ok: false, error: planned.error };
+ const slug = planned.plan.slug;
+ return runManagedFunction({
+ kind: SAVE_PAGE_NOW_JOB_KIND,
+ queueKey: WAYBACK_PAGES_QUEUE,
+ paths: opts.paths,
+ ...(slug ? { channelSlug: slug } : {}),
+ fn: async (onLog, signal) => {
+ onLog(`Save Page Now: ${planned.plan.url}${slug ? ` into ${slug}` : ""}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`);
+ const result = await savePageNow({
+ paths: opts.paths,
+ url: planned.plan.url,
+ ...(slug ? { slug } : {}),
+ ...(opts.settings ? { settings: opts.settings } : {}),
+ ...(opts.deps ? { deps: opts.deps } : {}),
+ ...(opts.pollMs !== undefined ? { pollMs: opts.pollMs } : {}),
+ onLog,
+ signal,
+ });
+ onLog(`${SAVE_PAGE_NOW_RESULT_MARKER}${JSON.stringify(result)}`);
+ opts.onDone?.(result);
+ if (!result.ok) throw new Error(result.error ?? "Save Page Now failed");
+ },
+ });
+}
+
+export class SavePageNowRefusal extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SavePageNowRefusal";
+ }
+}
+
+// LANE B's DOOR (the Captures tab's targets): one `save-page-now` job for one
+// URL, its capture imported into `slug`. Throws SavePageNowRefusal with the
+// sentence when it is refused (no keys among them).
+export async function startSavePageNowJob(opts: {
+ url: string;
+ slug?: string;
+ requestedBy?: string;
+ paths?: Paths;
+}): Promise<{ jobId: string }> {
+ const res = await queueSavePageNow({ ...opts, paths: opts.paths ?? getPaths() });
+ if (!res.ok) throw new SavePageNowRefusal(res.error);
+ void res.stream.cancel();
+ return { jobId: res.jobId };
+}
diff --git a/common/controller/videoAssist.ts b/common/controller/videoAssist.ts
@@ -0,0 +1,226 @@
+// `report-draft {"task": "video-assist", "project", "request" | "note",
+// "scope"?, "model"?, "maxUsd"?, "answers"?, "dryRun"?}` — the video
+// assistant (release 38 lane E) as an editor job. umtool's Ask box (the Build
+// tab's Look panel, the clip editor's side column, a project-level note)
+// starts it through `editorCall`; `pnpm ops report-draft` and the MCP's
+// `generate` do the same.
+//
+// project the video project's directory (absolute; it must hold a
+// video.manifest.json, and it is never inside the corpus)
+// request what to change, in words (or `note`: a project-level note's
+// text is the request, and the proposals are posted to it as the
+// agent's reply with an Apply — `POST <UMTOOL_URL>/api/notes`)
+// scope look | clips | fx | all (default): what the ask may touch
+// answers the `code` route: a Claude Code session's answer
+// (`{ops: [{op, id, key, value}], reply}`), checked exactly as a
+// model's — no model is called
+// dryRun (the ops route) the plan: the prompt, its estimate; nothing written
+//
+// Out: `<project>/assist-proposals.json` — PROPOSALS ONLY; nothing is applied.
+// Routed by settings.generation.routes["video-assist"] (local by default:
+// `draft:local`, every ollama call through the GPU arbiter, so it waits behind
+// a transcription; ollama unloaded when the job ends) or the API (`draft:api`:
+// the narration cap, the daily cap, its usage in the ledger as task
+// `video-assist`). The log ends `@@report-draft {article: "", iteration: 0,
+// task: "video-assist", project, status, summary, usd, assist}`.
+
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { getSettings } from "../lib/settings";
+import { capFor } from "../lib/generationSettings";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { usageOf } from "../lib/report/draft/tasks/run";
+import {
+ ASSIST_CODE_MODEL,
+ VIDEO_ASSIST_TASK,
+ VideoAssistRefusal,
+ loadAssistProject,
+ noteReplyOf,
+ noteRequestOf,
+ planVideoAssist,
+ runVideoAssist,
+ scopeOf,
+ type VideoAssistOutcome,
+ type VideoAssistPlan,
+} from "../lib/report/draft/tasks/videoAssist";
+import { getWorkerToken } from "../lib/workerToken";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { projectDirOf, umtoolOrigin } from "./clipsSuggest";
+import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft";
+
+export { ASSIST_CODE_MODEL, VIDEO_ASSIST_TASK };
+
+/** An Ask on a note: the reply posted to umtool's notes as the agent's, with the proposals' Apply. */
+export type AssistNoteReply = { project: string; note: string; text: string; proposal: { kind: "assist"; at: string; ops: number } | null };
+
+export type VideoAssistJobDeps = ReportDraftDeps & {
+ postReply?: (r: AssistNoteReply) => Promise<void>;
+ umtoolUrl?: string | null;
+ workerToken?: string;
+};
+
+/** POST the reply to umtool's notes as the agent's. */
+export async function postAssistReplyToUmtool(r: AssistNoteReply, o: { umtoolUrl: string; workerToken: string; fetch?: typeof fetch }): Promise<void> {
+ const f = o.fetch ?? fetch;
+ const res = await f(`${o.umtoolUrl}/api/notes?project=${encodeURIComponent(r.project)}`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${o.workerToken}`, "content-type": "application/json" },
+ body: JSON.stringify({ op: { op: "reply", id: r.note, text: r.text, ...(r.proposal ? { proposal: r.proposal } : {}) } }),
+ });
+ if (!res.ok) {
+ const j = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new Error(`umtool refused the reply (${res.status}): ${j.error ?? res.statusText}`);
+ }
+}
+
+type Refused = { result: StreamActionResult & { ok: false } };
+
+/** The model a job runs on: a session's answer is `claude-code`'s; else the asked one, else the route's. */
+function modelOfBody(body: ReportDraftBody, gen: ReturnType<typeof getSettings>["generation"]): string {
+ if (body.answers !== undefined) return ASSIST_CODE_MODEL;
+ return modelFor(gen, VIDEO_ASSIST_TASK, body.model);
+}
+
+async function requestOf(body: ReportDraftBody, dir: string): Promise<string> {
+ if (body.note) return noteRequestOf(dir, body.note);
+ if (!body.request) throw new VideoAssistRefusal("the assistant needs a request (or a note): say what to change");
+ return body.request;
+}
+
+/** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */
+export async function planVideoAssistJob(body: ReportDraftBody, deps: Pick<ReportDraftDeps, "paths" | "settings">): Promise<VideoAssistPlan> {
+ const gen = (deps.settings ?? getSettings)().generation;
+ const dir = projectDirOf(body.project ?? "", deps.paths);
+ const route = gen.routes[VIDEO_ASSIST_TASK];
+ const model = body.model ?? (route === "code" ? ASSIST_CODE_MODEL : modelFor(gen, VIDEO_ASSIST_TASK));
+ return planVideoAssist({ project: dir, model, request: await requestOf(body, dir), scope: scopeOf(body.scope) }, { llm: llmConfigOf(gen, deps.paths) });
+}
+
+export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssistJobDeps): Promise<ReportDraftEnqueued | Refused> {
+ const refuse = (error: string): Refused => ({ result: { ok: false as const, error } });
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ let dir: string;
+ let model: string;
+ let request: string;
+ try {
+ dir = projectDirOf(body.project ?? "", paths);
+ model = modelOfBody(body, gen);
+ // Refused at the ask, not at the job's turn: no manifest, no note, no request.
+ await loadAssistProject(dir);
+ request = await requestOf(body, dir);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const scope = scopeOf(body.scope);
+ const onNote = !!body.note;
+ const umtool = deps.umtoolUrl === undefined ? umtoolOrigin() : deps.umtoolUrl;
+ const token = deps.workerToken ?? getWorkerToken();
+ if (onNote && !deps.postReply) {
+ if (!umtool) return refuse("UMTOOL_URL is not set on the editor: the assistant's reply is posted to umtool's notes");
+ if (!token) return refuse("WORKER_TOKEN is not set on the editor: umtool takes the assistant's reply with it");
+ }
+ const provider = model === ASSIST_CODE_MODEL ? "code" : providerOf(model);
+ let maxUsd: number | undefined;
+ if (provider === "api") {
+ try {
+ maxUsd = capFor(gen.caps, "narration", body.maxUsd);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) return refuse(refusal);
+ }
+ const postReply = deps.postReply ?? ((r: AssistNoteReply) => postAssistReplyToUmtool(r, { umtoolUrl: umtool!, workerToken: token }));
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE,
+ paths,
+ fn: async (onLog, signal, setProgress, ctx) => {
+ const g = (deps.settings ?? getSettings)().generation;
+ if (provider === "api") {
+ const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily);
+ if (late) throw new Error(late);
+ }
+ onLog(
+ `video-assist${onNote ? ` on ${body.note}` : ""} in ${dir} on ${model} (` +
+ (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter: it waits for a transcription" : "a Claude Code session's answer") +
+ ")",
+ );
+ setProgress?.({ metric: "turns", initial: 0, target: 1, current: 0 });
+ let out: VideoAssistOutcome | null = null;
+ try {
+ out = await runVideoAssist(
+ {
+ project: dir,
+ model,
+ request,
+ scope,
+ ...(body.note ? { note: body.note } : {}),
+ ...(maxUsd !== undefined ? { maxUsd } : {}),
+ ...(body.answers !== undefined ? { answers: body.answers } : {}),
+ },
+ {
+ llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined),
+ log: onLog,
+ signal,
+ ...(deps.now ? { now: deps.now } : {}),
+ },
+ );
+ } finally {
+ if (provider === "local") {
+ await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ }
+ setProgress?.({ metric: "turns", initial: 0, target: 1, current: 1 });
+ if (provider === "api") {
+ const at = deps.now?.() ?? new Date();
+ const rows: GenerationUsageRow[] = Object.entries(out.byModel)
+ .filter(([, t]) => t.calls > 0)
+ .map(([m, t]) => {
+ const u = usageOf(t);
+ return {
+ at: at.toISOString(),
+ day: utcDay(at),
+ jobId: ctx.jobId,
+ article: "",
+ iteration: 0,
+ task: VIDEO_ASSIST_TASK,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ };
+ });
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ if (onNote && out.status === "done" && out.proposals) {
+ const p = out.proposals;
+ await postReply({ project: dir, note: body.note!, text: noteReplyOf(p), proposal: p.ops.length ? { kind: "assist", at: p.at, ops: p.ops.length } : null });
+ onLog(`replied to ${body.note}`);
+ }
+ const p = out.proposals;
+ onLog(
+ `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({
+ article: "",
+ iteration: 0,
+ task: VIDEO_ASSIST_TASK,
+ project: dir,
+ status: out.status,
+ summary: out.summary,
+ usd: out.usd,
+ assist: { at: p?.at ?? null, proposed: p?.ops.length ?? 0, refused: p?.refused.length ?? 0, diff: p?.diff ?? [], file: out.file, ...(body.note ? { note: body.note } : {}) },
+ })}`,
+ );
+ if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (out.status === "failed") throw new Error(out.summary);
+ },
+ });
+ if (!result.ok) return { result };
+ return { result, iteration: 0 };
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -618,6 +618,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "platform",
needsText: true,
},
+ // Save Page Now (release 37 S5, controller/savePageNow.ts): ask the Wayback
+ // Machine to capture a live page now (SPN2, archive.org's S3 keys), wait for
+ // the capture, then start an import-page of it into the channel named. On
+ // the archive.org queue, like the imports; it writes nothing itself (the
+ // import does). Not drainable (one capture); not replayable (each run asks
+ // archive.org for a new capture).
+ "save-page-now": {
+ kind: "save-page-now",
+ label: "Save Page Now",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ },
// A screenshot and the attached media of specific archived posts (and the X
// Article a post links to), into the channel's `posts-media/`
// (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts:
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -304,6 +304,57 @@ export class ArchiveOrgClient {
});
}
+ // ANY METHOD, ONE REQUEST (release 37 S5, Save Page Now: a form POST and its
+ // status polls carry an Authorization header) through the same chain and
+ // gap. A 429/503 (and 502/504, a dropped connection) is waited out and
+ // retried as getOnce does, then ArchiveOrgRequestError `rateLimited`; any
+ // other answer — a 4xx included — is handed back with its body as text, for
+ // the caller to read (SPN answers its refusals as JSON). The headers given
+ // are sent and never put in an error or a log line.
+ send(
+ url: string,
+ init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
+ ): Promise<{ status: number; text: string }> {
+ return this.serial(async () => {
+ let lastError = "";
+ for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
+ const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now();
+ if (wait > 0) await this.deps.sleep(wait, init.signal);
+ this.requests++;
+ let res: Response | null = null;
+ let text = "";
+ try {
+ const timeout = AbortSignal.timeout(this.opts.timeoutMs);
+ res = await this.deps.fetch(url, {
+ method: init.method,
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
+ redirect: "follow",
+ headers: { accept: init.accept ?? "application/json", "user-agent": ARCHIVE_ORG_USER_AGENT, ...init.headers },
+ ...(init.body !== undefined ? { body: init.body } : {}),
+ });
+ text = await res.text();
+ } catch (err) {
+ if (init.signal?.aborted) throw err;
+ lastError = (err as Error).message;
+ res = null;
+ } finally {
+ this.lastDoneAt = this.deps.now();
+ }
+ if (res && !RETRYABLE.has(res.status)) return { status: res.status, text };
+ if (res) lastError = `HTTP ${res.status}`;
+ if (attempt === this.opts.maxAttempts) break;
+ const retryAfter = res ? parseRetryAfterMs(res.headers.get("retry-after"), this.deps.now()) : null;
+ const delay = Math.min(this.opts.maxBackoffMs, retryAfter ?? this.backoffMs(attempt));
+ await this.deps.sleep(delay, init.signal);
+ }
+ throw new ArchiveOrgRequestError(
+ `archive.org did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`,
+ null,
+ true,
+ );
+ });
+ }
+
getJson(url: string, signal?: AbortSignal): Promise<unknown> {
return this.serial(async () => {
const res = await this.getOnce(url, "application/json", signal);
diff --git a/common/lib/archiveOrgTorrent.ts b/common/lib/archiveOrgTorrent.ts
@@ -150,8 +150,14 @@ export type ArchiveOrgFetchSettings = {
// 0 = unlimited.
maxDownloadKiBps: number;
maxUploadKiBps: number;
+ // Release 37 S5: the PATH of the mode-600 file holding archive.org's S3
+ // keys for Save Page Now (lib/waybackPages/savePageNow-server.ts). Never
+ // the keys themselves.
+ s3KeyFile: string;
};
+export const DEFAULT_ARCHIVE_ORG_S3_KEY_FILE = "~/.config/archilyzer/archive-org.env";
+
export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = {
torrent: true,
seedMinutes: 10,
@@ -160,8 +166,16 @@ export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = {
maxPeers: 30,
maxDownloadKiBps: 0,
maxUploadKiBps: 0,
+ s3KeyFile: DEFAULT_ARCHIVE_ORG_S3_KEY_FILE,
};
+// A value for `s3KeyFile` that is not a path (no "/", no leading "~") is
+// taken for a key pasted in the wrong place: refused, never stored.
+export function looksLikeS3Key(v: string): boolean {
+ const s = v.trim();
+ return !!s && !s.includes("/") && !s.startsWith("~");
+}
+
// ─── The aria2c command line ───
export type Aria2cSpec = {
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -95,6 +95,8 @@ const DECLARED: EnvVarDecl[] = [
// ── runtime ────────────────────────────────────────────────────────────
{ name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." },
{ name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." },
+ { name: "ARCHIVE_ORG_S3_ACCESS", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why." },
+ { name: "ARCHIVE_ORG_S3_SECRET", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above)." },
{ name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." },
{ name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." },
{ name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." },
@@ -210,6 +212,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_WORKERS", audience: "test", default: "1", readBy: "editor/playwright.config.ts (editor/e2e/servers.ts)", doc: "How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker." },
{ name: "E2E_SERIAL_LAST", audience: "test", default: "—", readBy: "editor/playwright.config.ts", doc: "Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole." },
{ name: "E2E_BUILD_CHECKED", audience: "test", default: "—", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts", doc: "Set by a suite's config once it has checked the start-mode build's stamp, so a worker's second load of the config does not check again." },
+ { name: "E2E_FORUM_FIXTURE_DIR", audience: "test", default: "unset (the forum fetcher opens its headless browser)", readBy: "common/social/forumFixtureLoader.ts (the forum-thread fetcher)", doc: "A directory of SYNTHETIC saved thread pages (`<dir>/<threadId>/page-<N>.html`) the forum-thread fetcher reads in place of a browser, with no pause between pages. The editor's e2e server names one in each slot's test data (`test-transcripts/.forum-fixture`; `forum-resume.spec`), and nothing else sets it." },
{ name: "E2E_QUEUE", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the machine-global e2e queue (the port check still runs)." },
{ name: "E2E_PORT_CHECK", audience: "test", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the pre-run check that the suite's ports are free." },
{ name: "E2E_QUEUE_TIMEOUT", audience: "test", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds to wait for the queue before giving up." },
@@ -231,7 +234,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
{ name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
- { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
+ { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/lib/forumWalk.test.ts b/common/lib/forumWalk.test.ts
@@ -0,0 +1,96 @@
+// The forum walk's positions, pure (release 37 lane G).
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/forumWalk.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ deriveForumWalk,
+ describeForumWalk,
+ describeRetryOnBlock,
+ forumWalkStartLine,
+ heldBand,
+ meanPagePauseSeconds,
+ parseRetryOnBlock,
+ retryOnBlockProblem,
+ roughDuration,
+} from "./forumWalk";
+
+const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i);
+
+test("the held band runs down from the newest held page; an isolated low page is not part of it", () => {
+ assert.equal(heldBand([]), null);
+ assert.deepEqual(heldBand([...range(2341, 2598), 1]), { low: 2341, high: 2598 });
+ assert.deepEqual(heldBand([5, 5, 4, 2, 1]), { low: 4, high: 5 });
+});
+
+test("the live bug's state migrates: an old single cursor above the held band heals to one page above its foot", () => {
+ // posts-state.json {"cursor": "2507"}; the archive holds pages 2341–2598.
+ const d = deriveForumWalk(undefined, "2507", range(2341, 2598));
+ assert.equal(d.walk.historyPage, 2342);
+ assert.equal(d.walk.newestPage, 2598);
+ assert.equal(d.walk.oldestPageReached, 2341);
+ assert.equal(d.walk.newestPostId, undefined, "no mark yet: the first catch-up stops at any archived post");
+ assert.equal(d.notes.length, 2);
+ // An old cursor BELOW the band (a history walk that was honest) is kept.
+ assert.equal(deriveForumWalk(undefined, "2340", range(2341, 2598)).walk.historyPage, 2340);
+});
+
+test("derive, don't trust: a stored position never above the band's foot + 1, complete only when page 1 is held", () => {
+ assert.equal(deriveForumWalk({ historyPage: 100 }, undefined, range(50, 200)).walk.historyPage, 51);
+ assert.equal(deriveForumWalk({ historyPage: 40 }, undefined, range(50, 200)).walk.historyPage, 40);
+ // No position at all (posts imported, never walked): from the posts.
+ assert.equal(deriveForumWalk(undefined, undefined, range(50, 200)).walk.historyPage, 51);
+ // Marked complete, but the pages stop at 50: reopened.
+ const reopened = deriveForumWalk({ complete: true }, undefined, range(50, 200));
+ assert.equal(reopened.walk.complete, false);
+ assert.equal(reopened.walk.historyPage, 51);
+ // Every page from 1 up held: complete, whatever was stored.
+ const done = deriveForumWalk({ historyPage: 3 }, undefined, range(1, 200));
+ assert.equal(done.walk.complete, true);
+ assert.equal(done.walk.historyPage, undefined);
+ // Nothing held: the stored positions as they are.
+ assert.deepEqual(deriveForumWalk({ historyPage: 7 }, undefined, []).walk, { historyPage: 7 });
+ // A cursor that is not a page number is not read.
+ assert.deepEqual(deriveForumWalk(undefined, "abc", []).walk, {});
+});
+
+test("the start line and the channel page's status line", () => {
+ assert.equal(
+ forumWalkStartLine({ newestPage: 2600, historyPage: 2338 }),
+ "caught up to page 2600; history resumes at page 2338",
+ );
+ assert.equal(
+ forumWalkStartLine({ newestPage: 2600, catchUpPage: 2590, complete: true }),
+ "caught up to page 2600; an unfinished catch-up continues at page 2590; history complete",
+ );
+ assert.equal(forumWalkStartLine({}), "nothing read yet; history from the last page");
+ const pace = meanPagePauseSeconds(12, 5);
+ assert.equal(pace, 15);
+ assert.equal(
+ describeForumWalk({ newestPage: 2600, oldestPageReached: 2338, historyPage: 2337 }, 12.3),
+ "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~8 h)",
+ );
+ assert.equal(
+ describeForumWalk({ newestPage: 40, oldestPageReached: 1, complete: true, catchUpPage: 38 }, pace),
+ "pages read 1–40 of 40 · catch-up unfinished at page 38 · history complete",
+ );
+ assert.equal(describeForumWalk(undefined, pace), null);
+ assert.equal(describeForumWalk({}, pace), null);
+ assert.equal(roughDuration(40), "~40 s");
+ assert.equal(roughDuration(25 * 60), "~25 min");
+ assert.equal(roughDuration(3 * 3600 + 600), "~3.2 h");
+});
+
+test("retry on a block: bounds, parsing, words", () => {
+ assert.equal(retryOnBlockProblem(undefined), null);
+ assert.equal(retryOnBlockProblem({ minutes: 30, max: 12 }), null);
+ assert.match(retryOnBlockProblem({ minutes: 1, max: 12 }) ?? "", /minutes/);
+ assert.match(retryOnBlockProblem({ minutes: 30, max: 0 }) ?? "", /max/);
+ assert.match(retryOnBlockProblem({ minutes: 30, max: 1.5 }) ?? "", /max/);
+ assert.deepEqual(parseRetryOnBlock({ minutes: 30, max: 12, extra: 1 }), { minutes: 30, max: 12 });
+ assert.equal(parseRetryOnBlock({ minutes: 2, max: 12 }), undefined);
+ assert.equal(parseRetryOnBlock("30x12"), undefined);
+ assert.equal(describeRetryOnBlock({ minutes: 30, max: 12 }), "wait 30 min after a block, up to 12 tries");
+ assert.equal(describeRetryOnBlock(undefined), "off");
+});
diff --git a/common/lib/forumWalk.ts b/common/lib/forumWalk.ts
@@ -0,0 +1,211 @@
+// WHERE A FORUM THREAD'S WALK STANDS (release 37 lane G) — `posts-state.json`'s
+// `forum`, pure: no fs, client-safe (the channel page's status line reads it).
+//
+// A thread is read newest first, and two walks share the pages:
+//
+// CATCH-UP — from the thread's last page down to the first page holding an
+// archived post at or below `newestPostId` (the MARK: every post up to it is
+// held, from `historyPage` up). It is what every run does first, so the
+// newest posts always come first. A capped or interrupted catch-up keeps its
+// own resume point (`catchUpPage`) and never touches `historyPage`.
+//
+// HISTORY — from `historyPage` down to page 1. Archived posts mean nothing
+// here (pages shift down as posts are deleted); a page whose posts are all
+// archived is stepped past without counting against a run's caps. It
+// advances only `historyPage`, and ends with `complete`.
+//
+// One cursor used to serve both walks: a capped catch-up stored its own
+// position as THE cursor and the next run re-read hundreds of held pages as
+// "history". Two positions, and the posts themselves as the check on them.
+//
+// DERIVE, DON'T TRUST. At the start of every run `historyPage` is re-derived
+// from the archived posts' pages (`ForumPostInfo.page`): it is never above one
+// page past the top of the held band — the contiguous run of held pages down
+// from the newest — so a lost or overwritten position heals from the posts.
+// Drift only moves posts to LOWER page numbers (a deletion shifts every later
+// post back), so a page number read earlier is never below where the post is
+// now: starting a page or two ABOVE the band's foot re-reads held pages
+// (skipped, uncounted) and can never step over an unread one.
+
+export type ForumWalkState = {
+ // The thread's last page, as the last run saw it.
+ newestPage?: number;
+ // THE MARK: the newest post of the held band. A catch-up ends at the first
+ // page holding an archived post at or below it. Absent before the first
+ // complete catch-up (a state from before release 37): then any archived post
+ // ends the catch-up, as it always did.
+ newestPostId?: string;
+ // An unfinished catch-up's next page: a capped or interrupted catch-up read
+ // the pages above it, and the band between it and the mark is still owed.
+ catchUpPage?: number;
+ // The next older page the history walk reads. Absent when `complete`.
+ historyPage?: number;
+ // The lowest page any walk has read.
+ oldestPageReached?: number;
+ // The history walk has read page 1.
+ complete?: boolean;
+};
+
+// How many pages above the held band's foot a derived history start re-reads.
+export const FORUM_HISTORY_OVERLAP = 2;
+
+// The contiguous run of pages down from the highest one held. An isolated low
+// page — an article thread's first post, shown atop every page and stored with
+// page 1, or a range imported from saved pages — is not part of it.
+export function heldBand(pages: Iterable<number>): { low: number; high: number } | null {
+ const set = new Set<number>();
+ for (const p of pages) if (Number.isInteger(p) && p >= 1) set.add(p);
+ if (set.size === 0) return null;
+ const high = Math.max(...set);
+ let low = high;
+ while (set.has(low - 1)) low--;
+ return { low, high };
+}
+
+export type DerivedForumWalk = {
+ walk: ForumWalkState;
+ // What the derivation changed, as sentences for the job log.
+ notes: string[];
+};
+
+// The positions a run starts from: the stored ones (or, for a state written
+// before release 37, its single `cursor` read as the history position),
+// checked against the pages the archive actually holds.
+export function deriveForumWalk(
+ stored: ForumWalkState | undefined,
+ legacyCursor: string | undefined,
+ heldPages: Iterable<number>,
+): DerivedForumWalk {
+ const notes: string[] = [];
+ const walk: ForumWalkState = { ...(stored ?? {}) };
+ if (!stored && legacyCursor !== undefined) {
+ const n = Number(legacyCursor);
+ if (Number.isInteger(n) && n >= 1) {
+ walk.historyPage = n;
+ notes.push(`Read the old single resume point (page ${n}) as the history position.`);
+ }
+ }
+ const band = heldBand(heldPages);
+ if (!band) return { walk, notes };
+ walk.oldestPageReached = Math.min(walk.oldestPageReached ?? band.low, band.low);
+ walk.newestPage = Math.max(walk.newestPage ?? band.high, band.high);
+ if (band.low <= 1) {
+ // Every page from 1 to the newest held is held: the history is done.
+ if (!walk.complete) notes.push("The archive holds every page from page 1 up: history complete.");
+ walk.complete = true;
+ delete walk.historyPage;
+ return { walk, notes };
+ }
+ const fromPosts = band.low + FORUM_HISTORY_OVERLAP - 1;
+ if (walk.complete) {
+ // Complete, yet the held band stops above page 1: the posts win.
+ walk.complete = false;
+ walk.historyPage = fromPosts;
+ notes.push(
+ `Marked complete, but the archived pages stop at page ${band.low}: history resumes at page ${fromPosts}.`,
+ );
+ return { walk, notes };
+ }
+ if (walk.historyPage === undefined || walk.historyPage > fromPosts) {
+ if (walk.historyPage !== undefined) {
+ notes.push(
+ `The stored history position (page ${walk.historyPage}) is above the archived pages (held down to page ${band.low}): history resumes at page ${fromPosts}.`,
+ );
+ } else {
+ notes.push(`No history position stored: resuming at page ${fromPosts}, from the archived pages (held down to page ${band.low}).`);
+ }
+ walk.historyPage = fromPosts;
+ }
+ return { walk, notes };
+}
+
+// The log line a run starts with.
+export function forumWalkStartLine(walk: ForumWalkState): string {
+ const parts: string[] = [];
+ parts.push(walk.newestPage ? `caught up to page ${walk.newestPage}` : "nothing read yet");
+ if (walk.catchUpPage) parts.push(`an unfinished catch-up continues at page ${walk.catchUpPage}`);
+ parts.push(
+ walk.complete
+ ? "history complete"
+ : walk.historyPage
+ ? `history resumes at page ${walk.historyPage}`
+ : "history from the last page",
+ );
+ return parts.join("; ");
+}
+
+// A forum walk's pause between two page loads (xenforoFetcher.ts), and the
+// floor a channel's `postPagePauseSeconds` is held to.
+export const FORUM_DEFAULT_PAGE_PAUSE_SECONDS = 12;
+export const FORUM_MIN_PAGE_PAUSE_SECONDS = 5;
+
+// The mean pause a paced walk waits per page: the jitter (xenforoFetcher.ts,
+// jitteredPause) spans [0.85, 1.65) of the base, so its mean is 1.25×.
+export function meanPagePauseSeconds(baseSeconds: number, floorSeconds: number): number {
+ return Math.max(floorSeconds, baseSeconds) * 1.25;
+}
+
+// "~8 h", "~25 min", "~40 s".
+export function roughDuration(seconds: number): string {
+ if (seconds < 90) return `~${Math.max(1, Math.round(seconds))} s`;
+ if (seconds < 90 * 60) return `~${Math.round(seconds / 60)} min`;
+ const h = seconds / 3600;
+ return `~${h < 10 ? Math.round(h * 10) / 10 : Math.round(h)} h`;
+}
+
+// The channel page's status line: "pages read 2338–2600 of 2600 · history to
+// page 1 remaining: 2337 pages (~8 h)". Null before any page was read.
+export function describeForumWalk(
+ walk: ForumWalkState | undefined,
+ pageSeconds: number,
+): string | null {
+ if (!walk || (!walk.newestPage && !walk.oldestPageReached)) return null;
+ const top = walk.newestPage ?? walk.oldestPageReached!;
+ const low = walk.complete ? 1 : (walk.oldestPageReached ?? top);
+ const parts = [`pages read ${low}–${top} of ${top}`];
+ if (walk.catchUpPage) parts.push(`catch-up unfinished at page ${walk.catchUpPage}`);
+ if (walk.complete) {
+ parts.push("history complete");
+ } else if (walk.historyPage) {
+ parts.push(
+ `history to page 1 remaining: ${walk.historyPage} page${walk.historyPage === 1 ? "" : "s"} (${roughDuration(walk.historyPage * pageSeconds)})`,
+ );
+ }
+ return parts.join(" · ");
+}
+
+// --- retry on a block ---------------------------------------------------------------
+
+// `fetch-posts {retryOnBlock}` and `settings.social.xenforo.retryOnBlock`: a
+// challenge or a refusal stops the walk, the job waits `minutes` and runs
+// again, `max` tries in all (the first included).
+export type RetryOnBlock = { minutes: number; max: number };
+
+// The shortest wait a retry may use, the longest, and the most tries.
+export const RETRY_MIN_MINUTES = 5;
+export const RETRY_MAX_MINUTES = 24 * 60;
+export const RETRY_MAX_TRIES = 48;
+
+export function retryOnBlockProblem(r: RetryOnBlock | undefined): string | null {
+ if (!r) return null;
+ if (!Number.isInteger(r.minutes) || r.minutes < RETRY_MIN_MINUTES || r.minutes > RETRY_MAX_MINUTES) {
+ return `retryOnBlock.minutes must be a whole number from ${RETRY_MIN_MINUTES} to ${RETRY_MAX_MINUTES}.`;
+ }
+ if (!Number.isInteger(r.max) || r.max < 1 || r.max > RETRY_MAX_TRIES) {
+ return `retryOnBlock.max (the tries in all, the first included) must be a whole number from 1 to ${RETRY_MAX_TRIES}.`;
+ }
+ return null;
+}
+
+// Total over `unknown`: a valid `{minutes, max}`, else undefined.
+export function parseRetryOnBlock(v: unknown): RetryOnBlock | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ const out = { minutes: Number(r.minutes), max: Number(r.max) };
+ return retryOnBlockProblem(out) ? undefined : out;
+}
+
+// "wait 30 min, up to 12 tries" / "off".
+export function describeRetryOnBlock(r: RetryOnBlock | undefined): string {
+ return r ? `wait ${r.minutes} min after a block, up to ${r.max} tr${r.max === 1 ? "y" : "ies"}` : "off";
+}
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -165,3 +165,19 @@ test("the clip finder's labels (release 36 lane D): routed like a media draft; a
assert.equal(g.routes["clips-suggest"], GENERATION_PRESETS[p]["clips-suggest"]);
}
});
+
+test("the video assistant (release 38 lane E): local in every preset but api; a file from before keeps its preset", () => {
+ assert.ok((GENERATION_TASKS as readonly string[]).includes("video-assist"));
+ assert.deepEqual(
+ (["code", "balanced", "api", "local"] as const).map((p) => GENERATION_PRESETS[p]["video-assist"]),
+ ["local", "local", "api", "local"],
+ );
+ for (const p of ["code", "balanced", "api", "local"] as const) {
+ const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "video-assist").map((t) => [t, GENERATION_PRESETS[p][t]]));
+ const g = sanitizeGeneration({ routes });
+ assert.equal(g.preset, p);
+ assert.equal(g.routes["video-assist"], GENERATION_PRESETS[p]["video-assist"]);
+ }
+ // A file that routes nothing: the default (balanced) — local.
+ assert.equal(sanitizeGeneration({}).routes["video-assist"], "local");
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -29,7 +29,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri
// (`<project>/clip-suggestions.json`), and an answer to a comment on a clip —
// no article, no iteration. Routed like a media draft; `code` = a Claude Code
// session answers the request (`/gen`, the MCP's `generate`).
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest"] as const;
+// `video-assist` (release 38 lane E): "make the joins 0.15 s" on a video
+// project — proposed look / clip / composition edits
+// (`<project>/assist-proposals.json`) the operator applies. LOCAL in every
+// preset but `api` (the point is small edits with no Claude at hand);
+// `code` = a Claude Code session answers the request.
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
// The tasks every settings file since release 27 S6 routes.
const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
@@ -41,12 +46,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const;
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local" },
// A frame scan is on the API in `balanced`: a vision model is not a given
// on the local card, and the cheap model's reads cost cents an hour.
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -144,7 +149,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
preset:
- "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.",
+ "The balance knob: `code` (Claude Code does every task but the video assistant's, which stays local), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.",
routes: "Where each task runs: `code`, `api` or `local` (below).",
models: "The model each route runs (below).",
caps: "The spend caps in USD (below).",
@@ -222,6 +227,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
"A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model.",
"clips-suggest":
"The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`).",
+ "video-assist":
+ "The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words (\"make the joins 0.15 s with less smear\") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).",
verdicts:
"Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.",
};
diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts
@@ -13,6 +13,7 @@
import { writeJsonAtomic } from "./jsonFile-server";
import path from "node:path";
+import type { ForumWalkState } from "./forumWalk";
import { readdir, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { appendFile } from "node:fs/promises";
import { mergePageRecord } from "./waybackPages/toPost";
@@ -139,15 +140,17 @@ export type UpsertPostsResult = WritePostsResult & {
unchanged: number;
};
-// What makes two records of one post differ, for an update.
-function postContentKey(p: Post): string {
+// What makes two records of one post differ, for an update. `ignorePosition`:
+// a forum post's "#N" alone does not (a full re-walk after deletions sees every
+// later post renumbered — not an edit).
+function postContentKey(p: Post, ignorePosition = false): string {
return JSON.stringify([
p.text,
p.author,
p.links,
p.media ?? null,
p.forum?.editedAt ?? null,
- p.forum?.position ?? null,
+ ignorePosition ? null : (p.forum?.position ?? null),
p.forum?.threadTitle ?? null,
]);
}
@@ -155,8 +158,8 @@ function postContentKey(p: Post): string {
// Is `incoming` a newer record of the same post than `stored`? A later edit
// time wins; an older one never replaces a newer one; with no edit times to
// compare (or equal ones), different content is taken as the later read.
-export function supersedesPost(stored: Post, incoming: Post): boolean {
- if (postContentKey(stored) === postContentKey(incoming)) return false;
+export function supersedesPost(stored: Post, incoming: Post, opts: { ignorePosition?: boolean } = {}): boolean {
+ if (postContentKey(stored, opts.ignorePosition) === postContentKey(incoming, opts.ignorePosition)) return false;
const a = stored.forum?.editedAt;
const b = incoming.forum?.editedAt;
if (a && b && a !== b) return b > a;
@@ -172,6 +175,7 @@ export function supersedesPost(stored: Post, incoming: Post): boolean {
export async function upsertPosts(
channelRoot: string,
posts: ReadonlyArray<Post>,
+ opts: { ignorePosition?: boolean } = {},
): Promise<UpsertPostsResult> {
// One record per id from the batch: the newest of them (two page records
// of one item merge — lib/waybackPages/toPost.ts, mergePageRecord).
@@ -198,7 +202,7 @@ export async function upsertPosts(
// same capture imported again): the split-record merge decides — the
// later capture's facts, the first capture kept in page.firstSeenTs.
const pageMerged = old?.page && p.page ? mergePageRecord(old, p) : undefined;
- if (pageMerged === null || (pageMerged === undefined && old && !supersedesPost(old, p))) {
+ if (pageMerged === null || (pageMerged === undefined && old && !supersedesPost(old, p, opts))) {
unchanged++;
continue;
}
@@ -416,6 +420,8 @@ export async function readPostAvailability(
availability: r.availability,
checkedAt: r.checkedAt,
...(Array.isArray(r.history) ? { history: r.history } : {}),
+ ...(typeof r.status === "number" || r.status === null ? { status: r.status } : {}),
+ ...(typeof r.reason === "string" ? { reason: r.reason } : {}),
};
}
return out;
@@ -436,19 +442,24 @@ export async function writePostAvailability(
// Fold new observations in, appending to history ONLY when the availability
// actually changes. That keeps the file small and, more importantly, preserves
// the moment a post was first seen deleted — which is the fact worth keeping.
+// `details` (release 37 S5, a page record's original-URL check) carries the
+// answer's status and reason, kept on the record (the latest only).
export function mergePostAvailability(
existing: PostAvailabilityMap,
observations: ReadonlyMap<string, PostAvailability>,
checkedAt: string,
+ details?: ReadonlyMap<string, { status: number | null; reason: string }>,
): { map: PostAvailabilityMap; newlyDeleted: string[]; changed: number } {
const map: PostAvailabilityMap = { ...existing };
const newlyDeleted: string[] = [];
let changed = 0;
for (const [id, availability] of observations) {
const prev = map[id];
+ const detail = details?.get(id);
+ const facts = detail ? { status: detail.status, reason: detail.reason } : {};
if (prev?.availability === availability) {
// Same verdict — just refresh when we last looked.
- map[id] = { ...prev, checkedAt };
+ map[id] = { ...prev, checkedAt, ...facts };
continue;
}
changed++;
@@ -458,6 +469,7 @@ export function mergePostAvailability(
map[id] = {
availability,
checkedAt,
+ ...facts,
history: [
...(prev?.history ?? []),
...(prev
@@ -491,6 +503,11 @@ export type PostFetchState = {
// `cursor` so a normal fetch never resumes backwards, and carried through
// every write a normal fetch makes.
older?: OlderBackfillState;
+ // A FORUM THREAD's two walks (release 37 lane G, lib/forumWalk.ts): the
+ // catch-up's mark and resume point, and the history walk's position — in
+ // place of `cursor`, which a forum fetch no longer writes (an old one is
+ // read once, as the history position, and dropped).
+ forum?: ForumWalkState;
// An X SEARCH channel's walk (release 38, controller/fetchXSearch.ts): its
// only walk — it has no timeline and no older walk.
search?: XSearchWalkState;
diff --git a/common/lib/posts.ts b/common/lib/posts.ts
@@ -188,6 +188,10 @@ export type PostAvailabilityRecord = {
// Appended only when the availability CHANGES, so the file stays small and
// the first-seen-deleted moment is preserved. Mirrors the video record.
history?: { availability: PostAvailability; at: string }[];
+ // Release 37 S5 (a page record: its ORIGINAL URL's check): the last
+ // answer's HTTP status (null: none) and why, in a phrase.
+ status?: number | null;
+ reason?: string;
};
// postId -> record, stored once per channel. Videos keep a file per video dir,
diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts
@@ -345,10 +345,11 @@ export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput):
// then says nothing was proposed); a cancel is rethrown.
export async function localOpsBatch(
h: TaskHandle,
- o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown> },
+ o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown>; schema?: object },
): Promise<void> {
const { deps } = h;
- const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema: OPS_SCHEMA, build: o.build });
+ const schema = o.schema ?? OPS_SCHEMA;
+ const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema, build: o.build });
h.log(`one ops batch over the ${o.what} (~${fitted.tokens} of ${fitted.cap} prompt tokens)`);
const t0 = Date.now();
const asked = await structuredAnswer<{ ops?: unknown[] }>({
@@ -356,7 +357,7 @@ export async function localOpsBatch(
model: o.model,
system: o.system,
user: fitted.user,
- schema: OPS_SCHEMA,
+ schema,
meter: h.meter,
signal: deps.signal,
}).catch((e: unknown) => {
diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts
@@ -33,8 +33,26 @@ export const VIDEO_OPS_TEXT = [
'- {"op":"trim","id":"<clip id>","start":S,"end":E} a clip\'s in/out seconds, within 3 s of its current ones',
'- {"op":"add_clip","citation":"<citation id from the report>","after":"<entry id>"} a clip for a cited moment not in the cut',
'- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}',
+ // Release 38: the look (the video assistant's look ops, checked by the look's own rules).
+ '- {"op":"look","key":"transition","value":0.15} the join between clips in seconds (0 = hard cuts); key transitionStyle (fade, fadeblack, fadewhite, dissolve, blurslide), qr (true/false), loudness (a LUFS target, higher = louder; null = as recorded), captions (true/false), headerHeight / footerHeight (pixels, 0 = off)',
+ '- {"op":"slide","key":"blur","value":0.3} the blur slide: key travel, blur (the smear) or grain',
+ '- {"op":"room","key":"maxS","value":2} room at the clips\' edges: key tail / head (true/false), maxS (seconds the sound may run past a cut), minGap',
].join("\n");
+// OPS_SCHEMA and the look ops' key and value (release 38).
+export const VIDEO_OPS_SCHEMA = {
+ ...OPS_SCHEMA,
+ properties: {
+ ops: {
+ ...OPS_SCHEMA.properties.ops,
+ items: {
+ ...OPS_SCHEMA.properties.ops.items,
+ properties: { ...OPS_SCHEMA.properties.ops.items.properties, key: { type: "string" }, value: { type: ["number", "string", "boolean", "null"] } },
+ },
+ },
+ },
+};
+
const shortQuote = (q: string, words = 12) => {
const w = q.split(/\s+/).filter(Boolean);
return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q;
@@ -94,7 +112,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
.join("\n");
const view = () => `${cutView(manifest)}\n\nREPORT CITATIONS (add_clip takes these ids):\n${cites}`;
const applyOps = (ops: unknown[]) => {
- const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest });
+ const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest, feedback });
manifest = r.manifest;
applied.push(...r.applied);
refused.push(...r.refused);
@@ -110,7 +128,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
{
name: "apply_ops",
description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.",
- inputSchema: OPS_SCHEMA,
+ inputSchema: VIDEO_OPS_SCHEMA,
run: async (inp: { ops?: unknown }) => {
const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []);
return (
@@ -135,6 +153,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
model,
system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`,
what: "cut",
+ schema: VIDEO_OPS_SCHEMA,
build: (maxChars) => {
const budget = maxChars - feedback.length - 400;
const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback });
@@ -185,7 +204,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
model,
system,
user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`,
- schema: OPS_SCHEMA,
+ schema: VIDEO_OPS_SCHEMA,
meter: h.meter,
signal: deps.signal,
}).catch((e: unknown) => {
diff --git a/common/lib/report/draft/tasks/videoAssist.test.ts b/common/lib/report/draft/tasks/videoAssist.test.ts
@@ -0,0 +1,124 @@
+// Release 38 lane E: the `video-assist` task on the fake ollama and the fake
+// Anthropic — every request of the table asked once on each, the answer
+// checked and written as proposals; nothing applied.
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../../../testing/llm/fakeAnthropic.mjs";
+import { jsonReply, startFakeOllama, PROMPT_CAP_TOKENS, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { ASSIST_NOTE, ASSIST_REQUESTS, answerOf, writeAssistProject } from "../../../../testing/clips/assistProject.mjs";
+import { readAssistProposals } from "../../videoAssistProposals.mjs";
+import { ASSIST_CODE_MODEL, VideoAssistRefusal, noteReplyOf, noteRequestOf, planVideoAssist, runVideoAssist } from "./videoAssist";
+import type { LlmConfig } from "../../../llm";
+
+let tmp: string;
+let api: FakeAnthropic;
+let ol: FakeOllama;
+let llm: LlmConfig;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "video-assist-"));
+ api = await startFakeAnthropic();
+ ol = await startFakeOllama();
+ llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } };
+});
+
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const userOfOllama = (body: { messages: { role: string; content: string }[] }) => body.messages.find((m) => m.role === "user")!.content;
+
+for (const [route, model] of [
+ ["local", "qwen3:8b"],
+ ["api", "claude-sonnet-5-5"],
+] as const) {
+ test(`every request of the table on the ${route} model: one ask, the ops checked, assist-proposals.json written, the manifest untouched`, async () => {
+ for (const [i, row] of ASSIST_REQUESTS.entries()) {
+ const dir = path.join(tmp, `${route}-${i}`);
+ const { manifest } = writeAssistProject(dir, { deck: !!row.deck });
+ const before = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ let prompt = "";
+ if (route === "local") {
+ ol.push((body: { messages: { role: string; content: string }[] }) => {
+ prompt = userOfOllama(body);
+ return jsonReply(answerOf(row));
+ });
+ } else {
+ api.push((body: { messages: { content: unknown }[] }) => {
+ prompt = JSON.stringify(body.messages[0]!.content);
+ return toolTurn("answer", answerOf(row));
+ });
+ }
+ const out = await runVideoAssist({ project: dir, model, request: row.request, scope: row.scope ?? "all" }, { llm, now: () => new Date("2026-10-20T00:00:00.000Z") });
+ assert.equal(out.status, "done", row.request);
+ assert.ok(prompt.includes(`THE REQUEST:${route === "api" ? "\\n" : "\n"}${row.request}`), `${row.request}: the request is in the prompt`);
+ const { doc } = await readAssistProposals(dir);
+ assert.ok(doc, row.request);
+ assert.deepEqual(doc!.diff, row.diff, row.request);
+ assert.deepEqual(doc!.ops.map((o) => o.status), row.diff.map(() => "proposed"));
+ assert.equal(doc!.refused.length, row.refused.length, `${row.request}: ${JSON.stringify(doc!.refused)}`);
+ doc!.refused.forEach((r, k) => assert.match(r.why, row.refused[k]!, row.request));
+ assert.equal(doc!.model, model);
+ assert.equal(doc!.request, row.request);
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before, `${row.request}: nothing applied`);
+ assert.ok(manifest);
+ }
+ if (route === "local") {
+ // Every local ask fitted under the GPU's prompt cap (the fake refuses one over it).
+ assert.ok(ol.requests.every((b: { format?: unknown }) => !!b.format), "schema-bound");
+ }
+ });
+}
+
+test("the local view is fitted to the prompt cap however long the cut", async () => {
+ const dir = path.join(tmp, "long");
+ const { manifest } = writeAssistProject(dir);
+ for (let i = 5; i <= 400; i++) manifest.timeline.push({ type: "clip", id: `r${i}`, channel: "c", video: "v", start: i * 60, end: i * 60 + 30, cutStart: i * 60 + 5, cutEnd: i * 60 + 25, quote: "words ".repeat(30) });
+ await import("node:fs/promises").then((fs) => fs.writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)));
+ const plan = await planVideoAssist({ project: dir, model: "qwen3:8b", request: "end r333 a second later" }, { llm });
+ assert.ok(plan.estimate.inputTokens <= PROMPT_CAP_TOKENS, String(plan.estimate.inputTokens));
+ assert.match(plan.request.user, /- r333: cut 19985–20005 s/);
+ assert.match(plan.request.user, /- r399 \(not shown in full\)/);
+ assert.equal(plan.estimate.usd, 0);
+ const api = await planVideoAssist({ project: dir, model: "claude-sonnet-5-5", request: "quicker joins" }, { llm });
+ assert.ok(api.estimate.usd > 0);
+});
+
+test("the code route: a session's answer is checked as a model's, written as claude-code's; junk is refused", async () => {
+ const dir = path.join(tmp, "code");
+ writeAssistProject(dir);
+ const asked = api.requests.length + ol.requests.length;
+ const out = await runVideoAssist({ project: dir, model: ASSIST_CODE_MODEL, request: "no QR", answers: { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." } }, { llm });
+ assert.equal(out.status, "done");
+ assert.equal(api.requests.length + ol.requests.length, asked, "no model asked");
+ const { doc } = await readAssistProposals(dir);
+ assert.equal(doc!.model, "claude-code");
+ assert.deepEqual(doc!.diff, ["QR code on → off"]);
+ assert.equal(doc!.reply, "QR off.");
+ await assert.rejects(runVideoAssist({ project: dir, model: ASSIST_CODE_MODEL, request: "x", answers: { nope: 1 } }, { llm }), /the session's answer is refused: the answer has no ops list/);
+});
+
+test("refusals at the ask: no manifest, no request, an API ask over its cap; a note's text is a request only on the whole project", async () => {
+ await assert.rejects(runVideoAssist({ project: path.join(tmp, "none"), model: "qwen3:8b", request: "x" }, { llm }), /holds no video\.manifest\.json/);
+ const dir = path.join(tmp, "refusals");
+ writeAssistProject(dir, { note: "make the joins quicker" });
+ await assert.rejects(runVideoAssist({ project: dir, model: "qwen3:8b", request: " " }, { llm }), VideoAssistRefusal);
+ await assert.rejects(runVideoAssist({ project: dir, model: "claude-sonnet-5-5", request: "quicker joins", maxUsd: 0.000001 }, { llm }), /is over its cap/);
+ assert.equal(await noteRequestOf(dir, ASSIST_NOTE), "make the joins quicker");
+ await assert.rejects(noteRequestOf(dir, "n_absent00"), /no note n_absent00/);
+});
+
+test("a note's reply: the proposals in words, the refusals, where to apply", () => {
+ const text = noteReplyOf({
+ version: 1, promptVersion: "video-assist-1", at: "t", model: "m", request: "r", scope: "all", reply: "Quicker joins.",
+ ops: [{ id: "a1", op: { op: "look" }, diff: "join 0.22 s → 0.15 s", status: "proposed" }],
+ refused: [{ op: {}, why: "render.transition must be a number of seconds from 0 (a hard cut) to 3" }],
+ diff: ["join 0.22 s → 0.15 s"],
+ });
+ assert.equal(text, "Quicker joins.\nProposed 1 edit — Apply below or in the Build tab's Look panel:\n• join 0.22 s → 0.15 s\n• not done: render.transition must be a number of seconds from 0 (a hard cut) to 3");
+});
diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts
@@ -0,0 +1,249 @@
+// THE `video-assist` TASK (release 38 lane E): "make the joins 0.15 s with
+// less smear" on a video project, as PROPOSALS the operator applies.
+//
+// in a video project's directory (its video.manifest.json), a request in
+// words, a scope (look | clips | fx | all: what the view shows and the
+// ops may touch), and on the `code` route a Claude Code session's
+// answer (`answers`, read exactly as a model's)
+// ask ONE schema-bound ask (videoAssistOps ASSIST_OPS_SCHEMA: `{ops:
+// [{op, id, key, value}], reply}`) over the project's compact view --
+// the look, the slide, the room, the clips with their edges and
+// windows, the declared params of the compositions it draws
+// (assistView) -- fitted to the prompt cap on a local model; the
+// same ask on the Claude API (no tool loop: one answer is the batch)
+// check every op against the manifest (checkAssistOps: the look's rules,
+// the clip's window and the 3 s slack, the declared params)
+// out `<project>/assist-proposals.json` (videoAssistProposals.mjs): the
+// kept ops with their diff lines, the refused with their reasons.
+// NOTHING IS APPLIED: umtool's Apply does that, op by op, through
+// the manifest's writers.
+//
+// It never writes the manifest, notes.json or a clip. An API model is held to
+// `maxUsd` (the ask's estimate checked first).
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm";
+import { ASSIST_OPS_SCHEMA, ASSIST_OPS_TEXT, ASSIST_SCOPES, assistView, checkAssistOps, type AssistScope } from "../../videoAssistOps.mjs";
+import { ASSIST_PROMPT_VERSION, proposalsDocOf, writeAssistProposals, type AssistProposals } from "../../videoAssistProposals.mjs";
+import { fitLocalAsk } from "./revise-report";
+
+export const VIDEO_ASSIST_TASK = "video-assist" as const;
+/** The `model` a Claude Code session's answer is written under (the `code` route). */
+export const ASSIST_CODE_MODEL = "claude-code";
+/** A request's length, at most. */
+export const ASSIST_REQUEST_MAX = 2000;
+const ANSWER_TOKENS = 700;
+/** The view's budget on the API (a local model's is fitted to its cap). */
+const API_VIEW_CHARS = 24_000;
+
+export class VideoAssistRefusal extends Error {}
+
+export type VideoAssistDeps = {
+ llm: LlmConfig;
+ // The model, stubbed (tests).
+ ask?: <T>(system: string, user: string, schema: object, model: string, maxTokens: number) => Promise<T>;
+ log?: (line: string) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+};
+
+export type VideoAssistInput = {
+ project: string;
+ model: string;
+ request: string;
+ scope?: AssistScope;
+ note?: string;
+ maxUsd?: number;
+ answers?: unknown;
+};
+
+export const scopeOf = (s: unknown): AssistScope => ((ASSIST_SCOPES as readonly string[]).includes(String(s)) ? (s as AssistScope) : "all");
+
+/** A video project: its manifest (refused without one). */
+export async function loadAssistProject(dir: string): Promise<{ dir: string; manifest: Record<string, unknown> }> {
+ let raw: string;
+ try {
+ raw = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ } catch {
+ throw new VideoAssistRefusal(`${dir} holds no video.manifest.json: the assistant works on a video project's cut`);
+ }
+ try {
+ const manifest = JSON.parse(raw) as Record<string, unknown>;
+ if (!manifest || typeof manifest !== "object" || !Array.isArray(manifest.timeline)) throw new Error("no timeline");
+ return { dir, manifest };
+ } catch (e) {
+ throw new VideoAssistRefusal(`${dir}/video.manifest.json is not a cut (${(e as Error).message})`);
+ }
+}
+
+/** A project-level note's text, as the request (an Ask on a note). */
+export async function noteRequestOf(dir: string, noteId: string): Promise<string> {
+ let doc: unknown = null;
+ try {
+ doc = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8"));
+ } catch {
+ throw new VideoAssistRefusal(`${dir} has no notes.json: no note ${noteId}`);
+ }
+ const notes = (doc as { notes?: unknown[] })?.notes;
+ const n = Array.isArray(notes) ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown } } | undefined) : undefined;
+ if (!n) throw new VideoAssistRefusal(`no note ${noteId} in ${dir}/notes.json`);
+ if (n.anchor?.kind !== "whole") throw new VideoAssistRefusal(`${noteId} is on a part of the project: the assistant answers a note on the whole project (a clip's note is the clip editor's Ask)`);
+ if (n.status !== "open") throw new VideoAssistRefusal(`${noteId} is resolved`);
+ const text = typeof n.text === "string" ? n.text.trim() : "";
+ if (!text) throw new VideoAssistRefusal(`${noteId} has no text`);
+ return text.slice(0, ASSIST_REQUEST_MAX);
+}
+
+const SYSTEM = (scope: AssistScope) =>
+ [
+ "You adjust a video project's settings for its editor. You read the project's settings now and a request in plain words, and answer with the edit operations that carry it out — nothing else changes.",
+ "Rules: use only the operations and keys below; give the new value (\"quicker joins\" → a shorter transition than now; \"louder\" → a higher loudness target than now; \"less\" or \"more\" of something → a value a clear step from the current one, within its bounds).",
+ "If the request asks for something no operation can do, or a value outside the bounds shown, give no op for it and say so in `reply`.",
+ scope === "all" ? "" : `Only ${scope === "look" ? "the look, the slide and the room" : scope === "clips" ? "the clips' edges and room" : "the compositions' params"} may change.`,
+ "`reply` is one short plain sentence for the editor: what you changed, or why not.",
+ "",
+ ASSIST_OPS_TEXT,
+ ]
+ .filter(Boolean)
+ .join("\n");
+
+const userOf = (request: string, view: string) => `THE REQUEST:\n${request}\n\nTHE PROJECT NOW:\n${view}\n\nAnswer with the ops that carry out the request, and the reply.`;
+
+/** The prompt one ask sends: on a local model the view is fitted to its prompt cap. */
+export function assistPrompt(o: { manifest: unknown; request: string; scope: AssistScope; model: string; llm: LlmConfig }): { system: string; user: string; tokens: number } {
+ const system = SYSTEM(o.scope);
+ const build = (maxChars: number) => userOf(o.request, assistView(o.manifest, { maxChars: maxChars - o.request.length - 120, request: o.request, scope: o.scope }).text);
+ if (providerOf(o.model) === "local") {
+ const fitted = fitLocalAsk({ llm: o.llm, model: o.model, system, schema: ASSIST_OPS_SCHEMA, build });
+ return { system, user: fitted.user, tokens: fitted.tokens };
+ }
+ const user = build(API_VIEW_CHARS);
+ return { system, user, tokens: structuredPromptEstimate({ system, user, schema: ASSIST_OPS_SCHEMA }) };
+}
+
+export type VideoAssistPlan = {
+ project: string;
+ model: string;
+ provider: "api" | "local" | "code";
+ promptVersion: string;
+ scope: AssistScope;
+ estimate: { inputTokens: number; outputTokens: number; usd: number };
+ // The request a Claude Code session answers (the `code` route).
+ request: { system: string; user: string; schema: object };
+};
+
+/** What one ask would send, and roughly what it costs — nothing called, nothing written. */
+export async function planVideoAssist(input: Omit<VideoAssistInput, "answers" | "maxUsd" | "note">, deps: Pick<VideoAssistDeps, "llm">): Promise<VideoAssistPlan> {
+ const { manifest } = await loadAssistProject(input.project);
+ const scope = scopeOf(input.scope);
+ const code = input.model === ASSIST_CODE_MODEL;
+ const pr = assistPrompt({ manifest, request: input.request, scope, model: code ? "claude-sonnet-5-5" : input.model, llm: deps.llm });
+ const p = priceOf(code ? "claude-sonnet-5-5" : input.model);
+ const usd = code || providerOf(input.model) === "local" ? 0 : (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6;
+ return {
+ project: input.project,
+ model: input.model,
+ provider: code ? "code" : providerOf(input.model),
+ promptVersion: ASSIST_PROMPT_VERSION,
+ scope,
+ estimate: { inputTokens: pr.tokens, outputTokens: ANSWER_TOKENS, usd: Math.round(usd * 10_000) / 10_000 },
+ request: { system: pr.system, user: pr.user, schema: ASSIST_OPS_SCHEMA },
+ };
+}
+
+export type VideoAssistOutcome = {
+ status: "done" | "cancelled" | "failed";
+ project: string;
+ model: string;
+ request: string;
+ scope: AssistScope;
+ proposals: AssistProposals | null;
+ file: string | null;
+ usd: number;
+ byModel: ReturnType<Meter["summary"]>["byModel"];
+ summary: string;
+};
+
+const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
+
+/** The answer's ops and reply, or why it is not one. */
+export function parseAssistAnswer(raw: unknown): { ok: true; ops: unknown[]; reply: string } | { ok: false; error: string } {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "the answer is not { ops: [...] }" };
+ const a = raw as { ops?: unknown; reply?: unknown };
+ if (!Array.isArray(a.ops)) return { ok: false, error: "the answer has no ops list" };
+ if (a.ops.length > 40) return { ok: false, error: `${a.ops.length} ops is more than one request needs (at most 40)` };
+ return { ok: true, ops: a.ops, reply: typeof a.reply === "string" ? a.reply : "" };
+}
+
+/** One ask (or a session's answer), checked, written as proposals. */
+export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistDeps): Promise<VideoAssistOutcome> {
+ const log = deps.log ?? (() => {});
+ const now = () => deps.now?.() ?? new Date();
+ const request = input.request.replace(/\s+/g, " ").trim();
+ if (!request) throw new VideoAssistRefusal("the assistant needs a request: say what to change");
+ if (request.length > ASSIST_REQUEST_MAX) throw new VideoAssistRefusal(`a request is at most ${ASSIST_REQUEST_MAX} characters`);
+ const scope = scopeOf(input.scope);
+ const { manifest } = await loadAssistProject(input.project);
+ const meter = new Meter();
+ const base = { project: input.project, model: input.model, request, scope };
+ let raw: unknown;
+ if (input.answers !== undefined) {
+ log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`);
+ raw = input.answers;
+ } else {
+ const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm });
+ log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_PROMPT_VERSION})`);
+ if (providerOf(input.model) === "api" && input.maxUsd !== undefined) {
+ const p = priceOf(input.model);
+ const est = (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6;
+ if (est > input.maxUsd) throw new VideoAssistRefusal(`the ask (~$${est.toFixed(4)}) is over its cap of $${input.maxUsd}`);
+ }
+ const ask =
+ deps.ask ??
+ (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) =>
+ structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens }));
+ try {
+ raw = await ask<unknown>(pr.system, pr.user, ASSIST_OPS_SCHEMA, input.model, 2048);
+ } catch (e) {
+ if (deps.signal?.aborted) return { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" };
+ throw e;
+ }
+ }
+ const parsed = parseAssistAnswer(raw);
+ if (!parsed.ok) {
+ if (input.answers !== undefined) throw new VideoAssistRefusal(`the session's answer is refused: ${parsed.error}`);
+ throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`);
+ }
+ if (deps.signal?.aborted) return { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" };
+ // Checked against the manifest as it is NOW: a cut edited while the model thought is what the ops meet.
+ const fresh = (await loadAssistProject(input.project)).manifest;
+ const checked = checkAssistOps(fresh, parsed.ops, { request, scope });
+ for (const k of checked.ops) log(` proposed: ${k.diff}${k.warning ? ` (${k.warning})` : ""}`);
+ for (const r of checked.refused) log(` refused: ${JSON.stringify(r.op).slice(0, 120)} — ${r.why}`);
+ const proposals = proposalsDocOf({
+ at: now().toISOString(),
+ model: input.model,
+ request,
+ scope,
+ ...(input.note ? { note: input.note } : {}),
+ reply: parsed.reply || null,
+ checked,
+ });
+ const file = await writeAssistProposals(input.project, proposals);
+ const usd = Math.round(meter.usd * 1e6) / 1e6;
+ const summary =
+ (checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed (${checked.diff.join("; ")})` : "no edit proposed") +
+ (checked.refused.length ? `, ${checked.refused.length} refused` : "") +
+ ` on ${input.model}` +
+ (usd ? ` · $${usd.toFixed(4)}` : "");
+ return { ...base, status: "done", proposals, file, usd, byModel: meter.summary().byModel, summary };
+}
+
+/** The reply an Ask on a note posts: the proposals in words, and where they are applied. */
+export function noteReplyOf(p: AssistProposals): string {
+ const kept = p.ops.map((o) => `• ${o.diff}${o.warning ? ` (${o.warning})` : ""}`);
+ const refused = p.refused.map((r) => `• not done: ${r.why}`);
+ const head = kept.length ? `Proposed ${plural(kept.length, "edit")} — Apply below or in the Build tab's Look panel:` : "No edit proposed.";
+ return [p.reply ? p.reply : "", head, ...kept, ...refused].filter(Boolean).join("\n").slice(0, 3800);
+}
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -119,7 +119,7 @@ test("unknown ops and entries are refused with a reason", () => {
assert.deepEqual(
r.refused.map((x) => x.why),
[
- 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle',
+ 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle, look, slide, room',
'no entry "nope" in the cut',
"an entry cannot move after itself",
],
@@ -147,3 +147,29 @@ test("trimmed cut view (Q3): the named chapter in full, every entry still listed
assert.ok(v.text.length < full.length);
assert.equal(trimmedCutView(manifest, { maxChars: 1e6 }).short.length, 0);
});
+
+test("the look ops (release 38): look, slide and room through the look's own rules; a bad value refused with the build's sentence", () => {
+ const r = applyVideoOps(
+ manifest,
+ [
+ { op: "look", key: "transition", value: 0.15 },
+ { op: "slide", key: "blur", value: 0.3 },
+ { op: "room", key: "tail", value: 2 },
+ { op: "look", key: "transition", value: 9 },
+ { op: "look", key: "chrome", value: {} },
+ ],
+ { report, feedback: "quicker joins, less smear, keep 2 s after the last word" },
+ );
+ const render = r.manifest.render as { transition: number; slide: unknown; room: unknown };
+ assert.equal(render.transition, 0.15);
+ assert.deepEqual(render.slide, { blur: 0.3 });
+ assert.deepEqual(render.room, { tail: true, maxS: 2 });
+ assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 2]);
+ // The slide's knobs warn on a cut whose join is not a blur slide.
+ assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
+ assert.deepEqual(
+ r.refused.map((x) => x.why),
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide)'],
+ );
+ assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
+});
diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts
@@ -9,6 +9,9 @@
// trim {id, start, end} a clip's in/out, within the fetched window ±3 s
// add_clip {citation, after?} a clip for a video citation of the report not in the cut
// title {text} / subtitle {text}
+// look {key, value} a look setting (release 38: the video assistant's ops,
+// slide {key, value} ../videoAssistOps.mjs — checked by the look's own rules,
+// room {key, value} common lib/report/look.mjs, as umtool's updateRender is)
//
// The rules, in code:
// - A narration passes ./grounding.ts's hard checks, or the op is refused
@@ -23,8 +26,9 @@
// Pure: the manifest in, a new one out.
import { checkNarration, groundingInputOf, type GroundingInput } from "./grounding";
+import { checkAssistOps } from "../videoAssistOps.mjs";
-export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle"] as const;
+export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle", "look", "slide", "room"] as const;
export const TRIM_SLACK_SECONDS = 3;
@@ -63,6 +67,8 @@ export type VideoOpsContext = {
parent?: VideoManifest;
// Grounding's input; default: from the report.
grounding?: GroundingInput;
+ // The operator's words: a look op may name more seconds than a step allows.
+ feedback?: string;
};
export type VideoOpsResult = { manifest: VideoManifest; applied: AppliedVideoOp[]; refused: RefusedVideoOp[] };
@@ -173,6 +179,16 @@ export function applyVideoOps(input: VideoManifest, ops: readonly unknown[], ctx
parentClips.set(cid, e);
break;
}
+ case "look":
+ case "slide":
+ case "room": {
+ // The video assistant's look ops (release 38): the look's own rules decide.
+ const r = checkAssistOps(manifest, [op], { request: ctx.feedback ?? "", scope: "look" });
+ if (r.refused.length) refuse(r.refused[0]!.why);
+ manifest.render = r.manifest.render;
+ if (r.ops[0]?.warning) warnings = [r.ops[0].warning];
+ break;
+ }
case "title":
case "subtitle": {
const t = str(op.text, "text").trim();
diff --git a/common/lib/report/fxParams.d.mts b/common/lib/report/fxParams.d.mts
@@ -0,0 +1,24 @@
+// Types for ./fxParams.mjs (release 38 lane E): the compositions' declared params.
+
+export type ParamKind = "seconds" | "number" | "int" | "px" | "enum" | "bool" | "text";
+export type CompositionParam = {
+ readonly key: string;
+ readonly label: string;
+ readonly kind: ParamKind;
+ readonly min?: number;
+ readonly max?: number;
+ readonly values?: readonly string[];
+ readonly maxLength?: number;
+ readonly default: unknown;
+};
+type Render = Record<string, unknown> | null | undefined;
+
+export const COMPOSITION_PARAMS: Readonly<Record<string, readonly CompositionParam[]>>;
+export const COMPOSITION_IDS: readonly string[];
+export function compositionOn(render: Render, id: string): boolean;
+export function compositionsOn(render: Render): string[];
+export function settingsPathOf(id: string): string[];
+export function paramOf(id: string, key: string): CompositionParam | null;
+export function paramValue(render: Render, id: string, key: string): unknown;
+export function paramValueError(p: CompositionParam, value: unknown): string | null;
+export function chromeWithParam(render: Render, id: string, key: string, value: unknown): Record<string, unknown> | null;
diff --git a/common/lib/report/fxParams.mjs b/common/lib/report/fxParams.mjs
@@ -0,0 +1,176 @@
+// THE COMPOSITIONS' TUNABLE PARAMS (release 38 lane E): the HyperFrames
+// regions a report cut can carry (report-to-video deck.mjs, stats.mjs, fx.mjs)
+// declare here the settings a person -- or the video assistant -- may change
+// by name, each with its bounds. Only a DECLARED param can be the target of a
+// video-assist `fx` op; nothing else under `render.chrome` is reachable that
+// way, and never free HTML.
+//
+// composition id where its settings live on when
+// deck render.chrome.deck the deck is (chrome.engine "hyperframes", layout "deck")
+// stats render.chrome.stats the deck is, and chrome.stats is an object
+// fx.<effect> render.chrome.fx.<effect> that effect is an object (fx.mjs FX_KEYS)
+//
+// A param is `{ key, label, kind, min?, max?, values?, maxLength?, default }`:
+// `key` a dot path inside the composition's settings, `kind` one of seconds /
+// number / int / px / enum / bool / text. The bounds are the composition's own
+// validator's (deck.mjs validateChrome, stats.mjs validateStats, fx.mjs
+// validateFx) -- report-to-video's fx-params.test.mjs holds each declaration
+// to its validator, at both bounds and just past them, so the two cannot
+// drift. The writer (umtool updateChrome, validateChrome on the whole render)
+// still has the last word at Apply: a param whose value is fine alone but
+// clashes with another setting is refused there, with the validator's reason.
+//
+// The modules re-export their own slice (DECK_PARAMS, STATS_PARAMS,
+// FX_PARAMS). Settings that move the layout as a whole (the deck's height,
+// the footage scale, the QR's size, the pips' sizes) are left out: each is
+// bounded by another and is a Media-tab decision, not a tweak.
+//
+// PURE. Plain ESM with a .d.mts beside it.
+
+const P = (key, label, kind, more) => Object.freeze({ key, label, kind, ...more });
+const sec = (key, label, min, max, def) => P(key, label, "seconds", { min, max, default: def });
+const numP = (key, label, min, max, def) => P(key, label, "number", { min, max, default: def });
+const intP = (key, label, min, max, def) => P(key, label, "int", { min, max, default: def });
+const oneOf = (key, label, values, def) => P(key, label, "enum", { values: Object.freeze(values), default: def });
+const bool = (key, label, def) => P(key, label, "bool", { default: def });
+const text = (key, label, maxLength, def) => P(key, label, "text", { maxLength, default: def });
+
+const CORNERS = ["top-left", "top-right", "bottom-left", "bottom-right"];
+
+/** Every composition's declared params, by composition id. */
+export const COMPOSITION_PARAMS = Object.freeze({
+ deck: Object.freeze([
+ sec("motion.in", "the deck's slide in", 0, 2, 0.45),
+ sec("motion.out", "the deck's slide out", 0, 2, 0.3),
+ sec("motion.pip", "the timeline pip's move", 0, 3, 0.7),
+ numP("title.size", "the clip title's size", 24, 96, 54),
+ intP("title.maxChars", "the clip title's length", 10, 120, 48),
+ bool("qr.show", "the deck's QR code", true),
+ oneOf("subtitle.dateFormat", "the subtitle's date", ["long", "iso"], "long"),
+ oneOf("background", "the deck's background", ["panel", "flush"], "panel"),
+ oneOf("overCards", "the deck over cards", ["hide", "show"], "hide"),
+ sec("posts.seconds", "how long a post is up", 0.5, 10, 4),
+ sec("posts.hold", "the freeze under a post", 0, 10, 2.5),
+ ]),
+ stats: Object.freeze([
+ oneOf("position", "the stats panel's corner", CORNERS, "bottom-left"),
+ bool("name", "the stats panel's name", true),
+ ]),
+ "fx.kineticQuote": Object.freeze([
+ oneOf("position", "the kinetic quote's place", ["bottom", "top"], "bottom"),
+ numP("size", "the kinetic quote's size", 24, 96, 54),
+ intP("maxWords", "the kinetic quote's words a page", 3, 30, 12),
+ ]),
+ "fx.redact": Object.freeze([
+ oneOf("position", "the redaction's place", ["bottom", "top"], "bottom"),
+ numP("size", "the redaction's size", 24, 96, 44),
+ intP("maxWords", "the redaction's words a page", 3, 30, 14),
+ ]),
+ "fx.odometer": Object.freeze([
+ oneOf("position", "the odometer's corner", CORNERS, "top-right"),
+ text("label", "the odometer's label", 24, "times"),
+ oneOf("at", "when the odometer rolls", ["phrase", "start"], "phrase"),
+ ]),
+ "fx.scrubber": Object.freeze([
+ oneOf("position", "the date rail's edge", ["top", "bottom"], "top"),
+ bool("thumbs", "the date rail's thumbnails", true),
+ ]),
+ "fx.glitch": Object.freeze([
+ oneOf("on", "where the glitch tears", ["year", "every"], "year"),
+ sec("seconds", "the glitch's length", 0.2, 1.5, 0.5),
+ bool("stamp", "the glitch's date stamp", true),
+ ]),
+ "fx.thenNow": Object.freeze([
+ sec("seconds", "the THEN/NOW wipe's length", 0.3, 2, 0.6),
+ oneOf("dates", "the THEN/NOW dates", ["date", "year"], "date"),
+ ]),
+ "fx.receipts": Object.freeze([
+ oneOf("position", "the receipts' side", ["right", "left"], "right"),
+ numP("width", "the receipts' width (of the footage)", 0.2, 0.6, 0.36),
+ ]),
+ "fx.zoom": Object.freeze([numP("width", "the zoom card's width (of the footage)", 0.3, 0.9, 0.56)]),
+ "fx.punchIn": Object.freeze([
+ numP("scale", "the punch-in's scale", 1.05, 2, 1.2),
+ sec("hold", "the punch-in's hold", 0.2, 6, 1.4),
+ oneOf("anchor", "where the punch-in aims", ["upper", "center"], "upper"),
+ bool("auto", "punch in on laughs", true),
+ ]),
+ "fx.whip": Object.freeze([oneOf("on", "where the whip pans", ["every", "year"], "every")]),
+});
+
+export const COMPOSITION_IDS = Object.freeze(Object.keys(COMPOSITION_PARAMS));
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+const deckOnOf = (render) => {
+ const c = render?.chrome;
+ return isObj(c) && c.engine === "hyperframes" && c.layout === "deck";
+};
+
+/** Is this composition drawn by the cut? */
+export function compositionOn(render, id) {
+ if (!COMPOSITION_IDS.includes(id)) return false;
+ if (id === "deck") return deckOnOf(render);
+ if (id === "stats") return deckOnOf(render) && isObj(render.chrome.stats);
+ const fx = render?.chrome?.fx;
+ return isObj(fx) && isObj(fx[id.slice(3)]);
+}
+
+/** The compositions this cut draws, in COMPOSITION_IDS order. */
+export const compositionsOn = (render) => COMPOSITION_IDS.filter((id) => compositionOn(render, id));
+
+/** Where a composition's settings live under `render.chrome`, as a path. */
+export const settingsPathOf = (id) => (id === "deck" ? ["deck"] : id === "stats" ? ["stats"] : ["fx", id.slice(3)]);
+
+/** The declared param `key` of composition `id`, or null. */
+export function paramOf(id, key) {
+ return (COMPOSITION_PARAMS[id] ?? []).find((p) => p.key === key) ?? null;
+}
+
+const at = (o, keys) => keys.reduce((v, k) => (isObj(v) ? v[k] : undefined), o);
+
+/** A param's value in this render: as written, else its default. */
+export function paramValue(render, id, key) {
+ const p = paramOf(id, key);
+ if (!p) return undefined;
+ const v = at(render?.chrome, [...settingsPathOf(id), ...key.split(".")]);
+ return v === undefined || v === null ? p.default : v;
+}
+
+/** Why `value` is not a value of the declared param (null: it is). */
+export function paramValueError(p, value) {
+ const fin = typeof value === "number" && Number.isFinite(value);
+ switch (p.kind) {
+ case "seconds":
+ case "number":
+ case "px":
+ return fin && value >= p.min && value <= p.max ? null : `${p.label} is ${p.kind === "seconds" ? "seconds" : "a number"} from ${p.min} to ${p.max}`;
+ case "int":
+ return fin && Number.isInteger(value) && value >= p.min && value <= p.max ? null : `${p.label} is a whole number from ${p.min} to ${p.max}`;
+ case "enum":
+ return p.values.includes(value) ? null : `${p.label} is one of ${p.values.join(", ")}`;
+ case "bool":
+ return typeof value === "boolean" ? null : `${p.label} is true or false`;
+ case "text":
+ return typeof value === "string" && value.trim().length <= p.maxLength ? null : `${p.label} is a text of at most ${p.maxLength} characters`;
+ default:
+ return `${p.label} cannot be set here`;
+ }
+}
+
+/**
+ * `render.chrome` with one declared param set (a copy; null when the
+ * composition is not drawn by this cut or the param is not declared). The
+ * composition writer (updateChrome) validates the result as a whole.
+ */
+export function chromeWithParam(render, id, key, value) {
+ if (!compositionOn(render, id) || !paramOf(id, key)) return null;
+ const chrome = structuredClone(render.chrome);
+ let o = chrome;
+ for (const k of [...settingsPathOf(id), ...key.split(".").slice(0, -1)]) {
+ if (!isObj(o[k])) o[k] = {};
+ o = o[k];
+ }
+ o[key.split(".").at(-1)] = value;
+ return chrome;
+}
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -0,0 +1,48 @@
+// Types for ./look.mjs (release 38 lane E): the look's rules — one set of
+// checks for umtool's updateRender, the build and the video assistant.
+
+type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
+type Render = Record<string, unknown> | null | undefined;
+
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide";
+export const LOOK_KEYS: readonly LookKey[];
+export const BAND_MAX: number;
+export const TRANSITION_MAX: number;
+export const TRANSITION_DEFAULT: number;
+
+export const TRANSITION_STYLES: readonly string[];
+export function transitionStyleOf(render: Render): string;
+export type Slide = { travel: number; blur: number; grain: number };
+export const SLIDE_DEFAULTS: Readonly<Slide>;
+export const SLIDE_BOUNDS: Readonly<Record<keyof Slide, readonly [number, number]>>;
+export function slideOf(render: Render): Slide;
+export function validateTransitionStyle(manifest: unknown): string[];
+export function validateSlide(manifest: unknown): string[];
+
+export const ROOM: Readonly<{ minGap: number; maxS: number; fade: number; pad: number; detectDb: number; detectD: number }>;
+export const ROOM_EDGES: readonly ("tail" | "head")[];
+export const ROOM_BOUNDS: Readonly<{ minGap: readonly [number, number]; maxS: readonly [number, number] }>;
+export function roomOn(render: Render): boolean;
+export function clipRoom(entry: unknown, render: Render): { tail: boolean; head: boolean; minGap: number; maxS: number } | null;
+export function validateRoom(manifest: unknown): string[];
+
+export const CAPTION_STYLES: readonly string[];
+export const CAPTION_SIZES: readonly string[];
+export const CAPTION_LABEL_MAX: number;
+export const LOUDNESS_MIN: number;
+export const LOUDNESS_MAX: number;
+export const VERTICAL_RATIO: number;
+export const VERTICAL_TOLERANCE: number;
+export const DEFAULT_SOURCE_ASPECT: number;
+export function captionsOn(render: Render): boolean;
+export function loudnessOn(render: Render): boolean;
+export function loudnessTargetOf(render: Render): number | null;
+export function validateCaptions(manifest: unknown): string[];
+export function validateLoudness(manifest: unknown): string[];
+export function verticalErrors(v: unknown, who?: string): string[];
+export function validateVertical(manifest: unknown): string[];
+export function validateLook(manifest: unknown): string[];
+
+export function lookErrors(manifest: unknown): string[];
+export function applyLookPatch(manifest: Manifest, patch: Record<string, unknown>): { render: Record<string, unknown>; errors: string[] };
+export function lookOf(render: unknown): Record<string, unknown>;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -0,0 +1,350 @@
+// THE LOOK'S RULES (release 38 lane E): the render keys a person sets for a
+// cut with no deck -- `headerHeight`, `footerHeight`, `qr`, `transition`,
+// `transitionStyle`, `loudness`, `captions`, `room`, `slide` -- and the ONE set
+// of checks every writer and reader of them runs:
+//
+// umtool's updateRender (lib/report/manifest.mjs: applyLookPatch, then lookErrors)
+// the build and the lint (report-to-video look.mjs / room.mjs / transition.mjs re-export these)
+// the video assistant (./videoAssistOps.mjs: a proposed look op is checked here first)
+//
+// They lived in report-to-video until release 38 moved them here so the
+// editor's `video-assist` task (which cannot import umtool) refuses exactly
+// what the writer and the build refuse. Moved, not copied: the render modules
+// re-export every name, so nothing that imported them changed.
+//
+// PURE: no fs, no ffmpeg. Plain ESM with a .d.mts beside it.
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const q = (v) => JSON.stringify(v);
+const round2 = (n) => Number(Number(n).toFixed(2));
+
+/** The render keys the Look panel writes, in its order. */
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
+
+/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
+export const BAND_MAX = 240;
+/** `transition`: seconds, 0 (a hard cut) to this. */
+export const TRANSITION_MAX = 3;
+/** The join's length when a cut sets none (the build's default). */
+export const TRANSITION_DEFAULT = 0.5;
+
+// ---------------------------------------------------------------------------
+// The join's style (`render.transitionStyle`) and the blur slide's knobs
+// (`render.slide`) -- report-to-video/transition.mjs draws them.
+// ---------------------------------------------------------------------------
+
+export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve", "blurslide"]);
+
+/** The style a plain join uses (`render.transitionStyle`, default "fade"). */
+export const transitionStyleOf = (render) => render?.transitionStyle ?? "fade";
+
+// The push's knobs (`render.slide`): travel = fraction of the width the
+// pictures move; blur = motion-smear strength (0 none, 1 = a frame's travel);
+// grain = noise strength on the seam's frames (0 none).
+export const SLIDE_DEFAULTS = Object.freeze({ travel: 0.08, blur: 0.5, grain: 2 });
+export const SLIDE_BOUNDS = Object.freeze({ travel: Object.freeze([0, 0.5]), blur: Object.freeze([0, 2]), grain: Object.freeze([0, 20]) });
+
+/** The push's knobs, the defaults filled in. */
+export function slideOf(render) {
+ const s = render?.slide && typeof render.slide === "object" ? render.slide : {};
+ const out = {};
+ for (const k of Object.keys(SLIDE_DEFAULTS)) out[k] = Number.isFinite(s[k]) ? s[k] : SLIDE_DEFAULTS[k];
+ return out;
+}
+
+/** @param {{ render?: { transitionStyle?: unknown } }} manifest */
+export function validateTransitionStyle(manifest) {
+ const s = manifest?.render?.transitionStyle;
+ const slide = validateSlide(manifest);
+ if (s === undefined || s === null) return slide;
+ return typeof s === "string" && TRANSITION_STYLES.includes(s)
+ ? slide
+ : [`render.transitionStyle: ${JSON.stringify(s)} is not one of ${TRANSITION_STYLES.join(", ")}`, ...slide];
+}
+
+/** `render.slide`: absent, or an object of the push's knobs within bounds. */
+export function validateSlide(manifest) {
+ const s = manifest?.render?.slide;
+ if (s === undefined || s === null) return [];
+ if (typeof s !== "object" || Array.isArray(s)) return ["render.slide must be an object {travel?, blur?, grain?}"];
+ const errs = [];
+ for (const [k, v] of Object.entries(s)) {
+ const b = SLIDE_BOUNDS[k];
+ if (!b) errs.push(`render.slide.${k} is not a key (travel, blur, grain)`);
+ else if (!Number.isFinite(v) || v < b[0] || v > b[1]) errs.push(`render.slide.${k} must be a number from ${b[0]} to ${b[1]}`);
+ }
+ return errs;
+}
+
+// ---------------------------------------------------------------------------
+// Room at a clip's edges (`render.room`, a clip's `room`) -- report-to-video/
+// room.mjs says what it does to the sound and the picture.
+// ---------------------------------------------------------------------------
+
+export const ROOM = Object.freeze({
+ /** A gap between two words this long (s) is the silence the sound stops at. */
+ minGap: 0.35,
+ /** The sound never runs more than this (s) past the cut's end. */
+ maxS: 2.5,
+ /** The fade at the silence point, and the fade in at a muted head (s). */
+ fade: 0.06,
+ /** Muted picture past D, so the fade is done before the join begins (s). */
+ pad: 0.1,
+ /** silencedetect, when there are no words: noise floor (dB) and least length (s). */
+ detectDb: -35,
+ detectD: 0.3,
+});
+export const ROOM_EDGES = Object.freeze(["tail", "head"]);
+/** `render.room.minGap` and `render.room.maxS`: seconds, within these. */
+export const ROOM_BOUNDS = Object.freeze({ minGap: Object.freeze([0.1, 2]), maxS: Object.freeze([0, 10]) });
+const MIN_GAP = ROOM_BOUNDS.minGap;
+const MAX_S = ROOM_BOUNDS.maxS;
+
+/** Does the cut's render block turn room on for either edge? */
+export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true);
+
+/**
+ * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or
+ * null. The clip's `room` (false, or per-edge booleans) beats the cut's.
+ */
+export function clipRoom(entry, render) {
+ const r = isObj(render?.room) ? render.room : null;
+ const c = entry?.room;
+ if (c === false) return null;
+ const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true);
+ const tail = edge("tail");
+ const head = edge("head");
+ if (!tail && !head) return null;
+ return {
+ tail,
+ head,
+ minGap: num(r?.minGap) ? r.minGap : ROOM.minGap,
+ maxS: num(r?.maxS) ? r.maxS : ROOM.maxS,
+ };
+}
+
+/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */
+export function validateRoom(manifest) {
+ const render = manifest?.render ?? {};
+ const errors = [];
+ const room = render.room;
+ if (room !== undefined && room !== null) {
+ if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`);
+ else {
+ for (const k of Object.keys(room)) {
+ if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`);
+ }
+ for (const k of ROOM_EDGES) {
+ if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`);
+ }
+ if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) {
+ errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`);
+ }
+ if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) {
+ errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)");
+ }
+ }
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.room === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).room`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`);
+ else if (e.room === false || e.room === null) return;
+ else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`);
+ else {
+ for (const [k, v] of Object.entries(e.room)) {
+ if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`);
+ else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`);
+ }
+ }
+ });
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// Captions, loudness and a clip's vertical crop -- report-to-video/look.mjs
+// draws them.
+// ---------------------------------------------------------------------------
+
+export const CAPTION_STYLES = Object.freeze(["speakers"]);
+export const CAPTION_SIZES = Object.freeze(["m", "l"]);
+export const CAPTION_LABEL_MAX = 40;
+
+export const LOUDNESS_MIN = -30;
+export const LOUDNESS_MAX = -8;
+
+export const VERTICAL_RATIO = 9 / 16;
+/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
+export const VERTICAL_TOLERANCE = 0.03;
+export const DEFAULT_SOURCE_ASPECT = 16 / 9;
+
+export const captionsOn = (render) => isObj(render?.captions);
+export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
+/** The target in LUFS, or null when the cut sets none. */
+export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
+
+/** `render.captions`: its keys and values, and what it does not combine with. */
+export function validateCaptions(manifest) {
+ const render = manifest?.render ?? {};
+ const c = render.captions;
+ if (c === undefined || c === null) return [];
+ if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
+ const errors = [];
+ for (const k of Object.keys(c)) {
+ if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
+ }
+ if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
+ if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
+ if (c.labels !== undefined && c.labels !== null) {
+ if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
+ else {
+ for (const [k, v] of Object.entries(c.labels)) {
+ if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
+ else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
+ errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
+ }
+ }
+ }
+ }
+ if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
+ return errors;
+}
+
+/** `render.loudness`: `{target}` in LUFS. */
+export function validateLoudness(manifest) {
+ const render = manifest?.render ?? {};
+ const l = render.loudness;
+ if (l === undefined || l === null) return [];
+ if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
+ const errors = [];
+ for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
+ if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
+ errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
+ }
+ if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
+ return errors;
+}
+
+/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
+export function verticalErrors(v, who = "vertical") {
+ if (v === undefined || v === null) return [];
+ if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
+ if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
+ errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
+ }
+ const c = v.crop;
+ if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
+ errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
+ return errors;
+ }
+ const [x, y, w, h] = c;
+ const E = 1e-3;
+ if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
+ if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
+ if (w > 0 && h > 0) {
+ const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
+ const shape = (w * aspect) / h;
+ if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
+ errors.push(`${who}.crop must be 9:16 on the source (w × aspect / h ≈ 0.5625; this one is ${shape.toFixed(4)})`);
+ }
+ }
+ return errors;
+}
+
+/** Every clip's `vertical`. */
+export function validateVertical(manifest) {
+ const errors = [];
+ (manifest?.timeline ?? []).forEach((e, i) => {
+ if (e?.vertical === undefined) return;
+ const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
+ if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
+ else errors.push(...verticalErrors(e.vertical, who));
+ });
+ return errors;
+}
+
+/** All of the look's keys: the build's validators and the lint call this. */
+export function validateLook(manifest) {
+ // render.room and a clip's room (release 36 lane E) are part of the look.
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
+}
+
+// ---------------------------------------------------------------------------
+// A patch of the look, applied: what updateRender writes, and what the video
+// assistant checks a proposed op against before anything is written.
+// ---------------------------------------------------------------------------
+
+/** Every reason this manifest's look cannot be built (the join's style and the slide, then the rest). */
+export const lookErrors = (manifest) => [...validateTransitionStyle(manifest), ...validateLook(manifest)];
+
+/**
+ * A patch of LOOK_KEYS applied to a render block: `null` removes a key (the
+ * build's default again); `qr: true` turns the code back on (removes a
+ * `false`; an object of settings is kept), `qr: false` turns it off; the
+ * heights and the join's length are checked here, everything else by the
+ * build's own validators against the manifest as it would be.
+ *
+ * Pure: returns `{ render, errors }` -- the new render block (a copy) and
+ * every sentence that refuses it (empty: it can be written).
+ *
+ * @param {{ render?: Record<string, unknown>, timeline?: unknown[] } & Record<string, unknown>} manifest
+ * @param {Record<string, unknown>} patch
+ * @returns {{ render: Record<string, unknown>, errors: string[] }}
+ */
+export function applyLookPatch(manifest, patch) {
+ const base = isObj(manifest?.render) ? manifest.render : {};
+ if (!isObj(patch)) return { render: { ...base }, errors: ["the patch must be an object of render keys"] };
+ const errors = [];
+ for (const k of Object.keys(patch)) {
+ if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
+ else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ }
+ if (errors.length) return { render: { ...base }, errors };
+ const render = { ...base };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) {
+ delete render[k];
+ continue;
+ }
+ switch (k) {
+ case "headerHeight":
+ case "footerHeight":
+ if (!(Number.isInteger(v) && v >= 0 && v <= BAND_MAX)) errors.push(`render.${k} must be a whole number of pixels from 0 to ${BAND_MAX}`);
+ else render[k] = v;
+ break;
+ case "qr":
+ if (v === false) render.qr = false;
+ else if (v === true) {
+ if (render.qr === false) delete render.qr;
+ } else errors.push("render.qr must be true (on) or false (off)");
+ break;
+ case "transition":
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > TRANSITION_MAX) errors.push(`render.transition must be a number of seconds from 0 (a hard cut) to ${TRANSITION_MAX}`);
+ else render.transition = round2(v);
+ break;
+ case "transitionStyle":
+ if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
+ else render.transitionStyle = v;
+ break;
+ default:
+ // loudness, captions, room, slide: stored as given; the build's validators below say what is wrong.
+ render[k] = v;
+ }
+ }
+ errors.push(...lookErrors({ ...manifest, render }));
+ return { render, errors };
+}
+
+/** The look keys of a render block as written (absent keys left out). */
+export function lookOf(render) {
+ const r = isObj(render) ? render : {};
+ /** @type {Record<string, unknown>} */
+ const out = {};
+ for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
+ return out;
+}
diff --git a/common/lib/report/videoAssistOps.d.mts b/common/lib/report/videoAssistOps.d.mts
@@ -0,0 +1,34 @@
+// Types for ./videoAssistOps.mjs (release 38 lane E): the video assistant's checked ops.
+
+export type AssistOpName = "look" | "slide" | "room" | "clip_edges" | "clip_room" | "fx";
+export type AssistScope = "look" | "clips" | "fx" | "all";
+export type AssistOp = { op: AssistOpName } & Record<string, unknown>;
+
+/** How a kept op is performed: the look's writer, the clip editor's, or the composition's. */
+export type AssistApply =
+ | { writer: "render"; patch: Record<string, unknown> }
+ | { writer: "clip"; body: { op: "trim"; clip: string; cutStart: number; cutEnd: number } | { op: "room"; clip: string; room: false | { tail?: boolean; head?: boolean } | null } }
+ | { writer: "chrome"; id: string; param: string; value: unknown };
+
+export type CheckedAssistOp = { op: AssistOp; diff: string; apply: AssistApply; warning?: string };
+export type RefusedAssistOp = { index: number; op: unknown; why: string };
+
+export const ASSIST_OP_NAMES: readonly AssistOpName[];
+export const ASSIST_SCOPES: readonly AssistScope[];
+export const EDGE_SLACK_SECONDS: number;
+export const MIN_CUT_SECONDS: number;
+export function secondsNamedIn(request: string): number;
+export function lookWords(key: string, value: unknown, render?: Record<string, unknown>): string;
+export function clipWindow(
+ entry: Record<string, unknown>,
+ render?: Record<string, unknown>,
+): { cut: { start: number; end: number }; window: { start: number; end: number }; hasCut: boolean };
+export function checkAssistOps(
+ manifest: unknown,
+ ops: readonly unknown[],
+ o?: { request?: string; scope?: string },
+): { ops: CheckedAssistOp[]; refused: RefusedAssistOp[]; diff: string[]; manifest: Record<string, unknown> };
+export function assistView(manifest: unknown, o?: { maxChars?: number; request?: string; scope?: string }): { text: string; clips: { shown: string[]; short: string[] } };
+export const ASSIST_OPS_TEXT: string;
+export function normalizeAssistOp(raw: unknown): unknown;
+export const ASSIST_OPS_SCHEMA: Readonly<Record<string, unknown>>;
diff --git a/common/lib/report/videoAssistOps.mjs b/common/lib/report/videoAssistOps.mjs
@@ -0,0 +1,522 @@
+// THE VIDEO ASSISTANT'S OPS (release 38 lane E): "make the joins 0.15 s with
+// less smear" as checked edits of a video project's manifest. A model (or a
+// Claude Code session, or nobody: every op is also a field of the Look panel
+// or the clip editor) proposes them; code checks each against the manifest
+// as it is; the operator applies them. Nothing here writes a file.
+//
+// look {key, value} a LOOK_KEYS render key (common look.mjs), checked by applyLookPatch
+// slide {travel?, blur?, grain?} the blur slide's knobs, within SLIDE_BOUNDS
+// room {tail?, head?, maxS?, minGap?} room at the clips' edges, within ROOM_BOUNDS
+// clip_edges {id, start?, end?} a clip's cut, in source seconds: inside the clip's source
+// window and at most EDGE_SLACK_SECONDS from where it is,
+// unless the request itself names more seconds
+// clip_room {id, tail?, head?, off?, reset?} one clip's room (off: none; reset: the cut's again)
+// fx {id, param, value} a DECLARED param of a composition the cut draws
+// (./fxParams.mjs) -- never free HTML
+//
+// Each op is applied in turn to a COPY of the manifest, so a later op is
+// checked against the earlier ones; a refused op refuses itself only, with its
+// reason. Each kept op carries a diff line ("join 0.22 s → 0.15 s") and the
+// writer that performs it (`apply`): umtool's updateRender for the look, the
+// clip editor's writer (runClipEditorOp trim / room) for a clip, updateChrome
+// for a composition. umtool re-checks an op against the manifest at Apply
+// time (checkAssistOps on it again), so a proposal made against an older
+// manifest is applied to the current one or refused -- never written blind.
+//
+// PURE. Plain ESM with a .d.mts beside it.
+
+import {
+ LOOK_KEYS,
+ LOUDNESS_MAX,
+ LOUDNESS_MIN,
+ ROOM,
+ ROOM_BOUNDS,
+ SLIDE_BOUNDS,
+ SLIDE_DEFAULTS,
+ TRANSITION_DEFAULT,
+ TRANSITION_MAX,
+ TRANSITION_STYLES,
+ applyLookPatch,
+ clipRoom,
+ validateRoom,
+} from "./look.mjs";
+import { COMPOSITION_PARAMS, chromeWithParam, compositionOn, compositionsOn, paramOf, paramValue, paramValueError } from "./fxParams.mjs";
+
+export const ASSIST_OP_NAMES = Object.freeze(["look", "slide", "room", "clip_edges", "clip_room", "fx"]);
+export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]);
+/** A clip's edge moves at most this far (s) in one op, unless the request names more seconds. */
+export const EDGE_SLACK_SECONDS = 3;
+/** The shortest cut a clip may have (the clip editor's writer refuses less). */
+export const MIN_CUT_SECONDS = 0.5;
+
+const SCOPE_OF = Object.freeze({ look: "look", slide: "look", room: "look", clip_edges: "clips", clip_room: "clips", fx: "fx" });
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (n) => Math.round(n * 100) / 100;
+const s2 = (n) => r2(n).toFixed(2).replace(/\.?0+$/, "") || "0";
+
+class Refusal extends Error {}
+const refuse = (why) => {
+ throw new Refusal(why);
+};
+
+/** A number from what a model wrote ("0.15", "0.15 s", 0.15). */
+function numOf(v, what) {
+ if (fin(v)) return v;
+ if (typeof v === "string") {
+ const m = /^\s*(-?\d+(?:\.\d+)?)\s*(?:s|sec|secs|seconds?|lufs|px)?\s*$/i.exec(v);
+ if (m) return Number(m[1]);
+ }
+ return refuse(`${what} must be a number`);
+}
+
+const boolOf = (v, what) => {
+ if (typeof v === "boolean") return v;
+ if (v === "on" || v === "true") return true;
+ if (v === "off" || v === "false") return false;
+ return refuse(`${what} must be true or false`);
+};
+
+/** The most seconds the request names ("the first 5 seconds", "2.5 s"), or 0. */
+export function secondsNamedIn(request) {
+ let most = 0;
+ for (const m of String(request ?? "").matchAll(/(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b/gi)) most = Math.max(most, Number(m[1]));
+ return most;
+}
+
+// ---------------------------------------------------------------------------
+// What each setting is called in a diff line.
+// ---------------------------------------------------------------------------
+
+const STYLE_WORDS = Object.freeze({ fade: "crossfade", fadeblack: "dip to black", fadewhite: "dip to white", dissolve: "dissolve", blurslide: "blur slide" });
+
+/** A look key's value as a person reads it. */
+export function lookWords(key, value, render = {}) {
+ switch (key) {
+ case "transition":
+ return value === undefined || value === null ? `${s2(TRANSITION_DEFAULT)} s` : Number(value) === 0 ? "a hard cut" : `${s2(Number(value))} s`;
+ case "transitionStyle":
+ return STYLE_WORDS[value ?? "fade"] ?? String(value);
+ case "headerHeight":
+ case "footerHeight":
+ return value === 0 ? "off" : value === undefined || value === null ? "on" : `${value} px`;
+ case "qr":
+ return value === false ? "off" : "on";
+ case "loudness":
+ return isObj(value) && fin(value.target) ? `${s2(value.target)} LUFS` : "as recorded";
+ case "captions":
+ return isObj(value) ? `on${value.size === "l" ? " (large)" : ""}` : "off";
+ case "room": {
+ const r = isObj(value) ? value : {};
+ const edges = ["tail", "head"].filter((k) => r[k] === true);
+ return edges.length ? edges.join(" + ") : "off";
+ }
+ case "slide": {
+ const s = { ...SLIDE_DEFAULTS, ...(isObj(value) ? value : {}) };
+ return `travel ${s2(s.travel)}, smear ${s2(s.blur)}, grain ${s2(s.grain)}`;
+ }
+ default:
+ return JSON.stringify(value ?? null);
+ }
+}
+
+const LOOK_LABEL = Object.freeze({
+ transition: "join",
+ transitionStyle: "join style",
+ headerHeight: "header",
+ footerHeight: "timeline footer",
+ qr: "QR code",
+ loudness: "loudness",
+ captions: "speaker captions",
+ room: "room at the edges",
+ slide: "blur slide",
+});
+const SLIDE_LABEL = Object.freeze({ travel: "slide travel", blur: "smear", grain: "grain" });
+const ROOM_LABEL = Object.freeze({ tail: "room tail", head: "room head", maxS: "room tail up to", minGap: "room's silence gap" });
+
+const onOff = (b) => (b ? "on" : "off");
+const arrow = (label, from, to) => `${label} ${from} → ${to}`;
+
+// ---------------------------------------------------------------------------
+// One op, normalised and checked against the manifest as it is.
+// ---------------------------------------------------------------------------
+
+/** A clip's cut and the window it may move in. */
+export function clipWindow(entry, render = {}) {
+ const hasCut = fin(entry.cutStart) && fin(entry.cutEnd);
+ const cut = { start: hasCut ? entry.cutStart : entry.start, end: hasCut ? entry.cutEnd : entry.end };
+ // A clip with a cut moves inside its extent (start–end, what was reviewed
+ // and fetched); one without inside its edges widened by the fetch pad.
+ const pad = hasCut ? 0 : fin(render.fetchPad) ? render.fetchPad : 0;
+ const lo = Math.max(0, (fin(entry.start) ? entry.start : cut.start) - pad);
+ const hi = (fin(entry.end) ? entry.end : cut.end) + pad;
+ return { cut, window: { start: r2(lo), end: r2(hi) }, hasCut };
+}
+
+const clipOf = (manifest, id) => {
+ if (typeof id !== "string" || !id) refuse("a clip op names its clip (id)");
+ const e = (manifest.timeline ?? []).find((x) => x?.id === id);
+ if (!e) refuse(`no clip "${id}" in the cut`);
+ if (e.type !== "clip") refuse(`"${id}" is a ${e.type ?? "non-clip"} entry, not a clip`);
+ return e;
+};
+
+/** A look key's patch value from what a model wrote. */
+function lookValueOf(key, value, render) {
+ if (value === null) return null;
+ switch (key) {
+ case "transition":
+ return numOf(value, "the join's length");
+ case "headerHeight":
+ case "footerHeight":
+ if (typeof value === "boolean") return value ? null : 0;
+ return numOf(value, `the ${LOOK_LABEL[key]}'s height`);
+ case "qr":
+ return boolOf(value, "the QR code");
+ case "loudness":
+ if (value === false || value === "off") return null;
+ if (isObj(value)) return { target: numOf(value.target, "the loudness target") };
+ return { target: numOf(value, "the loudness target") };
+ case "captions":
+ if (value === true || value === "on") return isObj(render.captions) ? render.captions : { style: "speakers" };
+ if (value === false || value === "off") return null;
+ return value;
+ case "room":
+ if (value === false || value === "off") return null;
+ if (isObj(value)) return { ...(isObj(render.room) ? render.room : {}), ...value };
+ return value;
+ case "slide":
+ if (isObj(value)) return { ...(isObj(render.slide) ? render.slide : {}), ...value };
+ return value;
+ default:
+ return value;
+ }
+}
+
+/**
+ * One op against `manifest` (mutated: the op's effect is applied to it).
+ * Returns `{ op, diff, apply }` or throws a Refusal.
+ */
+function checkOne(manifest, raw, ctx) {
+ const op = isObj(raw) ? raw : refuse("an op is an object");
+ const name = op.op;
+ if (!ASSIST_OP_NAMES.includes(name)) refuse(`no op "${String(name)}" — the ops are ${ASSIST_OP_NAMES.join(", ")}`);
+ if (ctx.scope !== "all" && SCOPE_OF[name] !== ctx.scope) refuse(`a ${name} op is outside what was asked about (${ctx.scope})`);
+ const render = isObj(manifest.render) ? manifest.render : {};
+ const montage = render.montage !== undefined && render.montage !== null;
+ const lookPatch = (patch, diff, norm, label) => {
+ const r = applyLookPatch(manifest, patch);
+ if (r.errors.length) refuse(r.errors.join("; "));
+ if (JSON.stringify(r.render) === JSON.stringify(render)) refuse(`${label} is already that`);
+ manifest.render = r.render;
+ return { op: norm, diff, apply: { writer: "render", patch } };
+ };
+ switch (name) {
+ case "look": {
+ const key = typeof op.key === "string" ? op.key.trim() : "";
+ if (!LOOK_KEYS.includes(key)) refuse(`"${key}" is not a look setting (${LOOK_KEYS.join(", ")})`);
+ if (montage && (key === "loudness" || key === "captions" || key === "room")) refuse(`a montage has no ${LOOK_LABEL[key]} of the look's (render.montage sets its own)`);
+ const value = lookValueOf(key, op.value, render);
+ const after = value === null ? undefined : value;
+ const diff = arrow(LOOK_LABEL[key], lookWords(key, render[key], render), lookWords(key, after, render));
+ return lookPatch({ [key]: value }, diff, { op: "look", key, value }, LOOK_LABEL[key]);
+ }
+ case "slide": {
+ const given = Object.keys(SLIDE_BOUNDS).filter((k) => op[k] !== undefined && op[k] !== null);
+ if (!given.length) refuse("a slide op sets travel, blur (the smear) or grain");
+ const was = { ...SLIDE_DEFAULTS, ...(isObj(render.slide) ? render.slide : {}) };
+ const next = { ...(isObj(render.slide) ? render.slide : {}) };
+ const parts = [];
+ for (const k of given) {
+ const v = numOf(op[k], SLIDE_LABEL[k]);
+ const [lo, hi] = SLIDE_BOUNDS[k];
+ if (v < lo || v > hi) refuse(`${SLIDE_LABEL[k]} ${s2(v)} is outside ${lo}–${hi}`);
+ next[k] = r2(v);
+ if (r2(v) !== r2(was[k])) parts.push(arrow(SLIDE_LABEL[k], s2(was[k]), s2(v)));
+ }
+ if (!parts.length) refuse(`the blur slide is already ${given.map((k) => `${SLIDE_LABEL[k]} ${s2(was[k])}`).join(", ")}`);
+ const style = render.transitionStyle ?? "fade";
+ const r = lookPatch({ slide: next }, parts.join(", "), { op: "slide", ...Object.fromEntries(given.map((k) => [k, next[k]])) }, "the blur slide");
+ // The knobs move a blur slide only: say so rather than let it look like it worked.
+ return style === "blurslide" ? r : { ...r, warning: `the join is a ${STYLE_WORDS[style] ?? style}: the slide's knobs show once the join style is blur slide` };
+ }
+ case "room": {
+ if (montage) refuse("a montage has no room at the edges (it cuts to its phrases)");
+ const was = isObj(render.room) ? render.room : {};
+ const next = { ...was };
+ const parts = [];
+ for (const k of ["tail", "head"]) {
+ if (op[k] === undefined || op[k] === null) continue;
+ // "keep 2 s after the last word": a number for the tail is the tail on, up to that.
+ if (k === "tail" && typeof op[k] !== "boolean" && op.maxS === undefined) {
+ const n = numOf(op[k], "the room's tail");
+ next.tail = true;
+ op.maxS = n;
+ } else next[k] = boolOf(op[k], ROOM_LABEL[k]);
+ if ((was[k] === true) !== next[k]) parts.push(arrow(ROOM_LABEL[k], onOff(was[k] === true), onOff(next[k])));
+ }
+ for (const k of ["maxS", "minGap"]) {
+ if (op[k] === undefined || op[k] === null) continue;
+ const v = numOf(op[k], ROOM_LABEL[k]);
+ const [lo, hi] = ROOM_BOUNDS[k];
+ if (v < lo || v > hi) refuse(`${ROOM_LABEL[k]} ${s2(v)} s is outside ${lo}–${hi} s`);
+ next[k] = r2(v);
+ const before = fin(was[k]) ? was[k] : ROOM[k];
+ if (r2(before) !== r2(v)) parts.push(arrow(ROOM_LABEL[k], `${s2(before)} s`, `${s2(v)} s`));
+ }
+ if (!parts.length) refuse("the room is already that");
+ if (next.tail !== true && next.head !== true && (next.maxS !== undefined || next.minGap !== undefined) && op.tail === undefined && op.head === undefined) {
+ // A number for an edge that is off would do nothing: turn the tail on with it.
+ next.tail = true;
+ op.tail = true;
+ parts.unshift(arrow(ROOM_LABEL.tail, "off", "on"));
+ }
+ const norm = { op: "room", ...Object.fromEntries(["tail", "head", "maxS", "minGap"].filter((k) => op[k] !== undefined && op[k] !== null).map((k) => [k, next[k]])) };
+ const r = lookPatch({ room: next }, parts.join(", "), norm, "the room");
+ return (render.transition ?? TRANSITION_DEFAULT) === 0 ? { ...r, warning: "the cut has hard cuts (join 0 s): room needs a join to make room for" } : r;
+ }
+ case "clip_edges": {
+ const e = clipOf(manifest, op.id);
+ const { cut, window } = clipWindow(e, render);
+ const start = op.start === undefined || op.start === null ? cut.start : r2(numOf(op.start, "the clip's in"));
+ const end = op.end === undefined || op.end === null ? cut.end : r2(numOf(op.end, "the clip's out"));
+ if (start === cut.start && end === cut.end) refuse(`${e.id} is already cut ${s2(cut.start)}–${s2(cut.end)} s`);
+ if (!(end - start >= MIN_CUT_SECONDS)) refuse(`${e.id}: a cut is at least ${MIN_CUT_SECONDS} s (${s2(start)}–${s2(end)})`);
+ if (start < window.start - 0.005 || end > window.end + 0.005) {
+ refuse(`${e.id}: ${s2(start)}–${s2(end)} s is outside the clip's source window (${s2(window.start)}–${s2(window.end)} s) — widen it in the clip editor first`);
+ }
+ const slack = Math.max(EDGE_SLACK_SECONDS, ctx.namedSeconds);
+ const moved = Math.max(Math.abs(start - cut.start), Math.abs(end - cut.end));
+ if (moved > slack + 0.005) {
+ refuse(`${e.id}: moves an edge ${s2(moved)} s; one op moves an edge at most ${s2(slack)} s (name the seconds in the request, or drag it in the clip editor)`);
+ }
+ const parts = [];
+ if (start !== cut.start) parts.push(arrow(`${e.id} in`, `${s2(cut.start)} s`, `${s2(start)} s`));
+ if (end !== cut.end) parts.push(arrow(`${e.id} out`, `${s2(cut.end)} s`, `${s2(end)} s`));
+ // The manifest as it would be: the clip editor's trim (a cut inside the extent, or the edges themselves).
+ if (fin(e.cutStart) && fin(e.cutEnd)) {
+ e.cutStart = start;
+ e.cutEnd = end;
+ } else {
+ e.start = start;
+ e.end = end;
+ }
+ return { op: { op: "clip_edges", id: e.id, start, end }, diff: parts.join(", "), apply: { writer: "clip", body: { op: "trim", clip: e.id, cutStart: start, cutEnd: end } } };
+ }
+ case "clip_room": {
+ const e = clipOf(manifest, op.id);
+ if (montage) refuse("a montage has no room at the edges (it cuts to its phrases)");
+ const words = (room) => {
+ const r = clipRoom({ room }, render);
+ return room === undefined || room === null ? `the cut's (${r ? ["tail", "head"].filter((k) => r[k]).join(" + ") : "none"})` : room === false ? "none" : r ? ["tail", "head"].filter((k) => r[k]).join(" + ") : "none";
+ };
+ let room;
+ if (op.reset === true) room = null;
+ else if (op.off === true) room = false;
+ else {
+ const was = isObj(e.room) ? e.room : {};
+ room = { ...was };
+ for (const k of ["tail", "head"]) if (op[k] !== undefined && op[k] !== null) room[k] = boolOf(op[k], `${e.id}'s room ${k}`);
+ if (!Object.keys(room).length) refuse("a clip_room op sets tail, head, off or reset");
+ }
+ const before = e.room;
+ if (JSON.stringify(before ?? null) === JSON.stringify(room)) refuse(`${e.id}'s room is already ${words(room)}`);
+ const errors = validateRoom({ timeline: [{ ...e, room: room ?? undefined }] });
+ if (errors.length) refuse(errors.join("; "));
+ if (room === null) delete e.room;
+ else e.room = room;
+ const norm = { op: "clip_room", id: e.id, ...(room === null ? { reset: true } : room === false ? { off: true } : room) };
+ return { op: norm, diff: arrow(`${e.id} room`, words(before), words(room ?? undefined)), apply: { writer: "clip", body: { op: "room", clip: e.id, room } } };
+ }
+ case "fx": {
+ const id = typeof op.id === "string" ? op.id.trim() : "";
+ const param = typeof op.param === "string" ? op.param.trim() : "";
+ if (!COMPOSITION_PARAMS[id]) refuse(`"${id}" is not a composition (${Object.keys(COMPOSITION_PARAMS).join(", ")})`);
+ if (!compositionOn(render, id)) refuse(`this cut does not draw ${id}${id === "deck" ? "" : " (turn it on in the Media tab first)"}`);
+ const p = paramOf(id, param);
+ if (!p) refuse(`${id} has no param "${param}" (it declares ${COMPOSITION_PARAMS[id].map((x) => x.key).join(", ")})`);
+ let value = op.value;
+ if (p.kind === "bool" && typeof value !== "boolean") value = boolOf(value, p.label);
+ if ((p.kind === "seconds" || p.kind === "number" || p.kind === "int" || p.kind === "px") && typeof value === "string") value = numOf(value, p.label);
+ if (typeof value === "number" && p.kind !== "int") value = r2(value);
+ const bad = paramValueError(p, value);
+ if (bad) refuse(bad);
+ const was = paramValue(render, id, param);
+ if (JSON.stringify(was) === JSON.stringify(value)) refuse(`${p.label} is already ${JSON.stringify(value)}`);
+ const unit = p.kind === "seconds" ? " s" : "";
+ const say = (v) => (typeof v === "boolean" ? onOff(v) : typeof v === "number" ? `${s2(v)}${unit}` : String(v));
+ manifest.render = { ...render, chrome: chromeWithParam(render, id, param, value) };
+ return { op: { op: "fx", id, param, value }, diff: arrow(p.label, say(was), say(value)), apply: { writer: "chrome", id, param, value } };
+ }
+ default:
+ return refuse(`no op "${String(name)}"`);
+ }
+}
+
+/**
+ * Check a batch of ops against a manifest. Each op is checked against the
+ * manifest as the ops before it left it.
+ *
+ * @param {unknown} manifest the project's video.manifest.json
+ * @param {readonly unknown[]} ops
+ * @param {{ request?: string, scope?: string }} [o]
+ * @returns {{ ops: { op: object, diff: string, apply: object, warning?: string }[], refused: { index: number, op: unknown, why: string }[], diff: string[], manifest: object }}
+ */
+export function checkAssistOps(manifest, ops, { request = "", scope = "all" } = {}) {
+ const m = structuredClone(isObj(manifest) ? manifest : {});
+ if (!Array.isArray(m.timeline)) m.timeline = [];
+ const ctx = { scope: ASSIST_SCOPES.includes(scope) ? scope : "all", namedSeconds: secondsNamedIn(request) };
+ const kept = [];
+ const refused = [];
+ for (const [index, raw] of (Array.isArray(ops) ? ops : []).entries()) {
+ try {
+ kept.push(checkOne(m, normalizeAssistOp(structuredClone(raw)), ctx));
+ } catch (e) {
+ if (!(e instanceof Refusal)) throw e;
+ refused.push({ index, op: raw, why: e.message });
+ }
+ }
+ return { ops: kept, refused, diff: kept.map((k) => k.diff), manifest: m };
+}
+
+// ---------------------------------------------------------------------------
+// What the model reads: the look, the slide, the room, the clips, the
+// declared params -- trimmed to a character budget.
+// ---------------------------------------------------------------------------
+
+const shortWords = (q, n = 10) => {
+ const w = String(q ?? "").split(/\s+/).filter(Boolean);
+ return w.length > n ? `${w.slice(0, n).join(" ")} …` : w.join(" ");
+};
+
+/**
+ * The project as the assistant reads it. `scope` leaves out what was not asked
+ * about; the clips the request names come first; a clip past the budget is
+ * listed by its id alone, so an op may still name it.
+ *
+ * @param {unknown} manifest
+ * @param {{ maxChars?: number, request?: string, scope?: string }} [o]
+ * @returns {{ text: string, clips: { shown: string[], short: string[] } }}
+ */
+export function assistView(manifest, { maxChars = 6000, request = "", scope = "all" } = {}) {
+ const m = isObj(manifest) ? manifest : {};
+ const render = isObj(m.render) ? m.render : {};
+ const want = (s) => scope === "all" || scope === s;
+ const out = [];
+ if (want("look")) {
+ const slide = { ...SLIDE_DEFAULTS, ...(isObj(render.slide) ? render.slide : {}) };
+ const room = isObj(render.room) ? render.room : {};
+ out.push(
+ "THE LOOK NOW (look ops: key = value):",
+ `- transition = ${fin(render.transition) ? render.transition : TRANSITION_DEFAULT} (the join between clips, seconds; 0 = a hard cut; up to ${TRANSITION_MAX})`,
+ `- transitionStyle = ${render.transitionStyle ?? "fade"} (one of ${TRANSITION_STYLES.join(", ")}; fade = crossfade, blurslide = a quick blurred push)`,
+ `- headerHeight = ${render.headerHeight ?? "default"}, footerHeight = ${render.footerHeight ?? "default"} (pixels; 0 = off)`,
+ `- qr = ${render.qr === false ? "false" : "true"} (the QR code on each clip)`,
+ `- loudness = ${isObj(render.loudness) ? render.loudness.target : "null (as recorded)"} (target LUFS, ${LOUDNESS_MIN} to ${LOUDNESS_MAX}; higher is louder)`,
+ `- captions = ${isObj(render.captions) ? "true" : "false"} (speaker captions)`,
+ `SLIDE (slide op; used when transitionStyle is blurslide): travel = ${slide.travel} (${SLIDE_BOUNDS.travel.join("–")}), blur = ${slide.blur} (the smear, ${SLIDE_BOUNDS.blur.join("–")}), grain = ${slide.grain} (${SLIDE_BOUNDS.grain.join("–")})`,
+ `ROOM (room op): tail = ${room.tail === true} (the sound runs on to the first silence after the cut), head = ${room.head === true} (a muted lead-in), maxS = ${fin(room.maxS) ? room.maxS : ROOM.maxS} (seconds the tail may run past the cut's end, ${ROOM_BOUNDS.maxS.join("–")}), minGap = ${fin(room.minGap) ? room.minGap : ROOM.minGap} (the silence that ends it, ${ROOM_BOUNDS.minGap.join("–")})`,
+ );
+ }
+ if (want("fx")) {
+ const on = compositionsOn(render);
+ if (on.length) {
+ out.push("COMPOSITIONS (fx ops: id, param = value now [bounds]):");
+ for (const id of on) {
+ const ps = COMPOSITION_PARAMS[id].map((p) => {
+ const b = p.kind === "enum" ? p.values.join("|") : p.kind === "bool" ? "true|false" : p.kind === "text" ? `≤${p.maxLength} chars` : `${p.min}–${p.max}`;
+ return `${p.key} = ${JSON.stringify(paramValue(render, id, p.key))} [${b}]`;
+ });
+ out.push(`- ${id}: ${ps.join("; ")}`);
+ }
+ } else if (scope === "fx") out.push("COMPOSITIONS: none (this cut draws no deck and no effects)");
+ }
+ const clips = (m.timeline ?? []).filter((e) => isObj(e) && e.type === "clip");
+ const shown = [];
+ const short = [];
+ if (want("clips") && clips.length) {
+ const head = out.join("\n").length + 200;
+ let left = maxChars - head;
+ const named = (id) => new RegExp(`(^|[^A-Za-z0-9_-])${id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_-]|$)`, "i").test(request);
+ const order = [...clips].sort((a, b) => Number(named(b.id)) - Number(named(a.id)));
+ const lines = new Map();
+ const idLine = (e) => `- ${e.id} (not shown in full)`;
+ left -= clips.reduce((n, e) => n + idLine(e).length + 1, 0);
+ for (const e of order) {
+ const { cut, window } = clipWindow(e, render);
+ const r = clipRoom(e, render);
+ const label = e.onscreen?.title ?? e.title ?? e.assist?.why ?? "";
+ const line =
+ `- ${e.id}: cut ${s2(cut.start)}–${s2(cut.end)} s (${s2(cut.end - cut.start)} s; may move within ${s2(window.start)}–${s2(window.end)})` +
+ `${e.room === false ? ", room off" : isObj(e.room) ? `, room ${r ? ["tail", "head"].filter((k) => r[k]).join("+") || "none" : "none"}` : ""}` +
+ `${label ? ` ${JSON.stringify(shortWords(label, 8))}` : ""}${e.quote ? ` quote: ${JSON.stringify(shortWords(e.quote))}` : ""}`;
+ const extra = line.length - idLine(e).length;
+ if (extra <= left) {
+ left -= extra;
+ lines.set(e.id, line);
+ shown.push(e.id);
+ } else short.push(e.id);
+ }
+ out.push(`CLIPS (clip_edges / clip_room ops, by id; seconds on the recording):`);
+ for (const e of clips) out.push(lines.get(e.id) ?? idLine(e));
+ }
+ return { text: out.join("\n"), clips: { shown, short } };
+}
+
+/** The ops, as the model is told them: one shape, `{op, id, key, value}`. */
+export const ASSIST_OPS_TEXT = [
+ 'Operations: objects {"op", "id", "key", "value"} in the `ops` list ("id" is "" when the op names no clip or composition).',
+ "Change only what the request asks for, one op a setting; give the NEW value, never a step or a difference.",
+ '- {"op":"look","id":"","key":"transition","value":0.15} the join between clips, seconds (0 = hard cuts)',
+ '- {"op":"look","id":"","key":"transitionStyle","value":"fade"} one of fade, fadeblack, fadewhite, dissolve, blurslide',
+ '- {"op":"look","id":"","key":"qr","value":false} the QR code on (true) or off (false); key headerHeight / footerHeight: pixels, 0 = off',
+ '- {"op":"look","id":"","key":"loudness","value":-14} the loudness target in LUFS (higher = louder; null = as recorded)',
+ '- {"op":"look","id":"","key":"captions","value":true} speaker captions on or off',
+ '- {"op":"slide","id":"","key":"blur","value":0.3} the blur slide: key travel (how far it pushes), blur (the smear) or grain',
+ '- {"op":"room","id":"","key":"maxS","value":2} room at the clips\' edges: key tail (true/false: the sound runs to the first silence), head (true/false: a muted lead-in), maxS (the most seconds the tail runs past the cut), minGap',
+ '- {"op":"clip_edges","id":"<clip id>","key":"start","value":S} a clip\'s cut: key start or end, in seconds on its recording',
+ '- {"op":"clip_room","id":"<clip id>","key":"off","value":true} one clip\'s room: key tail or head (true/false), off (no room for it) or reset (the cut\'s again)',
+ '- {"op":"fx","id":"<composition>","key":"<param>","value":V} a listed composition param, within its bounds',
+].join("\n");
+
+/** The schema the answer is held to: `{ ops: [{op, id, key, value}], reply }` -- four keys an op, so a strict tool (every key required) is still one plain shape. */
+export const ASSIST_OPS_SCHEMA = Object.freeze({
+ type: "object",
+ properties: {
+ ops: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ op: { type: "string", enum: [...ASSIST_OP_NAMES] },
+ id: { type: "string" },
+ key: { type: "string" },
+ value: { type: ["number", "string", "boolean", "null"] },
+ },
+ required: ["op", "id", "key", "value"],
+ },
+ },
+ reply: { type: "string" },
+ },
+ required: ["ops", "reply"],
+});
+
+/**
+ * An op in the model's one shape (`{op, id, key, value}`) as the checker's
+ * own: `{op:"slide", key:"blur", value:0.3}` → `{op:"slide", blur:0.3}`. An op
+ * already in the checker's shape is left as it is.
+ */
+export function normalizeAssistOp(raw) {
+ if (!isObj(raw)) return raw;
+ const { op, id, key, value } = raw;
+ const k = typeof key === "string" ? key.trim() : "";
+ if (op === "look" || !k) return raw;
+ if (op === "fx") return raw.param !== undefined ? raw : { op, id, param: k, value };
+ if (["slide", "room", "clip_edges", "clip_room"].includes(op) && raw[k] === undefined) {
+ const out = { op, [k]: value };
+ if (op === "clip_edges" || op === "clip_room") out.id = id;
+ return out;
+ }
+ return raw;
+}
diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts
@@ -0,0 +1,196 @@
+// Release 38 lane E: the video assistant's ops — the look's shared rules,
+// each op's bounds and refusals, its diff line, and the request table.
+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";
+import { LOOK_KEYS, SLIDE_BOUNDS, applyLookPatch, lookErrors, validateLook, validateTransitionStyle } from "./look.mjs";
+import { ASSIST_OPS_SCHEMA, assistView, checkAssistOps, clipWindow, normalizeAssistOp, secondsNamedIn } from "./videoAssistOps.mjs";
+import { COMPOSITION_PARAMS, chromeWithParam, compositionsOn, paramValue, paramValueError } from "./fxParams.mjs";
+import { markProposals, proposalsDocOf, proposalsErrors, readAssistProposals, writeAssistProposals } from "./videoAssistProposals.mjs";
+import { ASSIST_REQUESTS, assistDeckManifest, assistManifest } from "../../testing/clips/assistProject.mjs";
+
+test("the look's rules: one patch function — keys refused, null removes, qr on/off, bounds, then the build's validators", () => {
+ const m = assistManifest();
+ assert.deepEqual(applyLookPatch(m, { chrome: {} }).errors, ["render.chrome is the deck's: set it from the deck's settings (updateChrome), not here"]);
+ assert.match(applyLookPatch(m, { fps: 25 }).errors[0]!, /render\.fps is not a look setting/);
+ assert.equal(applyLookPatch(m, { loudness: null }).render.loudness, undefined);
+ assert.equal(applyLookPatch(m, { qr: false }).render.qr, false);
+ assert.equal(applyLookPatch({ render: { qr: false } }, { qr: true }).render.qr, undefined);
+ assert.deepEqual(applyLookPatch(m, { transition: 0.157 }).render.transition, 0.16, "2 dp");
+ assert.match(applyLookPatch(m, { transition: 3.5 }).errors[0]!, /from 0 \(a hard cut\) to 3/);
+ assert.match(applyLookPatch(m, { headerHeight: 241 }).errors[0]!, /from 0 to 240/);
+ // What it does not check itself, the build's validators do — the same sentences.
+ const bad = applyLookPatch(m, { slide: { blur: 9 } });
+ assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } }));
+ assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } }));
+ assert.deepEqual(lookErrors(m), []);
+ assert.equal(LOOK_KEYS.length, 9);
+});
+
+test("the request table: every request → the model's ops → the diff lines kept and the reasons refused", () => {
+ assert.ok(ASSIST_REQUESTS.length >= 20);
+ for (const row of ASSIST_REQUESTS) {
+ const r = checkAssistOps(row.deck ? assistDeckManifest() : assistManifest(), row.answer, { request: row.request, scope: row.scope ?? "all" });
+ assert.deepEqual(r.diff, row.diff, row.request);
+ assert.equal(r.refused.length, row.refused.length, `${row.request}: ${JSON.stringify(r.refused)}`);
+ r.refused.forEach((x, i) => assert.match(x.why, row.refused[i]!, row.request));
+ }
+});
+
+test("each kept op carries its writer: the look's, the clip editor's, the composition's", () => {
+ const m = assistManifest();
+ const r = checkAssistOps(m, [
+ { op: "look", id: "", key: "transition", value: 0.15 },
+ { op: "slide", id: "", key: "blur", value: 0.3 },
+ { op: "room", id: "", key: "maxS", value: 2 },
+ { op: "clip_edges", id: "r002", key: "start", value: 90 },
+ { op: "clip_room", id: "r003", key: "off", value: true },
+ ]);
+ assert.deepEqual(
+ r.ops.map((o) => o.apply),
+ [
+ { writer: "render", patch: { transition: 0.15 } },
+ { writer: "render", patch: { slide: { blur: 0.3 } } },
+ { writer: "render", patch: { room: { tail: true, head: true, maxS: 2 } } },
+ { writer: "clip", body: { op: "trim", clip: "r002", cutStart: 90, cutEnd: 99 } },
+ { writer: "clip", body: { op: "room", clip: "r003", room: false } },
+ ],
+ );
+ assert.deepEqual(r.ops.map((o) => o.op), [
+ { op: "look", key: "transition", value: 0.15 },
+ { op: "slide", blur: 0.3 },
+ { op: "room", maxS: 2 },
+ { op: "clip_edges", id: "r002", start: 90, end: 99 },
+ { op: "clip_room", id: "r003", off: true },
+ ]);
+ // The manifest as the ops left it (the input is never touched).
+ assert.equal(r.manifest.render && (r.manifest.render as { transition: number }).transition, 0.15);
+ assert.equal(m.render.transition, 0.22);
+ const deck = checkAssistOps(assistDeckManifest(), [{ op: "fx", id: "fx.glitch", key: "seconds", value: 0.8 }], { scope: "fx" });
+ assert.deepEqual(deck.ops[0]!.apply, { writer: "chrome", id: "fx.glitch", param: "seconds", value: 0.8 });
+ assert.deepEqual(deck.diff, ["the glitch's length 0.5 s → 0.8 s"]);
+});
+
+test("ops read one after another: a later op sees the earlier ones; a second identical op is 'already that'", () => {
+ const r = checkAssistOps(assistManifest(), [
+ { op: "look", id: "", key: "transitionStyle", value: "fade" },
+ { op: "slide", id: "", key: "grain", value: 0 },
+ { op: "look", id: "", key: "transitionStyle", value: "fade" },
+ ]);
+ assert.deepEqual(r.diff, ["join style blur slide → crossfade", "grain 2 → 0"]);
+ assert.match(r.ops[1]!.warning!, /the join is a crossfade: the slide's knobs show once the join style is blur slide/);
+ assert.deepEqual(r.refused.map((x) => x.why), ["join style is already that"]);
+});
+
+test("room: a number for the tail is the tail on up to that; numbers alone turn the tail on; hard cuts warn", () => {
+ const plain = { render: { transition: 0.4 }, timeline: [] };
+ const a = checkAssistOps(plain, [{ op: "room", id: "", key: "tail", value: 2 }]);
+ assert.deepEqual(a.diff, ["room tail off → on, room tail up to 2.5 s → 2 s"]);
+ assert.deepEqual(a.ops[0]!.op, { op: "room", tail: true, maxS: 2 });
+ const b = checkAssistOps(plain, [{ op: "room", id: "", key: "minGap", value: 0.5 }]);
+ assert.deepEqual(b.diff, ["room tail off → on, room's silence gap 0.35 s → 0.5 s"]);
+ const c = checkAssistOps({ render: { transition: 0 }, timeline: [] }, [{ op: "room", id: "", key: "head", value: true }]);
+ assert.match(c.ops[0]!.warning!, /hard cuts/);
+ assert.match(checkAssistOps(plain, [{ op: "room", id: "", key: "maxS", value: 11 }]).refused[0]!.why, /outside 0–10 s/);
+ assert.match(checkAssistOps({ render: { montage: { phrase: "x" } }, timeline: [] }, [{ op: "room", id: "", key: "tail", value: true }]).refused[0]!.why, /a montage has no room/);
+});
+
+test("slide: each knob within SLIDE_BOUNDS, refused past them with the bound", () => {
+ for (const [k, [lo, hi]] of Object.entries(SLIDE_BOUNDS)) {
+ const m = assistManifest();
+ assert.equal(checkAssistOps(m, [{ op: "slide", id: "", key: k, value: hi }]).ops.length, 1, `${k} at ${hi}`);
+ assert.match(checkAssistOps(m, [{ op: "slide", id: "", key: k, value: hi + 1 }]).refused[0]!.why, new RegExp(`outside ${lo}–${hi}`));
+ }
+ assert.match(checkAssistOps(assistManifest(), [{ op: "slide", id: "", key: "speed", value: 1 }]).refused[0]!.why, /sets travel, blur \(the smear\) or grain/);
+});
+
+test("clip edges: inside the source window, at most 3 s a step unless the request names more, never under half a second", () => {
+ const m = assistManifest();
+ assert.deepEqual(clipWindow(m.timeline[0]!), { cut: { start: 40, end: 47 }, window: { start: 38.5, end: 48.5 }, hasCut: true });
+ // A clip without a cut moves inside its edges, widened by the fetch pad.
+ assert.deepEqual(clipWindow({ start: 10, end: 20 }, { fetchPad: 3 }).window, { start: 7, end: 23 });
+ assert.deepEqual(secondsNamedIn("cut the first 6 seconds, then 2.5 s more"), 6);
+ assert.equal(secondsNamedIn("start at 516"), 0);
+ assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "r001", key: "end", value: 40.2 }]).refused[0]!.why, /a cut is at least 0\.5 s/);
+ assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "zz", key: "end", value: 40 }]).refused[0]!.why, /no clip "zz" in the cut/);
+ assert.match(checkAssistOps(m, [{ op: "clip_edges", id: "", key: "end", value: 40 }]).refused[0]!.why, /names its clip/);
+ const card = { render: {}, timeline: [{ type: "card", id: "c1" }] };
+ assert.match(checkAssistOps(card, [{ op: "clip_room", id: "c1", key: "off", value: true }]).refused[0]!.why, /"c1" is a card entry, not a clip/);
+});
+
+test("fx: only a declared param of a composition the cut draws, within its declared bounds", () => {
+ const deck = assistDeckManifest();
+ assert.deepEqual(compositionsOn(deck.render), ["deck", "fx.glitch"]);
+ assert.deepEqual(compositionsOn(assistManifest().render), []);
+ assert.equal(paramValue(deck.render, "deck", "motion.in"), 0.45);
+ assert.equal(paramValueError(COMPOSITION_PARAMS.deck!.find((p) => p.key === "background")!, "neon"), "the deck's background is one of panel, flush");
+ assert.match(checkAssistOps(deck, [{ op: "fx", id: "fx.zoom", key: "width", value: 0.5 }]).refused[0]!.why, /does not draw fx\.zoom \(turn it on in the Media tab first\)/);
+ assert.match(checkAssistOps(deck, [{ op: "fx", id: "page", key: "html", value: "<b>" }]).refused[0]!.why, /"page" is not a composition/);
+ const set = chromeWithParam(deck.render, "deck", "motion.in", 0.6) as { deck: { motion: { in: number }; qr: unknown } };
+ assert.deepEqual(set.deck, { qr: { show: false }, motion: { in: 0.6 } });
+ assert.deepEqual((deck.render.chrome as { deck: unknown }).deck, { qr: { show: false } }, "a copy");
+ // Booleans and enums as a model may write them.
+ assert.deepEqual(checkAssistOps(deck, [{ op: "fx", id: "fx.glitch", key: "stamp", value: "off" }]).diff, ["the glitch's date stamp on → off"]);
+});
+
+test("scope: an op outside what was asked is refused; the view shows only the scope", () => {
+ const m = assistDeckManifest();
+ assert.match(checkAssistOps(m, [{ op: "look", id: "", key: "qr", value: false }], { scope: "clips" }).refused[0]!.why, /a look op is outside what was asked about \(clips\)/);
+ const look = assistView(m, { scope: "look" }).text;
+ assert.match(look, /THE LOOK NOW/);
+ assert.doesNotMatch(look, /CLIPS|COMPOSITIONS/);
+ const fx = assistView(m, { scope: "fx" }).text;
+ assert.match(fx, /- deck: motion\.in = 0\.45 \[0–2\]/);
+ assert.match(fx, /- fx\.glitch: on = "year" \[year\|every\]; seconds = 0\.5 \[0\.2–1\.5\]/);
+ assert.doesNotMatch(fx, /THE LOOK NOW/);
+});
+
+test("the view: the clips the request names first; past the budget a clip is its id alone", () => {
+ const m = assistManifest();
+ for (let i = 5; i <= 60; i++) m.timeline.push({ type: "clip", id: `r${String(i).padStart(3, "0")}`, channel: "c", video: "v", start: i * 100, end: i * 100 + 20, cutStart: i * 100 + 2, cutEnd: i * 100 + 18, quote: "a quote of a good many words that runs on and on for a while" });
+ const v = assistView(m, { maxChars: 3000, request: "trim r057 a bit", scope: "all" });
+ assert.ok(v.text.length <= 3200, String(v.text.length));
+ assert.ok(v.clips.shown.includes("r057"));
+ assert.ok(v.clips.short.length > 10);
+ assert.match(v.text, /- r060 \(not shown in full\)/);
+ assert.match(v.text, /- r057: cut 5702–5718 s \(16 s; may move within 5700–5720\)/);
+});
+
+test("the model's one shape normalised; the schema keeps four keys an op (a strict tool requires every key)", () => {
+ assert.deepEqual(normalizeAssistOp({ op: "slide", id: "", key: "blur", value: 0.3 }), { op: "slide", blur: 0.3 });
+ assert.deepEqual(normalizeAssistOp({ op: "clip_edges", id: "r1", key: "end", value: 9 }), { op: "clip_edges", end: 9, id: "r1" });
+ assert.deepEqual(normalizeAssistOp({ op: "fx", id: "deck", key: "motion.in", value: 1 }), { op: "fx", id: "deck", param: "motion.in", value: 1 });
+ assert.deepEqual(normalizeAssistOp({ op: "slide", blur: 0.3 }), { op: "slide", blur: 0.3 });
+ const item = (ASSIST_OPS_SCHEMA as { properties: { ops: { items: { properties: object; required: string[] } } } }).properties.ops.items;
+ assert.deepEqual(Object.keys(item.properties), ["op", "id", "key", "value"]);
+ assert.deepEqual(item.required, ["op", "id", "key", "value"]);
+});
+
+test("the proposals file: one ask's doc, read back, marked; a file that is not proposals is said so", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "assist-proposals-"));
+ try {
+ assert.deepEqual(await readAssistProposals(dir), { doc: null, error: null });
+ const checked = checkAssistOps(assistManifest(), [
+ { op: "look", id: "", key: "transition", value: 0.15 },
+ { op: "look", id: "", key: "transition", value: 9 },
+ ]);
+ const doc = proposalsDocOf({ at: "2026-10-20T00:00:00.000Z", model: "qwen3:8b", request: "quicker", checked, reply: " Shorter\njoins. " });
+ assert.deepEqual(doc.ops, [{ id: "a1", op: { op: "look", key: "transition", value: 0.15 }, diff: "join 0.22 s → 0.15 s", status: "proposed" }]);
+ assert.equal(doc.refused.length, 1);
+ assert.equal(doc.reply, "Shorter joins.");
+ await writeAssistProposals(dir, doc);
+ assert.deepEqual((await readAssistProposals(dir)).doc, doc);
+ const marked = markProposals(doc, { a1: { status: "applied" } }, "2026-10-20T00:01:00.000Z");
+ assert.deepEqual(marked.ops[0]!.status, "applied");
+ assert.equal(marked.ops[0]!.at, "2026-10-20T00:01:00.000Z");
+ await writeFile(path.join(dir, "assist-proposals.json"), '{"version": 2}');
+ assert.match((await readAssistProposals(dir)).error!, /assist-proposals\.json: version is not 1/);
+ assert.ok(proposalsErrors({ version: 1, request: "x", ops: [{ id: "a1" }], refused: [] }).some((e) => /ops\[0\]/.test(e)));
+ await assert.rejects(writeAssistProposals(dir, { version: 1 } as never), /not proposals/);
+ assert.match(await readFile(path.join(dir, "assist-proposals.json"), "utf8"), /"version": 2/, "a refused write leaves the file");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/report/videoAssistProposals.d.mts b/common/lib/report/videoAssistProposals.d.mts
@@ -0,0 +1,35 @@
+// Types for ./videoAssistProposals.mjs (release 38 lane E): `<project>/assist-proposals.json`.
+import type { AssistOp, CheckedAssistOp, RefusedAssistOp } from "./videoAssistOps.mjs";
+
+export type AssistOpStatus = "proposed" | "applied" | "dismissed" | "failed";
+export type ProposedOp = { id: string; op: AssistOp; diff: string; warning?: string; status: AssistOpStatus; at?: string; error?: string };
+export type AssistProposals = {
+ version: 1;
+ promptVersion: string;
+ at: string;
+ model: string;
+ request: string;
+ scope: string;
+ note?: string;
+ reply?: string;
+ ops: ProposedOp[];
+ refused: { op: unknown; why: string }[];
+ diff: string[];
+};
+
+export const ASSIST_PROPOSALS_NAME: string;
+export const ASSIST_PROMPT_VERSION: string;
+export const ASSIST_OP_STATUSES: readonly AssistOpStatus[];
+export function proposalsDocOf(o: {
+ at: string;
+ model: string;
+ request: string;
+ scope?: string;
+ note?: string | null;
+ reply?: string | null;
+ checked: { ops: CheckedAssistOp[]; refused: RefusedAssistOp[] };
+}): AssistProposals;
+export function proposalsErrors(doc: unknown): string[];
+export function readAssistProposals(dir: string): Promise<{ doc: AssistProposals | null; error: string | null }>;
+export function writeAssistProposals(dir: string, doc: AssistProposals): Promise<string>;
+export function markProposals(doc: AssistProposals, marks: Record<string, { status: AssistOpStatus; error?: string }>, at: string): AssistProposals;
diff --git a/common/lib/report/videoAssistProposals.mjs b/common/lib/report/videoAssistProposals.mjs
@@ -0,0 +1,111 @@
+// THE VIDEO ASSISTANT'S PROPOSALS FILE (release 38 lane E):
+// `<project>/assist-proposals.json`, beside the project's video.manifest.json.
+//
+// { "version": 1, "promptVersion": "video-assist-1", "at": ISO, "model": "qwen3:8b",
+// "request": "make the joins 0.15 s with less smear", "scope": "look", "note"?: "n_…",
+// "reply"?: "…", a sentence the model added (shown, never applied)
+// "ops": [ { "id": "a1", "op": {…}, "diff": "join 0.22 s → 0.15 s", "warning"?: "…",
+// "status": "proposed" | "applied" | "dismissed" | "failed", "at"?: ISO, "error"?: "…" } ],
+// "refused": [ { "op": {…}, "why": "…" } ],
+// "diff": [ "join 0.22 s → 0.15 s", … ] }
+//
+// Written whole by the editor's `video-assist` task (one ask's proposals: a
+// new ask replaces the file), and its ops' `status` marked by umtool's Apply
+// and Dismiss. PROPOSALS ONLY: nothing in this file is applied by being here;
+// Apply re-checks each op against the manifest as it is then (umtool
+// lib/report/videoAssist.mjs) and writes through the manifest's writers.
+//
+// Tmp + rename, so a reader never sees half a file. Plain ESM with a .d.mts.
+
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const ASSIST_PROPOSALS_NAME = "assist-proposals.json";
+export const ASSIST_PROMPT_VERSION = "video-assist-1";
+export const ASSIST_OP_STATUSES = Object.freeze(["proposed", "applied", "dismissed", "failed"]);
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const fileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_PROPOSALS_NAME);
+
+/**
+ * The file's document from one ask: the checked ops (videoAssistOps.mjs
+ * checkAssistOps), each given an id and the status "proposed".
+ */
+export function proposalsDocOf({ at, model, request, scope = "all", note = null, reply = null, checked }) {
+ const ops = (checked?.ops ?? []).map((k, i) => ({
+ id: `a${i + 1}`,
+ op: k.op,
+ diff: k.diff,
+ ...(k.warning ? { warning: k.warning } : {}),
+ status: "proposed",
+ }));
+ return {
+ version: 1,
+ promptVersion: ASSIST_PROMPT_VERSION,
+ at,
+ model,
+ request,
+ scope,
+ ...(note ? { note } : {}),
+ ...(reply ? { reply: String(reply).replace(/\s+/g, " ").trim().slice(0, 600) } : {}),
+ ops,
+ refused: (checked?.refused ?? []).map((r) => ({ op: r.op, why: r.why })),
+ diff: ops.map((o) => o.diff),
+ };
+}
+
+/** The file's problems (empty: it can be read as proposals). */
+export function proposalsErrors(doc) {
+ if (!isObj(doc)) return ["not an object"];
+ const errors = [];
+ if (doc.version !== 1) errors.push("version is not 1");
+ if (typeof doc.request !== "string") errors.push("no request");
+ if (!Array.isArray(doc.ops)) errors.push("no ops list");
+ else
+ doc.ops.forEach((o, i) => {
+ if (!isObj(o) || typeof o.id !== "string" || !isObj(o.op) || typeof o.diff !== "string" || !ASSIST_OP_STATUSES.includes(o.status)) errors.push(`ops[${i}] is not { id, op, diff, status }`);
+ });
+ if (!Array.isArray(doc.refused)) errors.push("no refused list");
+ return errors;
+}
+
+/** `{ doc, error }`: the proposals, or null (no file, or one that is not proposals: `error` says why). */
+export async function readAssistProposals(dir) {
+ let raw;
+ try {
+ raw = await readFile(fileOf(dir), "utf8");
+ } catch {
+ return { doc: null, error: null };
+ }
+ try {
+ const doc = JSON.parse(raw);
+ const errors = proposalsErrors(doc);
+ return errors.length ? { doc: null, error: `${ASSIST_PROPOSALS_NAME}: ${errors.join("; ")}` } : { doc, error: null };
+ } catch (e) {
+ return { doc: null, error: `${ASSIST_PROPOSALS_NAME}: ${e instanceof Error ? e.message : String(e)}` };
+ }
+}
+
+/** Write the whole file (tmp + rename). Returns its path. */
+export async function writeAssistProposals(dir, doc) {
+ const errors = proposalsErrors(doc);
+ if (errors.length) throw new Error(`not proposals: ${errors.join("; ")}`);
+ const file = fileOf(dir);
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8");
+ await rename(tmp, file);
+ return file;
+}
+
+/** The doc with each op of `marks` (`{ [id]: { status, error? } }`) marked at `at`; ids not there are ignored. */
+export function markProposals(doc, marks, at) {
+ return {
+ ...doc,
+ ops: doc.ops.map((o) => {
+ const m = marks[o.id];
+ if (!m) return o;
+ const { error: _e, ...rest } = o;
+ return { ...rest, status: m.status, at, ...(m.error ? { error: String(m.error).slice(0, 400) } : {}) };
+ }),
+ };
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -40,6 +40,7 @@ import {
SOCIAL_LINK_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
+ XENFORO_SOCIAL_SETTINGS_FIELD_DOCS,
SYNC_SCHEDULER_SETTINGS_FIELD_DOCS,
defaultSiteSettings,
siteSettingsSchema,
@@ -197,6 +198,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
// and only a chosen one is written.
defaults: fromObject(d.social.x),
},
+ { path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS },
],
socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }],
savedVideoBackup: [
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -74,6 +74,7 @@ import {
import { ATTRIBUTION_PROMPT_VERSION } from "./attribution";
import {
DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS,
+ looksLikeS3Key,
type ArchiveOrgFetchSettings,
} from "./archiveOrgTorrent";
import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
@@ -120,17 +121,29 @@ import { previewBranchProblem } from "./pagesDeploy";
import {
sanitizeSocial,
type SocialSettings,
+ type XenforoSocialSettings,
type XSocialSettings,
} from "../social/xCookieSource";
export type { Worker } from "./workers";
-export type { SocialSettings, XSocialSettings } from "../social/xCookieSource";
+export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource";
// The `social` block (release 16 slice XL). The types and the coercion live
// with the source they choose, in social/xCookieSource.ts (pure, client-safe);
// the documentation lives here with every other block's.
export const SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<SocialSettings> = {
x: "X / Twitter. See `social.x` below.",
+ xenforo: "Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set.",
+};
+
+export const XENFORO_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XenforoSocialSettings> = {
+ retryOnBlock:
+ "`{ \"minutes\": N, \"max\": M }` — what a forum thread's Fetch posts button does when the forum " +
+ "serves a browser check that will not clear, or refuses a page (403/429): the job waits N minutes " +
+ "and runs again, M tries in all (the first included; minutes 5–1440, tries 1–48). A captcha or a " +
+ "login wall is never retried — it needs a person. ABSENT (the default): off, the job stops at the " +
+ "block. Set on the forum channel page (Retry after a block); `fetch-posts` takes its own " +
+ "`retryOnBlock`. common/lib/forumWalk.ts.",
};
export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = {
@@ -539,6 +552,12 @@ export const ARCHIVE_ORG_SETTINGS_FIELD_DOCS: FieldDocs<ArchiveOrgFetchSettings>
maxUploadKiBps:
"Upload rate cap while downloading and seeding, KiB/s (aria2c " +
"--max-overall-upload-limit). 0 = unlimited.",
+ s3KeyFile:
+ "Release 37: the file holding archive.org's S3 keys for Save Page Now (\"Ask the Wayback Machine to capture this now\"): " +
+ "two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — " +
+ "refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: " +
+ "a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the " +
+ "editor's environment win over the file. No keys: Save Page Now is off, and says why.",
};
function clampNumber(value: unknown, fallback: number, min: number, max: number): number {
@@ -558,6 +577,10 @@ export function sanitizeArchiveOrg(value: unknown): ArchiveOrgFetchSettings {
maxPeers: Math.floor(clampNumber(r.maxPeers, d.maxPeers, 1, 500)),
maxDownloadKiBps: Math.floor(clampNumber(r.maxDownloadKiBps, d.maxDownloadKiBps, 0, 10_000_000)),
maxUploadKiBps: Math.floor(clampNumber(r.maxUploadKiBps, d.maxUploadKiBps, 0, 10_000_000)),
+ s3KeyFile:
+ typeof r.s3KeyFile === "string" && r.s3KeyFile.trim() && !looksLikeS3Key(r.s3KeyFile)
+ ? r.s3KeyFile.trim()
+ : d.s3KeyFile,
};
}
@@ -1763,7 +1786,7 @@ export const siteSettingsSchema = z.object({
"How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).",
),
social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe(
- "Per-platform settings of the social posts. Today two keys, both X's, both chosen in the X account session section of /settings: where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`). See common/social/xCookieSource.ts.",
+ "Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.",
),
sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe(
"Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.",
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -203,6 +203,16 @@ export class WaybackClient {
return this.http.requests;
}
+ // One request of any method to web.archive.org through this client's chain
+ // and gap (release 37 S5: Save Page Now's POST and status polls,
+ // lib/waybackPages/savePageNow.ts). ArchiveOrgClient.send's contract.
+ send(
+ url: string,
+ init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
+ ): Promise<{ status: number; text: string }> {
+ return this.http.send(url, init);
+ }
+
// Whether the Wayback Machine holds the YouTube VIDEO itself (formats in
// its videoinfo index — what yt-dlp asks), not only captures of its page.
async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<boolean> {
diff --git a/common/lib/waybackPages/liveness-server.ts b/common/lib/waybackPages/liveness-server.ts
@@ -0,0 +1,106 @@
+// ONE ORIGINAL URL'S STATE (release 37 S5): the request side of
+// ./liveness.ts. Through the process's web pacer (lib/web/pacer.ts: one
+// request at a time, 3 s apart, 429/503 backed off) — never the Wayback
+// Machine, never a burst — and behind the web fetch's fence (http(s) only,
+// no private or loopback host, every redirect hop checked the same way).
+//
+// HEAD, following redirects by hand (at most WEB_FETCH_MAX_REDIRECTS);
+// a GET instead when the HEAD is refused (405, 403, 501) or when the page's
+// platform has a "gone" page that answers 200 (its words decide), its body
+// read up to LIVENESS_MAX_BODY_BYTES.
+//
+// Answers an OriginalCheck; never throws for what the site answered (a
+// cancelled run's abort is rethrown).
+
+import { fetchRefusal, WEB_FETCH_MAX_REDIRECTS, type WebFetchOptions } from "../web/fetchPage";
+import { webPacer, WebRequestError, type WebPacer } from "../web/pacer";
+import { classifyOriginalAnswer, hasGoneMarkers, type OriginalCheck } from "./liveness";
+
+// A "gone" page's words are near its top: the body is read no further.
+export const LIVENESS_MAX_BODY_BYTES = 256 * 1024;
+
+// A HEAD these statuses refuse is asked again as a GET.
+const HEAD_REFUSED = new Set([403, 405, 501]);
+
+export type CheckOriginalOptions = Pick<WebFetchOptions, "allowPrivate" | "resolve"> & {
+ pacer?: WebPacer;
+ signal?: AbortSignal;
+};
+
+async function readCapped(res: Response, maxBytes: number): Promise<string> {
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let n = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ n += value.byteLength;
+ if (n >= maxBytes) {
+ await reader.cancel().catch(() => {});
+ break;
+ }
+ }
+ return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes));
+}
+
+type Hop = { redirect: string } | { status: number; body?: string };
+
+// One method's walk: redirects followed by hand, each hop fenced.
+async function walk(
+ url: string,
+ method: "HEAD" | "GET",
+ o: CheckOriginalOptions,
+): Promise<{ finalUrl: string; status: number; body?: string } | { refusal: string; status: number | null; finalUrl: string }> {
+ const pacer = o.pacer ?? webPacer;
+ let at = url;
+ for (let hop = 0; hop <= WEB_FETCH_MAX_REDIRECTS; hop++) {
+ const refusal = await fetchRefusal(at, o);
+ if (refusal) return { refusal, status: null, finalUrl: at };
+ const step: Hop = await pacer.request(
+ at,
+ {
+ method,
+ redirect: "manual",
+ headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" },
+ ...(o.signal ? { signal: o.signal } : {}),
+ },
+ async (res): Promise<Hop> => {
+ const loc = res.headers.get("location");
+ if (res.status >= 300 && res.status < 400 && loc) {
+ await res.body?.cancel().catch(() => {});
+ return { redirect: new URL(loc, at).toString() };
+ }
+ if (method === "HEAD") {
+ await res.body?.cancel().catch(() => {});
+ return { status: res.status };
+ }
+ return { status: res.status, body: await readCapped(res, LIVENESS_MAX_BODY_BYTES) };
+ },
+ );
+ if ("redirect" in step) {
+ at = step.redirect;
+ continue;
+ }
+ return { finalUrl: at, status: step.status, ...(step.body !== undefined ? { body: step.body } : {}) };
+ }
+ return { refusal: `more than ${WEB_FETCH_MAX_REDIRECTS} redirects`, status: null, finalUrl: at };
+}
+
+export async function checkOriginalUrl(url: string, o: CheckOriginalOptions = {}): Promise<OriginalCheck> {
+ try {
+ let answer = await walk(url, "HEAD", o);
+ const headRefused = !("refusal" in answer) && HEAD_REFUSED.has(answer.status);
+ const needsBody = !("refusal" in answer) && answer.status >= 200 && answer.status < 300 && hasGoneMarkers(answer.finalUrl);
+ if (headRefused || needsBody) answer = await walk(url, "GET", o);
+ if ("refusal" in answer) {
+ return { url, availability: "error", status: answer.status, ...(answer.finalUrl !== url ? { finalUrl: answer.finalUrl } : {}), reason: answer.refusal };
+ }
+ return classifyOriginalAnswer({ url, finalUrl: answer.finalUrl, status: answer.status, ...(answer.body !== undefined ? { body: answer.body } : {}) });
+ } catch (e) {
+ if (o.signal?.aborted) throw e;
+ const status = e instanceof WebRequestError ? e.status : null;
+ return { url, availability: "error", status, reason: (e as Error).message };
+ }
+}
diff --git a/common/lib/waybackPages/liveness.test.ts b/common/lib/waybackPages/liveness.test.ts
@@ -0,0 +1,173 @@
+// Release 37 S5: a page record's ORIGINAL — the marker table, the verdict on
+// one answer, the same-site rule, grouping by original URL, and the request
+// side (HEAD, then GET) through a web pacer over a stub fetch. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/liveness.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyOriginalAnswer,
+ foldPageText,
+ groupByOriginalUrl,
+ hasGoneMarkers,
+ PAGE_GONE_MARKERS,
+ pageGoneMarker,
+ sameSite,
+ siteOf,
+} from "./liveness";
+import { checkOriginalUrl } from "./liveness-server";
+import { WebPacer } from "../web/pacer";
+
+// Synthetic "gone" pages: each marker's words in the platform's own furniture.
+const page = (words: string) => `<!doctype html><html><head><title>t</title><script>var x="${words.slice(0, 3)}";</script></head><body><div class="x"><h1>${words}</h1><p>Try something else.</p></div></body></html>`;
+
+const MARKER_CASES: { id: string; url: string; html: string }[] = [
+ { id: "x-no-account", url: "https://x.com/someone", html: page("This account doesn’t exist") },
+ { id: "x-no-page", url: "https://twitter.com/someone/status/1", html: page("Hmm...this page doesn’t exist. Try searching for something else.") },
+ { id: "x-suspended", url: "https://mobile.twitter.com/someone", html: page("Account suspended") },
+ { id: "tumblr-nothing-here", url: "https://someone.tumblr.com/post/123", html: page("There's nothing here.") },
+ { id: "tumblr-nothing-here", url: "https://www.tumblr.com/someone", html: page("Whatever you were looking for doesn't currently exist at this address. Unless you were looking for this error page, in which case: Congrats!") },
+ { id: "gdocs-no-file", url: "https://docs.google.com/document/d/abc/edit", html: page("Sorry, the file you have requested does not exist.") },
+ { id: "gdocs-permission", url: "https://drive.google.com/file/d/abc/view", html: page("You need access") },
+ { id: "youtube-no-channel", url: "https://www.youtube.com/@someone/about", html: page("This channel does not exist.") },
+ { id: "youtube-terminated", url: "https://m.youtube.com/channel/UCabc", html: page("This account has been terminated for a violation of YouTube's Terms of Service.") },
+];
+
+test("the marker table: every platform's gone page is told by its words, on its own hosts only", () => {
+ for (const c of MARKER_CASES) {
+ assert.equal(pageGoneMarker(c.url, c.html)?.id, c.id, c.url);
+ }
+ // Every marker has a case.
+ assert.deepEqual(new Set(MARKER_CASES.map((c) => c.id)), new Set(PAGE_GONE_MARKERS.map((m) => m.id)));
+ // The same words elsewhere are not a gone page (a blog quoting X's message).
+ assert.equal(pageGoneMarker("https://blog.example/post", page("This account doesn't exist")), null);
+ assert.equal(pageGoneMarker("https://example.tumblr.net/", page("There's nothing here.")), null);
+ // A live page on the platform is not one either.
+ assert.equal(pageGoneMarker("https://someone.tumblr.com/post/1", page("A post about bread")), null);
+ // Words inside a script are not the page's.
+ assert.equal(pageGoneMarker("https://x.com/a", `<html><script>var m = "Account suspended";</script><p>hello</p></html>`), null);
+ assert.equal(hasGoneMarkers("https://www.youtube.com/@a/about"), true);
+ assert.equal(hasGoneMarkers("https://blog.example/"), false);
+ assert.equal(foldPageText("<p>Doesn’t <b>EXIST</b></p>"), "doesn't exist");
+});
+
+test("one answer's verdict: 404/410 deleted, 2xx available on the same site, a marker, anything else an error with its status", () => {
+ const v = (url: string, finalUrl: string, status: number, body?: string) =>
+ classifyOriginalAnswer({ url, finalUrl, status, ...(body !== undefined ? { body } : {}) });
+ assert.deepEqual(
+ [v("https://a.example/x", "https://a.example/x", 404).availability, v("https://a.example/x", "https://a.example/x", 410).availability],
+ ["deleted", "deleted"],
+ );
+ const ok = v("http://a.example/x", "https://www.a.example/x/", 200);
+ assert.equal(ok.availability, "available");
+ assert.equal(ok.finalUrl, "https://www.a.example/x/");
+ const off = v("https://a.example/x", "https://parked.example/", 200);
+ assert.equal(off.availability, "error");
+ assert.match(off.reason, /redirects to another site \(parked\.example\)/);
+ const gone = v("https://someone.tumblr.com/post/1", "https://www.tumblr.com/someone", 200, page("There's nothing here."));
+ assert.deepEqual([gone.availability, gone.reason], ["deleted", "Tumblr says there's nothing here"]);
+ const walled = v("https://x.com/a", "https://x.com/a", 403);
+ assert.deepEqual([walled.availability, walled.status, walled.reason], ["error", 403, "HTTP 403"]);
+ assert.equal(v("https://a.example/", "https://a.example/", 500).availability, "error");
+ // A gone page behind another status still says so.
+ assert.equal(v("https://docs.google.com/d/1", "https://docs.google.com/d/1", 401, page("You need permission")).availability, "account_unavailable");
+});
+
+test("same site: www, http→https, a subdomain of the same domain, two-label suffixes, moved houses", () => {
+ assert.equal(sameSite("http://blog.example/", "https://www.blog.example/a"), true);
+ assert.equal(sameSite("https://someone.tumblr.com/", "https://www.tumblr.com/someone"), true);
+ assert.equal(sameSite("https://twitter.com/a", "https://x.com/a"), true);
+ assert.equal(sameSite("https://a.example.co.uk/", "https://b.example.co.uk/"), true);
+ assert.equal(sameSite("https://a.co.uk/", "https://b.co.uk/"), false);
+ assert.equal(sameSite("https://blog.example/", "https://other.example/"), false);
+ assert.equal(siteOf("www.news.bbc.co.uk"), "bbc.co.uk");
+});
+
+test("records grouped by original URL: one request per URL, whatever a capture split into", () => {
+ const rec = (id: string, originalUrl?: string) => ({ id, ...(originalUrl ? { page: { originalUrl } } : {}) });
+ const g = groupByOriginalUrl([rec("t1", "https://x.com/a"), rec("p1", "https://blog.example/"), rec("t2", "https://x.com/a"), rec("none")]);
+ assert.deepEqual([...g.entries()], [
+ ["https://x.com/a", ["t1", "t2"]],
+ ["https://blog.example/", ["p1"]],
+ ]);
+});
+
+// ─── The request side, over a stub fetch ───
+
+type Route = (method: string, url: string) => { status: number; headers?: Record<string, string>; body?: string };
+
+function stubPacer(route: Route) {
+ const sent: string[] = [];
+ const pacer = new WebPacer(
+ {
+ fetch: async (url, init) => {
+ const method = (init.method ?? "GET").toUpperCase();
+ sent.push(`${method} ${url}`);
+ const r = route(method, url);
+ return new Response(method === "HEAD" ? null : (r.body ?? ""), { status: r.status, headers: r.headers ?? {} });
+ },
+ sleep: async () => {},
+ },
+ { minGapMs: 0, maxAttempts: 2 },
+ );
+ // Every public name resolves to a public address; nothing is looked up.
+ return { pacer, sent, opts: { pacer, resolve: async () => ["93.184.216.34"] } };
+}
+
+test("checkOriginalUrl: a HEAD is enough for a plain page; a refused HEAD is asked again as a GET", async () => {
+ const live = stubPacer(() => ({ status: 200 }));
+ assert.equal((await checkOriginalUrl("https://blog.example/a", live.opts)).availability, "available");
+ assert.deepEqual(live.sent, ["HEAD https://blog.example/a"]);
+
+ const refused = stubPacer((m) => (m === "HEAD" ? { status: 405 } : { status: 200, body: "<p>hi</p>" }));
+ const r = await checkOriginalUrl("https://blog.example/a", refused.opts);
+ assert.equal(r.availability, "available");
+ assert.deepEqual(refused.sent, ["HEAD https://blog.example/a", "GET https://blog.example/a"]);
+
+ const gone = stubPacer(() => ({ status: 410 }));
+ assert.deepEqual(
+ [(await checkOriginalUrl("https://blog.example/a", gone.opts)).availability, gone.sent.length],
+ ["deleted", 1],
+ );
+});
+
+test("checkOriginalUrl: redirects followed by hand; a platform with a gone page is read with a GET", async () => {
+ const s = stubPacer((m, url) => {
+ if (url === "https://someone.tumblr.com/post/1") return { status: 301, headers: { location: "https://www.tumblr.com/someone/1" } };
+ return m === "HEAD" ? { status: 200 } : { status: 200, body: page("There’s nothing here.") };
+ });
+ const r = await checkOriginalUrl("https://someone.tumblr.com/post/1", s.opts);
+ assert.deepEqual([r.availability, r.finalUrl, r.reason], ["deleted", "https://www.tumblr.com/someone/1", "Tumblr says there's nothing here"]);
+ assert.deepEqual(s.sent, [
+ "HEAD https://someone.tumblr.com/post/1",
+ "HEAD https://www.tumblr.com/someone/1",
+ "GET https://someone.tumblr.com/post/1",
+ "GET https://www.tumblr.com/someone/1",
+ ]);
+ const off = stubPacer((_m, url) => (url.includes("blog.example") ? { status: 302, headers: { location: "https://parked.example/" } } : { status: 200 }));
+ const o = await checkOriginalUrl("https://blog.example/", off.opts);
+ assert.equal(o.availability, "error");
+ assert.match(o.reason, /another site/);
+});
+
+test("checkOriginalUrl: an error never reads as deleted — a 403 wall, a 503 that stays, a private address, no answer", async () => {
+ const wall = stubPacer(() => ({ status: 403 }));
+ const w = await checkOriginalUrl("https://blog.example/", wall.opts);
+ assert.deepEqual([w.availability, w.status], ["error", 403]);
+ assert.equal(wall.sent.length, 2, "HEAD, then GET");
+
+ const down = stubPacer(() => ({ status: 503 }));
+ const d = await checkOriginalUrl("https://blog.example/", down.opts);
+ assert.deepEqual([d.availability, d.status], ["error", 503]);
+
+ const inside = stubPacer(() => ({ status: 200 }));
+ const p = await checkOriginalUrl("http://127.0.0.1:9/", inside.opts);
+ assert.equal(p.availability, "error");
+ assert.match(p.reason, /private address/);
+ assert.equal(inside.sent.length, 0);
+
+ const dead = new WebPacer({ fetch: async () => { throw new Error("getaddrinfo ENOTFOUND"); }, sleep: async () => {} }, { minGapMs: 0 });
+ const n = await checkOriginalUrl("https://blog.example/", { pacer: dead, resolve: async () => ["93.184.216.34"] });
+ assert.deepEqual([n.availability, n.status], ["error", null]);
+});
diff --git a/common/lib/waybackPages/liveness.ts b/common/lib/waybackPages/liveness.ts
@@ -0,0 +1,227 @@
+// IS THE ORIGINAL STILL UP? (release 37 S5, plans/release-37/wayback-pages.md
+// "S5") — the pure half of a page record's availability: what one answer from
+// the ORIGINAL URL (never the Wayback Machine) says about it.
+//
+// available a 2xx, after any redirects that stayed on the same
+// site, whose body carries no platform's "gone" page
+// deleted 404 or 410, or a platform's "this does not exist"
+// page (PAGE_GONE_MARKERS) — the Wayback copy is then
+// the only copy
+// account_unavailable a platform's "this account is suspended / this
+// document is not shared" page: the page is not served,
+// and that may reverse
+// error anything else (a 403, a 5xx, a redirect to another
+// site, no answer), with the status — never a deletion
+// reported from ignorance
+//
+// Pure and client-safe: the request side is ./liveness-server.ts.
+
+import type { PostAvailability } from "../posts";
+
+// One platform's "gone" page: the hosts it applies to and the words it shows.
+export type PageGoneMarker = {
+ // A short name for logs and tests.
+ id: string;
+ // The page's host (no "www."), tested against each pattern.
+ hosts: readonly RegExp[];
+ // Matched against the page's text (tags dropped, entities and curly quotes
+ // folded, whitespace collapsed, lower case).
+ text: RegExp;
+ availability: Extract<PostAvailability, "deleted" | "account_unavailable">;
+ // What the log and the sidecar say.
+ reason: string;
+};
+
+const X_HOSTS = [/^(?:mobile\.)?(?:x|twitter)\.com$/];
+const TUMBLR_HOSTS = [/(?:^|\.)tumblr\.com$/];
+const GOOGLE_DOCS_HOSTS = [/^(?:docs|drive)\.google\.com$/];
+const YOUTUBE_HOSTS = [/^(?:m\.)?youtube\.com$/];
+
+// THE TABLE (unit-tested in liveness.test.ts). A platform that serves its
+// "nothing here" page with a 200 is only told apart by its words; one that
+// answers 404 needs no entry (the status says it).
+export const PAGE_GONE_MARKERS: readonly PageGoneMarker[] = [
+ {
+ id: "x-no-account",
+ hosts: X_HOSTS,
+ text: /this account doesn't exist/,
+ availability: "deleted",
+ reason: "X says the account doesn't exist",
+ },
+ {
+ id: "x-no-page",
+ hosts: X_HOSTS,
+ text: /(?:hmm\.\.\.\s*)?this page doesn't exist|sorry, that page doesn't exist/,
+ availability: "deleted",
+ reason: "X says the page doesn't exist",
+ },
+ {
+ id: "x-suspended",
+ hosts: X_HOSTS,
+ text: /account suspended/,
+ availability: "account_unavailable",
+ reason: "X says the account is suspended",
+ },
+ {
+ id: "tumblr-nothing-here",
+ hosts: TUMBLR_HOSTS,
+ text: /there's nothing here\.?|whatever you were looking for doesn't currently exist at this address/,
+ availability: "deleted",
+ reason: "Tumblr says there's nothing here",
+ },
+ {
+ id: "gdocs-no-file",
+ hosts: GOOGLE_DOCS_HOSTS,
+ text: /sorry, the file you have requested does not exist/,
+ availability: "deleted",
+ reason: "Google Docs says the file does not exist",
+ },
+ {
+ id: "gdocs-permission",
+ hosts: GOOGLE_DOCS_HOSTS,
+ text: /you need (?:access|permission)/,
+ availability: "account_unavailable",
+ reason: "Google Docs says the file is not shared",
+ },
+ {
+ id: "youtube-no-channel",
+ hosts: YOUTUBE_HOSTS,
+ text: /this channel does not exist/,
+ availability: "deleted",
+ reason: "YouTube says the channel does not exist",
+ },
+ {
+ id: "youtube-terminated",
+ hosts: YOUTUBE_HOSTS,
+ text: /this account has been terminated/,
+ availability: "account_unavailable",
+ reason: "YouTube says the account has been terminated",
+ },
+];
+
+// The host without "www.", lower case; "" for no URL.
+export function bareHost(url: string): string {
+ try {
+ return new URL(url).hostname.toLowerCase().replace(/^www\./, "");
+ } catch {
+ return "";
+ }
+}
+
+// Whether a platform has a "gone" page worth reading the body for.
+export function hasGoneMarkers(url: string): boolean {
+ const host = bareHost(url);
+ return !!host && PAGE_GONE_MARKERS.some((m) => m.hosts.some((h) => h.test(host)));
+}
+
+// The page's words, folded for matching: tags and scripts dropped, a few
+// entities and curly quotes folded, whitespace collapsed, lower case.
+export function foldPageText(html: string): string {
+ return html
+ .replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<[^>]+>/g, " ")
+ .replace(/�*39;|�*27;|'|’|‘|’|’/gi, "'")
+ .replace(/ | /gi, " ")
+ .replace(/&/gi, "&")
+ .replace(/[‘’ʼ]/g, "'")
+ .replace(/\s+/g, " ")
+ .trim()
+ .toLowerCase();
+}
+
+// The platform's "gone" page this body is, or null.
+export function pageGoneMarker(url: string, html: string): PageGoneMarker | null {
+ const host = bareHost(url);
+ if (!host || !html) return null;
+ const text = foldPageText(html);
+ for (const m of PAGE_GONE_MARKERS) {
+ if (!m.hosts.some((h) => h.test(host))) continue;
+ if (m.text.test(text)) return m;
+ }
+ return null;
+}
+
+// Two-label public suffixes the "same site" test must not stop at.
+const SECOND_LEVEL = /^(?:co|com|net|org|gov|ac|edu|ne|or)\.[a-z]{2}$/;
+
+// A host's registrable part, roughly: its last two labels, or three under a
+// two-label suffix (co.uk, com.au).
+// Sites that moved house: a redirect between them stays on the site.
+const SITE_ALIASES: Readonly<Record<string, string>> = { "twitter.com": "x.com", "youtu.be": "youtube.com" };
+
+export function siteOf(host: string): string {
+ const labels = host.toLowerCase().replace(/^www\./, "").split(".").filter(Boolean);
+ const last2 = labels.slice(-2).join(".");
+ const site = labels.length > 2 && SECOND_LEVEL.test(last2) ? labels.slice(-3).join(".") : last2;
+ return SITE_ALIASES[site] ?? site;
+}
+
+// Whether a redirect from `a` to `b` stayed on the same site (http→https,
+// www, a subdomain of the same registrable domain: tumblr's blog → www).
+export function sameSite(a: string, b: string): boolean {
+ const ha = bareHost(a);
+ const hb = bareHost(b);
+ if (!ha || !hb) return false;
+ return ha === hb || siteOf(ha) === siteOf(hb);
+}
+
+// One check's verdict on an original URL.
+export type OriginalCheck = {
+ url: string;
+ availability: PostAvailability;
+ // The final answer's HTTP status (null: no answer).
+ status: number | null;
+ // Where the redirects (if any) ended.
+ finalUrl?: string;
+ // Why, in a phrase (the marker's reason, the status, the redirect, the
+ // network error).
+ reason: string;
+};
+
+// THE VERDICT on one final answer. `body` is the page's text when it was
+// read (a GET), else undefined (a HEAD).
+export function classifyOriginalAnswer(a: {
+ url: string;
+ finalUrl: string;
+ status: number;
+ body?: string;
+}): OriginalCheck {
+ const base = { url: a.url, status: a.status, ...(a.finalUrl !== a.url ? { finalUrl: a.finalUrl } : {}) };
+ if (a.status === 404 || a.status === 410) {
+ return { ...base, availability: "deleted", reason: `HTTP ${a.status}` };
+ }
+ if (a.status >= 200 && a.status < 300) {
+ if (!sameSite(a.url, a.finalUrl)) {
+ return { ...base, availability: "error", reason: `redirects to another site (${bareHost(a.finalUrl) || a.finalUrl})` };
+ }
+ const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null;
+ if (marker) return { ...base, availability: marker.availability, reason: marker.reason };
+ return { ...base, availability: "available", reason: `HTTP ${a.status}` };
+ }
+ // A platform's gone page can come with another status (a 403 wall).
+ const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null;
+ if (marker) return { ...base, availability: marker.availability, reason: `${marker.reason} (HTTP ${a.status})` };
+ return { ...base, availability: "error", reason: `HTTP ${a.status}` };
+}
+
+// A webpage record's ids grouped by the original URL they were captured
+// from: one request per distinct URL, whatever number of records a capture
+// split into. Order: the order of `records` (first appearance).
+export function groupByOriginalUrl(
+ records: ReadonlyArray<{ id: string; page?: { originalUrl: string } }>,
+): Map<string, string[]> {
+ const out = new Map<string, string[]>();
+ for (const r of records) {
+ const url = r.page?.originalUrl;
+ if (!url) continue;
+ const list = out.get(url);
+ if (list) list.push(r.id);
+ else out.set(url, [r.id]);
+ }
+ return out;
+}
+
+// What a reader is told about a page record whose original is gone (the
+// source-gone label's page sentence, lib/sourceGone.ts SOURCE_GONE_LABELS
+// for everything else).
+export const PAGE_ORIGINAL_GONE_LABEL = "Original gone — the Wayback Machine copy is the only copy";
diff --git a/common/lib/waybackPages/savePageNow-server.ts b/common/lib/waybackPages/savePageNow-server.ts
@@ -0,0 +1,63 @@
+// archive.org's S3 KEYS for Save Page Now (release 37 S5), kept the way the
+// Claude API key is (lib/llm/anthropic.ts readApiKey): the environment first
+// (ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, both), else a mode-600
+// file whose PATH is the setting `archiveOrg.s3KeyFile` (two lines
+// `ARCHIVE_ORG_S3_ACCESS=…`, `ARCHIVE_ORG_S3_SECRET=…`). A file the group or
+// others can read is refused. The keys are never a setting, never logged,
+// never in an error, a job record or a result.
+
+import { readFileSync, statSync } from "node:fs";
+import os from "node:os";
+import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../archiveOrgTorrent";
+import { spnOffSentence, type SpnKeys } from "./savePageNow";
+
+export type SpnKeysRead = { ok: true; keys: SpnKeys; from: "env" | "file" } | { ok: false; reason: string };
+
+const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p);
+
+const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim();
+
+export function readSpnKeys(o: {
+ keyFile?: string;
+ env?: Readonly<Record<string, string | undefined>>;
+}): SpnKeysRead {
+ const env = o.env ?? process.env;
+ const keyFile = o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE;
+ const envAccess = (env.ARCHIVE_ORG_S3_ACCESS ?? "").trim();
+ const envSecret = (env.ARCHIVE_ORG_S3_SECRET ?? "").trim();
+ if (envAccess && envSecret) return { ok: true, keys: { access: envAccess, secret: envSecret }, from: "env" };
+ const file = expandHome(keyFile);
+ let mode: number;
+ try {
+ mode = statSync(file).mode;
+ } catch {
+ return { ok: false, reason: spnOffSentence(keyFile) };
+ }
+ if (mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; Save Page Now is off until then.` };
+ let text: string;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch {
+ return { ok: false, reason: `${keyFile} could not be read; Save Page Now is off.` };
+ }
+ let access = "";
+ let secret = "";
+ for (const raw of text.split("\n")) {
+ const line = raw.trim().replace(/^export\s+/, "");
+ if (line.startsWith("ARCHIVE_ORG_S3_ACCESS=")) access = unquote(line.slice("ARCHIVE_ORG_S3_ACCESS=".length));
+ if (line.startsWith("ARCHIVE_ORG_S3_SECRET=")) secret = unquote(line.slice("ARCHIVE_ORG_S3_SECRET=".length));
+ }
+ if (!access || !secret) {
+ return { ok: false, reason: `${keyFile} has no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines; Save Page Now is off.` };
+ }
+ return { ok: true, keys: { access, secret }, from: "file" };
+}
+
+// Replace the keys wherever they appear in a text: the last line of defence
+// for a message that leaves the module.
+export function redactSpnKeys(text: string, keys: SpnKeys | undefined): string {
+ if (!keys) return text;
+ let out = text;
+ for (const k of [keys.secret, keys.access]) if (k && k.length >= 4) out = out.split(k).join("[redacted]");
+ return out;
+}
diff --git a/common/lib/waybackPages/savePageNow.ts b/common/lib/waybackPages/savePageNow.ts
@@ -0,0 +1,106 @@
+// SAVE PAGE NOW (release 37 S5) — asking the Wayback Machine to capture a
+// live page now, through its SPN2 API (archive.org's documented
+// "Save Page Now 2 Public API"):
+//
+// POST https://web.archive.org/save
+// Authorization: LOW <access>:<secret> (archive.org's S3 keys)
+// Accept: application/json
+// url=<page>&capture_outlinks=0 (the page alone)
+// → {url, job_id} or {status: "error", status_ext, message}
+// GET https://web.archive.org/save/status/<job_id>
+// → {status: "pending"} ask again later
+// → {status: "success", timestamp, original_url}
+// → {status: "error", status_ext, message}
+//
+// Pure: what the answers mean. The keys, the requests and the job are
+// ./savePageNow-server.ts and controller/savePageNow.ts.
+
+// The archive's origin, spelled here (lib/waybackClient.ts's WAYBACK_ORIGIN
+// carries node:fs with it); the process client sends it to a test's fake.
+const ORIGIN = "https://web.archive.org";
+
+export const SPN_SAVE_URL = `${ORIGIN}/save`;
+
+export function spnStatusUrl(jobId: string): string {
+ return `${ORIGIN}/save/status/${encodeURIComponent(jobId)}`;
+}
+
+// The form a capture request sends: the page alone, no outlinks.
+export function spnSaveBody(url: string): string {
+ return new URLSearchParams({ url, capture_outlinks: "0" }).toString();
+}
+
+export type SpnKeys = { access: string; secret: string };
+
+// The Authorization header's value. Never logged.
+export function spnAuthorization(keys: SpnKeys): string {
+ return `LOW ${keys.access}:${keys.secret}`;
+}
+
+export type SpnSubmit = { ok: true; jobId: string } | { ok: false; error: string; code?: string };
+
+const json = (text: string): Record<string, unknown> | null => {
+ try {
+ const v = JSON.parse(text) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+};
+
+const str = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
+
+// What archive.org answered a capture request. A 401/403 is the keys; an
+// error body names its `status_ext` (error:too-many-daily-captures, …).
+export function parseSpnSubmit(status: number, text: string): SpnSubmit {
+ const body = json(text);
+ if (status === 401 || status === 403) {
+ return { ok: false, code: "auth", error: `archive.org refused the S3 keys (HTTP ${status}); check them at archive.org/account/s3.php` };
+ }
+ const jobId = str(body?.job_id);
+ if (status >= 200 && status < 300 && jobId) return { ok: true, jobId };
+ const ext = str(body?.status_ext);
+ const message = str(body?.message);
+ return {
+ ok: false,
+ ...(ext ? { code: ext } : {}),
+ error: `Save Page Now refused the capture (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`,
+ };
+}
+
+export type SpnStatus =
+ | { state: "pending" }
+ | { state: "success"; timestamp: string; originalUrl: string }
+ | { state: "error"; error: string; code?: string };
+
+// What a status poll answered.
+export function parseSpnStatus(status: number, text: string): SpnStatus {
+ const body = json(text);
+ if (status === 401 || status === 403) {
+ return { state: "error", code: "auth", error: `archive.org refused the S3 keys (HTTP ${status})` };
+ }
+ const state = str(body?.status);
+ if (status >= 200 && status < 300 && state === "pending") return { state: "pending" };
+ if (status >= 200 && status < 300 && state === "success") {
+ const timestamp = str(body?.timestamp);
+ const originalUrl = str(body?.original_url);
+ if (/^\d{14}$/.test(timestamp) && /^https?:\/\//i.test(originalUrl)) return { state: "success", timestamp, originalUrl };
+ return { state: "error", error: "Save Page Now said success but named no capture (timestamp, original_url)" };
+ }
+ const ext = str(body?.status_ext);
+ const message = str(body?.message);
+ return {
+ state: "error",
+ ...(ext ? { code: ext } : {}),
+ error: `the capture failed (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`,
+ };
+}
+
+// Why Save Page Now is off, in the sentence the button shows, when no keys
+// are configured.
+export function spnOffSentence(keyFile: string): string {
+ return (
+ `Save Page Now needs archive.org S3 keys: ARCHIVE_ORG_S3_ACCESS and ARCHIVE_ORG_S3_SECRET in the editor's ` +
+ `environment, or in ${keyFile} (mode 600; settings archiveOrg.s3KeyFile).`
+ );
+}
diff --git a/common/package.json b/common/package.json
@@ -48,6 +48,10 @@
"./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
+ "./lib/report/look.mjs": "./lib/report/look.mjs",
+ "./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs",
+ "./lib/report/videoAssistOps.mjs": "./lib/report/videoAssistOps.mjs",
+ "./lib/report/videoAssistProposals.mjs": "./lib/report/videoAssistProposals.mjs",
"./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs",
"./lib/report/panels.mjs": "./lib/report/panels.mjs",
"./lib/report/social.mjs": "./lib/report/social.mjs",
diff --git a/common/publish/findCopyPages.test.ts b/common/publish/findCopyPages.test.ts
@@ -0,0 +1,229 @@
+// Release 37 S5: find-copy's page mode on the fake Wayback — a cited page
+// whose original is gone gets the capture nearest its date imported into the
+// channel whose targets cover it, and the answer names the record to cite (and
+// the citation as a post citation of it); a dry run imports nothing; a live
+// page, an uncovered one and one the archive never captured are left with
+// their reason; a page already held is not fetched again; a cited page record
+// whose original is gone is "held" when its capture is stored, imported again
+// when it is not. The original sites are a stub; no network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyPages.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ startFakeWayback,
+ PAGE_ARTICLE_LATER_TS,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ PAGE_TOOLBAR_TS,
+ PAGE_TOOLBAR_URL,
+} from "../testing/web/fakeWayback.mjs";
+import type { Paths } from "../lib/paths";
+import type { Citation } from "../lib/citations/schema";
+import type { ReportHost } from "./reportHost";
+import type { OriginalCheck } from "../lib/waybackPages/liveness";
+import { WaybackClient } from "../lib/waybackClient";
+import { readAllPosts, upsertPosts, writePostAvailability } from "../lib/posts-server";
+import { pageRecordId } from "../lib/waybackPages/types";
+import { importPage } from "../controller/importPage";
+import { captureAtOf, channelsCovering, findPageCopies, pageCitationAsPost, recordForQuote, targetCoversUrl } from "./findCopyPages";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "find-page-copy-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths;
+const SETTINGS = { social: { x: { visibility: "private" } } };
+const HOST = { id: "demo-site" } as unknown as ReportHost;
+const NOW = new Date("2026-10-20T12:00:00Z");
+
+async function pagesChannel(slug: string, target: string, match = "prefix") {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ name: slug,
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: target.split("/")[0],
+ url: `https://web.archive.org/web/*/${target}*`,
+ wayback: { targets: [{ url: target, match }] },
+ }),
+ );
+ return dir;
+}
+
+const verdict = (url: string, availability: OriginalCheck["availability"], status: number | null): OriginalCheck => ({
+ url,
+ availability,
+ status,
+ reason: status ? `HTTP ${status}` : "no answer",
+});
+
+test("which channel covers a page; the date a citation asks for; the record a quote is from; a page citation as a post", () => {
+ assert.equal(targetCoversUrl({ url: "blog.example/2014/", match: "prefix" }, "https://www.blog.example/2014/03/a.html"), true);
+ assert.equal(targetCoversUrl({ url: "blog.example/2015/", match: "prefix" }, "https://blog.example/2014/03/a.html"), false);
+ assert.equal(targetCoversUrl({ url: "https://blog.example/a", match: "exact" }, "http://blog.example/a/"), true);
+ assert.equal(targetCoversUrl({ url: "blog.example", match: "host" }, "https://sub.blog.example/"), false);
+ assert.equal(targetCoversUrl({ url: "blog.example", match: "domain" }, "https://sub.blog.example/"), true);
+ assert.deepEqual(
+ channelsCovering(
+ [
+ { slug: "vids", config: { url: "x" } as never },
+ { slug: "blog", config: { sourceKind: "social", platform: "webpage", wayback: { targets: [{ url: "blog.example", match: "host" }] } } },
+ ],
+ "https://blog.example/a",
+ ),
+ ["blog"],
+ );
+ assert.equal(captureAtOf({ date: "2015-06-01" }, NOW), "20150601");
+ assert.equal(captureAtOf({ date: "2015" }, NOW), "2015");
+ assert.equal(captureAtOf({ archiveUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` }, NOW), PAGE_ARTICLE_TS);
+ assert.equal(captureAtOf({}, NOW), "20261020");
+ assert.equal(recordForQuote([{ id: "a", text: "one thing" }, { id: "b", text: "Another “thing” said" }], 'another "thing"'), "b");
+ assert.equal(recordForQuote([{ id: "a", text: "x" }], "not there"), "a");
+ assert.deepEqual(
+ pageCitationAsPost({ kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x", quote: "q", label: "L", note: "n" }, { channel: "blog", id: "r1" }),
+ { kind: "post", channel: "blog", id: "r1", quote: "q", label: "L", note: "n" },
+ );
+});
+
+test("a gone cited page: dry run names the nearest capture; the run imports it and names the record to cite; again = held", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 });
+ const dir = await pagesChannel("old-blog", "blog.example/");
+ const citations: Record<string, Citation> = {
+ c1: { kind: "page", url: PAGE_ARTICLE_URL, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" },
+ c2: { kind: "page", url: "https://live.example/up", quote: "still here" },
+ c3: { kind: "page", url: "https://elsewhere.example/gone", quote: "nobody covers this" },
+ c4: { kind: "page", url: "https://blog.example/never-captured.html", quote: "never captured" },
+ c5: { kind: "video", channel: "v", id: "abc", start: 1, end: 2, quote: "a video" },
+ };
+ const reports = [
+ { id: "r1", citations },
+ { id: "r2", citations: { x1: { kind: "page", url: PAGE_ARTICLE_URL, quote: "The first loaf came out flat" } as Citation } },
+ ];
+ const checks = new Map<string, OriginalCheck>([
+ [PAGE_ARTICLE_URL, verdict(PAGE_ARTICLE_URL, "deleted", 404)],
+ ["https://live.example/up", verdict("https://live.example/up", "available", 200)],
+ ["https://elsewhere.example/gone", verdict("https://elsewhere.example/gone", "deleted", 410)],
+ ["https://blog.example/never-captured.html", verdict("https://blog.example/never-captured.html", "deleted", 404)],
+ ]);
+ const asked: string[] = [];
+ const deps = {
+ reports: async () => reports,
+ check: async (url: string) => {
+ asked.push(url);
+ return checks.get(url) ?? verdict(url, "error", null);
+ },
+ nearest: (url: string, at: string) => client.closestCapture(url, at),
+ importCapture: (o: { slug: string; url: string }) => importPage({ paths, slug: o.slug, url: o.url, client, settings: SETTINGS }),
+ now: () => NOW,
+ };
+ const lines: string[] = [];
+ const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps, onLog: (l) => lines.push(l) });
+ assert.deepEqual([dry.pages, dry.posts], [4, 0]);
+ const byUrl = (r: typeof dry) => new Map(r.items.map((i) => [i.url, i]));
+ const d = byUrl(dry);
+ assert.equal(d.get(PAGE_ARTICLE_URL)!.outcome, "would-import");
+ assert.equal(d.get(PAGE_ARTICLE_URL)!.capture!.timestamp, PAGE_ARTICLE_LATER_TS, "the capture nearest 2015-06");
+ assert.deepEqual(d.get(PAGE_ARTICLE_URL)!.citedBy, ["r1#c1", "r2#x1"]);
+ assert.equal(d.get("https://live.example/up")!.outcome, "live");
+ assert.equal(d.get("https://elsewhere.example/gone")!.outcome, "no-channel");
+ assert.equal(d.get("https://blog.example/never-captured.html")!.outcome, "none-found");
+ assert.deepEqual(await readAllPosts(dir), [], "a dry run imports nothing");
+ assert.ok(lines.some((l) => /1 capture\(s\) would be imported \(dry run: nothing imported\)/.test(l)));
+
+ const run = await findPageCopies({ paths, host: HOST, deps });
+ const item = byUrl(run).get(PAGE_ARTICLE_URL)!;
+ const id = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL);
+ assert.equal(item.outcome, "imported", item.detail);
+ assert.deepEqual(item.pointTo, { channel: "old-blog", id });
+ assert.deepEqual(item.as, { kind: "post", channel: "old-blog", id, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" });
+ assert.deepEqual((await readAllPosts(dir)).map((p) => p.id), [id]);
+
+ // Again: the channel holds the page — nothing fetched.
+ const before = wb.requests.length;
+ const again = await findPageCopies({ paths, host: HOST, deps });
+ assert.equal(byUrl(again).get(PAGE_ARTICLE_URL)!.outcome, "held");
+ assert.deepEqual(byUrl(again).get(PAGE_ARTICLE_URL)!.pointTo, { channel: "old-blog", id });
+ assert.equal(wb.requests.length - before, 1, "only the never-captured page's CDX lookup");
+
+ // `max` leaves the rest for a later run.
+ const capped = await findPageCopies({ paths, host: HOST, deps, max: 1, dryRun: true });
+ assert.deepEqual([capped.items.length, capped.left], [1, 3]);
+
+ // A named channel that is not a pages channel is refused.
+ await assert.rejects(findPageCopies({ paths, host: HOST, deps, channel: "nope" }), /not a Wayback pages channel/);
+ } finally {
+ await wb.close();
+ }
+});
+
+test("a cited page record whose original is gone: held when its capture is stored, imported again when it is not", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 });
+ const dir = await pagesChannel("home-site", "home.example/");
+ // One record whose capture is stored (imported), one whose is not (its
+ // record written alone).
+ const imp = await importPage({ paths, slug: "home-site", url: `https://web.archive.org/web/${PAGE_TOOLBAR_TS}/${PAGE_TOOLBAR_URL}`, client, settings: SETTINGS });
+ assert.equal(imp.ok, true, imp.error);
+ const stored = imp.records![0]!;
+ const loose = (await readAllPosts(dir))[0]!;
+ const looseUrl = "https://home.example/links";
+ const looseTs = "20150101000000";
+ const looseId = pageRecordId(looseTs, looseUrl);
+ await upsertPosts(dir, [
+ {
+ ...loose,
+ id: looseId,
+ slug: `home-site/${looseId}`,
+ url: looseUrl,
+ page: { ...loose.page!, originalUrl: looseUrl, captureTs: looseTs, waybackUrl: `https://web.archive.org/web/${looseTs}/${looseUrl}`, rawUrl: `https://web.archive.org/web/${looseTs}id_/${looseUrl}` },
+ },
+ ]);
+ await writePostAvailability(dir, {
+ [stored]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" },
+ [looseId]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" },
+ });
+ const imported: string[] = [];
+ const deps = {
+ reports: async () => [
+ {
+ id: "r9",
+ citations: {
+ a: { kind: "post", channel: "home-site", id: stored, quote: "zines" } as Citation,
+ b: { kind: "post", channel: "home-site", id: looseId, quote: "links" } as Citation,
+ c: { kind: "post", channel: "not-a-pages-channel", id: "1", quote: "x" } as Citation,
+ },
+ },
+ ],
+ check: async (url: string) => verdict(url, "error", null),
+ nearest: (url: string, at: string) => client.closestCapture(url, at),
+ importCapture: async (o: { slug: string; url: string }) => {
+ imported.push(o.url);
+ return { ok: true, slug: o.slug, url: o.url, written: 0, updated: 0, unchanged: 1, records: [looseId] };
+ },
+ now: () => NOW,
+ };
+ const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps });
+ assert.equal(dry.posts, 2);
+ const of = (r: typeof dry, id: string) => r.items.find((i) => i.record?.id === id)!;
+ assert.equal(of(dry, stored).outcome, "held");
+ assert.equal(of(dry, looseId).outcome, "would-import");
+ assert.deepEqual(imported, []);
+ const run = await findPageCopies({ paths, host: HOST, deps });
+ assert.equal(of(run, looseId).outcome, "imported");
+ assert.deepEqual(imported, [`https://web.archive.org/web/${looseTs}/${looseUrl}`]);
+ assert.deepEqual(of(run, stored).pointTo, { channel: "home-site", id: stored });
+ } finally {
+ await wb.close();
+ }
+});
diff --git a/common/publish/findCopyPages.ts b/common/publish/findCopyPages.ts
@@ -0,0 +1,420 @@
+// FIND A COPY OF A GONE PAGE A REPORT CITES (release 37 S5) — find-copy's
+// page mode, beside its video modes (./findCopy.ts). A report cites a web page
+// either as a `page` citation (`{url, archiveUrl?}`: the page is not in the
+// corpus) or as a `post` citation of a page record (a Wayback Machine capture
+// already imported into a Wayback pages channel). When the page's ORIGINAL is
+// gone, the Wayback Machine's copy is the only copy, and the report should
+// cite it as a record:
+//
+// a `page` citation its original URL asked at its own site
+// (lib/waybackPages/liveness-server.ts, the web pacer);
+// gone (deleted, or the account/document unavailable) →
+// the capture NEAREST the citation's date (its `date`,
+// else its archiveUrl's timestamp, else today: the latest)
+// through ONE CDX request (WaybackClient.closestCapture),
+// imported into the Wayback pages channel named
+// (`channel`) or the one whose targets cover the URL
+// (import-page, controller/importPage.ts) — unless that
+// channel already holds a record of the page. Live: left
+// (Save Page Now is the act for a live page). The answer
+// names the record the citation should cite (`pointTo`)
+// and the citation as a `post` citation of it (`as`).
+// a `post` citation of a page record whose original the availability
+// check found deleted: its capture is held (nothing to
+// do) or, when its raw body is not stored, imported again.
+//
+// THE CITATION IS NOT REWRITTEN HERE: `pointTo`/`as` are what the report's
+// citation becomes (the report editor's "Import this capture" rewrites a page
+// citation to a post citation and keeps the page citation as its fallback;
+// release 37 lane D). A dry run asks the same paced questions and imports
+// nothing.
+//
+// PACED: one page at a time, at most `max` lookups per run; every Wayback
+// request goes through the process's Wayback client (one stream, 2 s apart,
+// 429s waited out — a refusal stops the run there), every original-site
+// request through the web pacer. The job runs on the archive.org queue.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema";
+import type { Post } from "../lib/posts";
+import { readAllPosts, readPostAvailability } from "../lib/posts-server";
+import { listChannelConfigs } from "../controller/channels";
+import { isWaybackPagesChannel, type WaybackTarget } from "../lib/waybackPages/config";
+import { bareHost, type OriginalCheck } from "../lib/waybackPages/liveness";
+import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import { hasStoredCapture } from "../lib/waybackPages/store-server";
+import { parseWaybackUrl, waybackPageUrl } from "../lib/wayback";
+import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
+import { waybackClient, type WaybackCapture, type WaybackClient } from "../lib/waybackClient";
+import { importPage, type ImportPageResult } from "../controller/importPage";
+import { loadHostReports } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+
+export const FIND_PAGE_COPY_DEFAULT_MAX = 10;
+export const FIND_PAGE_COPY_MAX_LIMIT = 100;
+
+// ─── Which channel a page belongs in ───
+
+const bare = (u: string) =>
+ u
+ .trim()
+ .replace(/^https?:\/\//i, "")
+ .replace(/^www\./i, "")
+ .replace(/#.*$/, "")
+ .replace(/\/+$/, "")
+ .toLowerCase();
+
+// Whether a Wayback pages channel's target covers a page.
+export function targetCoversUrl(target: Pick<WaybackTarget, "url" | "match">, url: string): boolean {
+ const host = bareHost(/^https?:\/\//i.test(url) ? url : `https://${url}`);
+ const targetHost = bareHost(/^https?:\/\//i.test(target.url) ? target.url : `https://${target.url}`);
+ if (!host || !targetHost) return false;
+ switch (target.match) {
+ case "exact":
+ return bare(url) === bare(target.url);
+ case "prefix":
+ return bare(url).startsWith(bare(target.url));
+ case "host":
+ return host === targetHost;
+ case "domain":
+ return host === targetHost || host.endsWith(`.${targetHost}`);
+ default:
+ return false;
+ }
+}
+
+// The Wayback pages channels whose targets cover `url`, by slug.
+export function channelsCovering(
+ channels: ReadonlyArray<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>,
+ url: string,
+): string[] {
+ return channels
+ .filter((c) => isWaybackPagesChannel(c.config) && (c.config.wayback?.targets ?? []).some((t) => targetCoversUrl(t, url)))
+ .map((c) => c.slug);
+}
+
+// ─── What the reports cite ───
+
+export type CitedPage = {
+ // `<report>#<citation id>` of each citation of it.
+ citedBy: string[];
+ url: string;
+ // The citation's own date or archive copy, for the nearest capture.
+ at?: string;
+ // The first citation's words (to pick the record of a split capture).
+ quote: string;
+ citation: PageCitation;
+};
+
+export type CitedPageRecord = {
+ citedBy: string[];
+ channel: string;
+ id: string;
+};
+
+// "2014-03-05…" / "2014-03" / "2014" → a capture time prefix.
+export function captureAtOf(c: Pick<PageCitation, "date" | "archiveUrl">, today: Date): string {
+ const d = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/.exec(c.date ?? "");
+ if (d) return `${d[1]}${d[2] ?? ""}${d[3] ?? ""}`;
+ const ref = parseWaybackUrl(c.archiveUrl ?? "");
+ if (ref && /^\d{4,14}$/.test(ref.captureTs)) return ref.captureTs;
+ return today.toISOString().slice(0, 10).replaceAll("-", "");
+}
+
+export function citedPages(
+ reports: ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>,
+ today: Date,
+): { pages: CitedPage[]; posts: CitedPageRecord[] } {
+ const pages = new Map<string, CitedPage>();
+ const posts = new Map<string, CitedPageRecord>();
+ for (const r of reports) {
+ for (const [cid, c] of Object.entries(r.citations ?? {})) {
+ const by = `${r.id}#${cid}`;
+ if (c.kind === "page") {
+ if (!/^https?:\/\//i.test(c.url)) continue;
+ const key = bare(c.url);
+ const seen = pages.get(key);
+ if (seen) seen.citedBy.push(by);
+ else pages.set(key, { citedBy: [by], url: c.url.trim(), at: captureAtOf(c, today), quote: c.quote, citation: c });
+ } else if (c.kind === "post") {
+ const key = `${c.channel}/${c.id}`;
+ const seen = posts.get(key);
+ if (seen) seen.citedBy.push(by);
+ else posts.set(key, { citedBy: [by], channel: c.channel, id: c.id });
+ }
+ }
+ }
+ return { pages: [...pages.values()], posts: [...posts.values()] };
+}
+
+// The record a quote is from, among a capture's records: the one whose text
+// holds the quote's words, else the first (a whole page's one record).
+export function recordForQuote(records: ReadonlyArray<Pick<Post, "id" | "text">>, quote: string): string | null {
+ if (records.length === 0) return null;
+ const fold = (s: string) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ").trim().toLowerCase();
+ const q = fold(quote);
+ if (q) {
+ const hit = records.find((r) => fold(r.text).includes(q));
+ if (hit) return hit.id;
+ }
+ return records[0]!.id;
+}
+
+// A page citation as a post citation of the record: its words and editorial
+// fields kept; the record carries the URL, the title and the Wayback copy.
+export function pageCitationAsPost(c: PageCitation, pointTo: { channel: string; id: string }): PostCitation {
+ const { kind: _kind, url: _url, title: _title, archiveUrl: _archive, ...common } = c;
+ return { kind: "post", channel: pointTo.channel, id: pointTo.id, ...common };
+}
+
+// ─── find-copy, page mode ───
+
+export type FindPageCopyOutcome =
+ // imported the nearest capture imported; `pointTo` is its record
+ // would-import (dry run) what an import would fetch
+ // held the channel already holds a record of the page (or the
+ // cited record's capture is stored): nothing fetched
+ // live the original still answers: left (Save Page Now it)
+ // none-found the Wayback Machine holds no capture that recorded a page
+ // no-channel no Wayback pages channel covers the URL and none was named
+ // refused the import was refused (its sentence: X, a video, …)
+ // error a check or a lookup failed: a later run asks again
+ | "imported"
+ | "would-import"
+ | "held"
+ | "live"
+ | "none-found"
+ | "no-channel"
+ | "refused"
+ | "error";
+
+export type FindPageCopyItem = {
+ citedBy: string[];
+ // The page cited, or the record cited.
+ url: string;
+ record?: { channel: string; id: string };
+ original?: Pick<OriginalCheck, "availability" | "status" | "reason">;
+ channel?: string;
+ capture?: { timestamp: string; original: string; waybackUrl: string };
+ outcome: FindPageCopyOutcome;
+ detail: string;
+ pointTo?: { channel: string; id: string };
+ // The citation as a post citation of `pointTo` (a page citation only).
+ as?: PostCitation;
+ records?: string[];
+};
+
+export type FindPageCopiesResult = {
+ host: string;
+ dryRun: boolean;
+ max: number;
+ pages: number;
+ posts: number;
+ items: FindPageCopyItem[];
+ // Cited pages left for a later run by `max`.
+ left: number;
+ stopped?: string;
+};
+
+export type FindPageCopiesDeps = {
+ reports: (host: ReportHost) => Promise<ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>>;
+ channels: (paths: Paths) => Promise<Array<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>>;
+ check: (url: string, signal?: AbortSignal) => Promise<OriginalCheck>;
+ // THE ONE CAPTURE LOOKUP: the capture of `url` nearest `at` (default: the
+ // Wayback Machine's CDX `closest`). An archive-source registry can stand in
+ // here without the rest of the mode changing.
+ nearest: (url: string, at: string, signal?: AbortSignal) => Promise<WaybackCapture | null>;
+ importCapture: (o: { slug: string; url: string; signal?: AbortSignal; onLog?: (line: string) => void }) => Promise<ImportPageResult>;
+ now: () => Date;
+};
+
+export function defaultFindPageCopiesDeps(paths: Paths, o: { check?: CheckOriginalOptions; client?: WaybackClient } = {}): FindPageCopiesDeps {
+ const client = o.client ?? waybackClient;
+ return {
+ reports: async (host) => (await loadHostReports(host)).reports,
+ channels: (p) => listChannelConfigs(p),
+ check: (url, signal) => checkOriginalUrl(url, { ...o.check, ...(signal ? { signal } : {}) }),
+ nearest: (url, at, signal) => client.closestCapture(url, at, signal ? { signal } : {}),
+ importCapture: (io) => importPage({ paths, slug: io.slug, url: io.url, client, ...(io.signal ? { signal: io.signal } : {}), ...(io.onLog ? { onLog: io.onLog } : {}) }),
+ now: () => new Date(),
+ };
+}
+
+const GONE = new Set(["deleted", "account_unavailable"]);
+
+export async function findPageCopies(opts: {
+ paths: Paths;
+ host: ReportHost;
+ // The Wayback pages channel every capture goes to (else: the one whose
+ // targets cover the page).
+ channel?: string;
+ dryRun?: boolean;
+ max?: number;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindPageCopiesDeps>;
+}): Promise<FindPageCopiesResult> {
+ const deps: FindPageCopiesDeps = { ...defaultFindPageCopiesDeps(opts.paths), ...opts.deps };
+ const log = (line: string) => opts.onLog?.(line);
+ const signal = opts.signal;
+ const dryRun = opts.dryRun === true;
+ const max = Math.min(FIND_PAGE_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_PAGE_COPY_DEFAULT_MAX)));
+ const today = deps.now();
+ const cited = citedPages(await deps.reports(opts.host), today);
+ const channels = await deps.channels(opts.paths);
+ const pagesChannels = new Set(channels.filter((c) => isWaybackPagesChannel(c.config)).map((c) => c.slug));
+ if (opts.channel && !pagesChannels.has(opts.channel)) {
+ throw new Error(`${opts.channel} is not a Wayback pages channel; name one on platform "webpage", or none (the channel whose targets cover each page)`);
+ }
+ // The post citations of page records only.
+ const postCitations = cited.posts.filter((p) => pagesChannels.has(p.channel));
+ const result: FindPageCopiesResult = { host: opts.host.id, dryRun, max, pages: cited.pages.length, posts: postCitations.length, items: [], left: 0 };
+ log(
+ `find-copy ${opts.host.id} (pages${dryRun ? ", dry run" : ""}): ${cited.pages.length} cited page(s), ` +
+ `${postCitations.length} cited page record(s); at most ${max} looked up.`,
+ );
+ const recordsOf = new Map<string, Post[]>();
+ const channelRecords = async (slug: string): Promise<Post[]> => {
+ let list = recordsOf.get(slug);
+ if (!list) {
+ list = (await readAllPosts(path.join(opts.paths.channelsDir, slug)).catch(() => [] as Post[])).filter((p) => p.page);
+ recordsOf.set(slug, list);
+ }
+ return list;
+ };
+
+ let lookups = 0;
+ const stopOn = (e: unknown): string | null =>
+ e instanceof ArchiveOrgRequestError && e.rateLimited ? `archive.org kept refusing (${e.message}); the rest are left for a later run` : null;
+
+ // 1. Cited pages.
+ for (const page of cited.pages) {
+ if (signal?.aborted || result.stopped) break;
+ if (lookups >= max) {
+ result.left++;
+ continue;
+ }
+ lookups++;
+ const item: FindPageCopyItem = { citedBy: page.citedBy, url: page.url, outcome: "error", detail: "" };
+ result.items.push(item);
+ const checked = await deps.check(page.url, signal);
+ item.original = { availability: checked.availability, status: checked.status, reason: checked.reason };
+ if (checked.availability === "available") {
+ item.outcome = "live";
+ item.detail = `the original still answers (${checked.reason}): left — Save Page Now captures a live page`;
+ } else if (!GONE.has(checked.availability)) {
+ item.outcome = "error";
+ item.detail = `the original could not be checked (${checked.reason}): try again later`;
+ } else {
+ const covering = opts.channel ? [opts.channel] : channelsCovering(channels, page.url);
+ const slug = covering[0];
+ if (!slug) {
+ item.outcome = "no-channel";
+ item.detail = `the original is gone (${checked.reason}), and no Wayback pages channel covers ${bareHost(page.url) || page.url}: name one ("channel") or create one targeting it`;
+ } else {
+ item.channel = slug;
+ const held = (await channelRecords(slug)).filter((r) => bare(r.page!.originalUrl) === bare(page.url));
+ if (held.length > 0) {
+ const id = recordForQuote(held, page.quote)!;
+ item.outcome = "held";
+ item.pointTo = { channel: slug, id };
+ item.as = pageCitationAsPost(page.citation, item.pointTo);
+ item.detail = `the original is gone (${checked.reason}); ${slug} already holds ${held.length} record(s) of the page`;
+ } else {
+ try {
+ const near: WaybackCapture | null = await deps.nearest(page.url, page.at ?? "", signal);
+ if (!near) {
+ item.outcome = "none-found";
+ item.detail = `the original is gone (${checked.reason}), and the Wayback Machine holds no capture of it that recorded a page`;
+ } else {
+ const waybackUrl = waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original });
+ item.capture = { timestamp: near.timestamp, original: near.original, waybackUrl };
+ if (dryRun) {
+ item.outcome = "would-import";
+ item.detail = `the original is gone (${checked.reason}); would import the capture ${near.timestamp} (nearest ${page.at}) into ${slug}`;
+ } else {
+ const imp = await deps.importCapture({ slug, url: waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) });
+ if (!imp.ok) {
+ // archive.org kept refusing (the client's sentence): stop the run there.
+ const busy = /did not answer .* attempts/.test(imp.error ?? "");
+ item.outcome = busy ? "error" : "refused";
+ item.detail = busy ? (imp.error ?? "") : `the import was refused: ${imp.error}`;
+ if (busy) result.stopped = `archive.org kept refusing (${imp.error}); the rest are left for a later run`;
+ } else {
+ recordsOf.delete(slug);
+ const records = (await channelRecords(slug)).filter((r) => (imp.records ?? []).includes(r.id));
+ const id = recordForQuote(records.length ? records : (imp.records ?? []).map((rid) => ({ id: rid, text: "" })), page.quote);
+ item.outcome = "imported";
+ item.records = imp.records ?? [];
+ if (id) {
+ item.pointTo = { channel: slug, id };
+ item.as = pageCitationAsPost(page.citation, item.pointTo);
+ }
+ item.detail = `the original is gone (${checked.reason}); ${imp.already ? "the capture was already stored" : "imported"} the capture ${imp.captureTs} into ${slug}`;
+ }
+ }
+ }
+ } catch (e) {
+ if (signal?.aborted) break;
+ item.outcome = "error";
+ item.detail = (e as Error).message;
+ const stop = stopOn(e);
+ if (stop) result.stopped = stop;
+ }
+ }
+ }
+ }
+ log(` ${page.url} (${page.citedBy.join(", ")}): ${item.outcome} — ${item.detail}${item.pointTo ? ` → cite ${item.pointTo.channel}/${item.pointTo.id}` : ""}`);
+ }
+
+ // 2. Cited page records whose original the availability check found gone.
+ for (const cite of postCitations) {
+ if (signal?.aborted || result.stopped) break;
+ const channelRoot = path.join(opts.paths.channelsDir, cite.channel);
+ const av = (await readPostAvailability(channelRoot))[cite.id];
+ if (!av || !GONE.has(av.availability)) continue;
+ const record = (await channelRecords(cite.channel)).find((r) => r.id === cite.id);
+ if (!record?.page) continue;
+ const item: FindPageCopyItem = {
+ citedBy: cite.citedBy,
+ url: record.page.originalUrl,
+ record: { channel: cite.channel, id: cite.id },
+ original: { availability: av.availability, status: av.status ?? null, reason: av.reason ?? "the availability check" },
+ channel: cite.channel,
+ capture: { timestamp: record.page.captureTs, original: record.page.originalUrl, waybackUrl: record.page.waybackUrl },
+ outcome: "held",
+ detail: "",
+ pointTo: { channel: cite.channel, id: cite.id },
+ };
+ result.items.push(item);
+ if (await hasStoredCapture(channelRoot, record.page.captureTs, record.page.originalUrl)) {
+ item.detail = `the original is gone (${item.original!.reason}); the record's capture is held — the Wayback copy is the only copy`;
+ } else if (dryRun) {
+ item.outcome = "would-import";
+ item.detail = `the original is gone; the record's capture is not stored: would import ${record.page.waybackUrl} into ${cite.channel}`;
+ } else {
+ try {
+ const imp = await deps.importCapture({ slug: cite.channel, url: record.page.waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) });
+ item.outcome = imp.ok ? "imported" : "refused";
+ item.records = imp.records ?? [];
+ item.detail = imp.ok ? `the original is gone; the record's capture imported again into ${cite.channel}` : `the import was refused: ${imp.error}`;
+ } catch (e) {
+ if (signal?.aborted) break;
+ item.outcome = "error";
+ item.detail = (e as Error).message;
+ const stop = stopOn(e);
+ if (stop) result.stopped = stop;
+ }
+ }
+ log(` ${cite.channel}/${cite.id} (${cite.citedBy.join(", ")}): ${item.outcome} — ${item.detail}`);
+ }
+
+ if (signal?.aborted && !result.stopped) result.stopped = "cancelled; the rest are left for a later run";
+ if (result.stopped) log(`find-copy: ${result.stopped}.`);
+ if (result.left > 0) log(`find-copy: ${result.left} more cited page(s) are left for a later run (max ${max}).`);
+ const imported = result.items.filter((i) => i.outcome === "imported").length;
+ const would = result.items.filter((i) => i.outcome === "would-import").length;
+ log(`find-copy: ${dryRun ? `${would} capture(s) would be imported (dry run: nothing imported)` : `${imported} capture(s) imported`}.`);
+ return result;
+}
diff --git a/common/social/__fixtures__/fakeForumThread.ts b/common/social/__fixtures__/fakeForumThread.ts
@@ -0,0 +1,75 @@
+// A SYNTHETIC forum thread that changes between runs (release 37 lane G): posts
+// arrive at its end, posts are deleted and the pages shift down, a page is
+// served as a challenge. The walk's tests read it through a loader, the
+// controller's and the e2e suite's through the saved-pages directory
+// E2E_FORUM_FIXTURE_DIR names (social/forumFixtureLoader.ts). Invented forum,
+// members and words (xenforoPages.ts).
+
+import { mkdir, readdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { threadPage, type FakePost } from "./xenforoPages";
+
+export const FAKE_THREAD_ID = "4242";
+const T0 = 1_760_000_000;
+
+export class FakeForumThread {
+ // The thread's posts as the forum shows them now, oldest first.
+ posts: FakePost[] = [];
+ private nextId: number;
+
+ constructor(
+ count: number,
+ readonly perPage = 3,
+ idBase = 9000,
+ ) {
+ this.nextId = idBase + 1;
+ this.add(count);
+ }
+
+ // `n` new posts at the thread's end.
+ add(n: number): void {
+ for (let i = 0; i < n; i++) {
+ const id = this.nextId++;
+ this.posts.push({ id, author: `Member${id % 4}`, userId: 50 + (id % 4), ts: T0 + id * 600, position: 0, body: `Words of post ${id}.` });
+ }
+ }
+
+ // Delete posts (by id): every later post moves back, pages shift down.
+ remove(ids: Iterable<number>): void {
+ const gone = new Set(ids);
+ this.posts = this.posts.filter((p) => !gone.has(p.id));
+ }
+
+ get last(): number {
+ return Math.max(1, Math.ceil(this.posts.length / this.perPage));
+ }
+
+ // The posts of page n (1-based), positions as the forum numbers them now.
+ pagePosts(n: number): FakePost[] {
+ const page = Math.min(Math.max(1, n), this.last);
+ return this.posts
+ .slice((page - 1) * this.perPage, page * this.perPage)
+ .map((p, i) => ({ ...p, position: (page - 1) * this.perPage + i + 1 }));
+ }
+
+ html(n: number): string {
+ const page = Math.min(Math.max(1, n), this.last);
+ return threadPage({ page, last: this.last, posts: this.pagePosts(page) });
+ }
+
+ ids(): string[] {
+ return this.posts.map((p) => String(p.id));
+ }
+
+ // The thread as E2E_FORUM_FIXTURE_DIR's saved pages: `<dir>/4242/page-<N>.html`,
+ // pages past the end removed (block overrides are left alone).
+ async writeTo(dir: string): Promise<void> {
+ const threadDir = path.join(dir, FAKE_THREAD_ID);
+ await mkdir(threadDir, { recursive: true });
+ for (const f of await readdir(threadDir)) {
+ const m = /^page-(\d+)\.html$/.exec(f);
+ if (m && Number(m[1]) > this.last) await rm(path.join(threadDir, f));
+ }
+ for (let n = 1; n <= this.last; n++) await writeFile(path.join(threadDir, `page-${n}.html`), this.html(n));
+ }
+}
diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts
@@ -15,6 +15,7 @@
import type { Post, PostAvailability, PostPlatform } from "../lib/posts";
import type { OlderBackfillPosition } from "../lib/posts-server";
+import type { ForumWalkState } from "../lib/forumWalk";
import type { XCookieSource } from "./xCookieSource";
import type { PostCaptureState } from "./postCapture";
@@ -67,7 +68,11 @@ export type PostFetchInput = {
// Save progress during a long run: called with posts not yet handed back and
// the resume point they are safe under. Posts passed here are NOT returned
// again in the result. A fetcher that pages in one shot never calls it.
- onCheckpoint?: (checkpoint: { posts: Post[]; cursor: string }) => Promise<void>;
+ onCheckpoint?: (checkpoint: { posts: Post[]; cursor: string; forumWalk?: ForumWalkState }) => Promise<void>;
+ // A forum thread's walk positions (lib/forumWalk.ts), derived by the
+ // controller from posts-state.json and the archived posts' pages. Given, it
+ // replaces `cursor` and `since` for the forum walker; the others ignore it.
+ forumWalk?: ForumWalkState;
signal: AbortSignal;
// A soft stop (the job's Drain): the run ends at its next resume point —
// between two pages — keeping that point, rather than walking on. `signal`
@@ -92,6 +97,14 @@ export type PostFetchResult = {
error?: string;
// The run stopped on `drain` at a resume point (`cursor`). Not a failure.
drained?: boolean;
+ // A forum thread's walk positions after the run (with every checkpoint's).
+ forumWalk?: ForumWalkState;
+ // What stopped the run, when the source refused or challenged it — the
+ // controller's retry-on-block reads it (a "challenge" or "blocked" is waited
+ // out and retried; a captcha or a login needs a person).
+ block?: "challenge" | "captcha" | "blocked" | "login" | "not-found" | "unknown";
+ // A complete full re-walk: archived posts of the thread it met on no page.
+ notSeen?: string[];
};
// Input for the older-posts backfill (`SocialFetcher.fetchOlder`): walk the
diff --git a/common/social/forumFixtureLoader.ts b/common/social/forumFixtureLoader.ts
@@ -0,0 +1,44 @@
+// A forum page loader over a DIRECTORY OF SAVED PAGES, for the editor's e2e
+// suite (E2E_FORUM_FIXTURE_DIR, set per slot by e2e/servers.ts only): the
+// forum-thread fetcher reads `<dir>/<threadId>/page-<N>.html` instead of
+// opening a browser, so the channel page's Fetch posts and Full re-walk run end
+// to end with no network. A page number past the last file is the last page,
+// as XenForo redirects it. `page-<N>.<status>.html` (a challenge page, a 403)
+// is served in place of page N, with that status, while it exists — a test
+// removes it to let the "block" clear. SYNTHETIC pages only.
+
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import type { ForumPageLoader } from "./forumSession";
+import { xenforoPageUrl, type XenforoThreadUrl } from "./xenforoParse";
+
+export function forumFixtureDir(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
+ const dir = env.E2E_FORUM_FIXTURE_DIR;
+ return dir && dir.trim() ? dir : undefined;
+}
+
+export function fixtureForumLoader(dir: string, thread: XenforoThreadUrl): ForumPageLoader {
+ const threadDir = path.join(dir, thread.threadId);
+ return {
+ async load(url) {
+ const files = await readdir(threadDir).catch(() => [] as string[]);
+ const pages = files
+ .map((f) => /^page-(\d+)\.html$/.exec(f))
+ .filter((m): m is RegExpExecArray => m !== null)
+ .map((m) => Number(m[1]));
+ if (pages.length === 0) throw new Error(`Could not load ${url}: no fixture pages in ${threadDir}`);
+ const m = /page-(\d+)\/?$/.exec(new URL(url).pathname);
+ const wanted = m ? Number(m[1]) : 1;
+ const page = Math.min(wanted, Math.max(...pages));
+ const blocked = files.map((f) => new RegExp(`^page-${page}\\.(\\d{3})\\.html$`).exec(f)).find((b) => b);
+ if (blocked) {
+ const html = await readFile(path.join(threadDir, blocked[0]), "utf8");
+ return { html, status: Number(blocked[1]), url: xenforoPageUrl(thread, page) };
+ }
+ const html = await readFile(path.join(threadDir, `page-${page}.html`), "utf8").catch(() => "");
+ if (!html) throw new Error(`Could not load ${url}: no fixture page ${page}`);
+ return { html, status: 200, url: xenforoPageUrl(thread, page) };
+ },
+ async close() {},
+ };
+}
diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts
@@ -19,6 +19,8 @@
// Pure and client-safe — no node imports. The settings schema, the fetch
// controller and the editor's Settings section all read it.
+import { parseRetryOnBlock, type RetryOnBlock } from "../lib/forumWalk";
+
export type XCookieSource = "browser" | "profile";
export const X_COOKIE_SOURCES: readonly XCookieSource[] = ["browser", "profile"];
@@ -51,8 +53,17 @@ export type XSocialSettings = {
visibility?: XPostsVisibility;
};
+// A forum thread's (platform "xenforo") settings (release 37 lane G).
+export type XenforoSocialSettings = {
+ // The Fetch posts button's retry on a block: wait `minutes` after a
+ // challenge or refusal page and run again, `max` tries in all. Absent: off.
+ retryOnBlock?: RetryOnBlock;
+};
+
export type SocialSettings = {
x: XSocialSettings;
+ // Absent: nothing set.
+ xenforo?: XenforoSocialSettings;
};
// Total over `unknown`, as every settings coercion is: anything that is not a
@@ -65,11 +76,16 @@ export function sanitizeSocial(value: unknown): SocialSettings {
const x = (r.x && typeof r.x === "object" && !Array.isArray(r.x)
? r.x
: {}) as Record<string, unknown>;
+ const xf = (r.xenforo && typeof r.xenforo === "object" && !Array.isArray(r.xenforo)
+ ? r.xenforo
+ : {}) as Record<string, unknown>;
+ const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock);
return {
x: {
...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}),
...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}),
},
+ ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}),
};
}
diff --git a/common/social/xenforoFetcher.test.ts b/common/social/xenforoFetcher.test.ts
@@ -10,6 +10,8 @@ import os from "node:os";
import path from "node:path";
import type { Post } from "../lib/posts";
import type { PostFetchInput } from "./fetchers";
+import { deriveForumWalk, type ForumWalkState } from "../lib/forumWalk";
+import { FakeForumThread } from "./__fixtures__/fakeForumThread";
import { loadForumPage, presentableUserAgent, type ForumPageLoader } from "./forumSession";
import type { PageLike } from "./playwrightRuntime";
import {
@@ -64,7 +66,7 @@ const pageOf = (url: string): number => {
type FakeLoader = ForumPageLoader & { urls: string[]; closed: number };
function fakeLoader(
- override: (url: string, page: number) => { html: string; status?: number } | undefined = () => undefined,
+ override: (url: string, page: number) => { html: string; status?: number; challengeMs?: number } | undefined = () => undefined,
): FakeLoader {
const loader: FakeLoader = {
urls: [],
@@ -76,6 +78,7 @@ function fakeLoader(
return {
html: o?.html ?? pageHtml(page),
...(o?.status ? { status: o.status } : { status: 200 }),
+ ...(o?.challengeMs !== undefined ? { challengeMs: o.challengeMs } : {}),
url: `${THREAD_URL}${page > 1 ? `page-${page}` : ""}`,
};
},
@@ -159,15 +162,22 @@ test("resume: a run with a cursor catches up from the last page, then continues
test("resume with a pages cap: the latest page is always read first, the cap spans both", async () => {
const seen = new Set(["9007", "9008", "9009", "9010", "9011", "9012", "9013", "9014", "9015"]);
+ // The last page holds nothing new: all held, it does not count — the cap's
+ // one page is the history's.
const one = fakeLoader();
const r1 = await walkXenforoThread(input({ cursor: "2", seenIds: seen, pages: 1 }), deps(one).deps);
- assert.deepEqual(one.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`]);
- assert.equal(r1.cursor, "2", "nothing new, and the older pages still owed");
+ assert.deepEqual(one.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`, `${THREAD_URL}page-2`]);
+ assert.equal(r1.cursor, "1");
+ assert.deepEqual(ids(r1.posts), [4, 5, 6]);
+ assert.equal(r1.forumWalk?.historyPage, 1);
+ assert.equal(r1.forumWalk?.newestPostId, "9015");
+ // A last page with something new counts: then the cap is the catch-up's.
+ const fewer = new Set([...seen].filter((id) => id !== "9015"));
const two = fakeLoader();
- const r2 = await walkXenforoThread(input({ cursor: "2", seenIds: seen, pages: 2 }), deps(two).deps);
- assert.deepEqual(two.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`, `${THREAD_URL}page-2`]);
- assert.equal(r2.cursor, "1");
- assert.deepEqual(ids(r2.posts), [4, 5, 6]);
+ const r2 = await walkXenforoThread(input({ cursor: "2", seenIds: fewer, pages: 1 }), deps(two).deps);
+ assert.deepEqual(two.urls, [`${THREAD_URL}page-${LAST_PAGE_PROBE}`]);
+ assert.deepEqual(ids(r2.posts), [15]);
+ assert.equal(r2.forumWalk?.historyPage, 2, "the history position is not moved by the catch-up");
});
test("incremental: stops on the page holding an already-archived post, keeping its new ones", async () => {
@@ -179,22 +189,37 @@ test("incremental: stops on the page holding an already-archived post, keeping i
assert.equal(loader.urls.length, 2);
});
-test("a full re-walk (stopAtKnown false) does not stop at archived posts", async () => {
+test("a full re-walk (stopAtKnown false) reads every page and hands archived posts back for their edits", async () => {
const loader = fakeLoader();
const res = await walkXenforoThread(
- input({ seenIds: new Set(["9013", "9010"]), stopAtKnown: false }),
+ input({ seenIds: new Set(["9013", "9010", "9999"]), stopAtKnown: false, forumWalk: { historyPage: 3, newestPostId: "9013" } }),
deps(loader).deps,
);
assert.equal(res.complete, true);
assert.equal(loader.urls.length, 5);
- assert.equal(res.posts.length, 13);
+ assert.equal(res.posts.length, 15, "the two archived ones too");
+ assert.equal(res.forumWalk?.complete, true);
+ assert.equal(res.forumWalk?.historyPage, undefined);
+ assert.equal(res.forumWalk?.newestPostId, "9015");
+ // An archived post no page shows any more: counted, not marked.
+ assert.deepEqual(res.notSeen, ["9999"]);
});
-test("the watermark stops the walk", async () => {
- const since = new Date((T0 + 10 * 600) * 1000).toISOString(); // post 10's time
- const res = await walkXenforoThread(input({ since }), deps(fakeLoader()).deps);
+test("the mark stops the catch-up: an archived post newer than it does not", async () => {
+ // Posts 13–15 were read by an earlier, capped catch-up (above the mark,
+ // 9010); 11 and 12 are owed; 10 is the mark.
+ const seen = new Set(["9001", "9002", "9003", "9004", "9005", "9006", "9007", "9008", "9009", "9010", "9013", "9014", "9015"]);
+ const loader = fakeLoader();
+ const log: string[] = [];
+ const res = await walkXenforoThread(
+ input({ seenIds: seen, forumWalk: { newestPostId: "9010", complete: true, newestPage: 4 }, onLog: (l) => log.push(l) }),
+ deps(loader).deps,
+ );
assert.equal(res.complete, true);
- assert.deepEqual(ids(res.posts), [13, 14, 15, 11, 12]);
+ assert.deepEqual(ids(res.posts), [11, 12]);
+ assert.equal(loader.urls.length, 2);
+ assert.equal(res.forumWalk?.newestPostId, "9015");
+ assert.match(log.join("\n"), /Page 5: all held, skipping on\./);
});
test("a post limit is checked after a whole page", async () => {
@@ -268,12 +293,15 @@ test("a captcha on the very first load keeps no cursor; a 429 is not a session p
assert.match(captcha.error ?? "", /captcha/);
const limited = await walkXenforoThread(
- input({ cursor: "2" }),
+ input({ cursor: "2", seenIds: new Set(["9015"]) }),
deps(fakeLoader(() => ({ html: "<html><body>slow down</body></html>", status: 429 }))).deps,
);
// Refused on the catch-up load: the stored cursor is kept, not lost.
assert.equal(limited.needsCookies, undefined);
assert.equal(limited.cursor, "2");
+ assert.equal(limited.forumWalk?.historyPage, 2);
+ assert.equal(limited.block, "blocked");
+ assert.equal(captcha.block, "captcha");
assert.match(limited.error ?? "", /HTTP 429/);
});
@@ -284,12 +312,11 @@ test("an article thread: its first post atop every page never stops the walk, an
for (let k = (page - 1) * PER_PAGE + 1; k <= page * PER_PAGE; k++) if (k > 1) posts.push(fakePost(k));
return { html: threadPage({ page, last: LAST, posts, article }) };
};
- // Incremental: the starter is archived, and old — neither ends the walk on
- // the last page; the archived post 10 on page 4 does.
+ // Incremental: the starter is archived — it does not end the walk on the
+ // last page; the archived post 10 on page 4 does.
const seen = new Set(["9001", "9010"]);
- const since = new Date((T0 + 10 * 600) * 1000).toISOString();
const res = await walkXenforoThread(
- input({ seenIds: seen, since }),
+ input({ seenIds: seen }),
deps(fakeLoader((_url, page) => withArticle(page))).deps,
);
assert.equal(res.complete, true);
@@ -300,15 +327,35 @@ test("an article thread: its first post atop every page never stops the walk, an
assert.equal(all.posts.length, 15);
});
-test("a page that parses to no posts stops rather than stepping past it", async () => {
+test("a page that parses to no posts is loaded once more, then stops rather than stepping past it", async () => {
const empty = threadPage({ page: 4, last: LAST, posts: [] });
- const res = await walkXenforoThread(
- input(),
- deps(fakeLoader((_url, page) => (page === 4 ? { html: empty } : undefined))).deps,
- );
+ const loader = fakeLoader((_url, page) => (page === 4 ? { html: empty } : undefined));
+ const res = await walkXenforoThread(input(), deps(loader).deps);
assert.equal(res.complete, false);
assert.equal(res.cursor, "4");
assert.match(res.error ?? "", /no posts/);
+ assert.equal(loader.urls.filter((u) => u.endsWith("page-4")).length, 2, "one reload, no more");
+});
+
+test("a page read empty just after a browser check cleared is reloaded, and the walk goes on", async () => {
+ // Live: "The browser check cleared in 12 s. → Page 2193/2606: 0 post(s)
+ // parsed" — the page standing after the check is not the thread page yet.
+ const empty = threadPage({ page: 4, last: LAST, posts: [] });
+ let reads = 0;
+ const loader = fakeLoader((_url, page) => {
+ if (page !== 4) return undefined;
+ reads++;
+ return reads === 1 ? { html: empty, challengeMs: 12_000 } : undefined;
+ });
+ const log: string[] = [];
+ const { deps: d, sleeps } = deps(loader);
+ const res = await walkXenforoThread(input({ onLog: (l) => log.push(l) }), d);
+ assert.equal(res.complete, true);
+ assert.equal(res.error, undefined);
+ assert.equal(res.posts.length, 15, "every post, page 4's included");
+ assert.equal(reads, 2);
+ assert.match(log.join("\n"), /Page 4: no posts on the first read after the browser check cleared; loading it again\./);
+ assert.equal(sleeps.length, loader.urls.length - 1, "the reload is paced like any load");
});
test("a bad cursor and a URL that is not a thread are refused before any load", async () => {
@@ -348,6 +395,116 @@ test("the fetcher claims thread URLs only, and probes offline", async () => {
});
});
+// --- two positions over a thread that changes (release 37 lane G) -----------------
+
+function threadLoader(t: FakeForumThread): FakeLoader {
+ const loader: FakeLoader = {
+ urls: [],
+ closed: 0,
+ async load(url) {
+ loader.urls.push(url);
+ const m = /page-(\d+)$/.exec(url);
+ const page = Math.min(m ? Number(m[1]) : 1, t.last);
+ return { html: t.html(page), status: 200, url: `${THREAD_URL}${page > 1 ? `page-${page}` : ""}` };
+ },
+ async close() {
+ loader.closed++;
+ },
+ };
+ return loader;
+}
+
+const pageUrls = (loader: FakeLoader) =>
+ loader.urls.map((u) => (u === THREAD_URL ? 1 : Number(/page-(\d+)$/.exec(u)![1]))).map((n) => (n === LAST_PAGE_PROBE ? "last" : n));
+
+// One run, as the controller drives it: the archive grows by what it hands
+// back, and the positions are the run's last.
+async function runOnce(
+ t: FakeForumThread,
+ held: Set<string>,
+ walk: ForumWalkState | undefined,
+ over: Partial<PostFetchInput> = {},
+) {
+ const loader = threadLoader(t);
+ const log: string[] = [];
+ const res = await walkXenforoThread(
+ input({ seenIds: new Set(held), ...(walk ? { forumWalk: walk } : {}), onLog: (l) => log.push(l), ...over }),
+ deps(loader).deps,
+ );
+ for (const p of res.posts) held.add(p.id);
+ return { res, loader, log, walk: res.forumWalk };
+}
+
+test("a capped catch-up keeps the history position; the next run jumps below what it read", async () => {
+ const t = new FakeForumThread(30); // 10 pages
+ const held = new Set<string>();
+ // An earlier history walk read pages 10–6.
+ const first = await runOnce(t, held, undefined, { pages: 5 });
+ assert.deepEqual(first.walk, { newestPage: 10, oldestPageReached: 6, historyPage: 5, newestPostId: "9030" });
+ // Nine new posts: pages 11–13. A run capped at 2 pages reads 13 and 12.
+ t.add(9);
+ const capped = await runOnce(t, held, first.walk, { pages: 2 });
+ assert.deepEqual(pageUrls(capped.loader), ["last", 12]);
+ assert.equal(capped.walk?.historyPage, 5, "the catch-up never touches the history position");
+ assert.equal(capped.walk?.catchUpPage, 11);
+ assert.equal(capped.walk?.newestPostId, "9030", "the mark moves only when a catch-up completes");
+ // The next run: page 13 is all held, jump to 11, meet the mark on 10, then
+ // the history at 5 — never re-reading 12, nor 9–6.
+ const next = await runOnce(t, held, capped.walk, { pages: 2 });
+ assert.deepEqual(pageUrls(next.loader), ["last", 11, 10, 5]);
+ assert.match(next.log.join("\n"), /an earlier catch-up read down to page 12; continuing there/);
+ assert.match(next.log.join("\n"), /Caught up to page 13; history resumes at page 5\./);
+ assert.equal(next.walk?.catchUpPage, undefined);
+ assert.equal(next.walk?.newestPostId, "9039");
+ assert.equal(next.walk?.historyPage, 4);
+ // And on to page 1: every post of the thread, once.
+ const rest = await runOnce(t, held, next.walk);
+ assert.deepEqual(pageUrls(rest.loader), ["last", 4, 3, 2, 1]);
+ assert.equal(rest.res.complete, true);
+ assert.equal(rest.walk?.complete, true);
+ assert.deepEqual([...held].sort(), t.ids().sort());
+});
+
+test("drift: posts deleted below the read pages shift every page down, and the history still reaches page 1 with no gap", async () => {
+ const t = new FakeForumThread(30);
+ const held = new Set<string>();
+ const first = await runOnce(t, held, undefined, { pages: 4 }); // pages 10–7: posts 19–30
+ assert.equal(first.walk?.historyPage, 6);
+ // Six early posts deleted: the thread is 8 pages; 19–30 now sit on 5–8.
+ t.remove([9001, 9002, 9003, 9004, 9005, 9006]);
+ const second = await runOnce(t, held, first.walk);
+ assert.deepEqual(pageUrls(second.loader), ["last", 6, 5, 4, 3, 2, 1]);
+ assert.match(second.log.join("\n"), /Page 6: all held, skipping on\./);
+ assert.equal(second.res.complete, true);
+ assert.deepEqual([...held].sort(), t.ids().sort(), "every surviving post, none skipped");
+});
+
+test("all-held pages in the history are stepped past without counting against the caps", async () => {
+ const t = new FakeForumThread(30);
+ const held = new Set(t.ids().slice(9)); // posts 10–30: pages 4–10 held
+ const res = await runOnce(t, held, { historyPage: 9, newestPostId: "9030" }, { pages: 1, limit: 1 });
+ // Page 10 meets the mark, then 9…4 are all held — none counted — and page
+ // 3 is the first with new posts: the one page the cap allows.
+ assert.deepEqual(pageUrls(res.loader), ["last", 9, 8, 7, 6, 5, 4, 3]);
+ assert.deepEqual(ids(res.res.posts), [7, 8, 9]);
+ assert.equal(res.walk?.historyPage, 2);
+ assert.match(res.log.join("\n"), /Page 5: all held, skipping on\./);
+});
+
+test("a lost history position heals from the archived pages (deriveForumWalk), and the walk fills the gap", async () => {
+ const t = new FakeForumThread(30);
+ // Pages 10–5 are held (posts 13–30); the stored position was overwritten
+ // by a catch-up's (page 9).
+ const held = new Set(t.ids().slice(12));
+ const pagesHeld = [10, 10, 10, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 5, 5, 5, 1];
+ const derived = deriveForumWalk({ historyPage: 9, newestPostId: "9030", newestPage: 10 }, undefined, pagesHeld);
+ assert.equal(derived.walk.historyPage, 6, "one page above the held band's foot (5), never the stored 9");
+ assert.match(derived.notes.join("\n"), /above the archived pages/);
+ const run = await runOnce(t, held, derived.walk);
+ assert.deepEqual(pageUrls(run.loader), ["last", 6, 5, 4, 3, 2, 1]);
+ assert.deepEqual([...held].sort(), t.ids().sort());
+});
+
// --- the page loader ---------------------------------------------------------------
function fakePage(script: { status?: number; htmls: string[]; href?: string }) {
diff --git a/common/social/xenforoFetcher.ts b/common/social/xenforoFetcher.ts
@@ -4,15 +4,16 @@
//
// THE WALK, NEWEST FIRST. A thread grows at its end, so a run starts on the
// last page (asked for with a page number past the end, which XenForo
-// redirects to the last page) and steps back a page at a time. It stops at the
-// first page holding an already-archived post (the incremental case), at the
-// watermark, at page 1, or at a cap — `pages` ("the latest N pages") or
-// `limit` (posts), checked after a whole page so a page is never half-read.
-// The cursor is the next page to read, so a capped or drained run resumes
-// there — after catching up from the last page first, so a run always starts
-// with the newest posts; past the cursor the walk goes on to page 1 (pages
-// shift as posts are deleted, so meeting an archived post there does not end
-// it).
+// redirects to the last page) and steps back a page at a time. Two walks share
+// the pages, each with its own position (lib/forumWalk.ts, posts-state.json's
+// `forum`): the CATCH-UP, from the last page down to the first page holding an
+// archived post at or below the mark, then the HISTORY, from its own page down
+// to page 1 (pages shift as posts are deleted, so meeting an archived post
+// there does not end it). A capped catch-up keeps its own resume point and
+// never moves the history's. A page whose posts are all archived is stepped
+// past without counting against `pages` ("the latest N pages") or `limit`
+// (posts), which are checked after a whole page so a page is never half-read.
+// A full re-walk reads every page from the last to page 1.
//
// PACED, SERIAL, ONE BROWSER. One page at a time with a jittered pause between
// loads (about 10–20 s by default; `pagePauseMs` from the channel), in one
@@ -22,8 +23,10 @@
// A BROWSER CHECK (KiwiFlare's proof of work and the like) is waited out by the
// loader, up to a minute; the profile keeps the clearance for later pages and
// runs. A check that does not clear, a captcha, a login wall, a ban or a
-// 403/429 STOPS the run with a typed failure and keeps the cursor — never a
-// retry loop, never an attempt at a captcha. `needsCookies` is set where
+// 403/429 STOPS the run with a typed failure (`block`) and keeps its
+// positions — never a retry loop here, never an attempt at a captcha. The
+// controller's retry-on-block waits a challenge or a refusal out (minutes, not
+// seconds) and runs again. `needsCookies` is set where
// Connect (a headed window on the same profile) is the way through.
//
// One parser for everything: xenforoParse.ts reads the live page here and the
@@ -32,6 +35,11 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { getPaths } from "../lib/paths";
+import {
+ FORUM_DEFAULT_PAGE_PAUSE_SECONDS,
+ FORUM_MIN_PAGE_PAUSE_SECONDS,
+ type ForumWalkState,
+} from "../lib/forumWalk";
import type { Post, PostMedia } from "../lib/posts";
import {
registerSocialFetcher,
@@ -46,6 +54,7 @@ import {
import {
browserForumLoader,
forumProfileDir,
+ type ForumPageLoad,
type ForumPageLoader,
} from "./forumSession";
import {
@@ -61,6 +70,7 @@ import {
type PostCaptureRecord,
type PostCaptureState,
} from "./postCapture";
+import { fixtureForumLoader, forumFixtureDir } from "./forumFixtureLoader";
import type { PageLike } from "./playwrightRuntime";
import {
classifyForumPage,
@@ -76,9 +86,9 @@ import {
// page, which saves reading page 1 just to learn where the end is.
export const LAST_PAGE_PROBE = 1_000_000;
-export const DEFAULT_PAGE_PAUSE_MS = 12_000;
+export const DEFAULT_PAGE_PAUSE_MS = FORUM_DEFAULT_PAGE_PAUSE_SECONDS * 1000;
// The floor a configured pause is held to.
-export const MIN_PAGE_PAUSE_MS = 5_000;
+export const MIN_PAGE_PAUSE_MS = FORUM_MIN_PAGE_PAUSE_SECONDS * 1000;
// The pause before a load: `base` jittered to [0.85, 1.65) of itself — 12 s
// gives 10.2–19.8 s.
@@ -147,15 +157,27 @@ export type ThreadWalkDeps = {
sleep: (ms: number, signal: AbortSignal) => Promise<void>;
};
+type WalkMode = "catch-up" | "history" | "full";
+
// THE WALK. Pure over its deps: the loader hands back HTML, the parser reads it.
//
-// Two modes. "new": from the last page down, stopping at the first archived
-// post (or the watermark) — what a run is for. "backfill": from a stored
-// cursor down to page 1, where an archived post means nothing (pages shift as
-// posts are deleted). A run with a cursor does both, newest first: it catches
-// up from the last page, then continues the older pages at the cursor — so
-// "the latest N pages" are always the newest, and an unfinished history is
-// never forgotten.
+// Three modes, every one from the thread's last page (lib/forumWalk.ts):
+//
+// "catch-up" — down to the first page holding an archived post at or below
+// the mark (`forumWalk.newestPostId`; with no mark, any archived post),
+// then on to the history walk at `forumWalk.historyPage`, never re-reading
+// the band in between. A capped or interrupted catch-up keeps its place in
+// `catchUpPage`; the next one, meeting the pages it read, jumps there.
+// "history" — down to page 1, where an archived post means nothing (pages
+// shift as posts are deleted). A first run (nothing archived) is one
+// history walk from the last page.
+// "full" — every page from the last to page 1 (`stopAtKnown: false`), every
+// post handed back, archived or not, for the controller to update edits.
+//
+// A page whose posts are all archived never counts against `pages` or
+// `limit` (except in a full re-walk, where every page is the point): the walk
+// steps on down. Caps are checked after a whole page, so a page is never
+// half-read. Every page's checkpoint carries the positions it leaves.
export async function walkXenforoThread(
input: PostFetchInput,
deps: ThreadWalkDeps,
@@ -165,85 +187,116 @@ export async function walkXenforoThread(
if (!thread) {
return { posts: [], complete: false, error: `${input.accountUrl} is not a XenForo thread URL (…/threads/<title>.<id>/).` };
}
- let resumeAt: number | undefined;
- if (input.cursor) {
- resumeAt = Number(input.cursor);
- if (!Number.isInteger(resumeAt) || resumeAt < 1) {
+ // The positions. A caller that derives none (a direct call with an old
+ // cursor) gets its cursor read as the history position.
+ let start: ForumWalkState;
+ if (input.forumWalk) {
+ start = input.forumWalk;
+ } else if (input.cursor) {
+ const n = Number(input.cursor);
+ if (!Number.isInteger(n) || n < 1) {
return { posts: [], complete: false, error: `The stored resume point "${input.cursor}" is not a page number.` };
}
+ start = { historyPage: n };
+ } else {
+ start = {};
+ }
+ const full = input.stopAtKnown === false;
+ // Nothing archived: whatever positions were stored mean nothing.
+ const firstRun = !full && seenIds.size === 0;
+ const w: ForumWalkState = firstRun ? {} : { ...start };
+ if (firstRun && (start.historyPage || start.newestPostId || start.complete)) {
+ onLog?.("Nothing is archived: the stored positions are dropped and the thread is read from its last page.");
}
- const stopAtKnown = input.stopAtKnown ?? true;
- // A full re-walk (stopAtKnown false) reads every page from the end; a
- // cursor means nothing to it.
- if (!stopAtKnown) resumeAt = undefined;
- const watermark = input.since;
+ const markId = w.newestPostId !== undefined ? Number(w.newestPostId) : undefined;
+ let mode: WalkMode = full ? "full" : firstRun ? "history" : "catch-up";
+
const posts: Post[] = [];
const taken = new Set<string>();
+ const metOnPages = new Set<string>();
let returnedCount = 0;
let loads = 0;
- let pagesRead = 0;
+ let pagesCounted = 0;
+ let runTopId: number | undefined;
+ let runLast = 0;
const fetchPage = async (url: string) => {
if (loads++ > 0) await deps.sleep(deps.pauseMs(), signal);
return deps.loader.load(url, signal);
};
+ // The resume point a stop leaves, for the log and for a caller that reads
+ // only the cursor.
+ const resumeCursor = (): string | undefined => {
+ if (w.catchUpPage) return String(w.catchUpPage);
+ if (!w.complete && w.historyPage) return String(w.historyPage);
+ return undefined;
+ };
+ const stop = (extra: Partial<PostFetchResult> = {}): PostFetchResult => {
+ const cursor = resumeCursor();
+ return { posts, complete: false, ...(cursor ? { cursor } : {}), forumWalk: { ...w }, ...extra };
+ };
+ const done = (): PostFetchResult => {
+ const missing = full && w.complete ? [...seenIds].filter((id) => !metOnPages.has(id)) : [];
+ return {
+ posts,
+ complete: !w.catchUpPage && (w.complete === true || w.historyPage === undefined),
+ forumWalk: { ...w },
+ ...(missing.length > 0 ? { notSeen: missing } : {}),
+ };
+ };
+
+ if (mode === "full") onLog?.("A full re-walk: every page from the last to page 1, archived posts re-read for edits.");
- let mode: "new" | "backfill" = "new";
let page = LAST_PAGE_PROBE;
- if (resumeAt) onLog?.(`An earlier run stopped at page ${resumeAt}: catching up from the last page first, then continuing there.`);
- let lastPage: number | undefined;
const visited = new Set<number>();
- const cursorOf = (n: number) => (n === LAST_PAGE_PROBE ? (resumeAt ? String(resumeAt) : undefined) : String(n));
-
try {
for (;;) {
- if (signal.aborted) {
- const cursor = cursorOf(page);
- return { posts, complete: false, ...(cursor ? { cursor } : {}) };
- }
+ if (signal.aborted) return stop();
const url = xenforoPageUrl(thread, page);
- let load;
- try {
- load = await fetchPage(url);
- } catch (err) {
- const cursor = cursorOf(page);
- return { posts, complete: false, ...(cursor ? { cursor } : {}), error: (err as Error).message };
- }
- if (signal.aborted) {
- const cursor = cursorOf(page);
- return { posts, complete: false, ...(cursor ? { cursor } : {}) };
- }
- const block = classifyForumPage(load.html, load.status);
- if (block) {
- const why = forumBlockFailure(block, thread.host);
- const cursor = cursorOf(page);
- onLog?.(`Page ${page === LAST_PAGE_PROBE ? "(last)" : page}: ${block.kind} — ${block.detail}.`);
- return {
- posts,
- complete: false,
- ...(cursor ? { cursor } : {}),
- error: why.error,
- ...(why.needsCookies ? { needsCookies: true } : {}),
- };
+ let load: ForumPageLoad;
+ let parsed: ReturnType<typeof parseXenforoThreadPage>;
+ // A page that parses to no posts is loaded ONCE more before the walk
+ // stops on it: right after a browser check clears, the page standing is
+ // often not yet the thread page (seen live: "Page 2193/2606: 0 post(s)
+ // parsed … (browser check cleared in 12 s)").
+ for (let tries = 1; ; tries++) {
+ try {
+ load = await fetchPage(url);
+ } catch (err) {
+ return stop({ error: (err as Error).message });
+ }
+ if (signal.aborted) return stop();
+ const block = classifyForumPage(load.html, load.status);
+ if (block) {
+ const why = forumBlockFailure(block, thread.host);
+ onLog?.(`Page ${page === LAST_PAGE_PROBE ? "(last)" : page}: ${block.kind} — ${block.detail}.`);
+ return stop({
+ error: why.error,
+ block: block.kind,
+ ...(why.needsCookies ? { needsCookies: true } : {}),
+ });
+ }
+ parsed = parseXenforoThreadPage(load.html, { channelSlug, pageUrl: load.url });
+ if (parsed.posts.length > 0 || tries >= 2) break;
+ onLog?.(
+ `Page ${page === LAST_PAGE_PROBE ? "(last)" : page}: no posts on the first read` +
+ (load.challengeMs !== undefined ? " after the browser check cleared" : "") +
+ "; loading it again.",
+ );
}
- const parsed = parseXenforoThreadPage(load.html, { channelSlug, pageUrl: load.url });
if (visited.has(parsed.page)) {
- return {
- posts,
- complete: false,
- ...(cursorOf(page) ? { cursor: cursorOf(page) } : {}),
- error: `Asked for page ${page} and was shown page ${parsed.page} again; stopped rather than loop.`,
- };
+ return stop({ error: `Asked for page ${page} and was shown page ${parsed.page} again; stopped rather than loop.` });
}
visited.add(parsed.page);
page = parsed.page;
- lastPage = Math.max(lastPage ?? 0, parsed.lastPage);
- pagesRead++;
- // Catching up has reached the pages the backfill has yet to read.
- if (mode === "new" && resumeAt && page <= resumeAt) mode = "backfill";
-
- let sawKnown = false;
- let sawOld = false;
+ // The thread's last page as THIS run sees it (deletions can lower it).
+ runLast = Math.max(runLast, parsed.lastPage);
+ w.newestPage = runLast;
+ w.oldestPageReached = Math.min(w.oldestPageReached ?? page, page);
+
+ let held = 0;
+ let own = 0;
+ let reachedMark = false;
const fresh: Post[] = [];
// Newest first within the page too, so the stops read in time order.
for (const post of [...parsed.posts].reverse()) {
@@ -258,12 +311,18 @@ export async function walkXenforoThread(
}
continue;
}
+ own++;
+ metOnPages.add(post.id);
+ const idNum = Number(post.id);
+ if (runTopId === undefined || idNum > runTopId) runTopId = idNum;
if (seenIds.has(post.id)) {
- if (mode === "new" && stopAtKnown) sawKnown = true;
- continue;
- }
- if (mode === "new" && watermark && post.createdAt <= watermark) {
- sawOld = true;
+ held++;
+ if (mode === "catch-up" && (markId === undefined || idNum <= markId)) reachedMark = true;
+ // A full re-walk hands archived posts back, for their edits.
+ if (mode === "full" && !taken.has(post.id)) {
+ taken.add(post.id);
+ fresh.push(post);
+ }
continue;
}
if (taken.has(post.id)) continue;
@@ -271,54 +330,88 @@ export async function walkXenforoThread(
fresh.push(post);
}
fresh.reverse();
+ const newCount = fresh.filter((p) => !seenIds.has(p.id)).length;
+ const allHeld = mode !== "full" && own > 0 && held === own && newCount === 0;
onLog?.(
- `Page ${page}/${lastPage}: ${parsed.posts.length} post(s) parsed, ${fresh.length} new` +
+ `Page ${page}/${parsed.lastPage}: ${parsed.posts.length} post(s) parsed, ${newCount} new` +
(load.challengeMs !== undefined ? ` (browser check cleared in ${Math.round(load.challengeMs / 1000)} s)` : "") +
- (sawKnown ? ", reached already-archived posts" : "") +
- (sawOld ? ", reached the watermark" : "") +
+ (reachedMark ? ", reached already-archived posts" : "") +
".",
);
if (parsed.posts.length === 0 && page > 1) {
// A thread page with no posts in it is not a page to step past
// silently: it is most likely markup this parser does not know.
- return {
- posts,
- complete: false,
- cursor: String(page),
- error: `Page ${page} of the thread parsed to no posts; stopped rather than walking on.`,
- };
+ return stop({ error: `Page ${page} of the thread parsed to no posts; stopped rather than walking on.` });
+ }
+ if (!allHeld) {
+ pagesCounted++;
+ returnedCount += newCount;
}
let next = page - 1;
- if (sawKnown || sawOld) {
- if (!resumeAt) {
- if (input.onCheckpoint && fresh.length > 0) await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)) });
- else posts.push(...fresh);
- return { posts, complete: true };
+ let finished = false;
+ if (mode === "catch-up") {
+ if (reachedMark || next < 1) {
+ // Caught up: every post from here to the top is held.
+ if (runTopId !== undefined) w.newestPostId = String(Math.max(runTopId, markId ?? 0));
+ delete w.catchUpPage;
+ if (next < 1) {
+ w.complete = true;
+ delete w.historyPage;
+ }
+ if (w.complete || w.historyPage === undefined) {
+ onLog?.(`Caught up to page ${w.newestPage}; ${w.complete ? "history complete" : "no older pages owed"}.`);
+ finished = true;
+ } else {
+ mode = "history";
+ next = Math.min(w.historyPage, next);
+ onLog?.(`Caught up to page ${w.newestPage}; history resumes at page ${next}.`);
+ }
+ } else if (allHeld) {
+ // The pages an earlier, unfinished catch-up read: jump below them.
+ if (w.catchUpPage && w.catchUpPage < next) {
+ onLog?.(`Page ${page}: all held — an earlier catch-up read down to page ${w.catchUpPage + 1}; continuing there.`);
+ next = w.catchUpPage;
+ } else {
+ onLog?.(`Page ${page}: all held, skipping on.`);
+ }
+ }
+ if (!finished && mode === "catch-up") w.catchUpPage = next;
+ } else if (mode === "history") {
+ if (runTopId !== undefined && firstRun) w.newestPostId = String(runTopId);
+ if (allHeld) onLog?.(`Page ${page}: all held, skipping on.`);
+ } else {
+ // A full re-walk: everything from here to the top is now read.
+ if (runTopId !== undefined) w.newestPostId = String(Math.max(runTopId, markId ?? 0));
+ delete w.catchUpPage;
+ }
+ if (mode === "history" || mode === "full") {
+ if (next < 1) {
+ w.complete = true;
+ delete w.historyPage;
+ finished = true;
+ } else if (!w.complete) {
+ w.historyPage = w.historyPage === undefined || mode === "history" ? next : Math.min(w.historyPage, next);
}
- // Caught up: on to the older pages an earlier run left.
- mode = "backfill";
- next = Math.min(resumeAt, next);
- onLog?.(`Caught up with the archive; continuing the older pages at page ${next}.`);
}
- returnedCount += fresh.length;
- if (input.onCheckpoint && fresh.length > 0) {
- await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)) });
+
+ if (input.onCheckpoint) {
+ await input.onCheckpoint({ posts: fresh, cursor: String(Math.max(1, next)), forumWalk: { ...w } });
} else {
posts.push(...fresh);
}
- if (next < 1) return { posts, complete: true };
- if (input.pages && pagesRead >= input.pages) {
- onLog?.(`Read ${pagesRead} page(s), the cap for this run; the next run continues at page ${next}.`);
- return { posts, complete: false, cursor: String(next) };
+ if (finished) return done();
+ if (input.pages && pagesCounted >= input.pages && !allHeld) {
+ onLog?.(`Read ${pagesCounted} page(s), the cap for this run; the next run continues at page ${next}.`);
+ return stop();
}
- if (input.limit && returnedCount >= input.limit) {
- return { posts, complete: false, cursor: String(next) };
+ if (input.limit && returnedCount >= input.limit && !allHeld) {
+ return stop();
}
if (input.drain?.aborted) {
onLog?.(`Drained; the next run continues at page ${next}.`);
- return { posts, complete: false, cursor: String(next), drained: true };
+ return stop({ drained: true });
}
page = next;
}
@@ -659,6 +752,11 @@ export const xenforoFetcher: SocialFetcher = {
async fetch(input: PostFetchInput): Promise<PostFetchResult> {
const thread = threadOrThrow(input.accountUrl);
+ // The e2e suite's saved pages (forumFixtureLoader.ts): no browser, no pause.
+ const fixtures = forumFixtureDir();
+ if (fixtures) {
+ return walkXenforoThread(input, { loader: fixtureForumLoader(fixtures, thread), pauseMs: () => 0, sleep: async () => {} });
+ }
const loader = browserForumLoader(forumProfileDir(getPaths(), thread.host), { onLog: input.onLog });
return walkXenforoThread(input, {
loader,
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. |
| `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. |
| `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. |
-| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. |
+| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane E): Save Page Now — `POST /save` (the fake keys `FAKE_SPN_ACCESS`/`FAKE_SPN_SECRET` in `Authorization: LOW …`, else 401; `spn.busyTimes` 429s; `spn.refuseUrls` answered `error:blocked-url`) and `GET /save/status/<job>` (`spn.pendingPolls` pending, then success at `SPN_CAPTURE_TS`, or `spn.failUrls` → `error:not-found`); a saved page is then served raw like a page capture (`spn.pages[url]` or a synthetic page); `wb.spnForms`, `wb.spnCaptures`. |
| `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. |
| `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. |
| `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. |
@@ -32,6 +32,7 @@ transcript, channel or person goes in these fixtures, ever.
| `mirrors/mirrorCorpus.mjs` | Release 31 lane D: a synthetic creator (`synth-streamer`, "youtube": a public, a deleted and a private stream, removed shorts in and out of the window), its Rumble twin (`synth-streamer-rumble`: data dirs are URL slugs, ids embed ids) and a VOD mirror (`synth-vod-archive`, "odysee", titles `[VOD] SynthStreamer - MM/DD/YYYY - <topic>`, config `recordedDate` + `mirror.of`). `MIRROR_RECORDS` / `CREATOR_RECORDS` / `RUMBLE_RECORDS` are the matcher's input; `writeMirrorCorpus(channelsDir)` writes the three channels to disk (config, metadata, availability); `EXPECTED` is what a mirror scan finds (each status once or more, the removed uploads the mirror holds). |
| `clips/reactionStream.mjs` | Release 35: a synthetic reaction stream (`reactionStream()`: a host interjecting over a narrated video — turns, words, cues, laugh windows; `reactionAudio()` its sound; `writeReactionCorpus(dir, o)` a channel on disk). Release 36: `twoVideoStream()` (an intro, video A by speaker 1, the host between, video B by speaker 2 with a pause and a stray cluster, an outro — what auto-scope reads), `reactionChat(o)` (a chat replay: a steady trickle and a burst of laugh tokens `lag` s after each laugh, `chatOnly` bursts), and `writeReactionCorpus`'s `two`, `chat` (live_chat.cues.json) and `meta` (keys into metadata.info.json) options. The "narration" is numbered filler words. |
| `clips/reactionProject.mjs` | Release 36 lane D: a synthetic reactions PROJECT over `reactionStream()` — `reactionProject()` (reactions.json with a host and a subject, five moments of every kind, five proposals: three in the cut, two not; words.json; a video.manifest.json of the three clips), `writeReactionProject(dir, {note})` (them on disk, and a notes.json with an open comment on a clip), `labelAnswer(ids)` (a model's answer for the clip finder's labels, in `SUGGEST_ANSWER_SCHEMA`'s shape). |
+| `clips/assistProject.mjs` | Release 38 lane E: the video assistant's project — `assistManifest()` (the reactions project's three clips plus `r004`, a clip with a wide window, under a look: a 0.22 s blur slide, room at both edges, −16 LUFS, no header or footer), `assistDeckManifest()` (the same under the deck with the glitch on), `writeAssistProject(dir, {deck, note})` (on disk; `note`: a note on the whole project, `ASSIST_NOTE`), and `ASSIST_REQUESTS` — 29 requests in words, what a model answers (`{op, id, key, value}`) and the diff lines kept and the reasons refused (`answerOf(row)` is the answer in the schema's shape). |
| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. |
diff --git a/common/testing/clips/assistProject.d.mts b/common/testing/clips/assistProject.d.mts
@@ -0,0 +1,14 @@
+// Types for ./assistProject.mjs (release 38 lane E): the video assistant's synthetic project and request table.
+export const ASSIST_NOTE: string;
+export const ASSIST_AT: string;
+export const ASSIST_LOOK: Readonly<Record<string, unknown>>;
+
+export type AssistManifest = { render: Record<string, any>; timeline: Record<string, any>[] } & Record<string, any>;
+export function assistManifest(): AssistManifest;
+export function assistDeckManifest(): AssistManifest;
+
+export type AssistModelOp = { op: string; id: string; key: string; value: unknown };
+export type AssistRequestRow = { request: string; scope?: "look" | "clips" | "fx" | "all"; deck?: boolean; answer: AssistModelOp[]; diff: string[]; refused: RegExp[] };
+export const ASSIST_REQUESTS: readonly AssistRequestRow[];
+export function answerOf(row: AssistRequestRow): { ops: AssistModelOp[]; reply: string };
+export function writeAssistProject(dir: string, o?: { deck?: boolean; note?: string | null }): { dir: string; manifest: AssistManifest };
diff --git a/common/testing/clips/assistProject.mjs b/common/testing/clips/assistProject.mjs
@@ -0,0 +1,103 @@
+// A synthetic video project for the video assistant (release 38 lane E): the
+// reactions project's cut (reactionProject.mjs) with a look on it -- a quick
+// blur slide, room at both edges, the loudness evened -- and a fourth clip
+// with a wide window; a deck variant with an effect on; and the REQUEST TABLE,
+// what a person asks for in words, what a model answers (in the ops' one
+// shape, `{op, id, key, value}`) and what the checks make of it.
+//
+// Synthetic, like everything in the kit: no real project, recording or person.
+
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { reactionProject } from "./reactionProject.mjs";
+
+export const ASSIST_NOTE = "n_assist0001";
+export const ASSIST_AT = "2026-10-20T00:00:00.000Z";
+
+/** The look the plain cut starts with. */
+export const ASSIST_LOOK = Object.freeze({
+ headerHeight: 0,
+ footerHeight: 0,
+ transition: 0.22,
+ transitionStyle: "blurslide",
+ loudness: Object.freeze({ target: -16 }),
+ room: Object.freeze({ tail: true, head: true }),
+});
+
+/** The plain cut (no deck): r001–r003 from the reactions project, and r004, a clip whose window is wide. */
+export function assistManifest() {
+ const { manifest } = reactionProject();
+ const m = structuredClone(manifest);
+ m.render = { width: 1920, height: 1080, fps: 30, ...structuredClone(ASSIST_LOOK) };
+ m.timeline.push({ type: "clip", id: "r004", channel: m.timeline[0].channel, video: m.timeline[0].video, start: 500, end: 530, cutStart: 510, cutEnd: 520, quote: "" });
+ return m;
+}
+
+/** The same cut under a deck, with the glitch on. */
+export function assistDeckManifest() {
+ const m = assistManifest();
+ const { captions: _c, ...render } = m.render;
+ m.render = { ...render, transitionStyle: "fade", chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, fx: { glitch: {} } } };
+ return m;
+}
+
+const op = (o, id, key, value) => ({ op: o, id, key, value });
+
+/**
+ * The request table: `{ request, scope?, deck?, answer, diff, refused }` --
+ * `answer` the model's `{ops, reply}`, `diff` the diff lines kept (in order),
+ * `refused` a pattern each refusal's reason matches (in order).
+ */
+export const ASSIST_REQUESTS = Object.freeze([
+ { request: "make the joins 0.15 s", answer: [op("look", "", "transition", 0.15)], diff: ["join 0.22 s → 0.15 s"], refused: [] },
+ { request: "quicker joins", answer: [op("look", "", "transition", 0.12)], diff: ["join 0.22 s → 0.12 s"], refused: [] },
+ { request: "no QR", answer: [op("look", "", "qr", false)], diff: ["QR code on → off"], refused: [] },
+ { request: "louder", answer: [op("look", "", "loudness", -14)], diff: ["loudness -16 LUFS → -14 LUFS"], refused: [] },
+ { request: "smear less", answer: [op("slide", "", "blur", 0.3)], diff: ["smear 0.5 → 0.3"], refused: [] },
+ { request: "keep 2 s after the last word", answer: [op("room", "", "maxS", 2)], diff: ["room tail up to 2.5 s → 2 s"], refused: [] },
+ { request: "cut the first 3 seconds of r002", scope: "clips", answer: [op("clip_edges", "r002", "start", 91)], diff: ["r002 in 88 s → 91 s"], refused: [] },
+ { request: "make the joins 5 seconds long", answer: [op("look", "", "transition", 5)], diff: [], refused: [/render\.transition must be a number of seconds from 0 \(a hard cut\) to 3/] },
+ { request: "hard cuts, no joins", answer: [op("look", "", "transition", 0)], diff: ["join 0.22 s → a hard cut"], refused: [] },
+ { request: "dip to black between clips", answer: [op("look", "", "transitionStyle", "fadeblack")], diff: ["join style blur slide → dip to black"], refused: [] },
+ { request: "the slide travels too far", answer: [op("slide", "", "travel", 0.04)], diff: ["slide travel 0.08 → 0.04"], refused: [] },
+ { request: "no grain on the slide", answer: [op("slide", "", "grain", 0)], diff: ["grain 2 → 0"], refused: [] },
+ { request: "turn on speaker captions", answer: [op("look", "", "captions", true)], diff: ["speaker captions off → on"], refused: [] },
+ { request: "even out the volume at -18", answer: [op("look", "", "loudness", -18)], diff: ["loudness -16 LUFS → -18 LUFS"], refused: [] },
+ { request: "leave the sound as recorded", answer: [op("look", "", "loudness", null)], diff: ["loudness -16 LUFS → as recorded"], refused: [] },
+ { request: "no muted lead-in", answer: [op("room", "", "head", false)], diff: ["room head on → off"], refused: [] },
+ { request: "no room on r003", scope: "clips", answer: [op("clip_room", "r003", "off", true)], diff: ["r003 room the cut's (tail + head) → none"], refused: [] },
+ { request: "end r001 a second later", scope: "clips", answer: [op("clip_edges", "r001", "end", 48)], diff: ["r001 out 47 s → 48 s"], refused: [] },
+ { request: "start r001 at 30", scope: "clips", answer: [op("clip_edges", "r001", "start", 30)], diff: [], refused: [/outside the clip's source window \(38\.5–48\.5 s\)/] },
+ { request: "tighten r004 to start at 516", scope: "clips", answer: [op("clip_edges", "r004", "start", 516)], diff: [], refused: [/moves an edge 6 s; one op moves an edge at most 3 s/] },
+ { request: "cut the first 6 seconds of r004", scope: "clips", answer: [op("clip_edges", "r004", "start", 516)], diff: ["r004 in 510 s → 516 s"], refused: [] },
+ { request: "a bigger header", answer: [op("look", "", "headerHeight", 56)], diff: ["header off → 56 px"], refused: [] },
+ { request: "make the joins 0.15 s with less smear", answer: [op("look", "", "transition", 0.15), op("slide", "", "blur", 0.3)], diff: ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"], refused: [] },
+ { request: "tighten r002 a little", scope: "look", answer: [op("clip_edges", "r002", "end", 98)], diff: [], refused: [/a clip_edges op is outside what was asked about \(look\)/] },
+ { request: "add a spinning logo", answer: [{ op: "html", id: "", key: "", value: "<div>" }], diff: [], refused: [/no op "html"/] },
+ { request: "glitch the deck", scope: "fx", answer: [op("fx", "deck", "motion.in", 0.6)], diff: [], refused: [/this cut does not draw deck/] },
+ { request: "slow the deck's slide in", deck: true, scope: "fx", answer: [op("fx", "deck", "motion.in", 0.6)], diff: ["the deck's slide in 0.45 s → 0.6 s"], refused: [] },
+ { request: "a longer glitch, 3 seconds", deck: true, scope: "fx", answer: [op("fx", "fx.glitch", "seconds", 3)], diff: [], refused: [/the glitch's length is seconds from 0\.2 to 1\.5/] },
+ { request: "a taller deck", deck: true, scope: "fx", answer: [op("fx", "deck", "height", 300)], diff: [], refused: [/deck has no param "height"/] },
+]);
+
+/** The model's answer for a row: `{ops, reply}` in the schema's shape. */
+export const answerOf = (row) => ({ ops: row.answer, reply: "" });
+
+/**
+ * The project on disk: its manifest (plain, or the deck variant), and with
+ * `note` a notes.json holding an open comment on the whole project.
+ * @param {string} dir
+ * @param {{ deck?: boolean, note?: string | null }} [o]
+ */
+export function writeAssistProject(dir, { deck = false, note = null } = {}) {
+ const manifest = deck ? assistDeckManifest() : assistManifest();
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ if (note) {
+ writeFileSync(
+ path.join(dir, "notes.json"),
+ `${JSON.stringify({ version: 1, subject: { kind: "video-project", project: path.basename(dir) }, notes: [{ id: ASSIST_NOTE, status: "open", author: "operator", text: note, at: ASSIST_AT, updatedAt: ASSIST_AT, anchor: { kind: "whole" }, replies: [] }] }, null, 1)}\n`,
+ );
+ }
+ return { dir, manifest };
+}
diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts
@@ -27,9 +27,17 @@ export const PAGE_JUMP_URL: string;
export const PAGE_JUMP_TS: string;
export const VIDEOS: string[];
+// Release 37 (lane E): Save Page Now.
+export const FAKE_SPN_ACCESS: string;
+export const FAKE_SPN_SECRET: string;
+export const SPN_CAPTURE_TS: string;
+
export type FakeWayback = {
base: string;
- requests: { path: string; at: number }[];
+ requests: { path: string; at: number; method?: string }[];
+ // (release 37 lane E) the SPN forms posted, and the captures SPN made.
+ spnForms: Record<string, string>[];
+ spnCaptures: FakePageCapture[];
fetch(url: string | URL, init?: RequestInit): Promise<Response>;
close(): Promise<void>;
};
@@ -46,6 +54,19 @@ export function startFakeWayback(opts?: {
pageCaptures?: FakePageCapture[];
// (release 37 S2) the Nth scan listing request and every one after answer 503.
scanRefuseFrom?: number;
+ // (release 37 lane E) Save Page Now: the keys it takes, 429s first, polls
+ // answered pending, URLs whose capture fails or is refused, bodies by URL,
+ // the capture timestamp.
+ spn?: {
+ access?: string;
+ secret?: string;
+ busyTimes?: number;
+ pendingPolls?: number;
+ failUrls?: string[];
+ refuseUrls?: string[];
+ pages?: Record<string, string>;
+ timestamp?: string;
+ };
}): Promise<FakeWayback>;
// (release 37 S2) the scan listing: a blog with posts, assets, a 404, a second host.
diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs
@@ -174,6 +174,88 @@ function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) {
return true;
}
+// ─── Release 37 (lane E): Save Page Now (SPN2) ──────────────────────────────
+//
+// POST /save url=<page>&capture_outlinks=0, Authorization
+// `LOW <access>:<secret>` → {url, job_id}; a wrong
+// or missing key → 401; opts.spn.busyTimes → 429
+// (Retry-After: 1) first; a url in opts.spn.refuseUrls
+// → 200 {status: "error", status_ext: "error:blocked-url"}
+// GET /save/status/<job_id> {status: "pending"} for opts.spn.pendingPolls polls
+// (default 1), then {status: "success", timestamp,
+// original_url} — and the capture is served raw like a
+// page capture from then on (opts.spn.pages[url] or a
+// synthetic page) — or, for a url in opts.spn.failUrls,
+// {status: "error", status_ext: "error:not-found"}
+// The keys are FAKE_SPN_ACCESS / FAKE_SPN_SECRET; nothing real.
+export const FAKE_SPN_ACCESS = "FAKEACCESS0001";
+export const FAKE_SPN_SECRET = "FAKESECRET0001";
+export const SPN_CAPTURE_TS = "20261020120000";
+
+const spnPageHtml = (url) => `<!doctype html><html lang="en"><head><meta charset="utf-8">
+<title>A page saved now</title></head><body>
+<nav><a href="/">Home</a></nav>
+<main><h1>A page saved now</h1>
+<p>This synthetic page stands for ${url}, captured by the fake Save Page Now while it was still up.</p>
+<p>It says what the page said on the day it was saved, which is the point of saving it.</p></main>
+<footer>Footer</footer></body></html>`;
+
+function readBody(req) {
+ return new Promise((resolve) => {
+ const chunks = [];
+ req.on("data", (c) => chunks.push(c));
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
+ });
+}
+
+// The SPN routes; true when the request was one of them.
+function spnAnswer(spn, req, u, send) {
+ if (u.pathname === "/save" && req.method === "POST") {
+ void readBody(req).then((body) => {
+ if (req.headers.authorization !== `LOW ${spn.access}:${spn.secret}`) {
+ return send(401, "application/json", JSON.stringify({ message: "You need to be logged in to use Save Page Now." }));
+ }
+ if (spn.busy > 0) {
+ spn.busy--;
+ return send(429, "application/json", JSON.stringify({ message: "You have already reached the limit of active sessions." }), { "retry-after": "1" });
+ }
+ const url = new URLSearchParams(body).get("url") ?? "";
+ spn.forms.push(Object.fromEntries(new URLSearchParams(body)));
+ if (spn.refuseUrls.includes(url)) {
+ return send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "This URL is in the Save Page Now service block list." }));
+ }
+ const jobId = `spn2-fake-${++spn.seq}`;
+ spn.jobs.set(jobId, { url, polls: 0 });
+ return send(200, "application/json", JSON.stringify({ url, job_id: jobId }));
+ });
+ return true;
+ }
+ const st = /^\/save\/status\/([^/]+)$/.exec(u.pathname);
+ if (st && req.method === "GET") {
+ const job = spn.jobs.get(decodeURIComponent(st[1]));
+ if (!job) {
+ send(404, "application/json", JSON.stringify({ status: "error", message: "Job not found." }));
+ return true;
+ }
+ job.polls++;
+ if (job.polls <= spn.pendingPolls) {
+ send(200, "application/json", JSON.stringify({ status: "pending", job_id: st[1] }));
+ return true;
+ }
+ if (spn.failUrls.includes(job.url)) {
+ send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:not-found", message: "Server returned a 404 for this page." }));
+ return true;
+ }
+ if (!spn.captured.some((c) => c.original === job.url)) {
+ const page = spn.pages[job.url];
+ spn.captured.push({ original: job.url, timestamp: spn.timestamp, statuscode: "200", mimetype: "text/html", body: () => page ?? spnPageHtml(job.url) });
+ }
+ send(200, "application/json", JSON.stringify({ status: "success", job_id: st[1], timestamp: spn.timestamp, original_url: job.url, duration_sec: 3 }));
+ return true;
+ }
+ return false;
+}
+
// YouTube ids whose video (not only its page) the fake archive holds.
export const VIDEOS = ["gone-video-05"];
@@ -189,13 +271,32 @@ export async function startFakeWayback(opts = {}) {
let busy = opts.busyTimes ?? 0;
let down = opts.downTimes ?? 0;
let scanRequests = 0;
+ // Release 37 (lane E): Save Page Now's state.
+ const spn = {
+ access: opts.spn?.access ?? FAKE_SPN_ACCESS,
+ secret: opts.spn?.secret ?? FAKE_SPN_SECRET,
+ busy: opts.spn?.busyTimes ?? 0,
+ pendingPolls: opts.spn?.pendingPolls ?? 1,
+ failUrls: opts.spn?.failUrls ?? [],
+ refuseUrls: opts.spn?.refuseUrls ?? [],
+ pages: opts.spn?.pages ?? {},
+ timestamp: opts.spn?.timestamp ?? SPN_CAPTURE_TS,
+ jobs: new Map(),
+ seq: 0,
+ forms: [],
+ captured: [],
+ };
const server = http.createServer((req, res) => {
const u = new URL(req.url ?? "/", "http://fake");
- requests.push({ path: u.pathname + u.search, at: Date.now() });
+ requests.push({ path: u.pathname + u.search, at: Date.now(), method: req.method });
const send = (status, type, body, headers = {}) => {
res.writeHead(status, { "content-type": type, ...headers });
res.end(body);
};
+ // Release 37 (lane E): Save Page Now, and the captures it made (raw).
+ if (spnAnswer(spn, req, u, send)) return;
+ const spc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search);
+ if (spc && pageCaptureAnswer(spn.captured, spc[1], spc[2] ?? "", spc[3], send, res)) return;
if (u.pathname === "/cdx/search/cdx") {
if (busy > 0) {
busy--;
@@ -264,6 +365,9 @@ export async function startFakeWayback(opts = {}) {
return {
base,
requests,
+ // Release 37 (lane E): the SPN forms posted (no headers), and the captures made.
+ spnForms: spn.forms,
+ spnCaptures: spn.captured,
fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/web\.archive\.org/, base), init),
close: () => new Promise((r) => server.close(() => r())),
};
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,6 +2,11 @@
## [Unreleased]
- **Save an X search across accounts, and see who keeps saying it.** Paste an X search page's URL (as copied from X's search box) into the New channel form, or choose **X search** as the platform and type a query: it makes an X search channel whose records are the matching posts from any account. The query is X's own — OR, "quotes", -term, from:, to:, @name, url:, filter:, lang: — and its dates are the channel's **Since** and **Until** (a pasted URL's since:/until: are moved there; typed into the query they are refused with a sentence). Fetch posts searches backwards a window at a time (3 months, or your **Window**), newest first, at the older walk's pace and with its X login; a run cut short resumes where it stopped, later fetches search only the new days, and a new query starts afresh. The channel page's **Leads** lists the accounts by how many matching posts they made, with their first and last day and a sample: **Archive this account** creates `<handle>-x` on no site and starts its fetch, **Never archive** hides the account (Restore brings it back), and an account an X channel already archives says so. An X search channel is never put on a site. From a terminal: `pnpm ops create-channel` with the search URL, `pnpm ops fetch-posts`, `pnpm ops get channel <slug> --leads` and `pnpm ops x-search-lead`; the MCP has `x_search_leads`. Nothing calls a model. Needs a restart of the editor.
+- **A forum thread's fetch resumes where it stopped instead of reading the thread again.** A forum channel now keeps two places: how far it has caught up with the newest posts, and where its walk back through the older pages stands. **Fetch posts** reads from the last page down to the newest post it already holds, then jumps straight to the older pages it has yet to read — a run capped at a few pages ("Latest N pages") no longer loses the older place, and a page whose posts are all held is stepped past without counting against the cap. Pages that shifted because posts were deleted are still read without a gap. **Full re-walk** (it replaces "Re-fetch full history" on a forum channel) asks first, with the page count and how long it takes at the channel's pace, then reads every page from the last to page 1: edited posts are updated, and posts no page shows any more are counted in the log and kept. The panel's status line says where both stand — "pages read 2338–2600 of 2600 · history to page 1 remaining: 2337 pages (~9.7 h)". The older place is checked against the pages the archive holds at every run, so a channel whose place was overwritten by the old single resume point heals on its next fetch. A page that reads empty — as one can just after a browser check clears — is loaded once more before the fetch stops on it. **Retry after a block** (the Forum session section) makes Fetch posts wait out a browser check that will not clear or a refused page — 30 minutes, then try again, up to 12 tries, say — and never retries a captcha or a login; `pnpm ops fetch-posts` takes `"retryOnBlock": {"minutes": 30, "max": 12}` (or `true` for the saved setting). Needs a restart of the editor.
+- **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor.
+- **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten.
+- **Ask for a small change to a report video in words, on the local model, and apply it with one click.** The Build tab's Look panel and the clip editor's side column have an **Ask** box: "make the joins 0.15 s with less smear", "louder", "no QR", "keep 2 s after the last word", "cut the first 3 seconds of r014". The assistant answers with proposed edits shown as a list of changes ("join 0.22 s → 0.15 s", "smear 0.5 → 0.3"), each with **Apply**, plus **Apply all** and **Dismiss**; nothing changes until you apply, and each edit is checked again and written by the same code the Look panel and the clip editor use. A change it cannot make, or a value out of range, is listed with the reason instead. It runs on the local model by default (in every preset but `api`), so it works without Claude Code; it waits while a transcription has the GPU, and the box says so. A note on the whole project can be asked too: the reply comes back on the note with an **Apply all**. **Preview join** renders the first few joins in the saved look and plays them in place. It can change the look, the blur slide, the room at the clips' edges, a clip's edges or room, and a set of declared deck and effect settings (`pnpm ops report-draft` task `video-assist`; the MCP's `generate`).
+- **The Look panel has the blur slide's and the room's numbers.** With the join set to blur slide, **Travel**, **Smear** and **Grain** are fields; with room at the clips' edges on, **Tail up to, s** (how far the sound may run past a cut) and **Silence gap, s**. Video revisions of an article can now change the look, the slide and the room too.
- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor.
- **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on.
- **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model.
diff --git a/editor/app/api/ops/_videoAssist.test.ts b/editor/app/api/ops/_videoAssist.test.ts
@@ -0,0 +1,160 @@
+import { after, before, 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";
+import { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";
+import { ASSIST_NOTE, writeAssistProject } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs";
+import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
+import { planVideoAssistJob, type AssistNoteReply, type VideoAssistJobDeps } from "yt-dlp-transcript-common/controller/videoAssist";
+import { readAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
+import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_videoAssist.test.ts"
+//
+// The `report-draft` task `video-assist` (release 38 lane E) end to end in
+// this process: the controller the ops route adapts, a synthetic video
+// project in a temp dir (common/testing/clips/assistProject.mjs), the fake
+// Anthropic and ollama servers, a temp jobs dir and usage ledger.
+
+let tmp: string;
+let api: FakeAnthropic;
+let ol: FakeOllama;
+let paths: Paths;
+let gen: GenerationSettings;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "video-assist-"));
+ api = await startFakeAnthropic();
+ ol = await startFakeOllama();
+ const keyFile = path.join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ transcriptsDir: path.join(tmp, "transcripts"),
+ channelsDir: path.join(tmp, "transcripts", "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: ol.url,
+ } as Paths;
+ gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 }, routes: { ...GENERATION_PRESETS.balanced } });
+});
+
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}, more: Partial<VideoAssistJobDeps> = {}) =>
+ ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }), ...more }) as ReportDraftDeps & VideoAssistJobDeps;
+
+const out = (o: Awaited<ReturnType<typeof enqueueReportDraft>>) => o.result as { ok: boolean; error: string };
+
+async function finished(o: Awaited<ReturnType<typeof enqueueReportDraft>>) {
+ assert.ok(o.result.ok, (o.result as { error?: string }).error);
+ const job = getRegistry().get(o.result.jobId)!;
+ void o.result.stream.cancel();
+ const done = await o.result.done;
+ return { job, done, log: await readFile(job.logPath, "utf8") };
+}
+
+test("the body: a project and a request (or a note), a scope; never an article", () => {
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", request: "x" }), /"project" is the video project's absolute directory/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p" }), /needs its "request"/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", note: "n_abcd1234" }), /not both/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", article: "a", project: "/p", request: "x" }), /not an article/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", scope: "everything" }), /"scope" is look, clips, fx or all/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", proposals: ["p1"] }), /a clips-suggest job's/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", request: "x" }), /"request" is a video-assist job's/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", iteration: 2 }), /takes no iteration/);
+ assert.throws(() => parseReportDraftBody({ task: "video-assist", project: "/p", request: "x", answers: { ops: [] }, model: "m" }), /no "model"/);
+ assert.deepEqual(parseReportDraftBody({ task: "video-assist", project: "/p", request: " quicker joins ", scope: "look", dryRun: true }), {
+ task: "video-assist",
+ article: "",
+ project: "/p",
+ request: "quicker joins",
+ scope: "look",
+ dryRun: true,
+ });
+});
+
+test("on the local model (the default route): draft:local through the arbiter, one schema-bound ask, proposals written, ollama unloaded, no ledger row", async () => {
+ const dir = path.join(tmp, "local");
+ writeAssistProject(dir);
+ assert.equal(gen.routes["video-assist"], "local");
+ ol.push(jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.15 }, { op: "slide", id: "", key: "blur", value: 0.3 }], reply: "Quicker, less smear." }));
+ const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "make the joins 0.15 s with less smear" }, deps()));
+ assert.equal(done.status, "done", log);
+ assert.equal(job.queueKey, "draft:local");
+ assert.match(log, /through the GPU arbiter: it waits for a transcription/);
+ assert.match(log, /proposed: join 0\.22 s → 0\.15 s/);
+ assert.match(log, /unloaded qwen3:8b from ollama/);
+ assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"video-assist","project":"[^"]+local","status":"done","summary":"2 edits proposed \(join 0\.22 s → 0\.15 s; smear 0\.5 → 0\.3\) on qwen3:8b"/);
+ const { doc } = await readAssistProposals(dir);
+ assert.deepEqual(doc!.diff, ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"]);
+ assert.ok(ol.unloads.includes("qwen3:8b"));
+ assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0);
+ const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.render.transition, 0.22, "nothing applied");
+});
+
+test("on the API: draft:api, the narration cap, a ledger row as task video-assist", async () => {
+ const dir = path.join(tmp, "api");
+ writeAssistProject(dir);
+ api.push(toolTurn("answer", { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." }));
+ const { job, done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps({ routes: { ...gen.routes, "video-assist": "api" } })));
+ assert.equal(done.status, "done", log);
+ assert.equal(job.queueKey, "draft:api");
+ assert.match(log, /the Claude API, cap \$1\)/);
+ const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id);
+ assert.deepEqual(rows.map((r) => [r.task, r.model, r.article, r.iteration]), [["video-assist", "claude-sonnet-5-5", "", 0]]);
+ assert.deepEqual((await readAssistProposals(dir)).doc!.diff, ["QR code on → off"]);
+});
+
+test("the code route: refused with no answer; the plan is the request; a session's answer runs on no model", async () => {
+ const dir = path.join(tmp, "code");
+ writeAssistProject(dir);
+ const code = { routes: { ...gen.routes, "video-assist": "code" as const } };
+ const refused = await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR" }, deps(code));
+ assert.ok(!out(refused).ok && /routed to Claude Code/.test(out(refused).error));
+ const plan = await planVideoAssistJob(parseReportDraftBody({ task: "video-assist", project: dir, request: "no QR", dryRun: true }), deps(code));
+ assert.equal(plan.provider, "code");
+ assert.match(plan.request.user, /THE REQUEST:\nno QR/);
+ assert.match(plan.request.user, /- qr = true/);
+ const asked = api.requests.length + ol.requests.length;
+ const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, request: "no QR", answers: { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "" } }, deps(code)));
+ assert.equal(done.status, "done", log);
+ assert.equal(api.requests.length + ol.requests.length, asked);
+ assert.equal((await readAssistProposals(dir)).doc!.model, "claude-code");
+});
+
+test("Ask on a note on the whole project: its text is the request; the reply posted as the agent's with an assist proposal; nothing applied", async () => {
+ const dir = path.join(tmp, "note");
+ writeAssistProject(dir, { note: "quicker joins please" });
+ const nowhere = await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { umtoolUrl: null, workerToken: "t" }));
+ assert.ok(!out(nowhere).ok && /UMTOOL_URL is not set/.test(out(nowhere).error));
+ const missing = await enqueueReportDraft({ task: "video-assist", project: dir, note: "n_absent00" }, deps({}, { umtoolUrl: "http://x", workerToken: "t" }));
+ assert.ok(!out(missing).ok && /no note n_absent00/.test(out(missing).error));
+ let prompt = "";
+ ol.push((body: { messages: { role: string; content: string }[] }) => {
+ prompt = body.messages.find((m) => m.role === "user")!.content;
+ return jsonReply({ ops: [{ op: "look", id: "", key: "transition", value: 0.12 }], reply: "Joins at 0.12 s." });
+ });
+ const posted: AssistNoteReply[] = [];
+ const { done, log } = await finished(await enqueueReportDraft({ task: "video-assist", project: dir, note: ASSIST_NOTE }, deps({}, { postReply: async (r) => void posted.push(r) })));
+ assert.equal(done.status, "done", log);
+ assert.match(prompt, /THE REQUEST:\nquicker joins please/);
+ const { doc } = await readAssistProposals(dir);
+ assert.equal(doc!.note, ASSIST_NOTE);
+ assert.deepEqual(posted, [
+ { project: dir, note: ASSIST_NOTE, text: "Joins at 0.12 s.\nProposed 1 edit — Apply below or in the Build tab's Look panel:\n• join 0.22 s → 0.12 s", proposal: { kind: "assist", at: doc!.at, ops: 1 } },
+ ]);
+ const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.equal(m.render.transition, 0.22);
+});
diff --git a/editor/app/api/ops/check-post-availability/route.ts b/editor/app/api/ops/check-post-availability/route.ts
@@ -0,0 +1,32 @@
+import { checkPostAvailabilityAction } from "../../../channels/[slug]/socialActions";
+import {
+ CHECK_POST_AVAILABILITY_MODES,
+ type CheckPostAvailabilityMode,
+} from "yt-dlp-transcript-common/controller/checkPostAvailability";
+import { OpsInputError, jobResponse, ops, optPositiveInt, optString, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, mode?, limit? } -> { ok: true, jobId }
+//
+// WHICH ARCHIVED POSTS ARE GONE AT THEIR SOURCE (the channel page's "Check
+// deleted posts"; release 37 S5 adds this door): a check-post-availability
+// job. A Wayback pages channel's records are checked by their ORIGINAL URL at
+// its own site (lib/waybackPages/liveness-server.ts, the web pacer — never
+// the Wayback Machine), one request per distinct URL; any other posts
+// channel through its fetcher's own check. `mode`: "stale" (default) |
+// "unchecked" | "all"; `limit` (default 200) counts posts, or URLs for a
+// pages channel. The verdicts land in posts-availability.json.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "mode", "limit"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const mode = optString(body, "mode");
+ if (mode !== undefined && !(CHECK_POST_AVAILABILITY_MODES as string[]).includes(mode)) {
+ throw new OpsInputError(`"mode" must be one of ${CHECK_POST_AVAILABILITY_MODES.join(", ")}`);
+ }
+ const limit = optPositiveInt(body, "limit");
+ return jobResponse(
+ await checkPostAvailabilityAction(slug, undefined, mode as CheckPostAvailabilityMode | undefined, limit),
+ );
+ });
+}
diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts
@@ -2,18 +2,36 @@ import { fetchPostsAction } from "../../../channels/[slug]/socialActions";
import {
jobResponse,
ops,
+ OpsInputError,
optBool,
optPositiveInt,
optString,
reqSlug,
+ type OpsBody,
} from "../_lib";
+import type { RetryOnBlock } from "yt-dlp-transcript-common/lib/forumWalk";
+
+// `retryOnBlock`: `{ "minutes": N, "max": M }`, or `true` for the forum
+// default in settings (`social.xenforo.retryOnBlock`; nothing when unset).
+function optRetryOnBlock(body: OpsBody): RetryOnBlock | "settings" | undefined {
+ const v = body.retryOnBlock;
+ if (v === undefined || v === null || v === false) return undefined;
+ if (v === true) return "settings";
+ if (typeof v === "object" && !Array.isArray(v)) {
+ const r = v as Record<string, unknown>;
+ if (typeof r.minutes === "number" && typeof r.max === "number") return { minutes: r.minutes, max: r.max };
+ }
+ throw new OpsInputError('"retryOnBlock" must be { "minutes": N, "max": M } or true.');
+}
export const dynamic = "force-dynamic";
-// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, queueKey? } -> { ok: true, jobId }
+// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId }
//
// `pages` caps how many pages a run reads, for a channel read page by page (a
-// forum thread: its latest N pages).
+// forum thread: its latest N pages). `retryOnBlock` ({minutes, max}, or true
+// for the forum default in settings) waits out a challenge or refusal page and
+// runs again, max tries in all — never on a captcha or a login.
//
// A social channel's "Fetch posts" button, over HTTP — and its "Re-fetch full
// history" (`full`) and "Fetch older posts" (`older`, with an optional `floor`
@@ -29,7 +47,7 @@ export const dynamic = "force-dynamic";
export async function POST(request: Request) {
return ops(
request,
- ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "queueKey"],
+ ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"],
async (body) => {
const slug = reqSlug(body, "slug");
return jobResponse(
@@ -43,6 +61,7 @@ export async function POST(request: Request) {
optBool(body, "force"),
optPositiveInt(body, "pages"),
optString(body, "from"),
+ optRetryOnBlock(body),
),
);
},
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -1,6 +1,8 @@
import { findCopyAction, findWholeCopiesAction } from "../../../channels/[slug]/videos/findCopyAction";
import { FIND_COPY_MAX_LIMIT, GONE_SCOPES, type GoneScope } from "yt-dlp-transcript-common/publish/findCopy";
import { OpsInputError, jobResponse, ops, optBool, optPositiveInt, optString } from "../_lib";
+import { findPageCopiesAction } from "../../../channels/[slug]/waybackLiveActions";
+import { FIND_PAGE_COPY_MAX_LIMIT } from "yt-dlp-transcript-common/publish/findCopyPages";
export const dynamic = "force-dynamic";
@@ -36,12 +38,48 @@ export const dynamic = "force-dynamic";
// with `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,
// looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?,
// via?, outcome}], left, items, stopped?, fetchJobId?, refused?}`.
+//
+// POST { article } | { siteId } | { articles: true }, pages: true, channel?,
+// max?, dryRun? -> { ok, jobId } — THE PAGE MODE (release 37 S5,
+// publish/findCopyPages.ts): every page the reports cite whose ORIGINAL is
+// gone at its own site gets the Wayback capture nearest the citation's date
+// imported into the Wayback pages channel named (`channel`) or the one whose
+// targets cover it; a cited page record whose original is gone has its
+// capture imported again when it is not stored. A find-copy job on the
+// archive.org queue; at most `max` (default 10, at most 100) pages looked up.
+// The log ends with `@@find-copy {host, dryRun, max, pages, posts, items:
+// [{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?,
+// as?, records?}], left, stopped?}` — `pointTo`/`as` name the record a
+// citation should cite; the report is not rewritten.
export async function POST(request: Request) {
- return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max"], async (body) => {
+ return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max", "pages", "channel"], async (body) => {
const article = optString(body, "article")?.trim();
const siteId = optString(body, "siteId")?.trim();
const articles = optBool(body, "articles") === true;
const gone = optString(body, "gone");
+ if (optBool(body, "pages") === true) {
+ if (gone !== undefined || optString(body, "slug") !== undefined || body.retryFailed !== undefined) {
+ throw new OpsInputError('"pages" is its own mode: send "article", "articles": true or "siteId", with "channel"?, "max"?, "dryRun"? — not "gone", "slug" or "retryFailed"');
+ }
+ if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) {
+ throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"');
+ }
+ const max = optPositiveInt(body, "max");
+ if (max !== undefined && max > FIND_PAGE_COPY_MAX_LIMIT) {
+ throw new OpsInputError(`"max" must be at most ${FIND_PAGE_COPY_MAX_LIMIT}`);
+ }
+ const channel = optString(body, "channel")?.trim() || undefined;
+ return jobResponse(
+ await findPageCopiesAction({
+ ...(article ? { article } : {}),
+ ...(siteId ? { siteId } : {}),
+ ...(channel ? { channel } : {}),
+ ...(max !== undefined ? { max } : {}),
+ dryRun: optBool(body, "dryRun") === true,
+ }),
+ );
+ }
+ if (optString(body, "channel") !== undefined) throw new OpsInputError('"channel" goes with "pages": true (the page mode)');
if (gone !== undefined) {
if (!(GONE_SCOPES as readonly string[]).includes(gone)) {
throw new OpsInputError(`"gone" must be one of ${GONE_SCOPES.join(", ")}`);
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -3,6 +3,7 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft";
import { planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh";
import { planClipsSuggestJob } from "yt-dlp-transcript-common/controller/clipsSuggest";
+import { planVideoAssistJob } from "yt-dlp-transcript-common/controller/videoAssist";
import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
import { jobResponse, ops, opsFail } from "../_lib";
import { refreshEditor, researchEditor } from "../_researchEditor";
@@ -61,7 +62,17 @@ export const dynamic = "force-dynamic";
// (UMTOOL_URL, WORKER_TOKEN); `answers`: a Claude Code session's labels
// (the `code` route), written as a model's; `dryRun: true` answers
// `{ ok, plan }` (the proposals, calls, the estimate, the request) and
-// writes nothing. Answers `{ ok, jobId, iteration: 0 }`.
+// writes nothing. Answers `{ ok, jobId, iteration: 0 }`;
+// - "video-assist" (release 38 lane E, controller/videoAssist.ts): on a
+// umtool video project, `project` (its absolute directory) and `request`
+// (what to change, in words; or `note`, a note on the whole project whose
+// text is the request — the proposals are posted to it as the agent's
+// reply), `scope` look | clips | fx | all — ONE ask whose checked ops land
+// in `<project>/assist-proposals.json` as proposals (nothing applied;
+// umtool's Apply does that); `answers`: a Claude Code session's
+// `{ops, reply}` (the `code` route); `dryRun: true` answers `{ ok, plan }`
+// (the prompt, the estimate) and writes nothing. Answers
+// `{ ok, jobId, iteration: 0 }`.
// `model` defaults to settings.generation's route for the task (a task routed
// to `code` needs one named). `extractorModel` is an API sweep's extractor
// (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's
@@ -98,6 +109,14 @@ export async function POST(request: Request) {
return opsFail((e as Error).message);
}
}
+ if (body.task === "video-assist" && body.dryRun === true) {
+ try {
+ const plan = await planVideoAssistJob(parseReportDraftBody(body), deps);
+ return NextResponse.json({ ok: true, plan });
+ } catch (e) {
+ return opsFail((e as Error).message);
+ }
+ }
const out = await enqueueReportDraft(body, deps);
if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result);
void out.result.stream.cancel();
diff --git a/editor/app/api/ops/save-page-now/route.ts b/editor/app/api/ops/save-page-now/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { savePageNowAction, savePageNowDryRunAction } from "../../../channels/[slug]/waybackLiveActions";
+import { jobResponse, ops, optBool, optString, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { url, slug?, dryRun? } -> { ok: true, jobId } | (dryRun) { ok: true, dryRun: true, wouldAsk, … }
+//
+// SAVE PAGE NOW (release 37 S5, controller/savePageNow.ts): the Wayback
+// Machine asked to capture `url` now, with archive.org's S3 keys (the
+// editor's ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, else the mode-600
+// file settings `archiveOrg.s3KeyFile` names) — a `save-page-now` job on the
+// archive.org queue that asks for the capture (the page alone), polls its
+// status, and, with `slug` (a Wayback pages channel), starts an import-page
+// job of the capture. The log ends with `@@save-page-now {ok, url, slug?,
+// spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?,
+// polls, error?}`. `dryRun` answers what it would ask and starts nothing.
+// Every refusal is the controller's sentence (no keys among them); the keys
+// are never echoed.
+export async function POST(request: Request) {
+ return ops(request, ["url", "slug", "dryRun"], async (body) => {
+ const url = reqString(body, "url");
+ const slug = optString(body, "slug")?.trim() || undefined;
+ if (optBool(body, "dryRun") === true) {
+ const r = await savePageNowDryRunAction(url, slug);
+ if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 });
+ return NextResponse.json(r);
+ }
+ return jobResponse(await savePageNowAction(url, slug, "ops"));
+ });
+}
diff --git a/editor/app/api/ops/settings/route.ts b/editor/app/api/ops/settings/route.ts
@@ -5,6 +5,7 @@ import { OpsInputError, ops, opsFail } from "../_lib";
import { readRoute, redactSecrets } from "../_read";
import { settingsPatchProblem } from "./patch";
import { looksLikeApiKey } from "yt-dlp-transcript-common/lib/generationSettings";
+import { looksLikeS3Key } from "yt-dlp-transcript-common/lib/archiveOrgTorrent";
export const dynamic = "force-dynamic";
@@ -65,6 +66,14 @@ export async function POST(request: Request) {
"generation.apiKeyFile is the PATH of the mode-600 file that holds the key, and the value sent looks like a key itself — refused, not stored",
);
}
+ // archive.org's S3 keys are never a setting either (release 37 S5): the
+ // same refusal for archiveOrg.s3KeyFile, without the value.
+ const s3KeyFile = (patch as { archiveOrg?: { s3KeyFile?: unknown } }).archiveOrg?.s3KeyFile;
+ if (typeof s3KeyFile === "string" && looksLikeS3Key(s3KeyFile)) {
+ throw new OpsInputError(
+ "archiveOrg.s3KeyFile is the PATH of the mode-600 file that holds archive.org's S3 keys, and the value sent is not a path — refused, not stored",
+ );
+ }
const current = getSettings();
const problem = settingsPatchProblem(
patch as Record<string, unknown>,
diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx
@@ -12,9 +12,15 @@ import {
connectForumSessionAction,
fetchPostsAction,
importForumPagesAction,
+ setForumRetryOnBlockAction,
setPostFetcherAction,
} from "../socialActions";
import type { ForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
+import {
+ describeRetryOnBlock,
+ roughDuration,
+ type RetryOnBlock,
+} from "yt-dlp-transcript-common/lib/forumWalk";
import { SocialPostTools } from "./SocialPostTools";
export type SocialChannelState = {
@@ -44,6 +50,15 @@ export type SocialChannelState = {
forumSession?: ForumSessionStatus;
// An X search channel (release 38): its query and where its walk stands.
search?: { query: string; walk: string };
+ // A forum thread's two walks (lib/forumWalk.ts): the status line, the
+ // thread's last page as last seen, the mean seconds a page takes at the
+ // channel's pace, and the Fetch posts button's retry after a block.
+ forumWalk?: {
+ status: string | null;
+ lastPage: number | null;
+ pageSeconds: number;
+ retryOnBlock: RetryOnBlock | null;
+ };
};
export function SocialChannelPanel({
@@ -114,8 +129,13 @@ export function SocialChannelPanel({
}
});
+ const [fetchNote, setFetchNote] = useState<string | null>(null);
+ const [fetchErr, setFetchErr] = useState<string | null>(null);
const run = (full: boolean, older = false) =>
startTransition(async () => {
+ setFetchNote(null);
+ setFetchErr(null);
+ setConfirmRewalk(false);
const n = Number(pages);
const res = await fetchPostsAction(
slug,
@@ -125,11 +145,45 @@ export function SocialChannelPanel({
older || undefined,
undefined,
undefined,
- forum && pages.trim() && Number.isInteger(n) && n > 0 ? n : undefined,
+ forum && !full && pages.trim() && Number.isInteger(n) && n > 0 ? n : undefined,
+ undefined,
+ // A forum thread's Fetch posts waits out a block as settings say.
+ forum && !full ? "settings" : undefined,
);
// The job streams to the jobs page; nothing to consume here, but the
// stream must be released or its buffered chunks leak.
- if (res.ok) void res.stream.cancel();
+ if (res.ok) {
+ void res.stream.cancel();
+ if (forum) setFetchNote(full ? "Full re-walk queued — its log is on the jobs page." : "Fetch queued — its log is on the jobs page.");
+ } else if (forum) {
+ setFetchErr(res.error);
+ }
+ });
+
+ // FULL RE-WALK (a forum thread): every page from the last to page 1, asked
+ // for twice — it is hours of paced loads.
+ const [confirmRewalk, setConfirmRewalk] = useState(false);
+ const walk = state.forumWalk;
+ const rewalkPages = walk?.lastPage ?? null;
+ const rewalkTime = rewalkPages && walk ? roughDuration(rewalkPages * walk.pageSeconds) : null;
+
+ // RETRY AFTER A BLOCK: settings.social.xenforo.retryOnBlock.
+ const [retry, setRetry] = useState<RetryOnBlock | null>(walk?.retryOnBlock ?? null);
+ const [retryMinutes, setRetryMinutes] = useState(String(walk?.retryOnBlock?.minutes ?? 30));
+ const [retryMax, setRetryMax] = useState(String(walk?.retryOnBlock?.max ?? 12));
+ const saveRetry = (on: boolean) =>
+ startTransition(async () => {
+ setForumNote(null);
+ setForumErr(null);
+ const res = await setForumRetryOnBlockAction(
+ on ? { minutes: Number(retryMinutes), max: Number(retryMax) } : null,
+ );
+ if (res.ok) {
+ setRetry(res.retryOnBlock);
+ setForumNote(res.retryOnBlock ? "Retry after a block saved." : "Retry after a block turned off.");
+ } else {
+ setForumErr(res.error);
+ }
});
return (
@@ -261,20 +315,33 @@ export function SocialChannelPanel({
>
Check deleted posts
</button>
- <button
- type="button"
- onClick={() => run(true)}
- disabled={pending}
- aria-label={state.search ? "search again from the top" : "refetch full history"}
- title={
- state.search
- ? "Walk the whole search again from its newest window. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates."
- : "Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates."
- }
- className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
- >
- {state.search ? "Search again from the top" : "Re-fetch full history"}
- </button>
+ {forum ? (
+ <button
+ type="button"
+ onClick={() => setConfirmRewalk(true)}
+ disabled={pending || confirmRewalk}
+ aria-label="full re-walk"
+ title="Re-read every page from the last to page 1: new posts added, edited ones updated, posts no page shows any more counted in the log."
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ Full re-walk
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={() => run(true)}
+ disabled={pending}
+ aria-label={state.search ? "search again from the top" : "refetch full history"}
+ title={
+ state.search
+ ? "Walk the whole search again from its newest window. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates."
+ : "Re-walk the account's whole history. Already-archived posts are deduped, so this repairs a gap rather than creating duplicates."
+ }
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ {state.search ? "Search again from the top" : "Re-fetch full history"}
+ </button>
+ )}
{state.canFetchOlder && (
<button
type="button"
@@ -289,6 +356,52 @@ export function SocialChannelPanel({
)}
</div>
+ {forum && confirmRewalk && (
+ <div
+ role="alertdialog"
+ aria-label="confirm full re-walk"
+ className="mt-3 flex flex-wrap items-center gap-2 rounded border border-warning/40 bg-warning-soft px-3 py-2 text-xs"
+ >
+ <span>
+ {rewalkPages
+ ? `Re-read all ${rewalkPages} pages, from the last to page 1 — ${rewalkTime} at this channel's pace.`
+ : "Re-read every page, from the last to page 1, at this channel's pace."}
+ </span>
+ <button
+ type="button"
+ onClick={() => run(true)}
+ disabled={pending}
+ aria-label="start full re-walk"
+ className="rounded-md bg-primary px-2 py-0.5 font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50"
+ >
+ Start full re-walk
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirmRewalk(false)}
+ aria-label="cancel full re-walk"
+ className="rounded-md border border-border px-2 py-0.5 hover:bg-muted"
+ >
+ Cancel
+ </button>
+ </div>
+ )}
+ {forum && walk?.status && (
+ <p aria-label="forum walk" className="mt-3 text-xs text-muted-foreground">
+ {walk.status}
+ </p>
+ )}
+ {fetchNote && (
+ <p role="status" className="mt-2 text-xs text-success">
+ {fetchNote}
+ </p>
+ )}
+ {fetchErr && (
+ <p role="alert" className="mt-2 text-xs text-destructive">
+ {fetchErr}
+ </p>
+ )}
+
{/* The two failure surfaces a social channel actually has. */}
{state.needsCookies && (
<p
@@ -361,6 +474,60 @@ export function SocialChannelPanel({
</button>
</div>
+ <div className="flex flex-col gap-1 border-t border-border pt-3 text-sm">
+ <span className="font-medium">Retry after a block</span>
+ <span aria-label="retry after a block" className="text-xs text-muted-foreground">
+ Fetch posts: {describeRetryOnBlock(retry ?? undefined)} (a captcha or a login is never retried)
+ </span>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-1">
+ <span>Wait</span>
+ <input
+ type="number"
+ min={5}
+ inputMode="numeric"
+ value={retryMinutes}
+ onChange={(e) => setRetryMinutes(e.target.value)}
+ aria-label="retry minutes"
+ className="w-20 rounded border border-border bg-card px-2 py-1 text-sm"
+ />
+ <span>min, up to</span>
+ </label>
+ <label className="flex items-center gap-1">
+ <input
+ type="number"
+ min={1}
+ inputMode="numeric"
+ value={retryMax}
+ onChange={(e) => setRetryMax(e.target.value)}
+ aria-label="retry tries"
+ className="w-16 rounded border border-border bg-card px-2 py-1 text-sm"
+ />
+ <span>tries</span>
+ </label>
+ <button
+ type="button"
+ onClick={() => saveRetry(true)}
+ disabled={pending}
+ aria-label="save retry after a block"
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ Save
+ </button>
+ {retry && (
+ <button
+ type="button"
+ onClick={() => saveRetry(false)}
+ disabled={pending}
+ aria-label="turn off retry after a block"
+ className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50"
+ >
+ Turn off
+ </button>
+ )}
+ </div>
+ </div>
+
<div className="border-t border-border pt-3">
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">Import saved pages</span>
diff --git a/editor/app/channels/[slug]/components/WaybackLivePanel.tsx b/editor/app/channels/[slug]/components/WaybackLivePanel.tsx
@@ -0,0 +1,185 @@
+"use client";
+
+// A WAYBACK PAGES channel, live (release 37 S5): whether each record's
+// ORIGINAL is still up (check-post-availability, asked at the original's own
+// site — never the Wayback Machine), the records whose original is gone (the
+// Wayback copy is then the only copy), and Save Page Now — "Ask the Wayback
+// Machine to capture this now" — for a page still up, its capture imported
+// here. Save Page Now is off without archive.org's S3 keys, and says why.
+
+import { useState, useTransition } from "react";
+import Link from "next/link";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../jobs/actions";
+import { checkPostAvailabilityAction } from "../socialActions";
+import { savePageNowAction } from "../waybackLiveActions";
+
+export type WaybackLiveRow = {
+ id: string;
+ title: string;
+ originalUrl: string;
+ waybackUrl: string;
+ // posts-availability.json's verdict on the original, when checked.
+ availability?: string;
+ reason?: string;
+ checkedAt?: string;
+};
+
+export type WaybackLiveState = {
+ // Distinct original URLs, and how many were checked / are gone.
+ originals: number;
+ checked: number;
+ gone: number;
+ unavailable: number;
+ // Records whose original is gone (deleted or unavailable), newest first.
+ goneRows: WaybackLiveRow[];
+ // Records whose original answered, one per original URL (Save Page Now).
+ liveRows: WaybackLiveRow[];
+ spn: { on: true } | { on: false; reason: string };
+};
+
+function CaptureNow({ slug, url, disabled }: { slug: string; url: string; disabled: boolean }) {
+ const [pending, start] = useTransition();
+ const [job, setJob] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ return (
+ <span className="inline-flex items-center gap-2">
+ <button
+ type="button"
+ disabled={disabled || pending}
+ aria-label={`capture ${url} now`}
+ onClick={() =>
+ start(async () => {
+ setErr(null);
+ const res = await savePageNowAction(url, slug);
+ if (res.ok) {
+ void res.stream.cancel();
+ setJob(res.jobId);
+ } else {
+ setErr(res.error);
+ }
+ })
+ }
+ className="rounded border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50"
+ >
+ {pending ? "Asking…" : "Capture now"}
+ </button>
+ {job && (
+ <Link href={`/jobs/${job}`} className="text-xs underline underline-offset-2">
+ job
+ </Link>
+ )}
+ {err && (
+ <span role="alert" className="text-xs text-destructive">
+ {err}
+ </span>
+ )}
+ </span>
+ );
+}
+
+export function WaybackLivePanel({ slug, state }: { slug: string; state: WaybackLiveState }) {
+ const [url, setUrl] = useState("");
+ const [checkJob, setCheckJob] = useState<string | null>(null);
+ const [spnJob, setSpnJob] = useState<string | null>(null);
+ const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono";
+ const spnOff = !state.spn.on;
+ return (
+ <div className="flex flex-col gap-4">
+ <section aria-label="originals" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h4 className="text-sm font-semibold">Originals</h4>
+ <span role="status" aria-label="originals checked" className="text-sm text-muted-foreground">
+ {state.checked} of {state.originals} original URL{state.originals === 1 ? "" : "s"} checked · {state.gone} gone
+ {state.unavailable > 0 ? ` · ${state.unavailable} unavailable` : ""}
+ </span>
+ </div>
+ <StreamActionLog
+ trigger={() => checkPostAvailabilityAction(slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Check originals"
+ runningLabel="Checking…"
+ label={`Check the originals of ${slug}`}
+ disabled={state.originals === 0}
+ onSettled={(started, out) => setCheckJob(started ? out.jobId : null)}
+ />
+ {checkJob && (
+ <Link href={`/jobs/${checkJob}`} className="text-xs underline underline-offset-2">
+ Open the check job
+ </Link>
+ )}
+ {state.goneRows.length > 0 && (
+ <table aria-label="originals gone" className="mt-1 w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-muted-foreground">
+ <th className="py-1 pr-2 font-medium">Page</th>
+ <th className="py-1 pr-2 font-medium">Original</th>
+ <th className="py-1 font-medium">Wayback copy</th>
+ </tr>
+ </thead>
+ <tbody>
+ {state.goneRows.map((r) => (
+ <tr key={r.id} data-original-gone={r.id} className="border-t border-border align-top">
+ <td className="py-1 pr-2">{r.title}</td>
+ <td className="py-1 pr-2 text-xs">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono underline underline-offset-2">
+ {r.availability === "deleted" ? "gone" : "unavailable"}
+ </a>
+ {r.reason && <span className="text-muted-foreground"> · {r.reason}</span>}
+ </td>
+ <td className="py-1 text-xs">
+ <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2">
+ the only copy
+ </a>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </section>
+ <section aria-label="save page now" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <h4 className="text-sm font-semibold">Save Page Now</h4>
+ {spnOff && (
+ <p role="status" aria-label="save page now off" className="text-xs text-muted-foreground">
+ {state.spn.on ? "" : state.spn.reason}
+ </p>
+ )}
+ <input
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ aria-label="page to capture"
+ placeholder="https://…"
+ disabled={spnOff}
+ className={`${input} w-[36rem] max-w-full`}
+ />
+ <StreamActionLog
+ trigger={() => savePageNowAction(url.trim(), slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Ask the Wayback Machine to capture this now"
+ runningLabel="Capturing…"
+ label={`Save Page Now into ${slug}`}
+ disabled={spnOff || !url.trim()}
+ onSettled={(started, out) => setSpnJob(started ? out.jobId : null)}
+ />
+ {spnJob && (
+ <Link href={`/jobs/${spnJob}`} aria-label="save page now job" className="text-xs underline underline-offset-2">
+ Open the capture job
+ </Link>
+ )}
+ {state.liveRows.length > 0 && (
+ <ul aria-label="originals still up" className="mt-1 flex flex-col gap-1 text-sm">
+ {state.liveRows.map((r) => (
+ <li key={r.id} data-original-live={r.id} className="flex flex-wrap items-center gap-2">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2">
+ {r.originalUrl}
+ </a>
+ <CaptureNow slug={slug} url={r.originalUrl} disabled={spnOff} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -20,8 +20,18 @@ import "yt-dlp-transcript-common/social/xNitterFetcher";
import "yt-dlp-transcript-common/social/xenforoFetcher";
import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSession";
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
+import {
+ deriveForumWalk,
+ describeForumWalk,
+ FORUM_DEFAULT_PAGE_PAUSE_SECONDS,
+ FORUM_MIN_PAGE_PAUSE_SECONDS,
+ meanPagePauseSeconds,
+} from "yt-dlp-transcript-common/lib/forumWalk";
import { SocialChannelPanel } from "./components/SocialChannelPanel";
import { WaybackPagesPanel } from "./components/WaybackPagesPanel";
+import { WaybackLivePanel } from "./components/WaybackLivePanel";
+import { waybackLiveState } from "./waybackLiveState";
+import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { isXSearchChannel } from "yt-dlp-transcript-common/lib/xSearch/config";
import { describeXSearchWalk } from "yt-dlp-transcript-common/lib/xSearch/walk";
@@ -188,13 +198,29 @@ export default async function ChannelDetailPage({
const forumSession = forumThread
? await readForumSessionStatus(paths, forumThread.host)
: undefined;
+ // A forum thread's two walks (release 37 lane G): the positions the next
+ // run starts from — derived from the archived posts' pages exactly as the
+ // fetch derives them, so a healed position shows before the run.
+ const forumPageSeconds = meanPagePauseSeconds(
+ config.postPagePauseSeconds ?? FORUM_DEFAULT_PAGE_PAUSE_SECONDS,
+ FORUM_MIN_PAGE_PAUSE_SECONDS,
+ );
+ const forumDerived = forumThread
+ ? deriveForumWalk(
+ fetchState?.forum,
+ fetchState?.cursor,
+ (await readAllPosts(channelRoot)).flatMap((p) =>
+ p.platform === "xenforo" && typeof p.forum?.page === "number" ? [p.forum.page] : [],
+ ),
+ ).walk
+ : null;
// A WAYBACK PAGES channel (release 37): its captures, its scope, Import a
// capture — no fetcher, nothing to fetch.
+ const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : [];
const wayback = isWaybackPagesChannel(config)
? {
captureCount: await countStoredCaptures(channelRoot),
- recent: (await readAllPosts(channelRoot))
- .filter((p) => p.page)
+ recent: pageRecords
.sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))
.slice(0, 20)
.map((p) => ({
@@ -216,6 +242,7 @@ export default async function ChannelDetailPage({
<div className="flex flex-col gap-6">
<RunningJobsList jobs={socialRunningJobs} hideChannelSlug />
{wayback ? (
+ <>
<WaybackPagesPanel
slug={slug}
state={{
@@ -225,6 +252,12 @@ export default async function ChannelDetailPage({
recent: wayback.recent,
}}
/>
+ {/* Release 37 S5: is each original still up; Save Page Now. */}
+ <WaybackLivePanel
+ slug={slug}
+ state={waybackLiveState(pageRecords, postAvailability, savePageNowAvailability())}
+ />
+ </>
) : (
<SocialChannelPanel
slug={slug}
@@ -258,6 +291,16 @@ export default async function ChannelDetailPage({
availableFetchers: [],
}
: {}),
+ ...(forumDerived
+ ? {
+ forumWalk: {
+ status: describeForumWalk(forumDerived, forumPageSeconds),
+ lastPage: forumDerived.newestPage ?? null,
+ pageSeconds: forumPageSeconds,
+ retryOnBlock: getSettings().social.xenforo?.retryOnBlock ?? null,
+ },
+ }
+ : {}),
}}
/>
)}
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -29,7 +29,13 @@ import {
fetchPosts,
FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL,
olderPostsProblem,
+ RETRY_AND_OLDER_REFUSAL,
} from "yt-dlp-transcript-common/controller/fetchPosts";
+import {
+ retryOnBlockProblem,
+ type RetryOnBlock,
+} from "yt-dlp-transcript-common/lib/forumWalk";
+import { saveSettings } from "../../settings/saveSettings";
import { isUtcDay } from "yt-dlp-transcript-common/social/olderBackfill";
import {
checkPostAvailability,
@@ -172,8 +178,17 @@ export async function fetchPostsAction(
pages?: number,
// The older walk's fresh start date (FetchPostsOptions.from).
from?: string,
+ // Wait out a challenge or refusal page and run again (release 37 lane G):
+ // `{minutes, max}`, or "settings" for `settings.social.xenforo.retryOnBlock`
+ // (a forum thread's Fetch posts button; nothing when it is unset).
+ retryOnBlock?: RetryOnBlock | "settings",
): Promise<StreamActionResult> {
if (full && older) return { ok: false, error: FULL_AND_OLDER_REFUSAL };
+ if (retryOnBlock && older) return { ok: false, error: RETRY_AND_OLDER_REFUSAL };
+ const retry =
+ retryOnBlock === "settings" ? getSettings().social.xenforo?.retryOnBlock : retryOnBlock;
+ const retryProblem = retryOnBlockProblem(retry);
+ if (retryProblem) return { ok: false, error: retryProblem };
if (pages !== undefined && !(Number.isInteger(pages) && pages > 0)) {
return { ok: false, error: "Pages must be a whole number above 0." };
}
@@ -230,7 +245,17 @@ export async function fetchPostsAction(
spec: {
kind: "fetch-posts",
slug,
- params: { queueKey, full, limit, older, floor, force, ...(pages ? { pages } : {}), ...(from ? { from } : {}) },
+ params: {
+ queueKey,
+ full,
+ limit,
+ older,
+ floor,
+ force,
+ ...(pages ? { pages } : {}),
+ ...(from ? { from } : {}),
+ ...(retry ? { retryOnBlock: retry } : {}),
+ },
},
fn: async (onLog, signal, _progress, ctx) => {
const result = await fetchPosts({
@@ -244,6 +269,7 @@ export async function fetchPostsAction(
force,
limit,
pages,
+ ...(retry ? { retryOnBlock: retry } : {}),
onLog,
signal,
// A drained fetch keeps its resume point and returns ok: the job
@@ -402,3 +428,24 @@ export async function importForumPagesAction(
},
});
}
+
+// RETRY AFTER A BLOCK — `settings.social.xenforo.retryOnBlock`, the forum
+// Fetch posts button's default (release 37 lane G). Null turns it off: the
+// key is written as undefined, which saveSettings' one-level merge of `social`
+// then drops from the file.
+export async function setForumRetryOnBlockAction(
+ retry: RetryOnBlock | null,
+): Promise<{ ok: true; retryOnBlock: RetryOnBlock | null } | { ok: false; error: string }> {
+ const problem = retry ? retryOnBlockProblem(retry) : null;
+ if (problem) return { ok: false, error: problem };
+ const social = getSettings().social;
+ try {
+ await saveSettings({
+ social: { ...social, xenforo: retry ? { ...social.xenforo, retryOnBlock: retry } : undefined },
+ });
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ revalidatePath("/channels");
+ return { ok: true, retryOnBlock: getSettings().social.xenforo?.retryOnBlock ?? null };
+}
diff --git a/editor/app/channels/[slug]/waybackLiveActions.ts b/editor/app/channels/[slug]/waybackLiveActions.ts
@@ -0,0 +1,102 @@
+"use server";
+
+// WAYBACK PAGES, LIVE (release 37 S5): Save Page Now — "Ask the Wayback
+// Machine to capture this now" (controller/savePageNow.ts) — and find-copy's
+// page mode, a copy of every gone page a report cites (publish/findCopyPages.ts).
+// Both on the archive.org queue; the controllers' refusals in their own
+// sentences, before a job exists. The original-URL availability check is the
+// posts' own action (socialActions.ts checkPostAvailabilityAction).
+
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
+import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
+import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ queueSavePageNow,
+ savePageNow,
+ savePageNowAvailability,
+ type SavePageNowAvailability,
+ type SavePageNowResult,
+} from "yt-dlp-transcript-common/controller/savePageNow";
+import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
+import { findPageCopies } from "yt-dlp-transcript-common/publish/findCopyPages";
+import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
+
+export async function savePageNowAction(url: string, slug?: string, requestedBy?: string): Promise<StreamActionResult> {
+ return queueSavePageNow({
+ paths: getPaths(),
+ url: url.trim(),
+ ...(slug?.trim() ? { slug: slug.trim() } : {}),
+ ...(requestedBy ? { requestedBy } : {}),
+ onDone: () => {
+ if (slug) safeRevalidate([`/channels/${slug}`]);
+ },
+ });
+}
+
+// What a capture WOULD ask, answered now (no job, no request).
+export async function savePageNowDryRunAction(url: string, slug?: string): Promise<SavePageNowResult> {
+ return savePageNow({ paths: getPaths(), url: url.trim(), ...(slug?.trim() ? { slug: slug.trim() } : {}), dryRun: true });
+}
+
+// Whether the button is on, and why not (the keys' presence, never their
+// value).
+export async function savePageNowAvailabilityAction(): Promise<SavePageNowAvailability> {
+ return savePageNowAvailability();
+}
+
+// FIND-COPY, PAGE MODE: `{article} | {articles: true} | {siteId}`, `channel?`,
+// `max?`, `dryRun?` — one find-copy job on the archive.org queue. Its log ends
+// with `@@find-copy {host, dryRun, max, pages, posts, items, left, stopped?}`.
+export async function findPageCopiesAction(req: {
+ article?: string;
+ siteId?: string;
+ channel?: string;
+ max?: number;
+ dryRun?: boolean;
+}): Promise<StreamActionResult> {
+ const paths = getPaths();
+ let host: ReportHost;
+ try {
+ if (req.article) {
+ host = await articlesWorkHost(paths, [req.article], { only: true });
+ } else if (req.siteId) {
+ if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` };
+ if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` };
+ host = siteReportHost(paths, getSite(req.siteId, paths));
+ } else {
+ host = await articlesWorkHost(paths);
+ }
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ if (req.channel) {
+ const config = await readChannelConfig(paths, req.channel);
+ if (!config) return { ok: false, error: `No such channel: ${req.channel}` };
+ if (!isWaybackPagesChannel(config)) return { ok: false, error: `${req.channel} is not a Wayback pages channel` };
+ }
+ return runManagedFunction({
+ kind: "find-copy",
+ queueKey: WAYBACK_PAGES_QUEUE,
+ paths,
+ ...(req.channel ? { channelSlug: req.channel } : {}),
+ fn: async (onLog, signal) => {
+ const r = await findPageCopies({
+ paths,
+ host,
+ ...(req.channel ? { channel: req.channel } : {}),
+ ...(req.max !== undefined ? { max: req.max } : {}),
+ dryRun: req.dryRun === true,
+ signal,
+ onLog,
+ });
+ onLog(`${FIND_COPY_RESULT_MARKER}${JSON.stringify(r)}`);
+ const touched = new Set(r.items.filter((i) => i.outcome === "imported" && i.channel).map((i) => `/channels/${i.channel}`));
+ if (touched.size > 0) safeRevalidate([...touched]);
+ if (signal.aborted) throw new Error("cancelled");
+ },
+ });
+}
diff --git a/editor/app/channels/[slug]/waybackLiveState.ts b/editor/app/channels/[slug]/waybackLiveState.ts
@@ -0,0 +1,51 @@
+// The Wayback pages channel's live panel's state (release 37 S5,
+// components/WaybackLivePanel.tsx), from its page records and the
+// availability sidecar: one row per original URL.
+
+import type { Post, PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts";
+import { groupByOriginalUrl } from "yt-dlp-transcript-common/lib/waybackPages/liveness";
+import type { WaybackLiveRow, WaybackLiveState } from "./components/WaybackLivePanel";
+
+const ROWS = 20;
+
+export function waybackLiveState(
+ records: ReadonlyArray<Post>,
+ availability: PostAvailabilityMap,
+ spn: WaybackLiveState["spn"],
+): WaybackLiveState {
+ const groups = groupByOriginalUrl(records);
+ const byId = new Map(records.map((r) => [r.id, r]));
+ let checked = 0;
+ let gone = 0;
+ let unavailable = 0;
+ const goneRows: WaybackLiveRow[] = [];
+ const liveRows: WaybackLiveRow[] = [];
+ for (const [url, ids] of groups) {
+ // The newest capture of the page stands for it.
+ const newest = ids
+ .map((id) => byId.get(id)!)
+ .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))[0]!;
+ const av = ids.map((id) => availability[id]).find(Boolean);
+ const row: WaybackLiveRow = {
+ id: newest.id,
+ title: newest.page!.title || newest.text.split("\n")[0]!.slice(0, 120) || url,
+ originalUrl: url,
+ waybackUrl: newest.page!.waybackUrl,
+ ...(av ? { availability: av.availability, checkedAt: av.checkedAt, ...(av.reason ? { reason: av.reason } : {}) } : {}),
+ };
+ if (av) checked++;
+ if (av?.availability === "deleted") gone++;
+ if (av?.availability === "account_unavailable") unavailable++;
+ if (av && (av.availability === "deleted" || av.availability === "account_unavailable")) goneRows.push(row);
+ else if (av?.availability === "available") liveRows.push(row);
+ }
+ return {
+ originals: groups.size,
+ checked,
+ gone,
+ unavailable,
+ goneRows: goneRows.slice(0, ROWS),
+ liveRows: liveRows.slice(0, ROWS),
+ spn,
+ };
+}
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -400,6 +400,10 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
bool(p.force),
num(p.pages),
str(p.from),
+ // The retry the job was queued with, resolved (never "settings").
+ p.retryOnBlock && typeof p.retryOnBlock === "object"
+ ? (p.retryOnBlock as { minutes: number; max: number })
+ : undefined,
);
},
// The ids are the spec's own (a capture is OF specific posts, unlike a
diff --git a/editor/e2e/forum-resume.spec.ts b/editor/e2e/forum-resume.spec.ts
@@ -0,0 +1,148 @@
+// A FORUM THREAD's two buttons (release 37 lane G): Fetch posts catches up
+// and then continues the history where it stopped — never re-reading the band
+// between — and Full re-walk re-reads every page, behind a confirm with the
+// page count and the time at the channel's pace. Plus the status line and the
+// retry after a block.
+//
+// The forum is invented and never contacted: the test server's forum fetcher
+// reads SYNTHETIC saved pages from E2E_FORUM_FIXTURE_DIR (e2e/servers.ts sets
+// it to <data root>/test-transcripts/.forum-fixture; see
+// common/social/forumFixtureLoader.ts), written here from a FakeForumThread.
+
+import { test, expect, type Page } from "@playwright/test";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { baseUrl } from "./baseUrl";
+import { pathExists, readJson, resetData, testPaths } from "./helpers";
+import { THREAD_URL } from "yt-dlp-transcript-common/social/__fixtures__/xenforoPages";
+import { FakeForumThread } from "yt-dlp-transcript-common/social/__fixtures__/fakeForumThread";
+
+const SLUG = "teapot-thread";
+
+type ForumState = {
+ forum?: {
+ newestPage?: number;
+ newestPostId?: string;
+ catchUpPage?: number;
+ historyPage?: number;
+ oldestPageReached?: number;
+ complete?: boolean;
+ };
+ cursor?: string;
+};
+
+const channelRoot = () => path.join(testPaths().transcriptsDir, "channels", SLUG);
+const fixtureDir = () => path.join(testPaths().transcriptsDir, ".forum-fixture");
+
+async function state(): Promise<ForumState | null> {
+ const file = path.join(channelRoot(), "posts-state.json");
+ return (await pathExists(file)) ? await readJson<ForumState>(file) : null;
+}
+
+async function archived(): Promise<string[]> {
+ const file = path.join(channelRoot(), "posts-archive");
+ if (!(await pathExists(file))) return [];
+ return (await readFile(file, "utf8")).split("\n").filter(Boolean).map((l) => l.split(" ")[1]).sort();
+}
+
+// A fetch's LAST write is the channel's lastSyncedAt (after posts-state.json):
+// a new stamp means the job is done and its state final.
+const lastSynced = async () =>
+ (await readJson<{ lastSyncedAt?: string }>(path.join(channelRoot(), "config.json"))).lastSyncedAt;
+
+async function untilDone(before: string | undefined) {
+ await expect.poll(lastSynced, { timeout: 30_000 }).not.toBe(before);
+}
+
+async function fetchOnce(page: Page, pages: string) {
+ await page.getByLabel("pages to fetch").fill(pages);
+ const before = await lastSynced();
+ await page.getByRole("button", { name: "fetch posts" }).click();
+ await expect(page.getByRole("status").filter({ hasText: "Fetch queued" })).toBeVisible();
+ await untilDone(before);
+}
+
+test("a forum thread: Fetch posts resumes the history, Full re-walk asks first, the retry is a setting", async ({ page }) => {
+ await resetData("empty");
+ await mkdir(channelRoot(), { recursive: true });
+ await writeFile(
+ path.join(channelRoot(), "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "xenforo",
+ postFetcher: "xenforo-thread",
+ socialHandle: "the-teapot-collectors-thread.4242",
+ name: "Teapot thread",
+ url: THREAD_URL,
+ }),
+ );
+ const thread = new FakeForumThread(30); // 10 pages
+ await thread.writeTo(fixtureDir());
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ await page.goto(`/channels/${SLUG}`);
+ await expect(page.getByRole("button", { name: "fetch posts" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "full re-walk" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "refetch full history" })).toHaveCount(0);
+ await expect(page.getByLabel("forum walk")).toHaveCount(0);
+
+ // The latest 4 pages (10–7): the history stops at 6.
+ await fetchOnce(page, "4");
+ expect((await state())?.forum).toEqual({ newestPage: 10, oldestPageReached: 7, historyPage: 6, newestPostId: "9030" });
+ expect((await state())?.cursor).toBeUndefined();
+
+ // Six new posts (pages 11–12); a 1-page run catches up page 12 only — the
+ // history position stays where it was.
+ thread.add(6);
+ await thread.writeTo(fixtureDir());
+ await page.reload();
+ await expect(page.getByLabel("forum walk")).toHaveText(
+ "pages read 7–10 of 10 · history to page 1 remaining: 6 pages (~2 min)",
+ );
+ await fetchOnce(page, "1");
+ expect((await state())?.forum).toMatchObject({ newestPage: 12, catchUpPage: 11, historyPage: 6, newestPostId: "9030" });
+ await page.reload();
+ await expect(page.getByLabel("forum walk")).toHaveText(
+ "pages read 7–12 of 12 · catch-up unfinished at page 11 · history to page 1 remaining: 6 pages (~2 min)",
+ );
+
+ // No cap: the rest of the catch-up (11), then the history from 6 to 1.
+ await fetchOnce(page, "");
+ expect((await state())?.forum).toMatchObject({ newestPage: 12, newestPostId: "9036", complete: true });
+ expect(await archived()).toEqual(thread.ids().sort());
+ await page.reload();
+ await expect(page.getByLabel("forum walk")).toHaveText("pages read 1–12 of 12 · history complete");
+
+ // FULL RE-WALK asks first: every page, and the time at the channel's pace.
+ await page.getByRole("button", { name: "full re-walk" }).click();
+ const confirm = page.getByRole("alertdialog", { name: "confirm full re-walk" });
+ await expect(confirm).toContainText("Re-read all 12 pages, from the last to page 1 — ~3 min at this channel's pace.");
+ await page.getByRole("button", { name: "cancel full re-walk" }).click();
+ await expect(confirm).toHaveCount(0);
+ const before = await lastSynced();
+ await page.getByRole("button", { name: "full re-walk" }).click();
+ await page.getByRole("button", { name: "start full re-walk" }).click();
+ await expect(page.getByRole("status").filter({ hasText: "Full re-walk queued" })).toBeVisible();
+ await untilDone(before);
+ expect((await state())?.forum).toMatchObject({ complete: true, newestPostId: "9036" });
+ expect(await archived()).toEqual(thread.ids().sort());
+
+ // RETRY AFTER A BLOCK: off until set; saved to settings.social.xenforo.
+ await expect(page.getByLabel("retry after a block", { exact: true })).toContainText("Fetch posts: off");
+ await page.getByLabel("retry minutes").fill("30");
+ await page.getByLabel("retry tries").fill("12");
+ await page.getByRole("button", { name: "save retry after a block" }).click();
+ await expect(page.getByLabel("retry after a block", { exact: true })).toContainText("wait 30 min after a block, up to 12 tries");
+ await expect
+ .poll(async () => (await readJson<{ social?: { xenforo?: unknown } }>(testPaths().settingsFile)).social?.xenforo)
+ .toEqual({ retryOnBlock: { minutes: 30, max: 12 } });
+ await page.getByLabel("retry minutes").fill("2");
+ await page.getByRole("button", { name: "save retry after a block" }).click();
+ await expect(page.getByRole("alert").filter({ hasText: "minutes must be a whole number from 5" })).toBeVisible();
+ await page.getByRole("button", { name: "turn off retry after a block" }).click();
+ await expect(page.getByLabel("retry after a block", { exact: true })).toContainText("Fetch posts: off");
+ await expect
+ .poll(async () => (await readJson<{ social?: { xenforo?: unknown } }>(testPaths().settingsFile)).social?.xenforo)
+ .toBeUndefined();
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -57,6 +57,11 @@ export function waybackOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-wayback-origin");
}
+/** The saved thread pages a slot's forum fetcher reads (forumFixtureLoader.ts; forum-resume.spec). */
+export function forumFixtureDir(transcriptsDir: string): string {
+ return join(transcriptsDir, ".forum-fixture");
+}
+
/** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */
export function umtoolOriginFile(transcriptsDir: string): string {
return join(transcriptsDir, ".fake-umtool-origin");
@@ -218,6 +223,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
// The same for the fake Wayback Machine wayback-pages.spec starts
// (lib/waybackClient.ts: the process's client sends web.archive.org there).
editorEnv.E2E_WAYBACK_ORIGIN_FILE = waybackOriginFile(paths.transcriptsDir);
+ // The forum fetcher's saved pages (forum-resume.spec): the slot's own
+ // directory (common/social/forumFixtureLoader.ts).
+ editorEnv.E2E_FORUM_FIXTURE_DIR = forumFixtureDir(paths.transcriptsDir);
// The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts).
editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir);
// The browser lookup's recorded page reads (browser-lookup.spec): set on
diff --git a/editor/e2e/wayback-live.spec.ts b/editor/e2e/wayback-live.spec.ts
@@ -0,0 +1,146 @@
+// Wayback pages, live (release 37 S5), over the fake Wayback Machine
+// (common/testing/web/fakeWayback.mjs, its Save Page Now block) named to the
+// test server through E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). Neither the
+// real web.archive.org nor any original site is contacted: the originals'
+// verdicts are written to posts-availability.json as the check would.
+//
+// A Wayback pages channel's page shows Originals (checked / gone, the gone
+// table) and Save Page Now: off with its sentence while no archive.org keys
+// are configured; with keys (a mode-600 file the settings name), "Ask the
+// Wayback Machine to capture this now" runs a save-page-now job whose capture
+// is imported into the channel. The ops door answers a dry run.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { chmod, mkdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ startFakeWayback,
+ FAKE_SPN_ACCESS,
+ FAKE_SPN_SECRET,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ SPN_CAPTURE_TS,
+} from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs";
+import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { waybackOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "old-blog-live";
+const LIVE = "https://blog.example/still-up.html";
+
+async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> {
+ let last = { status: "", tail: [] as string[] };
+ await expect
+ .poll(
+ async () => {
+ const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH });
+ const body = (await res.json()) as { job: { status: string }; tail?: string[] };
+ last = { status: body.job.status, tail: body.tail ?? [] };
+ return last.status;
+ },
+ { timeout: 90_000, intervals: [1_000] },
+ )
+ .toMatch(/^(done|failed|cancelled)$/);
+ return last;
+}
+
+test("Originals and Save Page Now on a Wayback pages channel: off without keys, then a capture imported", async ({ page, request }) => {
+ test.setTimeout(180_000);
+ await resetData("empty");
+ const root = resolvePath(testPaths().transcriptsDir);
+ const keyFile = path.join(root, "spn-keys.env");
+ await rm(keyFile, { force: true });
+ await writeSettings({ minFreeDiskGB: 0, archiveOrg: { s3KeyFile: keyFile } });
+ const channelRoot = path.join(root, "channels", SLUG);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify({
+ name: "Old blog (live)",
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ }),
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ const wb = await startFakeWayback();
+ const originFile = waybackOriginFile(root);
+ await writeFile(originFile, wb.base);
+ try {
+ // One record, imported from the fake.
+ const imp = await request.post(`${baseUrl}/api/ops/import-page`, {
+ headers: AUTH,
+ data: { slug: SLUG, url: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` },
+ });
+ const impBody = (await imp.json()) as { jobId?: string; error?: string };
+ expect(imp.status(), impBody.error).toBe(200);
+ expect((await waitForJob(request, impBody.jobId!)).status).toBe("done");
+ const articleId = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL);
+
+ await page.goto(`/channels/${SLUG}`);
+ const originals = page.getByRole("region", { name: "originals" });
+ await expect(originals.getByLabel("originals checked")).toHaveText("0 of 1 original URL checked · 0 gone");
+ await expect(originals.getByRole("button", { name: "Check originals" })).toBeEnabled();
+ // No keys: the button is off and says why; nothing was asked of SPN.
+ const spn = page.getByRole("region", { name: "save page now" });
+ await expect(spn.getByLabel("save page now off")).toContainText("Save Page Now needs archive.org S3 keys");
+ await expect(spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" })).toBeDisabled();
+ const refused = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG } });
+ expect(refused.status()).toBe(400);
+ expect(((await refused.json()) as { error: string }).error).toContain("needs archive.org S3 keys");
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // The original's verdict, as the check writes it: gone — the Wayback copy is the only copy.
+ await writeFile(
+ path.join(channelRoot, "posts-availability.json"),
+ JSON.stringify({ [articleId]: { availability: "deleted", checkedAt: "2026-10-20T10:00:00.000Z", status: 404, reason: "HTTP 404" } }),
+ );
+ // The keys, in a mode-600 file the settings name.
+ await writeFile(keyFile, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\nARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`);
+ await chmod(keyFile, 0o600);
+ await page.reload();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 1 original URL checked · 1 gone");
+ const goneRow = page.locator(`[data-original-gone="${articleId}"]`);
+ await expect(goneRow.getByRole("link", { name: "the only copy" })).toHaveAttribute(
+ "href",
+ `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`,
+ );
+ await expect(goneRow).toContainText("HTTP 404");
+ await expect(spn.getByLabel("save page now off")).toHaveCount(0);
+
+ // A dry run over ops asks nothing.
+ const dry = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG, dryRun: true } });
+ const dryBody = (await dry.json()) as { ok: boolean; wouldAsk?: string };
+ expect(dryBody.ok).toBe(true);
+ expect(dryBody.wouldAsk).toContain(`then import the capture into ${SLUG}`);
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // Ask the Wayback Machine to capture the live page now: the capture, then its import.
+ await spn.getByLabel("page to capture").fill(LIVE);
+ await spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" }).click();
+ const log = page.getByRole("log", { name: `Save Page Now into ${SLUG} output` });
+ await expect(log).toContainText('"ok":true', { timeout: 90_000 });
+ const text = (await log.textContent()) ?? "";
+ expect(text).toContain(`"captureTs":"${SPN_CAPTURE_TS}"`);
+ expect(text).not.toContain(FAKE_SPN_SECRET);
+ const importJobId = /"importJobId":"([^"]+)"/.exec(text)?.[1];
+ expect(importJobId, text).toBeTruthy();
+ expect((await waitForJob(request, importJobId!)).status).toBe("done");
+ expect(wb.spnForms).toEqual([{ url: LIVE, capture_outlinks: "0" }]);
+
+ await page.reload();
+ await expect(page.getByRole("region", { name: "Wayback pages" }).getByLabel("pages held")).toHaveText("2 records from 2 captures");
+ await expect(page.locator(`[data-page-record="${pageRecordId(SPN_CAPTURE_TS, LIVE)}"]`)).toBeVisible();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 2 original URLs checked · 1 gone");
+ } finally {
+ await rm(originFile, { force: true });
+ await rm(keyFile, { force: true });
+ await wb.close();
+ }
+});
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -39,6 +39,11 @@ import { currentSlot } from "./e2e/testPaths";
// into, where the editor's Wayback client then sends
// every web.archive.org request
// (common/lib/waybackClient.ts; wayback-pages.spec)
+// E2E_FORUM_FIXTURE_DIR set per slot (e2e/servers.ts): the directory of
+// SYNTHETIC saved thread pages the forum fetcher
+// reads in place of a browser, with no pause
+// (common/social/forumFixtureLoader.ts;
+// forum-resume.spec)
// E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
// writes its stub umtool's loopback origin into,
// which Find clips then posts to
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -150,6 +150,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async
frames: "api",
// The clip finder's labels (release 36 lane D).
"clips-suggest": "api",
+ // The video assistant (release 38 lane E): api only in the api preset.
+ "video-assist": "api",
},
},
},
@@ -509,3 +511,35 @@ test("generate clips-suggest: a project, not an article; routed to code, the edi
assert.match(b.text, /Nothing in the cut changed/);
assert.equal(done.sentOf("/api/ops/iterations").length, 0);
});
+
+test("generate video-assist: a project and a request (or a note); routed to code, the plan is this session's request; the answer goes back to the editor", async () => {
+ assert.ok(GENERATE_TASKS.includes("video-assist"));
+ assert.match(String((validateGenerateArgs({ task: "video-assist", article: "a" }) as { error: string }).error), /names its project/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p" }) as { error: string }).error), /needs its request/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", note: "n_abcd1234" }) as { error: string }).error), /not both/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", scope: "everything" }) as { error: string }).error), /scope is look, clips, fx or all/);
+ assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", iteration: 2 }) as { error: string }).error), /iteration is not a video-assist job's/);
+ assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", request: "x" }) as { error: string }).error), /a video-assist job's/);
+ const plan = { scope: "all", estimate: { inputTokens: 700 }, request: { system: "You adjust a video project's settings…", user: "THE REQUEST:\nno QR\n\nTHE PROJECT NOW:\n- qr = true" } };
+ const code = editor({ policy: { routes: { ...POLICY.routes, "video-assist": "code" } }, plan });
+ const a = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR" }, code.deps as never);
+ assert.equal(a.isError, undefined, a.text);
+ assert.match(a.text, /^generate video-assist: routed to Claude Code \(preset balanced\) — answer this request on the project in this session \(scope all\)\./);
+ assert.match(a.text, /call generate with task "video-assist", project "\/r\/p", the same request "no QR", answers: \{"ops": \[\.\.\.\], "reply": "\.\.\."\}/);
+ assert.match(a.text, /Never write that file or the manifest yourself/);
+ assert.match(a.text, /- qr = true/);
+ assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", dryRun: true }]);
+
+ const answers = { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." };
+ const done = editor({
+ markerJson: { article: "", iteration: 0, task: "video-assist", project: "/r/p", status: "done", summary: "1 edit proposed (QR code on → off) on claude-code", usd: 0, assist: { proposed: 1, refused: 0, diff: ["QR code on → off"] } },
+ });
+ const b = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR", answers, wait: true }, done.deps as never);
+ assert.equal(b.isError, false, b.text);
+ assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", answers }]);
+ assert.equal(done.sentOf("/api/ops/settings").length, 0, "a session's answer needs no policy read");
+ assert.match(b.text, /^generate video-assist: job job-1 ended \*\*done\*\* — 1 edit proposed \(QR code on → off\) on claude-code/);
+ assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused\n- QR code on → off/);
+ assert.match(b.text, /Nothing in the cut changed/);
+ assert.equal(done.sentOf("/api/ops/iterations").length, 0);
+});
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -237,7 +237,9 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
const task = trimmed(args.task);
if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`);
if (task === CLIPS_SUGGEST) return validateClipsSuggestArgs(args, waitSeconds);
+ if (task === VIDEO_ASSIST) return validateVideoAssistArgs(args, waitSeconds);
if (args.project !== undefined || args.answers !== undefined || args.proposals !== undefined) return bad("project, proposals and answers are a clips-suggest job's");
+ if (args.request !== undefined || args.scope !== undefined || args.note !== undefined) return bad("request, scope and note are a video-assist job's");
const article = trimmed(args.article);
if (!ARTICLE_RE.test(article)) return bad("article is an article id (a lowercase slug: a-z, 0-9, -)");
const body: Body = { task, article };
@@ -340,6 +342,98 @@ function validateClipsSuggestArgs(args: Record<string, unknown>, waitSeconds: nu
return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
}
+// ─── video-assist (release 38 lane E): the video assistant, on a umtool project ───
+
+const VIDEO_ASSIST = "video-assist";
+const NOTE_RE = /^n_[a-z0-9]{4,32}$/;
+
+function validateVideoAssistArgs(args: Record<string, unknown>, waitSeconds: number): { ok: true; request: GenerateRequest } | { ok: false; error: string } {
+ const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` });
+ const project = trimmed(args.project);
+ if (!project.startsWith("/")) return bad("a video-assist job names its project: the video project's absolute directory (project)");
+ for (const k of ["article", "iteration", "copyOf", "question", "channels", "feedback", "from", "to", "cards", "entries", "force", "autonomy", "extractorModel", "proposals"] as const) {
+ if (args[k] !== undefined) return bad(`${k} is not a video-assist job's (it reads its project)`);
+ }
+ const body: Body = { task: VIDEO_ASSIST, project };
+ if (args.request !== undefined) {
+ const r = trimmed(args.request);
+ if (!r) return bad("request is what to change, in words");
+ body.request = r;
+ }
+ if (args.note !== undefined) {
+ const n = trimmed(args.note);
+ if (!NOTE_RE.test(n)) return bad("note is a note id (n_…)");
+ body.note = n;
+ }
+ if (!body.request && !body.note) return bad("a video-assist job needs its request (what to change), or the note whose text is one");
+ if (body.request && body.note) return bad("give request or note, not both");
+ if (args.scope !== undefined) {
+ const sc = trimmed(args.scope);
+ if (!["look", "clips", "fx", "all"].includes(sc)) return bad("scope is look, clips, fx or all");
+ body.scope = sc;
+ }
+ if (args.model !== undefined) {
+ const m = trimmed(args.model);
+ if (!m) return bad("model is text");
+ body.model = m;
+ }
+ if (args.maxUsd !== undefined) {
+ if (typeof args.maxUsd !== "number" || !(args.maxUsd > 0)) return bad("maxUsd is a positive number of dollars");
+ body.maxUsd = args.maxUsd;
+ }
+ if (args.answers !== undefined) {
+ if (!args.answers || typeof args.answers !== "object" || Array.isArray(args.answers)) return bad('answers is {"ops": [{"op", "id", "key", "value"}], "reply"}');
+ if (body.model) return bad("answers are this session's: no model");
+ body.answers = args.answers;
+ }
+ let via: "api" | "local" | undefined;
+ if (args.via !== undefined) {
+ const v = trimmed(args.via);
+ if (v !== "api" && v !== "local") return bad('via is "api" or "local"');
+ if (body.model || body.answers) return bad("give model, via or answers — one");
+ via = v;
+ }
+ if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false");
+ return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
+}
+
+type AssistPlanView = { scope?: string; estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } };
+
+// The `code` route: this session answers the request the editor's plan names.
+export function renderVideoAssistRequest(body: Body, plan: AssistPlanView, preset: string): string {
+ const r = plan.request ?? {};
+ const said = body.note ? `note ${String(body.note)}` : `request ${JSON.stringify(String(body.request ?? ""))}`;
+ return [
+ `generate video-assist: routed to Claude Code (preset ${preset}) — answer this request on the project in this session (scope ${plan.scope ?? "all"}).`,
+ `Read the project's settings below and give the ops that carry out the request, each {"op", "id", "key", "value"}, and a one-sentence reply.`,
+ `Then call generate with task "video-assist", project "${String(body.project)}", the same ${said}${body.scope ? `, scope "${String(body.scope)}"` : ""}, answers: {"ops": [...], "reply": "..."} and wait: true — ` +
+ "the editor checks your ops exactly as a model's (a value outside its bounds is refused, with the reason) and writes assist-proposals.json. " +
+ "They are PROPOSALS: the operator applies them in umtool (the Look panel's Ask box). Never write that file or the manifest yourself.",
+ "",
+ "## The instructions",
+ r.system ?? "",
+ "",
+ "## The project",
+ r.user ?? "",
+ ].join("\n");
+}
+
+type AssistMarker = { project?: string; assist?: { proposed?: number; refused?: number; diff?: string[]; note?: string } };
+
+function videoAssistSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker & AssistMarker): ToolAnswer {
+ const a = m.assist ?? {};
+ const lines = [
+ `generate video-assist: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(),
+ `Project: ${m.project ?? "?"} · ${a.proposed ?? 0} proposed, ${a.refused ?? 0} refused` + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""),
+ ...(a.diff ?? []).map((d) => `- ${d}`),
+ "",
+ "These are proposals in assist-proposals.json: the operator applies them in umtool (the Build tab's Look panel, Ask box: Apply / Dismiss" +
+ (a.note ? `; the reply on note ${a.note} carries an Apply too` : "") +
+ "). Nothing in the cut changed.",
+ ];
+ return { text: lines.join("\n"), isError: f.job.status !== "done" };
+}
+
type SuggestPlanView = {
proposals?: number;
calls?: number;
@@ -574,6 +668,7 @@ async function summarise(
const marker = resultMarkerOf(f.tail);
if (marker?.task === "verdicts") return verdictsSummary(f, marker);
if (marker?.task === CLIPS_SUGGEST) return clipsSuggestSummary(f, marker);
+ if (marker?.task === VIDEO_ASSIST) return videoAssistSummary(f, marker as Marker & AssistMarker);
const article = marker?.article ?? hint.article;
const n = marker?.iteration ?? hint.iteration;
const task = marker?.task ?? hint.task ?? "report-draft";
@@ -662,6 +757,11 @@ export async function generateTool(
const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true });
if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true };
return { text: renderClipsSuggestRequest(String(body.project), (plan.body.plan ?? {}) as SuggestPlanView, p.preset) };
+ } else if (task === VIDEO_ASSIST && body.answers === undefined && p.routes[task] === "code") {
+ // The session answers it: the editor's plan is the request.
+ const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true });
+ if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true };
+ return { text: renderVideoAssistRequest(body, (plan.body.plan ?? {}) as AssistPlanView, p.preset) };
} else if (task === "verdicts" && p.routes[task] === "code") {
// Verdicts are not a session's to make: the bench's bar names the models.
return {
@@ -688,7 +788,7 @@ export async function generateTool(
const jobId = typeof a.body.jobId === "string" ? a.body.jobId : "";
const n = typeof a.body.iteration === "number" ? a.body.iteration : undefined;
if (!jobId) return { text: `generate: the editor accepted it and started no job (${JSON.stringify(a.body)})`, isError: true };
- const article = task === CLIPS_SUGGEST ? "" : String(body.article);
+ const article = task === CLIPS_SUGGEST || task === VIDEO_ASSIST ? "" : String(body.article);
const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : [];
const head =
`generate ${task}: queued as job ${jobId}` +
@@ -800,12 +900,20 @@ export const GENERATION_TOOLS = [
project: {
type: "string",
description:
- "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers.",
+ "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist: the video project's absolute directory (its video.manifest.json).",
},
proposals: { type: "array", items: { type: "string" }, description: "clips-suggest: only these proposal ids." },
+ request: {
+ type: "string",
+ description:
+ 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers.',
+ },
+ scope: { type: "string", enum: ["look", "clips", "fx", "all"], description: "video-assist: what the ask may touch (default all)." },
+ note: { type: "string", description: "video-assist: a note on the whole project (n_…) whose text is the request; the proposals are posted to it as the agent's reply." },
answers: {
type: "object",
- description: 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]} — read as a model\'s answer, written by the editor.',
+ description:
+ 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"} — read as a model\'s answer, written by the editor.',
},
wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." },
wait_seconds: {
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11247,3 +11247,138 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
action: "archive"|"never"|"restore", name?, fetch?, dryRun?}`; MCP `x_search_leads {channel, limit?}`
(`mcp/src/xSearchLeads.ts`, read only, through the editor). The e2e fake gallery-dl answers a `/search` URL with
four posts by three accounts dated 2026-05/06, bounded by the query's since/until/max_id.
+
+## Release 37 lane E: liveness, Save Page Now, find-copy for pages (verified 2026-10-20, branch `r37/live`)
+
+- **A page record's availability is its ORIGINAL URL's**, never the Wayback Machine's: `checkPostAvailability`
+ branches on `isWaybackPagesChannel` to `controller/checkPageAvailability.ts` (no fetcher needed). One request per
+ distinct `page.originalUrl` (`groupByOriginalUrl`); every record sharing it gets the verdict; `limit` counts URLs;
+ `stale` orders URLs by the OLDEST check among their records. The request side is
+ `lib/waybackPages/liveness-server.ts` `checkOriginalUrl`: through `webPacer` (3 s gap, 429/503 backed off), behind
+ `fetchRefusal` (the web fetch's private-host fence) on every hop, HEAD with manual redirects (≤ 5), a GET instead
+ when the HEAD answers 403/405/501 or when the final host has a gone-page marker (body read to 256 KB). Verdicts
+ (`lib/waybackPages/liveness.ts`): 404/410 `deleted`; 2xx on the same site (`sameSite`: www, http→https, same
+ registrable domain, two-label suffixes, twitter.com≡x.com, youtu.be≡youtube.com) `available` unless a
+ `PAGE_GONE_MARKERS` row matches the folded text; a 2xx after a redirect to another site, any other status, no
+ answer or a fence refusal `error`. Marker rows: X no-account / no-page (`deleted`), X suspended
+ (`account_unavailable`), Tumblr "There's nothing here" (`deleted`), Google Docs "file … does not exist"
+ (`deleted`) / "You need access|permission" (`account_unavailable`), YouTube "This channel does not exist"
+ (`deleted`) / terminated (`account_unavailable`) — each on its own hosts only.
+- **`posts-availability.json` records gained `status?: number | null` and `reason?: string`** (the latest answer;
+ `readPostAvailability` keeps them; `mergePostAvailability(existing, obs, at, details?)` — the 4th arg optional).
+ History is still appended only on a change. The index's `isDeleted` comes from `deleted` as for every post.
+ `PAGE_ORIGINAL_GONE_LABEL` ("Original gone — the Wayback Machine copy is the only copy") is exported from
+ `liveness.ts` for the citation surfaces; nothing renders it yet.
+- **Save Page Now** (`controller/savePageNow.ts`, job kind `save-page-now`, queue `platform:archive.org`, not
+ drainable/replayable): SPN2 `POST https://web.archive.org/save` (`url`, `capture_outlinks=0`, `Authorization: LOW
+ <access>:<secret>`) → `job_id`; `GET /save/status/<job_id>` every `SPN_POLL_MS` 10 s, at most `SPN_MAX_POLLS` 30;
+ success → `waybackPageUrl(timestamp, original_url)` and, with a slug, `startImportPageJob` (an import-page job
+ queued behind it; a refused import is `importError`, the capture stands). Requests go through
+ `WaybackClient.send` → `ArchiveOrgClient.send` (new: any method, same chain/gap/retry; a non-retryable status is
+ handed back with its body). Keys (`lib/waybackPages/savePageNow-server.ts` `readSpnKeys`): env
+ `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` (both), else the mode-600 file `settings.archiveOrg.s3KeyFile`
+ (default `~/.config/archilyzer/archive-org.env`, lines `ARCHIVE_ORG_S3_ACCESS=` / `ARCHIVE_ORG_S3_SECRET=`); a
+ group/other-readable file is refused; a settings value that is not a path is refused (`looksLikeS3Key`, also in
+ `/api/ops/settings`). `redactSpnKeys` runs on every log line and error. Lane B's door: `startSavePageNowJob({url,
+ slug?})` (throws `SavePageNowRefusal`).
+- **find-copy, page mode** (`publish/findCopyPages.ts`, ops `find-copy` with `pages: true`, a `find-copy` job on
+ `platform:archive.org`): `page` citations (grouped by URL) → `checkOriginalUrl` → gone (`deleted` |
+ `account_unavailable`) → the channel named or `channelsCovering` (a target's exact/prefix/host/domain over the
+ URL, `targetCoversUrl`) → held (the channel already has a record of the URL: no fetch) or `closestCapture(url,
+ captureAtOf(citation))` (its `date`, else its archiveUrl's timestamp, else today) → `importPage` inline (the run is
+ on the archive.org queue). `post` citations of a pages channel's record whose availability is gone: held when
+ `hasStoredCapture`, else its capture imported again. Each item carries `pointTo {channel, id}` (the record whose
+ text holds the quote, else the first) and `as` (the page citation as a `post` citation: `pageCitationAsPost`).
+ **The report is never rewritten here** (lane D's Import-this-capture owns rewriting with a fallback). `max`
+ default 10, at most 100.
+- **The fake** (`testing/web/fakeWayback.mjs`, lane E block): `POST /save` (keys `FAKE_SPN_ACCESS` /
+ `FAKE_SPN_SECRET`, `spn.busyTimes` 429s, `spn.refuseUrls`), `GET /save/status/<id>` (`spn.pendingPolls`, then
+ success at `SPN_CAPTURE_TS`, or `spn.failUrls` → error:not-found); a saved page is then served raw like a page
+ capture; `wb.spnForms`, `wb.spnCaptures`; `requests[].method`.
+- New ops: `check-post-availability {slug, mode?, limit?}` (any posts channel), `save-page-now {url, slug?,
+ dryRun?}`. UI: `components/WaybackLivePanel.tsx` under the pages panel (Check originals, the gone table, Save Page
+ Now field + per-live-record Capture now; off with `spnOffSentence` when no keys).
+
+## Release 37 lane G: a forum thread's two walks (verified 2026-10-20, branch `r37/forum-resume`)
+
+- **State**: `posts-state.json` `forum` (`ForumWalkState`, `common/lib/forumWalk.ts`, pure):
+ `{newestPage, newestPostId, catchUpPage?, historyPage?, oldestPageReached, complete?}`. A forum fetch no longer
+ writes `cursor`; an old state's `cursor` is read ONCE as `historyPage` (then healed, below) and the next state
+ write drops it (`fetchTimeline` builds the state fresh each run; `older` is carried as before).
+- **The mark** is `newestPostId`: a CATCH-UP (from the last page down) ends at the first page holding an archived
+ post whose numeric id is ≤ the mark (XenForo post ids grow globally). With no mark (a pre-release-37 state), any
+ archived non-repeated post ends it, as before. A completed catch-up sets the mark to the highest id read this run.
+ A capped/interrupted catch-up writes `catchUpPage` (its next page) and never touches `historyPage` or the mark;
+ the next catch-up, meeting an all-held page above the mark, jumps to `catchUpPage` when it is below.
+- **History** reads `historyPage` down to page 1, writes only `historyPage` (`complete` at page 1). A first run
+ (nothing archived: `seenIds.size === 0`) is one history walk from the last page; it sets the mark from its top.
+- **An empty page is loaded once more** before the walk stops on it (`Page N: no posts on the first read …;
+ loading it again.`): just after a browser check clears, the page standing is often not the thread page yet.
+- **All-held pages** (every non-repeated post archived, nothing new) never count against `pages`/`limit`, in the
+ catch-up or the history; they log `Page N: all held, skipping on.` A full re-walk counts every page.
+- **Derive, don't trust** (`deriveForumWalk`, run by `fetchPosts` and by the channel page): the held BAND is the
+ contiguous run of `forum.page` values down from the highest held page (an isolated page 1 — an article thread's
+ starter — or an imported range is not part of it); `historyPage = min(stored, band.low + 1)`. NOT `band.low − 2`:
+ drift only moves posts to LOWER page numbers, so a start below `band.low − 1` could step over an unread page;
+ starting one above the foot re-reads held pages, uncounted. `band.low ≤ 1` ⇒ `complete`; `complete` with
+ `band.low > 1` is reopened. Live `kf-oney-thread` at 2026-10-20 (`{"cursor": "2507"}`, held 2341–2598, no gaps):
+ migrates to `historyPage 2342`.
+- **Full re-walk** (`full: true`, `stopAtKnown: false`): every page, archived posts handed back and UPSERTED with
+ `upsertPosts(…, {ignorePosition: true})` (a renumbered `#N` alone is not an edit); a complete one returns
+ `notSeen` (archived ids on no page), LOGGED, never marked. It leaves the mark at the run's top, clears
+ `catchUpPage`, `historyPage = min(stored, next)`.
+- **Retry on a block**: `fetchPosts({retryOnBlock: {minutes, max}, sleep?})` re-runs the whole timeline fetch after
+ `minutes` when the result's `block` is `"challenge"` or `"blocked"` (403/429); `max` is tries IN ALL; minutes
+ 5–1440, max 1–48 (`retryOnBlockProblem`). `PostFetchResult.block` carries the `ForumBlockKind`. Default for the
+ forum Fetch posts button: `settings.social.xenforo.retryOnBlock` (absent = off; the button passes `"settings"`,
+ ops `true`). `saveSettings` merges `social` one level deep (`{...old.social, ...patch.social}`), so turning it
+ off writes `xenforo: undefined`, which JSON drops.
+- **Test seam**: `E2E_FORUM_FIXTURE_DIR` (test audience) makes `xenforoFetcher.fetch` read
+ `<dir>/<threadId>/page-<N>.html` (`page-<N>.<status>.html` served in its place while it exists) with no pause
+ (`common/social/forumFixtureLoader.ts`); `editor/e2e/servers.ts` sets it per slot to `test-transcripts/.forum-fixture`.
+ `common/social/__fixtures__/fakeForumThread.ts` is a thread that grows, loses posts and writes those pages.
+
+## Release 38 lane E: the video assistant — look rules, ops, proposals, join preview (verified 2026-10-20, branch `r38/video-assist`)
+
+- **The look's rules live in common now**: `common/lib/report/look.mjs` holds `LOOK_KEYS`, `applyLookPatch(manifest,
+ patch) → {render, errors}` (what umtool's `updateRender` writes with), `lookErrors`, and the validators that were in
+ report-to-video — `validateTransitionStyle`/`validateSlide` (+ `TRANSITION_STYLES`, `SLIDE_DEFAULTS`, `SLIDE_BOUNDS`,
+ now exported), `validateRoom`/`clipRoom`/`roomOn` (+ `ROOM`, `ROOM_EDGES`, `ROOM_BOUNDS` {minGap [0.1,2], maxS
+ [0,10]}), `validateCaptions`/`validateLoudness`/`verticalErrors`/`validateVertical`/`validateLook` and their
+ constants. `report-to-video/{look,room,transition}.mjs` RE-EXPORT every moved name, so no importer changed; umtool
+ `lib/report/manifest.mjs` re-exports `LOOK_KEYS` and `lookOf`. Moved, not copied: the editor (which cannot import
+ umtool) checks a proposed look op with the writer's own function.
+- **Composition params** (`common/lib/report/fxParams.mjs`): `COMPOSITION_PARAMS[id]` for `deck`
+ (`render.chrome.deck`), `stats`, `fx.<effect>` — `{key (dot path in the settings), label, kind
+ (seconds|number|int|px|enum|bool|text), min/max | values | maxLength, default}`. `deck.mjs` `DECK_PARAMS`,
+ `stats.mjs` `STATS_PARAMS`, `fx.mjs` `FX_PARAMS` (by effect) are the slices. `report-to-video/fx-params.test.mjs`
+ holds every declaration to `validateChrome` at its bounds and just past them. Layout-coupled settings (deck height,
+ footageScale, qr.size, pip sizes) are NOT declared.
+- **The ops** (`common/lib/report/videoAssistOps.mjs`): `look | slide | room | clip_edges | clip_room | fx`. The
+ model writes ONE shape `{op, id, key, value}` (`ASSIST_OPS_SCHEMA`: four required keys an op — a strict tool requires
+ every key); `normalizeAssistOp` turns it into the checker's (`{op:"slide", blur:0.3}`). `checkAssistOps(manifest,
+ ops, {request, scope}) → {ops: [{op, diff, apply, warning?}], refused: [{index, op, why}], diff, manifest}` applies
+ each op to a COPY in turn. `apply` = `{writer: "render", patch}` | `{writer: "clip", body}` (runClipEditorOp
+ `trim`/`room`) | `{writer: "chrome", id, param, value}`. A clip's window: its extent (start–end) when it has a cut,
+ else its edges ± `render.fetchPad` (0 when absent); an edge moves ≤ 3 s (`EDGE_SLACK_SECONDS`) unless the request
+ names more seconds (`secondsNamedIn`: "6 seconds", "2.5 s"). A room op's numeric `tail` = tail on + `maxS`.
+- **`<project>/assist-proposals.json`** (`common/lib/report/videoAssistProposals.mjs`): `{version: 1, promptVersion:
+ "video-assist-1", at, model, request, scope, note?, reply?, ops: [{id: "a<n>", op, diff, warning?, status:
+ proposed|applied|dismissed|failed, at?, error?}], refused: [{op, why}], diff}`. Written whole by the editor's task (a
+ new ask replaces it); statuses marked by umtool (`lib/report/videoAssist.mjs` `applyAssistOps`/`dismissAssistOps`).
+ Never applied by being there. umtool's own `.video-assist-job.json` is the followed job.
+- **Task `video-assist`** (`GENERATION_TASKS`; presets: `local` in code/balanced/local, `api` in api — the `code`
+ preset routes it LOCAL). `report-draft` body: `project` (absolute), `request` | `note` (a `whole`-anchored note's
+ text), `scope` (look|clips|fx|all), `answers` (code route), `dryRun` (the ops route: `planVideoAssistJob`). Its own
+ job (`common/controller/videoAssist.ts`), `draft:local` / `draft:api`, narration cap, ledger task `video-assist`;
+ marker `{article: "", iteration: 0, task: "video-assist", project, status, summary, usd, assist: {at, proposed,
+ refused, diff, file, note?}}`. A note's reply is posted to umtool's notes with proposal `{kind: "assist", at, ops}`
+ (a new `ReplyProposal` kind; umtool `lib/annotations/shape.mjs`).
+- **`videoOps.ts`** (revise-video) gained `look`, `slide`, `room` (through `checkAssistOps`, scope look);
+ `VIDEO_OPS_SCHEMA` = `OPS_SCHEMA` + `key`/`value`; `localOpsBatch` takes an optional `schema`.
+- **Join preview**: `build-video.mjs <manifest> --join-preview [--join-from <clip>]` → `out/join-preview.mp4` +
+ `out/join-preview.json` (`{version, madeAt, clips, look}`), work in `out/join-preview-work/`; no chapters, YouTube
+ text or thumbnail; in the heavy slot (`takesHeavySlot`). `report-to-video/join-preview.mjs`
+ `joinPreviewTimeline`: 4 consecutive clips, each the last 3 s of its cut (the last clip its first 3 s), cards out,
+ windows untouched; refused for a deck, a montage, hard cuts. umtool `/api/report/join-preview` (a `join preview
+ <project>` job on lib/jobs.ts).
diff --git a/plans/release-37/forum-resume.md b/plans/release-37/forum-resume.md
@@ -0,0 +1,131 @@
+# Release 37 lane G — `r37/forum-resume`: a forum walk that resumes, never re-crawls (as shipped)
+
+The operator, 2026-10-20: "change the walk to track the last page and be able to resume rather than always
+re-crawling, even if things could change. We can have two buttons like a channel's sync and full fetch." The bug seen
+live: a run capped with `pages: 3` caught up the 3 newest pages and stored its catch-up position as THE cursor,
+replacing the history cursor (2340 → 2593), and the next run re-read ~250 held pages in history mode. One cursor
+served two walks. Rulings followed: no model anywhere; every operation has a button (Fetch posts, Full re-walk, Retry
+after a block); polite (the walk's pace is unchanged, a retry waits minutes, never sooner); synthetic fixtures only
+(no real forum, no network — a saved-pages directory and a fake thread); commits end with the one Co-Authored-By
+trailer.
+
+## What
+
+1. **Two positions** — `posts-state.json` `forum` (`ForumWalkState`, `common/lib/forumWalk.ts`, pure):
+ `{newestPage, newestPostId, catchUpPage?, historyPage?, oldestPageReached, complete?}`. `newestPostId` is the
+ MARK: a catch-up ends at the first page holding an archived post with id ≤ it. A capped or interrupted catch-up
+ writes only `catchUpPage` (its next page); the history walk writes only `historyPage`. A forum fetch writes no
+ `cursor`; an old one is read once as the history position and dropped.
+2. **Derive, don't trust** — `deriveForumWalk(stored, legacyCursor, heldPages)`, run at the start of every fetch and
+ by the channel page: the held band is the contiguous run of archived `forum.page`s down from the highest;
+ `historyPage = min(stored, band.low + 1)`; page 1 held ⇒ complete; complete with the band above page 1 ⇒ reopened.
+ Each change is a log line. (`+1`, not the brief's `− 2`: see "Decisions".)
+3. **The walk** (`walkXenforoThread`, `common/social/xenforoFetcher.ts`) — three modes from the last page:
+ catch-up (to the mark, then a jump to `historyPage`, never re-reading the band between; meeting the pages an
+ earlier capped catch-up read, a jump to its `catchUpPage`), history (to page 1; archived posts mean nothing), full
+ (every page; archived posts handed back for their edits). A page whose posts are all archived never counts
+ against `pages`/`limit` (except in a full re-walk) and logs "Page N: all held, skipping on." Every checkpoint
+ carries the positions it leaves. A first run (nothing archived) is one history walk from the last page. The
+ start line says both positions ("caught up to page 2600; history resumes at page 2338"). The watermark (`since`)
+ is gone from the forum walk: after a capped catch-up it would stop the next one above the band still owed.
+4. **Two buttons** — the forum channel page's **Fetch posts** (catch up + continue history; "Latest N pages" caps
+ it) and **Full re-walk** (`full: true`; it replaces "Re-fetch full history" on a forum channel; an inline confirm
+ names the page count and the time at the channel's pace, `meanPagePauseSeconds` = 1.25 × the base pause). A full
+ re-walk upserts with `ignorePosition` (a renumbered `#N` is not an edit) and logs the archived posts no page
+ showed (`notSeen`), never marking them. A status line: "pages read 2338–2600 of 2600 · history to page 1
+ remaining: 2337 pages (~9.7 h)", plus "catch-up unfinished at page N" while one is owed.
+5. **Retry on a block** — `fetch-posts {retryOnBlock: {minutes, max}}`: a challenge or refusal (403/429) stops the
+ walk with `PostFetchResult.block`; the controller waits `minutes` (log: "Waiting 30 min after a challenge page,
+ try 2/12."), re-reads the state and runs again, `max` tries in all; never a captcha or a login; minutes 5–1440,
+ max 1–48; a cancel ends the wait, a drain ends it as a drained success. The default for the forum Fetch posts
+ button is `settings.social.xenforo.retryOnBlock` (off unless set), set on the channel page (Forum session →
+ **Retry after a block**: minutes, tries, Save, Turn off). Ops: `"retryOnBlock": {…}` or `true` (the setting);
+ CLI: `--retry-minutes N --retry-tries M` or `--retry-on-block`. The scheduler's unattended fetch never retries.
+6. **An empty page is read again, once** (the orchestrator's live finding, 2026-10-20: "The browser check cleared
+ in 12 s. → Page 2193/2606: 0 post(s) parsed … → [error] Page 2193 of the thread parsed to no posts"): right after
+ a browser check clears, the page standing is often not the thread page yet. A page that parses to no posts is
+ loaded once more (paced like any load; logged "Page N: no posts on the first read after the browser check
+ cleared; loading it again."); only a second empty read stops the walk, as before.
+7. **Test seam** — `E2E_FORUM_FIXTURE_DIR` (test audience, ENVIRONMENT.md): the forum fetcher reads
+ `<dir>/<threadId>/page-<N>.html` (and `page-<N>.<status>.html` in its place while it exists) with no pause
+ (`common/social/forumFixtureLoader.ts`); the e2e server sets it per slot (`e2e/servers.ts`) to `test-transcripts/.forum-fixture`.
+ `common/social/__fixtures__/fakeForumThread.ts`: a synthetic thread that grows, loses posts and writes its pages.
+
+## Files
+
+`common/lib/forumWalk.ts` (+ test), `common/social/xenforoFetcher.ts` (+ test), `common/social/forumFixtureLoader.ts`,
+`common/social/__fixtures__/fakeForumThread.ts`, `common/controller/fetchPosts.ts` (`fetchTimeline`, the retry loop,
+`sleepOrStop`), `common/controller/fetchForumPosts.test.ts`, `common/social/fetchers.ts` (additive:
+`PostFetchInput.forumWalk`, the checkpoint's `forumWalk`, `PostFetchResult.{forumWalk, block, notSeen}`),
+`common/lib/posts-server.ts` (`PostFetchState.forum`; `upsertPosts`/`supersedesPost` `ignorePosition`),
+`common/social/xCookieSource.ts` + `common/lib/settingsSchema.ts` + `settingsDocs.ts` (`social.xenforo`),
+`common/lib/envVars.ts`, `common/bin/fetch-posts.ts`, `common/bin/archilyzer.ts`, `scripts/archilyzer-ops.mjs`,
+`editor/app/channels/[slug]/{socialActions.ts, page.tsx, components/SocialChannelPanel.tsx}`,
+`editor/app/api/ops/fetch-posts/route.ts`, `editor/app/jobs/jobReplayRegistry.ts`,
+`editor/e2e/servers.ts` + `editor/playwright.config.ts`,
+`editor/e2e/forum-resume.spec.ts`; docs OPERATING.md, COMMANDS.md, SETTINGS.md, settings.json.example,
+ENVIRONMENT.md, FACTS ("Release 37 lane G"), CHANGELOG.
+
+## Interfaces
+
+- `ForumWalkState`, `deriveForumWalk`, `heldBand`, `forumWalkStartLine`, `describeForumWalk`,
+ `meanPagePauseSeconds`, `roughDuration`, `FORUM_HISTORY_OVERLAP`, `FORUM_DEFAULT_PAGE_PAUSE_SECONDS`,
+ `FORUM_MIN_PAGE_PAUSE_SECONDS`, `RetryOnBlock`, `retryOnBlockProblem`, `parseRetryOnBlock`,
+ `describeRetryOnBlock`, `RETRY_MIN_MINUTES`/`RETRY_MAX_MINUTES`/`RETRY_MAX_TRIES` (lib/forumWalk.ts).
+- `fetchPosts({…, retryOnBlock?, sleep?})` → `FetchPostsResult.{updated?, block?}`; `sleepOrStop`,
+ `RETRY_AND_OLDER_REFUSAL` (controller/fetchPosts.ts).
+- `fetchPostsAction(…, from?, retryOnBlock?: RetryOnBlock | "settings")`, `setForumRetryOnBlockAction(retry | null)`.
+- `fixtureForumLoader`, `forumFixtureDir`; `FakeForumThread`, `FAKE_THREAD_ID`.
+
+## Gates
+
+All through the session lock (`r31-locked.sh` / `r31-locked6.sh`), from the worktree root.
+
+| Gate | Base (main b8458892) | Branch (after merging main 1f440480) |
+|---|---|---|
+| `pnpm -r exec tsc --noEmit` | clean | clean (at 75482416, 8f63b988, 6cec4dd0) |
+| common `pnpm --filter yt-dlp-transcript-common test` | 4764 tests | 4821 tests, 4819 pass, 0 fail, 2 skipped (at 8f63b988; main's lanes B+E add their own) |
+| lane G unit files (xenforoFetcher, forumWalk, fetchForumPosts, envVars, settingsSchema, settingsDocs) | — | 80/80 |
+| editor `pnpm --filter editor test` | 356 | 357/357 |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | — | 379/379 |
+| `pnpm run test:scripts` | 1316 (1312 pass, 4 skipped) | 1317 (1313 pass, 0 fail, 4 skipped) |
+| `docs env / cli / files --check`, `settings example --check` | — | all 0 (ENVIRONMENT.md, COMMANDS.md, SETTINGS.md regenerated; settings.json.example unchanged) |
+| e2e `forum-resume.spec.ts` + `social-channel.spec.ts` (start mode, build 43 s) | — | 7 passed, 0 failed, 1.8 min (run 3; run 1 failed on a getByLabel substring match, run 2 on Turn off not removing the key — both fixed) |
+
+New tests: `lib/forumWalk.test.ts` (5), `controller/fetchForumPosts.test.ts` (6, through the real fetcher over saved
+pages), `social/xenforoFetcher.test.ts` +7 (capped catch-up keeps history, drift reaches page 1 with no gap, all-held
+pages uncounted, a lost position heals, the mark stops the catch-up, empty page reloaded once / after a check, full
+re-walk hands archived posts back and counts `notSeen`), `e2e/forum-resume.spec.ts` (the two buttons, the confirm,
+the status line, Retry after a block).
+
+## Decisions
+
+- **The derived history start is `band.low + 1`, not `lowest − 2`.** Drift only moves posts to LOWER page numbers
+ (a deletion shifts every later post back), so the unread posts below a page read earlier are still on pages ≤ the
+ page below it. Starting at `lowest − 2` skips page `lowest − 1` outright when nothing was deleted — a gap. Starting
+ `OVERLAP − 1` pages above the band's foot re-reads one or two held pages (all held, uncounted) and can never step
+ over an unread page. `min(stored, …)` keeps an honest stored position.
+- **The band is contiguous from the top** (no holes tolerated): an article thread's starter (stored with page 1)
+ or a range imported from saved pages far below would otherwise pull the history start down past pages never
+ read. A drift hole only makes the derived start higher — more uncounted re-reading, never a gap.
+- **A mark and a catch-up position**, beyond the brief's list: without `catchUpPage`, a capped catch-up leaves the
+ band between its foot and the old top owed, and the next catch-up (stopping at any archived post) would skip it;
+ with the mark alone, every capped run re-reads the partial top band. Both are additive keys.
+- **All-held pages are uncounted in the catch-up too** (one rule): a 1-page run whose last page holds nothing new
+ reads its one counted page from the history.
+- **Full re-walk is not resumable as such**: interrupted, its positions say what it covered (mark at its top,
+ `historyPage = min(stored, next)`), and Fetch posts continues from there.
+- **Deletions are counted, not marked**: a page the parser misread would otherwise mark live posts deleted.
+- **`max` is tries in all** (so "try 2/12" is the first retry); minutes ≥ 5.
+- **Retry only from the button and explicit callers**: the scheduler's fetch never waits hours on a lane.
+- **The e2e reads a saved-pages directory through an env seam** rather than a browser at an `.example` host.
+
+## Live migration (kf-oney-thread)
+
+State at 2026-10-20 (orchestrator's notes): `{"cursor":"2280","lastError":null}`, then — after the live run stopped
+on the empty page after a browser check (item 6) — `{"cursor":"2193"}`, later `{"cursor":"2143"}` and moving down; posts holding `forum.page` contiguously
+down to ~2194, the thread's last page ~2606. The first fetch after the restart: `deriveForumWalk` reads `cursor
+2193` as the history position ("Read the old single resume point (page 2193) as the history position."), checks it
+against the band (foot ~2194 → at most 2195): it stays 2193 (or heals down to `foot + 1` were the cursor above). No mark yet, so the catch-up runs from ~2602 down to the first page holding any archived post (as before),
+sets the mark to the newest post read, then jumps to page 2280 and continues the history. The state written has
+`forum` and no `cursor`. Nothing on disk needs changing by hand.
diff --git a/plans/release-37/live.md b/plans/release-37/live.md
@@ -0,0 +1,128 @@
+# Release 37 lane E — `r37/live`: liveness and saving what is still up (as shipped)
+
+The plan of record is [`wayback-pages.md`](wayback-pages.md) ("S5"). A page record (lane A) is a capture of a page;
+this lane answers whether the page's ORIGINAL is still up — when it is not, the Wayback copy is the only copy — asks
+the Wayback Machine to capture a page that is still up (Save Page Now), and teaches find-copy to find a copy of a
+gone page a report cites. Rulings followed: no model anywhere; every operation has a button (Check originals, Ask the
+Wayback Machine to capture this now, Capture now per live record) and an ops action; every archive.org request goes
+through the polite Wayback client on the `platform:archive.org` queue, every original-site request through the
+editor's web pacer — never a burst, never the Wayback Machine for liveness; synthetic fixtures only (the fake
+Wayback's new SPN block, stub original sites); the S3 keys are never a setting value, never logged; commits end with
+the one Co-Authored-By trailer.
+
+## What
+
+1. **Availability of a page record = its original URL's** (`controller/checkPageAvailability.ts`, reached from
+ `checkPostAvailability` for a Wayback pages channel). One request per distinct original URL (a split capture's
+ records and a page's versions share it), every record of it gets the verdict; `limit` counts URLs; `stale` orders
+ by the oldest check among a URL's records. The request (`lib/waybackPages/liveness-server.ts`
+ `checkOriginalUrl`): through `webPacer`, the web fetch's fence on every hop, HEAD with redirects followed by hand
+ (≤ 5), a GET when the HEAD is refused (403/405/501) or the platform has a "gone" page (body to 256 KB). The verdict
+ (`lib/waybackPages/liveness.ts`): `deleted` (404/410, or a `PAGE_GONE_MARKERS` row — X's "This account doesn't
+ exist" / "this page doesn't exist", Tumblr's "There's nothing here", Google Docs' "Sorry, the file you have
+ requested does not exist", YouTube's "This channel does not exist"), `account_unavailable` (X suspended, a Doc
+ not shared, a terminated YouTube account), `available` (2xx after redirects on the same site), `error` otherwise
+ with the status. Stored in `posts-availability.json` with the answer's `status` and `reason` (additive fields);
+ the index's `isDeleted` follows as for any post. The channel page's **Originals** (Check originals, "N of M
+ original URLs checked · K gone", the gone table with "the only copy" → the Wayback copy); ops
+ `check-post-availability` (new door, any posts channel); the CLI `archilyzer posts check` reaches the same branch.
+2. **Save Page Now** (`controller/savePageNow.ts`, `lib/waybackPages/savePageNow{,-server}.ts`): job kind
+ `save-page-now` on `platform:archive.org`: SPN2 `POST /save` (`url`, `capture_outlinks=0`, `Authorization: LOW
+ <access>:<secret>`), status polled every 10 s (≤ 30), then with a slug an `import-page` job of the capture
+ (`startImportPageJob`). Keys: `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the environment, else the
+ mode-600 file the new setting `archiveOrg.s3KeyFile` names (default `~/.config/archilyzer/archive-org.env`);
+ refused when others can read it; a settings value that is not a path is refused (also by `/api/ops/settings`,
+ without echoing it); `redactSpnKeys` over every log line and error. Refused before any request: no keys (the
+ button is off with that sentence), not http(s), a Wayback URL, not a pages channel, a video, X while private.
+ Requests through `WaybackClient.send` → `ArchiveOrgClient.send` (new: any method, same chain, gap and retry; a
+ non-retryable status handed back with its body). UI: the channel page's **Save Page Now** field ("Ask the Wayback
+ Machine to capture this now", also the plain field for a scan target's URL) and **Capture now** on each record
+ whose original answered. Ops `save-page-now {url, slug?, dryRun?}`. Lane B's door: `startSavePageNowJob({url,
+ slug?})`.
+3. **find-copy, page mode** (`publish/findCopyPages.ts`; ops `find-copy` with `"pages": true`, `channel?`, `max?`,
+ `dryRun?`; one `find-copy` job on `platform:archive.org`): every `page` citation (grouped by URL) whose original is
+ gone → the channel named or the one whose targets cover it (`targetCoversUrl`) → held (a record of the URL is
+ already there) or the capture nearest the citation's date (`captureAtOf`: its date, else its archiveUrl's
+ timestamp, else today) via ONE `closestCapture`, imported inline (`importPage`); a cited page record whose
+ original is gone: held when its capture is stored, else imported again. Live pages are left ("save it now"), an
+ uncovered page is `no-channel`, a never-captured one `none-found`, a check that failed `error`. Each item names
+ `pointTo` (the record whose text holds the quote, else the first) and `as` (the page citation as a post
+ citation). Dry run: the same paced questions, nothing imported.
+4. **The fake** (`testing/web/fakeWayback.mjs`, its own block): SPN `POST /save` and `GET /save/status/<id>`
+ (pending → success, 401 on wrong keys, 429s, refused and failed URLs), the saved page served raw afterwards,
+ `wb.spnForms` / `wb.spnCaptures`, `requests[].method`.
+
+## Interfaces
+
+- `lib/waybackPages/liveness.ts`: `PAGE_GONE_MARKERS`, `pageGoneMarker`, `hasGoneMarkers`, `foldPageText`,
+ `classifyOriginalAnswer`, `sameSite`, `siteOf`, `bareHost`, `groupByOriginalUrl`, `OriginalCheck`,
+ `PAGE_ORIGINAL_GONE_LABEL`. `liveness-server.ts`: `checkOriginalUrl(url, {pacer?, resolve?, allowPrivate?,
+ signal?})`, `LIVENESS_MAX_BODY_BYTES`.
+- `controller/checkPageAvailability.ts`: `checkPageAvailability`, `selectUrlsToCheck`.
+ `CheckPostAvailabilityOptions.pageCheck?` (tests).
+- `posts.ts` `PostAvailabilityRecord.status?` / `reason?`; `posts-server.ts` `mergePostAvailability(…, details?)`.
+- `lib/waybackPages/savePageNow.ts`: `SPN_SAVE_URL`, `spnStatusUrl`, `spnSaveBody`, `spnAuthorization`,
+ `parseSpnSubmit`, `parseSpnStatus`, `spnOffSentence`, `SpnKeys`. `savePageNow-server.ts`: `readSpnKeys`,
+ `redactSpnKeys`.
+- `controller/savePageNow.ts`: `planSavePageNow`, `savePageNow`, `queueSavePageNow`, **`startSavePageNowJob({url,
+ slug?, requestedBy?, paths?}) → {jobId}`** (throws `SavePageNowRefusal`), `savePageNowAvailability()`,
+ `SAVE_PAGE_NOW_JOB_KIND`, `SAVE_PAGE_NOW_RESULT_MARKER`, `SPN_POLL_MS`, `SPN_MAX_POLLS`.
+- `ArchiveOrgClient.send`, `WaybackClient.send`. `archiveOrgTorrent.ts`: `ArchiveOrgFetchSettings.s3KeyFile`,
+ `DEFAULT_ARCHIVE_ORG_S3_KEY_FILE`, `looksLikeS3Key`.
+- `publish/findCopyPages.ts`: `findPageCopies`, `citedPages`, `captureAtOf`, `targetCoversUrl`, `channelsCovering`,
+ `recordForQuote`, `pageCitationAsPost`, `defaultFindPageCopiesDeps`, `FIND_PAGE_COPY_DEFAULT_MAX`,
+ `FIND_PAGE_COPY_MAX_LIMIT`.
+- Routes `POST /api/ops/check-post-availability {slug, mode?, limit?}`, `POST /api/ops/save-page-now {url, slug?,
+ dryRun?}`, `POST /api/ops/find-copy {…, pages: true, channel?, max?, dryRun?}`. Actions
+ `editor/app/channels/[slug]/waybackLiveActions.ts`. Component `components/WaybackLivePanel.tsx` (state from
+ `waybackLiveState.ts`).
+
+## Files
+
+common: `lib/waybackPages/{liveness,liveness-server,savePageNow,savePageNow-server}.ts` (+ `liveness.test.ts`),
+`controller/{checkPageAvailability,savePageNow}.ts` (+ tests), `controller/checkPostAvailability.ts` (one branch),
+`publish/findCopyPages.ts` (+ test), `lib/posts.ts`, `lib/posts-server.ts`, `lib/archiveOrgClient.ts`,
+`lib/waybackClient.ts`, `lib/archiveOrgTorrent.ts`, `lib/settingsSchema.ts`, `lib/envVars.ts`, `jobs/jobKinds.ts`,
+`bin/archilyzer.ts` (one description), `testing/web/fakeWayback.{mjs,d.mts}`, `testing/README.md`. editor:
+`app/channels/[slug]/{page.tsx, waybackLiveActions.ts, waybackLiveState.ts, components/WaybackLivePanel.tsx}`,
+`app/api/ops/{check-post-availability,save-page-now}/route.ts`, `app/api/ops/find-copy/route.ts`,
+`app/api/ops/settings/route.ts`, `e2e/wayback-live.spec.ts`, `CHANGELOG.md`. scripts: `archilyzer-ops.mjs` (+
+test). Docs: OPERATING.md, COMMANDS.md, SETTINGS.md, ENVIRONMENT.md (regenerated), plans/FACTS.md.
+
+## Commits
+
+| sha | what |
+|---|---|
+| `442129c2` | the common half: liveness (markers, verdicts, the request), the pages branch of check-post-availability, Save Page Now (keys, client send, job), find-copy's page mode, the fake's SPN block, ops actions, generated docs |
+| `fbd569ae` | the editor half: the channel page's Originals and Save Page Now, the ops routes (check-post-availability, save-page-now, find-copy pages, the settings refusal), e2e spec |
+| (this) | the record, FACTS, OPERATING |
+
+Branched from main at d261ab33; main (14947e67, lane B) merged in before the first commit (three keep-both
+conflicts: OPERATING.md, fakeWayback.mjs/.d.mts).
+
+## Gates
+
+All through the session's locks, from the worktree root.
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean on the merged tree before the commits.
+- common: start (d261ab33) **4764 / 4762 pass / 0 fail / 2 skipped**; after (on 14947e67 + this lane) **4805 /
+ 4803 / 0 / 2** (+18 of this lane: liveness 7, checkPageAvailability 3, savePageNow 5, findCopyPages 3; the rest
+ lane B's).
+- editor unit: 356 → **357 / 357** (lane B's +1; none of this lane's).
+- test:scripts: 1316 (1312 + 4 skipped) → **1317: 1313 pass / 0 fail / 4 skipped** (+1: the ops actions' usage).
+- Docs: `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: all 0
+ (COMMANDS.md, ENVIRONMENT.md, SETTINGS.md, settings.json.example regenerated).
+- e2e (editor, start mode, stamp `131742a50d76` at `fbd569ae`; the build 1116 s in the heavy slot):
+ `wayback-live.spec.ts` + `wayback-pages.spec.ts` **2 / 2 passed** (58.5 s; 25.6 s + 14.2 s).
+
+## Rulings followed / decisions
+
+- Liveness never asks the Wayback Machine, and an `error` is never a deletion (a 403 wall, a 5xx, a redirect to
+ another site, a DNS failure, the fence).
+- A suspended account / an unshared document is `account_unavailable` (the enum's "may reverse"), not `deleted`.
+- The S3 keys follow the Claude API key's pattern: environment first, else a mode-600 file whose PATH is the setting.
+- SPN captures the page alone (`capture_outlinks=0`); the import is its own `import-page` job queued behind.
+- find-copy's page mode imports inline (its job is on the archive.org queue) and does NOT rewrite the report: it
+ answers `pointTo` / `as`; rewriting a citation (with its fallback) is the report editor's (lane D).
+- The availability check of a pages channel runs on the channel's own queue (`platform:webpage`), not archive.org's
+ (it never asks archive.org).
diff --git a/plans/release-38/research-cases-and-assist.md b/plans/release-38/research-cases-and-assist.md
@@ -128,3 +128,11 @@ Nik Drop: "make the joins 0.15 s with less smear" from the Ask box on local Qwen
page (the content sits in blocks it drops). Raw captures are kept, so `reextract-pages` fixes held records. (Lane C.)
- **Forum attachments as marked evidence**: `capture-posts` on a forum channel's posts → "forum attachment, post #N,
unverified" wherever shown; a case export lists them in an Evidence section with the post link. (Lane C.)
+- **Private names are stored as hashes** (`privateNames.sha256`: sha256 of each lowercased term), never as text: the
+ gate hashes every word and 2–3-word phrase of what it checks. A case's private terms then never sit in any file.
+ (Used live in `~/reports/oneylyzer/case/build_case.py`.) (Lane A.)
+- **Quarantine as a finding status** (operator 2026-10-20: forum joke culture): `quarantined` for anything first seen
+ on a forum and not corroborated by an independent source; its own report section; attachments looked at before
+ being described. (Lanes B/C.)
+- **An X search channel** (a saved query across accounts, leads ranked by author, Archive / Never archive) — lane S
+ `r38/x-search`, launched 2026-10-20.
diff --git a/plans/release-38/video-assist.md b/plans/release-38/video-assist.md
@@ -0,0 +1,168 @@
+# Release 38 lane E — `r38/video-assist`: the local video assistant (as shipped)
+
+The operator, 2026-10-20: "A feature to iterate on the video with hyperframes using qwen, such that I can request
+little things like changing transition time on local AI even when Claude Code is not available." This lane makes a
+request in words ("make the joins 0.15 s with less smear") a set of checked, proposed edits of a video project that
+the operator applies with a click — on the local model by default. Rulings followed: every model step optional and
+routed by `settings.generation` (local / api / code); every op the assistant can propose is also a field (the Look
+panel's slide and room numbers are new); nothing is applied without the operator's Apply, and Apply writes through
+the manifest's own writers, token-guarded; never free HTML, never a raw manifest write; synthetic fixtures only; no
+real network or model call in any test.
+
+## What
+
+1. **The look's rules moved to common** (`common/lib/report/look.mjs`, + `.d.mts`): `LOOK_KEYS`, `applyLookPatch`
+ (the body of umtool's `updateRender`, now pure), `lookErrors`, `lookOf`, and the validators and bounds that lived in
+ report-to-video (`validateTransitionStyle`/`validateSlide`, `validateRoom`/`clipRoom`/`roomOn`,
+ `validateCaptions`/`validateLoudness`/`verticalErrors`/`validateVertical`/`validateLook`; `SLIDE_BOUNDS` and
+ `ROOM_BOUNDS` exported). `report-to-video/{look,room,transition}.mjs` re-export every moved name; `updateRender`
+ calls `applyLookPatch`. Moved, not copied — the editor's task checks a look op with the writer's own function.
+2. **Declared composition params** (`common/lib/report/fxParams.mjs`): `COMPOSITION_PARAMS` for `deck`, `stats` and
+ each `fx.<effect>` — timings, sizes, positions, toggles, the odometer's label — each with the bounds its validator
+ holds it to; `DECK_PARAMS` / `STATS_PARAMS` / `FX_PARAMS` re-exported by `deck.mjs` / `stats.mjs` / `fx.mjs`;
+ `fx-params.test.mjs` holds every declaration to `validateChrome` at both bounds and just past them.
+3. **The ops** (`common/lib/report/videoAssistOps.mjs`, extending nothing: its own module, `.mjs` so umtool's plain-node
+ libs and the editor's TS both import it): `look`, `slide`, `room`, `clip_edges`, `clip_room`, `fx`, each checked
+ against the manifest as the ops before it left it, each with a diff line and the writer that performs it
+ (`checkAssistOps`); the model's one shape `{op, id, key, value}` (`ASSIST_OPS_SCHEMA`, four required keys — a strict
+ API tool requires every key) normalised to the checker's; `assistView` — the compact view trimmed to a budget, the
+ clips the request names first; `secondsNamedIn` (the 3 s slack widens to what the request names).
+4. **The proposals file** (`common/lib/report/videoAssistProposals.mjs`): `<project>/assist-proposals.json`
+ `{version, promptVersion, at, model, request, scope, note?, reply?, ops[{id, op, diff, warning?, status}],
+ refused[{op, why}], diff[]}` — written whole by the task, its statuses marked by umtool.
+5. **Task `video-assist`** (`GENERATION_TASKS`; local in every preset but `api`, the `code` preset included; field
+ docs; MCP `GENERATE_TASKS` derived): `common/lib/report/draft/tasks/videoAssist.ts` (one schema-bound ask, local
+ fitted to the prompt cap by `fitLocalAsk`, the API the same ask; the code route's `answers` read as a model's;
+ the ops checked against the manifest as it is after the answer; proposals written; never applied) and
+ `common/controller/videoAssist.ts` (its own `report-draft` job: `draft:local` through the GPU arbiter — the log and
+ the box say it waits for a transcription — ollama unloaded after; `draft:api` with the narration and daily caps and
+ a ledger row; `note`: a whole-project note's text is the request, the proposals posted back to it as the agent's
+ reply with `proposal {kind: "assist", at, ops}`). `reportDraft.ts` parses `request` / `scope` (and shares
+ `project` / `note` / `answers` with clips-suggest); the ops route's `dryRun` answers `planVideoAssistJob`.
+6. **MCP** (`mcp/src/generation.ts`): `generate` takes `task: "video-assist"` with `project` and `request` | `note`,
+ `scope`; routed to code it returns the editor's plan as this session's request and takes `answers` back;
+ `/gen` (`.claude/commands/gen.md`) says so.
+7. **umtool**: `lib/report/videoAssist.mjs` (the request, the followed job, `proposalsView` — each waiting op
+ re-checked, "now: …" when the manifest no longer allows it — `applyAssistOps` and `dismissAssistOps`);
+ `/api/report/video-assist` (GET view / job; POST ask, `action: "apply"` (token, ids, `at`) under `withEditNotes`,
+ `action: "dismiss"`, cancel); `components/projects/report/AssistBox.tsx` — the Ask box (status line: the route, the
+ GPU wait, or why not), the diff list with **Apply** / **Apply all** / **Dismiss**, applied and refused marked,
+ **Preview join**, and **Notes on the project** with **Ask the assistant** and the reply's **Apply all**; in the
+ Look panel (scope all, with the preview and the notes) and the clip editor's side column (a request naming no clip
+ is sent as about the selected one). `ReplyProposal` gains `kind: "assist"` (`lib/annotations/shape.mjs`,
+ `types.ts`); the clip editor never applies one.
+8. **The Look panel's owed fields**: the blur slide's **Travel**, **Smear**, **Grain** (shown for a blur slide), and
+ with the tail on **Tail up to, s** (`room.maxS`) and **Silence gap, s** (`room.minGap`) — written only off their
+ defaults.
+9. **Preview join**: `build-video.mjs --join-preview [--join-from <clip>]` (`report-to-video/join-preview.mjs`
+ `joinPreviewTimeline`: four consecutive clips, the last 3 s of each cut — the last clip its first 3 s — cards out,
+ windows untouched) → `out/join-preview.mp4` + `out/join-preview.json`, its own work dir, no chapters / YouTube text
+ / thumbnail, in the heavy slot; umtool `lib/report/joinPreview.mjs` + `/api/report/join-preview` (a job on the
+ app's runner), played under the box, marked stale when the look changed.
+10. **revise-video** gains `look` / `slide` / `room` (`videoOps.ts` through `checkAssistOps`, scope look;
+ `VIDEO_OPS_SCHEMA`; `localOpsBatch` takes the schema) — the article path keeps its iteration model.
+
+## Files
+
+common: `lib/report/look.mjs` + `.d.mts` (new), `lib/report/fxParams.mjs` + `.d.mts` (new),
+`lib/report/videoAssistOps.mjs` + `.d.mts` (new), `lib/report/videoAssistProposals.mjs` + `.d.mts` (new),
+`lib/report/videoAssistOps.test.ts` (new), `lib/report/draft/tasks/videoAssist.ts` + `.test.ts` (new),
+`lib/report/draft/videoOps.ts`, `lib/report/draft/tasks/revise-video.ts`, `lib/report/draft/tasks/revise-report.ts`
+(`localOpsBatch` schema), `controller/videoAssist.ts` (new), `controller/reportDraft.ts`, `lib/generationSettings.ts`
++ `.test.ts`, `testing/clips/assistProject.mjs` + `.d.mts` (new), `testing/README.md`, `package.json` (exports).
+editor: `app/api/ops/report-draft/route.ts`, `app/api/ops/_videoAssist.test.ts` (new), `CHANGELOG.md`. mcp:
+`src/generation.ts`, `src/generation.test.ts`. report-to-video: `look.mjs`, `room.mjs`, `transition.mjs` (re-exports),
+`deck.mjs`, `stats.mjs`, `fx.mjs` (params slices), `join-preview.mjs` + `.test.mjs` (new), `fx-params.test.mjs` (new),
+`build-video.mjs` (`--join-preview`), `package.json` (`./join-preview`). umtool: `lib/report/manifest.mjs`
+(`updateRender` over `applyLookPatch`), `lib/report/videoAssist.mjs` + `.test.mjs` (new), `lib/report/joinPreview.mjs`
+(new), `app/api/report/video-assist/route.ts` (new), `app/api/report/join-preview/route.ts` (new),
+`components/projects/report/AssistBox.tsx` (new), `components/projects/report/LookPanel.tsx`,
+`components/projects/review/ClipEditor.tsx`, `components/projects/review/ClipSuggest.tsx`,
+`lib/annotations/shape.mjs`, `lib/annotations/types.ts`, `lib/create/policy.mjs`, `e2e/video-assist.spec.ts` (new),
+`e2e/fixtures/video-assist-fixture.mjs` (new), `e2e/fixtures/make-fixture.mjs`, `e2e/fixtures/editor-stub.mjs`,
+`docs/report-video.md`. Root: `.claude/commands/gen.md`, `OPERATING.md`, `SETTINGS.md`, `settings.json.example` (regenerated),
+`plans/FACTS.md` ("Release 38 lane E").
+
+## Commits
+
+| sha | what |
+|---|---|
+| `e4542507` | common: the look's rules move to common/lib/report/look.mjs; compositions declare their tunable params (+ fx-params.test.mjs) |
+| `f9662056` | common: task video-assist — the ops, the proposals file, the task and its job, reportDraft, generation settings, the editor's dry run; the test kit's project and 29-request table; tests |
+| `5e9936d3` | common: revise-video takes the look ops (look, slide, room) |
+| `53fab519` | mcp: generate video-assist (project + request / note; the code route's request and answers); /gen |
+| `30bdc4bb` | umtool: the Ask box, Apply / Apply all / Dismiss, Preview join (build-video --join-preview), the Look panel's slide and room fields, notes' assist proposal; e2e video-assist.spec.ts; docs |
+| `276f002a` | plans: FACTS ("Release 38 lane E"); CHANGELOG |
+| `d3e009c1` | common: videoOps' refusal names the look ops (an existing test's expectation) |
+| `dd5f4237` | docs: the video-assist dry run in OPERATING's recipes; the ops syntax in umtool's docs |
+| (this commit) | plans: this record |
+
+## Gates
+
+All through the session's lock (`r31-locked.sh`; the e2e through `r31-locked6.sh`), from the worktree root. The
+machine sat under the lock's memory floor for most of the afternoon (available memory 0.7–3 GB while other lanes and a
+transcription ran), so the runs were queued detached and waited on in short loops.
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean before the commits (one umtool error —
+ `dismissAssistOps`' untyped options — fixed first; umtool re-checked clean).
+- common: 4764 (4762 pass, 2 skipped; measured at the branch's start) → **4784 / 4782 pass / 0 fail / 2 skipped**
+ (+20: videoAssistOps 12, the task 6, generation settings 1, videoOps 1).
+- editor unit: 356 → **361: 360 pass, 1 fail** — the one is `remote-listing/route.test.ts` ("a listing is a job whose
+ last line is the diff…": the log read before its `@@remote-listing` line landed, under the machine's load; not this
+ lane's code); that file alone afterwards **2 / 2 pass**. +5: `_videoAssist.test.ts`.
+- mcp: 379 (release 37's record) → **380 / 380** (+1: generate video-assist).
+- test:scripts: 1316 (1312 pass, 4 skipped; release 37's record) → **1326 / 1322 pass / 0 fail / 4 skipped** (+10:
+ fx-params 3, join-preview 2, umtool videoAssist 5).
+- umtool unit (`pnpm --filter umtool test`): **45 / 45** (none of this lane's tests are there: umtool's `.mjs` tests run
+ in test:scripts).
+- Docs: `docs env --check` 0, `docs files --check` 0, `docs cli --check` 0, `settings example --check` 0 (after
+ `docs files` and `settings example` regenerated SETTINGS.md and settings.json.example for the new route).
+- e2e (umtool, `pnpm --filter umtool run e2e video-assist.spec.ts clip-look.spec.ts`, prebuild stamped
+ `93df78d7b655` at `d3e009c1`): **2 / 2 passed** (35 s; video-assist 13.6 s, clip-look — the Look panel's existing
+ spec, a short rendered — 6.9 s), first run.
+
+## Decisions
+
+- **One module of its own** for the ops (`common/lib/report/videoAssistOps.mjs`, not an extension of `videoOps.ts`):
+ plain ESM so umtool's node libs (Apply) and the editor's TS task import the same checker; `videoOps.ts` calls it for
+ revise-video's look ops.
+- **The look's validators MOVED to common** (re-exported by report-to-video), not copied: the editor cannot import
+ umtool, and the brief's "the SAME validators updateRender uses" leaves no other honest way.
+- **The composition params are declared in common** (`fxParams.mjs`) and re-exported by `deck.mjs` / `stats.mjs` /
+ `fx.mjs` as their slices — the editor needs them too; a drift test holds each declaration to `validateChrome`. The
+ layout-coupled settings (deck height, footage scale, QR size, pip sizes) are not declared; `validateChrome` still
+ has the last word at Apply. An `fx` op only tunes a composition the cut already draws (it never turns one on).
+- **The model's op shape is `{op, id, key, value}`** (four required keys): the default API model is a strict tool
+ user, where every schema key is required — a flat schema of every op's fields would force junk into each op.
+- **"≤ 3 s from current unless the request says more"**: the step widens to the largest number of seconds the
+ request names ("6 seconds", "2.5 s"); a bare number ("start at 516") does not widen it.
+- **A clip's source window**: its extent (start–end) when it has a cut; else its edges ± `render.fetchPad` (0 when the
+ cut sets none).
+- **"room tail 2"** is `{tail: true, maxS: 2}`: a room edge is a boolean, `maxS` is its seconds; a number for the
+ tail turns it on up to that, and a number alone (maxS / minGap) on a cut with no room turns the tail on with it.
+- **The `code` preset routes `video-assist` local** (the brief: local in every preset but `api`); its field doc and
+ the preset's doc say so.
+- **Scope**: both Ask boxes ask with `all`; the clip editor's box sends a request that names no clip as about the
+ selected one ("… (on clip r002)"). `scope` stays a body field for the CLI and the MCP.
+- **Preview join** is `build-video --join-preview` (four clips, the last 3 s of each cut and the first 3 s of the
+ last), not `--only` (one segment has no join); its own work dir and file, so the cut's `out/` is never touched.
+ Refused for a deck cut (its joins are under the deck), a montage and hard cuts.
+- **A project-level note** is a `whole`-anchored note; the video project had no surface for one, so the Look panel's
+ box lists them (Notes on the project, with Add note). The reply's proposal is a new `ReplyProposal` kind `assist`
+ `{at, ops}`; its Apply all applies the waiting ops of THOSE proposals only while they are the latest (`at`).
+- **Apply** re-checks every op against the manifest as it is; an op the manifest no longer allows fails with the reason
+ and the rest go on; a stale token stops the batch (409) with what was applied kept and marked.
+- **The task re-reads the manifest after the answer** and checks the ops against that, so an edit made while the model
+ thought is what the ops meet.
+
+## Not done / owed
+
+- **Live, after merge** (the orchestrator's): the editor and umtool restarts; a dry run then a real ask on the Nik Drop
+ project ("make the joins 0.15 s with less smear") on local Qwen, applied, and a Preview join — commands in the
+ report.
+- The Build tab's other specs (`piece.spec.ts`, `visual-audit.spec.ts`) now render the Ask box under the Look panel;
+ not run here (two specs a run) — the orchestrator's full umtool suite covers them.
+- `fx` ops reach only the declared params (no layout-coupled deck settings, no `render.palette`, no kinetic-quote
+ voices) and never turn an effect on; widening that is a declaration per param plus its drift test.
+- The join preview is not offered for a deck cut (its joins are drawn under the deck; `--chrome-preview` is that
+ path).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -128,6 +128,11 @@
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait
// pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait
+// pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait
+// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'
+// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait
+// pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait
+// pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
// pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
@@ -463,6 +468,13 @@ const ACTIONS = [
// account as its own X channel on no site, or never archive it (hidden),
// or restore it ({slug, handle, action, name?, fetch?, dryRun?}).
"x-search-lead",
+ // WAYBACK PAGES, LIVE (release 37 S5): a posts channel's availability check
+ // ({slug, mode?, limit?}; a Wayback pages channel: each record's ORIGINAL
+ // URL at its own site), as a job; and Save Page Now ({url, slug?, dryRun?}):
+ // the Wayback Machine asked to capture a live page now (archive.org's S3
+ // keys), the capture imported into slug, as a save-page-now job.
+ "check-post-availability",
+ "save-page-now",
// EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
// ({url} or a record's {slug, id}), read only and paced; and find-copy — a
// copy of every gone recording a report cites (Wayback, then archive.org),
@@ -1266,7 +1278,12 @@ export function usage() {
' "YYYY-MM-DD" starts the walk afresh there, replacing its saved place',
' (and a "complete") — for a gap above one surviving old post. "limit": N caps',
' the posts one run reads; "pages": N caps the pages (a forum thread: its',
- ' latest N pages). "full" and "older" together are refused. An',
+ ' latest N pages). A forum thread keeps two positions: a run catches up',
+ ' from the last page, then continues the history where it stopped;',
+ ' "full": true is its full re-walk (every page, edits updated).',
+ ' "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default',
+ ' in settings) waits out a challenge or refusal page and runs again, max',
+ ' tries in all. "full" and "older" together are refused. An',
' older walk over an account that shows no posts (nothing archived, and',
' the last timeline fetch read none) is refused unless "force": true. A',
" drained fetch stops at its next resume point and the next run resumes.",
@@ -1491,6 +1508,20 @@ export function usage() {
" with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,",
" looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,",
" copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.",
+ ' The page mode (release 37): {"article"} | {"articles": true} |',
+ ' {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100),',
+ ' "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose',
+ " original is gone at its own site gets the Wayback capture nearest the",
+ " citation's date (one CDX lookup) imported into the Wayback pages channel",
+ " named, else the one whose targets cover the page; a cited page record",
+ " whose original is gone has its capture imported again when it is not",
+ " stored. A live page is left (save-page-now it). The answer names the",
+ " record each citation should cite (pointTo) and the citation as a post",
+ " citation of it (as); the report is not rewritten. A find-copy job on the",
+ " archive.org queue; dryRun asks the same paced questions and imports",
+ " nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts,",
+ " items: [{citedBy, url, original, channel?, capture?, outcome, detail,",
+ " pointTo?, as?, records?}], left, stopped?}.",
"",
'wayback-scan lists the Wayback Machine\'s captures of a Wayback pages',
' channel\'s targets (config wayback.targets) into its wayback-scan.json,',
@@ -1559,6 +1590,32 @@ export function usage() {
" {captures, stale, records: {added, changed, removed, unchanged, kept},",
" written}.",
"",
+ "check-post-availability checks which of a posts channel's archived posts",
+ ' are gone at their source: {"slug", "mode"?: "stale" (default) |',
+ ' "unchecked" | "all", "limit"?: 200}, as a check-post-availability job.',
+ " A Wayback pages channel's records are checked by their ORIGINAL URL at",
+ " its own site (never the Wayback Machine), one request per distinct URL",
+ " through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD",
+ " is refused or the platform has a \"gone\" page; available (2xx on the",
+ " same site), deleted (404/410, or X's, Tumblr's, Google Docs' or",
+ ' YouTube\'s "does not exist" page), account_unavailable (suspended, not',
+ " shared), error otherwise — with the status. A deleted original means the",
+ " Wayback copy is the only copy. Verdicts go to posts-availability.json.",
+ "",
+ "save-page-now asks the Wayback Machine to capture a live page now (Save",
+ ' Page Now, with archive.org\'s S3 keys): {"url", "slug"?, "dryRun"?}. A',
+ " save-page-now job on the archive.org queue: the capture asked (the page",
+ " alone, no outlinks), its status polled until it is made, then — with",
+ " slug, a Wayback pages channel — an import-page job of the new capture.",
+ " Refused, before any job: no keys (ARCHIVE_ORG_S3_ACCESS and",
+ " ARCHIVE_ORG_S3_SECRET in the editor's environment, or the mode-600 file",
+ " settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page",
+ " on the Wayback Machine, not a Wayback pages channel, a video, an X page",
+ " outside an X channel while X is private. The keys are never logged.",
+ ' "dryRun" answers what it would ask and starts nothing. The log ends with',
+ " @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl,",
+ " waybackUrl, importJobId?, importError?, polls, error?}.",
+ "",
'report-draft runs a generation over an article\'s iteration as a',
' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |',
' "research" | a media draft, "article", ...} -> {jobId, iteration,',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -923,3 +923,21 @@ test("import-page and reextract-pages are POSTs to their routes, named in the us
assert.match(usage(), /Actions:.*import-post, import-page, reextract-pages/);
assert.match(usage(), /import-page imports ONE Wayback Machine capture/);
});
+
+// Release 37 S5: a posts channel's availability check, Save Page Now and
+// find-copy's page mode are POSTs to their routes, named in the usage.
+test("check-post-availability, save-page-now and find-copy's page mode are POSTs, named in the usage", () => {
+ const c = parseArgs(["check-post-availability", "--json", '{"slug":"old-blog","mode":"unchecked"}', "--wait"]);
+ assert.equal(c.method, "POST");
+ assert.equal(c.path, "/api/ops/check-post-availability");
+ assert.deepEqual(c.body, { slug: "old-blog", mode: "unchecked" });
+ const s = parseArgs(["save-page-now", "--json", '{"url":"https://blog.example/a.html","slug":"old-blog","dryRun":true}']);
+ assert.equal(s.path, "/api/ops/save-page-now");
+ assert.deepEqual(s.body, { url: "https://blog.example/a.html", slug: "old-blog", dryRun: true });
+ const f = parseArgs(["find-copy", "--json", '{"siteId":"demo-site","pages":true,"channel":"old-blog"}', "--wait"]);
+ assert.equal(f.path, "/api/ops/find-copy");
+ assert.deepEqual(f.body, { siteId: "demo-site", pages: true, channel: "old-blog" });
+ assert.match(usage(), /Actions:.*reextract-pages, check-post-availability, save-page-now/);
+ assert.match(usage(), /save-page-now asks the Wayback Machine to capture a live page now/);
+ assert.match(usage(), /The page mode \(release 37\)/);
+});
diff --git a/settings.json.example b/settings.json.example
@@ -195,7 +195,8 @@
"stallMinutes": 5,
"maxPeers": 30,
"maxDownloadKiBps": 0,
- "maxUploadKiBps": 0
+ "maxUploadKiBps": 0,
+ "s3KeyFile": "~/.config/archilyzer/archive-org.env"
},
"publish": {
"enabled": false,
@@ -257,7 +258,8 @@
"social": "local",
"verdicts": "local",
"frames": "api",
- "clips-suggest": "local"
+ "clips-suggest": "local",
+ "video-assist": "local"
},
"models": {
"api": "claude-sonnet-5-5",
diff --git a/umtool/app/api/report/join-preview/route.ts b/umtool/app/api/report/join-preview/route.ts
@@ -0,0 +1,82 @@
+import { stat } from "node:fs/promises";
+import { cancelJob, getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { clipsOf, readManifest } from "@/lib/projects/report.mjs";
+import { rangeResponse } from "@/lib/report/serve.mjs";
+import { joinPreviewFile, joinPreviewSteps, readJoinPreview } from "@/lib/report/joinPreview.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE JOIN PREVIEW (release 38 lane E): `<project>/out/join-preview.mp4`, the
+// first few joins of the cut in its current look (build-video.mjs
+// --join-preview, in the heavy slot), as ONE job on the app's runner
+// (lib/jobs.ts) -- the Look panel's Preview join.
+//
+// GET ?project=<id> { preview, running }
+// GET ?project=<id>&file=1 the mp4 (ranges)
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, from? } make it (from that clip, else the first)
+// ?cancel=<job> stop it
+const headers = { "cache-control": "no-store" };
+const isPreviewJob = (kind: string) => /^join preview /.test(kind);
+
+async function reportProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "a join preview is a report video's" }, { status: 400, headers }) };
+ return { project };
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const r = await reportProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ if (url.searchParams.get("file")) {
+ const abs = joinPreviewFile(r.project.dir);
+ const st = await stat(abs).catch(() => null);
+ if (!st?.isFile()) return new Response("no join preview", { status: 404 });
+ return rangeResponse(request, {
+ abs,
+ size: st.size,
+ headers: { "content-type": "video/mp4", "accept-ranges": "bytes", "cache-control": "private, no-store" },
+ });
+ }
+ const manifest = await readManifest(r.project.dir);
+ const running = runningJob();
+ return Response.json(
+ {
+ preview: await readJoinPreview(r.project.dir, manifest),
+ running: running && running.project === r.project.id && isPreviewJob(running.kind) ? jobView(running) : null,
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) return Response.json({ cancelled: cancelJob(cancel) }, { headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await reportProject(body.project);
+ if ("error" in r) return r.error;
+ const manifest = await readManifest(r.project.dir);
+ if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers });
+ const from = body.from === undefined || body.from === null || body.from === "" ? null : String(body.from);
+ if (from && !clipsOf(manifest).some((e: { id: string }) => e.id === from)) return Response.json({ error: `no clip with id ${from}` }, { status: 400, headers });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ try {
+ const job = startJob(`join preview ${r.project.id}`, joinPreviewSteps(r.project, from), { project: r.project.id });
+ return Response.json({ ok: true, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+}
diff --git a/umtool/app/api/report/video-assist/route.ts b/umtool/app/api/report/video-assist/route.ts
@@ -0,0 +1,139 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
+import {
+ AssistRequestError,
+ applyAssistOps,
+ assistJobView,
+ assistRouteOf,
+ clearAssistJob,
+ dismissAssistOps,
+ draftBodyOf,
+ parseAssistRequest,
+ proposalsView,
+ readAssistJob,
+ writeAssistJob,
+} from "@/lib/report/videoAssist.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE VIDEO ASSISTANT (release 38 lane E) -- optional, every part of it. An
+// Ask (a request in words, or a note on the whole project) starts the
+// EDITOR's `report-draft` job, task `video-assist`, routed by
+// settings.generation (local by default, through the GPU arbiter); its
+// proposals land in `<project>/assist-proposals.json`. This route asks with
+// the shared WORKER_TOKEN (lib/articles/generation.ts askEditor), follows the
+// job, and APPLIES on the operator's click: each op re-checked and written
+// through the manifest's writers (lib/report/videoAssist.mjs), token-guarded.
+//
+// GET ?project=<id> { proposals, error, route, editorError, job, token }
+// GET ?project=<id>&job=<jobId> that job (ended: forgotten)
+// POST { project, request | note, scope? } → { jobId, job }
+// POST { project, action: "apply", ids?, token, at? } → { applied, failed, token, proposals } | 409
+// POST { project, action: "dismiss", ids?, at? } → { dismissed, proposals }
+// POST ?cancel=<jobId>&project=<id> stop it
+const headers = { "cache-control": "no-store" };
+
+async function assistProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) };
+ if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant works on a report video's cut" }, { status: 400, headers }) };
+ return { project };
+}
+
+const failed = (e: unknown) => {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers });
+ const status = e instanceof EditorError ? e.status : e instanceof AssistRequestError ? ((e as AssistRequestError & { status?: number }).status ?? 400) : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+};
+
+async function jobOf(dir: string, id: string) {
+ const rec = await readAssistJob(dir);
+ const job = await readDraftJob(id, 40);
+ const view = assistJobView(rec && rec.jobId === id ? rec : null, job);
+ if (view.ended) await clearAssistJob(dir, id);
+ return view;
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await assistProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ const dir = r.project.dir;
+ const id = url.searchParams.get("job");
+ if (id) {
+ try {
+ return Response.json(await jobOf(dir, id), { headers });
+ } catch (e) {
+ return failed(e);
+ }
+ }
+ const view = await proposalsView(dir);
+ // The route and the followed job need the editor; without one the proposals still show.
+ const policy = await readPolicy().catch((e: unknown) => e as Error);
+ const rec = await readAssistJob(dir);
+ let job = null;
+ if (rec) {
+ job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => {
+ if (e instanceof EditorError && e.status === 404) await clearAssistJob(dir, rec.jobId);
+ return null;
+ });
+ }
+ return Response.json(
+ {
+ ...view,
+ route: policy instanceof Error ? null : assistRouteOf(policy.generation, dir),
+ editorError: policy instanceof Error ? policy.message : null,
+ job,
+ token: await manifestToken(dir),
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) {
+ const r = await assistProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ try {
+ await cancelDraftJob(cancel);
+ return Response.json({ cancelled: true }, { headers });
+ } catch (e) {
+ return failed(e);
+ }
+ }
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await assistProject(body.project);
+ if ("error" in r) return r.error;
+ const dir = r.project.dir;
+ const ids = Array.isArray(body.ids) ? body.ids.map(String) : null;
+ const at = typeof body.at === "string" ? body.at : null;
+ try {
+ if (body.action === "apply") {
+ const token = body.token === undefined || body.token === null ? null : String(body.token);
+ const { result, editNotes } = await withEditNotes(r.project, () => applyAssistOps(r.project, { ids, token, at }));
+ return Response.json({ ok: true, ...result, editNotes }, { headers });
+ }
+ if (body.action === "dismiss") return Response.json({ ok: true, ...(await dismissAssistOps(dir, { ids, at })) }, { headers });
+ if (body.action !== undefined && body.action !== "ask") return Response.json({ error: 'action is "ask", "apply" or "dismiss"' }, { status: 400, headers });
+ const req = parseAssistRequest(body);
+ const running = await readAssistJob(dir);
+ if (running) {
+ const view = await jobOf(dir, running.jobId).catch(() => null);
+ if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers });
+ }
+ const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) });
+ const jobId = String(answer.jobId ?? "");
+ if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers });
+ await writeAssistJob(dir, { jobId, ...(req.note ? { note: req.note } : { request: req.request }), scope: req.scope, at: new Date().toISOString() });
+ const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null }));
+ return Response.json({ ok: true, jobId, job }, { headers });
+ } catch (e) {
+ return failed(e);
+ }
+}
diff --git a/umtool/components/projects/report/AssistBox.tsx b/umtool/components/projects/report/AssistBox.tsx
@@ -0,0 +1,462 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { useSharedNotes } from "@/components/notes/NotesProvider";
+import { NoteThread } from "@/components/notes/NoteThread";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// THE ASK BOX (release 38 lane E): the video assistant, optional in every
+// part. A request in words ("make the joins 0.15 s with less smear") starts
+// the editor's `video-assist` job (routed by settings.generation: local by
+// default, through the GPU arbiter); its PROPOSALS come back as a diff list
+// -- Apply all, Apply one, Dismiss -- and nothing is written until Apply,
+// which re-checks each op and writes through the manifest's own writers
+// (/api/report/video-assist, lib/report/videoAssist.mjs). A note on the whole
+// project can be asked too: the assistant replies on it, with an Apply.
+// Preview join renders the first joins in the current look (the heavy slot).
+// With generation routed elsewhere or no editor the box says so; the panel it
+// sits in is the manual path.
+// ---------------------------------------------------------------------------
+
+type Scope = "look" | "clips" | "fx" | "all";
+type ProposedOp = { id: string; op: Record<string, unknown>; diff: string; warning?: string; status: "proposed" | "applied" | "dismissed" | "failed"; error?: string; now?: string | null; diffNow?: string | null };
+type Proposals = { at: string; model: string; request: string; scope: string; note?: string; reply?: string; ops: ProposedOp[]; refused: { op: Record<string, unknown>; why: string }[] };
+type Job = { id: string; status: string; ended: boolean; queue: { key?: string; position?: number } | null; last: string | null; summary: string | null; note?: string; request?: string };
+type View = {
+ proposals: Proposals | null;
+ error: string | null;
+ route: { route: "code" | "api" | "local" | null; model: string | null; why: string | null } | null;
+ editorError: string | null;
+ job: Job | null;
+ token: string | null;
+};
+type Preview = { size: number; mtimeMs: number; stale: boolean; record: { clips?: string[] } | null } | null;
+type PreviewJob = { id: string; state: string; error: string | null };
+
+const routeLine = (v: View): string => {
+ if (!v.route) return `The assistant needs the editor${v.editorError ? ` (${v.editorError})` : ""}. Every setting here is a field you can change by hand.`;
+ if (v.route.why) return `${v.route.why}. Every setting here is a field you can change by hand.`;
+ if (v.route.route === "local") return `On the local model${v.route.model ? ` (${v.route.model})` : ""}, through the GPU: it waits while a transcription runs. Nothing changes until you Apply.`;
+ return `On the Claude API${v.route.model ? ` (${v.route.model})` : ""}. Nothing changes until you Apply.`;
+};
+
+const jobLine = (j: Job): string => {
+ if (j.ended) return j.status === "done" ? (j.summary ?? "Done") : `The ask ${j.status}${j.last ? ` — ${j.last}` : ""}`;
+ if (j.status === "queued") {
+ const gpu = j.queue?.key === "draft:local";
+ return `Queued${j.queue?.position ? ` (${j.queue.position} in line)` : ""}${gpu ? " — waiting for the GPU (a transcription runs first)" : ""}`;
+ }
+ return `Asking the assistant${j.last ? ` · ${j.last}` : ""}`;
+};
+
+const STATUS_WORD: Record<ProposedOp["status"], string> = { proposed: "proposed", applied: "applied", dismissed: "dismissed", failed: "not applied" };
+
+export function useAssist(project: string) {
+ const [view, setView] = useState<View | null>(null);
+ const [job, setJob] = useState<Job | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [ended, setEnded] = useState(0);
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (!r) return;
+ const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null;
+ if (!r.ok || !j) {
+ setError(j?.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setView(j);
+ if (j.job && !j.job.ended) setJob(j.job);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ const live = job && !job.ended ? job.id : null;
+ useEffect(() => {
+ if (!live) return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/video-assist?project=${encodeURIComponent(project)}&job=${encodeURIComponent(live)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as Job;
+ setJob(j);
+ if (j.ended) {
+ setEnded((n) => n + 1);
+ await load();
+ }
+ }, 1500);
+ return () => clearInterval(t);
+ }, [live, project, load]);
+ const post = useCallback(
+ async (body: Record<string, unknown>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await fetch("/api/report/video-assist", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, json: j };
+ } finally {
+ setBusy(false);
+ }
+ },
+ [project],
+ );
+ const ask = useCallback(
+ async (body: { request: string; scope: Scope } | { note: string; scope: Scope }) => {
+ // The last ask's line goes: what shows next is this one's.
+ setJob(null);
+ const r = await post(body);
+ if (r.json.job) setJob(r.json.job as Job);
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return r.ok;
+ },
+ [post],
+ );
+ const apply = useCallback(
+ async (ids: string[] | null, at?: string) => {
+ const r = await post({ action: "apply", token: view?.token ?? null, ...(ids ? { ids } : {}), ...(at ? { at } : {}) });
+ if (r.status === 409) {
+ await load();
+ setError(`${String(r.json.error ?? "the cut changed")} — reloaded; check and apply again`);
+ return false;
+ }
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ await load();
+ return r.ok && Array.isArray(r.json.applied) && (r.json.applied as unknown[]).length > 0;
+ },
+ [post, view?.token, load],
+ );
+ const dismiss = useCallback(
+ async (ids: string[] | null) => {
+ const r = await post({ action: "dismiss", ...(ids ? { ids } : {}), ...(view?.proposals ? { at: view.proposals.at } : {}) });
+ if (!r.ok) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ await load();
+ },
+ [post, view?.proposals, load],
+ );
+ const cancel = useCallback(async () => {
+ if (!job) return;
+ await fetch(`/api/report/video-assist?cancel=${encodeURIComponent(job.id)}&project=${encodeURIComponent(project)}`, { method: "POST" }).catch(() => null);
+ }, [job, project]);
+ return { view, job, error, busy, ended, load, ask, apply, dismiss, cancel };
+}
+
+/** The proposals as a diff list: Apply one, Apply all, Dismiss. */
+function ProposalList({ p, busy, onApply, onDismiss }: { p: Proposals; busy: boolean; onApply: (ids: string[] | null) => void; onDismiss: () => void }) {
+ const waiting = p.ops.filter((o) => o.status === "proposed" || o.status === "failed");
+ const applicable = waiting.filter((o) => !o.now);
+ return (
+ <section data-assist-proposals={p.ops.length} data-assist-at={p.at} className="space-y-1.5 rounded-[3px] border border-seam bg-panel-2 px-2.5 py-2">
+ <p className="m-0 text-[11.5px] text-muted" data-assist-request="">
+ “{p.request}” — {p.model} · {new Date(p.at).toLocaleString()}
+ </p>
+ {p.reply && (
+ <p className="m-0 text-[12px] text-text-2" data-assist-reply="">
+ {p.reply}
+ </p>
+ )}
+ {p.ops.length === 0 && <p className="m-0 text-[12px] text-muted">No edit proposed.</p>}
+ {p.ops.length > 0 && (
+ <ul className="m-0 list-none space-y-1 p-0">
+ {p.ops.map((o) => (
+ <li key={o.id} data-assist-op={o.id} data-assist-status={o.status} className={cn("flex flex-wrap items-baseline gap-2 text-[12.5px]", o.status === "dismissed" && "opacity-60")}>
+ <span className={cn("font-mono text-text", o.status === "applied" && "text-kept-text")}>{o.status === "proposed" && o.diffNow && o.diffNow !== o.diff ? o.diffNow : o.diff}</span>
+ {o.status !== "proposed" && <span className={badgeVariants({ variant: o.status === "applied" ? "on" : o.status === "failed" ? "blocking" : "info", size: "sm" })}>{STATUS_WORD[o.status]}</span>}
+ {(o.status === "proposed" || o.status === "failed") && (
+ <button type="button" data-assist-apply={o.id} disabled={busy || !!o.now} title={o.now ?? "write it now, through the look's (or the clip's) own writer"} onClick={() => onApply([o.id])} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Apply
+ </button>
+ )}
+ {o.warning && <span className="text-[11.5px] text-doubt-text">{o.warning}</span>}
+ {o.now && (o.status === "proposed" || o.status === "failed") && (
+ <span className="text-[11.5px] text-muted" data-assist-now="">
+ now: {o.now}
+ </span>
+ )}
+ {o.error && o.status === "failed" && !o.now && <span className="text-[11.5px] text-reject-text">{o.error}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {p.refused.length > 0 && (
+ <ul className="m-0 list-none space-y-0.5 p-0" data-assist-refused-list="">
+ {p.refused.map((r, i) => (
+ <li key={i} data-assist-refused="" className="text-[11.5px] text-muted">
+ not proposed: {r.why}
+ </li>
+ ))}
+ </ul>
+ )}
+ {waiting.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2 pt-0.5">
+ <button type="button" data-assist-apply-all="" disabled={busy || !applicable.length} onClick={() => onApply(null)} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Apply all
+ </button>
+ <button type="button" data-assist-dismiss="" disabled={busy} onClick={onDismiss} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Dismiss
+ </button>
+ </div>
+ )}
+ </section>
+ );
+}
+
+/** Preview join: the first joins in the look as saved (a render in the heavy slot), played here. */
+function JoinPreview({ project, version }: { project: string; version: string }) {
+ const [preview, setPreview] = useState<Preview>(null);
+ const [job, setJob] = useState<PreviewJob | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/join-preview?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { preview: Preview; running: PreviewJob | null };
+ setPreview(j.preview);
+ if (j.running) setJob(j.running);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load, version]);
+ const running = job?.state === "running";
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/join-preview?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as PreviewJob;
+ setJob(j);
+ if (j.state !== "running") await load();
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, load]);
+ const start = async () => {
+ setError(null);
+ const r = await fetch("/api/report/join-preview", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: PreviewJob; error?: string };
+ if (!r.ok || !j.job) setError(j.error ?? `HTTP ${r.status}`);
+ else setJob(j.job);
+ };
+ return (
+ <div className="space-y-1.5" data-join-preview={preview ? (preview.stale ? "stale" : "fresh") : "none"}>
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" data-assist-preview="" disabled={running} onClick={() => void start()} className={buttonVariants({ size: "sm" })} title="the first joins of the cut, a few seconds either side, in the look as saved (a render, in the machine's heavy slot)">
+ {running ? "Rendering the preview…" : preview ? "Preview join again" : "Preview join"}
+ </button>
+ {running && (
+ <button type="button" onClick={() => void fetch(`/api/report/join-preview?cancel=${job!.id}`, { method: "POST" })} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Stop
+ </button>
+ )}
+ {preview?.stale && <span className="text-[11.5px] text-doubt-text">the look changed since this preview</span>}
+ {job && !running && job.state !== "done" && <span className="text-[11.5px] text-reject-text">preview {job.state}{job.error ? `: ${job.error}` : ""}</span>}
+ {error && (
+ <span role="alert" className="text-[11.5px] text-reject-text">
+ {error}
+ </span>
+ )}
+ </div>
+ {preview && (
+ <video
+ data-assist-preview-video=""
+ key={preview.mtimeMs}
+ src={`/api/report/join-preview?project=${encodeURIComponent(project)}&file=1&v=${preview.mtimeMs}`}
+ controls
+ loop
+ className="max-h-[240px] w-full max-w-[480px] rounded-[3px] border border-seam bg-ground"
+ />
+ )}
+ </div>
+ );
+}
+
+/** The project-level notes, each with Ask the assistant; an agent reply's proposals with Apply all. */
+function ProjectNotes({ project, a, scope, apply }: { project: string; a: ReturnType<typeof useAssist>; scope: Scope; apply: (ids: string[] | null, at?: string) => Promise<boolean> }) {
+ const notes = useSharedNotes({ project });
+ const reloadNotes = notes.reload;
+ useEffect(() => {
+ if (a.ended) void reloadNotes();
+ }, [a.ended, reloadNotes]);
+ const [text, setText] = useState("");
+ const whole = notes.notes.filter((n) => n.anchor.kind === "whole");
+ const blocked = a.view?.route?.why ?? (a.view && !a.view.route ? "the assistant needs the editor" : null);
+ const asking = a.job && !a.job.ended ? a.job.note : null;
+ const p = a.view?.proposals ?? null;
+ const add = async () => {
+ if (!text.trim()) return;
+ const n = await notes.write({ op: "add", text, anchor: { kind: "whole" } });
+ if (n) setText("");
+ };
+ return (
+ <section data-assist-notes={whole.length} className="space-y-1.5">
+ <h3 className="micro m-0">Notes on the project{whole.length ? ` — ${whole.filter((n) => n.status === "open").length} open` : ""}</h3>
+ {whole.map((n) => (
+ <NoteThread
+ key={n.id}
+ note={n}
+ write={notes.write}
+ busy={notes.busy}
+ actions={
+ n.status === "open" ? (
+ <button
+ type="button"
+ data-note-action="assist"
+ disabled={notes.busy || a.busy || !!blocked || !!asking}
+ title={blocked ?? "the assistant reads this note as a request and replies here; what it proposes waits for your Apply"}
+ onClick={() => void a.ask({ note: n.id, scope })}
+ className="ink-link disabled:opacity-40"
+ >
+ {asking === n.id ? "Asking…" : "Ask the assistant"}
+ </button>
+ ) : null
+ }
+ afterReply={(r) => {
+ const pr = r.proposal;
+ if (!pr || pr.kind !== "assist" || r.author !== "agent") return null;
+ const current = !!p && p.at === pr.at;
+ const waiting = current ? p!.ops.filter((o) => o.status === "proposed" && !o.now).length : 0;
+ return (
+ <div data-reply-proposal="assist" className="ml-4 flex flex-wrap items-center gap-1.5 text-[11px] text-text-2">
+ <span className={badgeVariants({ variant: "meter", size: "sm" })}>proposes</span>
+ <span>
+ {pr.ops} edit{pr.ops === 1 ? "" : "s"}
+ </span>
+ {!current ? (
+ <span className="text-muted">a newer ask replaced these</span>
+ ) : waiting ? (
+ <button
+ type="button"
+ data-apply-proposal="assist"
+ disabled={a.busy}
+ onClick={() =>
+ void apply(null, pr.at).then((ok) => {
+ if (ok) void notes.write({ op: "reply", id: n.id, text: "Applied the assistant's edits" });
+ })
+ }
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Apply all
+ </button>
+ ) : (
+ <span className="text-muted">nothing waiting</span>
+ )}
+ </div>
+ );
+ }}
+ />
+ ))}
+ <div className="flex flex-wrap items-start gap-2">
+ <textarea
+ data-assist-note-input=""
+ value={text}
+ rows={1}
+ onChange={(e) => setText(e.target.value)}
+ placeholder="a note on the whole project — for you or the assistant"
+ className="min-w-[14rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal"
+ />
+ <button type="button" data-assist-note-add="" disabled={notes.busy || !text.trim()} onClick={() => void add()} className={buttonVariants({ size: "sm" })}>
+ Add note
+ </button>
+ </div>
+ </section>
+ );
+}
+
+/**
+ * The Ask box. `scope`: what an ask may touch here (the Look panel: the look;
+ * the clip editor: the clips). `onApplied`: the page re-reads what Apply
+ * wrote. `version`: changes when the page wrote the manifest itself (the box
+ * re-reads its token). `subject`: the clip the page has selected -- a request
+ * that names no clip is sent as about it ("… (on clip r002)").
+ */
+export default function AssistBox({
+ project,
+ scope,
+ placeholder,
+ onApplied,
+ version = 0,
+ subject,
+ preview = false,
+ notes = false,
+}: {
+ project: string;
+ scope: Scope;
+ placeholder?: string;
+ onApplied?: () => void;
+ version?: number | string;
+ subject?: string;
+ preview?: boolean;
+ notes?: boolean;
+}) {
+ const a = useAssist(project);
+ const [text, setText] = useState("");
+ const { load } = a;
+ const first = useRef(true);
+ useEffect(() => {
+ if (first.current) {
+ first.current = false;
+ return;
+ }
+ void load();
+ }, [version, load]);
+ const v = a.view;
+ const blocked = !v ? "reading…" : (v.route?.why ?? (!v.route ? "no editor" : null));
+ const running = !!a.job && !a.job.ended;
+ const submit = async () => {
+ if (!text.trim()) return;
+ // A clip id is letters, digits, ".", "_" and "-": only the dot needs escaping.
+ const id = subject ? subject.replace(/\./g, "\\.") : "";
+ const named = !!subject && new RegExp(`(^|[^A-Za-z0-9_-])${id}([^A-Za-z0-9_-]|$)`).test(text);
+ const request = subject && !named ? `${text.trim()} (on clip ${subject})` : text;
+ if (await a.ask({ request, scope })) setText("");
+ };
+ const apply = async (ids: string[] | null, at = v?.proposals?.at) => {
+ const ok = await a.apply(ids, at);
+ if (ok) onApplied?.();
+ return ok;
+ };
+ return (
+ <div data-assist-box={scope} data-assist-route={v?.route?.route ?? "none"} className="space-y-2">
+ <div className="flex flex-wrap items-start gap-2">
+ <textarea
+ data-assist-input=""
+ value={text}
+ rows={2}
+ disabled={!!blocked || running}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void submit();
+ }}
+ placeholder={placeholder ?? "ask in words — “make the joins 0.15 s with less smear”"}
+ className="min-w-[16rem] flex-1 resize-y rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12.5px] text-text outline-none focus:border-signal disabled:opacity-60"
+ />
+ <button type="button" data-assist-ask="" disabled={!!blocked || running || a.busy || !text.trim()} onClick={() => void submit()} className={buttonVariants({ variant: text.trim() ? "go" : "outline", size: "md" })}>
+ {running ? "Asking…" : "Ask"}
+ </button>
+ {running && (
+ <button type="button" data-assist-cancel="" onClick={() => void a.cancel()} className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Stop
+ </button>
+ )}
+ </div>
+ {v && (
+ <p className="m-0 text-[11.5px] text-muted" data-assist-status="">
+ {routeLine(v)}
+ </p>
+ )}
+ {a.job && (
+ <p className="m-0 text-[11.5px] text-text-2" data-assist-job={a.job.status}>
+ {jobLine(a.job)}
+ </p>
+ )}
+ {(a.error || v?.error) && (
+ <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-assist-error="">
+ {a.error ?? v?.error}
+ </p>
+ )}
+ {v?.proposals && <ProposalList p={v.proposals} busy={a.busy} onApply={(ids) => void apply(ids)} onDismiss={() => void a.dismiss(null)} />}
+ {preview && <JoinPreview project={project} version={`${version}:${a.ended}`} />}
+ {notes && <ProjectNotes project={project} a={a} scope={scope} apply={apply} />}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -4,6 +4,8 @@ import { useCallback, useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { Field, Input, Select } from "@/components/ui/field";
import { Panel } from "@/components/ui/panel";
+import { ROOM, ROOM_BOUNDS, SLIDE_BOUNDS, SLIDE_DEFAULTS } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import AssistBox from "./AssistBox";
// THE LOOK (release 36 lane C): the render keys a person sets for a cut with
// no deck -- the header, the timeline footer, the QR, the crossfade's length
@@ -12,6 +14,11 @@ import { Panel } from "@/components/ui/panel";
// /api/report/render (lib/report/manifest.mjs updateRender, the build's own
// checks). Nothing here calls a model. A deck cut keeps its own settings
// (the Media tab); a montage levels with render.montage.
+// Release 38 lane E: the blur slide's knobs (travel, smear, grain) and the
+// room's numbers (how far the tail may run, the silence that ends it) are
+// fields too, so every op the video assistant can propose is one here; the
+// assistant's Ask box (AssistBox: optional, its proposals applied only on
+// Apply) and Preview join sit under the fields.
type Look = {
headerHeight?: number;
@@ -22,6 +29,7 @@ type Look = {
loudness?: { target: number } | null;
captions?: { style: "speakers"; labels?: { host?: string | null; subject?: string | null } | null; size?: "m" | "l" } | null;
room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null;
+ slide?: { travel?: number; blur?: number; grain?: number } | null;
};
type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
@@ -41,6 +49,11 @@ type Draft = {
size: "m" | "l";
roomTail: boolean;
roomHead: boolean;
+ roomMaxS: string;
+ roomMinGap: string;
+ travel: string;
+ smear: string;
+ grain: string;
};
function draftOf(l: Look): Draft {
@@ -59,9 +72,20 @@ function draftOf(l: Look): Draft {
size: l.captions?.size ?? "m",
roomTail: l.room?.tail === true,
roomHead: l.room?.head === true,
+ roomMaxS: String(l.room?.maxS ?? ROOM.maxS),
+ roomMinGap: String(l.room?.minGap ?? ROOM.minGap),
+ travel: String(l.slide?.travel ?? SLIDE_DEFAULTS.travel),
+ smear: String(l.slide?.blur ?? SLIDE_DEFAULTS.blur),
+ grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain),
};
}
+const SLIDE_KEYS = [
+ ["travel", "travel"],
+ ["blur", "smear"],
+ ["grain", "grain"],
+] as const;
+
/** The patch that takes the saved look to the draft: only what changed, `null` to remove a key. */
function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
const p: Record<string, unknown> = {};
@@ -84,10 +108,29 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
// Room at the clips' edges (release 36 lane E): its settings kept as written.
const was0 = was.room ?? null;
const on = d.roomTail || d.roomHead;
- const next = on ? { ...(was0 ?? {}), tail: d.roomTail, head: d.roomHead } : null;
- const same = (was0?.tail === true) === d.roomTail && (was0?.head === true) === d.roomHead;
+ // The numbers (release 38): written only when they differ from the build's defaults.
+ const nums: Record<string, number> = {};
+ const maxS = Number(d.roomMaxS);
+ const minGap = Number(d.roomMinGap);
+ if (maxS !== ROOM.maxS || was0?.maxS !== undefined) nums.maxS = maxS;
+ if (minGap !== ROOM.minGap || was0?.minGap !== undefined) nums.minGap = minGap;
+ const { maxS: _m, minGap: _g, ...edges } = was0 ?? {};
+ const next = on ? { ...edges, tail: d.roomTail, head: d.roomHead, ...nums } : null;
+ const same =
+ (was0?.tail === true) === d.roomTail &&
+ (was0?.head === true) === d.roomHead &&
+ (!on || ((was0?.maxS ?? ROOM.maxS) === maxS && (was0?.minGap ?? ROOM.minGap) === minGap));
if (!same) p.room = next;
}
+ // The blur slide's knobs (release 38): only the ones off their defaults are written.
+ {
+ const cur = { travel: Number(d.travel), blur: Number(d.smear), grain: Number(d.grain) };
+ const had = { ...SLIDE_DEFAULTS, ...(was.slide ?? {}) };
+ if (SLIDE_KEYS.some(([k]) => cur[k] !== had[k])) {
+ const next = Object.fromEntries(SLIDE_KEYS.filter(([k]) => cur[k] !== SLIDE_DEFAULTS[k]).map(([k]) => [k, cur[k]]));
+ p.slide = Object.keys(next).length ? next : null;
+ }
+ }
return p;
}
@@ -97,6 +140,8 @@ export default function LookPanel({ project }: { project: string }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
+ // Bumped when this panel writes the manifest, so the Ask box re-reads its token.
+ const [version, setVersion] = useState(0);
const load = useCallback(async () => {
const r = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" });
@@ -139,6 +184,7 @@ export default function LookPanel({ project }: { project: string }) {
}
setView({ ...view, look: j.look ?? {}, token: j.token ?? null, errors: [] });
setDraft(draftOf(j.look ?? {}));
+ setVersion((n) => n + 1);
setStatus("Saved — the next render uses it");
} finally {
setBusy(false);
@@ -197,6 +243,40 @@ export default function LookPanel({ project }: { project: string }) {
{check("roomTail", "Tail: sound to the first silence, then muted", "data-look-room-tail", Number(draft.transition) === 0)}
{check("roomHead", "Head: muted lead-in", "data-look-room-head", Number(draft.transition) === 0)}
{Number(draft.transition) === 0 && <span className="text-[12px] text-muted">no join to make room for</span>}
+ {(draft.roomTail || draft.roomHead) && Number(draft.transition) !== 0 && (
+ <span className="flex flex-wrap items-end gap-3">
+ <Field label="Tail up to, s">
+ <Input data-look-room-max="" type="number" min={ROOM_BOUNDS.maxS[0]} max={ROOM_BOUNDS.maxS[1]} step={0.1} value={draft.roomMaxS} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMaxS: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ <Field label="Silence gap, s">
+ <Input data-look-room-gap="" type="number" min={ROOM_BOUNDS.minGap[0]} max={ROOM_BOUNDS.minGap[1]} step={0.05} value={draft.roomMinGap} disabled={busy || !draft.roomTail} onChange={(e) => set({ roomMinGap: e.target.value })} className="w-[5.5em]" />
+ </Field>
+ </span>
+ )}
+ </div>
+ )}
+ {draft.style === "blurslide" && Number(draft.transition) !== 0 && (
+ <div className="mt-3 flex flex-wrap items-end gap-4" data-look-slide="">
+ <span className="text-[12.5px] text-text-2">Blur slide</span>
+ {SLIDE_KEYS.map(([k, word]) => {
+ const field = k === "blur" ? "smear" : k;
+ const [lo, hi] = SLIDE_BOUNDS[k];
+ return (
+ <Field key={k} label={word[0]!.toUpperCase() + word.slice(1)}>
+ <Input
+ {...{ [`data-look-slide-${word}`]: "" }}
+ type="number"
+ min={lo}
+ max={hi}
+ step={k === "grain" ? 1 : k === "travel" ? 0.01 : 0.1}
+ value={draft[field]}
+ disabled={busy}
+ onChange={(e) => set({ [field]: e.target.value } as Partial<Draft>)}
+ className="w-[5.5em]"
+ />
+ </Field>
+ );
+ })}
</div>
)}
<div className="mt-3 space-y-2">
@@ -247,6 +327,11 @@ export default function LookPanel({ project }: { project: string }) {
) : null}
</span>
</div>
+ {/* --- the assistant (release 38): optional; its proposals wait for Apply */}
+ <div className="mt-4 border-t border-seam pt-3" data-look-assist="">
+ <h3 className="micro m-0 mb-2">Ask the assistant</h3>
+ <AssistBox project={project} scope="all" version={version} onApplied={() => void load().catch((e) => setError(e instanceof Error ? e.message : String(e)))} preview notes />
+ </div>
</Panel>
);
}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -13,6 +13,7 @@ import type { EditorClip, EditorView, Neighbourhood, Proposal, RenderTarget, Spe
import { cn } from "@/lib/utils";
import { ROOM, roomShade } from "umtool-report-to-video/room";
import { startTakeJob } from "../NewTakePanel";
+import AssistBox from "../report/AssistBox";
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional).
import type { ReplyProposal } from "@/lib/annotations/types";
import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest";
@@ -313,12 +314,15 @@ export default function ClipEditor({
// An agent reply's proposal, applied ON THE OPERATOR'S CLICK through the
// writer every other edit here uses (release 36 lane D).
const canApply = (p: ReplyProposal): string | null => {
+ // The video assistant's proposals (release 38) are applied in its Ask box, not here.
+ if (p.kind === "assist") return "apply it in the assistant's box";
const at = clips.findIndex((c) => c.id === p.clip);
if (at < 0) return `${p.clip} is no longer in the cut`;
if (p.kind === "merge" && clips[at + 1]?.id !== p.with) return `${p.with} is no longer the next clip`;
return null;
};
const applyProposal = async (p: ReplyProposal): Promise<boolean> => {
+ if (p.kind === "assist") return false;
await flush();
const j =
p.kind === "trim"
@@ -628,6 +632,18 @@ export default function ClipEditor({
{/* ---- the list, the proposals, the speakers, the take --------------- */}
<aside className="flex min-h-0 flex-col gap-3 overflow-auto border-t border-seam bg-panel p-3 lg:border-l lg:border-t-0" data-editor-side="">
<SuggestPanel s={assistant} sorted={byRank} onSort={setByRank} />
+ {/* Release 38: the video assistant — a request in words, its proposals applied only on Apply. */}
+ <section data-editor-assist="">
+ <h2 className="micro m-0 mb-1">Ask the assistant</h2>
+ <AssistBox
+ project={project}
+ scope="all"
+ subject={clip.id}
+ version={view.token ?? ""}
+ onApplied={() => void reload().catch((e) => setError(e instanceof Error ? e.message : String(e)))}
+ placeholder={`ask in words — “cut the first 2 s”, “no room on this clip”, “quicker joins”`}
+ />
+ </section>
<section>
<h2 className="micro mb-1">
{plural(clips.length, "clip")} · {clips.filter((c) => c.ruling === "keep").length} kept · {clips.filter((c) => c.ruling === "cut").length} cut
diff --git a/umtool/components/projects/review/ClipSuggest.tsx b/umtool/components/projects/review/ClipSuggest.tsx
@@ -214,6 +214,7 @@ export function SuggestPanel({ s, sorted, onSort }: { s: ClipSuggest; sorted: bo
/** What an agent reply proposes, in words. */
export function proposalWords(p: ReplyProposal): string {
+ if (p.kind === "assist") return `${p.ops} edit${p.ops === 1 ? "" : "s"} of the look or the cut (the Ask box)`;
if (p.kind === "trim") return `trim ${p.clip} to ${edgeClock(p.from)}–${edgeClock(p.to)} (${(p.to - p.from).toFixed(1)} s)`;
if (p.kind === "merge") return `merge ${p.clip} with ${p.with}`;
return `cut ${p.clip}`;
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1268,9 +1268,12 @@ head: true}` (lane B's seed, with lane E's join and room).
**The Look panel** (the Build tab, `/api/report/render`) sets them by hand:
**Header**, **Timeline footer**, **QR code**, the length **Between clips** (0 is
a hard cut) and the **Join** (crossfade, dip to black, dip to white, dissolve,
-blur slide), **Room at the clips' edges** (Tail, Head — below),
-**Loudness** (as recorded, −16 LUFS, or a custom target) and **Speaker
-captions** with each role's name and the size. **Save the look** writes only
+blur slide), **Room at the clips' edges** (Tail, Head, and with the tail on
+**Tail up to, s** — `maxS` — and **Silence gap, s** — `minGap`; below), the
+**Blur slide**'s **Travel**, **Smear** (`slide.blur`) and **Grain** when the
+join is a blur slide, **Loudness** (as recorded, −16 LUFS, or a custom target)
+and **Speaker captions** with each role's name and the size — so every edit
+the video assistant can propose is also a field here (release 38). **Save the look** writes only
what changed (`lib/report/manifest.mjs` `updateRender`: token-guarded, the
build's own checks, atomic; `null` puts a key back to the build's default). It
never touches `render.chrome` (the deck's own settings, the Media tab); a deck
@@ -1356,6 +1359,76 @@ own time. `render.slide` = `{travel: 0.08, blur: 0.5, grain: 2}` by default
length is `render.transition` (the seed's 0.22 s). A dip, a THEN/NOW wipe and a
whip keep their own look. With room at both edges the slide runs over muted picture.
+## The video assistant: Ask, Apply, Preview join (release 38)
+
+"Make the joins 0.15 s with less smear" — a small change to a cut in words,
+on the local model when Claude Code is not at hand. Optional in every part:
+with generation routed elsewhere, or no editor, the box says so, and the Look
+panel above it is the same panel.
+
+**The Ask box** sits under the Look panel's fields (the Build tab) and in the
+clip editor's side column (where a request that names no clip is sent as about
+the selected one: "… (on clip r002)"). An ask is one editor job, `report-draft`
+task **`video-assist`** (`common/controller/videoAssist.ts`), routed by
+`settings.generation.routes["video-assist"]` — **local in every preset but
+`api`**: on `draft:local`, through the GPU arbiter, so it waits while a
+transcription runs (the box says so), and ollama is unloaded after; on the API
+the narration cap and the daily cap hold it and its usage is a ledger row;
+`code` = a Claude Code session answers the request (`/gen`, the MCP's
+`generate`). The task asks once, schema-bound — `{ops: [{op, id, key, value}],
+reply}` — over the project's compact view: the look now, the blur slide's
+knobs, the room, the clips with their cuts and the window each may move in,
+and the declared params of the compositions the cut draws, trimmed to the
+prompt cap (the clips the request names first).
+
+**The ops** (`common/lib/report/videoAssistOps.mjs`), each checked against the
+manifest as it is, with its diff line:
+
+| Op | What | Checked by |
+|---|---|---|
+| `look` | a LOOK_KEYS render key (`transition`, `transitionStyle`, `qr`, `loudness`, `captions`, `headerHeight`, …) | `applyLookPatch` — the same function `updateRender` writes with (common `lib/report/look.mjs`, whose validators the build and the lint call too) |
+| `slide` | `travel` / `blur` (the smear) / `grain` | within `SLIDE_BOUNDS` (0–0.5, 0–2, 0–20) |
+| `room` | `tail` / `head` (on or off), `maxS` (how far the tail runs, 0–10 s), `minGap` (0.1–2 s); a number for the tail turns it on up to that ("keep 2 s after the last word") | `ROOM_BOUNDS`, `validateRoom` |
+| `clip_edges` | a clip's cut, `start` / `end` in seconds on its recording | inside the clip's source window (its extent; a clip with no cut, its edges widened by `fetchPad`), at least 0.5 s, and an edge moves at most 3 s unless the request names more seconds |
+| `clip_room` | one clip's room: `tail` / `head`, `off` (none), `reset` (the cut's again) | `validateRoom` |
+| `fx` | a composition's DECLARED param (`deck`, `stats`, `fx.<effect>`): e.g. the deck's `motion.in`, the glitch's `seconds` | its declaration's bounds (`common/lib/report/fxParams.mjs`; `fx-params.test.mjs` holds each to `validateChrome`); never free HTML |
+
+An op the checks refuse is not proposed: it is listed with its reason
+("render.transition must be a number of seconds from 0 (a hard cut) to 3").
+The job writes **`<project>/assist-proposals.json`** — the request, the model,
+the kept ops with their diff lines, the refused with their reasons — and
+**nothing else**: no manifest, no clip, no note.
+
+**Apply** (one op, or **Apply all**) re-checks each op against the manifest as
+it is then and writes it through the manifest's own writer — `updateRender` for
+the look, the slide and the room; the clip editor's `trim` and `room` for a
+clip (an assistant's clip becomes the operator's, as any trim makes it);
+`updateChrome` for a composition's param — token-guarded, the token carried
+from one write to the next (`/api/report/video-assist`,
+`lib/report/videoAssist.mjs`). A token that went stale stops it (reload); an op
+the manifest no longer allows fails with the reason (the list says so before
+the click: "now: …"). **Dismiss** marks the waiting ops and writes nothing
+else. An applied op is marked applied.
+
+**A note on the whole project** (the box's **Notes on the project**): **Ask the
+assistant** sends the note's text as the request; the proposals are posted back
+to it as the agent's reply, carrying an **Apply all** while they are the
+latest.
+
+**Preview join** renders the first four joins of the cut in the look as saved —
+each clip cut to the last 3 s of its cut (the last clip, its first 3 s), every
+other entry left out, the windows untouched so the fetched media is reused —
+to `out/join-preview.mp4` (and `out/join-preview.json`, what it was made
+from), and plays it under the box; it says when the look has changed since. A
+job on umtool's runner (`/api/report/join-preview`), `build-video.mjs
+<manifest> --join-preview [--join-from <clip>]` inside the heavy slot; the
+cut's own `out/` files (its segments, chapters, YouTube text) are not touched.
+Not for a deck cut, a montage or hard cuts.
+
+From a terminal: `pnpm ops report-draft --json '{"task": "video-assist", "project":
+"<dir>", "request": "quicker joins", "dryRun": true}'` (the prompt and its
+estimate), then without `dryRun`.
+
## Operator notes, timed notes and the generated-manifest guard
Notes on a project live in `<project>/notes.json` (shape and CLI:
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -25,6 +25,8 @@ import { fileURLToPath } from "node:url";
import { fetchWindowsRoute } from "./editor-stub-fetch-windows.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";
+import { proposalsDocOf, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
const PORT = portFor("EDITOR_STUB_PORT");
const CHANNELS = process.env.CHANNELS_DIR ?? "";
@@ -134,11 +136,12 @@ function writeWindow(dir, name, seconds) {
// startCannedDraft) — every isStepTask step answered.
const ARTICLES = process.env.ARTICLES_DIR ?? "";
const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? "";
+// Release 38 lane E: video-assist is local in every preset but api, as the editor's.
const PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code" },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", "video-assist": "local" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", "video-assist": "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", "video-assist": "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", "video-assist": "local" },
};
const generation = {
preset: "balanced",
@@ -846,6 +849,53 @@ function finishRefresh(job, parent, p) {
job.log.push(`refresh: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task: "refresh", status: "done", summary, refresh: patch.refresh })}`);
}
+// A `video-assist` report-draft (release 38 lane E): a canned "model" reads
+// the request's words (0.15 → the join, "smear" → the slide's blur, "QR" →
+// off, "louder" → -14 LUFS, "5 seconds" → a join the checks refuse) and the
+// ops are checked and written through common's own checker and writer, as
+// the real task does; a note's Ask (body.note) reads its text from
+// notes.json and posts no reply (the stub cannot reach umtool).
+const ASSIST_CANNED = [
+ [/0\.15/, { op: "look", id: "", key: "transition", value: 0.15 }],
+ [/smear/i, { op: "slide", id: "", key: "blur", value: 0.3 }],
+ [/\bqr\b/i, { op: "look", id: "", key: "qr", value: false }],
+ [/louder/i, { op: "look", id: "", key: "loudness", value: -14 }],
+ [/5 seconds/i, { op: "look", id: "", key: "transition", value: 5 }],
+];
+function startVideoAssist(body) {
+ if (typeof body.project !== "string" || !body.project.startsWith("/")) throw new Error('"project" is the video project\'s absolute directory');
+ let request = typeof body.request === "string" ? body.request : "";
+ if (typeof body.note === "string") {
+ const notes = JSON.parse(readFileSync(path.join(body.project, "notes.json"), "utf8"));
+ const n = (notes.notes ?? []).find((x) => x.id === body.note);
+ if (!n) throw new Error(`no note ${body.note}`);
+ request = n.text;
+ }
+ if (!request.trim()) throw new Error("the assistant needs a request");
+ const id = `stub-assist-${nextJob++}`;
+ const job = { id, article: null, n: 0, task: "video-assist", status: "queued", at: Date.now(), log: [`report-draft video-assist (stub)`], timers: [] };
+ draftJobs.set(id, job);
+ job.timers.push(setTimeout(() => { job.status = "running"; job.log.push("asking the stub model"); }, 300));
+ job.timers.push(
+ setTimeout(async () => {
+ try {
+ const manifest = JSON.parse(readFileSync(path.join(body.project, "video.manifest.json"), "utf8"));
+ const ops = ASSIST_CANNED.filter(([re]) => re.test(request)).map(([, op]) => op);
+ const checked = checkAssistOps(manifest, ops, { request, scope: body.scope ?? "all" });
+ const doc = proposalsDocOf({ at: new Date().toISOString(), model: generation.models.local, request, scope: body.scope ?? "all", note: body.note ?? null, reply: ops.length ? "Done as asked." : "Nothing I can change for that.", checked });
+ await writeAssistProposals(body.project, doc);
+ const summary = `${doc.ops.length} edit${doc.ops.length === 1 ? "" : "s"} proposed${doc.ops.length ? ` (${doc.diff.join("; ")})` : ""}${doc.refused.length ? `, ${doc.refused.length} refused` : ""} on ${generation.models.local}`;
+ job.log.push(summary, `@@report-draft ${JSON.stringify({ article: "", iteration: 0, task: "video-assist", project: body.project, status: "done", summary, usd: 0, assist: { at: doc.at, proposed: doc.ops.length, refused: doc.refused.length, diff: doc.diff } })}`);
+ job.status = "done";
+ } catch (err) {
+ job.log.push(String(err.message));
+ job.status = "failed";
+ }
+ }, 1500),
+ );
+ return { jobId: id, iteration: 0 };
+}
+
function cancelDraft(id) {
const job = draftJobs.get(id);
if (!job || !["queued", "running"].includes(job.status)) return false;
@@ -853,7 +903,7 @@ function cancelDraft(id) {
job.status = "cancelled";
job.log.push("cancelled");
job.child?.kill();
- if (job.task === "clips-suggest") return true;
+ if (job.task === "clips-suggest" || job.task === "video-assist") return true;
const it = readIt(job.article, job.n);
if (job.task === "narrate" || MEDIA_RUN.has(job.task) || MEDIA_TASKS.has(job.task)) {
patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) });
@@ -923,6 +973,14 @@ function generationRoute(req, res, url, auth) {
return json(res, 400, { ok: false, error: String(err.message) });
}
}
+ // Release 38 lane E: the video assistant (a project, not an article).
+ if (body?.task === "video-assist") {
+ try {
+ return json(res, 202, { ok: true, ...startVideoAssist(body) });
+ } catch (err) {
+ return json(res, 400, { ok: false, error: String(err.message) });
+ }
+ }
if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" });
if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" });
try {
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -37,6 +37,7 @@ import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs";
+import { makeVideoAssistFixture } from "./video-assist-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1819,6 +1820,8 @@ makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// Release 38 lane E: the video assistant's Ask box, Apply and Dismiss on the Look panel (video-assist.spec.ts).
+makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
diff --git a/umtool/e2e/fixtures/video-assist-fixture.mjs b/umtool/e2e/fixtures/video-assist-fixture.mjs
@@ -0,0 +1,18 @@
+// What video-assist.spec.ts reads and writes (release 38 lane E): the clip
+// editor's three clips (clip-editor-fixture.mjs, copied under its own name so
+// no two specs edit one project), with a quick blur slide as its look — the
+// cut the Ask box proposes edits of. The editor stub's canned "model"
+// (editor-stub.mjs startVideoAssist) answers from the request's words.
+// Synthetic, like every fixture.
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { makeClipEditorFixture } from "./clip-editor-fixture.mjs";
+
+/** @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o */
+export function makeVideoAssistFixture(o) {
+ makeClipEditorFixture({ ...o, name: "video-assist-fixture", title: "The Video Assist Fixture" });
+ const file = path.join(o.reports, "video-assist-fixture", "video.manifest.json");
+ const doc = JSON.parse(readFileSync(file, "utf8"));
+ doc.render = { ...doc.render, transition: 0.22, transitionStyle: "blurslide", qr: false, headerHeight: 0 };
+ writeFileSync(file, JSON.stringify(doc, null, 2) + "\n");
+}
diff --git a/umtool/e2e/video-assist.spec.ts b/umtool/e2e/video-assist.spec.ts
@@ -0,0 +1,118 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The video assistant (release 38 lane E) on the Build tab's Look panel. An
+// Ask ("make the joins 0.15 s with less smear") starts the editor's
+// `video-assist` job (the editor stub's canned model answers through common's
+// own checker and writer); its proposals come back as a diff list; nothing in
+// the manifest moves until Apply, which writes through updateRender; the
+// panel's fields read the new look. A second ask ("louder, and 5 seconds
+// between clips") shows its refusal with the reason, and Dismiss changes
+// nothing but the marks. A note on the whole project, asked, is the request
+// too; the agent's reply carries an Apply. Fixture:
+// e2e/fixtures/video-assist-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/video-assist-fixture";
+const DIR = path.join(FIXTURE, "reports", "video-assist-fixture");
+const TOKEN = "umtool-e2e-token";
+
+const json = (name: string) => {
+ try {
+ return JSON.parse(readFileSync(path.join(DIR, name), "utf8"));
+ } catch {
+ return null;
+ }
+};
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const render = () => json("video.manifest.json")?.render ?? {};
+const stubRequests = (): { route: string; task?: string; project?: string; request?: string; note?: string }[] => {
+ try {
+ return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8"));
+ } catch {
+ return [];
+ }
+};
+
+test("Ask on the Look panel: the diff, Apply through the look's writer, a refusal shown, Dismiss writes nothing; a project note asked", async ({ page, request }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.goto(urls.section(PROJECT, "build"));
+ await expect(page.locator("[data-look-panel]")).toHaveAttribute("data-look-panel", "");
+ const box = page.locator('[data-assist-box="all"]');
+ await expect(box).toHaveAttribute("data-assist-route", "local");
+ await expect(box.locator("[data-assist-status]")).toContainText("On the local model (qwen3:8b), through the GPU: it waits while a transcription runs.");
+ // The manual path is right there: the slide's knobs are fields.
+ await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.5");
+
+ // ---- an ask: the proposals, nothing applied ---------------------------------
+ const before = manifestText();
+ await box.locator("[data-assist-input]").fill("make the joins 0.15 s with less smear");
+ await box.locator("[data-assist-ask]").click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ expect(stubRequests().filter((r) => r.route === "report-draft" && r.task === "video-assist").map((r) => [r.project, r.request])).toEqual([[DIR, "make the joins 0.15 s with less smear"]]);
+ const list = box.locator("[data-assist-proposals]");
+ await expect(list).toHaveAttribute("data-assist-proposals", "2");
+ await expect(list.locator('[data-assist-op="a1"]')).toContainText("join 0.22 s → 0.15 s");
+ await expect(list.locator('[data-assist-op="a2"]')).toContainText("smear 0.5 → 0.3");
+ await expect(list.locator("[data-assist-reply]")).toHaveText("Done as asked.");
+ expect(manifestText()).toBe(before);
+
+ // ---- Apply one, then the rest: through updateRender; the panel reads it back
+ await list.locator('[data-assist-apply="a1"]').click();
+ await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "applied");
+ expect(render().transition).toBe(0.15);
+ expect(render().slide).toBeUndefined();
+ await expect(page.locator("[data-look-transition]")).toHaveValue("0.15");
+ await list.locator("[data-assist-apply-all]").click();
+ await expect(list.locator('[data-assist-op="a2"]')).toHaveAttribute("data-assist-status", "applied");
+ expect(render().slide).toEqual({ blur: 0.3 });
+ await expect(page.locator("[data-look-slide-smear]")).toHaveValue("0.3");
+ expect(json("assist-proposals.json")?.ops?.map((o: { status: string }) => o.status)).toEqual(["applied", "applied"]);
+ await expect(list.locator("[data-assist-apply-all]")).toHaveCount(0);
+
+ // ---- a second ask: one proposed, one refused with the reason; Dismiss ----
+ await box.locator("[data-assist-input]").fill("louder, and 5 seconds between clips");
+ await box.locator("[data-assist-ask]").click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ await expect(list).toHaveAttribute("data-assist-proposals", "1");
+ await expect(list.locator('[data-assist-op="a1"]')).toContainText("loudness as recorded → -14 LUFS");
+ await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: render.transition must be a number of seconds from 0 (a hard cut) to 3");
+ const applied = manifestText();
+ await list.locator("[data-assist-dismiss]").click();
+ await expect(list.locator('[data-assist-op="a1"]')).toHaveAttribute("data-assist-status", "dismissed");
+ expect(manifestText()).toBe(applied);
+ expect(render().loudness).toBeUndefined();
+
+ // ---- a note on the whole project, asked: its text is the request ----------
+ await box.locator("[data-assist-note-input]").fill("no QR, please");
+ await box.locator("[data-assist-note-add]").click();
+ const thread = box.locator("[data-assist-notes] [data-note-id]");
+ await expect(thread).toHaveCount(1);
+ const noteId = (await thread.getAttribute("data-note-id"))!;
+ await thread.locator('[data-note-action="assist"]').click();
+ await expect(box.locator("[data-assist-job]")).toHaveAttribute("data-assist-job", "done", { timeout: 20_000 });
+ expect(stubRequests().filter((r) => r.task === "video-assist" && r.note).map((r) => [r.project, r.note])).toEqual([[DIR, noteId]]);
+ // The QR is already off in this cut: the checks say so (nothing proposed).
+ await expect(list).toHaveAttribute("data-assist-proposals", "0");
+ await expect(list.locator("[data-assist-refused]")).toHaveText("not proposed: QR code is already that");
+
+ // The agent's reply with an assist proposal (posted here: the stub cannot reach umtool) shows its Apply only while current.
+ const at = json("assist-proposals.json").at as string;
+ const read = await (await request.get(`/api/notes?project=${encodeURIComponent(PROJECT)}`)).json();
+ const replied = await request.post(`/api/notes?project=${encodeURIComponent(PROJECT)}`, {
+ headers: { authorization: `Bearer ${TOKEN}` },
+ data: { token: read.token, op: { op: "reply", id: noteId, text: "No edit proposed.", proposal: { kind: "assist", at, ops: 1 } } },
+ });
+ expect(replied.ok()).toBe(true);
+ await page.reload();
+ const reply = page.locator('[data-assist-notes] [data-reply-proposal="assist"]');
+ await expect(reply).toContainText("1 edit");
+ await expect(reply).toContainText("nothing waiting");
+});
diff --git a/umtool/lib/annotations/shape.mjs b/umtool/lib/annotations/shape.mjs
@@ -117,7 +117,7 @@ export function validateAnchor(raw) {
}
}
-export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"];
+export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut", "assist"];
/**
* An agent reply's proposal (release 36 lane D, "Ask the assistant"): ONE
@@ -126,6 +126,9 @@ export const REPLY_PROPOSAL_KINDS = ["trim", "merge", "cut"];
* { kind: "merge", clip, with, basis? } the clip and the next one, joined
* { kind: "cut", clip, basis? } the clip ruled out
* `basis` is the clip's cut when the agent read it ({ cutStart, cutEnd }).
+ * Release 38 lane E, the video assistant on a note on the whole project:
+ * { kind: "assist", at, ops } the proposals in assist-proposals.json
+ * made at `at` (their Apply is the Ask box's)
* Never applied by whoever writes it. `{ proposal }` or `{ error }`.
* @param {unknown} raw
*/
@@ -133,8 +136,13 @@ export function validateReplyProposal(raw) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "proposal is not an object" };
const p = /** @type {Record<string, unknown>} */ (raw);
if (!REPLY_PROPOSAL_KINDS.includes(/** @type {string} */ (p.kind))) return { error: `proposal kind must be one of ${REPLY_PROPOSAL_KINDS.join(", ")}` };
- if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" };
const fin = (v) => typeof v === "number" && Number.isFinite(v);
+ if (p.kind === "assist") {
+ if (!short(p.at, 40) || !p.at || Number.isNaN(Date.parse(/** @type {string} */ (p.at)))) return { error: "an assist proposal names its proposals' time (at)" };
+ if (!Number.isInteger(p.ops) || /** @type {number} */ (p.ops) < 1 || /** @type {number} */ (p.ops) > 40) return { error: "an assist proposal counts its ops (1 to 40)" };
+ return { proposal: { kind: "assist", at: p.at, ops: p.ops } };
+ }
+ if (!short(p.clip, 128) || !ID.test(p.clip)) return { error: "proposal needs the clip's id" };
const out = { kind: p.kind, clip: p.clip };
if (p.kind === "trim") {
if (!fin(p.from) || !fin(p.to) || p.from < 0 || p.to - p.from < 0.5) return { error: "a trim proposal needs from ≥ 0 and to at least half a second after it" };
diff --git a/umtool/lib/annotations/types.ts b/umtool/lib/annotations/types.ts
@@ -48,7 +48,9 @@ export type AnchorKind = Anchor["kind"];
export type ReplyProposal =
| { kind: "trim"; clip: string; from: number; to: number; basis?: { cutStart: number; cutEnd: number } }
| { kind: "merge"; clip: string; with: string; basis?: { cutStart: number; cutEnd: number } }
- | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } };
+ | { kind: "cut"; clip: string; basis?: { cutStart: number; cutEnd: number } }
+ /** Release 38 lane E: the video assistant's proposals (assist-proposals.json, made at `at`), applied in the Ask box. */
+ | { kind: "assist"; at: string; ops: number };
export type NoteReply = { author: NoteAuthor; text: string; at: string; proposal?: ReplyProposal };
diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs
@@ -29,6 +29,7 @@ const TASK_WORD = {
youtube: "YouTube drafts",
social: "social post drafts",
"clips-suggest": "clip labels",
+ "video-assist": "the video assistant",
};
/**
diff --git a/umtool/lib/report/joinPreview.mjs b/umtool/lib/report/joinPreview.mjs
@@ -0,0 +1,58 @@
+// THE JOIN PREVIEW, umtool's half (release 38 lane E): `<project>/out/join-
+// preview.mp4`, the first few joins of the cut in its current look
+// (report-to-video/join-preview.mjs; build-video.mjs `--join-preview`, which
+// runs in the machine's heavy slot), as ONE job on the app's runner
+// (lib/jobs.ts: one at a time, a log, Cancel) -- the Look panel's and the Ask
+// box's Preview join. Its record (`out/join-preview.json`) says what it was
+// made from, so the page can say when the look has moved since.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD } from "umtool-report-to-video/join-preview";
+import { PIPELINE_DIR } from "./driver.mjs";
+
+/** A preview is a few seconds of four clips: minutes at most. */
+export const JOIN_PREVIEW_TIMEOUT_MS = 15 * 60_000;
+const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/;
+
+const outOf = (dir) => path.join(/* turbopackIgnore: true */ dir, "out");
+export const joinPreviewFile = (dir) => path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_FILE);
+
+/**
+ * The job's one step: build-video `--join-preview` (from `from`, else the
+ * first clip), NDJSON progress. No path or argv from a client.
+ * @param {{ dir: string }} project
+ * @param {string | null} [from]
+ */
+export function joinPreviewSteps(project, from = null) {
+ if (from !== null && !CLIP_ID.test(from)) throw new Error(`not a clip id: ${from}`);
+ return [
+ {
+ cwd: PIPELINE_DIR,
+ env: {},
+ label: `preview the joins${from ? ` from ${from}` : ""}`,
+ argv: [
+ "node", path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"),
+ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
+ "--out", outOf(project.dir),
+ "--join-preview", ...(from ? ["--join-from", from] : []), "--progress", "ndjson",
+ ],
+ ndjson: true,
+ timeoutMs: JOIN_PREVIEW_TIMEOUT_MS,
+ },
+ ];
+}
+
+/**
+ * The preview on disk, or null: `{ size, mtimeMs, record, stale }` --
+ * `stale` when the look (lookOf the render) is not what it was made with.
+ * @param {string} dir
+ * @param {any} [manifest]
+ */
+export async function readJoinPreview(dir, manifest = null) {
+ const st = await stat(joinPreviewFile(dir)).catch(() => null);
+ if (!st?.isFile()) return null;
+ const record = await readFile(path.join(/* turbopackIgnore: true */ outOf(dir), JOIN_PREVIEW_RECORD), "utf8").then(JSON.parse, () => null);
+ const stale = !!manifest && !!record && JSON.stringify(record.look ?? {}) !== JSON.stringify(lookOf(manifest.render ?? {}));
+ return { size: st.size, mtimeMs: Math.round(st.mtimeMs), record, stale };
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -33,9 +33,9 @@ import { isCalendarDate } from "umtool-report-to-video/attribution";
import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck";
import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
-import { validateLook, verticalErrors } from "umtool-report-to-video/look";
+import { verticalErrors } from "umtool-report-to-video/look";
+import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { validateRoom } from "umtool-report-to-video/room";
-import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
import { applySectionEnter } from "./sections.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateNarration } from "umtool-report-to-video/narration";
@@ -936,17 +936,10 @@ export class ChromeRefused extends Error {
// checks against the render as it will be, then written atomically.
// ---------------------------------------------------------------------------
-/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide"]);
-
-/** The look keys of a render block as written (absent keys left out). */
-export function lookOf(render) {
- const r = isObj(render) ? render : {};
- /** @type {Record<string, unknown>} */
- const out = {};
- for (const k of LOOK_KEYS) if (r[k] !== undefined) out[k] = r[k];
- return out;
-}
+// LOOK_KEYS, lookOf and the patch's rules are the look's (common
+// lib/report/look.mjs, release 38): the video assistant checks a proposed op
+// with the same function this writer writes with.
+export { LOOK_KEYS, lookOf };
/** The build's sentences for a refused look, thrown whole so a route can return each one. */
export class RenderRefused extends Error {
@@ -958,12 +951,12 @@ export class RenderRefused extends Error {
}
}
-const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
-
/**
* Patch the look. Each key of `patch` is one of LOOK_KEYS; `null` removes the
* key (the build's default again). `qr: true` turns the code back on (removes
* a `false`; an object of settings is kept), `qr: false` turns it off.
+ * The rules are applyLookPatch's (common lib/report/look.mjs), against the
+ * manifest as it is inside the lock.
*
* @param {string} dir
* @param {Record<string, unknown>} patch
@@ -972,49 +965,16 @@ const intIn = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
*/
export async function updateRender(dir, patch, { token = null } = {}) {
if (!isObj(patch)) throw new RenderRefused(["the patch must be an object of render keys"]);
- const errors = [];
- for (const k of Object.keys(patch)) {
- if (k === "chrome") errors.push("render.chrome is the deck's: set it from the deck's settings (updateChrome), not here");
- else if (!LOOK_KEYS.includes(k)) errors.push(`render.${k} is not a look setting (${LOOK_KEYS.join(", ")})`);
+ {
+ // The keys alone, before the lock: a patch naming no look key is refused without reading the file.
+ const keys = applyLookPatch({}, Object.fromEntries(Object.keys(patch).map((k) => [k, null])));
+ if (keys.errors.length) throw new RenderRefused(keys.errors);
}
- if (errors.length) throw new RenderRefused(errors);
return withManifestLock(async () => {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
- const render = { ...(isObj(manifest.render) ? manifest.render : {}) };
- for (const [k, v] of Object.entries(patch)) {
- if (v === null) {
- delete render[k];
- continue;
- }
- switch (k) {
- case "headerHeight":
- case "footerHeight":
- if (!intIn(v, 0, 240)) errors.push(`render.${k} must be a whole number of pixels from 0 to 240`);
- else render[k] = v;
- break;
- case "qr":
- if (v === false) render.qr = false;
- else if (v === true) {
- if (render.qr === false) delete render.qr;
- } else errors.push("render.qr must be true (on) or false (off)");
- break;
- case "transition":
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 3) errors.push("render.transition must be a number of seconds from 0 (a hard cut) to 3");
- else render.transition = round2(v);
- break;
- case "transitionStyle":
- if (typeof v !== "string" || !TRANSITION_STYLES.includes(v)) errors.push(`render.transitionStyle must be one of ${TRANSITION_STYLES.join(", ")}`);
- else render.transitionStyle = v;
- break;
- default:
- // loudness, captions, room: stored as given; the build's validators below say what is wrong.
- render[k] = v;
- }
- }
- const next = { ...manifest, render };
- errors.push(...validateTransitionStyle(next), ...validateLook(next));
+ const { render, errors } = applyLookPatch(manifest, patch);
if (errors.length) throw new RenderRefused(errors);
manifest.render = render;
const nextToken = await writeManifestAtomic(dir, manifest);
diff --git a/umtool/lib/report/videoAssist.mjs b/umtool/lib/report/videoAssist.mjs
@@ -0,0 +1,238 @@
+// THE VIDEO ASSISTANT, umtool's half (release 38 lane E): the Ask box's
+// request to the editor, the job the page follows, the proposals file read
+// for the page, and APPLY -- the one place a proposed op becomes a write.
+//
+// assist-proposals.json written by the EDITOR's `report-draft` task
+// `video-assist` (common lib/report/videoAssistProposals.mjs);
+// its ops' status marked here (applied / dismissed / failed)
+// .video-assist-job.json the editor job the page follows, so a reload shows it;
+// umtool's own file, cleared when the job is seen to end
+//
+// Apply re-checks each op against the manifest AS IT IS (common
+// videoAssistOps.mjs checkAssistOps -- the look's rules, the clip's window,
+// the declared params), then writes through the manifest's own writers:
+// updateRender (the look, the slide, the room), the clip editor's
+// runClipEditorOp (trim, room), updateChrome (a composition's param) -- each
+// token-guarded, the token carried from one write to the next. A stale token
+// stops it (409: reload); a refusal fails that op only, with its reason.
+// Never a raw manifest write, never free HTML. Dismiss marks ops and writes
+// nothing else.
+//
+// Everything is optional: with no editor, no model, or generation routed to
+// Claude Code, the Look panel and the clip editor are the same as before.
+import { readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
+import { chromeWithParam } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs";
+import { runClipEditorOp } from "./clipEditor.mjs";
+
+export const ASSIST_TASK = "video-assist";
+export const ASSIST_JOB_FILE = ".video-assist-job.json";
+export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]);
+export const ASSIST_REQUEST_MAX = 2000;
+const JOB_RE = /^[A-Za-z0-9_-]+$/;
+const NOTE_RE = /^n_[a-z0-9]{4,32}$/;
+const OP_ID_RE = /^a\d{1,3}$/;
+const RESULT_MARKER = "@@report-draft ";
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+export class AssistRequestError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/**
+ * A POST's ask, judged: `{ request, scope? }` (the Ask box) or `{ note, scope? }`
+ * (Ask the assistant on a note on the whole project).
+ * @param {unknown} body
+ */
+export function parseAssistRequest(body) {
+ if (!isObj(body)) throw new AssistRequestError("a body is { project, request | note, scope? }");
+ const scope = body.scope === undefined || body.scope === null ? "all" : String(body.scope);
+ if (!ASSIST_SCOPES.includes(scope)) throw new AssistRequestError(`scope is ${ASSIST_SCOPES.join(", ")}`);
+ if (body.note !== undefined && body.note !== null) {
+ if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new AssistRequestError("a note's Ask names the note (n_…)");
+ if (body.request !== undefined && body.request !== null) throw new AssistRequestError("give a request or a note, not both");
+ return { note: body.note, scope };
+ }
+ const request = typeof body.request === "string" ? body.request.replace(/\s+/g, " ").trim() : "";
+ if (!request) throw new AssistRequestError("say what to change");
+ if (request.length > ASSIST_REQUEST_MAX) throw new AssistRequestError(`a request is at most ${ASSIST_REQUEST_MAX} characters`);
+ return { request, scope };
+}
+
+/** The editor's `report-draft` body for an ask on a project directory. */
+export function draftBodyOf(dir, req) {
+ return { task: ASSIST_TASK, project: dir, ...(req.note ? { note: req.note } : { request: req.request }), ...(req.scope && req.scope !== "all" ? { scope: req.scope } : {}) };
+}
+
+const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_JOB_FILE);
+
+/** The job the page follows, or null: `{ jobId, request?, note?, scope, at }`. */
+export async function readAssistJob(dir) {
+ try {
+ const j = JSON.parse(await readFile(jobFileOf(dir), "utf8"));
+ return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Remember the job an Ask started (tmp + rename). */
+export async function writeAssistJob(dir, rec) {
+ const file = jobFileOf(dir);
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(rec)}\n`);
+ await rename(tmp, file);
+}
+
+/** Forget it — only when it is still that job. */
+export async function clearAssistJob(dir, jobId) {
+ const cur = await readAssistJob(dir);
+ if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true });
+}
+
+export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]);
+
+/** The job's `@@report-draft` result in its log tail, or null. */
+export function assistMarkerOf(tail) {
+ for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) {
+ const at = String(tail[i]).indexOf(RESULT_MARKER);
+ if (at < 0) continue;
+ try {
+ return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length));
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
+
+/** What the page shows of a job: its state, where it waits, its last line, and its result once it ended. */
+export function assistJobView(rec, job) {
+ const marker = assistMarkerOf(job.tail);
+ const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null;
+ return {
+ id: job.id,
+ ...(rec?.note ? { note: rec.note } : {}),
+ ...(rec?.request ? { request: rec.request } : {}),
+ status: job.status,
+ ended: ENDED.includes(job.status),
+ queue: job.queue ?? null,
+ last: last === null ? null : String(last).slice(0, 300),
+ summary: typeof marker?.summary === "string" ? marker.summary : null,
+ };
+}
+
+/**
+ * How the task is routed, for the box: `{ route, model, why }` from the
+ * policy's generation block, or null without one. `why` is set when the box
+ * cannot start a job here (routed to Claude Code, or no route).
+ */
+export function assistRouteOf(generation, dir) {
+ if (!isObj(generation) || !isObj(generation.routes)) return null;
+ const route = generation.routes[ASSIST_TASK] ?? null;
+ if (route === "code") return { route, model: null, why: `routed to Claude Code — in a session: /gen on ${dir}: <what to change>` };
+ const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null;
+ return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no video-assist" };
+}
+
+/**
+ * The proposals for the page: each op with whether it would still apply to
+ * the manifest as it is (`now: null` when it would, else the reason).
+ * @param {string} dir
+ */
+export async function proposalsView(dir) {
+ const [{ doc, error }, manifest] = await Promise.all([readAssistProposals(dir), readManifest(dir)]);
+ if (!doc) return { proposals: null, error };
+ const ops = doc.ops.map((o) => {
+ if (o.status !== "proposed" && o.status !== "failed") return { ...o, now: null };
+ const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope });
+ return { ...o, now: r.refused[0]?.why ?? null, diffNow: r.ops[0]?.diff ?? null };
+ });
+ return { proposals: { ...doc, ops }, error: null };
+}
+
+/**
+ * Apply proposed ops (`ids`, or every one still proposed) in the file's
+ * order, each re-checked against the manifest as the ones before it left it.
+ * `token` is the manifest's as the page read it (null: unguarded — the CLI).
+ * `at`, when given, is the proposals the caller saw: a newer ask's file is a
+ * 409, not a silent apply of other ops.
+ *
+ * @param {{ id: string, dir: string, kind: string }} project
+ * @param {{ ids?: string[] | null, token?: string | null, at?: string | null, now?: string | null }} [o]
+ * @returns {Promise<{ applied: string[], failed: { id: string, error: string }[], token: string | null, proposals: unknown }>}
+ */
+export async function applyAssistOps(project, { ids = null, token = null, at = null, now = null } = {}) {
+ const dir = project.dir;
+ const { doc, error } = await readAssistProposals(dir);
+ if (!doc) throw new AssistRequestError(error ?? "no proposals to apply", 404);
+ if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409);
+ if (ids && !ids.every((id) => typeof id === "string" && OP_ID_RE.test(id))) throw new AssistRequestError("ids is a list of op ids (a1, a2, …)");
+ const wanted = doc.ops.filter((o) => (ids ? ids.includes(o.id) : o.status === "proposed") && (o.status === "proposed" || o.status === "failed"));
+ if (!wanted.length) throw new AssistRequestError(ids ? "those ops are not waiting (applied or dismissed already)" : "nothing is waiting to apply");
+ let cur = await manifestToken(dir);
+ if (token !== null && cur !== token) throw new StaleToken(token, cur);
+ const stamp = now ?? new Date().toISOString();
+ /** @type {Record<string, { status: "applied" | "failed", error?: string }>} */
+ const marks = {};
+ const applied = [];
+ const failed = [];
+ for (const o of wanted) {
+ const manifest = await readManifest(dir);
+ const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope });
+ if (r.refused.length) {
+ marks[o.id] = { status: "failed", error: r.refused[0].why };
+ failed.push({ id: o.id, error: r.refused[0].why });
+ continue;
+ }
+ const a = r.ops[0].apply;
+ try {
+ if (a.writer === "render") cur = (await updateRender(dir, a.patch, { token: cur })).token;
+ else if (a.writer === "chrome") {
+ const chrome = chromeWithParam(manifest.render, a.id, a.param, a.value);
+ cur = (await updateChrome(dir, chrome, { token: cur })).token;
+ } else {
+ const res = await runClipEditorOp(project, { ...a.body, token: cur });
+ cur = res?.view?.token ?? (await manifestToken(dir));
+ }
+ marks[o.id] = { status: "applied" };
+ applied.push(o.id);
+ } catch (e) {
+ // Another writer got in between: stop, say so; what was applied stays applied.
+ if (e instanceof StaleToken) {
+ await writeAssistProposals(dir, markProposals(doc, marks, stamp));
+ throw e;
+ }
+ const msg = e instanceof Error ? (Array.isArray(e.errors) ? e.errors.join("; ") : e.message) : String(e);
+ marks[o.id] = { status: "failed", error: msg };
+ failed.push({ id: o.id, error: msg });
+ }
+ }
+ const next = markProposals(doc, marks, stamp);
+ await writeAssistProposals(dir, next);
+ return { applied, failed, token: cur, proposals: next };
+}
+
+/**
+ * Dismiss ops (`ids`, or every one still waiting): marked, nothing else written.
+ * @param {string} dir
+ * @param {{ ids?: string[] | null, at?: string | null, now?: string | null }} [o]
+ */
+export async function dismissAssistOps(dir, { ids = null, at = null, now = null } = {}) {
+ const { doc, error } = await readAssistProposals(dir);
+ if (!doc) throw new AssistRequestError(error ?? "no proposals to dismiss", 404);
+ if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409);
+ const marks = Object.fromEntries(
+ doc.ops.filter((o) => (ids ? ids.includes(o.id) : true) && (o.status === "proposed" || o.status === "failed")).map((o) => [o.id, { status: "dismissed" }]),
+ );
+ const next = markProposals(doc, marks, now ?? new Date().toISOString());
+ await writeAssistProposals(dir, next);
+ return { dismissed: Object.keys(marks), proposals: next };
+}
diff --git a/umtool/lib/report/videoAssist.test.mjs b/umtool/lib/report/videoAssist.test.mjs
@@ -0,0 +1,139 @@
+// The video assistant in umtool (release 38 lane E): the Ask's request, the
+// job the page follows, and APPLY — each proposed op re-checked and written
+// through the manifest's own writers (updateRender, the clip editor's trim and
+// room, updateChrome), token-guarded; Dismiss writes nothing but the marks.
+// Synthetic (common/testing/clips/assistProject.mjs).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { assistDeckManifest, assistManifest } from "yt-dlp-transcript-common/testing/clips/assistProject.mjs";
+import { writeReactionProject } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs";
+import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
+import { proposalsDocOf, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs";
+import { MANIFEST_NAME, StaleToken, manifestToken, updateRender } from "./manifest.mjs";
+import {
+ AssistRequestError,
+ applyAssistOps,
+ assistJobView,
+ assistRouteOf,
+ dismissAssistOps,
+ draftBodyOf,
+ parseAssistRequest,
+ proposalsView,
+} from "./videoAssist.mjs";
+
+const AT = "2026-10-20T00:00:00.000Z";
+
+async function project({ deck = false, ops }) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-assist-"));
+ writeReactionProject(dir);
+ const manifest = deck ? assistDeckManifest() : assistManifest();
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ const checked = checkAssistOps(manifest, ops, { request: "the request" });
+ await writeAssistProposals(dir, proposalsDocOf({ at: AT, model: "qwen3:8b", request: "the request", checked }));
+ return { id: "reports/assist", dir, kind: "report" };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+
+test("an Ask's request: words or a note, a scope; the editor's body", () => {
+ assert.deepEqual(parseAssistRequest({ request: " quicker joins " }), { request: "quicker joins", scope: "all" });
+ assert.deepEqual(parseAssistRequest({ note: "n_abcd1234", scope: "look" }), { note: "n_abcd1234", scope: "look" });
+ assert.throws(() => parseAssistRequest({ request: " " }), AssistRequestError);
+ assert.throws(() => parseAssistRequest({ request: "x", scope: "everything" }), /scope is look, clips, fx, all/);
+ assert.throws(() => parseAssistRequest({ note: "n_abcd1234", request: "x" }), /not both/);
+ assert.deepEqual(draftBodyOf("/r/p", { request: "quicker joins", scope: "all" }), { task: "video-assist", project: "/r/p", request: "quicker joins" });
+ assert.deepEqual(draftBodyOf("/r/p", { note: "n_abcd1234", scope: "look" }), { task: "video-assist", project: "/r/p", note: "n_abcd1234", scope: "look" });
+ assert.deepEqual(assistRouteOf({ routes: { "video-assist": "local" }, models: { local: "qwen3:8b" } }, "/r/p"), { route: "local", model: "qwen3:8b", why: null });
+ assert.match(assistRouteOf({ routes: { "video-assist": "code" }, models: {} }, "/r/p").why, /routed to Claude Code — in a session: \/gen on \/r\/p/);
+ const v = assistJobView({ jobId: "j1", request: "quicker" }, { id: "j1", status: "done", tail: ["one ask", '@@report-draft {"task":"video-assist","status":"done","summary":"1 edit proposed"}'] });
+ assert.deepEqual([v.ended, v.summary, v.last, v.request], [true, "1 edit proposed", "one ask", "quicker"]);
+});
+
+test("Apply all: each op re-checked and written by its own writer, in order, the token carried; the ops marked applied", async () => {
+ const p = await project({
+ ops: [
+ { op: "look", id: "", key: "transition", value: 0.15 },
+ { op: "slide", id: "", key: "blur", value: 0.3 },
+ { op: "clip_edges", id: "r002", key: "start", value: 90 },
+ { op: "clip_room", id: "r003", key: "off", value: true },
+ ],
+ });
+ try {
+ const token = await manifestToken(p.dir);
+ const r = await applyAssistOps(p, { token, now: AT });
+ assert.deepEqual(r.applied, ["a1", "a2", "a3", "a4"]);
+ assert.deepEqual(r.failed, []);
+ assert.equal(r.token, await manifestToken(p.dir));
+ const m = await read(p.dir);
+ assert.equal(m.render.transition, 0.15);
+ assert.deepEqual(m.render.slide, { blur: 0.3 });
+ const r002 = m.timeline.find((e) => e.id === "r002");
+ assert.deepEqual([r002.cutStart, r002.cutEnd], [90, 99]);
+ assert.equal(r002.assist.by, "operator", "the clip editor's writer: an edit of an assistant's clip is the operator's");
+ assert.equal(m.timeline.find((e) => e.id === "r003").room, false);
+ const { doc } = await readAssistProposals(p.dir);
+ assert.deepEqual(doc.ops.map((o) => [o.id, o.status, o.at]), [["a1", "applied", AT], ["a2", "applied", AT], ["a3", "applied", AT], ["a4", "applied", AT]]);
+ await assert.rejects(applyAssistOps(p, {}), /nothing is waiting to apply/);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("Apply one; a stale token is a 409 before anything is written; newer proposals are refused by `at`", async () => {
+ const p = await project({ ops: [{ op: "look", id: "", key: "qr", value: false }, { op: "look", id: "", key: "loudness", value: -14 }] });
+ try {
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(applyAssistOps(p, { token: "123" }), StaleToken);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+ await assert.rejects(applyAssistOps(p, { at: "2026-01-01T00:00:00.000Z" }), (e) => e instanceof AssistRequestError && e.status === 409);
+ const r = await applyAssistOps(p, { ids: ["a2"], token: await manifestToken(p.dir) });
+ assert.deepEqual(r.applied, ["a2"]);
+ const m = await read(p.dir);
+ assert.deepEqual([m.render.qr, m.render.loudness], [undefined, { target: -14 }]);
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["proposed", "applied"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("an op the manifest no longer allows fails at Apply with the reason; the view says so before", async () => {
+ const p = await project({ ops: [{ op: "clip_edges", id: "r001", key: "end", value: 48 }, { op: "look", id: "", key: "transition", value: 0.15 }] });
+ try {
+ // Somebody narrowed r001's window meanwhile, and set the join themselves.
+ const m = await read(p.dir);
+ m.timeline[0].end = 47.5;
+ await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n");
+ await updateRender(p.dir, { transition: 0.15 });
+ const v = await proposalsView(p.dir);
+ assert.match(v.proposals.ops[0].now, /outside the clip's source window \(38\.5–47\.5 s\)/);
+ assert.match(v.proposals.ops[1].now, /join is already that/);
+ const r = await applyAssistOps(p, {});
+ assert.deepEqual(r.applied, []);
+ assert.deepEqual(r.failed.map((f) => f.id), ["a1", "a2"]);
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["failed", "failed"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
+
+test("a composition's param through updateChrome; Dismiss changes nothing but the marks", async () => {
+ const p = await project({ deck: true, ops: [{ op: "fx", id: "deck", key: "motion.in", value: 0.6 }, { op: "fx", id: "fx.glitch", key: "seconds", value: 0.8 }] });
+ try {
+ const r = await applyAssistOps(p, { ids: ["a1"] });
+ assert.deepEqual(r.applied, ["a1"]);
+ const m = await read(p.dir);
+ assert.deepEqual(m.render.chrome.deck, { qr: { show: false }, motion: { in: 0.6 } });
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ const d = await dismissAssistOps(p.dir, { at: AT });
+ assert.deepEqual(d.dismissed, ["a2"]);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before, "Dismiss writes no manifest");
+ assert.deepEqual((await readAssistProposals(p.dir)).doc.ops.map((o) => o.status), ["applied", "dismissed"]);
+ } finally {
+ await rm(p.dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -165,6 +165,8 @@ import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage
import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { blurSlideEdges, validateTransitionStyle, xfadeTransitionOf } from "./transition.mjs";
+import { JOIN_PREVIEW_FILE, JOIN_PREVIEW_RECORD, joinPreviewTimeline } from "./join-preview.mjs";
+import { lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
// The look of a highlights cut (release 36 lane C): render.captions,
// render.loudness, a clip's vertical crop and the short made from it -- pure,
// in look.mjs. Every hook below runs only when its key is set.
@@ -5144,6 +5146,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
if (e.type !== "clip") throw new Error(`${opts.short} is a ${e.type ?? "non-clip"} entry: a short is made from a clip`);
manifest.render = shortRender(manifest.render ?? {});
}
+ // A join preview (release 38, join-preview.mjs): the first few joins of
+ // the cut, each clip shortened to a few seconds at the join, in the cut's look.
+ if (opts.joinPreview) {
+ if (only || fetchOnly) throw new Error("--join-preview builds the joins: not with --only, --short or --fetch-only");
+ manifest.timeline = joinPreviewTimeline(manifest, { from: opts.joinPreview.from ?? null });
+ EMIT("note", { message: `join preview: ${manifest.timeline.map((e) => e.id).join(", ")}` });
+ }
for (const message of rulingsLines(ruled)) EMIT("note", { message });
const { render, provenance } = manifest;
// A `src` clip's file and cues, checked and measured before anything else.
@@ -5220,6 +5229,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const dirs = variantPaths(outRoot, manifest.slug, variant);
// A short's work is its own: the cut's segments are never overwritten by one.
if (opts.short) dirs.dir = path.join(outRoot, "shorts-work");
+ // A join preview's too: its own work dir and file, the cut's out/ untouched.
+ if (opts.joinPreview) {
+ dirs.dir = path.join(outRoot, "join-preview-work");
+ dirs.final = path.join(outRoot, JOIN_PREVIEW_FILE);
+ }
const outDir = dirs.dir;
// Where media may already be on disk. The channels tree is the one the clip
// bench reads for this project (sources.mjs channelsDirFor): the manifest's
@@ -5829,6 +5843,16 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// shortest=1), and a hang means an unbounded -loop 1.
if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build");
+ // A join preview ends here: no chapters, no YouTube text, no thumbnail --
+ // those are the cut's. A record beside it says what it was made from.
+ if (opts.joinPreview) {
+ await pruneFrames();
+ const record = { version: 1, madeAt: new Date().toISOString(), clips: manifest.timeline.map((e) => e.id), look: lookOf(render) };
+ await replaceFile(path.join(outRoot, JOIN_PREVIEW_RECORD), JSON.stringify(record, null, 2) + "\n");
+ EMIT("done", { out: final, failures: [], joinPreview: true });
+ return { out: final, failures };
+ }
+
const muxed = opts.noChapters
? null
: await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") });
@@ -5975,6 +5999,7 @@ async function main() {
console.error(
"usage: build-video.mjs <manifest.json> [--out <dir>] [--variant sourced|full]\n" +
" [--only <id>] [--fetch-only <id>] [--short <id>] (a vertical short of one clip: <project>/shorts/<id>.mp4)\n" +
+ " [--join-preview [--join-from <id>]] (the first few joins, a few seconds each side: out/join-preview.mp4)\n" +
" [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" +
" [--progress ndjson] [--continue-on-error] [--no-reuse]\n" +
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
@@ -6023,6 +6048,7 @@ async function main() {
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
short: flag("--short") ?? null,
+ joinPreview: argv.includes("--join-preview") ? { from: flag("--join-from") ?? null } : null,
};
try {
Object.assign(opts, chromeFlags(argv));
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -15,6 +15,7 @@
// No ffmpeg, no fs, no network. If a function here needs one, it belongs in
// build-video.mjs or compose-chrome.mjs instead.
import { createHash } from "node:crypto";
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { attributionParts, deckSubtitle } from "./attribution.mjs";
import {
@@ -74,6 +75,14 @@ export const DECK_DEFAULTS = Object.freeze({
}),
});
+/**
+ * The deck's TUNABLE params (release 38): the settings the video assistant's
+ * `fx` op may set by name, each with the bounds validateChrome holds it to
+ * (declared in common lib/report/fxParams.mjs; fx-params.test.mjs keeps the
+ * two in step).
+ */
+export const DECK_PARAMS = COMPOSITION_PARAMS.deck;
+
/** Where a clip's deck QR links (`qr.links`): the archive at the clip, or the original. */
export const QR_LINKS = Object.freeze(["site", "original"]);
diff --git a/umtool/report-to-video/fx-params.test.mjs b/umtool/report-to-video/fx-params.test.mjs
@@ -0,0 +1,79 @@
+// The compositions' declared params (release 38 lane E, common
+// lib/report/fxParams.mjs) held to the validators that build them: every
+// declared param is accepted at its bounds and its default and refused just
+// past them, so a declaration cannot promise the video assistant a value the
+// deck's own check refuses.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { COMPOSITION_PARAMS, chromeWithParam, compositionOn } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+import { DECK_PARAMS, validateChrome } from "./deck.mjs";
+import { STATS_PARAMS } from "./stats.mjs";
+import { FX_KEYS, FX_PARAMS } from "./fx.mjs";
+
+// Each composition on, with the one setting validateChrome needs beside it.
+const ON = {
+ deck: {},
+ stats: { stats: {} },
+ "fx.kineticQuote": { fx: { kineticQuote: {} } },
+ "fx.redact": { fx: { redact: {} } },
+ "fx.odometer": { fx: { odometer: {} } },
+ "fx.scrubber": { fx: { scrubber: {} } },
+ "fx.glitch": { fx: { glitch: {} } },
+ "fx.thenNow": { fx: { thenNow: { pairs: [{ then: "c1", now: "c2" }] } } },
+ "fx.receipts": { fx: { receipts: {} } },
+ "fx.zoom": { fx: { zoom: {} } },
+ "fx.punchIn": { fx: { punchIn: {} } },
+ "fx.whip": { fx: { whip: {} } },
+};
+const renderOf = (id) => ({ width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck", deck: {}, ...ON[id] } });
+const errorsWith = (id, key, value) => {
+ const render = renderOf(id);
+ const chrome = chromeWithParam(render, id, key, value);
+ assert.ok(chrome, `${id}.${key}: chromeWithParam gave nothing`);
+ const { chrome: _c, ...rest } = render;
+ return validateChrome(chrome, rest);
+};
+
+test("the modules re-export their slice of the declarations", () => {
+ assert.equal(DECK_PARAMS, COMPOSITION_PARAMS.deck);
+ assert.equal(STATS_PARAMS, COMPOSITION_PARAMS.stats);
+ assert.deepEqual(Object.keys(FX_PARAMS).sort(), Object.keys(COMPOSITION_PARAMS).filter((k) => k.startsWith("fx.")).map((k) => k.slice(3)).sort());
+ for (const k of Object.keys(FX_PARAMS)) assert.ok(FX_KEYS.includes(k), `${k} is an effect`);
+ for (const id of Object.keys(COMPOSITION_PARAMS)) assert.ok(ON[id], `${id} has a fixture here`);
+});
+
+test("every declared param: its default and both bounds build; just past them, the validator refuses", () => {
+ for (const [id, params] of Object.entries(COMPOSITION_PARAMS)) {
+ assert.ok(compositionOn(renderOf(id), id), `${id} is on in its fixture`);
+ for (const p of params) {
+ const where = `${id}.${p.key}`;
+ assert.deepEqual(errorsWith(id, p.key, p.default), [], `${where} default`);
+ if (p.kind === "enum") {
+ for (const v of p.values) assert.deepEqual(errorsWith(id, p.key, v), [], `${where} = ${v}`);
+ assert.ok(errorsWith(id, p.key, "nope").length, `${where} = "nope" is refused`);
+ } else if (p.kind === "bool") {
+ for (const v of [true, false]) assert.deepEqual(errorsWith(id, p.key, v), [], `${where} = ${v}`);
+ assert.ok(errorsWith(id, p.key, "yes").length, `${where} = "yes" is refused`);
+ } else if (p.kind === "text") {
+ assert.deepEqual(errorsWith(id, p.key, "x".repeat(p.maxLength)), [], `${where} at its length`);
+ assert.ok(errorsWith(id, p.key, "x".repeat(p.maxLength + 1)).length, `${where} past its length is refused`);
+ } else {
+ const eps = p.kind === "int" ? 1 : 0.01;
+ assert.deepEqual(errorsWith(id, p.key, p.min), [], `${where} = min ${p.min}`);
+ assert.deepEqual(errorsWith(id, p.key, p.max), [], `${where} = max ${p.max}`);
+ assert.ok(errorsWith(id, p.key, p.min - eps).length, `${where} below min is refused`);
+ assert.ok(errorsWith(id, p.key, p.max + eps).length, `${where} above max is refused`);
+ }
+ }
+ }
+});
+
+test("a composition the cut does not draw has nothing to set", () => {
+ const plain = { width: 1920, height: 1080 };
+ assert.equal(compositionOn(plain, "deck"), false);
+ assert.equal(chromeWithParam(plain, "deck", "motion.in", 0.3), null);
+ assert.equal(compositionOn(renderOf("deck"), "fx.glitch"), false);
+ assert.equal(chromeWithParam(renderOf("deck"), "deck", "height", 300), null, "an undeclared param");
+});
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -29,6 +29,8 @@
// way round -- and it imports nothing of the montage's (montage.mjs imports
// deck.mjs), so the few date and phrase helpers it needs are its own.
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+
/** Each effect's key under `render.chrome.fx`, in the order the page stacks them (later on top). */
export const FX_KEYS = Object.freeze(["scrubber", "receipts", "zoom", "kineticQuote", "redact", "odometer", "punchIn", "thenNow", "whip", "glitch"]);
@@ -62,6 +64,16 @@ export const FX_DEFAULTS = Object.freeze({
whip: Object.freeze({ on: "every" }),
});
+/**
+ * Each effect's TUNABLE params (release 38), keyed by effect: the settings the
+ * video assistant's `fx` op may set by name ("fx.<effect>"), with the bounds
+ * validateFx holds them to (declared in common lib/report/fxParams.mjs;
+ * fx-params.test.mjs keeps the two in step).
+ */
+export const FX_PARAMS = Object.freeze(
+ Object.fromEntries(Object.entries(COMPOSITION_PARAMS).filter(([id]) => id.startsWith("fx.")).map(([id, ps]) => [id.slice(3), ps])),
+);
+
/** The motion every effect shares, in seconds. */
export const FX_MOTION = Object.freeze({
word: 0.14, // a word coming in
diff --git a/umtool/report-to-video/join-preview.mjs b/umtool/report-to-video/join-preview.mjs
@@ -0,0 +1,51 @@
+// A JOIN PREVIEW (release 38 lane E): a few seconds either side of the first
+// few joins of a cut, in the cut's own look -- the quick render the video
+// assistant's Ask box and the Look panel play to judge a join's length,
+// style, slide and room before a full build. `build-video.mjs <manifest>
+// --join-preview [--join-from <clip id>]` writes out/join-preview.mp4 (and
+// out/join-preview.json, what it was made from) through the heavy slot, as a
+// full build does; nothing of the cut's own out/ files is touched.
+//
+// The cut: JOIN_PREVIEW_CLIPS consecutive clips (from `from`, else the first),
+// every other entry left out; each clip keeps the last JOIN_PREVIEW_SECONDS
+// of its cut (so its tail -- where room and the join act -- is its own), the
+// last one the first JOIN_PREVIEW_SECONDS. The windows are untouched, so the
+// media already fetched for the cut is what the preview cuts from.
+//
+// PURE: the manifest in, a timeline out.
+
+export const JOIN_PREVIEW_CLIPS = 4;
+export const JOIN_PREVIEW_SECONDS = 3;
+export const JOIN_PREVIEW_FILE = "join-preview.mp4";
+export const JOIN_PREVIEW_RECORD = "join-preview.json";
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (n) => Math.round(n * 100) / 100;
+
+/**
+ * The preview's timeline, or a thrown reason it cannot be made.
+ *
+ * @param {{ render?: Record<string, unknown>, timeline?: Record<string, unknown>[] }} manifest
+ * @param {{ from?: string | null, clips?: number, seconds?: number }} [o]
+ */
+export function joinPreviewTimeline(manifest, { from = null, clips = JOIN_PREVIEW_CLIPS, seconds = JOIN_PREVIEW_SECONDS } = {}) {
+ const render = manifest?.render ?? {};
+ if (render.chrome !== undefined && render.chrome !== null) throw new Error("a join preview is a plain cut's: this one is drawn under the deck (a full build or --chrome-preview shows its joins)");
+ if (render.montage !== undefined && render.montage !== null) throw new Error("a join preview is a plain cut's: a montage cuts to its phrases");
+ if (!(fin(render.transition) ? render.transition > 0 : true)) throw new Error("this cut has hard cuts (render.transition 0): there is no join to preview");
+ const all = (manifest?.timeline ?? []).filter((e) => e?.type === "clip");
+ const at = from ? all.findIndex((e) => e.id === from) : 0;
+ if (at < 0) throw new Error(`no clip ${from} in the cut`);
+ const picked = all.slice(at, at + clips);
+ if (picked.length < 2) throw new Error("a join preview needs two clips after it starts");
+ return picked.map((e, i) => {
+ const a = fin(e.cutStart) && fin(e.cutEnd) ? e.cutStart : e.start;
+ const b = fin(e.cutStart) && fin(e.cutEnd) ? e.cutEnd : e.end;
+ if (!fin(a) || !fin(b) || b - a <= seconds) return { ...e };
+ const last = i === picked.length - 1;
+ const cut = last ? { cutStart: r2(a), cutEnd: r2(a + seconds) } : { cutStart: r2(b - seconds), cutEnd: r2(b) };
+ // A mute mark stays: before the shortened cut it mutes all of it, as it
+ // mutes that stretch of the full cut; past it, nothing, as in the cut.
+ return { ...e, ...cut };
+ });
+}
diff --git a/umtool/report-to-video/join-preview.test.mjs b/umtool/report-to-video/join-preview.test.mjs
@@ -0,0 +1,35 @@
+// The join preview's cut (release 38 lane E, join-preview.mjs).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { JOIN_PREVIEW_SECONDS, joinPreviewTimeline } from "./join-preview.mjs";
+
+const clip = (id, a, b, extra = {}) => ({ type: "clip", id, channel: "ch", video: "v1", start: a - 1.5, end: b + 1.5, cutStart: a, cutEnd: b, ...extra });
+const M = (timeline, render = {}) => ({ render: { transition: 0.22, transitionStyle: "blurslide", ...render }, timeline });
+
+test("four clips from the first: each keeps the last seconds of its cut, the last its first seconds; cards left out", () => {
+ const tl = [{ type: "card", id: "t0" }, clip("a", 10, 20), clip("b", 30, 32), clip("c", 40, 50, { muteFrom: 41 }), clip("d", 60, 70), clip("e", 80, 90)];
+ const out = joinPreviewTimeline(M(tl));
+ assert.deepEqual(out.map((e) => [e.id, e.cutStart, e.cutEnd, e.start, e.end]), [
+ ["a", 20 - JOIN_PREVIEW_SECONDS, 20, 8.5, 21.5],
+ ["b", 30, 32, 28.5, 33.5],
+ ["c", 47, 50, 38.5, 51.5],
+ ["d", 60, 63, 58.5, 71.5],
+ ]);
+ assert.equal(out[2].muteFrom, 41, "a mute mark before the shortened cut stays (it mutes all of it, as in the cut)");
+ // From a named clip.
+ assert.deepEqual(joinPreviewTimeline(M(tl), { from: "c" }).map((e) => e.id), ["c", "d", "e"]);
+ // A clip with no cut fields is shortened the same way, inside its edges.
+ const plain = joinPreviewTimeline(M([{ type: "clip", id: "x", start: 0, end: 10 }, { type: "clip", id: "y", start: 20, end: 30 }]));
+ assert.deepEqual(plain.map((e) => [e.cutStart, e.cutEnd]), [[7, 10], [20, 23]]);
+});
+
+test("refused: a deck, a montage, hard cuts, fewer than two clips, an unknown clip", () => {
+ const tl = [clip("a", 10, 20), clip("b", 30, 40)];
+ assert.throws(() => joinPreviewTimeline(M(tl, { chrome: { engine: "hyperframes", layout: "deck" } })), /plain cut's: this one is drawn under the deck/);
+ assert.throws(() => joinPreviewTimeline(M(tl, { montage: {} })), /a montage cuts to its phrases/);
+ assert.throws(() => joinPreviewTimeline(M(tl, { transition: 0 })), /no join to preview/);
+ assert.throws(() => joinPreviewTimeline(M(tl), { from: "b" }), /needs two clips/);
+ assert.throws(() => joinPreviewTimeline(M(tl), { from: "zz" }), /no clip zz/);
+});
diff --git a/umtool/report-to-video/look.mjs b/umtool/report-to-video/look.mjs
@@ -23,17 +23,36 @@
// other #F6F1E6 paper bottom centre (a third voice, or a word heard in no turn)
// Black outline (3 px at 1080p), soft shadow. ASS colours are &HAABBGGRR.
-import { validateRoom } from "./room.mjs";
+// The checks (captions, loudness, the vertical crop, room) and their bounds
+// are the look's rules (common lib/report/look.mjs, release 38): re-exported
+// here, so the writer, the build and the video assistant refuse the same things.
+import { DEFAULT_SOURCE_ASPECT, VERTICAL_RATIO, loudnessTargetOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+export {
+ CAPTION_LABEL_MAX,
+ CAPTION_SIZES,
+ CAPTION_STYLES,
+ DEFAULT_SOURCE_ASPECT,
+ LOUDNESS_MAX,
+ LOUDNESS_MIN,
+ VERTICAL_RATIO,
+ VERTICAL_TOLERANCE,
+ captionsOn,
+ loudnessOn,
+ loudnessTargetOf,
+ validateCaptions,
+ validateLoudness,
+ validateLook,
+ validateVertical,
+ verticalErrors,
+} from "yt-dlp-transcript-common/lib/report/look.mjs";
-export const CAPTION_STYLES = Object.freeze(["speakers"]);
-export const CAPTION_SIZES = Object.freeze(["m", "l"]);
export const CAPTION_ROLES = Object.freeze(["host", "subject", "other"]);
export const CAPTION_COLOURS = Object.freeze({ host: "#FFC840", subject: "#6FD3FF", other: "#F6F1E6" });
/** ASS alignment (numpad): host bottom-left, subject bottom-right, other bottom-centre. */
export const CAPTION_ALIGN = Object.freeze({ host: 1, subject: 3, other: 2 });
/** The font, vendored in fonts/ (IBM Plex Sans, OFL): libass is pointed at that directory. */
export const CAPTION_FONT = "IBM Plex Sans";
-export const CAPTION_LABEL_MAX = 40;
/** Words a line: at least (unless a speaker change or the clip's end forces fewer), at most. */
export const CAPTION_MIN_WORDS = 2;
export const CAPTION_MAX_WORDS = 6;
@@ -42,115 +61,14 @@ export const CAPTION_PAUSE = 0.45;
/** How long a line stays up after its last word (s), never past the next line. */
export const CAPTION_HOLD = 0.3;
-export const LOUDNESS_MIN = -30;
-export const LOUDNESS_MAX = -8;
/** A short's target when the cut sets none. */
export const SHORT_LOUDNESS = -16;
export const SHORT_WIDTH = 1080;
export const SHORT_HEIGHT = 1920;
-export const VERTICAL_RATIO = 9 / 16;
-/** How far a crop's shape may be from 9:16 (relative): the build fits it exactly. */
-export const VERTICAL_TOLERANCE = 0.03;
-export const DEFAULT_SOURCE_ASPECT = 16 / 9;
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
-const q = (v) => JSON.stringify(v);
-
-export const captionsOn = (render) => isObj(render?.captions);
-export const loudnessOn = (render) => isObj(render?.loudness) && num(render.loudness.target);
-/** The target in LUFS, or null when the cut sets none. */
-export const loudnessTargetOf = (render) => (loudnessOn(render) ? render.loudness.target : null);
-
-/** `render.captions`: its keys and values, and what it does not combine with. */
-export function validateCaptions(manifest) {
- const render = manifest?.render ?? {};
- const c = render.captions;
- if (c === undefined || c === null) return [];
- if (!isObj(c)) return [`render.captions must be an object ({style: "speakers"}) or absent, not ${q(c)}`];
- const errors = [];
- for (const k of Object.keys(c)) {
- if (!["style", "labels", "size"].includes(k)) errors.push(`render.captions.${k} is not a setting here (the settings are style, labels, size)`);
- }
- if (!CAPTION_STYLES.includes(c.style)) errors.push(`render.captions.style must be "speakers", not ${q(c.style)}`);
- if (c.size !== undefined && !CAPTION_SIZES.includes(c.size)) errors.push(`render.captions.size must be "m" or "l", not ${q(c.size)}`);
- if (c.labels !== undefined && c.labels !== null) {
- if (!isObj(c.labels)) errors.push(`render.captions.labels must be an object ({host, subject}), not ${q(c.labels)}`);
- else {
- for (const [k, v] of Object.entries(c.labels)) {
- if (k !== "host" && k !== "subject") errors.push(`render.captions.labels.${k} is not a role here (host, subject)`);
- else if (v !== null && (typeof v !== "string" || v.length > CAPTION_LABEL_MAX)) {
- errors.push(`render.captions.labels.${k} must be a short text (up to ${CAPTION_LABEL_MAX} characters), or null`);
- }
- }
- }
- }
- if (isObj(render.chrome)) errors.push("render.captions does not combine with render.chrome (the deck draws its own words: render.chrome.fx.kineticQuote)");
- if (render.montage !== undefined && render.montage !== null) errors.push("render.captions does not combine with render.montage (a montage re-times its clips)");
- return errors;
-}
-
-/** `render.loudness`: `{target}` in LUFS. */
-export function validateLoudness(manifest) {
- const render = manifest?.render ?? {};
- const l = render.loudness;
- if (l === undefined || l === null) return [];
- if (!isObj(l)) return [`render.loudness must be an object ({target: -16}) or absent, not ${q(l)}`];
- const errors = [];
- for (const k of Object.keys(l)) if (k !== "target") errors.push(`render.loudness.${k} is not a setting here (the setting is target)`);
- if (!num(l.target) || l.target < LOUDNESS_MIN || l.target > LOUDNESS_MAX) {
- errors.push(`render.loudness.target must be a number from ${LOUDNESS_MIN} to ${LOUDNESS_MAX} LUFS, not ${q(l.target)}`);
- }
- if (render.montage !== undefined && render.montage !== null) errors.push("render.loudness does not combine with render.montage (a montage levels with render.montage.loudness)");
- return errors;
-}
-
-/** One clip's `vertical` (null when it has none): its errors, prefixed by `who`. */
-export function verticalErrors(v, who = "vertical") {
- if (v === undefined || v === null) return [];
- if (!isObj(v)) return [`${who} must be an object ({crop: [x, y, w, h]}), not ${q(v)}`];
- const errors = [];
- for (const k of Object.keys(v)) if (k !== "crop" && k !== "aspect") errors.push(`${who}.${k} is not a setting here (crop, aspect)`);
- if (v.aspect !== undefined && (!num(v.aspect) || v.aspect <= 0.2 || v.aspect > 5)) {
- errors.push(`${who}.aspect must be the source's width / height (a number from 0.2 to 5), not ${q(v.aspect)}`);
- }
- const c = v.crop;
- if (!Array.isArray(c) || c.length !== 4 || !c.every(num)) {
- errors.push(`${who}.crop must be [x, y, w, h], four fractions of the source picture`);
- return errors;
- }
- const [x, y, w, h] = c;
- const E = 1e-3;
- if (w <= 0 || h <= 0) errors.push(`${who}.crop's width and height must be above 0`);
- if (x < -E || y < -E || x + w > 1 + E || y + h > 1 + E) errors.push(`${who}.crop must lie inside the picture (each of x, y, x + w, y + h from 0 to 1)`);
- if (w > 0 && h > 0) {
- const aspect = num(v.aspect) ? v.aspect : DEFAULT_SOURCE_ASPECT;
- const shape = (w * aspect) / h;
- if (Math.abs(shape / VERTICAL_RATIO - 1) > VERTICAL_TOLERANCE) {
- errors.push(`${who}.crop must be 9:16 on the source (w × aspect / h ≈ 0.5625; this one is ${shape.toFixed(4)})`);
- }
- }
- return errors;
-}
-
-/** Every clip's `vertical`. */
-export function validateVertical(manifest) {
- const errors = [];
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.vertical === undefined) return;
- const who = `timeline[${i}] (${e?.id ?? "?"}).vertical`;
- if (e?.type !== "clip") errors.push(`${who}: only a clip has a vertical crop`);
- else errors.push(...verticalErrors(e.vertical, who));
- });
- return errors;
-}
-
-/** All of the look's keys: the build's validators and the lint call this. */
-export function validateLook(manifest) {
- // render.room and a clip's room (room.mjs, release 36 lane E) are part of the look.
- return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest)];
-}
// ---------------------------------------------------------------------------
// The vertical crop.
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -34,6 +34,7 @@
"./montage-rulings": "./montage-rulings.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",
+ "./join-preview": "./join-preview.mjs",
"./look": "./look.mjs",
"./mute": "./mute.mjs",
"./narration": "./narration.mjs",
diff --git a/umtool/report-to-video/room.mjs b/umtool/report-to-video/room.mjs
@@ -36,90 +36,16 @@
// fetch pad) clamps it -- the build says so, and the lint warns when the
// room can reach past the window.
-export const ROOM = Object.freeze({
- /** A gap between two words this long (s) is the silence the sound stops at. */
- minGap: 0.35,
- /** The sound never runs more than this (s) past the cut's end. */
- maxS: 2.5,
- /** The fade at the silence point, and the fade in at a muted head (s). */
- fade: 0.06,
- /** Muted picture past D, so the fade is done before the join begins (s). */
- pad: 0.1,
- /** silencedetect, when there are no words: noise floor (dB) and least length (s). */
- detectDb: -35,
- detectD: 0.3,
-});
-export const ROOM_EDGES = Object.freeze(["tail", "head"]);
-const MIN_GAP = [0.1, 2];
-const MAX_S = [0, 10];
+// ROOM, its edges, its bounds and validateRoom / roomOn / clipRoom are the
+// look's rules (common lib/report/look.mjs, release 38): re-exported here, so
+// the writer, the build and the video assistant refuse the same things.
+import { ROOM, clipRoom } from "yt-dlp-transcript-common/lib/report/look.mjs";
+
+export { ROOM, ROOM_BOUNDS, ROOM_EDGES, clipRoom, roomOn, validateRoom } from "yt-dlp-transcript-common/lib/report/look.mjs";
-const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
-const q = (v) => JSON.stringify(v);
const r3 = (n) => Math.round(n * 1000) / 1000;
-/** Does the cut's render block turn room on for either edge? */
-export const roomOn = (render) => isObj(render?.room) && (render.room.tail === true || render.room.head === true);
-
-/**
- * One clip's room: `{tail, head, minGap, maxS}` with at least one edge on, or
- * null. The clip's `room` (false, or per-edge booleans) beats the cut's.
- */
-export function clipRoom(entry, render) {
- const r = isObj(render?.room) ? render.room : null;
- const c = entry?.room;
- if (c === false) return null;
- const edge = (k) => (isObj(c) && typeof c[k] === "boolean" ? c[k] : r?.[k] === true);
- const tail = edge("tail");
- const head = edge("head");
- if (!tail && !head) return null;
- return {
- tail,
- head,
- minGap: num(r?.minGap) ? r.minGap : ROOM.minGap,
- maxS: num(r?.maxS) ? r.maxS : ROOM.maxS,
- };
-}
-
-/** `render.room` and every clip's `room`: each problem in a sentence naming the key. */
-export function validateRoom(manifest) {
- const render = manifest?.render ?? {};
- const errors = [];
- const room = render.room;
- if (room !== undefined && room !== null) {
- if (!isObj(room)) errors.push(`render.room must be an object ({tail: true, head: true}) or absent, not ${q(room)}`);
- else {
- for (const k of Object.keys(room)) {
- if (!["tail", "head", "minGap", "maxS"].includes(k)) errors.push(`render.room.${k} is not a setting here (tail, head, minGap, maxS)`);
- }
- for (const k of ROOM_EDGES) {
- if (room[k] !== undefined && typeof room[k] !== "boolean") errors.push(`render.room.${k} must be true or false, not ${q(room[k])}`);
- }
- if (room.minGap !== undefined && (!num(room.minGap) || room.minGap < MIN_GAP[0] || room.minGap > MIN_GAP[1])) {
- errors.push(`render.room.minGap must be seconds from ${MIN_GAP[0]} to ${MIN_GAP[1]}, not ${q(room.minGap)}`);
- }
- if (room.maxS !== undefined && (!num(room.maxS) || room.maxS < MAX_S[0] || room.maxS > MAX_S[1])) {
- errors.push(`render.room.maxS must be seconds from ${MAX_S[0]} to ${MAX_S[1]}, not ${q(room.maxS)}`);
- }
- if (render.montage !== undefined && render.montage !== null) errors.push("render.room does not combine with render.montage (a montage cuts to its phrases)");
- }
- }
- (manifest?.timeline ?? []).forEach((e, i) => {
- if (e?.room === undefined) return;
- const who = `timeline[${i}] (${e?.id ?? "?"}).room`;
- if (e?.type !== "clip") errors.push(`${who}: only a clip has room at its edges`);
- else if (e.room === false || e.room === null) return;
- else if (!isObj(e.room)) errors.push(`${who} must be false or {tail?, head?}, not ${q(e.room)}`);
- else {
- for (const [k, v] of Object.entries(e.room)) {
- if (!ROOM_EDGES.includes(k)) errors.push(`${who}.${k} is not a setting here (tail, head)`);
- else if (typeof v !== "boolean") errors.push(`${who}.${k} must be true or false, not ${q(v)}`);
- }
- }
- });
- return errors;
-}
-
/** Timed words, in time order (any of the transcribers' keys for the text is fine; only times are read). */
function timed(words) {
return (Array.isArray(words) ? words : [])
diff --git a/umtool/report-to-video/stats.mjs b/umtool/report-to-video/stats.mjs
@@ -15,6 +15,8 @@
// PURE, like factcheck.mjs: validation, the defaults, the schedule. No fs, no
// ffmpeg. deck.mjs imports this file -- never the other way round.
+import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+
/** Where the stats sit in the footage box. */
export const STATS_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]);
@@ -31,6 +33,9 @@ export const STATS_LABELS = Object.freeze({ stack: "Stack", stackBB: "Big blinds
*/
export const STATS_DEFAULTS = Object.freeze({ position: "bottom-left", fields: STATS_FIELDS, name: true });
+/** The stats panel's TUNABLE params (release 38; common lib/report/fxParams.mjs): what the video assistant's `fx` op may set. */
+export const STATS_PARAMS = COMPOSITION_PARAMS.stats;
+
/** How long the panel takes to come in and go out, in seconds. */
export const STATS_MOTION = Object.freeze({ in: 0.3, out: 0.25 });
diff --git a/umtool/report-to-video/transition.mjs b/umtool/report-to-video/transition.mjs
@@ -12,24 +12,21 @@
// five taps spaced by the moment's speed (most at the start, none as it lands),
// and the frames nearest the seam take a light temporal grain. One xfade
// custom expression (`pushExpr`) plus the grain on each clip's edge.
-export const TRANSITION_STYLES = Object.freeze(["fade", "fadeblack", "fadewhite", "dissolve", "blurslide"]);
+//
+// The style list, the slide's knobs and their checks are the look's rules
+// (common lib/report/look.mjs, release 38): re-exported here, so the writer,
+// the build and the video assistant refuse the same things.
+import { slideOf, transitionStyleOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
-/** The style a plain join uses (`render.transitionStyle`, default "fade"). */
-export const transitionStyleOf = (render) => render?.transitionStyle ?? "fade";
-
-// The push's knobs (`render.slide`): travel = fraction of the width the
-// pictures move; blur = motion-smear strength (0 none, 1 = a frame's travel);
-// grain = noise strength on the seam's frames (0 none).
-export const SLIDE_DEFAULTS = Object.freeze({ travel: 0.08, blur: 0.5, grain: 2 });
-const SLIDE_BOUNDS = Object.freeze({ travel: [0, 0.5], blur: [0, 2], grain: [0, 20] });
-
-/** The push's knobs, the defaults filled in. */
-export function slideOf(render) {
- const s = render?.slide && typeof render.slide === "object" ? render.slide : {};
- const out = {};
- for (const k of Object.keys(SLIDE_DEFAULTS)) out[k] = Number.isFinite(s[k]) ? s[k] : SLIDE_DEFAULTS[k];
- return out;
-}
+export {
+ SLIDE_BOUNDS,
+ SLIDE_DEFAULTS,
+ TRANSITION_STYLES,
+ slideOf,
+ transitionStyleOf,
+ validateSlide,
+ validateTransitionStyle,
+} from "yt-dlp-transcript-common/lib/report/look.mjs";
/**
* The push as an xfade custom expression, for a join `D` seconds long at `fps`.
@@ -89,27 +86,3 @@ export function blurSlideEdges(d, D, render, { tail = false, head = false } = {}
if (head) parts.push(`lt(t,${w.toFixed(3)})`);
return `noise=alls=${Math.round(grain)}:allf=t+u:enable='${parts.join("+")}'`;
}
-
-/** @param {{ render?: { transitionStyle?: unknown } }} manifest */
-export function validateTransitionStyle(manifest) {
- const s = manifest?.render?.transitionStyle;
- const slide = validateSlide(manifest);
- if (s === undefined || s === null) return slide;
- return typeof s === "string" && TRANSITION_STYLES.includes(s)
- ? slide
- : [`render.transitionStyle: ${JSON.stringify(s)} is not one of ${TRANSITION_STYLES.join(", ")}`, ...slide];
-}
-
-/** `render.slide`: absent, or an object of the push's knobs within bounds. */
-export function validateSlide(manifest) {
- const s = manifest?.render?.slide;
- if (s === undefined || s === null) return [];
- if (typeof s !== "object" || Array.isArray(s)) return ["render.slide must be an object {travel?, blur?, grain?}"];
- const errs = [];
- for (const [k, v] of Object.entries(s)) {
- const b = SLIDE_BOUNDS[k];
- if (!b) errs.push(`render.slide.${k} is not a key (travel, blur, grain)`);
- else if (!Number.isFinite(v) || v < b[0] || v > b[1]) errs.push(`render.slide.${k} must be a number from ${b[0]} to ${b[1]}`);
- }
- return errs;
-}