Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 683118e56daaff13b843071819176bf7e28ab4ea
parent ee19da711b740b48e70228781f90df2575ca83cb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 02:22:37 -0400

Merge branch 'ux/integration' into ux/p3

Diffstat:
M.claude/commands/gen.md | 27++++++++++++++++++++-------
MCOMMANDS.md | 11+++++++----
MOPERATING.md | 49+++++++++++++++++++++++++++++++++++++++++++++----
MREPORT.md | 2+-
MSETTINGS.md | 54++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/bin/archilyzer.ts | 12++++++++++--
Mcommon/bin/gen.test.ts | 26+++++++++++++++++++++++---
Mcommon/bin/gen.ts | 17++++++++++++++---
Acommon/bin/reports-bench-verdicts.test.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/reports-bench-verdicts.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/reports-check.test.ts | 32++++++++++++++++++++++++++++++++
Mcommon/bin/reports-check.ts | 53++++++++++++++++++++++++++++++++++++++++++++++++-----
Acommon/controller/benchVerdicts.ts | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/relocateChannelMedia.test.ts | 15+++++++++++++++
Mcommon/controller/reportDraft.ts | 148++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Acommon/controller/researchAutoContinue.test.ts | 341+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/researchAutoContinue.ts | 357+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/researchRuns.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/jobs/jobKinds.test.ts | 2++
Mcommon/jobs/jobKinds.ts | 13+++++++++++++
Mcommon/jobs/registry.ts | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/lib/citations/fragment.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/citations/fragment.ts | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.test.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.ts | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/llm/structured.ts | 15++++++++++++++-
Mcommon/lib/report/convertManifest.ts | 10++++++++++
Mcommon/lib/report/docs.ts | 8++++++--
Mcommon/lib/report/draft/authoringRules.ts | 9++++++++-
Acommon/lib/report/draft/bench/bench.test.ts | 361+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/bench/index.ts | 8++++++++
Acommon/lib/report/draft/bench/items.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/bench/prompt.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/bench/run.ts | 334+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/bench/score.ts | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/bench/store.ts | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/grounding.test.ts | 34+++++++++++++++++++++++++++++++++-
Mcommon/lib/report/draft/grounding.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/lib/report/draft/reportOps.test.ts | 19+++++++++++++++++++
Mcommon/lib/report/draft/reportOps.ts | 13++++++++++---
Mcommon/lib/report/draft/research/state.ts | 22++++++++++++++++++++++
Mcommon/lib/report/draft/sweepModel.test.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/report/draft/sweepModel.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/clipEvidence.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/cut.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/cut.ts | 419+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/deckChecks.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/flips.ts | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Acommon/lib/report/draft/tasks/media.test.ts | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/media.ts | 494+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/narrate.ts | 186+++++++++++++++++++++++++++++++++++--------------------------------------------
Acommon/lib/report/draft/tasks/onscreen.test.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/onscreen.ts | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/panelTasks.test.ts | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/quotes.ts | 25+++++++++++++++++++++++--
Mcommon/lib/report/draft/tasks/research.ts | 6++++--
Mcommon/lib/report/draft/tasks/revise-report.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/lib/report/draft/tasks/revise-video.ts | 145++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mcommon/lib/report/draft/tasks/run.ts | 11++++++++++-
Mcommon/lib/report/draft/tasks/sweep-agent.ts | 18++++++++++++++----
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 25++++++++++++++++++++++---
Mcommon/lib/report/draft/tasks/tasks.test.ts | 23+++++++++++++++++++++++
Acommon/lib/report/draft/tasks/teaser.test.ts | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/teaser.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/threads.ts | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/types.ts | 20+++++++++++++++++++-
Acommon/lib/report/draft/tasks/youtube.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/videoOps.test.ts | 18+++++++++++++++++-
Mcommon/lib/report/draft/videoOps.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/drafted.d.mts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/drafted.mjs | 530+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/drafted.test.ts | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/panels.d.mts | 20++++++++++++++++++++
Acommon/lib/report/panels.mjs | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 6++++++
Mcommon/lib/settingsSchema.ts | 3+++
Mcommon/package.json | 2++
Acommon/publish/siteDelete.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/siteDelete.ts | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 6++++--
Mcommon/testing/draft/derive.ts | 2+-
Mcommon/testing/draft/manifests/basic.video.manifest.json | 10+++++++++-
Acommon/testing/draft/manifests/flips.video.manifest.json | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/manifests/full.video.manifest.json | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/draft/manifests/paragraphs.video.manifest.json | 10+++++++++-
Mcommon/testing/draft/manifests/posts-only.video.manifest.json | 10+++++++++-
Acommon/testing/draft/reports/ruled.report.json | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runMediaStep.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/cut.json | 20++++++++++++++++++++
Acommon/testing/draft/runs/flips.json | 21+++++++++++++++++++++
Acommon/testing/draft/runs/onscreen.json | 20++++++++++++++++++++
Acommon/testing/draft/runs/teaser.json | 20++++++++++++++++++++
Acommon/testing/draft/runs/threads.json | 21+++++++++++++++++++++
Acommon/testing/draft/runs/youtube.json | 21+++++++++++++++++++++
Acommon/testing/draft/sweeps/fragment.md | 11+++++++++++
Mcommon/testing/fakes.test.ts | 14++++++++++++++
Meditor/CHANGELOG.md | 26++++++++++++++++++++++++++
Aeditor/app/api/ops/_autoContinue.ts | 16++++++++++++++++
Aeditor/app/api/ops/_benchVerdicts.test.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/_reportDraft.test.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/bench-verdicts/route.ts | 29+++++++++++++++++++++++++++++
Aeditor/app/api/ops/delete-site/route.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 15++++++++++-----
Meditor/app/api/ops/research-approve/route.ts | 7++++---
Meditor/app/jobs/components/JobProgressBars.tsx | 9+++++++++
Meditor/app/scheduler/heartbeat.ts | 12++++++++++++
Meditor/app/sites/actions.ts | 41++++++++++++++++++++++++++++++++++++++---
Meditor/app/sites/components/SiteListActions.tsx | 133++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Meditor/e2e/backfill.spec.ts | 17+++++++++++++++--
Meditor/e2e/report-draft.spec.ts | 47+++++++++++++++++++++++++++++++++++++++++++++--
Aeditor/e2e/site-delete.spec.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/sites-crud.spec.ts | 5+++--
Meditor/instrumentation.ts | 11+++++++++++
Mmcp/src/draftTasks.test.ts | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mmcp/src/generation.test.ts | 88++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mmcp/src/generation.ts | 52++++++++++++++++++++++++++++++++++++++++------------
Mmcp/src/instructions.test.ts | 17++++++++++++++++-
Mmcp/src/instructions.ts | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mplans/FACTS.md | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/STATE.md | 43+++++++++++++++----------------------------
Aplans/release-28.md | 983+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 65++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mscripts/parakeet-stitch.mjs | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Ascripts/parakeet-stitch.test.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/queue-lock.test.mjs | 34+++++++++++++++++++++++++++++++---
Msettings.json.example | 19++++++++++++++++++-
Mumtool/app/api/articles/chain/route.ts | 33+++++++++++++++++++++------------
Mumtool/app/api/articles/delete/route.ts | 7++++++-
Aumtool/app/api/articles/draft/route.ts | 21+++++++++++++++++++++
Mumtool/app/api/articles/generate/route.ts | 11++++++++---
Aumtool/app/api/bench/bar/route.ts | 27+++++++++++++++++++++++++++
Aumtool/app/api/report/drafts/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/narration/route.ts | 8+++++---
Mumtool/app/articles/page.tsx | 3+++
Aumtool/app/bench/page.tsx | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 21+++++++++++++++------
Mumtool/components/articles/ChainPanel.tsx | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Aumtool/components/articles/ExtractorSelect.tsx | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/IterationsTab.tsx | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/components/articles/NewArticleForm.tsx | 6++++++
Mumtool/components/articles/ResearchSlot.tsx | 46+++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/components/bench/BarForm.tsx | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/DraftPanel.tsx | 355+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/DraftsReview.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/NarrationPage.tsx | 5+++--
Mumtool/components/projects/NarrationReview.tsx | 37+++++++++++++++++++++++++++++++++----
Mumtool/components/projects/OnscreenSection.tsx | 8++++++++
Mumtool/components/projects/ProjectView.tsx | 4++++
Mumtool/components/projects/ReportProject.tsx | 34++++++++++++++++++++++++++++++++++
Aumtool/components/projects/ReviewPage.tsx | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/StructureEditors.tsx | 28++++++++++++++++++++++++++--
Aumtool/components/projects/YoutubeSection.tsx | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/drafts.tsx | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/authoring.md | 17+++++++++++++++++
Mumtool/docs/report-video.md | 27++++++++++++++++++++-------
Mumtool/e2e/article-new.spec.ts | 6++++++
Mumtool/e2e/article-research.spec.ts | 32+++++++++++++++++++++++++++++++-
Aumtool/e2e/draft-review.spec.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/bench-fixture.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/draft-review-fixture.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 242++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/e2e/fixtures/make-fixture.mjs | 16++++++++++++++++
Aumtool/e2e/fixtures/media-draft-fixture.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/media-surfaces-fixture.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/youtube-fixture.mjs | 32++++++++++++++++++++++++++++++++
Aumtool/e2e/media-draft-e.spec.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/media-draft.spec.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/media-surfaces.spec.ts | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/narration-review.spec.ts | 14+++++++++-----
Aumtool/e2e/verdict-bench.spec.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/generation.ts | 39+++++++++++++++++++++++++--------------
Aumtool/lib/articles/projectDraft.ts | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/bench.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/chain-draft.mjs | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/report/chain-draft.test.mjs | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/chain-run.mjs | 162++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/report/chain.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/report/chain.test.mjs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafted-writer.test.mjs | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafts.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafts.test.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/driver.mjs | 5++++-
Mumtool/lib/report/manifest.mjs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/narration-review.mjs | 10+++++++---
Mumtool/report-to-video/README.md | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mumtool/report-to-video/build-video.mjs | 87++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Aumtool/report-to-video/drafts-review.mjs | 377+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/drafts-review.test.mjs | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/fixtures-r28.test.mjs | 35+++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/flips.mjs | 80++++---------------------------------------------------------------------------
Mumtool/report-to-video/lint.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/report-to-video/narration-review.mjs | 130++++++++++++++++++++++++-------------------------------------------------------
Mumtool/report-to-video/narration-review.test.mjs | 8+++++---
Mumtool/report-to-video/package.json | 4+++-
Mumtool/report-to-video/threads.mjs | 87+++++--------------------------------------------------------------------------
Aumtool/report-to-video/youtube.mjs | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/youtube.test.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
198 files changed, 18247 insertions(+), 864 deletions(-)

diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -8,20 +8,33 @@ each task. Use the archilyzer MCP tools only; run no script for it. 1. Call `mcp__archilyzer__generation_policy` with no arguments and read the routes, the models and the day's spend. 2. Map the request below to tasks: `sweep` (a new cited report), `revise-report` (a new iteration of an article's - report from feedback), `revise-video` (a new iteration of its video cut: cards, narration, title), `narrate` - (card narration drafts for a done iteration's cut), `research` (find what the corpus lacks and propose - acquisitions — archive.org imports, channels, posts — under an autonomy: propose, limits or auto; a sweep with - the research run's iteration continues it over the widened scope). The clip fetches, voices, render and podcast are the - pipeline's code, not generation: the operator runs that chain from umtool (the article's Iterations tab). + report from feedback), `revise-video` (a new iteration of its video cut from feedback), `research` (find what the + corpus lacks and propose acquisitions — archive.org imports, channels, posts — under an autonomy: propose, limits + or auto; a sweep with the research run's iteration continues it over the widened scope). A request to draft part + of a done iteration's video cut is a media draft, a step on that iteration (`iteration`; `entries` to limit it): + - `cut` — "pick the clips", "reorder the cut", "cut it down"; + - `onscreen` — "draft the on-screen titles", "titles and subtitles"; + - `teaser` — "make a teaser", "the teaser lines"; + - `flips` — "then and now", "the flip-flops", "THEN/NOW pairs"; + - `threads` — "group the clips into threads", "the threads panel"; + - `narrate` — "narrate it", "the card narration"; + - `youtube` — "YouTube title", "YouTube description", "the upload text". + "Draft everything" (every media draft in order, then voices, a fast build and the podcast) is the operator's button + on umtool's Iterations tab, or `umtool chain <article> <n> --draft-all`; it is not a `generate` task. The clip + fetches, voices, render and podcast are the pipeline's code, not generation: the operator runs that chain from umtool. 3. For each task routed to `api` or `local`, call `mcp__archilyzer__generate` with the task, the article, its inputs (question and channels for a sweep or research run; iteration and concrete feedback for a revision; - iteration for a narration) and `wait: true`, and do not redo its work yourself. If it answers still running, call it again with + iteration, and `entries` when the operator named some, for a media draft) and `wait: true`, and do not redo its + work yourself. If it answers still running, call it again with the job, article and iteration it names — never start the same task twice. Then REVIEW what it made, as its answer says: read the iteration's files, spot-check its quotes with `mcp__archilyzer__get_transcript`, read the ops it refused and its checks, and tell the operator what is good and what is not. Recommend making it current (the operator does that in umtool) or a revision; for a revision, call `generate` again with that feedback. A research run's proposals are the operator's to approve (umtool's research queue); say which you would approve - and why. Edit an iteration's files by hand only if the operator asks. + and why. A media draft's review is as its answer says: its `<task>-draft.json` and the drafted fields; the + operator approves or rejects each field in umtool (the project page's Review drafts) — never write + `drafts.review.json` yourself. `force: true` re-drafts only what a model drafted; a field the operator wrote is + never replaced. Edit an iteration's files by hand only if the operator asks. 4. For each task routed to `code`, do it yourself as usual: `/sweep` for a report (its plan reads the same policy). 5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks diff --git a/COMMANDS.md b/COMMANDS.md @@ -36,11 +36,12 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster &lt;image&gt;\] \[--caption &lt;line&gt;\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) | | `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/&lt;id&gt;/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) | | `archilyzer reports delete` | `<articleId> [--iteration <n>] [--apply] [--force] [--json]` | delete an article — its directory (report, video, history, notes, iterations), its iterations' video projects under settings.generation.projectsRoot and its staged exports — or, with --iteration, one iteration and its project, through the article registry. A dry run printing the plan (every path with its size, what is kept and why, what refuses) unless --apply. Refused: a published article, or a site page naming it with no report of its own (--force unpublishes it and drops the page first); a queued or running iteration; an iteration that is current (article, its report's source, video) or that another revises or copies (exit 1 when refused; 2 for no such article or iteration) | +| `archilyzer reports bench-verdicts` | `--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json]` | the verdict bench (release 28): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT\_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues. Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /bench) (exit 1 when the run stopped early or was refused; 2 for usage) | | `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) | | `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers | | `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) | -| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, narrate, research) | -| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) | +| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube) | +| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a step on --iteration &lt;n&gt;, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) | | `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* | | `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) | | `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) | @@ -93,6 +94,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | | `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | | `delete-iteration` | delete-iteration deletes one iteration and its video project: {"id", "n"}, "dryRun"?. Its number is never given again. Refused with the plan (409), no override: the current article, the iteration its report.json came from, the current video, a queued or running one, one another revises or copies. | `pnpm ops delete-iteration --json '{"id":"demo-article","n":3}'` | +| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/&lt;id&gt;/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/&lt;id&gt;/) and compose's staging for it (export/.export-index/sites/&lt;id&gt;/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` | | `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'` | | `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` | | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | @@ -143,8 +145,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | -| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate" \| "research", "article", ...} -&gt; {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 narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "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). | `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}'` | -| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":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", ...} -&gt; {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). | `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}'` | +| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | +| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | ### Usage, flags and environment diff --git a/OPERATING.md b/OPERATING.md @@ -164,7 +164,7 @@ umtool chain example-article 3 - In umtool: `/articles/new` starts an article with a sweep or with research (question, channels, dates, model, cap; research takes an autonomy, defaulted from the settings, and needs no channel); the article's **Iterations** tab (`/articles/<id>?tab=iterations`) lists its iterations and runs the rest (**New iteration**, **Copy with - model**, **Narrate**, **Cancel**, **Make the video**, **Use this iteration**); `/articles/<id>/compare?a=&b=` + model**, **Narrate**, **Draft**, **Draft everything**, **Cancel**, **Make the video**, **Use this iteration**); `/articles/<id>/compare?a=&b=` puts two side by side. The pages: [umtool/docs/sites.md](umtool/docs/sites.md). - Each generation is an **iteration** of the article, `i1`, `i2`, … in `transcripts/reports/<id>/iterations/<n>/`, never published ([REPORT.md](REPORT.md), "Iterations"). The article's `report.json` changes only when you choose @@ -182,6 +182,39 @@ umtool chain example-article 3 podcast, attach, dedupe. A re-run resumes at the first step not done. The project is `<projectsRoot>/<id>/i<n>/` (default `~/reports/articles`), off the corpus disk. +**The media drafts** are steps on a done iteration's video cut, each drafting fields of its manifest: + +```sh +pnpm ops report-draft --json '{"task":"onscreen","article":"example-article","iteration":3,"entries":["c01","c02"]}' --wait +pnpm archilyzer gen run youtube --article example-article --iteration 3 --wait +umtool chain example-article 3 --draft-all --model qwen3:8b +``` + +| Task | Field | Limits (code's) | Review | +| --- | --- | --- | --- | +| `cut` | the timeline's order (`drafted.timeline`) | ids from the report's citations only, 3 to `generation.cut.maxClips` (20); windows untouched | the project page's **Review drafts** | +| `onscreen` | each clip's `onscreen.{title, subtitle}` | title ≤ 60, subtitle ≤ 90, one line; a subtitle quotes the clip's own words only | the On-screen table, **Review drafts** | +| `teaser` | a teaser's `lines` (a cut with none gets one) | 3 to 5 lines ≤ 70, no quote read out | the teaser editor, **Review drafts** | +| `flips` | `render.chrome.flips` | pairs over the cut's clips of two dates, THEN the earlier; needs the deck | **Review drafts** | +| `threads` | `render.chrome.threads` and each clip's `thread` | 2 to 4 threads; needs the deck; not with flips | **Review drafts** | +| `narrate` | a card's `narration` | third person; names and numbers from the report; no quote read out | the narration page, **Review drafts** | +| `youtube` | `publish.youtube {title, description}` | title ≤ 100, summary ≤ 900; the build adds chapters and sources to `out/youtube.txt` | the YouTube section, **Review drafts** | + +- Every drafted field carries `drafted {task, model, at, iteration, attempt}`. A field you wrote or edited is never + replaced: the draft is kept in `<task>-draft.json` as an alternative, taken with **Use this**. `force` re-drafts + only a field a model drafted. `entries` limits a per-entry task to those entries. +- In umtool: the project page's **draft** section has **Draft with** a model per task (force, the entries, the job's + progress, the last run's written, skipped and refused); the Iterations tab has the six beside **Narrate**. A + project not made from an iteration (`<projectsRoot>/<id>/i<n>/`) offers none. +- **Draft everything** (the Iterations tab, or `umtool chain <id> <n> --draft-all [--model M]`) is the chain with + its drafts: current → windows → prepare → posts → manifest → cut → on-screen → teaser → flips → threads → + narration → voices → the fast build → podcast → YouTube (its chapters re-muxed so `out/youtube.txt` is written). + No attach, no dedupe. A draft refused or failed is recorded failed and the chain goes on; one with nothing to draft, + or flips and threads with no deck (or the other panel on), is skipped. A resume passes a draft that ran. +- **The review gate:** approve or reject each drafted field (with a note) on `/browse/<project>/review`. A preview or + fast build warns of an unreviewed draft; a `final` build refuses one, and refuses a rejected one whatever the + flags; `--drafts-unreviewed` builds it anyway. A video revision that reorders the cut makes the order its draft. + **The policy** is `settings.generation`: where each task runs (`code` = Claude Code, `api` = the Claude API, `local` = the local model), the models, the caps. @@ -211,8 +244,9 @@ pnpm ops get generation-usage while a transcription or a synthesis runs, and the model is unloaded when its job ends. A local sweep is the code-driven pipeline (the model proposes terms, judges, extracts and groups; code reads, cites and checks). It reads the web through the editor's paced `web-search` / `web-fetch`; a Claude model uses its own web search. -- The stopgap's kept runs (`~/reports/local-reports`) are imported once by - `pnpm archilyzer reports import-local-runs` (a dry run; `--apply` writes). +- The stopgap (`~/reports/local-reports`) is retired: its kept runs were imported (release 27, + `pnpm archilyzer reports import-local-runs`) and the directory deleted (release 28). The repo's + `.claude/commands/gen.md` is the one `/gen` (the stopgap's user-level copy is deleted too). ## Research runs @@ -246,7 +280,14 @@ pnpm ops report-draft --json '{"task":"sweep","article":"example-article","i - **Continue** (umtool's **Continue into a sweep**, shown once the run is done and nothing is pending) is a sweep with `"iteration"` naming the research run: its question, over its channels and every channel an acquisition wrote into. It is refused while the run waits, unless `"force": true`. A channel on no site - is in no build: put it on a site and build before continuing. Nothing continues on its own. + is in no build: put it on a site and build before continuing. +- **An `auto` run continues by itself** once its acquisitions settle (every job ended, nothing waiting for you): the + editor asks that same sweep, on the run's own model, at the job's end or on its heartbeat. The caps hold (the + sweep's per-job cap; past the daily cap it is refused, and tried again the next UTC day). A channel in no build is + left out, with the warning `not in any build yet: <slug> — rebuild the site and continue again` (a failed check on + the sweep); with nothing left to sweep it waits for a newer build. The queue says "continued automatically by iN", + or why not. `propose` and `limits` runs are continued by you. An idle boot (`ARCHILYZER_IDLE_BOOT`) continues + nothing. - **The standing rules hold in every mode**, and a proposal that breaks one is refused: a new channel is created on no site; an X channel never goes on a site; a Twitch VOD URL is refused (look for the stream on archive.org); every fetch goes through the editor's queues, holds and cooldowns (one stream, real gaps, backing off on a 429), never yt-dlp or gallery-dl by diff --git a/REPORT.md b/REPORT.md @@ -146,7 +146,7 @@ An article made or revised by a model keeps each generation as an **iteration**, ## Checking quotes -`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`. +`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. A quote under four words, or one that stops on a function word (`as`, `to`, `the`, …), is a **`fragment`**: a warning too, with the full sentence to quote when the record has one; a GENERATED fragment fails, and the repair round is handed that sentence. `drift` and `en-orig-drift` come before `inexact`, and `inexact` before `fragment`. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `fragment`, `missing-record`, `no-cues`, `missing-post`, `unreadable`. ## Making a report from what exists diff --git a/SETTINGS.md b/SETTINGS.md @@ -954,7 +954,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 and narration 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), `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). | @@ -966,6 +966,8 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. | | `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. | | `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. | +| `cut` | object — see below | The cut task's limits (below). | +| `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. | #### `generation.routes` @@ -976,6 +978,12 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `revise-video` | `"local"` | A video-cut iteration from feedback, through checked ops. | | `narrate` | `"local"` | Card narration for an iteration's cut, under the narration rules and the grounding checks. | | `research` | `"api"` | A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP. | +| `cut` | `"local"` | A media draft (a step on a done iteration, as narration): the cut's clips and their order, chosen from the report's citations. | +| `onscreen` | `"local"` | A media draft: each clip's on-screen title and subtitle. | +| `teaser` | `"local"` | A media draft: the teaser's lines. | +| `flips` | `"local"` | A media draft: THEN/NOW pairs over the cut's clips. | +| `threads` | `"local"` | A media draft: the cut's threads and each clip's thread. | +| `youtube` | `"local"` | A media draft: the YouTube title and description. | #### `generation.models` @@ -991,7 +999,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude |---|---|---| | `sweep` | `5` | A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap. | | `revision` | `2` | A report or video revision job's cap when it names none. | -| `narration` | `1` | A narration job's cap when it names none. | +| `narration` | `1` | A narration (or other media draft) job's cap when it names none. | | `daily` | `20` | The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap. | | `max` | `10` | The most a job may ask for: a larger `maxUsd` is refused. | @@ -1006,13 +1014,34 @@ Report and video generation (release 27): where each task runs (`code` = Claude | Key | Default | Description | |---|---|---| -| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. | +| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. | | `maxItemsPerRun` | `20` | The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits. | | `maxGbPerRun` | `5` | The most GB one run may download without approval. An acquisition of unknown size waits. | | `maxTranscribeHours` | `6` | The most hours of transcription one run may queue without approval. One of unknown length waits. | | `newChannelsNeedApproval` | `true` | Under `limits`, a new channel waits for approval. (A new channel is always created on no site.) | | `postWalksNeedApproval` | `true` | Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval. | +#### `generation.cut` + +| Key | Default | Description | +|---|---|---| +| `maxClips` | `20` | The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says). | + +#### `generation.verdicts` + +| Key | Default | Description | +|---|---|---| +| `bar` | object — see below | The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set. | +| `models` | `[]` | The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals. | + +#### `generation.verdicts.bar` + +| Key | Default | Description | +|---|---|---| +| `agreement` | `0` | The least share of claims on which the model's verdict must equal the operator's (strictly: PARTLY is not CORROBORATED). | +| `contradictedRecall` | `0` | The least share of the claims the operator ruled CONTRADICTED that the model must rule so. | +| `notFoundRecall` | `0` | The least share of the claims the operator ruled NOT_FOUND that the model must rule so. | + Default: ```json @@ -1023,7 +1052,13 @@ Default: "revise-report": "api", "revise-video": "local", "narrate": "local", - "research": "api" + "research": "api", + "cut": "local", + "onscreen": "local", + "teaser": "local", + "flips": "local", + "threads": "local", + "youtube": "local" }, "models": { "api": "claude-sonnet-5-5", @@ -1047,6 +1082,9 @@ Default: "searchUrl": "" }, "citationOrigin": "", + "cut": { + "maxClips": 20 + }, "research": { "autonomy": "propose", "maxItemsPerRun": 20, @@ -1054,6 +1092,14 @@ Default: "maxTranscribeHours": 6, "newChannelsNeedApproval": true, "postWalksNeedApproval": true + }, + "verdicts": { + "bar": { + "agreement": 0, + "contradictedRecall": 0, + "notFoundRecall": 0 + }, + "models": [] } } ``` diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -414,6 +414,13 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["reports", "bench-verdicts"], + usage: + "--models <a,b,…> [--report <id,…>] [--window <s>] [--max-usd <n>] [--limit <n>] [--run <id>] [--dry] [--here] [--wait] [--json] the verdict bench (release 28): every claim of the registry's fact-checks (or of --report) with the operator's verdict and a citation with cues, asked of each model one claim per call — the claim, its quotes and the transcript within --window seconds (default 60) of each cited span, never the findings or the verdict — and scored against the rulings (agreement, the confusion matrix, CONTRADICTED and NOT_FOUND recall, against an always-CORROBORATED baseline). --dry lists the items and the skipped claims and estimates the cost, asking nothing. Otherwise through the editor (`pnpm ops bench-verdicts`; a local model through the GPU arbiter; --wait follows the job), or --here in this process for API models only. The run stops at --max-usd (default 5, the whole run); a --run that exists continues. Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench) (exit 1 when the run stopped early or was refused; 2 for usage)", + flags: { report: "string", models: "string", window: "string", "max-usd": "string", limit: "string", run: "string", dry: "boolean", here: "boolean", wait: "boolean", json: "boolean" }, + run: async (ctx) => (await import("./reports-bench-verdicts")).benchRow(ctx), + }, + { path: ["reports", "import-local-runs"], usage: "[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>] ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused)", @@ -437,14 +444,14 @@ export const COMMANDS: Command[] = [ }, { path: ["gen", "set"], - usage: "<task> <code|api|local> route one generation task (sweep, revise-report, revise-video, narrate, research)", + usage: "<task> <code|api|local> route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube)", maxPositionals: 2, run: async (ctx) => (await import("./gen")).genSetRow(ctx), }, { path: ["gen", "run"], usage: - "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)", + "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)", flags: { via: "string", article: "string", @@ -458,6 +465,7 @@ export const COMMANDS: Command[] = [ model: "string", "max-usd": "string", cards: "string", + entries: "string", force: "boolean", autonomy: "string", source: "string", diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { GENERATION_PRESETS } from "../lib/generationSettings"; // `archilyzer gen` (release 27 S9). settings.json and the ledger are pinned to // a temp dir BEFORE anything reads getPaths() (it caches), so the offline @@ -73,11 +74,12 @@ test("gen preset writes the preset's routes; gen set writes one; nonsense is a u const m = memoryStore(); const deps = { store: async () => m.store, runOps: async () => 0, out: c.out }; assert.equal(await gen.setMain({ preset: "local" }, deps), 0); - assert.deepEqual(m.written[0], { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }); + // Every task, the media drafts (release 28) included. + assert.deepEqual(m.written[0], { ...GENERATION_PRESETS.local }); assert.equal(await gen.setMain({ task: "sweep", route: "api" }, deps), 0); - assert.deepEqual(m.written[1], { sweep: "api", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }); + assert.deepEqual(m.written[1], { ...GENERATION_PRESETS.local, sweep: "api" }); assert.ok(c.lines.includes("(written to the editor at http://editor.test)")); - for (const o of [{ preset: "cheap" }, { task: "sweep", route: "cloud" }, { task: "sweep" }, { task: "teaser", route: "api" }]) { + for (const o of [{ preset: "cheap" }, { task: "sweep", route: "cloud" }, { task: "sweep" }, { task: "nope", route: "api" }]) { assert.equal(await gen.setMain(o, deps), 2, JSON.stringify(o)); } assert.equal(m.written.length, 2); @@ -210,3 +212,21 @@ test("gen run research takes --autonomy; nothing else does", async () => { // A continuation: a sweep naming the research run. assert.deepEqual(gen.runBody("sweep", undefined, { article: "synth-a", iteration: "4", force: true }), { task: "sweep", article: "synth-a", iteration: 4, force: true }); }); + +test("gen run a media draft: a step on --iteration, no words, --entries and --force (release 28)", () => { + assert.deepEqual(gen.runBody("onscreen", undefined, { article: "synth-a", iteration: "2", entries: "c01, c02", force: true }), { + task: "onscreen", + article: "synth-a", + iteration: 2, + entries: ["c01", "c02"], + force: true, + }); + assert.deepEqual(gen.runBody("youtube", undefined, { article: "synth-a", iteration: "2", model: "qwen3:8b" }), { task: "youtube", article: "synth-a", iteration: 2, model: "qwen3:8b" }); + assert.deepEqual(gen.runBody("cut", undefined, { article: "synth-a" }), { error: "gen run: a cut draft names its iteration (--iteration <n>)" }); + assert.deepEqual(gen.runBody("teaser", "make it punchier", { article: "synth-a", iteration: "2" }), { + error: "gen run: a teaser draft takes no question or feedback: it drafts from the iteration's report and cut", + }); + assert.deepEqual(gen.runBody("flips", undefined, { article: "synth-a", iteration: "2", "copy-of": "1" }), { error: "gen run: a flips draft is a step on its iteration: no --copy-of" }); + assert.deepEqual(gen.runBody("sweep", "q", { article: "synth-a", entries: "c01" }), { error: "gen run: --entries is a media draft's" }); +}); + diff --git a/common/bin/gen.ts b/common/bin/gen.ts @@ -5,7 +5,9 @@ // archilyzer gen preset code|balanced|api|local route every task at once // archilyzer gen set <task> code|api|local route one task // archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait] -// enqueue a report-draft job (`pnpm ops report-draft`) +// enqueue a report-draft job (`pnpm ops report-draft`); +// a media draft (cut, onscreen, teaser, flips, threads, +// narrate, youtube) takes --iteration, --entries, --force // // THROUGH THE EDITOR when it answers: `GET/POST /api/ops/settings` (its one // settings writer) and `GET /api/ops/generation-usage`, with the token @@ -33,6 +35,8 @@ import { GENERATION_PRESETS, GENERATION_PRESET_NAMES, GENERATION_ROUTES, + MEDIA_STEP_TASKS, + isStepTask, type GenerationPreset, type GenerationRoute, } from "../lib/generationSettings"; @@ -66,7 +70,7 @@ export type GenDeps = { out?: Out; }; -const TASKS_HELP = "sweep, revise-report, revise-video, narrate, research"; +const TASKS_HELP = `sweep, revise-report, revise-video, research, or a media draft: ${MEDIA_STEP_TASKS.join(", ")}`; const isRoute = (v: unknown): v is GenerationRoute => typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v); export function policyFrom(value: unknown): GenPolicy | null { @@ -263,12 +267,19 @@ export function runBody(task: string, text: string | undefined, flags: Record<st if (e) return { error: e }; } const words = text?.trim(); + // A media draft (release 28) is a step on the iteration it names; it takes + // no words — it drafts from the iteration's report and cut. + if (isStepTask(task)) { + if (body.iteration === undefined) return { error: `gen run: a ${task} draft names its iteration (--iteration <n>)` }; + if (body.copyOf !== undefined) return { error: `gen run: a ${task} draft is a step on its iteration: no --copy-of` }; + if (words || str("question") || str("feedback")) return { error: `gen run: a ${task} draft takes no question or feedback: it drafts from the iteration's report and cut` }; + } else if (str("entries")) return { error: "gen run: --entries is a media draft's" }; if (words) body[task === "sweep" || task === "research" ? "question" : "feedback"] = words; for (const k of ["question", "feedback", "from", "to", "model", "source", "build"] as const) { const v = str(k); if (v) body[k] = v; } - for (const k of ["channels", "cards"] as const) { + for (const k of ["channels", "cards", "entries"] as const) { const v = str(k); if (v) body[k] = v.split(",").map((x) => x.trim()).filter(Boolean); } diff --git a/common/bin/reports-bench-verdicts.test.ts b/common/bin/reports-bench-verdicts.test.ts @@ -0,0 +1,91 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { CHANNELS } from "../testing/draft/corpus.mjs"; +import type { Paths } from "../lib/paths"; +import { benchMain, benchOptionsOf } from "./reports-bench-verdicts"; + +const RULED = path.join(import.meta.dirname, "../testing/draft/reports/ruled.report.json"); + +// A temp corpus: the ruled fact-check in the article store, and the synthetic +// recordings' cues on disk, as `diskCuesOf` reads them. +async function corpus() { + const dir = await mkdtemp(path.join(os.tmpdir(), "bench-cli-")); + const report = JSON.parse(await readFile(RULED, "utf8")); + await mkdir(path.join(dir, "reports", report.id), { recursive: true }); + await writeFile(path.join(dir, "reports", report.id, "report.json"), JSON.stringify(report)); + for (const ch of CHANNELS) { + for (const r of ch.records) { + const rec = path.join(dir, "channels", ch.slug, "data", r.id); + await mkdir(rec, { recursive: true }); + await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues })); + } + } + const paths = { + articlesDir: path.join(dir, "reports"), + exportIndexDir: path.join(dir, ".export-index"), + channelsDir: path.join(dir, "channels"), + generationUsageFile: path.join(dir, ".generation", "usage.jsonl"), + } as Paths; + return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) }; +} + +function capture() { + const logs: string[] = []; + const errors: string[] = []; + return { out: { log: (s: string) => logs.push(s), error: (s: string) => errors.push(s) }, logs, errors }; +} + +test("the flags: lists split, numbers read, the options judged before anything runs", () => { + assert.deepEqual(benchOptionsOf({ models: "claude-sonnet-5-5, qwen3:8b", report: "a,b", window: "30", "max-usd": "2.5", limit: "4", run: "vb-x" }), { + models: ["claude-sonnet-5-5", "qwen3:8b"], + reports: ["a", "b"], + windowS: 30, + maxUsd: 2.5, + limit: 4, + runId: "vb-x", + }); + assert.throws(() => benchOptionsOf({}), /at least one model/); + assert.throws(() => benchOptionsOf({ models: "m", window: "soon" }), /--window takes a number/); + assert.throws(() => benchOptionsOf({ models: "m", run: "Not An Id" }), /--run is a run id/); +}); + +test("--dry: the items over the local corpus's cues, the skipped claims and the estimate; nothing asked, nothing written", async () => { + const c = await corpus(); + try { + const cap = capture(); + let asked = 0; + const code = await benchMain({ models: "claude-sonnet-5-5,claude-opus-5-5,qwen3:8b", dry: true }, { paths: c.paths, runOps: async () => ++asked, out: cap.out }); + assert.equal(code, 0); + assert.equal(asked, 0); + assert.match(cap.logs[0]!, /^7 items from 1 fact-check\(s\), a 60 s window; 1 claims skipped$/); + assert.ok(cap.logs.includes(" skipped 1: no citation")); + assert.ok(cap.logs.some((l) => /^ {2}synth-ruled\/r04 {2}CONTRADICTED {2}1 quote\(s\), \d+ cues$/.test(l))); + assert.ok(cap.logs.some((l) => /^ {2}qwen3:8b \(local\): 7 calls, .*~\$0\.0000$/.test(l))); + // No claim text without --json. + assert.ok(!cap.logs.join("\n").includes("The article says")); + await assert.rejects(stat(path.join(c.dir, ".generation")), /ENOENT/); + } finally { + await c.done(); + } +}); + +test("a run goes through the editor (pnpm ops bench-verdicts); --here refuses a local model", async () => { + const c = await corpus(); + try { + const seen: string[][] = []; + const code = await benchMain( + { models: "claude-sonnet-5-5,qwen3:8b", "max-usd": "5", run: "vb-real", wait: true }, + { paths: c.paths, runOps: async (argv) => (seen.push(argv), 0), out: capture().out }, + ); + assert.equal(code, 0); + assert.deepEqual(seen, [["bench-verdicts", "--json", JSON.stringify({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-real", maxUsd: 5 }), "--wait"]]); + const cap = capture(); + assert.equal(await benchMain({ models: "qwen3:8b", here: true }, { paths: c.paths, runOps: async () => 0, out: cap.out }), 2); + assert.match(cap.errors.join("\n"), /qwen3:8b runs on the GPU, which only the editor arbitrates/); + } finally { + await c.done(); + } +}); diff --git a/common/bin/reports-bench-verdicts.ts b/common/bin/reports-bench-verdicts.ts @@ -0,0 +1,153 @@ +// `archilyzer reports bench-verdicts --models a,b,c [--report <id>,…] [--window 60] +// [--max-usd 5] [--limit n] [--run <id>] [--dry] [--here] [--wait] [--json]` +// (release 28, M7) — the verdict bench: every ruled claim of the registry's +// fact-checks asked of each model, one claim per call, and scored against the +// operator's rulings (lib/report/draft/bench/). +// +// --dry lists the items (key, the operator's verdict, quotes, cues — no +// claim text unless --json) and the skipped claims with their +// reasons, and estimates each model's cost. Reads only; asks +// nothing; writes nothing. +// (none) THROUGH THE EDITOR: `pnpm ops bench-verdicts` (a child), so a +// local model gets the GPU arbiter's turn and is unloaded after — +// the only correct path for one. `--wait` follows the job. +// --here in this process, for API models only (a local model is refused: +// the GPU is arbitrated in the editor alone). The day's cap and the +// usage ledger hold as in the editor's job. +// +// The results are local-only, in `.generation/bench/verdicts/<run>/` +// (items.jsonl, results.jsonl, summary.json); umtool's /bench shows them. +// A `--run` that exists continues it. +// +// Exit 0 when the run is done (a dry run: when it has items); 1 when it +// stopped early (the cap, a cancel, a failure) or the editor refused; 2 for +// usage. + +import type { CommandContext } from "./_cli"; +import type { FlagValue } from "./_parseFlags"; +import { getPaths, type Paths } from "../lib/paths"; +import { getSettings } from "../lib/settings"; +import { diskCuesOf } from "../lib/report/convert-server"; +import { + BenchInputError, + isBenchRunId, + newBenchRunId, + validateBenchOptions, + planVerdictBench, + type BenchOptions, + type BenchPlan, +} from "../lib/report/draft/bench/index"; +import { benchDailyCapRefusal, runBenchWithSettings } from "../controller/benchVerdicts"; +import { runOpsChild } from "./gen"; + +type Out = { log: (s: string) => void; error: (s: string) => void }; + +const list = (v: FlagValue | undefined) => (typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : []); + +function num(v: FlagValue | undefined, name: string): number | undefined { + if (v === undefined) return undefined; + const n = typeof v === "string" ? Number(v) : NaN; + if (!Number.isFinite(n)) throw new BenchInputError(`--${name} takes a number`); + return n; +} + +export function benchOptionsOf(flags: Record<string, FlagValue>): BenchOptions { + const o: BenchOptions = { models: list(flags.models) }; + const reports = list(flags.report); + if (reports.length) o.reports = reports; + const w = num(flags.window, "window"); + if (w !== undefined) o.windowS = w; + const m = num(flags["max-usd"], "max-usd"); + if (m !== undefined) o.maxUsd = m; + const l = num(flags.limit, "limit"); + if (l !== undefined) o.limit = l; + if (typeof flags.run === "string") o.runId = flags.run; + validateBenchOptions(o); + if (o.runId !== undefined && !isBenchRunId(o.runId)) throw new BenchInputError("--run is a run id: lowercase letters, digits and dashes"); + return o; +} + +export function formatBenchPlan(plan: BenchPlan): string[] { + const lines: string[] = []; + lines.push(`${plan.items.length} items from ${plan.reports.length} fact-check(s), a ${plan.windowS} s window; ${plan.skipped.length} claims skipped`); + const reasons = new Map<string, number>(); + for (const s of plan.skipped) reasons.set(s.reason, (reasons.get(s.reason) ?? 0) + 1); + for (const [r, n] of reasons) lines.push(` skipped ${n}: ${r}`); + const ruled = new Map<string, number>(); + for (const it of plan.items) ruled.set(it.verdict, (ruled.get(it.verdict) ?? 0) + 1); + lines.push(` ruled: ${[...ruled].map(([v, n]) => `${v} ${n}`).join(", ") || "none"}`); + lines.push("items:"); + for (const it of plan.items) { + const cues = it.windows.reduce((s, w) => s + w.cues.length, 0); + lines.push(` ${it.key} ${it.verdict} ${it.quotes.length} quote(s), ${cues} cues`); + } + for (const s of plan.skipped) lines.push(` skipped ${s.key}: ${s.reason}`); + lines.push("estimate:"); + for (const e of plan.estimate) { + lines.push(` ${e.model} (${e.provider}): ${e.calls} calls, ~${e.inputTokens} in / ~${e.outputTokens} out tokens, ~$${e.usd.toFixed(4)}`); + } + lines.push(` total ~$${plan.estimateUsd.toFixed(4)} (the run stops at its --max-usd, default $5)`); + return lines; +} + +export type BenchDeps = { + paths: Paths; + runOps: (argv: string[]) => Promise<number>; + out?: Out; +}; + +export async function benchMain(flags: Record<string, FlagValue>, deps: BenchDeps): Promise<number> { + const out = deps.out ?? console; + let opts: BenchOptions; + try { + opts = benchOptionsOf(flags); + if (flags.dry === true) { + const plan = await planVerdictBench(opts, { paths: deps.paths, cuesOf: diskCuesOf(deps.paths.channelsDir) }); + if (flags.json === true) out.log(JSON.stringify(plan, null, 2)); + else for (const l of formatBenchPlan(plan)) out.log(l); + return plan.items.length ? 0 : 1; + } + } catch (e) { + if (e instanceof BenchInputError) { + out.error(`reports bench-verdicts: ${e.message}`); + return 2; + } + throw e; + } + if (flags.here === true) { + const gen = getSettings().generation; + const refusal = await benchDailyCapRefusal(opts, deps.paths, gen); + if (refusal) { + out.error(`reports bench-verdicts: ${refusal}`); + return 1; + } + const runId = opts.runId ?? newBenchRunId(); + const ac = new AbortController(); + const stop = () => ac.abort(); + process.once("SIGINT", stop); + try { + const r = await runBenchWithSettings({ ...opts, runId }, { paths: deps.paths, gen, onLog: (l) => out.error(l), signal: ac.signal, jobId: `cli-${runId}`, gpu: false }); + out.log(JSON.stringify({ run: r.id, dir: r.dir, status: r.summary.status, items: r.summary.items, spentUsd: r.summary.spentUsd, ...(r.summary.stopped ? { stopped: r.summary.stopped } : {}) })); + return r.summary.status === "done" ? 0 : 1; + } catch (e) { + if (e instanceof BenchInputError) { + out.error(`reports bench-verdicts: ${e.message}`); + return 2; + } + throw e; + } finally { + process.off("SIGINT", stop); + } + } + const body: Record<string, unknown> = { models: opts.models }; + if (opts.runId) body.run = opts.runId; + if (opts.reports) body.reports = opts.reports; + if (opts.windowS !== undefined) body.window = opts.windowS; + if (opts.maxUsd !== undefined) body.maxUsd = opts.maxUsd; + if (opts.limit !== undefined) body.limit = opts.limit; + return deps.runOps(["bench-verdicts", "--json", JSON.stringify(body), ...(flags.wait === true ? ["--wait"] : [])]); +} + +export async function benchRow(ctx: CommandContext): Promise<number> { + return benchMain(ctx.flags, { paths: getPaths(), runOps: runOpsChild }); +} diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts @@ -249,6 +249,38 @@ test("verify-quotes: `inexact` — recall passes, the strict check does not — assert.match(w.text(), /2 quote\(s\): 1 inexact, 1 ok \(inexact is a warning\)/); }); +test("verify-quotes: `fragment` — verbatim, but stopping mid-thought — is a warning with the full sentence (testing/draft/sweeps/fragment.md)", async () => { + // The kitchen channel's records are on disk from the test above. + const { report } = await convertFixture("fragment"); + const file = path.join(ROOT, "fragment.report.json"); + writeJson(file, report); + const c = capture(); + const code = await verifyQuotesMain({ file, json: true, paths }, c.out); + const { results } = JSON.parse(c.text()) as { results: { citation: string; status: string; sentence?: string; message?: string }[] }; + const by = Object.fromEntries(results.map((r) => [r.citation, r])); + assert.equal(by.c01.status, "fragment"); + assert.equal(by.c01.sentence, "I paid for the new mixer myself"); + assert.match(by.c01.message!, /ends on “the”/); + assert.equal(by.c02.status, "fragment"); + assert.equal(by.c02.sentence, "my lawyer told me not to talk about the lease"); + assert.equal(by.c03.status, "fragment"); + assert.match(by.c03.message!, /under 4 words/); + assert.equal(by.c03.sentence, "I did not enter the contest this year"); + assert.equal(by.c04.status, "ok"); + assert.equal(code, 0, "a fragment is a warning"); + const w = capture(); + assert.equal(await verifyQuotesMain({ file, paths }, w.out), 0); + assert.match(w.text(), /FRAGMENT \(warning\) c01/); + assert.match(w.text(), /4 quote\(s\): 3 fragment, 1 ok \(fragment is a warning\)/); + // Precedence: a quote that is not verbatim is `inexact`, never `fragment`. + const reversed = { ...report, citations: { ...report.citations, c01: { ...report.citations!.c01!, quote: "I paid for a" } } }; + writeJson(file, reversed); + const r = capture(); + await verifyQuotesMain({ file, json: true, paths }, r.out); + const rc01 = (JSON.parse(r.text()) as { results: { citation: string; status: string }[] }).results.find((x) => x.citation === "c01")!; + assert.notEqual(rc01.status, "fragment"); +}); + // ─── attach-video ─── test("encodePlan: remux an H.264 mp4 under the limit; encode the rest to fit; refuse what cannot", () => { diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -25,6 +25,11 @@ // and counted, and does not change the exit code; compose and publish do not // use it. // +// A quote that is a FRAGMENT — under four words, or stopping on a function +// word (lib/citations/fragment.ts, release 28 Q2) — is `fragment`: a WARNING +// too, with the full sentence to quote when the record has one. Precedence: +// `drift` / `en-orig-drift` > `inexact` > `fragment` > `ok`. +// // `--article <id>` checks one ARTICLE (release 26: transcripts/reports/<id>/, // published or a draft) as the homepage's compose would — any channel of the // corpus citable, the articles' prepared media. @@ -51,6 +56,7 @@ import { strictTextCheck, type StrictQuoteResult, } from "../lib/citations/verify"; +import { fragmentOf, fullSentenceFor, type FragmentFinding } from "../lib/citations/fragment"; import { ComposeReportsError, checkSpanQuote, @@ -142,6 +148,9 @@ export type QuoteStatus = | "en-orig-drift" // Recall passes, the strict check does not: a warning (release 27 D3). | "inexact" + // Verbatim, but under four words or stopping on a function word: a + // warning (release 28 Q2). + | "fragment" | "missing-record" | "no-cues" | "missing-post" @@ -165,11 +174,13 @@ export type QuoteResult = { // The strict check (verbatim within ±90 s): whether it passed, and the // first fragment it did not find. Absent where recall already failed. strict?: { ok: boolean; failed?: string }; + // A fragment's full sentence, from the record, when one fits. + sentence?: string; message?: string; }; // Statuses that are warnings: printed and counted, never a failure. -export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact"]); +export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact", "fragment"]); const strictOf = (r: StrictQuoteResult): NonNullable<QuoteResult["strict"]> => r.ok ? { ok: true } : { ok: false, ...(r.failed !== undefined ? { failed: r.failed } : {}) }; @@ -181,6 +192,14 @@ export function inexactMessage(failed: string | undefined): string { ); } +export function fragmentMessage(f: FragmentFinding, sentence: string | null): string { + return ( + `"${f.part.slice(0, 120)}" is a fragment (${f.why}): quote the whole sentence` + + (sentence ? ` — "${sentence}"` : " or clause") + + " — a warning; compose is unchanged" + ); +} + export const EN_ORIG_TRACK = "transcript.en-orig.vtt"; // Every video, audio and post citation of a report, checked against the @@ -233,18 +252,23 @@ export async function verifyReportQuotes( } const v = quoteVerification(c.quote, postText, now); const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText); - const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : "ok"; + const frag = fragmentOf(c.quote); + const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : frag ? "fragment" : "ok"; + const sentence = status === "fragment" ? fullSentenceFor(frag!.part, [{ start: 0, end: 1, text: postText }], 0) : null; results.push({ ...base, score: v.quoteScore, track: "post", status, ...(strict ? { strict: strictOf(strict) } : {}), + ...(sentence ? { sentence } : {}), ...(status === "drift" ? { message: quoteDriftMessage(v.quoteScore) } : status === "inexact" ? { message: inexactMessage(strict?.failed) } - : {}), + : status === "fragment" + ? { message: fragmentMessage(frag!, sentence) } + : {}), }); continue; } @@ -269,14 +293,19 @@ export async function verifyReportQuotes( // The strict check passes when any track has the quote verbatim near // the cited second (as recall takes the best track). let strict: StrictQuoteResult | null = null; + let strictCues = record.cues; if (!quoteDrifted(checked.verification)) { const tracks = record.tracks.length ? record.tracks.map((t) => t.cues) : [record.cues]; for (const cues of tracks) { const r = strictQuoteCheck(c.quote, cues, c.start); if (!strict || r.ok) strict = r; - if (r.ok) break; + if (r.ok) { + strictCues = cues; + break; + } } } + let sentence: string | null = null; if (quoteDrifted(checked.verification)) { status = "drift"; message = quoteDriftMessage(score); @@ -288,6 +317,13 @@ export async function verifyReportQuotes( } else if (strict && !strict.ok) { status = "inexact"; message = inexactMessage(strict.failed); + } else { + const frag = fragmentOf(c.quote); + if (frag) { + status = "fragment"; + sentence = fullSentenceFor(frag.part, strictCues, c.start); + message = fragmentMessage(frag, sentence); + } } results.push({ ...base, @@ -296,6 +332,7 @@ export async function verifyReportQuotes( tracks: checked.tracks, ...(enOrig !== undefined ? { enOrig } : {}), ...(strict ? { strict: strictOf(strict) } : {}), + ...(sentence ? { sentence } : {}), status, ...(message ? { message } : {}), }); @@ -343,8 +380,14 @@ export async function verifyQuotesMain( `reports verify-quotes: ${results.length} quote(s): ` + [...counts].map(([s, n]) => `${n} ${s}`).join(", ") + (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : "") + - (results.some((r) => QUOTE_WARNING_STATUSES.has(r.status)) ? " (inexact is a warning)" : ""), + warningsNote(results), ); } return bad.length > 0 || parsed.problems.length > 0 ? 1 : 0; } + +// " (inexact is a warning)", " (inexact and fragment are warnings)", or "". +function warningsNote(results: readonly QuoteResult[]): string { + const seen = [...QUOTE_WARNING_STATUSES].filter((w) => results.some((r) => r.status === w)); + return seen.length ? ` (${seen.join(" and ")} ${seen.length > 1 ? "are warnings" : "is a warning"})` : ""; +} diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts @@ -0,0 +1,215 @@ +// `bench-verdicts` — the verdict bench (release 28, M7) as an editor job: +// `archilyzer reports bench-verdicts` → `pnpm ops bench-verdicts` → +// POST /api/ops/bench-verdicts → here. +// +// run the run's id: a new one, or one to continue (default vb-<stamp>) +// reports the fact-check articles to read (default: every one) +// models the models to ask (required) +// window seconds of transcript either side of each cited span (default 60) +// maxUsd the whole run's API cap (default 5, at most 50) +// limit the first n items only +// +// WHY A JOB IN THE EDITOR, NOT A `report-draft`: a bench writes no iteration +// and is no task of an article, so `report-draft`'s machinery (an iteration +// created queued, the task registry) would be bent to fit it. What it needs +// of release 27 is the GPU path, which is the editor's alone (the arbiter's +// holds are in-process): a run with any LOCAL model goes on `draft:local`, +// every ollama call through `gpuGatedFetch` (it waits for transcription and +// for a synthesis, and holds the card while it runs), and ollama is unloaded +// when the job ends, however it ends — exactly as a `report-draft` on +// `draft:local`. A run of API models only goes on `draft:api`. +// +// An API run is refused past the day's cap (settings.generation.caps.daily), +// and its spend is appended to the usage ledger (task `bench-verdicts`, no +// article) so the day's total counts it. The cues are the local corpus's +// (`diskCuesOf`): a fact-check may cite channels no build carries. The log +// ends `@@bench-verdicts {json}` with the run's id, status and spend. + +import { getSettings } from "../lib/settings"; +import type { Paths } from "../lib/paths"; +import type { GenerationSettings } from "../lib/generationSettings"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; +import { providerOf, unloadOllama } from "../lib/llm"; +import { diskCuesOf } from "../lib/report/convert-server"; +import { + BenchInputError, + DEFAULT_BENCH_MAX_USD, + isBenchRunId, + newBenchRunId, + runVerdictBench, + validateBenchOptions, + type BenchOptions, +} from "../lib/report/draft/bench/index"; +import { isReportId } from "../lib/report/schema"; +import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; +import { llmConfigOf } from "./reportDraft"; + +export const BENCH_VERDICTS_JOB_KIND = "bench-verdicts"; +export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; +export const BENCH_VERDICTS_BODY_KEYS = ["run", "reports", "models", "window", "maxUsd", "limit"] as const; + +const fail = (msg: string): never => { + throw new BenchInputError(msg); +}; + +// The body, judged without touching the disk. +export function parseBenchVerdictsBody(b: Record<string, unknown>): BenchOptions { + const out: BenchOptions = { models: [] }; + if (b.run !== undefined) { + if (!isBenchRunId(b.run)) fail(`"run" is a run id: lowercase letters, digits and dashes`); + out.runId = b.run as string; + } + if (b.reports !== undefined) { + if (!Array.isArray(b.reports) || !b.reports.every((r) => isReportId(r))) fail(`"reports" is a list of article ids`); + out.reports = b.reports as string[]; + } + const models = typeof b.models === "string" ? b.models.split(",") : b.models; + if (!Array.isArray(models) || !models.every((m) => typeof m === "string")) fail(`"models" is a list of model names`); + out.models = (models as string[]).map((m) => m.trim()).filter(Boolean); + if (b.window !== undefined) { + if (typeof b.window !== "number") fail(`"window" is a number of seconds`); + out.windowS = b.window as number; + } + if (b.maxUsd !== undefined) { + if (typeof b.maxUsd !== "number") fail(`"maxUsd" is a number of dollars`); + out.maxUsd = b.maxUsd as number; + } + if (b.limit !== undefined) { + if (typeof b.limit !== "number") fail(`"limit" is a number of items`); + out.limit = b.limit as number; + } + validateBenchOptions(out); + return out; +} + +export type BenchVerdictsDeps = { + paths: Paths; + settings?: () => { generation: GenerationSettings }; + now?: () => Date; + // Where runs live (tests); default `.generation/bench/verdicts/`. + root?: string; +}; + +export type BenchVerdictsEnqueued = { result: StreamActionResult; run: string }; + +// One run with the settings' providers: the job's body, and `archilyzer +// reports bench-verdicts --here` (API models only: no GPU arbiter outside the +// editor, so a local model there is refused). The ledger gets this run's API +// spend; a local model is unloaded at the end. Answers the outcome. +export async function runBenchWithSettings( + opts: BenchOptions & { runId: string }, + o: { + paths: Paths; + gen: GenerationSettings; + onLog: (line: string) => void; + signal?: AbortSignal; + jobId: string; + // In the editor: every ollama call through the GPU arbiter. + gpu: boolean; + now?: () => Date; + root?: string; + }, +): Promise<Awaited<ReturnType<typeof runVerdictBench>>> { + const { paths, gen: g, onLog } = o; + const locals = opts.models.filter((m) => providerOf(m) === "local"); + if (locals.length && !o.gpu) { + throw new BenchInputError(`${locals.join(", ")} run${locals.length === 1 ? "s" : ""} on the GPU, which only the editor arbitrates: run the bench through the editor (pnpm ops bench-verdicts)`); + } + let spent: Awaited<ReturnType<typeof runVerdictBench>>["spent"] | null = null; + try { + const out = await runVerdictBench(opts, { + paths, + ...(o.root ? { root: o.root } : {}), + cuesOf: diskCuesOf(paths.channelsDir), + llm: llmConfigOf(g, paths, locals.length ? { onLog, ...(o.signal ? { signal: o.signal } : {}) } : undefined), + log: onLog, + ...(o.signal ? { signal: o.signal } : {}), + ...(o.now ? { now: o.now } : {}), + }); + spent = out.spent; + const s = out.summary; + onLog( + `${BENCH_VERDICTS_RESULT_MARKER}${JSON.stringify({ + run: s.id, + status: s.status, + items: s.items, + skipped: s.skipped.length, + spentUsd: s.spentUsd, + ...(s.stopped ? { stopped: s.stopped } : {}), + })}`, + ); + return out; + } finally { + for (const m of locals) { + await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, m).then( + () => onLog(`unloaded ${m} from ollama`), + (e) => onLog(`ollama unload failed: ${(e as Error).message}`), + ); + } + if (spent) { + const now = o.now?.() ?? new Date(); + const rows: GenerationUsageRow[] = Object.entries(spent.byModel) + .filter(([m, t]) => providerOf(m) === "api" && (t.usd > 0 || t.calls > 0)) + .map(([m, t]) => ({ + at: now.toISOString(), + day: utcDay(now), + jobId: o.jobId, + article: "", + iteration: 0, + task: BENCH_VERDICTS_JOB_KIND, + model: m, + inputTokens: t.input, + outputTokens: t.output, + cacheReadTokens: t.cacheRead, + cacheWriteTokens: t.cacheWrite, + usd: Math.round(t.usd * 10_000) / 10_000, + })); + await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); + } + } +} + +// The day's cap, for a run with an API model: the refusal, or null. +export async function benchDailyCapRefusal(opts: BenchOptions, paths: Pick<Paths, "generationUsageFile">, gen: GenerationSettings, now?: Date): Promise<string | null> { + if (!opts.models.some((m) => providerOf(m) === "api")) return null; + return dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(now)), gen.caps.daily); +} + +export async function enqueueVerdictBench( + raw: Record<string, unknown>, + deps: BenchVerdictsDeps, +): Promise<BenchVerdictsEnqueued | { result: StreamActionResult & { ok: false } }> { + const refuse = (error: string) => ({ result: { ok: false as const, error } }); + let opts: BenchOptions; + try { + opts = parseBenchVerdictsBody(raw); + } catch (e) { + return refuse((e as Error).message); + } + const paths = deps.paths; + const gen = (deps.settings ?? getSettings)().generation; + const anyLocal = opts.models.some((m) => providerOf(m) === "local"); + const refusal = await benchDailyCapRefusal(opts, paths, gen, deps.now?.()); + if (refusal) return refuse(refusal); + const run = opts.runId ?? newBenchRunId(deps.now?.() ?? new Date()); + const result = await runManagedFunction({ + kind: BENCH_VERDICTS_JOB_KIND, + queueKey: anyLocal ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, + paths, + fn: async (onLog, signal, _progress, ctx) => { + const g = (deps.settings ?? getSettings)().generation; + // Again at the job's turn: jobs ahead in the queue may have spent the day. + const late = await benchDailyCapRefusal(opts, paths, g, deps.now?.()); + if (late) throw new Error(late); + onLog(`verdict bench ${run}: ${opts.models.join(", ")} (API cap $${opts.maxUsd ?? DEFAULT_BENCH_MAX_USD})`); + const out = await runBenchWithSettings( + { ...opts, runId: run }, + { paths, gen: g, onLog, signal, jobId: ctx.jobId, gpu: true, ...(deps.now ? { now: deps.now } : {}), ...(deps.root ? { root: deps.root } : {}) }, + ); + if (out.summary.status === "cancelled" || signal.aborted) throw new Error("cancelled"); + }, + }); + if (!result.ok) return { result }; + return { result, run }; +} diff --git a/common/controller/relocateChannelMedia.test.ts b/common/controller/relocateChannelMedia.test.ts @@ -749,6 +749,15 @@ async function leftoverCopies(channelDir: string): Promise<string[]> { // rsync -a of the tree, so the seeded "already copied" target is byte-for-byte // what a completed copy phase would have left — including mtimes, which the // re-verify compares. Over `media/` only: it holds no links. +// Every directory under (and including) `dir` set to MTIME, so a test's +// itemized drift is the files' alone, whatever second the setup ran in. +async function pinDirTimes(dir: string): Promise<void> { + for (const entry of await readdir(dir, { withFileTypes: true })) { + if (entry.isDirectory()) await pinDirTimes(path.join(dir, entry.name)); + } + await utimes(dir, MTIME, MTIME); +} + async function copyTree(src: string, dest: string): Promise<void> { await mkdir(dest, { recursive: true }); for (const entry of await readdir(src, { withFileTypes: true })) { @@ -1612,6 +1621,12 @@ test("reconcile: an extra and a changed file on the destination are settled, and await copyTree(mediaLink, target); await writeFile(path.join(target, "v1", "stale.json"), "{}"); await writeFile(path.join(target, "v1", "transcript.live_chat.json"), '{"v":1}'); + // Every directory's mtime pinned on both sides: writing stale.json moved + // the target's v1/ mtime, and when the setup crossed a second boundary + // rsync (comparing whole seconds) itemized `.d..t v1/` as a third + // difference — the release 28 flake. Only the two files differ now. + await pinDirTimes(mediaLink); + await pinDirTimes(target); await seedMarker(paths, "alpha", { target, direction: "out", phase: "copy" }); const lines: string[] = []; diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -2,12 +2,17 @@ // (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft → // here. // -// task sweep | revise-report | revise-video | narrate | research +// task sweep | revise-report | revise-video | research, or a media +// draft: narrate | cut | onscreen | teaser | flips | threads | +// youtube (a STEP on a done iteration, MEDIA_STEP_TASKS) // article the article id (an article in the making is fine for a sweep) // iteration a revision's parent; the iteration a narration voices; for a // sweep, the research run it CONTINUES (S11: its question, and its // channels widened by what it acquired, are the defaults); else none // model default: settings.generation.models[route] for the task's route +// extractorModel an API sweep's extractor (default: +// settings.generation.models.extractor): a Claude model id the +// price table knows (release 28 F2) // question / channels / from / to a sweep's // feedback a revision's // copyOf run iteration N again on another model (same kind and inputs) @@ -15,6 +20,9 @@ // source / build the corpus (default: the newest build holding the channels) // cards / force a narration's (force: a continuation over a research // run that still waits, with what is done so far) +// entries a media draft's (cut, onscreen, teaser, flips, threads, +// youtube; narrate too): only these entry ids; `force` re-drafts +// a field that is a draft already (release 28) // autonomy a research run's: propose | limits | auto (default: // settings.generation.research.autonomy; the limits are the // settings') @@ -33,12 +41,13 @@ import os from "node:os"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; -import type { Paths } from "../lib/paths"; +import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; -import { capFor, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; +import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; -import { providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { PRICES, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; import { webTools } from "../lib/web/tools"; import { copyIteration, @@ -53,6 +62,7 @@ import { diskPostChannelOf } from "../lib/report/convert-server"; import { readAllPosts } from "../lib/posts-server"; import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index"; import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; +import { loadDeckChecks, type DeckChecks } from "../lib/report/draft/tasks/deckChecks"; import type { CorpusToolsLike } from "../lib/report/draft/tasks/types"; import { verifyReportQuotes } from "../bin/reports-check"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; @@ -72,6 +82,7 @@ export const REPORT_DRAFT_BODY_KEYS = [ "article", "iteration", "model", + "extractorModel", "feedback", "question", "channels", @@ -82,6 +93,7 @@ export const REPORT_DRAFT_BODY_KEYS = [ "source", "build", "cards", + "entries", "force", "autonomy", ] as const; @@ -93,6 +105,7 @@ export type ReportDraftBody = { article: string; iteration?: number; model?: string; + extractorModel?: string; feedback?: string; question?: string; channels?: string[]; @@ -103,11 +116,18 @@ export type ReportDraftBody = { source?: string; build?: string; cards?: string[]; + entries?: string[]; force?: boolean; autonomy?: Autonomy; }; -const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate", "research"]; +// A Claude model the price table knows: one of its ids, or a dated id of one +// (`claude-haiku-4-5-20251001`). +export function isKnownApiModel(model: string): boolean { + return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`)); +} + +const TASKS: readonly GenerationTask[] = GENERATION_TASKS; const ymd = /^\d{4}-\d{2}-\d{2}$/; function fail(msg: string): never { @@ -146,10 +166,19 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod set("iteration", int("iteration")); set("copyOf", int("copyOf")); set("model", text("model")); + const extractor = text("extractorModel"); + if (extractor !== undefined) { + if (!isKnownApiModel(extractor)) { + fail(`"extractorModel" is a Claude model id (${Object.keys(PRICES).filter((m) => m.startsWith("claude-")).join(", ")}): an API sweep's extractor runs on the API`); + } + if (task !== "sweep") fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)'); + out.extractorModel = extractor; + } set("feedback", text("feedback")); set("question", text("question")); set("channels", list("channels")); set("cards", list("cards")); + set("entries", list("entries")); set("source", text("source")); set("build", text("build")); for (const k of ["from", "to"] as const) { @@ -187,26 +216,24 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`); if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`); } + // A media draft (narrate, cut, …) is a step on the iteration it names. if (out.task === "narrate" && out.iteration === undefined) fail('a narration names the iteration it voices ("iteration")'); if (out.task === "narrate" && out.copyOf !== undefined) fail("a narration is a step, not an iteration: it has no copy"); + if (isStepTask(out.task) && out.iteration === undefined) fail(`a ${out.task} draft names the iteration it drafts on ("iteration")`); + if (isStepTask(out.task) && out.copyOf !== undefined) fail(`a ${out.task} draft is a step, not an iteration: it has no copy`); + if (out.entries && !isStepTask(out.task)) fail('"entries" is a media draft\'s (narrate, cut, onscreen, teaser, flips, threads, youtube)'); return out; } -const KIND_OF: Record<GenerationTask, Iteration["kind"]> = { - sweep: "sweep", - "revise-report": "revise-report", - "revise-video": "revise-video", - narrate: "sweep", // (a step: no iteration of its own) - research: "research", -}; +// A step task (narrate, cut, …) has no iteration of its own, so no kind; its +// cap is a narration's. +function kindOf(task: GenerationTask): Iteration["kind"] { + if (isStepTask(task)) throw new ReportDraftInputError(`a ${task} draft is a step: it makes no iteration`); + return task === "revise-report" || task === "revise-video" || task === "research" ? task : "sweep"; +} -const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = { - sweep: "sweep", - "revise-report": "revision", - "revise-video": "revision", - narrate: "narration", - research: "sweep", -}; +const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => + isStepTask(task) ? "narration" : task === "revise-report" || task === "revise-video" ? "revision" : "sweep"; export function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; @@ -304,7 +331,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null; if (body.copyOf !== undefined) { if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`); - if (src.kind !== KIND_OF[body.task]) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); + if (src.kind !== kindOf(body.task)) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); } if (body.task === "research" && !deps.researchEditor) { return refuse("a research run runs in the editor (its reads and acquisitions are the editor's actions)"); @@ -334,18 +361,22 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep } const model = modelFor(gen, body.task, body.model); const provider = providerOf(model); + if (body.extractorModel && provider === "local") { + warnings.push(`extractorModel ${body.extractorModel} is unused: a sweep on a local model runs the pipeline, which has no extractor`); + } let maxUsd: number | undefined; if (provider === "api") { - maxUsd = capFor(gen.caps, CAP_OF[body.task], body.maxUsd); + maxUsd = capFor(gen.caps, capOf(body.task), body.maxUsd); const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } - // The iteration: a new one (or a copy), queued; a narration's is the one named. + // The iteration: a new one (or a copy), queued; a step's is the one named. let n: number; - if (body.task === "narrate") { + if (isStepTask(body.task)) { const it = await readIteration(body.article, body.iteration!, paths); if (!it) return refuse(`"${body.article}" has no iteration i${body.iteration}`); - if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: a narration runs over a done iteration`); + const what = body.task === "narrate" ? "a narration" : `a ${body.task} draft`; + if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: ${what} runs over a done iteration`); n = it.n; } else if (src) { n = (await copyIteration(body.article, src.n, { model }, paths)).n; @@ -368,7 +399,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep await createIteration( body.article, { - kind: KIND_OF[body.task], + kind: kindOf(body.task), model, ...(body.task === "sweep" || body.task === "research" ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } } @@ -382,17 +413,17 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, _progress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal }, deps), + fn: (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps), }); if (!result.ok) { - if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); return { result }; } - if (body.task !== "narrate") await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); if (cont) await markContinued(body.article, cont.research.n, n, paths).catch(() => {}); // A job cancelled (or refused) before it ran leaves its iteration queued: end it. void result.done.then(async (d) => { - if (body.task === "narrate") return; + if (isStepTask(body.task)) return; const it = await readIteration(body.article, n, paths).catch(() => null); if (it?.status === "queued") { await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {}); @@ -405,7 +436,16 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep } async function runReportDraft( - o: { body: ReportDraftBody; model: string; maxUsd?: number; n: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal }, + o: { + body: ReportDraftBody; + model: string; + maxUsd?: number; + n: number; + jobId: string; + onLog: (l: string) => void; + signal: AbortSignal; + setProgress?: (snap: JobProgress) => void; + }, deps: ReportDraftDeps, ): Promise<void> { const { body, model, n, onLog, signal } = o; @@ -417,12 +457,12 @@ async function runReportDraft( // Again at the job's turn: jobs ahead in the queue may have spent the day. const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) { - if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); throw new Error(refusal); } } const it = (await readIteration(body.article, n, paths))!; - const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths); + const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, isStepTask(body.task) ? n : (it.parent ?? n), paths); let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null; let result: TaskResult | null = null; try { @@ -439,6 +479,7 @@ async function runReportDraft( } return p.then((m) => m.get(id) ?? null); }; + let deck: Promise<DeckChecks> | undefined; const taskDeps: TaskDeps = { llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined), corpus, @@ -455,6 +496,12 @@ async function runReportDraft( .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })), paths, log: onLog, + // The task's count as the job's progress (release 28 F3): turns, cards + // or entries, the runner's own `current` (nothing on disk re-counts it). + progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }), + // The build's validators, from this checkout's umtool (loaded once, when + // a media task first asks). + deckChecks: () => (deck ??= loadDeckChecks(paths.monorepoRoot || getPaths().monorepoRoot)), signal, ...(deps.now ? { now: deps.now } : {}), ...(body.task === "research" && deps.researchEditor ? { editor: deps.researchEditor, editorChannels: () => editorChannelsOf(paths) } : {}), @@ -462,7 +509,7 @@ async function runReportDraft( const projectsRoot = projectsRootOf(gen); // A local run costs nothing: it has no dollar cap. const cap = provider === "api" ? o.maxUsd! : Number.POSITIVE_INFINITY; - const extractor = gen.models.extractor; + const extractor = body.extractorModel ?? gen.models.extractor; let input: TaskInput; switch (body.task) { case "sweep": @@ -491,12 +538,35 @@ async function runReportDraft( break; } case "narrate": - input = { task: "narrate", article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.cards ? { cards: body.cards } : {}), ...(body.force ? { force: true } : {}) }; + case "cut": + case "onscreen": + case "teaser": + case "flips": + case "threads": + case "youtube": { + // A media draft: a step on the done iteration n (./tasks/media.ts). + const step = { + article: body.article, + n, + model, + projectsRoot, + ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), + jobId: o.jobId, + ...(body.entries ? { entries: body.entries } : {}), + ...(body.force ? { force: true } : {}), + }; + input = + body.task === "narrate" + ? { task: "narrate", ...step, ...(body.cards ? { cards: body.cards } : {}) } + : body.task === "cut" + ? { task: "cut", ...step, maxClips: gen.cut.maxClips } + : { task: body.task, ...step }; break; + } } result = await runTask(input, taskDeps); } catch (e) { - if (body.task !== "narrate") { + if (!isStepTask(body.task)) { const cur = await readIteration(body.article, n, paths).catch(() => null); if (cur && (cur.status === "queued" || cur.status === "running")) { await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {}); @@ -521,16 +591,16 @@ async function runReportDraft( if (result.status === "failed") throw new Error(result.summary); } -// The job's spend, per model, from the iteration's usage (a narration: the -// step's cost, on its model). +// The job's spend, per model, from the iteration's usage (a step — a +// narration, any media draft: the step's cost, on its model). async function recordUsage(body: ReportDraftBody, n: number, model: string, jobId: string, paths: Paths, now: Date) { const it = await readIteration(body.article, n, paths); if (!it) return; const day = utcDay(now); const base = { at: now.toISOString(), day, jobId, article: body.article, iteration: n, task: body.task }; let rows: GenerationUsageRow[]; - if (body.task === "narrate") { - const step = [...it.steps].reverse().find((s) => s.task === "narrate" && s.jobId === jobId); + if (isStepTask(body.task)) { + const step = [...it.steps].reverse().find((s) => s.task === body.task && s.jobId === jobId); rows = step?.cost ? [{ ...base, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: step.cost }] : []; } else { rows = Object.entries(it.usage) diff --git a/common/controller/researchAutoContinue.test.ts b/common/controller/researchAutoContinue.test.ts @@ -0,0 +1,341 @@ +// An `auto` research run continues into its sweep by itself (release 28 F1): +// the job-end trigger and the scan, once only, the caps, the builds, the idle +// boot. A temp store, temp builds, real registry jobs; the sweep it enqueues +// fails at its corpus (a stub that throws) — what is asserted is that it was +// asked for, once, as Continue asks it. No LLM is called. + +import { after, afterEach, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { sanitizeGeneration, type GenerationSettings } from "../lib/generationSettings"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction } from "../jobs/streamCommand"; +import { createIteration, iterationFile, listIterations, readIteration, updateIteration, type Iteration } from "../lib/report/iterations"; +import { newResearchState, writeResearchState, type ResearchRecord } from "../lib/report/draft/research/state"; +import { DEFAULT_RESEARCH_LIMITS, type Autonomy, type Proposal } from "../lib/report/draft/research/decide"; +import { appendGenerationUsage, utcDay } from "./generationUsage"; +import type { ReportDraftDeps } from "./reportDraft"; +import { + armResearchAutoContinue, + disarmResearchAutoContinue, + isResearchAutoContinueArmed, + maybeAutoContinue, + researchAutoContinueTick, + UNBUILT_CHECK, +} from "./researchAutoContinue"; + +let tmp: string; +let paths: Paths; +let gen: GenerationSettings; +const MODEL = "claude-sonnet-5-5"; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "research-auto-")); + paths = { + jobsDir: path.join(tmp, ".jobs"), + articlesDir: path.join(tmp, "reports"), + exportIndexDir: path.join(tmp, ".export-index"), + exportBuildsDir: path.join(tmp, ".export-builds"), + sitesDir: path.join(tmp, "sites"), + channelsDir: path.join(tmp, "channels"), + generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), + ollamaUrl: "http://127.0.0.1:9", + } as Paths; + await mkdir(paths.channelsDir, { recursive: true }); + gen = sanitizeGeneration({ anthropicBaseUrl: "http://127.0.0.1:9", caps: { sweep: 2, daily: 20, max: 5 } }); + await writeBuild("synth", ["synth-kitchen"]); +}); + +afterEach(() => disarmResearchAutoContinue()); + +after(async () => { + // Every job this file started has ended (asserted per test). + await rm(tmp, { recursive: true, force: true }); +}); + +async function writeBuild(build: string, channels: string[], mtime?: Date) { + const dir = path.join(paths.exportBuildsDir, build, "out"); + await mkdir(dir, { recursive: true }); + const file = path.join(dir, "corpus.json"); + await writeFile(file, JSON.stringify({ channels: channels.map((slug) => ({ slug })) })); + if (mtime) await utimes(file, mtime, mtime); +} + +const corpusAsked: string[] = []; +const deps = (o: { now?: () => Date; jobOf?: ReportDraftDeps["jobOf"] } = {}): ReportDraftDeps => ({ + paths, + corpusTools: async (source) => { + corpusAsked.push(source); + throw new Error("the test's corpus is a stub"); + }, + settings: () => ({ generation: gen }), + ...o, +}); + +const prop = (id: string, action: Proposal["action"], args: Record<string, unknown>, status: Proposal["status"], extra: Partial<Proposal> = {}): Proposal => ({ + id, + action, + args, + reason: "r", + evidence: [], + status, + ...extra, +}); + +// A research run whose job has ended: its proposals and autonomy. +async function makeRun(article: string, o: { autonomy?: Autonomy; channels?: string[]; proposals?: Proposal[] } = {}): Promise<number> { + const it = await createIteration(article, { kind: "research", model: MODEL, question: "Where did the second shop story start?", scope: o.channels ? { channels: o.channels } : {} }, paths); + const state = newResearchState(o.autonomy ?? "auto", DEFAULT_RESEARCH_LIMITS); + state.proposals = o.proposals ?? [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/1" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" })]; + await writeResearchState(article, it.n, state, paths); + await updateIteration(article, it.n, { status: "done", research: { autonomy: o.autonomy ?? "auto", phase: "wait" } } as never, paths); + return it.n; +} + +const recOf = async (article: string, n: number) => ((await readIteration(article, n, paths)) as Iteration & { research?: ResearchRecord }).research!; +const sweepsOf = async (article: string, n: number) => (await listIterations(article, paths)).filter((x) => x.kind === "sweep" && x.parent === n); +const turnsOf = async (article: string, n: number) => + (await readFile(iterationFile(paths, article, n, "turns.jsonl"), "utf8").catch(() => "")) + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as { kind: string; outcome: string }); + +// A job's end, waited for (the sweep the continuation enqueued fails at its stub corpus). +async function ended(jobId: string) { + for (let i = 0; i < 200; i++) { + const s = getRegistry().get(jobId)?.status; + if (s && s !== "queued" && s !== "running") return s; + await new Promise((r) => setTimeout(r, 20)); + } + throw new Error(`job ${jobId} did not end`); +} + +async function until<T>(fn: () => Promise<T | undefined | null | false>, what: string): Promise<T> { + for (let i = 0; i < 250; i++) { + const v = await fn(); + if (v) return v; + await new Promise((r) => setTimeout(r, 20)); + } + throw new Error(`timed out waiting for ${what}`); +} + +test("an auto run continues once, by itself, when its last acquisition's job ends", async () => { + // A real editor job stands for the acquisition: it runs until released. + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + const acq = await runManagedFunction({ kind: "import-video", queueKey: "", paths, fn: async () => gate }); + assert.ok(acq.ok); + void acq.stream.cancel(); + const article = "synth-auto-end"; + const n = await makeRun(article, { + channels: ["synth-kitchen"], + proposals: [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/2" }, "enqueued", { jobId: acq.jobId })], + }); + assert.ok(armResearchAutoContinue(deps(), { bootScan: false, env: {} })); + + // While the job runs: not now, and nothing written but the phase. + const early = await maybeAutoContinue(article, n, deps()); + assert.deepEqual(early, { outcome: "not-now", why: `waits on job(s): ${acq.jobId}` }); + assert.equal((await recOf(article, n)).autoContinue, undefined); + + // The job ends: the listener continues the run, with nothing else asked. + release(); + await acq.done; + const rec = await until(async () => { + const r = await recOf(article, n); + return r.autoContinue?.status === "continued" ? r : null; + }, "the continuation"); + const sweeps = await sweepsOf(article, n); + assert.equal(sweeps.length, 1); + const sweep = sweeps[0]!; + assert.deepEqual(rec.continuedBy, [sweep.n]); + assert.equal(rec.phase, "continued"); + assert.equal(rec.autoContinue!.by, sweep.n); + assert.equal(sweep.model, MODEL, "the run's own model"); + assert.equal(sweep.question, "Where did the second shop story start?"); + assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]); + assert.equal(getRegistry().get(sweep.jobId!)?.queueKey, "draft:api"); + assert.equal(await ended(sweep.jobId!), "failed", "the stub corpus"); + assert.deepEqual((await turnsOf(article, n)).map((t) => [t.kind, t.outcome]), [["auto-continue", "continued"]]); + + // Again, by either trigger: nothing more. + assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "continued already", final: true }); + await researchAutoContinueTick(); + assert.equal((await sweepsOf(article, n)).length, 1); +}); + +test("the heartbeat and job ends racing continue once; a claim held elsewhere is respected, a stale one looked into", async () => { + const article = "synth-auto-race"; + const n = await makeRun(article, { channels: ["synth-kitchen"] }); + armResearchAutoContinue(deps(), { bootScan: false, env: {} }); + const [tick, a, b] = await Promise.all([researchAutoContinueTick(), maybeAutoContinue(article, n, deps()), maybeAutoContinue(article, n, deps())]); + const outcomes = [...(tick?.continued.filter((c) => c.article === article).map(() => "continued") ?? []), a.outcome, b.outcome]; + assert.equal(outcomes.filter((o) => o === "continued").length, 1, JSON.stringify({ tick, a, b })); + const sweeps = await sweepsOf(article, n); + assert.equal(sweeps.length, 1); + assert.deepEqual((await recOf(article, n)).continuedBy, [sweeps[0]!.n]); + await ended(sweeps[0]!.jobId!); + // The sweep's end starts a scan: let it finish, then stop listening. + await researchAutoContinueTick(); + disarmResearchAutoContinue(); + + // Another process's fresh claim (the store's lock is what it took): not now. + const held = await makeRun("synth-auto-claimed", { channels: ["synth-kitchen"] }); + await updateIteration("synth-auto-claimed", held, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: new Date().toISOString() } } }) as never, paths); + assert.deepEqual(await maybeAutoContinue("synth-auto-claimed", held, deps()), { outcome: "not-now", why: "being continued" }); + assert.equal((await sweepsOf("synth-auto-claimed", held)).length, 0); + + // A stale claim whose sweep was made (the editor died before marking it): recorded, not made again. + const stale = await makeRun("synth-auto-stale", { channels: ["synth-kitchen"] }); + await updateIteration("synth-auto-stale", stale, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: "2026-01-01T00:00:00.000Z" } } }) as never, paths); + const made = await createIteration("synth-auto-stale", { kind: "sweep", model: MODEL, parent: stale, question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const r = await maybeAutoContinue("synth-auto-stale", stale, deps()); + assert.deepEqual(r, { outcome: "continued", by: made.n, warnings: [] }); + assert.deepEqual((await recOf("synth-auto-stale", stale)).continuedBy, [made.n]); + assert.equal((await sweepsOf("synth-auto-stale", stale)).length, 1); +}); + +test("propose and limits never continue by themselves; a proposal waiting for approval holds an auto run", async () => { + for (const autonomy of ["propose", "limits"] as const) { + const article = `synth-auto-${autonomy}`; + const n = await makeRun(article, { autonomy, channels: ["synth-kitchen"] }); + const r = await maybeAutoContinue(article, n, deps()); + assert.deepEqual(r, { outcome: "not-now", why: `autonomy ${autonomy}: the operator continues it`, final: true }); + assert.equal((await sweepsOf(article, n)).length, 0); + } + const article = "synth-auto-pending"; + const n = await makeRun(article, { + channels: ["synth-kitchen"], + proposals: [ + prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/3" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" }), + prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/4" }, "proposed", { note: "a download of unknown size waits" }), + ], + }); + assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "waits for approval: p02" }); + assert.equal((await sweepsOf(article, n)).length, 0); + assert.equal((await recOf(article, n)).autoContinue, undefined, "nothing recorded"); + // A run still running is not read further. + await updateIteration(article, n, { status: "running" }, paths); + assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "the run is running" }); +}); + +test("the daily cap: refused and recorded, not tried again the same UTC day, continued the next", async () => { + const day1 = new Date("2031-03-04T12:00:00.000Z"); + const day2 = new Date("2031-03-05T00:30:00.000Z"); + await appendGenerationUsage(paths.generationUsageFile, [ + { at: day1.toISOString(), day: utcDay(day1), jobId: "x", article: "other", iteration: 1, task: "sweep", model: MODEL, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 20 }, + ]); + const article = "synth-auto-cap"; + const n = await makeRun(article, { channels: ["synth-kitchen"] }); + const r = await maybeAutoContinue(article, n, deps({ now: () => day1 })); + assert.equal(r.outcome, "refused"); + assert.match((r as { reason: string }).reason, /daily/i); + const rec = await recOf(article, n); + assert.equal(rec.autoContinue!.status, "refused"); + assert.equal(rec.autoContinue!.day, "2031-03-04"); + const updatedAt = (await readIteration(article, n, paths))!.updatedAt; + + // The same day, later: not tried, nothing written. + const again = await maybeAutoContinue(article, n, deps({ now: () => new Date("2031-03-04T23:59:00.000Z") })); + assert.equal(again.outcome, "not-now"); + assert.match((again as { why: string }).why, /^refused today .*tried again tomorrow \(UTC\)$/); + assert.equal((await readIteration(article, n, paths))!.updatedAt, updatedAt); + assert.equal((await sweepsOf(article, n)).length, 0); + + // The next UTC day: the day's total is 0 again, and it continues. + const next = await maybeAutoContinue(article, n, deps({ now: () => day2 })); + assert.equal(next.outcome, "continued", JSON.stringify(next)); + const sweeps = await sweepsOf(article, n); + assert.equal(sweeps.length, 1); + await ended(sweeps[0]!.jobId!); + assert.deepEqual((await turnsOf(article, n)).map((t) => t.outcome), ["refused", "continued"]); +}); + +test("channels in no build are left out with a warning; with nothing left the run is held until a newer build", async () => { + // Acquired into a new channel (in no build) beside the run's own. + const article = "synth-auto-unbuilt"; + const n = await makeRun(article, { + channels: ["synth-kitchen"], + proposals: [ + prop("p01", "create-channel", { fields: { name: "Synth Radio" } }, "done", { channel: "synth-radio", doneAt: "2026-10-13T10:00:00.000Z" }), + prop("p02", "import-video", { slug: "synth-radio", url: "https://video.example/v/5" }, "done", { doneAt: "2026-10-13T10:05:00.000Z" }), + ], + }); + const r = await maybeAutoContinue(article, n, deps()); + assert.equal(r.outcome, "continued", JSON.stringify(r)); + const warning = "not in any build yet: synth-radio — rebuild the site and continue again"; + assert.ok((r as { warnings: string[] }).warnings.includes(warning)); + const sweep = (await sweepsOf(article, n))[0]!; + assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]); + assert.deepEqual( + (await readIteration(article, sweep.n, paths))!.checks?.find((c) => c.name === UNBUILT_CHECK), + { name: UNBUILT_CHECK, ok: false, detail: warning }, + ); + assert.ok((await recOf(article, n)).autoContinue!.warnings!.includes(warning)); + await ended(sweep.jobId!); + + // Nothing of its own, and its one acquisition in no build: held. + const only = "synth-auto-held"; + const h = await makeRun(only, { + proposals: [prop("p01", "create-channel", { fields: { name: "Synth Late" } }, "done", { channel: "synth-late", doneAt: "2026-10-13T10:00:00.000Z" })], + }); + const held = await maybeAutoContinue(only, h, deps()); + assert.deepEqual(held, { outcome: "held", reason: "not in any build yet: synth-late — rebuild the site, and it continues by itself" }); + assert.equal((await recOf(only, h)).autoContinue!.status, "held"); + const before = (await readIteration(only, h, paths))!.updatedAt; + const quiet = await maybeAutoContinue(only, h, deps()); + assert.equal(quiet.outcome, "not-now", "the same day and no newer build: not read further"); + assert.equal((await readIteration(only, h, paths))!.updatedAt, before); + // A build that holds it, newer than the hold: it continues. + await writeBuild("synth-late", ["synth-late"], new Date(Date.now() + 60_000)); + const now = await maybeAutoContinue(only, h, deps()); + assert.equal(now.outcome, "continued", JSON.stringify(now)); + const s = (await sweepsOf(only, h))[0]!; + assert.deepEqual(s.scope?.channels, ["synth-late"]); + await ended(s.jobId!); +}); + +test("a held run continues when a site build that holds its channel ends", async () => { + const article = "synth-auto-rebuilt"; + const n = await makeRun(article, { + proposals: [prop("p01", "create-channel", { fields: { name: "Synth Rebuilt" } }, "done", { channel: "synth-rebuilt", doneAt: "2026-10-13T10:00:00.000Z" })], + }); + assert.equal((await maybeAutoContinue(article, n, deps())).outcome, "held"); + armResearchAutoContinue(deps(), { bootScan: false, env: {} }); + // The operator puts it on a site and builds it: the build job's end runs the scan. + const build = await runManagedFunction({ + kind: "build-export", + queueKey: "", + paths, + fn: async () => writeBuild("synth-rebuilt", ["synth-rebuilt"], new Date(Date.now() + 120_000)), + }); + assert.ok(build.ok); + void build.stream.cancel(); + await build.done; + const rec = await until(async () => { + const r = await recOf(article, n); + return r.autoContinue?.status === "continued" ? r : null; + }, "the continuation after the build"); + const sweep = (await sweepsOf(article, n))[0]!; + assert.equal(rec.autoContinue!.by, sweep.n); + assert.deepEqual(sweep.scope?.channels, ["synth-rebuilt"]); + await ended(sweep.jobId!); + await researchAutoContinueTick(); +}); + +test("an idle boot arms nothing: no listener, and the heartbeat's call is a no-op", async () => { + const article = "synth-auto-idle"; + const n = await makeRun(article, { channels: ["synth-kitchen"] }); + assert.equal(armResearchAutoContinue(deps(), { env: { ARCHILYZER_IDLE_BOOT: "1" } }), false); + assert.equal(isResearchAutoContinueArmed(), false); + assert.equal(await researchAutoContinueTick(), null); + assert.equal((await sweepsOf(article, n)).length, 0); + // Armed, the boot scan finds it. + assert.equal(armResearchAutoContinue(deps(), { env: {}, bootScan: false }), true); + const tick = await researchAutoContinueTick(); + assert.ok(tick?.continued.some((c) => c.article === article && c.n === n), JSON.stringify(tick)); + await ended((await sweepsOf(article, n))[0]!.jobId!); +}); diff --git a/common/controller/researchAutoContinue.ts b/common/controller/researchAutoContinue.ts @@ -0,0 +1,357 @@ +// AN `auto` RESEARCH RUN CONTINUES INTO ITS SWEEP BY ITSELF (release 28 F1). +// +// What the operator's "Continue into a sweep" does — `report-draft {task: +// "sweep", iteration: n}` (controller/reportDraft.ts, through continuationOf) +// — done by the editor once the run's acquisitions settle, for a run whose +// autonomy is `auto` (`propose` and `limits` are always continued by the +// operator). maybeAutoContinue(article, n) is the one function; it is +// idempotent, and two triggers call it: +// - the end of a job the run waits on: settle (researchRuns.ts) names an +// `auto` run's pending editor jobs, and the registry's job-end listener +// takes the run of one that ended; a `report-draft` job's end (the +// research job itself, among others) or a site build's runs the scan +// below; +// - the scan, on the editor's heartbeat and once at boot: the research +// iterations (a proposals.json) of every article, a run already finished +// with (continued, or not `auto`) remembered and not read again. +// Both are armed by the editor's instrumentation BELOW the idle gate +// (armResearchAutoContinue refuses an idle boot too): ARCHILYZER_IDLE_BOOT +// arms nothing, and the heartbeat's call is a no-op unarmed. +// +// A run continues when: +// - it is a done research run, `auto`, not continued (no `continuedBy`, no +// fresh claim), with nothing waiting for the operator's yes or no and +// every acquisition job ended (done, failed or cancelled); +// - something it would sweep is in a composed build: a channel in none +// (a created channel is on no site until the operator puts it on one and +// builds it) is left out, and the sweep carries the warning "not in any +// build yet: <slug> — rebuild the site and continue again". With nothing +// left the run is `held`, and tried again once a newer build exists (or +// on a later day); +// - the caps hold: the sweep is the run's own model, its per-job cap the +// sweep's (caps.sweep), and an API model is refused past the daily cap — +// `refused`, tried again on a later UTC day, never in a loop. Any other +// refusal of the ask is recorded and retried the same way. +// The once-only mark is a claim taken under the article store's lock +// (updateIteration's read-patch-write): a heartbeat and a job end racing, in +// this process or another, continue once. A claim older than CLAIM_STALE_MS +// (the editor died between the claim and the enqueue) is looked into: a +// sweep it made is recorded, else it is claimed again. +// +// Every outcome is on the run: `research.autoContinue` in its iteration.json +// (the umtool queue shows it), a `{kind: "auto-continue"}` line in its +// turns.jsonl, and — for channels left out — a failed `unbuilt channels` +// check on the sweep it made. + +import { readdir, stat } from "node:fs/promises"; +import { isIdleBoot } from "../lib/idleBoot"; +import { getSettings } from "../lib/settings"; +import { providerOf } from "../lib/llm"; +import { onJobEnd } from "../jobs/registry"; +import { REPORT_ID_RE } from "../lib/report/schema"; +import { + appendIterationTurns, + iterationDirNumbers, + iterationFile, + listIterations, + readIteration, + updateIteration, + type Iteration, +} from "../lib/report/iterations"; +import { listCorpusBuilds } from "../lib/report/draft/tasks/corpusSource"; +import { readResearchState, widenedChannels, type AutoContinueRecord, type ResearchRecord } from "../lib/report/draft/research/state"; +import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage"; +import { enqueueReportDraft, REPORT_DRAFT_JOB_KIND, type ReportDraftDeps } from "./reportDraft"; +import { markContinued, researchState, takeWatchedRun } from "./researchRuns"; + +export const CLAIM_STALE_MS = 10 * 60_000; + +// The jobs whose end runs the scan: a generation's (the research job's own +// among them) and a site build's (a held run may now have its build). +export const SCAN_ON_END = new Set([REPORT_DRAFT_JOB_KIND, "publish-build-site", "build-export", "build-deploy", "build-all", "build-deploy-all"]); +export const UNBUILT_CHECK = "unbuilt channels"; + +export type AutoContinueResult = + | { outcome: "continued"; by: number; jobId?: string; warnings: string[] } + | { outcome: "held" | "refused"; reason: string } + // Not now (nothing written). `final`: never — the scan stops reading it. + | { outcome: "not-now"; why: string; final?: boolean }; + +const recordOf = (it: Iteration): ResearchRecord | undefined => (it as { research?: ResearchRecord }).research; + +// One attempt per run at a time, in this process (the claim below is the +// guard across processes). +const chains = new Map<string, Promise<unknown>>(); +function serial<T>(key: string, fn: () => Promise<T>): Promise<T> { + const prev = chains.get(key) ?? Promise.resolve(); + const next = prev.then(fn, fn); + const tail = next.catch(() => {}); + chains.set(key, tail); + void tail.then(() => { + if (chains.get(key) === tail) chains.delete(key); + }); + return next; +} + +class NotNow extends Error {} + +async function record(article: string, n: number, ac: AutoContinueRecord, deps: ReportDraftDeps, now: Date): Promise<void> { + await updateIteration( + article, + n, + (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: "auto" as const, phase: "ready" as const }), autoContinue: ac } }), + deps.paths, + now, + ); + const { status, ...rest } = ac; + await appendIterationTurns(article, n, [{ kind: "auto-continue", outcome: status, ...rest }], deps.paths).catch(() => {}); +} + +// Why run `it` is not continued now, from its iteration.json alone (null: +// read on). `final` when it never will be. +function notYet(it: Iteration | null, now: Date): { why: string; final?: boolean } | null { + if (!it) return { why: "no such iteration", final: true }; + if (it.kind !== "research") return { why: `a ${it.kind} iteration, not a research run`, final: true }; + const rec = recordOf(it); + if (rec && rec.autonomy !== "auto") return { why: `autonomy ${rec.autonomy}: the operator continues it`, final: true }; + if ((rec?.continuedBy?.length ?? 0) > 0 || rec?.autoContinue?.status === "continued") return { why: "continued already", final: true }; + if (it.status === "failed" || it.status === "cancelled") return { why: `the run ${it.status}`, final: true }; + if (it.status !== "done") return { why: `the run is ${it.status}` }; + const ac = rec?.autoContinue; + if (ac?.status === "claimed" && now.getTime() - Date.parse(ac.at) < CLAIM_STALE_MS) return { why: "being continued" }; + if (ac?.status === "refused" && ac.day === utcDay(now)) return { why: `refused today (${ac.reason}); tried again tomorrow (UTC)` }; + return null; +} + +// Continue research run `n` of `article` into its sweep if it is ready to be +// (see the head of this file). Idempotent. +export function maybeAutoContinue(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> { + return serial(`${article}/${n}`, () => attempt(article, n, deps)); +} + +async function attempt(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> { + const paths = deps.paths; + const now = deps.now?.() ?? new Date(); + const today = utcDay(now); + const it = await readIteration(article, n, paths).catch(() => null); + const no = notYet(it, now); + if (no) return { outcome: "not-now", ...no }; + const run = it!; + const rec = recordOf(run); + if (!rec) { + // A record is written with the run's first proposals; without one, its + // autonomy is proposals.json's. + const state = await readResearchState(article, n, paths); + if (!state) return { outcome: "not-now", why: "no proposals yet" }; + if (state.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${state.autonomy}: the operator continues it`, final: true }; + } + const builds = await listCorpusBuilds(paths.exportBuildsDir); + const newest = Math.max(0, ...builds.map((b) => b.mtimeMs)); + const ac = rec?.autoContinue; + if (ac?.status === "held" && ac.day === today && newest <= (ac.buildsAt ?? 0)) { + return { outcome: "not-now", why: `held (${ac.reason}) until a newer build` }; + } + + // The run now: its acquisitions refreshed from their jobs (and its phase + // written, and its pending jobs watched). + const view = await researchState(article, n, { paths, ...(deps.jobOf ? { jobOf: deps.jobOf } : {}) }); + if (view.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${view.autonomy}: the operator continues it`, final: true }; + if (view.waitingOn.approval.length) return { outcome: "not-now", why: `waits for approval: ${view.waitingOn.approval.join(", ")}` }; + if (view.waitingOn.jobs.length) return { outcome: "not-now", why: `waits on job(s): ${view.waitingOn.jobs.join(", ")}` }; + if (view.phase !== "ready") return { outcome: "not-now", why: `its phase is ${view.phase}`, ...(view.phase === "continued" ? { final: true } : {}) }; + + // The scope: the run's channels and what it acquired into, less any in no build. + const channels = widenedChannels(run.scope?.channels ?? [], view); + const built = new Set(builds.flatMap((b) => b.channels)); + const unbuilt = channels.filter((c) => !built.has(c)); + const kept = channels.filter((c) => built.has(c)); + const warnings = unbuilt.length ? [`not in any build yet: ${unbuilt.join(", ")} — rebuild the site and continue again`] : []; + if (!kept.length) { + const reason = channels.length ? `not in any build yet: ${unbuilt.join(", ")} — rebuild the site, and it continues by itself` : "it names no channel and acquired into none"; + await record(article, n, { status: "held", at: now.toISOString(), reason, day: today, buildsAt: newest }, deps, now); + return { outcome: "held", reason }; + } + + // The caps: an API model is refused past the day's total (and the ask + // refuses again; the job, at its turn). + const gen = (deps.settings ?? getSettings)().generation; + const model = run.model; + if (providerOf(model) === "api") { + const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, today), gen.caps.daily); + if (refusal) { + await record(article, n, { status: "refused", at: now.toISOString(), reason: refusal, day: today }, deps, now); + return { outcome: "refused", reason: refusal }; + } + } + + // A stale claim: the sweep it made, if any, is the continuation. + if (ac?.status === "claimed") { + const made = (await listIterations(article, paths)).find((x) => x.kind === "sweep" && x.parent === n && Date.parse(x.createdAt) >= Date.parse(ac.at)); + if (made) { + await markContinued(article, n, made.n, paths); + await record(article, n, { status: "continued", at: now.toISOString(), by: made.n, ...(ac.warnings?.length ? { warnings: ac.warnings } : {}) }, deps, now); + return { outcome: "continued", by: made.n, warnings: ac.warnings ?? [] }; + } + } + + // THE CLAIM: checked and marked in one write under the store's lock. + try { + await updateIteration( + article, + n, + (cur) => { + const r = recordOf(cur); + if ((r?.continuedBy?.length ?? 0) > 0 || r?.autoContinue?.status === "continued") throw new NotNow("continued already"); + const c = r?.autoContinue; + if (c?.status === "claimed" && now.getTime() - Date.parse(c.at) < CLAIM_STALE_MS) throw new NotNow("being continued"); + return { + research: { + ...(r ?? { autonomy: "auto" as const, phase: "ready" as const }), + autoContinue: { status: "claimed" as const, at: now.toISOString(), ...(warnings.length ? { warnings } : {}) }, + }, + }; + }, + paths, + now, + ); + } catch (e) { + if (e instanceof NotNow) return { outcome: "not-now", why: e.message }; + throw e; + } + + // The continuation, as the operator's Continue asks it. + const out = await enqueueReportDraft({ task: "sweep", article, iteration: n, model, channels: kept }, deps); + if (!out.result.ok || !("iteration" in out)) { + const reason = (out.result as { error: string }).error; + await record(article, n, { status: "refused", at: now.toISOString(), reason, day: today }, deps, now); + return { outcome: "refused", reason }; + } + // Nobody reads the job's stream (the ops routes release it the same way). + void out.result.stream.cancel(); + const all = [...warnings, ...(out.warnings ?? [])]; + await record(article, n, { status: "continued", at: now.toISOString(), by: out.iteration, ...(all.length ? { warnings: all } : {}) }, deps, now); + if (unbuilt.length) { + await updateIteration( + article, + out.iteration, + (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => c.name !== UNBUILT_CHECK), { name: UNBUILT_CHECK, ok: false, detail: warnings[0] }] }), + paths, + now, + ).catch(() => {}); + } + return { outcome: "continued", by: out.iteration, jobId: out.result.jobId, warnings: all }; +} + +// ─── the scan ─── + +// Runs the scan has finished with (continued, or never `auto`): not read again. +const finished = new Set<string>(); +let scanning: Promise<ScanResult> | null = null; + +export type ScanResult = { runs: number; continued: { article: string; n: number; by: number }[]; held: string[]; refused: string[] }; + +// Every research run that might continue, tried once. One scan at a time (a +// second caller shares the one going). +export function scanAutoContinue(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> { + if (!scanning) { + scanning = scan(deps, log).finally(() => { + scanning = null; + }); + } + return scanning; +} + +async function scan(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> { + const out: ScanResult = { runs: 0, continued: [], held: [], refused: [] }; + let articles: string[]; + try { + articles = (await readdir(deps.paths.articlesDir, { withFileTypes: true })).filter((e) => e.isDirectory() && REPORT_ID_RE.test(e.name)).map((e) => e.name); + } catch { + return out; + } + for (const article of articles) { + let ns: number[]; + try { + ns = await iterationDirNumbers(article, deps.paths); + } catch { + continue; + } + for (const n of ns) { + const key = `${article}/${n}`; + if (finished.has(key)) continue; + // Only a research run has a proposals.json. + if (!(await stat(iterationFile(deps.paths, article, n, "proposals.json")).then(() => true, () => false))) continue; + out.runs++; + const r: AutoContinueResult = await maybeAutoContinue(article, n, deps).catch((e): AutoContinueResult => ({ outcome: "not-now", why: (e as Error).message })); + report(article, n, r, out, log); + if (r.outcome === "continued" || (r.outcome === "not-now" && r.final)) finished.add(key); + } + } + return out; +} + +function report(article: string, n: number, r: AutoContinueResult, out: ScanResult | null, log?: (line: string) => void) { + if (r.outcome === "continued") { + out?.continued.push({ article, n, by: r.by }); + log?.(`research auto-continue: ${article} i${n} continued by i${r.by}${r.warnings.length ? ` (${r.warnings.join("; ")})` : ""}`); + } else if (r.outcome === "held" || r.outcome === "refused") { + out?.[r.outcome].push(`${article}/${n}`); + log?.(`research auto-continue: ${article} i${n} ${r.outcome}: ${r.reason}`); + } +} + +// ─── arming (the editor's instrumentation, below the idle gate) ─── + +type Armed = { deps: ReportDraftDeps; log?: (line: string) => void; off: () => void }; + +declare global { + // eslint-disable-next-line no-var + var __yttResearchAutoContinue__: Armed | undefined; +} + +// Arm both triggers: the job-end listener now, the boot scan now, and the +// heartbeat's tick from here on. Refused (false) on an idle boot. Idempotent: +// a second call only replaces the deps. +export function armResearchAutoContinue(deps: ReportDraftDeps, o: { log?: (line: string) => void; env?: Record<string, string | undefined>; bootScan?: boolean } = {}): boolean { + if (isIdleBoot(o.env)) return false; + const armed = globalThis.__yttResearchAutoContinue__; + if (armed) { + armed.deps = deps; + armed.log = o.log; + return true; + } + const state: Armed = { deps, ...(o.log ? { log: o.log } : {}), off: () => {} }; + state.off = onJobEnd((job) => { + const run = takeWatchedRun(job.id); + if (run) { + void maybeAutoContinue(run.article, run.n, state.deps).then( + (r) => report(run.article, run.n, r, null, state.log), + (e) => state.log?.(`research auto-continue: ${run.article} i${run.n}: ${(e as Error).message}`), + ); + } else if (SCAN_ON_END.has(job.kind)) { + // A research job's end (or any generation's) — the scan finds its run — + // or a site build's, which may hold what a held run waits for. + void scanAutoContinue(state.deps, state.log).catch(() => {}); + } + }); + globalThis.__yttResearchAutoContinue__ = state; + if (o.bootScan !== false) void scanAutoContinue(deps, o.log).catch(() => {}); + return true; +} + +export function disarmResearchAutoContinue(): void { + globalThis.__yttResearchAutoContinue__?.off(); + globalThis.__yttResearchAutoContinue__ = undefined; + finished.clear(); +} + +export function isResearchAutoContinueArmed(): boolean { + return globalThis.__yttResearchAutoContinue__ !== undefined; +} + +// The heartbeat's call: a scan when armed, else nothing (null). +export async function researchAutoContinueTick(): Promise<ScanResult | null> { + const armed = globalThis.__yttResearchAutoContinue__; + if (!armed) return null; + return scanAutoContinue(armed.deps, armed.log); +} diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts @@ -18,7 +18,9 @@ // THE CONTINUATION is `report-draft {task: "sweep", iteration: <research n>}` // (controller/reportDraft.ts, through continuationOf here): a sweep iteration // whose parent is the research run, over the run's channels and every channel -// a done acquisition wrote into. +// a done acquisition wrote into. An `auto` run asks it by itself once its +// acquisitions settle (release 28 F1, controller/researchAutoContinue.ts): +// settle below names the jobs such a run still waits on (watchResearchJobs). import type { Paths } from "../lib/paths"; import { getJobEntry } from "../jobs/listJobs"; @@ -35,6 +37,7 @@ import { waitingOn, widenedChannels, writeResearchState, + type AutoContinueRecord, type JobOf, type ResearchPhase, type ResearchRecord, @@ -95,9 +98,48 @@ async function settle(article: string, it: Iteration, state: ResearchState, chan if (it.status !== "queued" && it.status !== "running" && rec?.phase !== phase) { await updateIteration(article, it.n, (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: state.autonomy }), phase } }), paths); } + // An `auto` run hears its acquisitions end (release 28 F1). + if (state.autonomy === "auto" && phase !== "continued") watchResearchJobs(article, it.n, waitingOn(state).jobs); return phase; } +// ─── the jobs an `auto` run waits on (release 28 F1) ─── +// +// Job id → the run, in this process: whoever refreshes an `auto` run (settle, +// above) names the editor jobs it still waits on, and the job-end listener +// (controller/researchAutoContinue.ts) takes the run of a job that ended. A +// restart forgets them; the boot pass and the heartbeat find the runs again. + +const WATCH_MAX = 2000; + +declare global { + // eslint-disable-next-line no-var + var __yttResearchJobWatch__: Map<string, { article: string; n: number }> | undefined; +} + +const watch = () => (globalThis.__yttResearchJobWatch__ ??= new Map()); + +export function watchResearchJobs(article: string, n: number, jobIds: readonly string[]): void { + const m = watch(); + for (const id of jobIds) { + m.delete(id); + m.set(id, { article, n }); + } + // Oldest first out: a map past its bound forgets the longest-watched. + for (const id of m.keys()) { + if (m.size <= WATCH_MAX) break; + m.delete(id); + } +} + +// The run waiting on job `id`, once (the watch is taken). +export function takeWatchedRun(id: string): { article: string; n: number } | undefined { + const m = watch(); + const run = m.get(id); + if (run) m.delete(id); + return run; +} + export type ResearchView = { article: string; iteration: number; @@ -111,6 +153,9 @@ export type ResearchView = { continuedBy: number[]; // The agent's closing words: what the archive holds, what it asked for. notes?: string; + // An `auto` run's own continuation: continued (by), refused or held, and + // why (release 28 F1). + autoContinue?: AutoContinueRecord; }; function viewOf(article: string, it: Iteration, state: ResearchState, phase: ResearchPhase): ResearchView { @@ -126,6 +171,7 @@ function viewOf(article: string, it: Iteration, state: ResearchState, phase: Res waitingOn: waitingOn(state), continuedBy: recordOf(it)?.continuedBy ?? [], ...(recordOf(it)?.notes ? { notes: recordOf(it)!.notes } : {}), + ...(recordOf(it)?.autoContinue ? { autoContinue: recordOf(it)!.autoContinue } : {}), }; } diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -99,6 +99,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "transcribe-file": { label: "Transcribe file", drainable: false }, // One synthesis (pnpm ops tts): one engine run, or a cache hit. "tts-file": { label: "Text to speech", drainable: false }, + // The verdict bench (pnpm ops bench-verdicts, release 28 M7): one run. + "bench-verdicts": { label: "Verdict bench", drainable: false }, }; test("added kinds carry their pinned label and drainability", () => { diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -942,6 +942,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: false, queueKeyStrategy: "custom", }, + // The verdict bench (release 28 M7): ruled fact-check claims asked of + // models, one per call — `pnpm ops bench-verdicts`, on `draft:local` when + // any model is local (the GPU arbiter's path) else `draft:api`. It reads + // the article registry and cues' text, and writes only under the checkout's + // `.generation/bench/`; neither guard. Not replayable: a re-run of the same + // run id resumes it. + "bench-verdicts": { + kind: "bench-verdicts", + label: "Verdict bench", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + }, "tts-file": { kind: "tts-file", label: "Text to speech", diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -26,7 +26,14 @@ export type JobProgressMetric = // Clip windows of a fetch-windows batch (controller/fetchWindows.ts). Spans // channels, so there is no channel count to re-count; the runner always sets // `current`. - | "clips"; + | "clips" + // A report-draft job (controller/reportDraft.ts, release 28 F3): an agent + // task's model turns (the target is its turn cap), a media task's cards, a + // pipeline's recordings read or a media task's entries. Nothing on disk to + // re-count; the runner always sets `current`. + | "turns" + | "cards" + | "entries"; export type JobProgress = { metric: JobProgressMetric; @@ -184,6 +191,45 @@ function markTerminal( if (typeof exitCode === "number") job.exitCode = exitCode; } +// WHO HEARS A JOB END (release 28 F1): a listener is told once per job, after +// its terminal state is set, on a later turn of the event loop (so the job's +// own end — its sidecar write — goes first), and a listener that throws never +// touches the job. Kept on globalThis like the registry. An `auto` research +// run listens for its acquisitions here (controller/researchAutoContinue.ts). +export type JobEndListener = (job: Readonly<Pick<JobRecord, "id" | "kind" | "status" | "channelSlug">>) => void; + +declare global { + // eslint-disable-next-line no-var + var __yttJobEndListeners__: Set<JobEndListener> | undefined; +} + +const endNotified = new WeakSet<JobRecord>(); + +// Listen for every job's end; the answer stops listening. +export function onJobEnd(listener: JobEndListener): () => void { + const set = (globalThis.__yttJobEndListeners__ ??= new Set()); + set.add(listener); + return () => { + set.delete(listener); + }; +} + +function notifyJobEnd(job: JobRecord): void { + const set = globalThis.__yttJobEndListeners__; + if (!set?.size || endNotified.has(job)) return; + endNotified.add(job); + const seen = { id: job.id, kind: job.kind, status: job.status, ...(job.channelSlug ? { channelSlug: job.channelSlug } : {}) }; + setImmediate(() => { + for (const fn of set) { + try { + fn(seen); + } catch { + // a listener never breaks a job's end + } + } + }); +} + // The registry owns job LIFECYCLE/STATE (the JobRecord, meta sidecars, tasks, // terminal transitions). Queue ORDERING — which job runs vs. waits, and the // foreground-before-background priority — is delegated to the shared Scheduler @@ -285,6 +331,7 @@ class JobRegistry { job.tasks = []; job.drainController = undefined; getScheduler().complete(id); + notifyJobEnd(job); } cancel(id: string): boolean { diff --git a/common/lib/citations/fragment.test.ts b/common/lib/citations/fragment.test.ts @@ -0,0 +1,58 @@ +// Fragment quotes (release 28 Q2): what is one, and the full sentence code offers. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { FRAGMENT_END_WORDS, fragmentOf, fullSentenceFor, isFragmentQuote } from "./fragment"; +import { strictQuoteCheck } from "./verify"; +import { cuesOf } from "../../testing/draft/corpus.mjs"; + +const cue = (start: number, text: string) => ({ start, end: start + 4.8, text }); + +test("a fragment: under four words, or a part ending on a function word", () => { + assert.deepEqual(fragmentOf("I priced it as"), { why: "ends on “as”", part: "I priced it as" }); + assert.equal(fragmentOf("never again")?.why, "under 4 words"); + assert.equal(fragmentOf("my lawyer told me not to")?.why, "ends on “to”"); + // Case and punctuation aside; an ellipsis part is judged on its own. + assert.equal(fragmentOf("I paid for THE")?.why, "ends on “the”"); + assert.equal(fragmentOf("I would never sell the bakery … to a chain and")?.part, "to a chain and"); + // Whole sentences and clauses pass. + assert.equal(fragmentOf("I would never sell the bakery to a chain"), null); + assert.equal(fragmentOf("What are you even looking at?"), null, "sentence punctuation ends a sentence whatever its last word"); + assert.equal(isFragmentQuote("the judges were friends of mine so it felt wrong"), false); + assert.equal(fragmentOf(""), null); + assert.ok(FRAGMENT_END_WORDS.includes("as") && FRAGMENT_END_WORDS.includes("her")); +}); + +test("the full sentence: unpunctuated captions extend to the end of the quote's cue", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + assert.equal(fullSentenceFor("I paid for the", cues, 45), "I paid for the new mixer myself"); + const pie = (await cuesOf("synth-kitchen", "pie-stream-02"))!; + assert.equal(fullSentenceFor("my lawyer told me not to", pie, 40), "my lawyer told me not to talk about the lease"); + // Under four words: the cue's run holds it. + assert.equal(fullSentenceFor("I did not", pie, 10), "I did not enter the contest this year"); + // Not there verbatim: nothing to offer. + assert.equal(fullSentenceFor("I sold the bakery as", cues, 15), null); +}); + +test("the full sentence: punctuation, a new cue's capital, one more cue, and the cap", () => { + const punct = [cue(0, "So the price. I priced it as a loss, and"), cue(5, "then I moved on. Next")]; + assert.equal(fullSentenceFor("I priced it as", punct, 0), "I priced it as a loss, and then I moved on."); + // A cue boundary where the next cue starts a sentence ends it (the pronoun I does not). + const caps = [cue(0, "we said that the oven ran hot"), cue(5, "Then we left"), cue(10, "I think")]; + assert.equal(fullSentenceFor("the oven ran", caps, 0), "the oven ran hot"); + // Still under four words: back to the sentence's start. + assert.equal(fullSentenceFor("ran hot", caps, 0), "we said that the oven ran hot"); + // The quote's cue ends on a function word: one more cue. + const more = [cue(0, "she told me that the shop is"), cue(5, "closing in the spring"), cue(10, "and nobody knew")]; + assert.equal(fullSentenceFor("the shop is", more, 0), "the shop is closing in the spring"); + // Too long to be offered. + const long = [cue(0, `the ${"very ".repeat(40)}long one of`), cue(5, "and of")]; + assert.equal(fullSentenceFor("the very very", long, 0, { maxWords: 10 }), null); +}); + +test("the full sentence passes the strict check wherever the quote did", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + const s = fullSentenceFor("I paid for the", cues, 45)!; + assert.equal(strictQuoteCheck(s, cues, 45).ok, true); + assert.equal(fragmentOf(s), null); +}); diff --git a/common/lib/citations/fragment.ts b/common/lib/citations/fragment.ts @@ -0,0 +1,155 @@ +// FRAGMENT QUOTES — a quote that stops mid-thought (release 28, Q2). +// +// A quote is a FRAGMENT when it has fewer than FRAGMENT_MIN_WORDS words, or +// one of its parts (the runs convertSweep joins with an ellipsis) ends on a +// function word — "I priced it as", "my lawyer told me not to". A part that +// ends on sentence punctuation (. ! ? …) is a whole sentence whatever its last +// word ("What are you looking at?"). Accepted collateral of the end-word rule: +// a sentence that really ends on an object pronoun ("I told her") when its +// transcript is unpunctuated. +// +// `fullSentenceFor` is what code offers instead: the smallest run of the +// record's text, from the quote's first word, that ends at sentence +// punctuation or at a cue boundary where the next cue starts a new sentence; +// with unpunctuated captions, the end of the cue the quote ends in, then one +// more cue while it is still a fragment. Capped at FULL_SENTENCE_MAX_WORDS +// (or the quote's own length and a margin, when the quote is longer). A +// result still under the minimum is widened back to the sentence's start. +// The words are the cues' own, joined with single spaces, so the sentence +// passes the strict check wherever the quote did. +// +// Pure, no imports but ./verify (also pure). + +import { STRICT_QUOTE_WINDOW_SECONDS, quoteFragments, strictNormalize } from "./verify"; + +export const FRAGMENT_MIN_WORDS = 4; + +// The words a quote may not end on (lowercase; compared normalised). +export const FRAGMENT_END_WORDS = [ + "as", "to", "the", "and", "of", "a", "an", "in", "on", "for", "with", "at", "by", "from", "that", "which", + "but", "or", "if", "is", "was", "be", "i", "my", "your", "their", "our", "his", "her", +] as const; + +export const FULL_SENTENCE_MAX_WORDS = 30; + +const END_WORDS = new Set<string>(FRAGMENT_END_WORDS); + +// A word that ends a sentence: its last letter is followed by . ! ? or … +// (closing quotes and brackets allowed after). +const SENTENCE_END_RE = /[.!?…]["'”’)\]]*$/; + +const wordsOf = (text: string) => strictNormalize(text).split(" ").filter(Boolean); + +export type FragmentFinding = { + // Why it is a fragment: "under 4 words", or "ends on “as”". + why: string; + // The part (an ellipsis-joined run, or the whole quote) that is one. + part: string; +}; + +// Whether a quote is a fragment, and which part; null when it is not. +export function fragmentOf(quote: string): FragmentFinding | null { + const total = wordsOf(quote).length; + if (total === 0) return null; + const parts = quoteFragments(quote); + if (total < FRAGMENT_MIN_WORDS) return { why: `under ${FRAGMENT_MIN_WORDS} words`, part: parts.at(-1) ?? quote.trim() }; + for (const part of parts) { + if (SENTENCE_END_RE.test(part.trim())) continue; + const last = wordsOf(part).at(-1); + if (last && END_WORDS.has(last)) return { why: `ends on “${last}”`, part }; + } + return null; +} + +export const isFragmentQuote = (quote: string) => fragmentOf(quote) !== null; + +type TimedText = { start: number; end: number; text: string }; + +type Word = { raw: string; cue: number; norms: string[] }; + +// A cue's first word starts a new sentence when it is capitalised and is not +// the pronoun I (or a contraction of it). +const startsSentence = (raw: string) => /^["'“‘(]?[A-Z]/.test(raw) && !/^["'“‘(]?I(['’][a-z]+)?$/.test(raw); + +// The full sentence a quote (or one part of it) stops short of, from the cues +// overlapping ±windowSeconds of `second`; null when the quote is not found +// there verbatim, or no whole sentence fits the cap. +export function fullSentenceFor( + quote: string, + cues: readonly TimedText[], + second: number, + opts: { windowSeconds?: number; maxWords?: number } = {}, +): string | null { + const win = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS; + const window = cues.filter((c) => c.end > second - win && c.start < second + win); + const words: Word[] = []; + window.forEach((c, k) => { + for (const raw of c.text.split(/\s+/).filter(Boolean)) words.push({ raw, cue: k, norms: wordsOf(raw) }); + }); + const flat: { tok: string; w: number }[] = []; + words.forEach((w, i) => w.norms.forEach((tok) => flat.push({ tok, w: i }))); + const q = wordsOf(quote); + if (!q.length) return null; + // Every place the quote occurs; the one nearest the cited second wins. + let best: { from: number; to: number; dist: number } | null = null; + for (let i = 0; i + q.length <= flat.length; i++) { + let ok = true; + for (let k = 0; k < q.length && ok; k++) ok = flat[i + k]!.tok === q[k]; + if (!ok) continue; + const from = flat[i]!.w; + const to = flat[i + q.length - 1]!.w; + const dist = Math.abs(window[words[from]!.cue]!.start - second); + if (!best || dist < best.dist) best = { from, to, dist }; + } + if (!best) return null; + const cap = Math.max(opts.maxWords ?? FULL_SENTENCE_MAX_WORDS, q.length + 15); + const text = (a: number, b: number) => words.slice(a, b + 1).map((w) => w.raw).join(" "); + const span = (a: number, b: number) => wordsOf(text(a, b)).length; + const lastOfCue = (cue: number) => { + let j = -1; + words.forEach((w, i) => { + if (w.cue === cue) j = i; + }); + return j; + }; + + let start = best.from; + let end = -1; + // 1. Forward to sentence punctuation, or to a cue boundary before a new sentence. + for (let j = best.to; j < words.length && span(start, j) <= cap; j++) { + if (SENTENCE_END_RE.test(words[j]!.raw)) { + end = j; + break; + } + const next = words[j + 1]; + if (next && next.cue !== words[j]!.cue && startsSentence(next.raw)) { + end = j; + break; + } + } + // 2. Unpunctuated: the end of the quote's last cue, then one more cue. + if (end < 0) { + end = lastOfCue(words[best.to]!.cue); + if (fragmentOf(text(start, end)) && end + 1 < words.length) end = lastOfCue(words[end + 1]!.cue); + if (span(start, end) > cap) return null; + } + // 3. Still too short: back to the sentence's start (the previous sentence + // punctuation, else the start of the quote's first cue). + if (wordsOf(text(start, end)).length < FRAGMENT_MIN_WORDS) { + let i = start; + while (i > 0 && !SENTENCE_END_RE.test(words[i - 1]!.raw) && words[i - 1]!.cue === words[start]!.cue) i--; + while (i > 0 && !SENTENCE_END_RE.test(words[i - 1]!.raw) && span(i - 1, end) <= cap && !startsSentence(words[i]!.raw)) i--; + start = i; + } + const out = text(start, end); + return fragmentOf(out) ? null : out; +} + +// The words a check hands back for a fragment: what it is, and the sentence +// to quote instead when there is one — the repair hint. +export function fragmentHint(f: FragmentFinding, sentence: string | null): string { + return ( + `a fragment (${f.why}): "${f.part.slice(0, 120)}" — quote the whole sentence` + + (sentence ? `: "${sentence}"` : " or clause") + ); +} diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -3,7 +3,10 @@ import assert from "node:assert/strict"; import { DEFAULT_GENERATION_SETTINGS, GENERATION_PRESETS, + GENERATION_TASKS, + MEDIA_STEP_TASKS, capFor, + isStepTask, looksLikeApiKey, presetOf, sanitizeGeneration, @@ -74,3 +77,45 @@ test("research (S11): a route of its own, a file from before it keeps its preset assert.deepEqual(r, { autonomy: "auto", maxItemsPerRun: 3, maxGbPerRun: 5, maxTranscribeHours: 6, newChannelsNeedApproval: false, postWalksNeedApproval: true }); assert.equal(sanitizeGeneration({ research: { autonomy: "yolo" } }).research.autonomy, "propose"); }); + +test("the media drafts (release 28): steps, each with narrate's route in every preset; a file from before keeps its preset", () => { + assert.deepEqual([...MEDIA_STEP_TASKS], ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]); + for (const t of MEDIA_STEP_TASKS) { + assert.ok(isStepTask(t)); + assert.ok((GENERATION_TASKS as readonly string[]).includes(t)); + for (const p of Object.values(GENERATION_PRESETS)) assert.equal(p[t], p.narrate, `${t} routes as narrate`); + } + for (const t of ["sweep", "revise-report", "revise-video", "research", "nope", undefined]) assert.equal(isStepTask(t), false); + assert.equal(sanitizeGeneration(undefined).routes.cut, "local", "balanced drafts media on the local model"); + // routes written before the media tasks had any (release 27's five). + const five = (p: keyof typeof GENERATION_PRESETS) => + Object.fromEntries(["sweep", "revise-report", "revise-video", "narrate", "research"].map((t) => [t, GENERATION_PRESETS[p][t as "sweep"]])); + for (const p of ["code", "balanced", "api", "local"] as const) { + const old = sanitizeGeneration({ routes: five(p) }); + assert.equal(old.preset, p); + assert.deepEqual(old.routes, GENERATION_PRESETS[p]); + } + // A custom five keep their own routes; the media tasks take the default's. + const custom = sanitizeGeneration({ routes: { ...five("api"), narrate: "local" } }); + assert.equal(custom.preset, "custom"); + assert.equal(custom.routes.youtube, "local"); + // A partial patch names no preset. + assert.equal(sanitizeGeneration({ routes: { narrate: "api" } }).routes.cut, "local"); + // One media task routed on its own is custom. + assert.equal(sanitizeGeneration({ routes: { ...GENERATION_PRESETS.api, teaser: "local" } }).preset, "custom"); +}); + +test("cut (release 28 M1): the most entries a drafted cut keeps, 20 by default, a whole number from 3", () => { + assert.equal(sanitizeGeneration(undefined).cut.maxClips, 20); + assert.equal(sanitizeGeneration({ cut: { maxClips: 12 } }).cut.maxClips, 12); + for (const bad of [2, 12.5, -1, "12", null]) assert.equal(sanitizeGeneration({ cut: { maxClips: bad } }).cut.maxClips, 20, String(bad)); +}); + +test("generation settings: the verdict bench's bar (fractions, clamped) and the ticked models; none by default", () => { + assert.deepEqual(DEFAULT_GENERATION_SETTINGS.verdicts, { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] }); + assert.deepEqual(sanitizeGeneration({}).verdicts, DEFAULT_GENERATION_SETTINGS.verdicts); + const v = sanitizeGeneration({ + verdicts: { bar: { agreement: 0.756789, contradictedRecall: 1.5, notFoundRecall: "x" }, models: ["claude-sonnet-5-5", " qwen3:8b ", "bad model", 3, "claude-sonnet-5-5"] }, + }).verdicts; + assert.deepEqual(v, { bar: { agreement: 0.7568, contradictedRecall: 1, notFoundRecall: 0 }, models: ["claude-sonnet-5-5", "qwen3:8b"] }); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -10,17 +10,30 @@ import type { FieldDocs } from "./fieldDocs"; import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, type Autonomy } from "./report/draft/research/decide"; -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research"] as const; +// The media tasks (release 28): each drafts fields of a done iteration's video +// manifest, and runs as a STEP on that iteration (recorded in its `steps`, +// never an iteration of its own), as narrate did first. THE one list: the +// controller, the job, the MCP and umtool ask `isStepTask`. +export const MEDIA_STEP_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] as const; +export type MediaStepTask = (typeof MEDIA_STEP_TASKS)[number]; +export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "string" && (MEDIA_STEP_TASKS as readonly string[]).includes(t); + +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] 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"]; export const GENERATION_ROUTES = ["code", "api", "local"] as const; export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; +// The media tasks other than narrate take narrate's route in every preset. +const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }) as const; + export const GENERATION_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", ...mediaRoutes("code") }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local") }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api") }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("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[]; @@ -42,6 +55,15 @@ export type GenerationResearch = { postWalksNeedApproval: boolean; }; +// The cut task's limits (release 28 M1). +export type GenerationCut = { maxClips: number }; +// The verdict bench's bar and the models that cleared it (release 28 M7): +// the bar is the operator's, set on umtool's /bench after reading a run; +// `models` are the passing models the operator ticked — never set +// automatically. M8's verdict proposals run only on these. +export type GenerationVerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number }; +export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[] }; + export type GenerationSettings = { preset: GenerationPreset | "custom"; routes: GenerationRoutes; @@ -55,8 +77,12 @@ export type GenerationSettings = { web: GenerationWeb; citationOrigin: string; research: GenerationResearch; + cut: GenerationCut; + verdicts: GenerationVerdicts; }; +export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] }; + export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS }; export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env"; @@ -74,11 +100,13 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { web: { provider: "duckduckgo", searchUrl: "" }, citationOrigin: "", research: { ...DEFAULT_GENERATION_RESEARCH }, + cut: { maxClips: 20 }, + verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] }, }; 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 and narration 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), `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).", @@ -93,6 +121,25 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { citationOrigin: "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", research: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.", + cut: "The cut task's limits (below).", + verdicts: + "The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.", +}; + +export const GENERATION_VERDICTS_FIELD_DOCS: FieldDocs<GenerationVerdicts> = { + bar: "The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set.", + models: "The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals.", +}; + +export const GENERATION_VERDICT_BAR_FIELD_DOCS: FieldDocs<GenerationVerdictBar> = { + agreement: "The least share of claims on which the model's verdict must equal the operator's (strictly: PARTLY is not CORROBORATED).", + contradictedRecall: "The least share of the claims the operator ruled CONTRADICTED that the model must rule so.", + notFoundRecall: "The least share of the claims the operator ruled NOT_FOUND that the model must rule so.", +}; + +export const GENERATION_CUT_FIELD_DOCS: FieldDocs<GenerationCut> = { + maxClips: + "The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says).", }; export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { @@ -102,6 +149,12 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.", research: "A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP.", + cut: "A media draft (a step on a done iteration, as narration): the cut's clips and their order, chosen from the report's citations.", + onscreen: "A media draft: each clip's on-screen title and subtitle.", + teaser: "A media draft: the teaser's lines.", + flips: "A media draft: THEN/NOW pairs over the cut's clips.", + threads: "A media draft: the cut's threads and each clip's thread.", + youtube: "A media draft: the YouTube title and description.", }; export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { @@ -113,7 +166,7 @@ export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = { sweep: "A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap.", revision: "A report or video revision job's cap when it names none.", - narration: "A narration job's cap when it names none.", + narration: "A narration (or other media draft) job's cap when it names none.", daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.", max: "The most a job may ask for: a larger `maxUsd` is refused.", }; @@ -125,7 +178,7 @@ export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = { export const GENERATION_RESEARCH_FIELD_DOCS: FieldDocs<GenerationResearch> = { autonomy: - "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.", + "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.", maxItemsPerRun: "The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits.", maxGbPerRun: "The most GB one run may download without approval. An acquisition of unknown size waits.", maxTranscribeHours: "The most hours of transcription one run may queue without approval. One of unknown length waits.", @@ -161,11 +214,16 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { const v = rr[t]; routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t]; } - // A file from before research had a route (S11) keeps its preset: research - // takes the route of the preset the other tasks' routes are. - if (!(typeof rr.research === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr.research))) { - const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => t === "research" || routes[t] === GENERATION_PRESETS[p][t])); - if (was) routes.research = GENERATION_PRESETS[was].research; + // A file from before a task had a route (research, S11; the media tasks, + // release 28) keeps its preset: a task it does not name takes the route of + // the preset the tasks it names are routed by. + // (Only a file that routes release 27's first four names a preset this way; + // a partial patch is not one.) + const named = (t: GenerationTask) => typeof rr[t] === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr[t] as string); + const unnamed = GENERATION_TASKS.filter((t) => !named(t)); + if (unnamed.length && FIRST_TASKS.every(named)) { + const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => !named(t) || routes[t] === GENERATION_PRESETS[p][t])); + if (was) for (const t of unnamed) routes[t] = GENERATION_PRESETS[was][t]; } // The ROUTES are the truth; the preset names them (the preset whose routes // they are, else `custom`). Choosing a preset is writing its routes. @@ -200,6 +258,12 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { projectsRoot: str(r.projectsRoot, d.projectsRoot), web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) }, citationOrigin: url(r.citationOrigin, d.citationOrigin), + cut: { + maxClips: (() => { + const ct = r.cut && typeof r.cut === "object" && !Array.isArray(r.cut) ? (r.cut as Record<string, unknown>) : {}; + return typeof ct.maxClips === "number" && Number.isInteger(ct.maxClips) && ct.maxClips >= 3 && ct.maxClips <= 500 ? ct.maxClips : d.cut.maxClips; + })(), + }, research: { autonomy: (AUTONOMIES as readonly string[]).includes(String(rs.autonomy)) ? (rs.autonomy as Autonomy) : dr.autonomy, maxItemsPerRun: Math.floor(count(rs.maxItemsPerRun, dr.maxItemsPerRun, 10_000)), @@ -208,9 +272,20 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { newChannelsNeedApproval: typeof rs.newChannelsNeedApproval === "boolean" ? rs.newChannelsNeedApproval : dr.newChannelsNeedApproval, postWalksNeedApproval: typeof rs.postWalksNeedApproval === "boolean" ? rs.postWalksNeedApproval : dr.postWalksNeedApproval, }, + verdicts: sanitizeVerdicts(r.verdicts), }; } +function sanitizeVerdicts(v: unknown): GenerationVerdicts { + const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; + const b = o.bar && typeof o.bar === "object" && !Array.isArray(o.bar) ? (o.bar as Record<string, unknown>) : {}; + const frac = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? Math.min(1, Math.max(0, Math.round(x * 10_000) / 10_000)) : 0); + const models = Array.isArray(o.models) + ? [...new Set(o.models.filter((m): m is string => typeof m === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m.trim())).map((m) => m.trim()))] + : []; + return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models }; +} + export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" { return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom"; } diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -20,7 +20,7 @@ import { } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; import type { Meter } from "./meter"; -import { ollamaChat, OllamaError, PromptTooLargeError } from "./ollama"; +import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; const ASK = "Answer by calling the `answer` tool."; @@ -105,6 +105,19 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`); } +// What a local structuredAnswer's prompt is estimated at — the very request +// localAnswer sends (its messages and its format), counted as ollamaChat +// counts it against the cap (release 28 Q3: a caller fits its text first). +export function structuredPromptEstimate(o: { system: string; user: string; schema: object }): number { + return promptEstimate({ + messages: [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ], + format: o.schema, + }); +} + async function localAnswer<T>(o: Opts): Promise<T> { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; diff --git a/common/lib/report/convertManifest.ts b/common/lib/report/convertManifest.ts @@ -36,6 +36,9 @@ // them: relative to ITS directory (the CLI says so when the report is written // elsewhere). // +// The starter's timeline is marked drafted by code (`drafted.timeline`, +// `{task: "convert", model: "code"}`): the cut task may redraft its order. +// // A report → a STARTER manifest: no cold open — a title card, then per section // a chapter card, its body's citations in order, and per claim its source // sentence's still (an `image`) and its video and audio citations (`clip`s), @@ -65,6 +68,10 @@ import { isVerdict, type Verdict } from "./verdicts"; import { parseReport } from "./validate"; import { reportFullTitle } from "./views"; import type { Problem } from "../citations/validate"; +import { makeProvenance } from "./drafted.mjs"; + +// The provenance task of a timeline this converter made (`model: "code"`). +export const CONVERT_TASK = "convert"; type Obj = Record<string, unknown>; @@ -566,6 +573,9 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {}) timelineNodes: [], timeline, ...(posts.length ? { posts } : {}), + // The order is code's (release 28 M1): the cut task may redraft it, and it + // needs no review. An operator's reorder in umtool clears the mark. + drafted: { timeline: makeProvenance({ task: CONVERT_TASK, model: "code", at: opts.today ? `${opts.today}T00:00:00.000Z` : new Date(), attempt: 1 }) }, }; return { ok: true, manifest, warnings }; } diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts @@ -238,8 +238,12 @@ export function renderReportMarkdown(): string { "recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its " + "cited second is **`inexact`**: a warning, printed and counted, that does not change the " + "exit code; compose and publish do not use it. A GENERATED quote must pass that strict " + - "check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, " + - "`en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.", + "check: a finding whose quote fails it is dropped. A quote under four words, or one that " + + "stops on a function word (`as`, `to`, `the`, …), is a **`fragment`**: a warning too, with the " + + "full sentence to quote when the record has one; a GENERATED fragment fails, and the repair " + + "round is handed that sentence. `drift` and `en-orig-drift` come before `inexact`, and " + + "`inexact` before `fragment`. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, " + + "`fragment`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.", ); out.push(""); out.push("## Making a report from what exists"); diff --git a/common/lib/report/draft/authoringRules.ts b/common/lib/report/draft/authoringRules.ts @@ -32,7 +32,8 @@ export const NARRATION_TASTE = [ "No expressive tags or stage directions of any kind, nothing in angle brackets.", "No stock phrases or filler openers; start with the point.", "Every number and every name you use must already be in the evidence below; add no facts.", - "Do not read quotes out; the clips that follow say them. Do not put a speaker's words in your own mouth.", + "Do not read quotes out; the clips that follow say them.", + "The narrator is third person: never I, me, my, we, us or our, and never a speaker's words as your own.", "Keep every negation and hedge the evidence has; say what was said, not why.", ] as const; @@ -68,6 +69,12 @@ export const VERBATIM_QUOTES_RULE = "never fix a transcript's spelling, grammar or names inside quotes, never join words from two moments " + "into one quote. A quote that is not word for word what was said within 90 seconds of its link is refused."; +// A quote that stops mid-thought (release 28 Q2, lib/citations/fragment.ts) +// is refused in code; the refusal carries the sentence to quote. +export const WHOLE_SENTENCE_QUOTE_RULE = + "Quote a whole sentence or clause: a quote under four words, or one that stops on a function word (an " + + "article, a preposition, a conjunction, a possessive), is refused as a fragment."; + export const ONE_QUOTE_PER_FINDING_RULE = "Each finding is a list item under a `## section`: the claim in plain words, the quoted words in double " + "quotes, then the citation link. One quote, one link per item."; diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts @@ -0,0 +1,361 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { errorTurn, startFakeAnthropic, toolTurn } from "../../../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, reply, startFakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { cuesOf } from "../../../../testing/draft/corpus.mjs"; +import { VERDICTS, type Verdict } from "../../verdicts"; +import { + BASELINE_MODEL, + benchItemsOf, + benchPrompt, + benchReportsOf, + benchRootOf, + LOCAL_PROMPT_CAP, + passesBar, + planVerdictBench, + readBenchRun, + runVerdictBench, + scoreBench, + VERDICT_BENCH_SYSTEM, + type BenchItem, + type BenchResult, +} from "./index"; +import { promptEstimate } from "../../../llm/ollama"; + +const RULED = path.join(import.meta.dirname, "../../../../testing/draft/reports/ruled.report.json"); + +// The operator's rulings in the synthetic fact-check, by claim. +const TRUTH: Record<string, Verdict> = { + r01: "CORROBORATED", + r02: "PARTLY", + r03: "PARTLY", + r04: "CONTRADICTED", + r05: "CONTRADICTED", + r06: "CORROBORATED", + r07: "NOT_FOUND", +}; + +async function store(mutate?: (r: any) => void) { + const dir = await mkdtemp(path.join(os.tmpdir(), "bench-")); + const report = JSON.parse(await readFile(RULED, "utf8")); + mutate?.(report); + await mkdir(path.join(dir, "reports", report.id), { recursive: true }); + await writeFile(path.join(dir, "reports", report.id, "report.json"), JSON.stringify(report)); + // A sweep beside it: never an item. + await mkdir(path.join(dir, "reports", "a-sweep"), { recursive: true }); + await writeFile( + path.join(dir, "reports", "a-sweep", "report.json"), + JSON.stringify({ format: "archilyzer-report", version: 1, id: "a-sweep", kind: "sweep", title: "A sweep", sections: [] }), + ); + const paths = { + articlesDir: path.join(dir, "reports"), + exportIndexDir: path.join(dir, "export-index"), + generationUsageFile: path.join(dir, ".generation", "usage.jsonl"), + }; + return { dir, paths, done: () => rm(dir, { recursive: true, force: true }) }; +} + +const claimOf = (user: string) => /^Claim: (.*)$/m.exec(user)?.[1] ?? ""; + +// The synthetic claims' texts, to answer by. +async function claimTexts(): Promise<Record<string, string>> { + const report = JSON.parse(await readFile(RULED, "utf8")); + const out: Record<string, string> = {}; + for (const s of report.sections) for (const c of s.claims) out[c.text] = c.id; + return out; +} + +function userOf(body: any): string { + const m = body.messages?.[0]?.content; + return typeof m === "string" ? m : ""; +} + +test("items: the ruled claims with cues; a claim with no citation skipped, with its reason; the answer kept off the prompt", async () => { + const s = await store(); + try { + const reports = await benchReportsOf(s.paths); + assert.deepEqual(reports.map((r) => r.id), ["synth-ruled"]); + const { items, skipped } = await benchItemsOf(reports, { cuesOf, windowS: 60 }); + assert.deepEqual(items.map((i) => i.claim), ["r01", "r02", "r03", "r04", "r05", "r06", "r07"]); + assert.deepEqual(skipped, [{ key: "synth-ruled/r08", report: "synth-ruled", claim: "r08", reason: "no citation" }]); + for (const it of items) assert.equal(it.verdict, TRUTH[it.claim]); + const r04 = items.find((i) => i.claim === "r04")!; + assert.equal(r04.windows.length, 1); + const w = r04.windows[0]!; + assert.equal(w.from, 150); + assert.equal(w.to, 274.8); + assert.ok(w.cues.length > 0 && w.cues.every((c) => c.end >= 150 && c.start <= 274.8)); + // Nothing the check found is on an item, and the prompt never shows the verdict. + for (const it of items) { + assert.equal("findings" in it, false); + const p = benchPrompt(it); + assert.ok(p.user.includes(it.text)); + assert.ok(p.user.includes(it.quotes[0]!.quote)); + assert.ok(!p.user.includes(it.verdict), `${it.claim}'s prompt names its verdict`); + } + const findings = JSON.parse(await readFile(RULED, "utf8")).sections.flatMap((x: any) => x.claims).map((c: any) => c.findings); + for (const it of items) for (const f of findings) assert.ok(!benchPrompt(it).user.includes(f)); + } finally { + await s.done(); + } +}); + +test("items: a citation whose recording has no cues, and a post-only claim, are skipped; a named report must be a fact-check", async () => { + const s = await store((r) => { + r.citations.q07.id = "no-such-recording"; + r.citations.p1 = { kind: "post", channel: "synth-kitchen-posts", id: "p-1", quote: "a post" }; + r.sections[1].claims[1].citations = ["q07"]; + r.sections[1].claims.push({ id: "r09", text: "The article says she posted about it.", verdict: "CORROBORATED", citations: ["p1"] }); + }); + try { + const { items, skipped } = await benchItemsOf(await benchReportsOf(s.paths, ["synth-ruled"]), { cuesOf }); + assert.equal(items.length, 6); + assert.deepEqual( + skipped.map((x) => [x.claim, x.reason]), + [ + ["r07", "no cited recording has cues around the cited seconds"], + ["r08", "no citation"], + ["r09", "no video or audio citation"], + ], + ); + await assert.rejects(benchReportsOf(s.paths, ["a-sweep"]), /a sweep, not a factcheck/); + await assert.rejects(benchReportsOf(s.paths, ["nope"]), /no article "nope"/); + } finally { + await s.done(); + } +}); + +test("prompt: rules only (every verdict defined, no example); a local prompt's window trimmed to the cap, never the claim", async () => { + for (const v of VERDICTS) assert.ok(VERDICT_BENCH_SYSTEM.includes(`- ${v}:`), v); + assert.ok(!/example/i.test(VERDICT_BENCH_SYSTEM)); + // A claim with a very long window: thousands of cues. + const cues = Array.from({ length: 4000 }, (_, i) => ({ start: i * 5, end: i * 5 + 4.9, text: `line ${i} of a long stream about the bakery and the oven` })); + const item: BenchItem = { + key: "x/c1", + report: "x", + claim: "c1", + text: "The article says the oven was broken.", + verdict: "PARTLY", + quotes: [{ citation: "q", channel: "c", id: "v", start: 10000, end: 10004.9, quote: "the oven was fine" }], + windows: [{ channel: "c", id: "v", from: 0, to: 20000, cited: [{ start: 10000, end: 10004.9 }], cues }], + }; + const whole = benchPrompt(item); + assert.equal(whole.cuesTrimmed, 0); + assert.ok(whole.estimate > 8000); + const local = benchPrompt(item, { capTokens: LOCAL_PROMPT_CAP }); + assert.ok(local.cuesTrimmed > 0); + assert.ok(local.estimate <= LOCAL_PROMPT_CAP && LOCAL_PROMPT_CAP < 8000); + assert.equal(local.estimate, promptEstimate({ messages: [{ role: "system", content: local.system }, { role: "user", content: local.user }], format: (await import("./prompt")).VERDICT_ANSWER_SCHEMA })); + assert.ok(local.user.includes("Claim: The article says the oven was broken.")); + assert.ok(local.user.includes('"the oven was fine"')); + // The cues nearest the cited span stay; the farthest go. + assert.ok(local.user.includes("line 2000 of")); + assert.ok(!local.user.includes("line 0 of")); + assert.ok(!local.user.includes("line 3999 of")); +}); + +test("score: agreement, the matrix, the recalls (PARTLY strict and adjacent), failures, and the always-CORROBORATED baseline", () => { + const items = Object.entries(TRUTH).map(([claim, verdict]) => ({ key: `r/${claim}`, verdict })); + const said: Record<string, Verdict | "parse" | "error"> = { + r01: "CORROBORATED", + r02: "CORROBORATED", // adjacent + r03: "PARTLY", + r04: "CONTRADICTED", + r05: "PARTLY", + r06: "parse", + r07: "NOT_FOUND", + }; + const results: BenchResult[] = Object.entries(said).map(([claim, v]) => ({ + key: `r/${claim}`, + model: "m", + verdict: v === "parse" || v === "error" ? null : v, + ...(v === "parse" ? { failure: "parse" as const } : {}), + ms: 100, + usd: 0.01, + inputTokens: 10, + outputTokens: 5, + at: "", + })); + const s = scoreBench(items, results, ["m"]); + const m = s.models[0]!; + assert.equal(s.items, 7); + assert.deepEqual(s.ruled, { CORROBORATED: 2, PARTLY: 2, CONTRADICTED: 2, NOT_FOUND: 1, UNTESTABLE: 0 }); + assert.equal(m.asked, 7); + assert.equal(m.answered, 6); + assert.equal(m.parseFailures, 1); + assert.equal(m.agreed, 4); // r01 r03 r04 r07 + assert.equal(m.agreement, 0.5714); + assert.equal(m.agreedAdjacent, 5); // + r02 + const C = VERDICTS.indexOf("CORROBORATED"); + const P = VERDICTS.indexOf("PARTLY"); + const X = VERDICTS.indexOf("CONTRADICTED"); + assert.equal(m.matrix[P]![C], 1); + assert.equal(m.matrix[X]![P], 1); + assert.equal(m.unanswered[C], 1); + assert.deepEqual(m.recall.CONTRADICTED, { ruled: 2, matched: 1, recall: 0.5 }); + assert.deepEqual(m.recall.NOT_FOUND, { ruled: 1, matched: 1, recall: 1 }); + assert.deepEqual(m.recall.PARTLY, { ruled: 2, matched: 1, recall: 0.5 }); + assert.deepEqual(m.recall.PARTLY_ADJACENT, { ruled: 2, matched: 2, recall: 1 }); + assert.equal(m.usd, 0.07); + assert.equal(m.latency.medianMs, 100); + // The baseline: right on every CORROBORATED, finds no CONTRADICTED or NOT_FOUND. + assert.equal(s.baseline.model, BASELINE_MODEL); + assert.equal(s.baseline.agreement, 0.2857); + assert.equal(s.baseline.agreementAdjacent, 0.5714); + assert.equal(s.baseline.recall.CONTRADICTED.recall, 0); + assert.equal(s.baseline.recall.NOT_FOUND.recall, 0); + // The bar. + assert.deepEqual(passesBar(m, { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }), { pass: true, misses: [] }); + const fail = passesBar(m, { agreement: 0.6, contradictedRecall: 0.75, notFoundRecall: 0 }); + assert.equal(fail.pass, false); + assert.equal(fail.misses.length, 2); + assert.equal(passesBar(s.baseline, { agreement: 0, contradictedRecall: 0.1, notFoundRecall: 0 }).pass, false); +}); + +test("run: Sonnet over the fake API, qwen over the fake ollama — answers written as they land, scored, costed; a parse failure counted", async () => { + const s = await store(); + const texts = await claimTexts(); + const api = await startFakeAnthropic(); + const ol = await startFakeOllama(); + // Sonnet: right on everything but r05 (PARTLY). + for (let i = 0; i < 7; i++) { + api.push((body: any) => { + const id = texts[claimOf(userOf(body))]!; + return toolTurn("answer", { verdict: id === "r05" ? "PARTLY" : TRUTH[id], reason: `ruled on ${id} ${"x".repeat(400)}` }); + }); + } + // qwen: always CORROBORATED, and r03's answer is not JSON (twice: the retry too). + for (let i = 0; i < 8; i++) { + ol.push((body: any) => { + const id = texts[claimOf(body.messages[1].content)]!; + return id === "r03" ? reply("I think it is partly true") : jsonReply({ verdict: "CORROBORATED", reason: "she says so" }); + }); + } + try { + const lines: string[] = []; + const out = await runVerdictBench( + { runId: "vb-test", models: ["claude-sonnet-5-5", "qwen3:8b"] }, + { + paths: s.paths, + cuesOf, + llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } }, + log: (l) => lines.push(l), + }, + ); + assert.equal(out.summary.status, "done"); + assert.equal(out.dir, path.join(benchRootOf(s.paths), "vb-test")); + assert.equal(api.requests.length, 7); + // The strict model's way: the answer tool, tool_choice auto, no temperature. + assert.equal(api.requests[0].tool_choice.type, "auto"); + assert.equal(api.requests[0].tools[0].name, "answer"); + // The findings never reach a model. + for (const r of [...api.requests.map((b: any) => JSON.stringify(b)), ...ol.requests.map((b: any) => JSON.stringify(b))]) { + assert.ok(!r.includes("She calls it a small place")); + } + const sonnet = out.summary.score.models[0]!; + assert.equal(sonnet.model, "claude-sonnet-5-5"); + assert.equal(sonnet.agreed, 6); + assert.ok(sonnet.usd > 0); + assert.ok(Math.abs(out.summary.spentUsd - sonnet.usd) < 1e-5); + const qwen = out.summary.score.models[1]!; + assert.equal(qwen.parseFailures, 1); + assert.equal(qwen.agreed, 2); + assert.equal(qwen.usd, 0); + // On disk: the items (answer key included), every result, the summary. + const run = (await readBenchRun(benchRootOf(s.paths), "vb-test"))!; + assert.equal(run.items.length, 7); + assert.equal(run.results.length, 14); + assert.ok(run.results.every((r) => (r.reason ?? "").length <= 300)); + assert.equal(run.summary.skipped.length, 1); + assert.equal(run.summary.score.baseline.agreed, 2); + assert.ok(lines.some((l) => l.startsWith("run vb-test: 7 items"))); + } finally { + await api.close(); + await ol.close(); + await s.done(); + } +}); + +test("run: the cap is checked before each API call — past it the run stops capped, with what it did", async () => { + const s = await store(); + const api = await startFakeAnthropic(); + for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" })); + try { + // One call costs about a cent at Opus 5.5's price; a two-cent cap stops early. + const out = await runVerdictBench( + { runId: "vb-cap", models: ["claude-opus-5-5"], maxUsd: 0.02 }, + { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } }, + ); + assert.equal(out.summary.status, "capped"); + assert.ok(api.requests.length >= 1 && api.requests.length < 7, `${api.requests.length} calls`); + assert.ok(out.summary.spentUsd <= 0.02); + assert.match(out.summary.stopped![0]!, /the cap/); + assert.equal(out.summary.score.models[0]!.asked, api.requests.length); + // A cap smaller than one call: nothing is sent at all. + const none = await runVerdictBench( + { runId: "vb-cap-0", models: ["claude-opus-5-5"], maxUsd: 0.0001 }, + { paths: s.paths, cuesOf, llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } } }, + ); + assert.equal(none.summary.status, "capped"); + assert.equal(none.summary.score.models[0]!.asked, 0); + } finally { + await api.close(); + await s.done(); + } +}); + +test("run: a re-run with the same id resumes — answered pairs skipped, failed ones asked again; three errors in a row stop a model", async () => { + const s = await store(); + const texts = await claimTexts(); + const api = await startFakeAnthropic(); + const llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; + // First run: r01–r03 answered, then three 400s in a row (not retried) stop the model. + for (let i = 0; i < 3; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" })); + for (let i = 0; i < 3; i++) api.push(errorTurn(400, "invalid_request_error", "a bad request")); + try { + const first = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); + assert.equal(first.summary.status, "done"); + assert.equal(api.requests.length, 6); + assert.match(first.summary.stopped![0]!, /stopped after 3 errors in a row/); + assert.equal(first.summary.score.models[0]!.errors, 3); + assert.equal(first.summary.score.models[0]!.asked, 6); + // The re-run asks only the four not answered (three failed, one never asked). + for (let i = 0; i < 4; i++) api.push((body: any) => toolTurn("answer", { verdict: TRUTH[texts[claimOf(userOf(body))]!], reason: "ok" })); + const again = await runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"] }, { paths: s.paths, cuesOf, llm }); + assert.equal(api.requests.length, 10); + const asked = api.requests.slice(6).map((b: any) => texts[claimOf(userOf(b))]); + assert.deepEqual(asked, ["r04", "r05", "r06", "r07"]); + assert.equal(again.summary.status, "done"); + assert.equal(again.summary.score.models[0]!.agreed, 7); + assert.equal(again.summary.score.models[0]!.errors, 0); + assert.equal((await readBenchRun(benchRootOf(s.paths), "vb-resume"))!.results.length, 7); + // The window is the run's: another one is refused. + await assert.rejects(runVerdictBench({ runId: "vb-resume", models: ["claude-sonnet-5-5"], windowS: 30 }, { paths: s.paths, cuesOf, llm }), /60 s window/); + } finally { + await api.close(); + await s.done(); + } +}); + +test("plan (the dry run): the items, the skipped, an estimate per model; nothing asked, nothing written", async () => { + const s = await store(); + try { + const plan = await planVerdictBench({ models: ["claude-sonnet-5-5", "claude-opus-5-5", "qwen3:8b"], limit: 5 }, { paths: s.paths, cuesOf }); + assert.equal(plan.items.length, 5); + assert.equal(plan.skipped.length, 1); + assert.deepEqual(plan.reports, ["synth-ruled"]); + const [sonnet, opus, qwen] = plan.estimate; + assert.ok(sonnet!.usd > 0 && opus!.usd > sonnet!.usd); + assert.equal(qwen!.usd, 0); + assert.equal(qwen!.provider, "local"); + assert.equal(plan.estimateUsd, Math.round((sonnet!.usd + opus!.usd) * 10_000) / 10_000); + await assert.rejects(readFile(path.join(benchRootOf(s.paths), "x")), /ENOENT/); + await assert.rejects(planVerdictBench({ models: [] }, { paths: s.paths, cuesOf }), /at least one model/); + await assert.rejects(planVerdictBench({ models: ["m"], maxUsd: 500 }, { paths: s.paths, cuesOf }), /over the bench's limit/); + } finally { + await s.done(); + } +}); diff --git a/common/lib/report/draft/bench/index.ts b/common/lib/report/draft/bench/index.ts @@ -0,0 +1,8 @@ +// The verdict bench (release 28, M7): items from ruled fact-checks, one claim +// per call, scored against the operator's rulings. See ./run.ts. + +export * from "./items"; +export * from "./prompt"; +export * from "./score"; +export * from "./store"; +export * from "./run"; diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts @@ -0,0 +1,209 @@ +// THE VERDICT BENCH'S ITEMS (release 28, M7): one per ruled fact-check claim. +// +// An item is a claim of a `kind: "factcheck"` article that carries the +// operator's `verdict` and at least one span citation (video or audio) whose +// recording has cues around the cited seconds: the claim's text, the cited +// quotes, and the transcript WINDOW (the cues within ±`windowS` of each cited +// span, overlapping windows of one recording merged). Every other claim is +// SKIPPED, with its reason, and counted. +// +// The operator's `verdict` is the answer key: it is kept on the item for the +// scorer, and the prompt (./prompt.ts) never reads it. The claim's `findings`, +// `gist`, `flag` and `title` are never copied onto an item at all — they say +// what the check found. +// +// The reports are read through the article registry (`listArticleDirs`, +// `articleFile`, `parseReport`), never by globbing the corpus; the cues through +// a `CuesOf` (the local corpus's `diskCuesOf`, or the synthetic corpus in tests). + +import { readJsonFile } from "../../../jsonFile-server"; +import type { Paths } from "../../../paths"; +import { isSpanCitation, type Citation } from "../../../citations/schema"; +import type { CuesOf } from "../../convertShared"; +import { articleFile, listArticleDirs } from "../../registry"; +import type { Report } from "../../schema"; +import { parseReport } from "../../validate"; +import { isVerdict, type Verdict } from "../../verdicts"; + +export const DEFAULT_WINDOW_S = 60; + +export type BenchCue = { start: number; end: number; text: string }; + +export type BenchQuote = { + citation: string; + channel: string; + id: string; + start: number; + end: number; + quote: string; + label?: string; + speaker?: string; + date?: string; +}; + +// One recording's cues around the cited spans in it. +export type BenchWindow = { + channel: string; + id: string; + label?: string; + from: number; + to: number; + // The cited spans in this window (for the trim: the cues nearest them stay). + cited: { start: number; end: number }[]; + cues: BenchCue[]; +}; + +export type BenchItem = { + // `<report>/<claim>`: unique across a run. + key: string; + report: string; + claim: string; + text: string; + // THE ANSWER: the operator's ruling. Never shown to a model. + verdict: Verdict; + quotes: BenchQuote[]; + windows: BenchWindow[]; +}; + +export type BenchSkipped = { key: string; report: string; claim: string; reason: string }; + +export type BenchReport = { id: string; report: Report }; + +export type BenchItems = { items: BenchItem[]; skipped: BenchSkipped[] }; + +export class BenchInputError extends Error {} + +// The fact-checks the bench reads: every article of kind `factcheck` (or the +// named ones, each of which must be one), in id order. +export async function benchReportsOf( + paths: Pick<Paths, "articlesDir" | "exportIndexDir">, + ids?: readonly string[], +): Promise<BenchReport[]> { + const all = await listArticleDirs(paths); + const wanted = ids && ids.length ? [...new Set(ids)] : null; + if (wanted) { + const missing = wanted.filter((id) => !all.includes(id)); + if (missing.length) throw new BenchInputError(`no article ${missing.map((m) => `"${m}"`).join(", ")} in the registry`); + } + const out: BenchReport[] = []; + for (const id of wanted ?? all) { + const read = await readJsonFile(articleFile(paths, id)); + if (!read.ok) { + if (wanted) throw new BenchInputError(`article "${id}": report.json is ${read.reason}`); + continue; + } + const parsed = parseReport(read.value, { id }); + if (!parsed.ok) { + if (wanted) throw new BenchInputError(`article "${id}": report.json does not parse as a report`); + continue; + } + if (parsed.value.kind !== "factcheck") { + if (wanted) throw new BenchInputError(`article "${id}" is a ${parsed.value.kind}, not a factcheck`); + continue; + } + out.push({ id, report: parsed.value }); + } + return out; +} + +function mergeWindows(windows: BenchWindow[]): BenchWindow[] { + const byRecord = new Map<string, BenchWindow[]>(); + for (const w of windows) { + const k = `${w.channel}/${w.id}`; + byRecord.set(k, [...(byRecord.get(k) ?? []), w]); + } + const out: BenchWindow[] = []; + for (const list of byRecord.values()) { + list.sort((a, b) => a.from - b.from); + let cur: BenchWindow | null = null; + for (const w of list) { + if (cur && w.from <= cur.to) { + cur.to = Math.max(cur.to, w.to); + cur.cited.push(...w.cited); + const seen = new Set(cur.cues.map((c) => `${c.start}`)); + for (const c of w.cues) if (!seen.has(`${c.start}`)) cur.cues.push(c); + cur.cues.sort((a, b) => a.start - b.start); + } else { + if (cur) out.push(cur); + cur = { ...w, cited: [...w.cited], cues: [...w.cues] }; + } + } + if (cur) out.push(cur); + } + return out; +} + +// The items of one report: its ruled claims with a span citation that has cues. +export async function benchItemsOfReport( + r: BenchReport, + o: { cuesOf: CuesOf; windowS?: number }, +): Promise<BenchItems> { + const windowS = o.windowS ?? DEFAULT_WINDOW_S; + const items: BenchItem[] = []; + const skipped: BenchSkipped[] = []; + const citations = (r.report.citations ?? {}) as Record<string, Citation>; + for (const section of r.report.sections) { + for (const claim of section.claims ?? []) { + const key = `${r.id}/${claim.id}`; + const skip = (reason: string) => skipped.push({ key, report: r.id, claim: claim.id, reason }); + if (!isVerdict(claim.verdict)) { + skip("no operator verdict"); + continue; + } + const ids = claim.citations ?? []; + if (!ids.length) { + skip("no citation"); + continue; + } + const spans = ids.map((id) => [id, citations[id]] as const).filter((e): e is readonly [string, Citation] => !!e[1] && isSpanCitation(e[1])); + if (!spans.length) { + skip("no video or audio citation"); + continue; + } + const quotes: BenchQuote[] = []; + const windows: BenchWindow[] = []; + for (const [cid, c] of spans) { + if (!isSpanCitation(c)) continue; + const cues = await o.cuesOf(c.channel, c.id).catch(() => null); + if (!cues || !cues.length) continue; + const from = Math.max(0, c.start - windowS); + const to = c.end + windowS; + const inWindow = cues.filter((q) => q.end >= from && q.start <= to).map((q) => ({ start: q.start, end: q.end, text: q.text })); + if (!inWindow.length) continue; + quotes.push({ + citation: cid, + channel: c.channel, + id: c.id, + start: c.start, + end: c.end, + quote: c.quote, + ...(c.label ? { label: c.label } : {}), + ...(c.speaker ? { speaker: c.speaker } : {}), + ...(c.date ? { date: c.date } : {}), + }); + windows.push({ channel: c.channel, id: c.id, ...(c.label ? { label: c.label } : {}), from, to, cited: [{ start: c.start, end: c.end }], cues: inWindow }); + } + if (!quotes.length) { + skip("no cited recording has cues around the cited seconds"); + continue; + } + items.push({ key, report: r.id, claim: claim.id, text: claim.text, verdict: claim.verdict, quotes, windows: mergeWindows(windows) }); + } + } + return { items, skipped }; +} + +// Every item of every report, in report then claim order; `limit` keeps the first n. +export async function benchItemsOf( + reports: readonly BenchReport[], + o: { cuesOf: CuesOf; windowS?: number; limit?: number }, +): Promise<BenchItems> { + const items: BenchItem[] = []; + const skipped: BenchSkipped[] = []; + for (const r of reports) { + const got = await benchItemsOfReport(r, o); + items.push(...got.items); + skipped.push(...got.skipped); + } + return { items: o.limit !== undefined && o.limit >= 0 ? items.slice(0, o.limit) : items, skipped }; +} diff --git a/common/lib/report/draft/bench/prompt.ts b/common/lib/report/draft/bench/prompt.ts @@ -0,0 +1,122 @@ +// THE VERDICT BENCH'S PROMPT (release 28, M7): one claim per call. +// +// Q0: the system prompt is rules only — what each verdict means, and that the +// model judges only what the window shows — with no worked example. The reason's +// length is enforced in code (./run.ts cuts it at REASON_MAX), not trusted to +// the prompt. A local model's prompt is held under its cap (8k tokens) by +// trimming the WINDOW, the cues farthest from a cited span first; the claim +// and the cited quotes are never trimmed. +// +// The prompt reads an item's claim text, its quotes and its windows — never +// its `verdict` (the operator's ruling, the answer). + +import { VERDICTS } from "../../verdicts"; +import { PROMPT_CAP_TOKENS, promptEstimate } from "../../../llm/ollama"; +import type { BenchItem, BenchWindow } from "./items"; + +export const REASON_MAX = 300; + +export const VERDICT_ANSWER_SCHEMA = { + type: "object", + properties: { + verdict: { type: "string", enum: [...VERDICTS], description: "The ruling on the claim." }, + reason: { + type: "string", + description: `Why, in one or two plain sentences of at most ${REASON_MAX} characters, naming what the transcript shows.`, + }, + }, + required: ["verdict", "reason"], +} as const; + +export const VERDICT_BENCH_SYSTEM = [ + "You rule on one claim about what a person said in recordings, using only the transcript you are given.", + "", + "You are shown the claim, the lines it cites, and the transcript around each cited line (each line stamped with its time in the recording).", + "", + "Rules:", + "- Judge only from the transcript shown. Do not use outside knowledge, and do not assume what may have been said elsewhere or off the record.", + "- The cited lines are where the claim's evidence was found; read the transcript around them before ruling, since context can change their meaning.", + "- The transcript is automatic speech recognition: forgive misspellings and missing punctuation, never a change of meaning.", + "", + "The verdicts:", + "- CORROBORATED: the transcript shows the claim is true as stated.", + "- PARTLY: the transcript supports part of the claim, and another part is unsupported, overstated or wrong.", + "- CONTRADICTED: the transcript shows the opposite of the claim, or something that cannot be true at the same time as it.", + "- NOT_FOUND: the claim could be checked against what was said, and the transcript shown does not contain it — the topic may come up without what the claim says about it.", + "- UNTESTABLE: the claim is an opinion, a judgement, a prediction, or anything else a transcript cannot show to be true or false.", + "", + `Give the verdict and a reason of at most ${REASON_MAX} characters that names what the transcript says.`, +].join("\n"); + +const stamp = (s: number) => { + const t = Math.max(0, Math.floor(s)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; + +type Prompted = Pick<BenchItem, "text" | "quotes" | "windows">; + +function render(item: Prompted, windows: BenchWindow[]): string { + const lines: string[] = [`Claim: ${item.text}`, "", "Cited lines:"]; + for (const q of item.quotes) { + const where = [q.label, stamp(q.start)].filter(Boolean).join(", "); + const who = [q.speaker ? `speaker: ${q.speaker}` : "", q.date ? `date: ${q.date}` : ""].filter(Boolean).join("; "); + lines.push(`- [${where}] "${q.quote}"${who ? ` (${who})` : ""}`); + } + lines.push("", "Transcript:"); + windows.forEach((w, i) => { + lines.push("", `## ${w.label ?? `Recording ${i + 1}`}, ${stamp(w.from)} to ${stamp(w.to)}`); + if (!w.cues.length) lines.push("(trimmed to fit)"); + for (const c of w.cues) lines.push(`[${stamp(c.start)}] ${c.text}`); + }); + return lines.join("\n"); +} + +// The distance of a cue from the nearest cited span of its window, in seconds. +function distance(w: BenchWindow, c: { start: number; end: number }): number { + let best = Number.POSITIVE_INFINITY; + for (const s of w.cited) { + const d = c.end < s.start ? s.start - c.end : c.start > s.end ? c.start - s.end : 0; + best = Math.min(best, d); + } + return best; +} + +export type BenchPrompt = { system: string; user: string; estimate: number; cuesShown: number; cuesTrimmed: number }; + +// The prompt for one item. With `capTokens` (a local model), the window is +// trimmed until system + user + the schema fit under it; without, it is whole. +export function benchPrompt(item: Prompted, o: { capTokens?: number } = {}): BenchPrompt { + const total = item.windows.reduce((s, w) => s + w.cues.length, 0); + const estimateOf = (user: string) => + promptEstimate({ messages: [{ role: "system", content: VERDICT_BENCH_SYSTEM }, { role: "user", content: user }], format: VERDICT_ANSWER_SCHEMA }); + const whole = render(item, item.windows); + const cap = o.capTokens; + if (cap === undefined || estimateOf(whole) <= cap) { + return { system: VERDICT_BENCH_SYSTEM, user: whole, estimate: estimateOf(whole), cuesShown: total, cuesTrimmed: 0 }; + } + // Every cue, farthest from a cited span first: dropping the first k of them + // is the k-trim. The fewest drops that fit, found by bisection. + const order: { w: number; c: number; d: number }[] = []; + item.windows.forEach((w, wi) => w.cues.forEach((c, ci) => order.push({ w: wi, c: ci, d: distance(w, c) }))); + order.sort((a, b) => b.d - a.d || a.w - b.w || b.c - a.c); + const keepAfter = (k: number): BenchWindow[] => { + const drop = new Set(order.slice(0, k).map((e) => `${e.w}:${e.c}`)); + return item.windows.map((w, wi) => ({ ...w, cues: w.cues.filter((_, ci) => !drop.has(`${wi}:${ci}`)) })); + }; + let lo = 0; + let hi = order.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (estimateOf(render(item, keepAfter(mid))) <= cap) hi = mid; + else lo = mid + 1; + } + const user = render(item, keepAfter(lo)); + return { system: VERDICT_BENCH_SYSTEM, user, estimate: estimateOf(user), cuesShown: total - lo, cuesTrimmed: lo }; +} + +// The cap a local prompt is held to: the ollama client's (8k), less a margin +// for the estimate's slack. +export const LOCAL_PROMPT_CAP = PROMPT_CAP_TOKENS - 200; diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts @@ -0,0 +1,334 @@ +// THE VERDICT BENCH (release 28, M7): can a model propose a fact-check verdict +// well enough to be worth an operator's review? +// +// `planVerdictBench` reads only: the items, the skipped claims, and an +// estimate of what each model would cost (the `--dry`). `runVerdictBench` +// asks each model about each item, one claim per call — `structuredAnswer` +// against {verdict, reason} — writes every answer as it lands, and scores the +// run (./score.ts). The calls are SEQUENTIAL (API and local alike; a local +// model's GPU turn is the caller's `llm` config — the editor's job passes the +// GPU arbiter's gated fetch). +// +// THE CAP: `maxUsd` (default 5) for the whole run, resumed spend included, +// checked before each API call against the spend so far plus that call's +// estimate — past it the run stops `capped` with what it did. A model with +// three errors in a row is stopped (the rest of its items stay unasked) and +// the run goes on with the next. +// +// RESUME: a run id whose directory exists continues it — its items are the +// stored ones, and each (item, model) pair already ANSWERED is skipped; a +// failed one is asked again. + +import { mkdir } from "node:fs/promises"; +import type { Paths } from "../../../paths"; +import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, type LlmConfig } from "../../../llm"; +import { ApiKeyError } from "../../../llm/anthropic"; +import { CHARS_PER_TOKEN } from "../../../llm/ollama"; +import type { CuesOf } from "../../convertShared"; +import { isVerdict } from "../../verdicts"; +import { benchItemsOf, benchReportsOf, BenchInputError, DEFAULT_WINDOW_S, type BenchItem, type BenchSkipped } from "./items"; +import { benchPrompt, LOCAL_PROMPT_CAP, REASON_MAX, VERDICT_ANSWER_SCHEMA } from "./prompt"; +import { scoreBench, type BenchResult } from "./score"; +import { + BENCH_FORMAT, + BENCH_VERSION, + benchRootOf, + benchRunDir, + newBenchRunId, + readBenchRun, + writeBenchItems, + writeBenchResults, + writeBenchSummary, + type BenchStatus, + type BenchSummary, +} from "./store"; + +export const DEFAULT_BENCH_MAX_USD = 5; +// Above this a run is refused outright (the release's real run is ≤ $5). +export const BENCH_MAX_USD_LIMIT = 50; +// A model stopped after this many errors in a row. +export const BENCH_ERROR_STREAK = 3; +// The estimate's allowances per call: the tool definition and instruction +// around the prompt, and the answer (with a strict model's possible re-ask). +const CALL_OVERHEAD_TOKENS = 350; +const ANSWER_TOKENS = 300; +const MAX_ANSWER_TOKENS = 1024; + +export type BenchOptions = { + // A run to continue, or the new run's id (default `vb-<stamp>`). + runId?: string; + // The fact-checks to read (default: every one in the registry). + reports?: string[]; + models: string[]; + windowS?: number; + maxUsd?: number; + limit?: number; +}; + +export type BenchDeps = { + paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "generationUsageFile">; + // Where runs live (default `.generation/bench/verdicts/`, ./store.ts). + root?: string; + cuesOf: CuesOf; + // The providers' config (the editor's job gates a local model's calls on the GPU). + llm: LlmConfig; + log?: (line: string) => void; + signal?: AbortSignal; + now?: () => Date; + // A local prompt's cap in tokens (default LOCAL_PROMPT_CAP, under the 8k). + localCapTokens?: number; +}; + +export type BenchModelEstimate = { model: string; provider: "api" | "local"; calls: number; inputTokens: number; outputTokens: number; usd: number }; + +export type BenchPlan = { + items: BenchItem[]; + skipped: BenchSkipped[]; + reports: string[]; + windowS: number; + estimate: BenchModelEstimate[]; + estimateUsd: number; +}; + +export function validateBenchOptions(o: BenchOptions): { models: string[]; windowS: number; maxUsd: number; limit?: number } { + const models = [...new Set((o.models ?? []).map((m) => m.trim()).filter(Boolean))]; + if (!models.length) throw new BenchInputError("name at least one model (--models a,b,c)"); + for (const m of models) { + if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m)) throw new BenchInputError(`"${m}" is not a model name`); + } + const windowS = o.windowS ?? DEFAULT_WINDOW_S; + if (!Number.isFinite(windowS) || windowS < 0 || windowS > 600) throw new BenchInputError("the window is 0 to 600 seconds"); + const maxUsd = o.maxUsd ?? DEFAULT_BENCH_MAX_USD; + if (!Number.isFinite(maxUsd) || maxUsd <= 0) throw new BenchInputError("maxUsd must be a positive number of dollars"); + if (maxUsd > BENCH_MAX_USD_LIMIT) throw new BenchInputError(`maxUsd $${maxUsd} is over the bench's limit of $${BENCH_MAX_USD_LIMIT}`); + if (o.limit !== undefined && (!Number.isInteger(o.limit) || o.limit < 1)) throw new BenchInputError("limit is a whole number of items, at least 1"); + return { models, windowS, maxUsd, ...(o.limit !== undefined ? { limit: o.limit } : {}) }; +} + +// What one call to `model` about `item` would cost, by the prompt's size. +export function estimateCall(item: BenchItem, model: string, localCapTokens = LOCAL_PROMPT_CAP): { inputTokens: number; outputTokens: number; usd: number } { + const local = providerOf(model) === "local"; + const p = benchPrompt(item, local ? { capTokens: localCapTokens } : {}); + const inputTokens = Math.ceil((p.system.length + p.user.length + JSON.stringify(VERDICT_ANSWER_SCHEMA).length) / CHARS_PER_TOKEN) + CALL_OVERHEAD_TOKENS; + const outputTokens = ANSWER_TOKENS; + const price = priceOf(model); + return { inputTokens, outputTokens, usd: (inputTokens * price.input + outputTokens * price.output) / 1e6 }; +} + +function estimateOf(items: readonly BenchItem[], models: readonly string[], localCapTokens?: number): BenchModelEstimate[] { + return models.map((model) => { + let inputTokens = 0; + let outputTokens = 0; + let usd = 0; + for (const it of items) { + const e = estimateCall(it, model, localCapTokens); + inputTokens += e.inputTokens; + outputTokens += e.outputTokens; + usd += e.usd; + } + return { model, provider: providerOf(model), calls: items.length, inputTokens, outputTokens, usd: Math.round(usd * 10_000) / 10_000 }; + }); +} + +// The dry run: the items, the skipped claims and the estimate. Reads only. +export async function planVerdictBench(o: BenchOptions, deps: Pick<BenchDeps, "paths" | "cuesOf" | "localCapTokens">): Promise<BenchPlan> { + const v = validateBenchOptions(o); + const reports = await benchReportsOf(deps.paths, o.reports); + const { items, skipped } = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) }); + const estimate = estimateOf(items, v.models, deps.localCapTokens); + return { + items, + skipped, + reports: reports.map((r) => r.id), + windowS: v.windowS, + estimate, + estimateUsd: Math.round(estimate.reduce((s, e) => s + e.usd, 0) * 10_000) / 10_000, + }; +} + +// `spent`: this invocation's spend per model (a resumed run's earlier spend is +// in `summary.spentUsd`, not here) — what a job's usage ledger rows record. +export type BenchOutcome = { id: string; dir: string; summary: BenchSummary; spent: ReturnType<Meter["summary"]> }; + +const round6 = (v: number) => Math.round(v * 1e6) / 1e6; + +export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise<BenchOutcome> { + const v = validateBenchOptions(o); + const now = () => (deps.now ? deps.now() : new Date()); + const log = deps.log ?? (() => {}); + const root = deps.root ?? benchRootOf(deps.paths); + const id = o.runId ?? newBenchRunId(now()); + const dir = benchRunDir(root, id); + const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP; + + // A new run, or the stored one continued. + const prior = await readBenchRun(root, id); + let items: BenchItem[]; + let skipped: BenchSkipped[]; + let results: BenchResult[]; + let models: string[]; + let reportsAsked: string[]; + let createdAt: string; + if (prior) { + const s = prior.summary; + if (o.windowS !== undefined && o.windowS !== s.windowS) { + throw new BenchInputError(`run ${id} was made with a ${s.windowS} s window: drop the window, or start a new run`); + } + if (o.reports?.length && [...o.reports].sort().join(",") !== [...s.reports].sort().join(",")) { + throw new BenchInputError(`run ${id} was made over other reports: drop them, or start a new run`); + } + items = prior.items; + skipped = s.skipped; + results = prior.results; + models = [...s.models, ...v.models.filter((m) => !s.models.includes(m))]; + reportsAsked = s.reports; + createdAt = s.createdAt; + log(`continuing run ${id}: ${items.length} items, ${results.filter((r) => r.verdict !== null).length} answers on disk`); + } else { + const reports = await benchReportsOf(deps.paths, o.reports); + const got = await benchItemsOf(reports, { cuesOf: deps.cuesOf, windowS: v.windowS, ...(v.limit ? { limit: v.limit } : {}) }); + items = got.items; + skipped = got.skipped; + results = []; + models = v.models; + reportsAsked = o.reports?.length ? [...new Set(o.reports)] : []; + createdAt = now().toISOString(); + await mkdir(dir, { recursive: true }); + await writeBenchItems(dir, items); + log(`run ${id}: ${items.length} items from ${reports.length} fact-check(s), ${skipped.length} claims skipped`); + } + + const priorSpend = round6(results.reduce((s, r) => s + r.usd, 0)); + const meter = new Meter(); + let status: BenchStatus = "running"; + const stopped: string[] = []; + const summaryOf = (): BenchSummary => ({ + format: BENCH_FORMAT, + version: BENCH_VERSION, + id, + createdAt, + updatedAt: now().toISOString(), + status, + ...(stopped.length ? { stopped: [...stopped] } : {}), + models, + windowS: prior?.summary.windowS ?? v.windowS, + maxUsd: v.maxUsd, + reports: reportsAsked, + ...(prior?.summary.limit !== undefined ? { limit: prior.summary.limit } : v.limit !== undefined ? { limit: v.limit } : {}), + spentUsd: round6(priorSpend + meter.usd), + items: items.length, + skipped, + score: scoreBench(items, results, models), + }); + const save = async () => { + await writeBenchResults(dir, results); + await writeBenchSummary(dir, summaryOf()); + }; + const record = (r: BenchResult) => { + const at = results.findIndex((x) => x.key === r.key && x.model === r.model); + if (at >= 0) results[at] = r; + else results.push(r); + }; + await save(); + + const answered = new Set(results.filter((r) => r.verdict !== null).map((r) => `${r.model}\u0000${r.key}`)); + try { + models: for (const model of models) { + const local = providerOf(model) === "local"; + let streak = 0; + for (const item of items) { + if (answered.has(`${model}\u0000${item.key}`)) continue; + if (deps.signal?.aborted) { + status = "cancelled"; + stopped.push("cancelled"); + break models; + } + if (!local) { + const next = estimateCall(item, model, localCap).usd; + const spent = priorSpend + meter.usd; + if (spent + next > v.maxUsd) { + status = "capped"; + stopped.push(`the cap: $${spent.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${v.maxUsd}`); + log(`stopped at the cap ($${spent.toFixed(4)} of $${v.maxUsd})`); + break models; + } + } + const prompt = benchPrompt(item, local ? { capTokens: localCap } : {}); + const before = meter.summary().byModel[model]; + const usdBefore = meter.usd; + const t0 = Date.now(); + let r: BenchResult; + try { + const ans = await structuredAnswer<{ verdict?: unknown; reason?: unknown }>({ + llm: deps.llm, + model, + system: prompt.system, + user: prompt.user, + schema: VERDICT_ANSWER_SCHEMA, + meter, + ...(deps.signal ? { signal: deps.signal } : {}), + maxTokens: MAX_ANSWER_TOKENS, + }); + const verdict = isVerdict(ans?.verdict) ? ans.verdict : null; + const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : null; + r = { + key: item.key, + model, + verdict: verdict && reason !== null ? verdict : null, + ...(reason !== null ? { reason } : {}), + ...(verdict && reason !== null ? {} : { failure: "parse" as const, error: verdict ? "no reason" : `not a verdict: ${JSON.stringify(ans?.verdict ?? null).slice(0, 60)}` }), + ms: Date.now() - t0, + usd: 0, + inputTokens: 0, + outputTokens: 0, + at: now().toISOString(), + }; + streak = 0; + } catch (err) { + if (deps.signal?.aborted) { + status = "cancelled"; + stopped.push("cancelled"); + break models; + } + const parse = err instanceof StructuredAnswerError; + r = { + key: item.key, + model, + verdict: null, + failure: parse ? "parse" : "error", + error: (err as Error).message.slice(0, 300), + ms: Date.now() - t0, + usd: 0, + inputTokens: 0, + outputTokens: 0, + at: now().toISOString(), + }; + if (parse) streak = 0; + else streak++; + if (err instanceof ApiKeyError) streak = BENCH_ERROR_STREAK; + } + const after = meter.summary().byModel[model]; + r.usd = round6(meter.usd - usdBefore); + r.inputTokens = (after?.input ?? 0) + (after?.cacheRead ?? 0) + (after?.cacheWrite ?? 0) - ((before?.input ?? 0) + (before?.cacheRead ?? 0) + (before?.cacheWrite ?? 0)); + r.outputTokens = (after?.output ?? 0) - (before?.output ?? 0); + if (prompt.cuesTrimmed) r.cuesTrimmed = prompt.cuesTrimmed; + record(r); + await save(); + log(`${model} ${item.key}: ${r.verdict ?? `(${r.failure}: ${r.error})`} ${r.ms} ms${r.usd ? ` $${r.usd.toFixed(4)}` : ""}`); + if (streak >= BENCH_ERROR_STREAK) { + stopped.push(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row (${r.error})`); + log(`${model}: stopped after ${BENCH_ERROR_STREAK} errors in a row`); + continue models; + } + } + } + if (status === "running") status = "done"; + } catch (err) { + status = "failed"; + stopped.push((err as Error).message); + await save(); + throw err; + } + await save(); + return { id, dir, summary: summaryOf(), spent: meter.summary() }; +} diff --git a/common/lib/report/draft/bench/score.ts b/common/lib/report/draft/bench/score.ts @@ -0,0 +1,186 @@ +// THE VERDICT BENCH'S SCORE (release 28, M7) — pure. +// +// Per model, over the items it was asked: +// - agreement: the model's verdict equals the operator's, over every item +// asked (a failed answer — a parse failure or an error — counts as a miss); +// - agreementAdjacent: the same, with PARTLY and CORROBORATED counted as +// agreeing with each other ("PARTLY adjacent to CORROBORATED"); +// - the confusion matrix, 5×5 in VERDICTS order (rows: the operator's +// verdict, columns: the model's), with each row's failed answers beside it +// (`unanswered`); +// - recall for CONTRADICTED and NOT_FOUND (of the items the operator ruled +// so, the share the model ruled so), and for PARTLY strictly and adjacent; +// - cost (USD from the Meter), latency (ms per call), parse failures, errors. +// The BASELINE is a model that always answers CORROBORATED, scored the same way +// over the same items. A pass against the operator's bar is `passesBar`. + +import { VERDICTS, type Verdict } from "../../verdicts"; + +export type BenchResult = { + key: string; + model: string; + // The model's verdict, or null when it gave none. + verdict: Verdict | null; + reason?: string; + // `parse`: no structured answer, or one outside the schema; `error`: the + // call failed (the API, the network, a prompt over the local cap). + failure?: "parse" | "error"; + error?: string; + ms: number; + usd: number; + inputTokens: number; + outputTokens: number; + at: string; + // The local prompt's window trim, when one was needed. + cuesTrimmed?: number; +}; + +export type Recall = { ruled: number; matched: number; recall: number | null }; + +export type ModelScore = { + model: string; + asked: number; + answered: number; + agreed: number; + agreement: number | null; + agreedAdjacent: number; + agreementAdjacent: number | null; + // matrix[operator][model], VERDICTS order. + matrix: number[][]; + unanswered: number[]; + recall: { CONTRADICTED: Recall; NOT_FOUND: Recall; PARTLY: Recall; PARTLY_ADJACENT: Recall }; + parseFailures: number; + errors: number; + usd: number; + latency: { meanMs: number | null; medianMs: number | null; p90Ms: number | null }; +}; + +export type BenchScore = { + items: number; + // How many items the operator ruled each verdict. + ruled: Record<Verdict, number>; + models: ModelScore[]; + baseline: ModelScore; +}; + +export type VerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number }; + +export const BASELINE_MODEL = "always-CORROBORATED"; + +const idx = (v: Verdict) => VERDICTS.indexOf(v); +const ratio = (a: number, b: number) => (b > 0 ? Math.round((a / b) * 10_000) / 10_000 : null); +const adjacent = (a: Verdict, b: Verdict) => a === b || ((a === "PARTLY" || a === "CORROBORATED") && (b === "PARTLY" || b === "CORROBORATED")); + +function percentile(sorted: number[], p: number): number | null { + if (!sorted.length) return null; + const i = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1)); + return sorted[i]!; +} + +function recallOf(matrix: number[][], unanswered: number[], v: Verdict, also?: Verdict): Recall { + const row = matrix[idx(v)]!; + const ruled = row.reduce((s, n) => s + n, 0) + unanswered[idx(v)]!; + const matched = row[idx(v)]! + (also ? row[idx(also)]! : 0); + return { ruled, matched, recall: ratio(matched, ruled) }; +} + +// One model's score over `truth` (key → the operator's verdict). Only the +// results whose key is in `truth` count; the last result per key wins. +export function scoreModel(model: string, truth: ReadonlyMap<string, Verdict>, results: readonly BenchResult[]): ModelScore { + const last = new Map<string, BenchResult>(); + for (const r of results) if (r.model === model && truth.has(r.key)) last.set(r.key, r); + const matrix = VERDICTS.map(() => VERDICTS.map(() => 0)); + const unanswered = VERDICTS.map(() => 0); + let agreed = 0; + let agreedAdjacent = 0; + let parseFailures = 0; + let errors = 0; + let usd = 0; + const ms: number[] = []; + for (const [key, r] of last) { + const op = truth.get(key)!; + usd += r.usd; + if (r.ms > 0) ms.push(r.ms); + if (r.verdict === null) { + unanswered[idx(op)]! += 1; + if (r.failure === "parse") parseFailures++; + else errors++; + continue; + } + matrix[idx(op)]![idx(r.verdict)]! += 1; + if (r.verdict === op) agreed++; + if (adjacent(op, r.verdict)) agreedAdjacent++; + } + const asked = last.size; + ms.sort((a, b) => a - b); + return { + model, + asked, + answered: asked - parseFailures - errors, + agreed, + agreement: ratio(agreed, asked), + agreedAdjacent, + agreementAdjacent: ratio(agreedAdjacent, asked), + matrix, + unanswered, + recall: { + CONTRADICTED: recallOf(matrix, unanswered, "CONTRADICTED"), + NOT_FOUND: recallOf(matrix, unanswered, "NOT_FOUND"), + PARTLY: recallOf(matrix, unanswered, "PARTLY"), + PARTLY_ADJACENT: recallOf(matrix, unanswered, "PARTLY", "CORROBORATED"), + }, + parseFailures, + errors, + usd: Math.round(usd * 1e6) / 1e6, + latency: { + meanMs: ms.length ? Math.round(ms.reduce((s, n) => s + n, 0) / ms.length) : null, + medianMs: percentile(ms, 0.5), + p90Ms: percentile(ms, 0.9), + }, + }; +} + +// The whole run's score: each model in `models` order, and the baseline over +// every item. +export function scoreBench( + items: readonly { key: string; verdict: Verdict }[], + results: readonly BenchResult[], + models: readonly string[], +): BenchScore { + const truth = new Map(items.map((i) => [i.key, i.verdict] as const)); + const ruled = Object.fromEntries(VERDICTS.map((v) => [v, 0])) as Record<Verdict, number>; + for (const i of items) ruled[i.verdict]++; + const baselineResults: BenchResult[] = items.map((i) => ({ + key: i.key, + model: BASELINE_MODEL, + verdict: "CORROBORATED", + ms: 0, + usd: 0, + inputTokens: 0, + outputTokens: 0, + at: "", + })); + return { + items: items.length, + ruled, + models: models.map((m) => scoreModel(m, truth, results)), + baseline: scoreModel(BASELINE_MODEL, truth, baselineResults), + }; +} + +export type BarCheck = { pass: boolean; misses: string[] }; + +// A model against the operator's bar (fractions 0..1): strict agreement, and +// the CONTRADICTED and NOT_FOUND recalls. A recall with nothing ruled that way +// is not a miss (there was nothing to find). +export function passesBar(s: ModelScore, bar: VerdictBar): BarCheck { + const misses: string[] = []; + const pct = (v: number) => `${Math.round(v * 1000) / 10}%`; + if ((s.agreement ?? 0) < bar.agreement) misses.push(`agreement ${pct(s.agreement ?? 0)} < ${pct(bar.agreement)}`); + const c = s.recall.CONTRADICTED.recall; + if (c !== null && c < bar.contradictedRecall) misses.push(`CONTRADICTED recall ${pct(c)} < ${pct(bar.contradictedRecall)}`); + const nf = s.recall.NOT_FOUND.recall; + if (nf !== null && nf < bar.notFoundRecall) misses.push(`NOT_FOUND recall ${pct(nf)} < ${pct(bar.notFoundRecall)}`); + if (s.asked === 0) misses.push("no items asked"); + return { pass: misses.length === 0, misses }; +} diff --git a/common/lib/report/draft/bench/store.ts b/common/lib/report/draft/bench/store.ts @@ -0,0 +1,148 @@ +// WHERE A VERDICT BENCH RUN LIVES (release 28, M7): local-only, under the +// checkout's gitignored `.generation/` (beside the usage ledger): +// +// .generation/bench/verdicts/<run-id>/ +// items.jsonl one item per line (./items.ts) — the operator's verdict +// included: the answer key, never shown to a model +// results.jsonl one answer per (item, model) (./score.ts BenchResult) +// summary.json the run's parameters, status, spend, skipped claims and +// its score +// +// Never `transcripts/`, never a commit: the items quote ruled claims. Every +// write is atomic (tmp + rename, the whole file); a re-run with the same id +// resumes (./run.ts skips each pair already answered). + +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { writeFileAtomic, writeJsonAtomic } from "../../../jsonFile-server"; +import type { Paths } from "../../../paths"; +import type { BenchItem, BenchSkipped } from "./items"; +import type { BenchResult, BenchScore } from "./score"; + +export const BENCH_FORMAT = "archilyzer-verdict-bench"; +export const BENCH_VERSION = 1; + +export const BENCH_ITEMS_FILE = "items.jsonl"; +export const BENCH_RESULTS_FILE = "results.jsonl"; +export const BENCH_SUMMARY_FILE = "summary.json"; + +export const BENCH_STATUSES = ["running", "done", "capped", "cancelled", "failed"] as const; +export type BenchStatus = (typeof BENCH_STATUSES)[number]; + +export type BenchSummary = { + format: typeof BENCH_FORMAT; + version: typeof BENCH_VERSION; + id: string; + createdAt: string; + updatedAt: string; + status: BenchStatus; + // Why the run stopped early (the cap, a cancel, a model's errors), when it did. + stopped?: string[]; + models: string[]; + windowS: number; + maxUsd: number; + // The reports asked for (empty: every fact-check in the registry). + reports: string[]; + limit?: number; + spentUsd: number; + items: number; + skipped: BenchSkipped[]; + score: BenchScore; +}; + +export type BenchRun = { summary: BenchSummary; items: BenchItem[]; results: BenchResult[] }; + +const RUN_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; + +export function isBenchRunId(v: unknown): v is string { + return typeof v === "string" && RUN_ID_RE.test(v); +} + +// A new run's id: `vb-<UTC yyyymmdd-hhmmss>`. +export function newBenchRunId(now: Date = new Date()): string { + const s = now.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15); + return `vb-${s}`; +} + +// The runs' directory: `.generation/bench/verdicts/`, beside the usage ledger. +export function benchRootOf(paths: Pick<Paths, "generationUsageFile">): string { + return path.join(path.dirname(paths.generationUsageFile), "bench", "verdicts"); +} + +export function benchRunDir(root: string, id: string): string { + if (!isBenchRunId(id)) throw new Error(`"${id}" is not a run id (lowercase letters, digits and dashes)`); + return path.join(root, id); +} + +function jsonl(rows: readonly unknown[]): string { + return rows.map((r) => `${JSON.stringify(r)}\n`).join(""); +} + +async function readJsonl<T>(file: string): Promise<T[]> { + let text: string; + try { + text = await readFile(file, "utf8"); + } catch { + return []; + } + const out: T[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + out.push(JSON.parse(line) as T); + } catch { + // a torn line is skipped + } + } + return out; +} + +export async function writeBenchItems(dir: string, items: readonly BenchItem[]): Promise<void> { + await writeFileAtomic(path.join(dir, BENCH_ITEMS_FILE), jsonl(items), { mkdir: true }); +} + +export async function writeBenchResults(dir: string, results: readonly BenchResult[]): Promise<void> { + await writeFileAtomic(path.join(dir, BENCH_RESULTS_FILE), jsonl(results), { mkdir: true }); +} + +export async function writeBenchSummary(dir: string, summary: BenchSummary): Promise<void> { + await writeJsonAtomic(path.join(dir, BENCH_SUMMARY_FILE), summary, { mkdir: true }); +} + +export async function readBenchSummary(dir: string): Promise<BenchSummary | null> { + try { + const v = JSON.parse(await readFile(path.join(dir, BENCH_SUMMARY_FILE), "utf8")) as BenchSummary; + return v && v.format === BENCH_FORMAT ? v : null; + } catch { + return null; + } +} + +export async function readBenchRun(root: string, id: string): Promise<BenchRun | null> { + const dir = benchRunDir(root, id); + const summary = await readBenchSummary(dir); + if (!summary) return null; + const [items, results] = await Promise.all([ + readJsonl<BenchItem>(path.join(dir, BENCH_ITEMS_FILE)), + readJsonl<BenchResult>(path.join(dir, BENCH_RESULTS_FILE)), + ]); + return { summary, items, results }; +} + +// Every run's summary, newest first. +export async function listBenchRuns(root: string): Promise<BenchSummary[]> { + let names: string[]; + try { + names = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory() && isBenchRunId(e.name)).map((e) => e.name); + } catch { + return []; + } + const out: BenchSummary[] = []; + for (const n of names) { + const s = await readBenchSummary(path.join(root, n)); + if (s) out.push(s); + } + return out.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)); +} + +export { readJsonl as readBenchJsonl }; diff --git a/common/lib/report/draft/grounding.test.ts b/common/lib/report/draft/grounding.test.ts @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { checkNarration, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE } from "./grounding"; +import { checkNarration, firstPersonWords, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE, THIRD_PERSON_MESSAGE } from "./grounding"; const REPORTS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/reports"); const basic = JSON.parse(await readFile(path.join(REPORTS, "basic.report.json"), "utf8")); @@ -75,3 +75,35 @@ test("checkNarration carries the lints as soft warnings", () => { assert.equal(r.soft.length, 1); assert.match(r.soft[0]!, /negation mismatch/); }); + +test("hard (Q1): the narrator is third person — a first-person sentence is refused", () => { + // The live smoke's line: no cited quote it restates. + const r = checkNarration("She talks about the contest. I've already finished mine.", input); + assert.equal(r.hard.length, 1, r.hard.join("|")); + assert.ok(r.hard[0]!.startsWith(`${THIRD_PERSON_MESSAGE} (“I've”, “mine”)`), r.hard[0]); + for (const line of ["We tried the bakery.", "That's my oven.", "The oven is ours.", "Let me be clear: the bakery stays.", "So we're done.", "It was us all along."]) { + assert.ok(checkNarration(line, input).hard.some((h) => h.startsWith(THIRD_PERSON_MESSAGE)), line); + } +}); + +test("hard (Q1): a first-person sentence that restates a cited quote names whose line it is and where", () => { + const r = checkNarration("I paid for the mixer myself.", input); + assert.equal(r.hard.length, 1, r.hard.join("|")); + assert.match(r.hard[0]!, /^the narrator is third person \(“I”, “myself”\): this is the speaker's line from c03 \(Bread day @ 0:45\), “I paid for the new mixer myself”/); + // A named speaker is named. + const named = groundingInputOf({ ...basic, citations: { ...basic.citations, c03: { ...basic.citations.c03, speaker: "the baker" } } }); + assert.match(checkNarration("I paid for the mixer myself.", named).hard[0]!, /this is the baker's line from c03/); +}); + +test("Q1: first person inside quotation marks is not the narrator's; word boundaries, not substrings", () => { + assert.deepEqual(firstPersonWords('She said "I quit" and “we are done” twice.'), []); + const quoted = checkNarration('She said "I quit" twice.', input).hard; + assert.ok(!quoted.some((h) => h.startsWith(THIRD_PERSON_MESSAGE)), quoted.join("|")); + assert.ok(quoted.includes("text in quotation marks: no quotes in narration"), "the quote itself is still refused"); + // Not first person: names and words that only contain the letters. + assert.deepEqual(firstPersonWords("Iowa's myth of the mineral museum in the US is idle."), []); + // Accepted collateral: "mine" the noun. + assert.deepEqual(firstPersonWords("The old mine shaft."), ["mine"]); + // Curly apostrophes read as straight ones. + assert.deepEqual(firstPersonWords("I’m sure."), ["I’m".replace("’", "'")]); +}); diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -9,7 +9,11 @@ // - a capitalised name the report does not have (the first word of a // sentence and the COMMON_CAPS words aside); // - text in quotation marks: a narrator does not read quotes out; -// - six or more consecutive words of a cited quote: the clip says it. +// - six or more consecutive words of a cited quote: the clip says it; +// - a first-person word (I, me, my, we, us, our, … — FIRST_PERSON_WORDS) +// outside quotation marks: the narrator is third person (release 28 Q1). +// When the sentence restates a cited quote, the reason names whose line it +// is and where it was cited. // // SOFT (a warning; the line may be used, flagged for review) — the Q0 lints, // for what the hard checks cannot see (plans/local-llm-report-media.md, Q0): @@ -80,15 +84,25 @@ export type GroundingInput = { // The evidence lines (claims and quotes) the Q0 lints compare against; // default: the quotes. evidence?: readonly string[]; + // Every cited quote with who said it and where it is cited, for the + // first-person reason (default: none — the reason names no line). + sources?: readonly QuoteSource[]; }; +export type QuoteSource = { quote: string; speaker?: string; citation?: string }; + export type GroundingResult = { hard: string[]; soft: string[] }; type ReportLike = { title?: string; summary?: string | null; sections?: readonly { title?: string; body?: string | null; claims?: readonly { text?: string; title?: string }[] | null }[]; - citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null; + citations?: + | Record< + string, + { quote?: string; label?: string; date?: string; speaker?: string; channel?: string; id?: string; start?: number } | undefined + > + | null; }; // Every text of a report a narration may draw on: title, summary, section @@ -120,8 +134,75 @@ export function reportEvidence(report: ReportLike): string[] { return [...out, ...reportQuotes(report)]; } +const mmssOf = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; + +// Each cited quote with its speaker and its citation, as the first-person +// reason names them: `c03 (Pie stream @ 0:30)`. +export function reportQuoteSources(report: ReportLike): QuoteSource[] { + const out: QuoteSource[] = []; + for (const [cid, c] of Object.entries(report.citations ?? {})) { + if (!c?.quote) continue; + const where = c.label ?? (c.channel && c.id ? `${c.channel}/${c.id}` : ""); + const at = typeof c.start === "number" ? ` @ ${mmssOf(c.start)}` : ""; + out.push({ quote: c.quote, ...(c.speaker ? { speaker: c.speaker } : {}), citation: where ? `${cid} (${where}${at})` : cid }); + } + return out; +} + export function groundingInputOf(report: ReportLike): GroundingInput { - return { reference: reportText(report), quotes: reportQuotes(report), evidence: reportEvidence(report) }; + return { + reference: reportText(report), + quotes: reportQuotes(report), + evidence: reportEvidence(report), + sources: reportQuoteSources(report), + }; +} + +// ─── the narrator is third person (release 28 Q1) ─── + +// Word-bounded and case-insensitive: "Iowa", "myth" and "mineral" are not +// hits. Two kinds of collateral are accepted: "mine" the noun (a gold mine) +// and a roman numeral I; the all-caps "US" (the country) is not a hit. +export const FIRST_PERSON_WORDS = [ + "i", "i'm", "i've", "i'd", "i'll", "me", "my", "mine", "myself", + "we", "we're", "we've", "we'd", "we'll", "us", "our", "ours", "ourselves", +] as const; + +export const THIRD_PERSON_MESSAGE = "the narrator is third person"; + +const FIRST_PERSON = new Set<string>(FIRST_PERSON_WORDS); + +// A sentence's first-person words outside quotation marks, as written. +export function firstPersonWords(sentence: string): string[] { + const outside = sentence + .replace(/[’‘ʼ]/g, "'") + .replace(/"[^"]*"|“[^”]*”/g, " "); + const out: string[] = []; + for (const m of outside.matchAll(/[A-Za-z]+(?:'[A-Za-z]+)?/g)) { + const w = m[0]; + if (w === "US") continue; + if (FIRST_PERSON.has(w.toLowerCase())) out.push(w); + } + return out; +} + +// The hard problem for each first-person sentence: the rule, and — when the +// sentence restates a cited quote — whose line it is and where it is cited. +export function firstPersonProblems(text: string, sources: readonly QuoteSource[] = []): string[] { + const out: string[] = []; + for (const sent of sentencesOf(text)) { + const words = firstPersonWords(sent); + if (!words.length) continue; + const said = [...new Set(words)].map((w) => `“${w}”`).join(", "); + const line = sources.length ? closest(strictNormalize(sent), sources.map((s) => s.quote)) : null; + const src = line === null ? undefined : sources.find((s) => s.quote === line); + out.push( + src + ? `${THIRD_PERSON_MESSAGE} (${said}): this is ${src.speaker ? `${src.speaker}'s` : "the speaker's"} line from ${src.citation ?? "a citation"}, “${src.quote.slice(0, 80)}”` + : `${THIRD_PERSON_MESSAGE} (${said}): say what the speaker said, not as the speaker`, + ); + } + return out; } const SENTENCE_SPLIT = /(?<=[.!?…])\s+/; @@ -132,23 +213,25 @@ export function sentencesOf(text: string): string[] { const hasWord = (normText: string, w: string) => ` ${normText} `.includes(` ${w} `); -export function checkNarration(text: string, input: GroundingInput): GroundingResult { - const hard = new Set<string>(); - const soft = new Set<string>(); +/** + * The numbers (digits or words) and names (a capitalised word past a + * sentence's first that is not a common one) in `text` that `reference` does + * not have, as sentences naming `where` ("the report"; a media task's own + * evidence). What checkNarration grounds; release 28's on-screen and teaser + * drafts ground the same way. + */ +export function groundedProblems(text: string, reference: string, where = "the report"): string[] { + const out = new Set<string>(); const low = text.toLowerCase(); - if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); - for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); - - const ref = input.reference; - const refNorm = strictNormalize(ref); - const refNums = new Set(ref.replace(/,/g, "").match(/\d+/g) ?? []); + const refNorm = strictNormalize(reference); + const refNums = new Set(reference.replace(/,/g, "").match(/\d+/g) ?? []); for (const d of text.match(/\d[\d,]*/g) ?? []) { - if (!refNums.has(d.replace(/,/g, ""))) hard.add(`number ${d} is not in the report`); + if (!refNums.has(d.replace(/,/g, ""))) out.add(`number ${d} is not in ${where}`); } for (const w of low.match(/[a-z]+/g) ?? []) { const n = NUM_WORDS[w]; if (n === undefined) continue; - if (!hasWord(refNorm, w) && !refNums.has(String(n))) hard.add(`number “${w}” is not in the report`); + if (!hasWord(refNorm, w) && !refNums.has(String(n))) out.add(`number “${w}” is not in ${where}`); } for (const sent of sentencesOf(text)) { const toks = sent.match(/[A-Za-z][A-Za-z'’.-]*/g) ?? []; @@ -156,9 +239,20 @@ export function checkNarration(text: string, input: GroundingInput): GroundingRe const t = raw.replace(/^[.\-’']+|[.\-’']+$/g, ""); if (!/^[A-Z]/.test(t) || COMMON_CAPS.has(t)) continue; const n = strictNormalize(t.replace(/['’]s$/, "")); - if (n && !refNorm.includes(n)) hard.add(`name “${t}” is not in the report`); + if (n && !refNorm.includes(n)) out.add(`name “${t}” is not in ${where}`); } } + return [...out]; +} + +export function checkNarration(text: string, input: GroundingInput): GroundingResult { + const hard = new Set<string>(); + const soft = new Set<string>(); + const low = text.toLowerCase(); + if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); + for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); + + for (const p of groundedProblems(text, input.reference)) hard.add(p); if (/(^|\s)'[^']+(\s[^']+){3,}'/.test(text) || /["“”]/.test(text)) { hard.add("text in quotation marks: no quotes in narration"); } @@ -172,6 +266,7 @@ export function checkNarration(text: string, input: GroundingInput): GroundingRe } } } + for (const p of firstPersonProblems(text, input.sources)) hard.add(p); for (const w of lintNarration(text, input.evidence ?? input.quotes)) soft.add(w); return { hard: [...hard].sort(), soft: [...soft].sort() }; } diff --git a/common/lib/report/draft/reportOps.test.ts b/common/lib/report/draft/reportOps.test.ts @@ -198,3 +198,22 @@ test("two-line findings (the claim on the bullet, its quote and link under it) a const { problems } = await sweepToReport(after, { cuesOf }); assert.deepEqual(problems, []); }); + +test("add: a fragment quote is refused, and the refusal carries the full sentence (release 28 Q2)", async () => { + const doc = parseSweep(await readSweep("basic")); + const link = momentHref("synth-kitchen", "pie-stream-02", 40); + const r = await applyReportOps( + doc, + [ + { op: "add", section: "The lease", text: "She will not discuss the lease", quote: "my lawyer told me not to", link }, + { op: "add", section: "The lease", text: "She will not discuss the lease", quote: "my lawyer told me not to talk about the lease", link }, + ], + { checkQuote: strictCheckerOver(cuesOf), origin: "https://synth.example" }, + ); + assert.equal(r.refused.length, 1); + assert.match(r.refused[0]!.why, /a fragment \(ends on “to”\).*"my lawyer told me not to talk about the lease"/); + assert.equal(r.applied.length, 1); + // The words-only checker lets it through. + const words = await strictCheckerOver(cuesOf, { fragments: false })({ channel: "synth-kitchen", id: "pie-stream-02", second: 40, quote: "my lawyer told me not to" }); + assert.deepEqual(words, { ok: true }); +}); diff --git a/common/lib/report/draft/reportOps.ts b/common/lib/report/draft/reportOps.ts @@ -28,6 +28,7 @@ // add). import { STRICT_QUOTE_WINDOW_SECONDS, strictQuoteCheck } from "../../citations/verify"; +import { fragmentHint, fragmentOf, fullSentenceFor } from "../../citations/fragment"; import { LINK_RE, QUOTE_MARK_RE, @@ -64,17 +65,23 @@ export type ReportOpsContext = { }; // The strict checker over a cue reader (testing/draft/corpus.mjs cuesOf, or -// the MCP's transcript read): every fragment verbatim within ±90 s. +// the MCP's transcript read): every fragment verbatim within ±90 s, and the +// quote not a FRAGMENT (release 28 Q2: under four words, or stopping on a +// function word) — the refusal then carries the full sentence to quote. +// `fragments: false` checks the words only. export function strictCheckerOver( cuesOf: (channel: string, id: string) => Promise<readonly { start: number; end: number; text: string }[] | null>, - opts: { windowSeconds?: number } = {}, + opts: { windowSeconds?: number; fragments?: boolean } = {}, ): (q: QuoteCheckRequest) => Promise<QuoteCheckAnswer> { const windowSeconds = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS; return async ({ channel, id, second, quote }) => { const cues = await cuesOf(channel, id); if (!cues || cues.length === 0) return { ok: false, why: `no transcript cues for ${channel}/${id}` }; const r = strictQuoteCheck(quote, cues, second, { windowSeconds }); - return r.ok ? { ok: true } : { ok: false, why: `"${r.failed}" is not there` }; + if (!r.ok) return { ok: false, why: `"${r.failed}" is not there` }; + const frag = opts.fragments === false ? null : fragmentOf(quote); + if (frag) return { ok: false, why: fragmentHint(frag, fullSentenceFor(frag.part, cues, second, { windowSeconds })) }; + return { ok: true }; }; } diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts @@ -51,6 +51,28 @@ export type ResearchRecord = { continuedBy?: number[]; // The agent's closing words (what the corpus holds, what it proposed). notes?: string; + // An `auto` run continuing by itself (release 28 F1). + autoContinue?: AutoContinueRecord; +}; + +// What became of an `auto` run's own continuation (controller/ +// researchAutoContinue.ts): +// claimed a continuation is being enqueued (the once-only mark, taken +// under the article store's lock; stale after 10 minutes) +// continued sweep `by` continues it (`warnings`: channels left out) +// refused the ask was refused (the daily cap, a build, a route): tried +// again on a later UTC day than `day` +// held nothing it could sweep is in a build yet: tried again once a +// build newer than `buildsAt` (ms) exists, or on a later day +export const AUTO_CONTINUE_STATUSES = ["claimed", "continued", "refused", "held"] as const; +export type AutoContinueRecord = { + status: (typeof AUTO_CONTINUE_STATUSES)[number]; + at: string; + by?: number; + reason?: string; + warnings?: string[]; + day?: string; + buildsAt?: number; }; export function newResearchState(autonomy: Autonomy, limits: ResearchLimits): ResearchState { diff --git a/common/lib/report/draft/sweepModel.test.ts b/common/lib/report/draft/sweepModel.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, splitFinding } from "./sweepModel"; +import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, sectionsNamedBy, splitFinding, trimmedNumberedView } from "./sweepModel"; const SWEEPS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/sweeps"); @@ -86,3 +86,49 @@ test("the numbered view a model reads", async () => { const p = numberedView(parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8"))); assert.match(p, /## Coverage {2}\(coverage — keep\)/); }); + +// A synthetic report of `sections` × `per` findings with long quotes. +function bigSweep(sections: number, per: number): string { + const out = ["# Big", "", "A summary.", ""]; + let n = 0; + for (let s = 1; s <= sections; s++) { + out.push(`## Part ${s}`); + for (let k = 0; k < per; k++) { + n++; + out.push(`- Claim ${n} of part ${s}: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen" [Rec @ 0:${k}](https://synth.example/?v=ch%2Fv${n}&t=${k})`); + } + } + return out.join("\n"); +} + +test("trimmed view (Q3): the named sections first, the rest while the budget lasts; numbers the document's; the omitted said", () => { + const doc = parseSweep(bigSweep(20, 5)); + const full = numberedView(doc); + const v = trimmedNumberedView(doc, { maxChars: 2500, feedback: "Rework Part 17 and drop 3." }); + assert.ok(v.text.length <= 2500 + 400, String(v.text.length)); + assert.ok(full.length > 4 * v.text.length); + assert.deepEqual(v.named, [0, 16], "part 17 by its title; finding 3's section by its number"); + for (const n of [81, 82, 83, 84, 85, 3]) assert.ok(v.shown.includes(n), `[${n}] shown`); + assert.match(v.text, /## Part 17\n\[81\] Claim 81 of part 17/); + // Shown in document order; the left-out findings named by number. + assert.ok(v.text.indexOf("## Part 1\n") < v.text.indexOf("## Part 17")); + assert.match(v.text, /## Part 20 {2}\(findings \[96\]–\[100\] not shown\)/); + assert.equal(v.shown.length + v.omitted.length, 100); + // Quotes shortened and links reduced to their labels, in the view only. + assert.match(v.text, /\[81\] Claim 81 of part 17: "one two three four five six seven eight …" \[Rec @ 0:0\]/); + assert.ok(!v.text.includes("https://")); + assert.ok(renderSweep(doc).includes("fifteen\" [Rec @ 0:0](https://synth.example/?v=ch%2Fv81&t=0)"), "the document is untouched"); + // No feedback: document order. + const plain = trimmedNumberedView(doc, { maxChars: 2500 }); + assert.ok(plain.shown.includes(1) && !plain.shown.includes(81)); + // A budget that holds everything shows everything. + assert.equal(trimmedNumberedView(doc, { maxChars: 1e6 }).omitted.length, 0); +}); + +test("sectionsNamedBy: titles, section numbers, finding numbers", () => { + const doc = parseSweep(bigSweep(4, 2)); + assert.deepEqual([...sectionsNamedBy(doc, "In part 2, reword the claim.")], [1]); + assert.deepEqual([...sectionsNamedBy(doc, "section 4 is too long")].sort(), [3]); + assert.deepEqual([...sectionsNamedBy(doc, "merge [5] into 6")].sort(), [2]); + assert.deepEqual([...sectionsNamedBy(doc, "trim it to 30 s")], []); +}); diff --git a/common/lib/report/draft/sweepModel.ts b/common/lib/report/draft/sweepModel.ts @@ -212,3 +212,115 @@ export function numberedView(doc: SweepDoc): string { export function quotesOf(f: Finding): string[] { return [...evidenceOf(f).matchAll(new RegExp(QUOTED_RE.source, "g"))].map((m) => m[0].slice(1, -1)); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// A local model gets the numbered view in ONE prompt under the 8k cap, so the +// view is trimmed to a character budget: the sections the feedback names +// first (a section's title, "section N", or the number of a finding in it), +// then the rest in document order, finding by finding while the budget lasts. +// It is shown in document order; what is left out is said, with its numbers. +// Quotes are shortened and links reduced to their labels IN THE VIEW ONLY: an +// op still numbers against the whole document and never reaches a quote. + +export const VIEW_QUOTE_WORDS = 12; + +const normWords = (s: string) => + s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s]/gu, " ") + .replace(/\s+/g, " ") + .trim(); + +// A quoted span cut to its first words when it is long. +function shortQuote(q: string, words: number): string { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +} + +// A finding's evidence as the trimmed view shows it. +export function shortEvidence(f: Finding, quoteWords = VIEW_QUOTE_WORDS): string { + return evidenceOf(f) + .replace(new RegExp(QUOTED_RE.source, "g"), (m) => `"${shortQuote(m.slice(1, -1), quoteWords)}"`) + .replace(new RegExp(LINK_RE.source, "g"), (m) => m.slice(0, m.indexOf("](") + 1)); +} + +// The sections (their indices) the feedback names. +export function sectionsNamedBy(doc: SweepDoc, feedback: string): Set<number> { + const fb = ` ${normWords(feedback)} `; + const out = new Set<number>(); + // What is left once the titles and "section N" are taken out: its numbers + // are findings' ("drop 3", "[5]"). + let rest = ` ${normWords(feedback)} `; + doc.sections.forEach((s, i) => { + const t = normWords(s.title); + if (t.length >= 3 && fb.includes(` ${t} `)) { + out.add(i); + rest = rest.split(` ${t} `).join(" "); + } + if (new RegExp(`\\b(?:section|§)\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + rest = rest.replace(/\bsection \d+/g, " ").replace(/\b\d+ ?(?:s|sec|secs|seconds|min|minutes|percent)\b/g, " "); + const numbers = new Set([...rest.matchAll(/\b(\d{1,4})\b/g)].map((m) => Number(m[1]))); + for (const x of numberFindings(doc)) if (numbers.has(x.n)) out.add(doc.sections.indexOf(x.section)); + return out; +} + +export type TrimmedView = { text: string; shown: number[]; omitted: number[]; named: number[] }; + +export function trimmedNumberedView( + doc: SweepDoc, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): TrimmedView { + const numbered = numberFindings(doc); + const numberOf = new Map(numbered.map((x) => [x.finding, x.n])); + const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" "); + const head = [`TITLE: ${doc.title}`, `SUMMARY: ${summary.length > 600 ? `${summary.slice(0, 600)} …` : summary}`]; + const named = o.feedback ? sectionsNamedBy(doc, o.feedback) : new Set<number>(); + const order = [...doc.sections.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + let used = head.join("\n").length + doc.sections.reduce((n, s) => n + s.title.length + 40, 0); + // Which blocks of each section are shown. + const keep = new Map<number, Set<SweepBlock>>(); + for (const i of order) { + const set = new Set<SweepBlock>(); + keep.set(i, set); + for (const b of doc.sections[i]!.body) { + const line = + b.type === "finding" ? `[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}` : b.text.trim(); + if (!line) continue; + if (used + line.length + 1 > o.maxChars) continue; + used += line.length + 1; + set.add(b); + } + } + const lines = [...head]; + const shown: number[] = []; + const omitted: number[] = []; + doc.sections.forEach((s, i) => { + const set = keep.get(i)!; + const left = findingsOf(s).filter((f) => !set.has(f)).map((f) => numberOf.get(f)!); + const note = left.length ? ` (findings ${ranges(left)} not shown)` : ""; + lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}${note}`); + for (const b of s.body) { + if (!set.has(b)) continue; + if (b.type === "finding") { + lines.push(`[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}`.trimEnd()); + shown.push(numberOf.get(b)!); + } else lines.push(b.text); + } + omitted.push(...left); + }); + return { text: lines.join("\n"), shown: shown.sort((a, b) => a - b), omitted: omitted.sort((a, b) => a - b), named: [...named].sort((a, b) => a - b) }; +} + +// 1, 2, 3, 5 → "[1]–[3], [5]". +function ranges(ns: readonly number[]): string { + const out: string[] = []; + for (let i = 0; i < ns.length; ) { + let j = i; + while (j + 1 < ns.length && ns[j + 1] === ns[j]! + 1) j++; + out.push(j > i ? `[${ns[i]}]–[${ns[j]}]` : `[${ns[i]}]`); + i = j + 1; + } + return out.join(", "); +} diff --git a/common/lib/report/draft/tasks/clipEvidence.ts b/common/lib/report/draft/tasks/clipEvidence.ts @@ -0,0 +1,171 @@ +// What the flips, threads and youtube drafts read (release 28, M4–M6): the +// cut's clips as facts code can check against — each clip's quote, the claim +// it stands for (and that claim's verdict), the chapter it sits under, and +// the date its recording was made — and the one check of a short line of +// text (a topic, a label, a title) against the report. +// +// THE DATE is code's, never the model's: the entry's own `date` (the +// operator's, what the clip's header shows), else the recording's upload date +// from the corpus record (`get_video_metadata`, the reader the other tasks +// use), else the citation's `date`. A clip with none is in no pair. + +import { strictNormalize } from "../../../citations/verify"; +import { extractJsonObject } from "../../../parseStdoutJson"; +import { checkNarration, type GroundingInput, type GroundingResult } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import type { MediaReport } from "./media"; +import type { CorpusToolsLike } from "./types"; + +export type ClipClaim = { id?: string; text: string; verdict?: string }; + +/** One clip of the cut, as the media drafts read it. */ +export type ClipFact = { + id: string; + // The clip's first place in the timeline. + index: number; + quote: string; + claim: ClipClaim | null; + // The chapter card it sits under (its heading), if any. + section: string | null; + // YYYY-MM-DD, or null when nothing says. + date: string | null; + dateFrom: "entry" | "record" | "citation" | null; +}; + +const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); + +/** `20260105`, `2026-01-05` or an ISO stamp → `2026-01-05`; else null. */ +export function isoDay(v: unknown): string | null { + if (typeof v !== "string") return null; + const t = v.trim(); + let m = /^(\d{4})(\d{2})(\d{2})$/.exec(t); + if (m) return `${m[1]}-${m[2]}-${m[3]}`; + m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(t); + return m ? `${m[1]}-${m[2]}-${m[3]}` : null; +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** A side's `when`, written by code from its date: `Jan 2026`. */ +export const whenOf = (day: string) => `${MONTHS[Number(day.slice(5, 7)) - 1] ?? ""} ${day.slice(0, 4)}`.trim(); + +// Every claim of the report by id, and by the citations it cites. +function claimIndex(report: MediaReport) { + const byId = new Map<string, ClipClaim>(); + const byCite = new Map<string, ClipClaim>(); + for (const s of (report.sections ?? []) as { claims?: { id?: string; text?: string; citations?: string[]; verdict?: string }[] }[]) { + for (const c of s.claims ?? []) { + const claim: ClipClaim = { ...(c.id ? { id: c.id } : {}), text: stripCites(c.text ?? ""), ...(c.verdict ? { verdict: c.verdict } : {}) }; + if (c.id) byId.set(c.id, claim); + for (const cid of c.citations ?? []) if (!byCite.has(cid)) byCite.set(cid, claim); + } + } + return { byId, byCite }; +} + +/** + * The cut's clips (every clip of the timeline once, in timeline order), with + * their claims, chapters and dates. `corpus` is asked for the dates the + * entries do not carry; a failed read leaves the date to the citation's. + */ +export async function clipFacts( + manifest: VideoManifest, + report: MediaReport, + corpus: Pick<CorpusToolsLike, "call"> | null, + { dates = true }: { dates?: boolean } = {}, +): Promise<ClipFact[]> { + const { byId, byCite } = claimIndex(report); + const cites = (report.citations ?? {}) as Record<string, { date?: string } | undefined>; + const prov = (manifest.provenance ?? {}) as { channelSlug?: string }; + const recordDates = new Map<string, Promise<string | null>>(); + const recordDate = (channel: string, video: string) => { + const key = `${channel}/${video}`; + let p = recordDates.get(key); + if (!p) { + p = (corpus ? corpus.call("get_video_metadata", { channel, video_id: video }) : Promise.resolve("")) + .then((t) => isoDay((extractJsonObject(t) as { uploadDate?: unknown } | null)?.uploadDate)) + .catch(() => null); + recordDates.set(key, p); + } + return p; + }; + const out: ClipFact[] = []; + const seen = new Set<string>(); + let section: string | null = null; + for (const [index, e] of manifest.timeline.entries()) { + if (e.type === "card" && e.style === "chapter") section = e.heading ?? null; + if (e.type !== "clip" || seen.has(e.id)) continue; + seen.add(e.id); + const claimRef = (e.claim ?? null) as { id?: string; verdict?: string } | null; + const base = (claimRef?.id ? byId.get(claimRef.id) : undefined) ?? byCite.get(e.id) ?? null; + const claim = base || claimRef?.verdict ? { ...(base ?? { text: "" }), ...(claimRef?.verdict ? { verdict: claimRef.verdict } : {}) } : null; + const channel = String(e.siteChannel ?? e.channel ?? prov.channelSlug ?? ""); + const video = String(e.siteVideo ?? e.video ?? ""); + let date = dates ? isoDay(e.date) : null; + let dateFrom: ClipFact["dateFrom"] = date ? "entry" : null; + if (dates && !date && channel && video) { + date = await recordDate(channel, video); + if (date) dateFrom = "record"; + } + if (dates && !date) { + date = isoDay(cites[e.id]?.date); + if (date) dateFrom = "citation"; + } + out.push({ id: e.id, index, quote: String(e.quote ?? "").trim(), claim, section, date, dateFrom }); + } + return out; +} + +/** A clip's evidence line for a prompt (its quote and claim cut to `max` characters each). */ +export function clipLine(c: ClipFact, { max = 160, date = true }: { max?: number; date?: boolean } = {}): string { + const cut = (s: string) => (s.length > max ? `${s.slice(0, max - 1)}…` : s); + return ( + `- ${c.id}` + + (date ? ` [${c.date ?? "date unknown"}]` : "") + + (c.section ? ` (chapter: ${c.section})` : "") + + (c.quote ? `: "${cut(c.quote)}"` : "") + + (c.claim?.text ? ` — claim: ${cut(c.claim.text)}` : "") + ); +} + +/** Lines that fit a character budget, in order; the rest counted. */ +export function fitLines(lines: string[], budget: number): { text: string; omitted: number } { + const kept: string[] = []; + let used = 0; + for (const l of lines) { + if (used + l.length + 1 > budget) break; + kept.push(l); + used += l.length + 1; + } + return { text: kept.join("\n"), omitted: lines.length - kept.length }; +} + +const QUOTED = /“([^”]+)”|"([^"]+)"/g; + +/** + * A short line's problems (a topic, a label, a title or a summary), by the + * narration's grounding (./grounding.ts): every name and number in the + * report, no stock phrase, no first person, no tag. With `quotes`, words in + * quotation marks are allowed only when a cited quote says them verbatim + * (they are then left out of the other checks); without, any quotation marks + * or a run of a quote's words is refused, as in narration. + */ +export function checkLine(text: string, g: GroundingInput, { quotes = false }: { quotes?: boolean } = {}): GroundingResult { + if (!quotes) return checkNarration(text, g); + const hard: string[] = []; + const said = g.quotes.map((q) => ` ${strictNormalize(q)} `); + const stripped = text.replace(QUOTED, (_m, a: string | undefined, b: string | undefined) => { + const words = strictNormalize(a ?? b ?? ""); + if (!words || !said.some((q) => q.includes(` ${words} `))) hard.push(`“${(a ?? b ?? "").slice(0, 80)}” is not what a cited clip says, word for word`); + return " "; + }); + const r = checkNarration(stripped, { ...g, quotes: [] }); + return { hard: [...new Set([...hard, ...r.hard])].sort(), soft: r.soft }; +} + +/** The clips in a manifest by id (the first entry with each id). */ +export function clipsById(manifest: VideoManifest): Map<string, ManifestEntry> { + const m = new Map<string, ManifestEntry>(); + for (const e of manifest.timeline) if (e.type === "clip" && !m.has(e.id)) m.set(e.id, e); + return m; +} diff --git a/common/lib/report/draft/tasks/cut.test.ts b/common/lib/report/draft/tasks/cut.test.ts @@ -0,0 +1,209 @@ +// TASK cut (release 28 M1) over the S0 kit's manifests and the basic report, +// against the fake ollama: each code check refuses what it should, the better +// of two attempts is kept, the timeline is BUILT by code from the entries it +// had (and the umtool lint passes on it), the order's owner is the M1 ruling's, +// and an operator's order is never replaced. Real iterations store and project +// in a temp dir; the build's validators loaded from this checkout. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { reportToManifest } from "../../convertManifest"; +import { buildCut, checkCut, cut, cutCandidates, isConverterOrder, parseCut, pinnedEntries, CUT_SPEC } from "./cut"; +import { loadDeckChecks, type DeckChecks } from "./deckChecks"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "../../../../.."); +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); +const run = promisify(execFile); + +let tmp: string; +let ol: FakeOllama; +let deck: DeckChecks; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "cut-task-")); + ol = await startFakeOllama(); + deck = await loadDeckChecks(ROOT); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown, report?: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const r = report ?? (await kit("reports/basic.report.json")); + await writeIterationFile("synth-basic", 1, "report.json", r, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(r)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const progress: unknown[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + progress: (p) => progress.push(p), + now: () => new Date("2026-10-13T12:00:00.000Z"), + deckChecks: async () => deck, + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "cut-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, paths, projectsRoot, deps, lines, progress, manifestNow, draft, input }; +} + +const ids = (m: { timeline: { id: string }[] }) => m.timeline.map((e) => e.id); + +test("cut, the recorded run: the better of two attempts, the timeline built from the entries it had, marked, and the umtool lint passes", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + assert.equal(m.drafted.timeline.model, "code", "the converter marks its order"); + const p = await project(m); + const r = await kit("runs/cut.json"); + ol.push(...r.turns); + const out = await cut(p.input({ maxClips: 20 }), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.match(out.summary, /^1 cut\(s\) drafted \(undo: revisions\/.*-auto-before-cut\.manifest\.json\)$/); + const after = await p.manifestNow(); + assert.deepEqual(ids(after), ["title", "the-contest", "c04", "c06", "the-bakery", "c03", "c01"]); + // Entries untouched: the same objects, moved. + for (const e of after.timeline) assert.deepEqual(e, m.timeline.find((x: { id: string }) => x.id === e.id)); + assert.deepEqual(after.drafted.timeline, { task: "cut", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 }); + const file = await p.draft(); + const u = file.units.cut as { attempts: { hard: string[] }[]; applied: string }; + assert.equal(u.applied, "applied"); + assert.equal(u.attempts.length, 2); + assert.match(u.attempts[0]!.hard.join("\n"), /not a candidate of this cut: c09/); + assert.match(u.attempts[0]!.hard.join("\n"), /chosen more than once: c01/); + assert.deepEqual(p.progress, [ + { metric: "entries", current: 0, total: 1 }, + { metric: "entries", current: 1, total: 1 }, + ]); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.status, "done"); + assert.equal(it.steps.find((s) => s.task === "cut")!.status, "done"); + // The umtool lint over the written manifest (a node child, as a build runs it). + const lint = await run(process.execPath, [path.join(ROOT, "umtool/report-to-video/lint.mjs"), path.join(p.dir, "video.manifest.json"), "--json"]).catch((e) => e); + const res = JSON.parse(lint.stdout); + assert.deepEqual(res.errors, [], lint.stdout); +}); + +test("cut's checks: ids, twice, the cap and the floor, a pinned id, headings, and what would not build", async () => { + const report = await kit("reports/basic.report.json"); + const unitOf = async (m: unknown, maxClips = 20) => { + const p = await project(m, report); + const ctx = { manifest: m, report, input: p.input({ maxClips }), handle: { deps: p.deps, log: () => {} } } as never; + return { u: ((await CUT_SPEC.units(ctx)) as never[])[0] as never, m: m as never }; + }; + const basic = await kit("manifests/basic.video.manifest.json"); + const { u } = await unitOf(basic, 4); + const g = (...groups: [string, string[]][]) => ({ groups: groups.map(([heading, clips]) => ({ heading, clips })) }); + const hard = (v: ReturnType<typeof g>, man: unknown = basic, unit: never = u) => checkCut(v, unit, man as never).hard; + assert.deepEqual(hard(g(["The bakery", ["c01", "c02"]], ["The contest", ["c04"]])), []); + assert.match(hard(g(["The bakery", ["c01", "c02", "c99"]]))[0]!, /not a candidate of this cut: c99/); + assert.match(hard(g(["The bakery", ["c01", "c02", "c02"]])).join(), /chosen more than once: c02/); + assert.match(hard(g(["The bakery", ["c01", "c02", "c03"]], ["The contest", ["c04", "c05"]])).join(), /5 ids chosen \(at most 4\)/); + assert.match(hard(g(["The bakery", ["c01", "c02"]])).join(), /2 ids chosen \(at least 3\)/); + assert.match(hard(g(["The oven", ["c01", "c02", "c03"]])).join(), /"The oven" is not a section heading of this cut/); + assert.match(hard(g(["The bakery", ["c01"]], ["the bakery", ["c02", "c03"]])).join(), /"the bakery" heads two groups/); + // A post rides on c02: it must stay. + const withPost = { ...basic, posts: [{ id: "p01", platform: "x", date: "2026-01-05", text: "x", url: "https://x.com/i/status/1", attachTo: "c02" }] }; + const pu = (await unitOf(withPost)).u; + assert.match(hard(g(["The bakery", ["c01", "c03"]], ["The contest", ["c04"]]), withPost, pu).join(), /c02 must stay \(post p01 rides on it\)/); + // The full kit's threads: dropping every contest clip leaves a thread with none. + const full = await kit("manifests/full.video.manifest.json"); + const fu = (await unitOf(full)).u; + assert.match(hard(g(["The bakery", ["c01", "c02", "c03"]]), full, fu).join(), /the cut would not build: render\.chrome\.threads: thread contest has no clip/); + assert.deepEqual(hard(g(["The contest", ["c05"]], ["The bakery", ["c03", "c01"]]), full, fu), []); + // parse: a flat list is one group; empty groups go. + assert.deepEqual(parseCut({ clips: [" c01 ", "c02"] }), { groups: [{ heading: "", clips: ["c01", "c02"] }] }); + assert.throws(() => parseCut({ nope: 1 }), /no "groups"/); +}); + +test("buildCut: cards kept for sections with entries, a card with nothing dropped, head and tail in place, twins together, nothing invented", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const cands = cutCandidates(full, report); + assert.deepEqual(cands.map((c) => [c.citation, c.entry, c.chapter]), [ + ["c01", "c01", "The bakery"], ["c02", "c02", "The bakery"], ["c03", "c03", "The bakery"], + ["c04", "c04", "The contest"], ["c05", "c05", "The contest"], ["c06", "c06", "The contest"], + ]); + // c07 is cited by no citation of this report: after the last candidate, it stays with the teaser. + const t = buildCut(full, cands, { groups: [{ heading: "The contest", clips: ["c06", "c04"] }, { heading: "The bakery", clips: ["c03"] }] }); + assert.deepEqual(t.map((e) => e.id), ["title", "the-contest", "c06", "c04", "the-bakery", "c03", "c07", "fin"]); + // No chapter for a group with no heading; the bakery card dropped (nothing left in it). + const t2 = buildCut(full, cands, { groups: [{ heading: "The contest", clips: ["c04", "c05", "c02"] }] }); + assert.deepEqual(t2.map((e) => e.id), ["title", "the-contest", "c04", "c05", "c02", "c07", "fin"]); + // Variant twins move together; a hand-added entry stays in its chapter. + const tw = structuredClone(full); + const i = tw.timeline.findIndex((e: { id: string }) => e.id === "c02"); + tw.timeline.splice(i + 1, 0, { ...tw.timeline[i], variant: "full", start: 26 }, { type: "image", id: "still-1", src: "s.png", seconds: 4, title: "A still" }); + const t3 = buildCut(tw, cutCandidates(tw, report), { groups: [{ heading: "The contest", clips: ["c04"] }, { heading: "The bakery", clips: ["c02"] }] }); + assert.deepEqual(t3.map((e) => `${e.id}${e.variant ? `/${e.variant}` : ""}`), ["title", "the-contest", "c04", "the-bakery", "still-1", "c02", "c02/full", "c07", "fin"]); + // Pins: posts and flips. + const flips = await kit("manifests/flips.video.manifest.json"); + assert.deepEqual([...pinnedEntries(flips).keys()], ["c01", "c07"]); +}); + +test("who owns the order (the M1 ruling): code's is drafted over, the converter's unmarked too; a model's needs force; the operator's never", async () => { + const basic = await kit("manifests/basic.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const answer = jsonReply({ groups: [{ heading: "The bakery", clips: ["c03", "c02", "c01"] }] }); + // (2) No mark, the converter's order: code-made. + const unmarked = structuredClone(basic); + delete unmarked.drafted; + assert.equal(await isConverterOrder(unmarked, report), true); + const p1 = await project(unmarked); + ol.push(answer); + assert.equal((await cut(p1.input(), p1.deps)).status, "done"); + assert.deepEqual(ids(await p1.manifestNow()), ["title", "the-bakery", "c03", "c02", "c01"]); + // A model's draft: skipped without force, redrafted with it. + const again = await cut(p1.input(), p1.deps); + assert.equal(again.status, "failed"); + assert.match(String((await p1.draft()).units.cut!.skipped), /has a value \(a draft\); force re-drafts it/); + ol.push(answer); + assert.equal((await cut(p1.input({ force: true }), p1.deps)).status, "done"); + // The operator's: unmarked and not the converter's order — never replaced, even forced. + const mine = structuredClone(unmarked); + const [a, b] = [2, 3].map((i) => mine.timeline[i]); + mine.timeline.splice(2, 2, b, a); + assert.equal(await isConverterOrder(mine, report), false); + const p2 = await project(mine); + const skipped = await cut(p2.input(), p2.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p2.draft()).units.cut!.skipped), /the operator's/); + ol.push(answer); + const forced = await cut(p2.input({ force: true }), p2.deps); + assert.equal(forced.status, "done"); + assert.match(forced.summary, /0 cut\(s\) drafted, 1 as alternatives/); + assert.deepEqual(ids(await p2.manifestNow()), ids(mine), "the operator's order stands"); + const alt = (await p2.draft()).alternatives; + assert.deepEqual([alt.length, alt[0]!.reason, (alt[0]!.value as { id: string }[]).map((e) => e.id).join(" ")], [1, "operator", "title the-bakery c03 c02 c01"]); + assert.equal(ol.remaining(), 0); +}); + +test("the converter marks its timeline as code's, at the day it was made", async () => { + const made = await reportToManifest(await kit("reports/basic.report.json"), { today: "2026-10-13" }); + assert.ok(made.ok); + assert.deepEqual((made.manifest as { drafted: unknown }).drafted, { timeline: { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 } }); +}); diff --git a/common/lib/report/draft/tasks/cut.ts b/common/lib/report/draft/tasks/cut.ts @@ -0,0 +1,419 @@ +// TASK cut — which of the report's citations a video's cut keeps, and in what +// order (release 28 M1). A STEP on a done iteration (./media.ts), one unit: +// the timeline's ORDER (`drafted.timeline`). +// +// The model sees the report's claims (section, text, verdict) with the +// citation ids the cut can show and their quotes, and answers an ordered list +// of ids grouped under the section headings. Code checks it — ids only from +// the candidates, none twice, at least CUT_MIN_CLIPS and at most `maxClips` +// (settings.generation.cut.maxClips), every pinned id kept (a post rides on +// it, a flip names it), headings that are the cut's — and then BUILDS the +// timeline itself (`buildCut`): the existing entries of the chosen citations, +// untouched (their windows, cite, quote, on-screen text: fetch and snap stay +// code), chapter cards kept for the sections that still have entries and +// dropped when nothing is left (S7's rule), the title card and everything +// before the first chapter, the teaser and everything after the last clip, +// kept where they are. It never invents an entry. The built cut must pass the +// build's own validators as the cut it replaces did (`TaskDeps.deckChecks`). +// +// WHO OWNS THE ORDER (the M1 ruling). A timeline marked by a code path +// (`model: "code"` — the converter's, `convertManifest.ts`) is nobody's: the +// task drafts it without `force`. So is an unmarked one whose clips, in order, +// are exactly what the converter makes from the project's report (a project +// from before release 28). One marked by a model is a draft (`force` +// redrafts it); any other is the operator's, never replaced: the draft goes +// to cut-draft.json as an alternative. +// +// Q0: counts are code's; the prompt carries rules only; the better of two +// attempts is kept; the local prompt is fitted under its cap. + +import { applyDraft, draftedOf, isCodeDraft, makeProvenance } from "../../drafted.mjs"; +import { citedIds } from "../../convertShared"; +import { reportToManifest, CONVERT_TASK } from "../../convertManifest"; +import { providerOf } from "../../../llm"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import { fitLocalAsk } from "./revise-report"; +import type { DeckChecks } from "./deckChecks"; +import { runMediaTask, type MediaContext, type MediaReport, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const CUT_MIN_CLIPS = 3; +export const DEFAULT_MAX_CLIPS = 20; +// The room a re-ask's words take on top of the fitted prompt. +const RETRY_ROOM_CHARS = 1500; + +export type CutInput = MediaTaskInput & { + // settings.generation.cut.maxClips (the job passes it). + maxClips?: number; +}; + +/** One citation the cut can show: its entry in the timeline, and what the report says of it. */ +export type CutCandidate = { + citation: string; + entry: string; + kind: "clip" | "still"; + // The chapter it sits under now (its card's heading), or "". + chapter: string; + claim: { id?: string; text: string; verdict?: string } | null; + quote: string; + label: string; + date: string; +}; + +/** The model's answer, as code reads it. */ +export type CutValue = { groups: { heading: string; clips: string[] }[] }; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); +const norm = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim().toLowerCase(); +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); +const isChapter = (e: Obj) => e?.type === "card" && e?.style === "chapter"; +const isCandidateType = (e: Obj) => e?.type === "clip" || e?.type === "image"; + +/** + * The citation each clip or still of the timeline shows: its id when the + * report has a citation of that id (the converter's rule), else the video + * citation of its recording and second. First entry per citation. + */ +export function cutCandidates(manifest: VideoManifest, report: MediaReport): CutCandidate[] { + const cites: Record<string, Obj> = isObj(report.citations) ? report.citations : {}; + const used = new Set<string>(); + const claimOf = new Map<string, { id?: string; text: string; verdict?: string }>(); + for (const s of Array.isArray(report.sections) ? report.sections : []) { + for (const c of Array.isArray(s?.claims) ? s.claims : []) { + const ids = [...(Array.isArray(c?.citations) ? c.citations : []), ...citedIds(typeof c?.findings === "string" ? c.findings : undefined)]; + if (c?.sourceQuote?.citation) ids.unshift(c.sourceQuote.citation); + for (const id of ids) { + if (!claimOf.has(id)) claimOf.set(id, { ...(c.id ? { id: c.id } : {}), text: stripCites(String(c.text ?? "")), ...(c.verdict ? { verdict: c.verdict } : {}) }); + } + } + } + const slug = isObj(manifest.provenance) ? manifest.provenance.channelSlug : undefined; + const out: CutCandidate[] = []; + let chapter = ""; + for (const e of manifest.timeline) { + if (isChapter(e)) chapter = String(e.heading ?? ""); + if (!isCandidateType(e)) continue; + let cid: string | null = cites[e.id] && !used.has(e.id) ? e.id : null; + if (!cid && e.type === "clip") { + const ch = e.channel ?? slug; + cid = + Object.entries(cites).find( + ([id, c]) => + !used.has(id) && (c.kind === "video" || c.kind === "audio") && c.channel === ch && c.id === e.video && typeof c.start === "number" && Math.floor(c.start) === e.cite, + )?.[0] ?? null; + } + if (!cid || used.has(cid)) continue; + used.add(cid); + const c = cites[cid]!; + out.push({ + citation: cid, + entry: e.id, + kind: e.type === "clip" ? "clip" : "still", + chapter, + claim: claimOf.get(cid) ?? null, + quote: String(e.quote ?? c.quote ?? ""), + label: String(c.label ?? ""), + date: String(e.date ?? c.date ?? ""), + }); + } + return out; +} + +/** The entries something else names, which a cut must keep: posts ride on them, flips pair them. */ +export function pinnedEntries(manifest: VideoManifest): Map<string, string> { + const out = new Map<string, string>(); + for (const p of Array.isArray(manifest.posts) ? manifest.posts : []) { + if (isObj(p) && typeof p.attachTo === "string" && p.attachTo) out.set(p.attachTo, `post ${p.id ?? "?"} rides on it`); + } + const pairs = isObj(manifest.render) && isObj(manifest.render.chrome) && isObj(manifest.render.chrome.flips) ? manifest.render.chrome.flips.pairs : null; + for (const pr of Array.isArray(pairs) ? pairs : []) { + for (const side of ["then", "now"]) { + const id = isObj(pr?.[side]) ? pr[side].entry : null; + if (typeof id === "string" && id) out.set(id, `flip ${pr.id ?? "?"} pairs it`); + } + } + return out; +} + +/** + * The cut the answer makes (pure; the timeline's entries only, never a new + * one): what is before the first chapter or citation entry stays first, what + * is after the last citation entry stays last (the teaser), and between them + * each group plays under its chapter card (kept only when the group keeps an + * entry), its chosen entries in the answer's order. An entry no citation + * names (a hand-added clip, a still) stays with its chapter, after its card; + * a chapter only such entries keep goes after the groups. Variant twins (one + * id, several entries) move together. + */ +export function buildCut(manifest: VideoManifest, candidates: readonly CutCandidate[], value: CutValue): ManifestEntry[] { + const T = manifest.timeline; + const entryOf = new Map(candidates.map((c) => [c.citation, c.entry])); + const candidateEntries = new Set(candidates.map((c) => c.entry)); + const isCand = (e: ManifestEntry) => candidateEntries.has(e.id) && isCandidateType(e); + const first = T.findIndex((e) => isChapter(e) || isCand(e)); + let last = -1; + T.forEach((e, i) => { + if (isCand(e)) last = i; + }); + if (first < 0 || last < 0) return T.map((e) => ({ ...e })); + const head = T.slice(0, first); + const tail = T.slice(last + 1).filter((e) => !isChapter(e)); + // The chapters between: a card (or none, before the first) and the entries + // under it that no citation names. + type Chapter = { card: ManifestEntry | null; others: ManifestEntry[] }; + const chapters: Chapter[] = [{ card: null, others: [] }]; + for (const e of T.slice(first, last + 1)) { + if (isChapter(e)) { + // A variant twin of a card already seen joins it. + if (chapters.some((c) => c.card?.id === e.id)) continue; + chapters.push({ card: e, others: [] }); + } else if (!isCand(e)) chapters.at(-1)!.others.push(e); + } + const twins = (id: string) => T.filter((e) => e.id === id); + const cardTwins = (c: ManifestEntry) => twins(c.id).filter(isChapter); + const byHeading = new Map<string, Chapter>(); + for (const c of chapters) if (c.card && !byHeading.has(norm(c.card.heading))) byHeading.set(norm(c.card.heading), c); + const placed = new Set<Chapter>(); + const middle: ManifestEntry[] = [...chapters[0]!.others]; + placed.add(chapters[0]!); + for (const g of value.groups) { + const ids = g.clips.map((cid) => entryOf.get(cid)).filter((x): x is string => !!x); + if (!ids.length) continue; + const ch = g.heading.trim() ? byHeading.get(norm(g.heading)) : undefined; + if (ch && !placed.has(ch)) { + placed.add(ch); + middle.push(...cardTwins(ch.card!), ...ch.others); + } + for (const id of ids) middle.push(...twins(id).filter(isCand)); + } + for (const c of chapters) { + if (placed.has(c) || !c.others.length) continue; + middle.push(...(c.card ? cardTwins(c.card) : []), ...c.others); + } + return JSON.parse(JSON.stringify([...head, ...middle, ...tail])) as ManifestEntry[]; +} + +const clipOrder = (timeline: readonly Obj[]) => timeline.filter((e) => e?.type === "clip").map((e) => e.id); + +/** Is this timeline's clip order exactly the converter's from the report (a cut nobody reordered)? */ +export async function isConverterOrder(manifest: VideoManifest, report: MediaReport): Promise<boolean> { + try { + const made = await reportToManifest(report, {}); + if (!made.ok) return false; + const want = clipOrder(made.manifest.timeline as Obj[]); + const have = clipOrder(manifest.timeline); + return want.length === have.length && want.every((id, i) => id === have[i]); + } catch { + return false; + } +} + +type CutUnit = MediaUnit & { + candidates: CutCandidate[]; + pinned: Map<string, string>; + headings: string[]; + max: number; + // The order is code's (a converter mark, or the converter's order unmarked). + codeMade: boolean; + deck: DeckChecks | null; + // The build's validator errors of the cut as read (unindexed): the draft may not add any. + before: Set<string>; +}; + +const words = (s: string, n: number) => { + const w = s.split(/\s+/).filter(Boolean); + return w.length <= n ? w.join(" ") : `${w.slice(0, n).join(" ")} …`; +}; + +// The evidence, at a level of detail: 0 the quotes in full, 1 shortened, +// 2 none, 3 claims shortened too. +function evidenceText(u: CutUnit, report: MediaReport, level: number): string { + const lines = [`Report: ${String(report.title ?? "")}`, "", "Candidates, by the section each sits in now:"]; + let chapter: string | null = null; + let claim: string | null = null; + for (const c of u.candidates) { + if (c.chapter !== chapter) { + chapter = c.chapter; + claim = null; + lines.push("", `## ${c.chapter || "(before the first section)"}`); + } + const ct = c.claim ? `${c.claim.verdict ? `[${c.claim.verdict}] ` : ""}${level >= 3 ? words(c.claim.text, 15) : c.claim.text}` : "(no claim: cited in the section's text)"; + if (ct !== claim) { + claim = ct; + lines.push(`- Claim: ${ct}`); + } + const where = [c.kind === "still" ? "a still" : "a clip", c.label, c.date].filter(Boolean).join(", "); + const q = level >= 2 || !c.quote ? "" : ` — "${level === 1 ? words(c.quote, 10) : words(c.quote, 40)}"`; + lines.push(` - ${c.citation} (${where})${q}`); + } + const pinned = u.candidates.filter((c) => u.pinned.has(c.entry)); + lines.push("", `Section headings: ${u.headings.map((h) => `"${h}"`).join(", ") || "(none)"}`); + if (pinned.length) lines.push(`Must stay: ${pinned.map((c) => `${c.citation} (${u.pinned.get(c.entry)})`).join("; ")}`); + lines.push(`Choose from ${CUT_MIN_CLIPS} to ${u.max} ids.`); + return lines.join("\n"); +} + +export function cutSystem(max: number): string { + const rules = [ + "Use only the citation ids listed under the candidates, each at most once.", + `Choose at least ${CUT_MIN_CLIPS} and at most ${max} ids in all.`, + "Keep every id listed under Must stay.", + "Order the ids so the video builds its case: each one sets up or supports what follows, and the strongest evidence is not buried in the middle.", + "Group them under the report's section headings, written exactly as given, in the order the groups play; each heading heads at most one group. An id may move to the group where it argues best.", + "When two candidates show the same thing, keep the clearer one and leave the other out.", + "Do not add anything that is not a candidate: no new clips, no new headings.", + ]; + return ( + "You choose the clips of a short evidence video cut from a cited report, and their order. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "groups": a list of {"heading", "clips"} in play order, "clips" the citation ids in play order.' + ); +} + +const SCHEMA = { + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "object", + properties: { heading: { type: "string" }, clips: { type: "array", items: { type: "string" } } }, + required: ["heading", "clips"], + }, + }, + }, + required: ["groups"], +}; + +/** The model's answer to a CutValue (a throw is a hard failure). */ +export function parseCut(answer: unknown): CutValue { + const a = isObj(answer) ? answer : {}; + const raw = Array.isArray(a.groups) ? a.groups : Array.isArray(a.clips) ? [{ heading: "", clips: a.clips }] : null; + if (!raw) throw new Error('no "groups" in the answer'); + const groups = raw.map((g: unknown) => { + const o = isObj(g) ? g : {}; + const clips = (Array.isArray(o.clips) ? o.clips : []).map((x: unknown) => String(x ?? "").trim()).filter(Boolean); + return { heading: String(o.heading ?? "").replace(/\s+/g, " ").trim(), clips }; + }); + return { groups: groups.filter((g: { clips: string[] }) => g.clips.length) }; +} + +const LIST_AT_MOST = 6; +// A validator's sentence with its timeline positions taken out: a reorder +// moves an old problem, it does not make a new one. +const unindexed = (e: string) => e.replace(/\[\d+\]/g, "[]"); +const listed = (xs: string[]) => (xs.length > LIST_AT_MOST ? [...xs.slice(0, LIST_AT_MOST), `and ${xs.length - LIST_AT_MOST} more`] : xs).join(", "); + +/** Every code check of a cut: `hard` refuses it. */ +export function checkCut(value: CutValue, u: CutUnit, manifest: VideoManifest): { hard: string[]; soft: string[] } { + const hard: string[] = []; + const known = new Map(u.candidates.map((c) => [c.citation, c])); + const ids = value.groups.flatMap((g) => g.clips); + const unknown = [...new Set(ids.filter((id) => !known.has(id)))]; + if (unknown.length) hard.push(`not a candidate of this cut: ${listed(unknown)} (choose only the ids listed)`); + const twice = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))]; + if (twice.length) hard.push(`chosen more than once: ${listed(twice)}`); + const n = new Set(ids.filter((id) => known.has(id))).size; + if (n > u.max) hard.push(`${n} ids chosen (at most ${u.max})`); + if (n < CUT_MIN_CLIPS) hard.push(`${n} ids chosen (at least ${CUT_MIN_CLIPS})`); + const missing = u.candidates.filter((c) => u.pinned.has(c.entry) && !ids.includes(c.citation)); + for (const c of missing) hard.push(`${c.citation} must stay (${u.pinned.get(c.entry)})`); + const headings = new Set(u.headings.map(norm)); + const seen = new Set<string>(); + for (const g of value.groups) { + if (!g.heading) continue; + const h = norm(g.heading); + if (!headings.has(h)) hard.push(`"${g.heading}" is not a section heading of this cut (${u.headings.map((x) => `"${x}"`).join(", ")})`); + else if (seen.has(h)) hard.push(`"${g.heading}" heads two groups`); + seen.add(h); + } + if (!hard.length && u.deck) { + const next = { ...manifest, timeline: buildCut(manifest, u.candidates, value) }; + const added = u.deck.validatorErrors(next).filter((e) => !u.before.has(unindexed(e))); + for (const e of added.slice(0, LIST_AT_MOST)) hard.push(`the cut would not build: ${e}`); + } + return { hard, soft: [] }; +} + +/** The cut as a media task (./media.ts): one unit, the timeline's order. */ +export const CUT_SPEC: MediaTaskSpec<CutUnit, CutValue, CutInput> = { + task: "cut", + noun: "cut", + verb: "drafted", + progressMetric: "entries", + async units(ctx) { + const { manifest, report, input } = ctx; + const candidates = cutCandidates(manifest, report); + if (candidates.length < CUT_MIN_CLIPS) { + return [{ id: "cut", skipped: `only ${candidates.length} of the report's citations are in the cut (a cut needs ${CUT_MIN_CLIPS})` } satisfies MediaSkip]; + } + let deck: DeckChecks | null = null; + try { + deck = (await ctx.handle.deps.deckChecks?.()) ?? null; + } catch (e) { + ctx.handle.log(` the build's validators are not loaded (${(e as Error).message}); the cut is checked without them`); + } + const mark = draftedOf(manifest, { field: "timeline" }); + const codeMade = mark ? isCodeDraft(mark) : await isConverterOrder(manifest, report); + // The chapters a group may play under: the cards before the last + // candidate (one after it has nothing to head, and is dropped). + const lastAt = Math.max(...candidates.map((c) => manifest.timeline.findIndex((e) => e.id === c.entry))); + const headings: string[] = []; + for (const e of manifest.timeline.slice(0, lastAt)) { + if (isChapter(e) && e.heading && !headings.some((h) => norm(h) === norm(e.heading))) headings.push(String(e.heading)); + } + return [ + { + id: "cut", + target: { field: "timeline" }, + label: "the cut's clips and order", + candidates, + pinned: pinnedEntries(manifest), + headings, + max: Math.max(CUT_MIN_CLIPS, input.maxClips ?? DEFAULT_MAX_CLIPS), + codeMade, + deck, + before: new Set(deck ? deck.validatorErrors(manifest).map(unindexed) : []), + }, + ]; + }, + owner(manifest, u) { + const mark = draftedOf(manifest, { field: "timeline" }); + if (mark) return isCodeDraft(mark) ? "empty" : "drafted"; + return u.codeMade ? "empty" : "operator"; + }, + schema: () => SCHEMA, + system: (u) => cutSystem(u.max), + user(u, ctx: MediaContext<CutInput>) { + const ask = "\n\nChoose the cut's ids and their order."; + const build = (maxChars: number) => { + for (let level = 0; level <= 3; level++) { + const t = evidenceText(u, ctx.report, level) + ask; + if (t.length <= maxChars || level === 3) return t; + } + return ""; + }; + if (providerOf(ctx.input.model) !== "local") return build(Number.POSITIVE_INFINITY); + const system = cutSystem(u.max); + return fitLocalAsk({ llm: ctx.handle.deps.llm, model: ctx.input.model, system, schema: SCHEMA, build: (max) => build(max - RETRY_ROOM_CHARS) }).user; + }, + parse: (answer) => parseCut(answer), + check: (value, u, ctx) => checkCut(value, u, ctx.manifest), + toField: (value, u, manifest) => buildCut(manifest, u.candidates, value), + apply(manifest, u, value, provenance, force) { + const mark = draftedOf(manifest, { field: "timeline" }); + // A code-made order is nobody's: drafted over as a draft would be. One + // with no mark is given the converter's first, so the writer sees a draft. + if (u.codeMade && !mark) { + manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), timeline: makeProvenance({ task: CONVERT_TASK, model: "code", attempt: 1 }) }; + } + const code = u.codeMade || isCodeDraft(mark); + return applyDraft(manifest, { field: "timeline", value, provenance, force: force || code }); + }, + describe: (v) => v.groups.map((g) => `${g.heading || "—"}: ${g.clips.join(" ")}`).join(" | "), +}; + +export async function cut(input: CutInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(CUT_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/deckChecks.ts b/common/lib/report/draft/tasks/deckChecks.ts @@ -0,0 +1,45 @@ +// The build's own validators, for a media task's code checks (release 28). +// +// A drafted teaser must pass `validateTeaser` (the frame's fit per role), and +// a drafted cut must leave the manifest as valid as it found it (posts that +// ride on a clip, flips and threads that name clips). Those rules live in +// umtool's report-to-video (`deck.mjs`, `lint.mjs` `validatorErrors`: what a +// build runs before it renders) — plain `.mjs` that common does not depend on +// (it depends on common). So they are loaded at run time from the checkout, +// natively (the editor is never a standalone bundle: AGENTS.md, "The runtime +// container"), and handed to a task as `TaskDeps.deckChecks`. + +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +export type DeckChecks = { + // umtool/report-to-video/deck.mjs: a teaser entry's problems ([] = it builds). + validateTeaser(entry: unknown, where?: string): string[]; + // umtool/report-to-video/lint.mjs: every validator a build runs on the whole + // manifest, as sentences. + validatorErrors(manifest: unknown): string[]; +}; + +// The checkout's report-to-video directory. +export const deckDirOf = (repoRoot: string) => path.join(/* turbopackIgnore: true */ repoRoot, "umtool", "report-to-video"); + +const load = (file: string) => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ pathToFileURL(file).href); + +/** The validators, from the checkout at `repoRoot` (throws when it has no umtool). */ +export async function loadDeckChecks(repoRoot: string): Promise<DeckChecks> { + const dir = deckDirOf(repoRoot); + const [deck, lint] = await Promise.all([load(path.join(dir, "deck.mjs")), load(path.join(dir, "lint.mjs"))]); + if (typeof deck.validateTeaser !== "function" || typeof lint.validatorErrors !== "function") { + throw new Error(`${dir}: no validateTeaser / validatorErrors (an older checkout?)`); + } + return { + validateTeaser: (entry, where) => deck.validateTeaser(entry, where), + validatorErrors: (manifest) => { + try { + return lint.validatorErrors(manifest); + } catch (e) { + return [(e as Error).message]; + } + }, + }; +} diff --git a/common/lib/report/draft/tasks/flips.ts b/common/lib/report/draft/tasks/flips.ts @@ -0,0 +1,363 @@ +// TASK flips — THEN/NOW pairs over the cut's clips (release 28, M4): the +// `render.chrome.flips` panel (umtool/report-to-video/flips.mjs). A STEP on a +// done iteration, on the media task scaffold (./media.ts): one unit, the +// whole field. +// +// The model proposes pairs — a topic and two clip ids, and optionally a part +// of each clip's quote. CODE does the rest and checks it all: +// - the ids name clips of the cut, no clip is in two pairs, 1 to +// FLIPS_LIMITS.pairs[1] pairs (and no more than the dated clips allow); +// - the dates are the recordings' (./clipEvidence.ts), never the model's: +// the earlier clip is THEN, the later NOW, and two clips of one day are +// no pair; each side's `when` is written from its date ("Jan 2026"); +// - a side's `words` are its clip's quote, verbatim — the model's part of +// it only when the quote says exactly that — cut to the limit by code; +// - the topic is one line of at most FLIPS_LIMITS.topic characters, its +// names and numbers the report's (grounding); +// - THEN plays before NOW: a pair the other way round is refused, unless +// the cut's order is a draft itself (`drafted.timeline`) and the flips +// will be applied — then code swaps the two clips' places in the +// timeline, written through applyDraft with this task's provenance; +// - the result passes the build's own validateFlips and validateFlipEntries +// (common's panels.mjs). +// A pair failing a check is dropped when the others stand (the repair); the +// better of two attempts is kept. +// +// ONE LEFT PANEL: flips and threads share it. A cut with threads is refused — +// unless `force` and the threads are a draft: then the flips replace them +// (the list, each clip's `thread` and their mark go) and the log says so. +// A cut with no on-screen deck (`render.chrome`) has no panel: refused. + +import { applyDraft, clearDrafted, entriesWithId, ownerOf } from "../../drafted.mjs"; +import { FLIPS_LIMITS, threadsOn, validateFlipEntries, validateFlips } from "../../panels.mjs"; +import type { GroundingInput } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import { checkLine, clipFacts, clipLine, fitLines, whenOf, type ClipFact } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import { TaskInputError } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export type FlipsInput = MediaTaskInput; + +/** A pair as the model proposes it. */ +export type ProposedPair = { topic: string; then: string; now: string; thenWords?: string; nowWords?: string }; +export type FlipsValue = { pairs: ProposedPair[] }; + +type Side = { entry: string; when: string; words: string }; +export type FlipPair = { id: string; topic: string; then: Side; now: Side }; + +/** What code makes of a proposal: the field, the swaps it needs, and what is wrong (per pair, and overall). */ +export type FlipsPlan = { + flips: { pairs: FlipPair[] }; + swaps: [string, string][]; + pairProblems: string[][]; + problems: string[]; + soft: string[]; +}; + +type FlipsUnit = MediaUnit & { + // The cut as read (what every plan is made over). + manifest: VideoManifest; + clips: ClipFact[]; + g: GroundingInput; + // The cut's order is a draft and the flips will be applied: a pair may swap its clips. + reorderable: boolean; + // The threads are a draft and `force` is set: the flips replace them. + dropThreads: boolean; + maxPairs: number; + // The kept value's plan (set by toField, read by apply). + chosen?: FlipsPlan; +}; + +// The evidence's share of a prompt (characters), well under the local 8k tokens. +const EVIDENCE_BUDGET = 14_000; + +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** A pair id from its topic: letters, digits and `-`; unique among `taken`. */ +export function pairId(topic: string, i: number, taken: Set<string>): string { + let base = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); + if (!/^[a-z0-9]/.test(base)) base = `pair-${i + 1}`; + let id = base; + for (let k = 2; taken.has(id); k++) id = `${base}-${k}`; + taken.add(id); + return id; +} + +/** + * A side's words: the clip's quote, verbatim — or the part of it the model + * named, when the quote says exactly that — cut to `max` characters at a word + * (with `…`). `soft` when the model's part was not the quote's. + */ +export function sideWords(quote: string, part: string | undefined, max: number = FLIPS_LIMITS.words): { words: string; soft?: string } { + const q = oneLine(quote); + let w = q; + let soft: string | undefined; + const p = oneLine(part).replace(/^["“'…\s]+|["”'…\s]+$/g, ""); + if (p) { + const at = q.toLowerCase().indexOf(p.toLowerCase()); + if (at >= 0) w = q.slice(at, at + p.length); + else soft = "its words are not the clip's quote: the quote is used"; + } + if (w.length > max) { + const cut = w.slice(0, max - 1); + const sp = cut.lastIndexOf(" "); + w = `${(sp > max / 2 ? cut.slice(0, sp) : cut).replace(/[\s,;:.]+$/, "")}…`; + } + return { words: w, ...(soft ? { soft } : {}) }; +} + +/** The timeline with each pair of ids' places swapped. */ +export function swapEntries(timeline: ManifestEntry[], swaps: readonly [string, string][]): ManifestEntry[] { + const out = [...timeline]; + for (const [a, b] of swaps) { + const i = out.findIndex((e) => e.id === a); + const j = out.findIndex((e) => e.id === b); + if (i < 0 || j < 0) continue; + [out[i], out[j]] = [out[j]!, out[i]!]; + } + return out; +} + +const twins = (m: VideoManifest, id: string) => entriesWithId(m, id).length > 1; + +/** Code's reading of a proposal over this cut (pure). */ +export function planFlips(value: FlipsValue, unit: Pick<FlipsUnit, "clips" | "g" | "reorderable" | "dropThreads" | "maxPairs">, manifest: VideoManifest): FlipsPlan { + const byId = new Map(unit.clips.map((c) => [c.id, c])); + const problems: string[] = []; + const soft: string[] = []; + const [lo] = FLIPS_LIMITS.pairs; + const n = value.pairs.length; + if (n < lo) problems.push("no pair: propose at least one"); + if (n > unit.maxPairs) problems.push(`${n} pairs: at most ${unit.maxPairs}`); + const used = new Set<string>(); + const taken = new Set<string>(); + const pairs: FlipPair[] = []; + const pairProblems: string[][] = []; + const swaps: [string, string][] = []; + value.pairs.forEach((p, i) => { + const bad: string[] = []; + const w = `pair ${i + 1}`; + const topic = oneLine(p.topic); + if (!topic) bad.push(`${w}: no topic`); + else if (topic.length > FLIPS_LIMITS.topic) bad.push(`${w}: the topic is ${topic.length} characters (at most ${FLIPS_LIMITS.topic})`); + else for (const h of checkLine(topic, unit.g).hard) bad.push(`${w}: the topic: ${h}`); + let a = byId.get(p.then); + let b = byId.get(p.now); + if (!a) bad.push(`${w}: ${p.then || "(none)"} is not a clip of the cut`); + if (!b) bad.push(`${w}: ${p.now || "(none)"} is not a clip of the cut`); + let side = { then: p.thenWords, now: p.nowWords }; + if (a && b) { + if (a.id === b.id) bad.push(`${w}: THEN and NOW are the same clip`); + for (const c of [a, b]) { + if (used.has(c.id)) bad.push(`${w}: ${c.id} is already in a pair`); + if (!c.date) bad.push(`${w}: ${c.id}'s recording has no date`); + if (!c.quote) bad.push(`${w}: ${c.id} has no quote`); + } + if (a.date && b.date) { + if (a.date === b.date) bad.push(`${w}: ${a.id} and ${b.id} are of the same day (${a.date})`); + else if (a.date > b.date) { + // THEN is the earlier recording: the dates are code's. + [a, b] = [b, a]; + side = { then: p.nowWords, now: p.thenWords }; + } + } + if (a.id !== b.id && a.index > b.index) { + if (!unit.reorderable) bad.push(`${w}: THEN ${a.id} (${a.date}) plays after NOW ${b.id} (${b.date}) and the cut's order is not a draft — pick another pair, or reorder the cut by hand`); + else if (twins(manifest, a.id) || twins(manifest, b.id)) bad.push(`${w}: ${a.id} or ${b.id} has variant twins — reorder the cut by hand`); + } + } + if (a && b && !bad.length) { + const tw = sideWords(a.quote, side.then); + const nw = sideWords(b.quote, side.now); + if (tw.soft) soft.push(`${w}: ${a.id} ${tw.soft}`); + if (nw.soft) soft.push(`${w}: ${b.id} ${nw.soft}`); + if (a.index > b.index) swaps.push([a.id, b.id]); + pairs.push({ + id: pairId(topic, i, taken), + topic, + then: { entry: a.id, when: whenOf(a.date!), words: tw.words }, + now: { entry: b.id, when: whenOf(b.date!), words: nw.words }, + }); + } + // Only a pair that stands takes its clips: a refused one leaves them free. + if (a && b && !bad.length) for (const c of [a, b]) used.add(c.id); + pairProblems.push(bad); + }); + const flips = { pairs }; + if (pairs.length && !pairProblems.some((x) => x.length) && !problems.length) { + // The build's own checks, on the cut as it will be. + const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + after.timeline = swapEntries(after.timeline, swaps); + if (after.render?.chrome) { + if (unit.dropThreads) delete after.render.chrome.threads; + after.render.chrome.flips = flips; + } + problems.push(...validateFlips(flips), ...validateFlipEntries(after)); + } + return { flips, swaps, pairProblems, problems, soft }; +} + +const allProblems = (p: FlipsPlan) => [...p.problems, ...p.pairProblems.flat()]; + +export function flipsSystem(maxPairs: number): string { + return ( + "You pick THEN/NOW pairs for a short evidence video: two clips of the same speaker on one topic, where what was said " + + "at the earlier date is reversed or contradicted by what was said at the later one. Rules: (1) use only clip ids from " + + "the list; (2) a clip is in one pair at most; (3) propose only pairs that really reverse, at most " + + `${maxPairs}, best first; (4) the topic names what the pair is about in plain words, at most ${FLIPS_LIMITS.topic} ` + + "characters, no quotation marks, no first person, nothing the evidence does not say; (5) the dates are given and " + + "decide which clip is THEN — you never write a date; (6) thenWords and nowWords are optional: a part of that clip's " + + `quote copied word for word, when the whole quote is longer than ${FLIPS_LIMITS.words} characters; leave them out ` + + "otherwise." + ); +} + +export const FLIPS_SPEC: MediaTaskSpec<FlipsUnit, FlipsValue, FlipsInput> = { + task: "flips", + noun: "flips panel", + async units(ctx: MediaContext<FlipsInput>) { + const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; + const chrome = m.render?.chrome; + if (!chrome || typeof chrome !== "object") { + throw new TaskInputError("flips are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); + } + let dropThreads = false; + if (threadsOn(m.render)) { + const owner = ownerOf(m, { field: "render.chrome.threads" }); + if (!ctx.input.force || owner === "operator") { + throw new TaskInputError( + "this cut has threads (render.chrome.threads), and flips and threads share the left panel" + + (owner === "operator" ? ": the threads are the operator's — remove them first" : ": force replaces drafted threads"), + ); + } + dropThreads = true; + } + const clips = await clipFacts(m, ctx.report, ctx.handle.deps.corpus ?? null); + const dated = clips.filter((c) => c.date && c.quote); + const days = new Set(dated.map((c) => c.date)); + if (dated.length < 2 || days.size < 2) { + return [{ id: "flips", skipped: `a pair needs two clips of different dates: ${dated.length} dated clip(s), ${days.size} date(s)` }]; + } + const flipsOwner = ownerOf(m, { field: "render.chrome.flips" }); + return [ + { + id: "flips", + target: { field: "render.chrome.flips" }, + label: "THEN/NOW pairs", + manifest: m, + clips, + g: ctx.grounding, + reorderable: ownerOf(m, { field: "timeline" }) === "drafted" && flipsOwner !== "operator", + dropThreads, + maxPairs: Math.min(FLIPS_LIMITS.pairs[1], Math.floor(dated.length / 2)), + }, + ]; + }, + schema: () => ({ + type: "object", + properties: { + pairs: { + type: "array", + items: { + type: "object", + properties: { + topic: { type: "string" }, + then: { type: "string" }, + now: { type: "string" }, + thenWords: { type: "string" }, + nowWords: { type: "string" }, + }, + required: ["topic", "then", "now"], + }, + }, + }, + required: ["pairs"], + }), + system: (u) => flipsSystem(u.maxPairs), + user(u, ctx) { + const r = ctx.report as { title?: string; summary?: string | null }; + const ev = fitLines(u.clips.map((c) => clipLine(c)), EVIDENCE_BUDGET); + return ( + `Report: ${r.title ?? ""}` + + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + + `\n\nThe cut's clips (id [recording date] (chapter): "quote" — the claim it stands for):\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + + "\n\nPropose the pairs." + ); + }, + parse(answer) { + const list = (answer as { pairs?: unknown } | null)?.pairs; + if (!Array.isArray(list)) throw new Error("no pairs list in the answer"); + return { + pairs: list + .filter((p): p is Record<string, unknown> => !!p && typeof p === "object") + .map((p) => ({ + topic: oneLine(p.topic), + then: oneLine(p.then), + now: oneLine(p.now), + ...(typeof p.thenWords === "string" && p.thenWords.trim() ? { thenWords: p.thenWords } : {}), + ...(typeof p.nowWords === "string" && p.nowWords.trim() ? { nowWords: p.nowWords } : {}), + })), + }; + }, + check(value, u) { + const plan = planFlips(value, u, u.manifest); + return { hard: allProblems(plan), soft: plan.soft }; + }, + // The best attempt's pairs that pass, when there is one (never a new pair). + repair(attempts, u) { + let best: MediaAttempt<FlipsValue> | null = null; + for (const a of attempts) { + if (!a.value) continue; + const plan = planFlips(a.value, u, u.manifest); + const good = a.value.pairs.filter((_, i) => !plan.pairProblems[i]?.length).slice(0, u.maxPairs); + if (!good.length) continue; + const v = { pairs: good }; + const again = planFlips(v, u, u.manifest); + const hard = allProblems(again); + if (hard.length) continue; + if (!best || good.length > best.value!.pairs.length) { + best = { value: v, hard: [], soft: [...again.soft, `${a.value.pairs.length - good.length} refused pair(s) dropped`] }; + } + } + return best; + }, + toField(value, u) { + u.chosen = planFlips(value, u, u.manifest); + return u.chosen.flips; + }, + apply(manifest, u, value, provenance, force, ctx) { + const res = applyDraft(manifest, { field: "render.chrome.flips", value, provenance, force }); + if (!res.applied) return res; + const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (u.dropThreads && m.render?.chrome) { + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + clearDrafted(m, { field: "render.chrome.threads" }); + ctx.handle.log(" the drafted threads were removed: flips and threads share the left panel"); + } + const swaps = u.chosen?.swaps ?? []; + if (swaps.length) { + const t = applyDraft(m, { field: "timeline", value: swapEntries(m.timeline, swaps), provenance, force: true }); + ctx.handle.log( + t.applied + ? ` the cut's order changed so THEN plays first: ${swaps.map(([a, b]) => `${a} ⇄ ${b}`).join(", ")}` + : ` the cut's order could not be changed (${t.reason}): THEN plays after NOW`, + ); + } + return res; + }, + describe: (v, u) => { + const pairs = planFlips(v, u, u.manifest).flips.pairs; + return ( + `${pairs.length} pair(s): ` + + pairs.map((p) => `${p.topic} (${p.then.entry} ${p.then.when} → ${p.now.entry} ${p.now.when})`).join("; ") + + (u.dropThreads ? " — replaces the drafted threads" : "") + ); + }, +}; + +export async function flips(input: FlipsInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(FLIPS_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -1,13 +1,22 @@ // The generation tasks (release 27, S5), and one dispatcher the editor's // `report-draft` job runs (S6). +import type { MediaStepTask } from "../../../generationSettings"; +import type { MediaTaskInput } from "./media"; +import { cut, type CutInput } from "./cut"; +import { flips } from "./flips"; import { narrate, type NarrateInput } from "./narrate"; +import { onscreen, type OnscreenInput } from "./onscreen"; +import { teaser, type TeaserInput } from "./teaser"; import { research, type ResearchInput } from "./research"; import { reviseReport, type ReviseReportInput } from "./revise-report"; import { reviseVideo, type ReviseVideoInput } from "./revise-video"; import { sweepAgent, type SweepAgentInput } from "./sweep-agent"; import { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline"; +import { TaskInputError, runOnIteration } from "./run"; +import { threads } from "./threads"; import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types"; +import { youtube } from "./youtube"; export * from "./types"; export { TaskInputError, runOnIteration, usageOf } from "./run"; @@ -15,7 +24,37 @@ export { sweepAgent, SWEEP_READ_TOOLS, type SweepAgentInput } from "./sweep-agen export { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline"; export { reviseReport, type ReviseReportInput } from "./revise-report"; export { reviseVideo, type ReviseVideoInput } from "./revise-video"; -export { narrate, type NarrateInput } from "./narrate"; +export { narrate, NARRATE_SPEC, type NarrateInput } from "./narrate"; +export { cut, CUT_SPEC, CUT_MIN_CLIPS, DEFAULT_MAX_CLIPS, buildCut, cutCandidates, isConverterOrder, type CutInput } from "./cut"; +export { loadDeckChecks, type DeckChecks } from "./deckChecks"; +export { teaser, TEASER_SPEC, TEASER_MIN_LINES, TEASER_MAX_LINES, TEASER_LINE_MAX, checkTeaser, type TeaserInput } from "./teaser"; +export { onscreen, ONSCREEN_SPEC, ONSCREEN_TITLE_MAX, ONSCREEN_SUBTITLE_MAX, checkOnscreen, type OnscreenInput } from "./onscreen"; +// The media task scaffold (release 28, M0): what every media task is. +export { + ALTERNATIVES_PER_FIELD, + defaultScore, + draftFileName, + isSkip, + loadMediaContext, + mergeAlternatives, + rankAttempts, + readDraftFile, + runMediaTask, + type DraftAlternative, + type DraftFile, + type MediaAttempt, + type MediaContext, + type MediaReport, + type MediaSkip, + type MediaTaskInput, + type MediaTaskSpec, + type MediaUnit, +} from "./media"; +// Release 28 M4–M6: the left panel (flips or threads) and the upload's text. +export { flips, FLIPS_SPEC, planFlips, sideWords, swapEntries, type FlipsInput, type FlipsPlan, type FlipsValue } from "./flips"; +export { threads, THREADS_SPEC, THREADS_TASK_COUNT, planThreads, type ThreadsInput, type ThreadsPlan, type ThreadsValue } from "./threads"; +export { youtube, YOUTUBE_SPEC, YOUTUBE_SUMMARY_MAX, type YoutubeInput, type YoutubeValue } from "./youtube"; +export { checkLine, clipFacts, whenOf, type ClipFact } from "./clipEvidence"; export { research, RESEARCH_READ_TOOLS, type ResearchInput } from "./research"; export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource"; export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; @@ -28,7 +67,11 @@ export type TaskInput = | ({ task: "revise-report" } & ReviseReportInput) | ({ task: "revise-video" } & ReviseVideoInput) | ({ task: "narrate" } & NarrateInput) - | ({ task: "research" } & ResearchInput); + | ({ task: "research" } & ResearchInput) + | ({ task: "cut" } & CutInput) + | ({ task: "onscreen" } & OnscreenInput) + | ({ task: "teaser" } & TeaserInput) + | ({ task: Exclude<MediaStepTask, "narrate" | "cut" | "onscreen" | "teaser"> } & MediaTaskInput); export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { switch (input.task) { @@ -44,6 +87,18 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { return narrate(input, deps); case "research": return research(input, deps); + case "flips": + return flips(input, deps); + case "threads": + return threads(input, deps); + case "youtube": + return youtube(input, deps); + case "cut": + return cut(input, deps); + case "onscreen": + return onscreen(input, deps); + case "teaser": + return teaser(input, deps); } } diff --git a/common/lib/report/draft/tasks/media.test.ts b/common/lib/report/draft/tasks/media.test.ts @@ -0,0 +1,259 @@ +// The media task scaffold (release 28, M0): a toy task over the fake ollama +// — two attempts, the better kept, an operator's field never replaced and its +// draft kept as an alternative — and narrate on it writing its drafted marks. +// Real iterations store and project in a temp dir; no model but the fake. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { reviewAddress } from "../../drafted.mjs"; +import { narrate } from "./narrate"; +import { + mergeAlternatives, + rankAttempts, + runMediaTask, + type DraftAlternative, + type DraftFile, + type MediaTaskSpec, + type MediaUnit, +} from "./media"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +let tmp: string; +let ol: FakeOllama; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "media-task-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +// A done sweep iteration with a project holding `manifest` and the basic report. +async function project(manifest: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + return { dir, paths, projectsRoot, deps, lines, manifestNow }; +} + +// A toy task: a title for each clip, at most 20 characters, never "BAD". +type ToyUnit = MediaUnit & { quote: string }; +const TOY: MediaTaskSpec<ToyUnit, { title: string }> = { + task: "toy", + units: (ctx) => + ctx.manifest.timeline + .filter((e) => e.type === "clip") + .slice(0, 3) + .map((e) => ({ id: e.id, target: { entry: e.id, field: "onscreen" }, quote: String(e.quote ?? "") })), + schema: () => ({ type: "object", properties: { title: { type: "string" } }, required: ["title"] }), + system: () => "Write a short title. Rules: at most 20 characters.", + user: (u) => `Quote: ${u.quote}`, + parse: (a) => ({ title: String((a as { title?: unknown }).title ?? "").trim() }), + check: (v) => ({ + hard: [...(v.title.length > 20 ? [`${v.title.length} characters (at most 20)`] : []), ...(v.title === "BAD" ? ["bad"] : [])], + soft: v.title.endsWith("!") ? ["an exclamation"] : [], + }), +}; + +test("the scaffold: two attempts and the better kept; the operator's field kept and the draft an alternative; marks, snapshot, draft file", async () => { + const m = await kit("manifests/full.video.manifest.json"); + const p = await project(m); + // c01 has hand-written on-screen text (the operator's); c02 and c03 none. + ol.push( + // c01 (forced): clean — but the field is the operator's. + jsonReply({ title: "Not for sale?" }), + // c02: too long, then clean. + jsonReply({ title: "A title far too long for the frame" }), + jsonReply({ title: "The old oven" }), + // c03: a soft flag, then worse (hard): the first is kept. + jsonReply({ title: "The mixer!" }), + jsonReply({ title: "BAD" }), + ); + const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.match(out.summary, /^2 field\(s\) drafted, 1 as alternatives \(see toy-draft\.json\) \(undo: revisions\/.*-auto-before-toy\.manifest\.json\)$/); + const after = await p.manifestNow(); + const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); + assert.deepEqual(e("c01").onscreen, m.timeline.find((x: { id: string }) => x.id === "c01").onscreen, "the operator's words stand"); + assert.equal(e("c01").drafted, undefined); + assert.deepEqual(e("c02").onscreen, { title: "The old oven" }); + assert.deepEqual(e("c02").drafted.onscreen, { task: "toy", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 }); + assert.deepEqual(e("c03").onscreen, { title: "The mixer!" }); + assert.equal(e("c03").drafted.onscreen.attempt, 1, "the better of two: the first"); + assert.equal((await readdir(path.join(p.dir, "revisions"))).length, 1); + const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; + assert.equal(file.task, "toy"); + assert.equal(file.iteration, 1); + assert.equal((file.units.c02!.attempts as unknown[]).length, 2); + assert.equal(file.units.c01!.applied, "operator"); + assert.equal(file.units.c02!.applied, "applied"); + assert.deepEqual(file.alternatives.map((a) => [a.target, a.value, a.reason]), [[{ entry: "c01", field: "onscreen" }, { title: "Not for sale?" }, "operator"]]); + assert.equal(file.checks.find((c) => c.name === "toy")!.ok, true); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.status, "done", "a step leaves the iteration's status"); + assert.equal(it.steps.find((s) => s.task === "toy")!.status, "done"); + + // Again, unforced: every field has a value now, so nothing is asked; the + // alternative from the run before is carried over. + const again = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps); + assert.equal(again.status, "failed"); + assert.match(again.summary, /no field drafted/); + const file2 = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; + assert.match(String(file2.units.c02!.skipped), /has a value \(a draft\); force re-drafts it/); + assert.match(String(file2.units.c01!.skipped), /the operator's/); + assert.equal(file2.alternatives.length, 1); +}); + +test("the scaffold: entries keeps only the named units; a unit with no clean value is not written", async () => { + const m = await kit("manifests/full.video.manifest.json"); + const p = await project(m); + ol.push(jsonReply({ title: "BAD" }), jsonReply({ title: "BAD" })); + const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, entries: ["c02"] }, p.deps); + assert.equal(out.status, "failed"); + assert.equal(ol.remaining(), 0, "only c02 was asked"); + const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; + assert.deepEqual(Object.keys(file.units), ["c02"]); + assert.deepEqual(await p.manifestNow(), m, "nothing written"); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.checks!.find((c) => c.name === "toy")!.ok, false); +}); + +test("rankAttempts and mergeAlternatives", () => { + const a = { value: 1, hard: ["x"], soft: [] }; + const b = { value: 2, hard: [], soft: ["y", "z"] }; + const c = { value: 3, hard: [], soft: ["y", "z"] }; + assert.deepEqual(rankAttempts([a, b, c]).map((x) => x.value), [2, 3, 1], "stable among equals"); + const alt = (entry: string, title: string): DraftAlternative => ({ + target: { entry, field: "onscreen" }, + value: { title }, + provenance: { task: "toy", model: "m", at: "2026-10-13T00:00:00.000Z", attempt: 1 }, + reason: "operator", + }); + const many = Array.from({ length: 7 }, (_, i) => alt("c01", `t${i}`)); + const merged = mergeAlternatives(many.slice(0, 4), [...many.slice(4), alt("c01", "t0"), alt("c02", "x")]); + assert.deepEqual( + merged.map((x) => `${reviewAddress(x.target)}:${(x.value as { title: string }).title}`), + ["onscreen/c01/onscreen:t3", "onscreen/c01/onscreen:t4", "onscreen/c01/onscreen:t5", "onscreen/c01/onscreen:t6", "onscreen/c01/onscreen:t0", "onscreen/c02/onscreen:x"], + "five per field, the newest; a repeat keeps its newest place", + ); +}); + +test("narrate on the scaffold: a narration it writes carries drafted.narration; the operator's is kept and its draft an alternative", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const contest = m.timeline.find((e: { id: string }) => e.id === "the-contest"); + contest.narration = { text: "Words the operator wrote." }; + const p = await project(m); + // Each card's words by its heading, however many times it is asked. + const byCard = (body: { messages: { content: string }[] }) => { + const user = body.messages.at(-1)!.content; + if (/heading on screen: The bakery/.test(user)) return jsonReply({ text: "First, the bakery. She won't sell it, and she paid for the mixer herself." }); + if (/heading on screen: The contest/.test(user)) return jsonReply({ text: "Then the contest. She stayed out of it this year." }); + return jsonReply({ text: "What does the baker say about her bakery? And about the contest?" }); + }; + ol.push(byCard, byCard, byCard, byCard, byCard, byCard); + const out = await narrate({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.match(out.summary, /^2 card\(s\) narrated, 1 as alternatives \(see narration-draft\.json\)/); + const after = await p.manifestNow(); + const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); + assert.equal(e("the-bakery").narration.text, "First, the bakery. She won't sell it, and she paid for the mixer herself."); + assert.equal(e("the-bakery").seconds, "auto"); + assert.deepEqual(e("the-bakery").drafted, { narration: { task: "narrate", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 1 } }); + assert.equal(e("title").drafted.narration.task, "narrate"); + assert.equal(e("the-contest").narration.text, "Words the operator wrote."); + assert.equal(e("the-contest").drafted, undefined); + const file = JSON.parse(await readFile(path.join(p.dir, "narration-draft.json"), "utf8")) as DraftFile; + assert.deepEqual(file.alternatives.map((a) => [a.target.entry, (a.value as { text: string }).text]), [["the-contest", "Then the contest. She stayed out of it this year."]]); + const revisions = await readdir(path.join(p.dir, "revisions")); + assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.checks!.find((c) => c.name === "narration")!.ok, true); +}); + +test("the scaffold in batches (release 28): one ask for several units, the re-ask only for the refused; progress per batch; an owner hook", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + m.timeline.find((e: { id: string }) => e.id === "c01").onscreen = { title: "x" }; + const p = await project(m); + // A fake of its own: the script above may have turns left. + const own = await startFakeOllama(); + p.deps.llm = { ollama: { baseUrl: own.url } }; + const progress: { metric: string; current: number; total?: number }[] = []; + p.deps.progress = (x) => progress.push(x); + const BATCHED: MediaTaskSpec<ToyUnit, { title: string }> = { + ...TOY, + task: "toy-batch", + // c01 counts as nobody's although it will have a value (the cut's hook). + owner: (manifest, u) => (u.id === "c01" ? "empty" : undefined) ?? (manifest.timeline.find((e) => e.id === u.id)?.onscreen ? "operator" : "empty"), + batch: { + group: (us) => [us.slice(0, 2), us.slice(2)], + schema: () => ({ type: "object", properties: { entries: { type: "array", items: { type: "object" } } }, required: ["entries"] }), + system: () => TOY.system(null as never, null as never), + user: (us) => us.map((u) => `${u.id}: ${u.quote}`).join("\n"), + split: (a) => Object.fromEntries(((a as { entries: { id: string; title: string }[] }).entries ?? []).map((e) => [e.id, e])), + }, + }; + const asked: string[] = []; + const reply = (entries: { id: string; title: string }[]) => (body: { messages: { content: string }[] }) => { + asked.push(body.messages.at(-1)!.content); + return jsonReply({ entries }); + }; + own.push( + // c01 + c02: c02 refused; c01 clean. + reply([{ id: "c01", title: "Not for sale" }, { id: "c02", title: "BAD" }]), + // the re-ask: c02 alone. + reply([{ id: "c02", title: "The old oven" }]), + // c03 alone in its batch, and no draft for it. + reply([]), + reply([{ id: "c03", title: "The mixer" }]), + ); + const out = await runMediaTask(BATCHED, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps); + await own.close(); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(own.remaining(), 0); + assert.equal(asked.length, 4); + assert.match(asked[1]!, /^c02: we never said/); + assert.match(asked[1]!, /Your last drafts were refused: c02: bad/); + assert.match(asked[3]!, /c03: no draft for c03 in the answer/); + const after = await p.manifestNow(); + const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); + // The hook let c01 be asked; the writer still keeps the operator's words. + assert.deepEqual([e("c01").onscreen, e("c02").onscreen, e("c03").onscreen], [{ title: "x" }, { title: "The old oven" }, { title: "The mixer" }]); + const file = JSON.parse(await readFile(path.join(p.dir, "toy-batch-draft.json"), "utf8")) as DraftFile; + assert.deepEqual(file.alternatives.map((a) => [a.target.entry, a.reason]), [["c01", "operator"]]); + assert.equal(e("c02").drafted.onscreen.attempt, 2); + assert.deepEqual(progress, [ + { metric: "entries", current: 0, total: 3 }, + { metric: "entries", current: 2, total: 3 }, + { metric: "entries", current: 3, total: 3 }, + ]); +}); diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -0,0 +1,494 @@ +// THE MEDIA TASK SCAFFOLD (release 28, M0) — what every task that drafts a +// field of an iteration's video manifest is, extracted from narrate (the +// first; ./narrate.ts is now a spec on this). Phase 2's tasks (cut, onscreen, +// teaser, flips, threads, youtube) are small files on it: a spec and an input. +// +// A media task is a STEP on a done iteration (recorded in its `steps`, its +// status left as it is), run by `runMediaTask(spec, input, deps)`: +// +// 1. the iteration's project: its `video.manifest.json` (none: the task +// cannot start) and its report (the project's `report.json`, else the +// iteration's source report); +// 2. `spec.units(ctx)`: one UNIT per field to draft -- its `target` +// (`{ entry?, field }`, drafted.mjs) and whatever evidence the prompt +// needs -- or a skip record (`{ id, skipped }`) for one that is not +// drafted and says why. `input.entries` keeps only the units it names +// (by entry id or unit id). A unit whose field has a value is skipped +// unless `input.force` (then an operator's field is drafted anyway, and +// the refused draft becomes an ALTERNATIVE); +// 3. per unit, at most two attempts: `structuredAnswer` against +// `spec.schema(unit)` with `spec.system` / `spec.user` (the second ask +// carries what the first was refused for), `spec.parse` (a throw is a +// hard failure of that attempt), then the task's CODE checks +// (`spec.check` → `{ hard, soft }`: counts, lengths, ids that exist, +// grounding). A clean first attempt is not asked again; +// 4. the better attempt (`spec.score`, default fewest hard then fewest soft +// problems); one still failing a hard check goes to `spec.repair` (narrate +// removes the failing sentences), and a unit with no clean value is not +// written; +// 5. the manifest is snapshotted (`revisions/<stamp>-auto-before-<op>`) and +// each kept value is written through `applyDraft` (drafted.mjs) -- or +// `spec.apply`, which must call it -- with the provenance +// `{ task, model, at, iteration, attempt }`. A field that is the +// operator's is NEVER replaced: its value goes to `alternatives[]`; +// 6. orphan marks dropped, the manifest written whole (only when something +// was applied), and `<task>-draft.json` (`spec.draftFile`) written beside +// it: every unit's attempts and checks, the kept value, what was applied, +// and the alternatives (earlier runs' carried over, newest five per field). +// +// Q0 binds every spec: counts and lengths are enforced in `check`, never only +// asked for; prompts carry rules, never worked examples; a local prompt stays +// under 8k tokens. Progress: `h.progress` counts the units drafted of those +// to draft (`spec.progressMetric`, default "entries"; narrate's "cards"). +// Batching (`spec.batch`, release 28 M2) asks several units at once. + +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { structuredAnswer } from "../../../llm"; +import { readIteration, readIterationFile, reportSourceOf } from "../../iterations"; +import { + applyDraft, + makeProvenance, + ownerOf, + pruneDrafted, + reviewAddress, + stableStringify, + valueKey, + type ApplyDraftResult, + type DraftTarget, + type Provenance, +} from "../../drafted.mjs"; +import { groundingInputOf, type GroundingInput } from "../grounding"; +import type { VideoManifest } from "../videoOps"; +import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project"; +import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export type { DraftTarget, Provenance } from "../../drafted.mjs"; + +/** What every media task takes (its own input extends it). */ +export type MediaTaskInput = { + article: string; + n: number; + model: string; + projectsRoot: string; + // Only these units: an entry id (every unit on it) or a unit id. + entries?: string[]; + // Re-draft a field that has a value. An operator's field is still never + // replaced: the draft becomes an alternative. + force?: boolean; + maxUsd?: number; + jobId?: string; +}; + +/** A report as a media task reads it (report.json's shape, loosely). */ +export type MediaReport = Record<string, any>; + +/** What a spec is handed: the run, the project, the manifest as read, the report. */ +export type MediaContext<I extends MediaTaskInput = MediaTaskInput> = { + handle: TaskHandle; + input: I; + dir: string; + manifest: VideoManifest; + report: MediaReport; + // groundingInputOf(report): what a spec's check grounds numbers and names in. + grounding: GroundingInput; +}; + +/** One field to draft. A spec's own units extend it with their evidence. */ +export type MediaUnit = { id: string; target: DraftTarget; label?: string }; + +/** A unit that is not drafted, and why (recorded in the draft file). */ +export type MediaSkip = { id: string; skipped: string }; + +/** One attempt: the value parsed (null: none), and the code checks' findings. */ +export type MediaAttempt<V> = { value: V | null; hard: string[]; soft: string[] }; + +/** A refused value kept for the operator: umtool shows it under its field with "Use this". */ +export type DraftAlternative = { + target: DraftTarget; + value: unknown; + provenance: Provenance; + reason: "operator" | "drafted" | "missing"; +}; + +/** `<task>-draft.json`: the run's record. */ +export type DraftFile = { + task: string; + model: string; + at: string; + article: string; + iteration: number; + units: Record<string, Record<string, unknown>>; + checks: { name: string; ok: boolean; detail?: string }[]; + alternatives: DraftAlternative[]; +}; + +export type MediaTaskSpec<U extends MediaUnit, V, I extends MediaTaskInput = MediaTaskInput> = { + // The task's name: the step's, the provenance's, the default file's. + task: string; + // Default `<task>-draft.json`. + draftFile?: string; + // The snapshot's op (`auto-before-<op>`); default the task. + snapshotOp?: string; + // The iteration check's name; default the task. + checkName?: string; + // turns.jsonl's `kind` per attempt; default the task. + turnKind?: string; + // Words for the summary: "<n> <noun>(s) <verb>"; defaults "field", "drafted". + noun?: string; + verb?: string; + units(ctx: MediaContext<I>): (U | MediaSkip)[] | Promise<(U | MediaSkip)[]>; + schema(unit: U, ctx: MediaContext<I>): object; + system(unit: U, ctx: MediaContext<I>): string; + user(unit: U, ctx: MediaContext<I>): string; + // The model's answer to a value; a throw is that attempt's hard failure. + parse(answer: unknown, unit: U, ctx: MediaContext<I>): V; + // The code checks: `hard` refuses the value, `soft` is a flag. + check(value: V, unit: U, ctx: MediaContext<I>): { hard: string[]; soft: string[] }; + // Lower is better, compared element by element. Default [hard, soft]. + score?(a: MediaAttempt<V>): number[]; + // When the best attempt still fails a hard check: a clean value made from + // the attempts (never a new one), or null. Its own `hard` must be empty. + repair?(attempts: MediaAttempt<V>[], unit: U, ctx: MediaContext<I>): MediaAttempt<V> | null; + // The re-ask's added words; default "Your last draft was refused for: …". + retry?(last: MediaAttempt<V>, unit: U): string; + // The field's value for a kept value (default: the value itself) -- what is + // written, and what an alternative holds (umtool's "Use this" writes it as is). + // Narrate's is the card's narration object with the new words. + toField?(value: V, unit: U, manifest: VideoManifest): unknown; + // After a value is applied (narrate: the card's `seconds` to "auto"). + afterApply?(manifest: VideoManifest, unit: U): void; + // Write the kept value instead of `applyDraft(manifest, { ...unit.target, + // value: toField(value), provenance, force })`; an override must go through + // applyDraft. + apply?(manifest: VideoManifest, unit: U, value: unknown, provenance: Provenance, force: boolean, ctx: MediaContext<I>): ApplyDraftResult; + // A line for the log per unit kept; default the value as JSON. + describe?(value: V, unit: U): string; + // Who owns the unit's field, for the skip (default drafted.mjs `ownerOf`): + // "empty" is drafted, anything else only with `force`. The cut's: a + // timeline the converter made is nobody's. + owner?(manifest: VideoManifest, unit: U, ctx: MediaContext<I>): "empty" | "drafted" | "operator"; + // What the job's progress counts (release 28 F3); default "entries". + progressMetric?: "cards" | "entries"; + // Several units in one ask (the local model's 8k prompt holds more than + // one on-screen line). Without it, one ask per unit. + batch?: MediaBatch<U, I>; +}; + +/** + * Units asked together: `group` cuts the units to draft into asks (each list + * one ask, in order); `split` gives each unit's own answer out of the + * batch's, keyed by unit id (one with none is that attempt's hard failure), + * which `parse` and `check` then judge as a single unit's. A re-ask carries + * only the units the first ask did not settle cleanly (`retry`'s words). + */ +export type MediaBatch<U extends MediaUnit, I extends MediaTaskInput = MediaTaskInput> = { + group(units: U[], ctx: MediaContext<I>): U[][]; + schema(units: U[], ctx: MediaContext<I>): object; + system(units: U[], ctx: MediaContext<I>): string; + user(units: U[], ctx: MediaContext<I>): string; + split(answer: unknown, units: U[], ctx: MediaContext<I>): Record<string, unknown>; + retry?(failing: { id: string; last: MediaAttempt<unknown> }[]): string; +}; + +export const isSkip = (u: MediaUnit | MediaSkip): u is MediaSkip => typeof (u as MediaSkip).skipped === "string"; + +/** Default score: fewest hard problems, then fewest soft ones. */ +export const defaultScore = <V>(a: MediaAttempt<V>) => [a.hard.length, a.soft.length]; + +const lexLess = (a: number[], b: number[]) => { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i] ?? 0; + const y = b[i] ?? 0; + if (x !== y) return x < y; + } + return false; +}; + +/** The attempts best first (a stable sort: the earlier of two equals first). */ +export function rankAttempts<V>(attempts: MediaAttempt<V>[], score: (a: MediaAttempt<V>) => number[] = defaultScore): MediaAttempt<V>[] { + return attempts + .map((a, i) => ({ a, i, s: score(a) })) + .sort((x, y) => (lexLess(x.s, y.s) ? -1 : lexLess(y.s, x.s) ? 1 : x.i - y.i)) + .map((x) => x.a); +} + +export const draftFileName = (task: string) => `${task}-draft.json`; + +/** The newest alternatives kept per field. */ +export const ALTERNATIVES_PER_FIELD = 5; + +const targetKey = (t: DraftTarget) => reviewAddress({ entry: t.entry ?? null, field: t.field }); + +/** A project's draft file, or null (absent or unreadable). */ +export async function readDraftFile(dir: string, file: string): Promise<DraftFile | null> { + try { + const j = JSON.parse(await readFile(path.join(dir, file), "utf8")); + return j && typeof j === "object" && !Array.isArray(j) ? (j as DraftFile) : null; + } catch { + return null; + } +} + +/** Earlier alternatives, then these; one per field and value, the newest ALTERNATIVES_PER_FIELD per field. */ +export function mergeAlternatives(earlier: readonly DraftAlternative[], now: readonly DraftAlternative[]): DraftAlternative[] { + const seen = new Set<string>(); + const out: DraftAlternative[] = []; + // Newest first while picking, so a repeat keeps its newest copy. + for (const a of [...now].reverse().concat([...earlier].reverse())) { + if (!a || typeof a !== "object" || !a.target || typeof a.target.field !== "string") continue; + const k = `${targetKey(a.target)}\u0000${valueKey(a.value)}`; + if (seen.has(k)) continue; + if (out.filter((x) => targetKey(x.target) === targetKey(a.target)).length >= ALTERNATIVES_PER_FIELD) continue; + seen.add(k); + out.push(a); + } + return out.reverse(); +} + +async function writeJsonAtomic(file: string, value: unknown) { + const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); + await rename(tmp, file); +} + +/** The project, the manifest and the report a media task reads. */ +export async function loadMediaContext<I extends MediaTaskInput>(h: TaskHandle, input: I): Promise<MediaContext<I>> { + const it = (await readIteration(h.article, h.n, h.paths))!; + const dir = projectDirOf(it, input.projectsRoot); + const manifest = await readManifest(dir); + if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`); + let report = (await readProjectReport(dir)) as MediaReport | null; + if (!report) { + const from = await reportSourceOf(h.article, h.n, h.paths); + const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths); + report = text ? (JSON.parse(text) as MediaReport) : null; + } + if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to draft from`); + return { handle: h, input, dir, manifest, report, grounding: groundingInputOf(report) }; +} + +const refusedFor = <V>(last: MediaAttempt<V>) => + `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`; + +const batchRefusedFor = <V>(failing: { id: string; last: MediaAttempt<V> }[]) => + `\n\nYour last drafts were refused: ${failing.map((f) => `${f.id}: ${[...f.last.hard, ...f.last.soft].join("; ")}`).join(" | ")}. ` + + "Write those again without those problems."; + +// At most two asks per unit: alone (the spec's schema, system and user), or +// with the others of its batch (`spec.batch`); the second ask carries only the +// units the first did not settle cleanly, and what each was refused for. +async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( + spec: MediaTaskSpec<U, V, I>, + h: TaskHandle, + ctx: MediaContext<I>, + group: U[], +): Promise<Map<string, MediaAttempt<V>[]>> { + const { deps } = h; + const out = new Map<string, MediaAttempt<V>[]>(group.map((u) => [u.id, []])); + const judge = (raw: unknown, u: U): MediaAttempt<V> => { + try { + const value = spec.parse(raw, u, ctx); + return { value, ...spec.check(value, u, ctx) }; + } catch (e) { + return { value: null, hard: [(e as Error).message], soft: [] }; + } + }; + const ask = (system: string, user: string, schema: object) => + structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal }); + const b = spec.batch; + // Computed once per unit (a batch: once for the whole), as narrate always did. + const first = b ? { system: b.system(group, ctx), user: b.user(group, ctx) } : null; + const single = new Map(b ? [] : group.map((u) => [u.id, { system: spec.system(u, ctx), user: spec.user(u, ctx) }])); + let pending = group; + for (let k = 0; k < 2 && pending.length; k++) { + deps.signal?.throwIfAborted(); + if (!b) { + const u = pending[0]!; + const list = out.get(u.id)!; + const extra = list.length ? (spec.retry ?? refusedFor)(list.at(-1)!, u) : ""; + let a: MediaAttempt<V>; + try { + a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx)), u); + } catch (e) { + if (deps.signal?.aborted) throw e; + list.push({ value: null, hard: [(e as Error).message], soft: [] }); + continue; + } + list.push(a); + h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); + if (!a.hard.length && !a.soft.length) pending = []; + continue; + } + // A batch: the first ask is the whole group's; a re-ask names only the + // units still refused or flagged. + const failing = pending.map((u) => ({ id: u.id, last: out.get(u.id)!.at(-1) })).filter((f): f is { id: string; last: MediaAttempt<V> } => !!f.last); + const user = (k === 0 ? first!.user : b.user(pending, ctx)) + (failing.length ? (b.retry ?? batchRefusedFor)(failing) : ""); + const system = k === 0 ? first!.system : b.system(pending, ctx); + let answers: Record<string, unknown>; + try { + answers = b.split(await ask(system, user, b.schema(pending, ctx)), pending, ctx); + } catch (e) { + if (deps.signal?.aborted) throw e; + for (const u of pending) out.get(u.id)!.push({ value: null, hard: [(e as Error).message], soft: [] }); + continue; + } + for (const u of pending) { + const a: MediaAttempt<V> = + answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); + out.get(u.id)!.push(a); + h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); + } + pending = pending.filter((u) => { + const last = out.get(u.id)!.at(-1)!; + return last.hard.length > 0 || last.soft.length > 0; + }); + } + return out; +} + +/** + * Run one media task over an iteration (the shape above). The result is the + * step's: `done` when at least one unit kept a clean value (applied, or kept + * as an alternative), else `failed`. + */ +export async function runMediaTask<U extends MediaUnit, V, I extends MediaTaskInput>( + spec: MediaTaskSpec<U, V, I>, + input: I, + deps: TaskDeps, +): Promise<TaskResult> { + return runOnIteration( + { + article: input.article, + n: input.n, + deps, + maxUsd: input.maxUsd, + step: { task: spec.task, model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) }, + }, + (h) => mediaBody(spec, h, input), + ); +} + +async function mediaBody<U extends MediaUnit, V, I extends MediaTaskInput>( + spec: MediaTaskSpec<U, V, I>, + h: TaskHandle, + input: I, +): Promise<TaskOutcome> { + const { deps } = h; + const now = () => deps.now?.() ?? new Date(); + const ctx = await loadMediaContext(h, input); + const { dir, manifest } = ctx; + const file = spec.draftFile ?? draftFileName(spec.task); + const noun = spec.noun ?? "field"; + const verb = spec.verb ?? "drafted"; + const score = spec.score ?? defaultScore; + const only = input.entries?.length ? new Set(input.entries) : null; + const units: Record<string, Record<string, unknown>> = {}; + const kept: { unit: U; value: V; attempt: 1 | 2 }[] = []; + h.log(`${spec.task} on i${h.n}, ${input.model} (${dir})`); + + // The units to draft: the ones asked for, with a field nobody owns (or + // `force`); the rest are recorded as skipped. + const eligible: U[] = []; + for (const u of await spec.units(ctx)) { + if (only && !only.has(u.id) && !(!isSkip(u) && u.target.entry && only.has(u.target.entry))) continue; + if (isSkip(u)) { + units[u.id] = { skipped: u.skipped }; + continue; + } + const owner = spec.owner ? spec.owner(manifest, u, ctx) : ownerOf(manifest, u.target); + if (owner !== "empty" && !input.force) { + units[u.id] = { target: u.target, skipped: `has a value (${owner === "operator" ? "the operator's" : "a draft"}); force re-drafts it` }; + continue; + } + eligible.push(u); + } + + // Progress (release 28 F3): the units drafted of those to draft. + const metric = spec.progressMetric ?? "entries"; + let drafted = 0; + h.progress({ metric, current: 0, total: eligible.length }); + const groups = spec.batch ? spec.batch.group(eligible, ctx).filter((g) => g.length) : eligible.map((u) => [u]); + for (const group of groups) { + const attemptsOf = await askUnits(spec, h, ctx, group); + for (const u of group) { + const attempts = attemptsOf.get(u.id) ?? []; + const ranked = rankAttempts(attempts, score); + let chosen: MediaAttempt<V> | null = ranked[0] ?? null; + let attemptNo = (chosen ? attempts.indexOf(chosen) + 1 : 1) as 1 | 2; + if (chosen && chosen.hard.length) { + const fixed = spec.repair?.(attempts, u, ctx) ?? null; + if (fixed && !fixed.hard.length && fixed.value !== null) { + chosen = fixed; + attemptNo = Math.min(2, attempts.length) as 1 | 2; + } + } + units[u.id] = { target: u.target, ...(u.label ? { label: u.label } : {}), attempts, chosen }; + drafted++; + if (!chosen || chosen.hard.length || chosen.value === null) { + h.log(` ${u.id}: NOT written — ${chosen?.hard.join("; ") ?? "no draft"}`); + continue; + } + kept.push({ unit: u, value: chosen.value, attempt: attemptNo }); + const said = spec.describe ? spec.describe(chosen.value, u) : JSON.stringify(chosen.value); + h.log(` ${u.id}: ${said}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`); + } + h.progress({ metric, current: drafted, total: eligible.length }); + } + + const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt<V> | null | undefined)?.hard?.length).length; + const at = now(); + const alternatives: DraftAlternative[] = []; + const next = JSON.parse(JSON.stringify(manifest)) as VideoManifest; + let applied = 0; + for (const k of kept) { + const provenance = makeProvenance({ task: spec.task, model: input.model, at, iteration: h.n, attempt: k.attempt }); + const value = spec.toField ? spec.toField(k.value, k.unit, next) : k.value; + const res = spec.apply + ? spec.apply(next, k.unit, value, provenance, !!input.force, ctx) + : applyDraft(next, { ...k.unit.target, value, provenance, force: !!input.force }); + units[k.unit.id]!.applied = res.applied ? "applied" : res.reason; + if (res.applied) { + applied++; + spec.afterApply?.(next, k.unit); + } else alternatives.push({ target: k.unit.target, value, provenance, reason: res.reason }); + } + pruneDrafted(next); + let snap: string | null = null; + if (applied) { + snap = await snapshotManifest(dir, spec.snapshotOp ?? spec.task, at); + await writeManifest(dir, next); + } + h.check({ + name: spec.checkName ?? spec.task, + ok: refused === 0, + detail: + `${applied} ${noun}(s) ${verb}` + + (alternatives.length ? `, ${alternatives.length} kept as an alternative (the field is the operator's)` : "") + + (refused ? `, ${refused} not written (a hard check)` : ""), + }); + const earlier = (await readDraftFile(dir, file))?.alternatives ?? []; + const record: DraftFile = { + task: spec.task, + model: input.model, + at: at.toISOString(), + article: h.article, + iteration: h.n, + units, + checks: h.checks, + alternatives: mergeAlternatives(Array.isArray(earlier) ? earlier : [], alternatives), + }; + await writeJsonAtomic(path.join(dir, file), record).catch((e) => h.log(`${file} not written: ${(e as Error).message}`)); + if (!kept.length) return { status: "failed", summary: `no ${noun} ${verb} (see ${file})` }; + return { + status: "done", + summary: + `${applied} ${noun}(s) ${verb}` + + (alternatives.length ? `, ${alternatives.length} as alternatives (see ${file})` : "") + + (snap ? ` (undo: ${snap})` : ""), + }; +} + +// Exported for tests and for a spec that compares values the way the writer does. +export { stableStringify, valueKey }; diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts @@ -11,16 +11,17 @@ // failing a hard check loses its failing sentences, and a card with nothing // left is not written. The manifest is snapshotted, then written whole; every // draft and its checks go to the project's narration-draft.json. +// +// Release 28 (M0): a spec on the media task scaffold (./media.ts). A narration +// it writes carries its drafted mark (`entry.drafted.narration`), and a card +// whose narration is the operator's (words with no mark) is never replaced, +// even with `force`: the draft goes to narration-draft.json's alternatives. -import { writeFile } from "node:fs/promises"; -import path from "node:path"; -import { structuredAnswer } from "../../../llm"; -import { readIteration, reportSourceOf, readIterationFile } from "../../iterations"; +import { entriesWithId } from "../../drafted.mjs"; import { NARRATION_HARD_RULE, NARRATION_TASTE, NARRATION_WRITING_RULES, rulesForModel } from "../authoringRules"; import { checkNarration, groundingInputOf, sentencesOf, type GroundingInput } from "../grounding"; import type { ManifestEntry } from "../videoOps"; -import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project"; -import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +import { runMediaTask, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import type { TaskDeps, TaskResult } from "./types"; export const TITLE_WORDS = 35; @@ -28,17 +29,9 @@ export const CHAPTER_WORDS = 45; // A draft this far over its limit is refused outright. export const OVER_LIMIT_SLACK = 10; -export type NarrateInput = { - article: string; - n: number; - model: string; - projectsRoot: string; +export type NarrateInput = MediaTaskInput & { // Only these card ids (default: every title and chapter card). cards?: string[]; - // Re-draft a card that has narration already. - force?: boolean; - maxUsd?: number; - jobId?: string; }; type Section = { title?: string; body?: string | null; claims?: { text?: string; citations?: string[] }[] | null }; @@ -118,97 +111,82 @@ export function chooseDraft(attempts: Attempt[], g: GroundingInput, limit: numbe return best; } -export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> { - return runOnIteration( - { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, step: { task: "narrate", model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } }, - (h) => narrateBody(h, input), - ); -} - -async function narrateBody(h: TaskHandle, input: NarrateInput): Promise<TaskOutcome> { - const { deps } = h; - const it = (await readIteration(h.article, h.n, h.paths))!; - const dir = projectDirOf(it, input.projectsRoot); - const manifest = await readManifest(dir); - if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`); - let report = (await readProjectReport(dir)) as ReportLike | null; - if (!report) { - const from = await reportSourceOf(h.article, h.n, h.paths); - const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths); - report = text ? (JSON.parse(text) as ReportLike) : null; - } - if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to narrate from`); - const base = groundingInputOf(report); - const only = input.cards?.length ? new Set(input.cards) : null; - const drafts = new Map<string, string>(); - const record: Record<string, unknown> = {}; - h.log(`narrating i${h.n} on ${input.model} (${dir})`); +// A unit: one card, its limit and evidence. +type NarrateUnit = MediaUnit & { card: ManifestEntry; limit: number; g: GroundingInput; ctxText: string }; - for (const card of manifest.timeline) { - if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue; - if (only && !only.has(card.id)) continue; - if (card.narration?.text && !input.force) continue; - if ((card.heading ?? "").trim().toLowerCase() === "coverage") { - record[card.id] = { skipped: "the Coverage card is not narrated (its numbers are on the page)" }; - continue; - } - const ctx = cardContext(card, report); - if (!ctx) { - record[card.id] = { skipped: "no section in the report matches this card's heading" }; - continue; - } - const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS; - const g: GroundingInput = { ...base, quotes: ctx.quotes }; - const system = narrationSystem(limit); - const user = `Card heading on screen: ${card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${ctx.text}\n\nWrite this card's narration.`; - const attempts: Attempt[] = []; - for (let k = 0; k < 2; k++) { - deps.signal?.throwIfAborted(); - const extra = attempts.length - ? `\n\nYour last draft was refused for: ${[...attempts.at(-1)!.hard, ...attempts.at(-1)!.soft].join("; ")}. Write it again without those problems.` - : ""; - let text = ""; - try { - const ans = await structuredAnswer<{ text?: unknown }>({ - llm: deps.llm, - model: input.model, - system, - user: user + extra, - schema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, - meter: h.meter, - signal: deps.signal, - }); - text = String(ans.text ?? "").replace(/\s+/g, " ").trim().replace(/^"+|"+$/g, ""); - } catch (e) { - if (deps.signal?.aborted) throw e; - attempts.push({ text: "", hard: [(e as Error).message], soft: [] }); +/** Narrate as a media task (./media.ts): one unit per title and chapter card. */ +export const NARRATE_SPEC: MediaTaskSpec<NarrateUnit, string, NarrateInput> = { + task: "narrate", + // Its audit file kept its release 27 name. + draftFile: "narration-draft.json", + snapshotOp: "narration", + checkName: "narration", + turnKind: "narration", + noun: "card", + verb: "narrated", + progressMetric: "cards", + units(ctx) { + const out: (NarrateUnit | MediaSkip)[] = []; + const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null; + const seen = new Set<string>(); + for (const card of ctx.manifest.timeline) { + if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue; + if (only && !only.has(card.id)) continue; + if (seen.has(card.id)) continue; + seen.add(card.id); + if ((card.heading ?? "").trim().toLowerCase() === "coverage") { + out.push({ id: card.id, skipped: "the Coverage card is not narrated (its numbers are on the page)" }); continue; } - const a = checkDraft(text, g, limit); - attempts.push(a); - h.turns([{ kind: "narration", card: card.id, attempt: k + 1, ...a }]); - if (!a.hard.length && !a.soft.length) break; - } - const chosen = chooseDraft(attempts, g, limit); - record[card.id] = { heading: card.heading, attempts, chosen }; - if (chosen.hard.length) { - h.log(` ${card.id}: NOT written — ${chosen.hard.join("; ")}`); - continue; + const c = cardContext(card, ctx.report as ReportLike); + if (!c) { + out.push({ id: card.id, skipped: "no section in the report matches this card's heading" }); + continue; + } + const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS; + out.push({ + id: card.id, + target: { entry: card.id, field: "narration" }, + label: card.heading, + card, + limit, + g: { ...ctx.grounding, quotes: c.quotes }, + ctxText: c.text, + }); } - drafts.set(card.id, chosen.text); - h.log(` ${card.id}: ${chosen.text}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`); - } - await writeFile(path.join(dir, "narration-draft.json"), `${JSON.stringify(record, null, 2)}\n`).catch(() => {}); - const refused = Object.values(record).filter((r) => (r as { chosen?: Attempt }).chosen?.hard.length).length; - h.check({ name: "narration", ok: refused === 0, detail: `${drafts.size} card(s) drafted${refused ? `, ${refused} not written (a hard check)` : ""}` }); - if (!drafts.size) return { status: "failed", summary: "no card narrated (see narration-draft.json)" }; - const snap = await snapshotManifest(dir, "narration", deps.now?.() ?? new Date()); - for (const e of manifest.timeline) { - const text = drafts.get(e.id); - if (e.type !== "card" || !text) continue; - e.narration = { ...(e.narration && typeof e.narration === "object" ? e.narration : {}), text }; - e.seconds = "auto"; - } - await writeManifest(dir, manifest); - return { status: "done", summary: `${drafts.size} card(s) narrated${snap ? ` (undo: ${snap})` : ""}` }; + return out; + }, + schema: () => ({ type: "object", properties: { text: { type: "string" } }, required: ["text"] }), + system: (u) => narrationSystem(u.limit), + user: (u) => + `Card heading on screen: ${u.card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${u.ctxText}\n\nWrite this card's narration.`, + parse: (answer) => + String((answer as { text?: unknown } | null)?.text ?? "") + .replace(/\s+/g, " ") + .trim() + .replace(/^"+|"+$/g, ""), + check(text, u) { + const a = checkDraft(text, u.g, u.limit); + return { hard: a.hard, soft: a.soft }; + }, + repair(attempts, u) { + const chosen = chooseDraft( + attempts.map((a) => ({ text: a.value ?? "", hard: a.hard, soft: a.soft })), + u.g, + u.limit, + ); + return chosen.hard.length ? null : { value: chosen.text, hard: [], soft: chosen.soft }; + }, + toField(text, u, manifest) { + const cur = entriesWithId(manifest, u.card.id)[0]?.narration; + return { ...(cur && typeof cur === "object" ? cur : {}), text }; + }, + afterApply(manifest, u) { + for (const e of entriesWithId(manifest, u.card.id)) e.seconds = "auto"; + }, + describe: (text) => text, +}; + +export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(NARRATE_SPEC, input, deps); } diff --git a/common/lib/report/draft/tasks/onscreen.test.ts b/common/lib/report/draft/tasks/onscreen.test.ts @@ -0,0 +1,176 @@ +// TASK onscreen (release 28 M2) over the S0 kit's manifests and the basic +// report, against the fake ollama: several clips in one ask, the re-ask only +// for the refused, each code check refusing what it should, the better of two +// kept, a clip with no clean draft not written, the operator's text kept and +// the draft an alternative. Real iterations store and project in a temp dir. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { checkOnscreen, isTitleCase, isVerbatimOf, onscreen, onscreenBatches, quotedParts, titleAsSentence, ONSCREEN_SPEC } from "./onscreen"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +let tmp: string; +let ol: FakeOllama; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "onscreen-task-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const progress: unknown[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + progress: (p) => progress.push(p), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "onscreen-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, paths, deps, lines, progress, manifestNow, draft, input, report }; +} + +const entry = (m: { timeline: { id: string }[] }, id: string) => m.timeline.find((e) => e.id === id) as Record<string, any>; + +test("onscreen, the recorded run: six clips in one ask, the four refused asked again, the better of two kept, a clip with none clean not written", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const p = await project(m); + const r = await kit("runs/onscreen.json"); + const asked: string[] = []; + ol.push(...r.turns.map((t: unknown) => (body: { messages: { content: string }[] }) => (asked.push(body.messages.at(-1)!.content), t))); + const out = await onscreen(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.equal(asked.length, 2, "one ask for six clips, one re-ask"); + assert.match(asked[0]!, /### Clip c01[\s\S]*### Clip c06/); + assert.doesNotMatch(asked[1]!, /### Clip c01|### Clip c05/); + assert.match(asked[1]!, /Your last drafts were refused: c02: the title has quotation marks/); + assert.match(out.summary, /^5 clip\(s\) titled \(undo: /); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, { title: "She will not sell to a chain", subtitle: '"I would never sell the bakery to a chain"' }); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied", subtitle: '"we never said that about the old oven"' }); + assert.deepEqual(entry(after, "c03").onscreen, { title: "Who paid for the mixer", subtitle: '"I paid for the new mixer myself"' }); + assert.equal(entry(after, "c04").onscreen.title, "Out of the contest this year"); + assert.equal(entry(after, "c04").drafted.onscreen.attempt, 2); + assert.equal(entry(after, "c05").drafted.onscreen.attempt, 1); + assert.equal(entry(after, "c06").onscreen, undefined, "no clean draft: not written"); + const file = await p.draft(); + const c06 = file.units.c06 as { attempts: { hard: string[] }[] }; + assert.match(c06.attempts[0]!.hard.join(), /number 2024 is not in the clip's evidence/); + assert.match(c06.attempts[1]!.hard.join(), /name “Marco” is not in the clip's evidence/); + const c04 = file.units.c04 as { attempts: { hard: string[] }[] }; + assert.match(c04.attempts[0]!.hard.join(), /the title is \d+ characters \(at most 60\)/); + const c03 = file.units.c03 as { attempts: { hard: string[] }[] }; + assert.match(c03.attempts[0]!.hard.join(), /the subtitle quotes “I bought the mixer”, which is not the clip's quote word for word/); + assert.deepEqual(p.progress, [ + { metric: "entries", current: 0, total: 6 }, + { metric: "entries", current: 6, total: 6 }, + ]); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.checks!.find((c) => c.name === "onscreen")!.ok, false, "a clip not written fails the check"); + assert.equal(it.steps.find((s) => s.task === "onscreen")!.status, "done"); +}); + +test("onscreen's checks, each alone", () => { + const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" }; + const hard = (title: string, subtitle?: string) => checkOnscreen({ title, ...(subtitle ? { subtitle } : {}) }, u).hard; + assert.deepEqual(hard("Not for sale", "The baker on a chain"), []); + assert.deepEqual(hard("Not for sale", '"never sell the bakery"'), [], "a verbatim part of the quote"); + assert.deepEqual(hard("Not for sale", "“Never sell the bakery,” on Bread day"), [], "curly marks, case and punctuation aside"); + assert.match(hard("x".repeat(61)).join(), /the title is 61 characters \(at most 60\)/); + assert.match(hard("Not for sale", "y".repeat(91)).join(), /the subtitle is 91 characters \(at most 90\)/); + assert.match(hard("Not for\nsale").join(), /the title is more than one line/); + assert.match(hard('"Not for sale"').join(), /the title has quotation marks/); + assert.match(hard("The ‘chain’ line").join(), /the title has quotation marks/); + assert.deepEqual(hard("She won't sell"), [], "an apostrophe is not a quotation"); + assert.match(hard("Not for sale", '"never sell it"').join(), /quotes “never sell it”, which is not the clip's quote word for word/); + assert.match(hard("Not for sale", 'She said "never sell').join(), /quotation marks do not pair up/); + assert.match(hard("Not for sale", "Sold in 2025").join(), /number 2025 is not in the clip's evidence/); + assert.deepEqual(hard("Not for sale", "Bread day, 2026"), []); + assert.match(hard("Not for sale", "Her friend Marco agrees").join(), /name “Marco” is not in the clip's evidence/); + assert.match(hard("I will never sell").join(), /the narrator is third person/); + assert.deepEqual(quotedParts('a "b c" d «e»'), { parts: ["b c", "e"], balanced: true }); + assert.equal(isVerbatimOf("sell the", "I would never sell the bakery"), true); + assert.equal(isVerbatimOf("sel the", "I would never sell the bakery"), false, "whole words"); +}); + +test("onscreen: a Title Case title passes as its sentence case; an unknown name in one still fails (release 28 M9 ruling)", () => { + const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nClaim: The baker says she will not sell to a chain.\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" }; + const hard = (title: string) => checkOnscreen({ title }, u).hard; + // Ordinary Title Case: every word capitalised, none a name. + assert.deepEqual(hard("The Baker Will Never Sell The Bakery"), []); + assert.deepEqual(hard("She Refuses To Sell To A Chain"), []); + assert.deepEqual(hard("Not For Sale, Says The Baker"), []); + // A name the evidence has keeps its capital and passes. + assert.deepEqual(hard("Synth Kitchen Will Not Sell"), []); + // A name it lacks still fails, Title Case or not. + assert.match(hard("Why Marco Says The Bakery Stays").join(), /name “Marco” is not in the clip's evidence/); + assert.match(hard("The Bakery Stays, Says Marco").join(), /name “Marco” is not in the clip's evidence/); + assert.match(hard("The bakery stays, says Marco").join(), /name “Marco” is not in the clip's evidence/); + assert.equal(isTitleCase("The Baker Will Never Sell"), true); + assert.equal(isTitleCase("The baker will never sell"), false); + assert.equal(isTitleCase("Bakery"), false, "one word is not a case"); + assert.equal(titleAsSentence("Never Sell The Bakery To Marco", u.evidence), "Never sell the bakery to Marco"); + assert.equal(titleAsSentence("The baker said no", u.evidence), "The baker said no", "a sentence-case title as it is"); +}); + +test("onscreen: the operator's text kept (forced, the draft an alternative); entries asks only those; batches fit the local cap", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const p = await project(full); + // c01 and c04 hold the operator's text: skipped unforced, so c02 alone is asked. + ol.push(jsonReply({ entries: [{ id: "c02", title: "The oven story, denied", subtitle: "" }] })); + const one = await onscreen(p.input({ entries: ["c01", "c02", "c04"] }), p.deps); + assert.equal(one.status, "done", `${one.summary}\n${p.lines.join("\n")}`); + const f1 = await p.draft(); + assert.deepEqual(Object.keys(f1.units).sort(), ["c01", "c02", "c04"]); + assert.match(String(f1.units.c01!.skipped), /the operator's/); + // Forced over c01: its words stand, the draft is an alternative. + ol.push(jsonReply({ entries: [{ id: "c01", title: "She will not sell to a chain", subtitle: "" }] })); + const forced = await onscreen(p.input({ entries: ["c01"], force: true }), p.deps); + assert.match(forced.summary, /^0 clip\(s\) titled, 1 as alternatives/); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, entry(full, "c01").onscreen); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied" }); + const alt = (await p.draft()).alternatives; + assert.deepEqual(alt.map((a) => [a.target.entry, a.reason, (a.value as { title: string }).title]), [["c01", "operator", "She will not sell to a chain"]]); + assert.equal(ol.remaining(), 0); + + // Batches: at most eight, and as many as fit a small cap. + const ctx = { manifest: full, report: p.report, input: p.input(), handle: { deps: p.deps } } as never; + const units = (await ONSCREEN_SPEC.units(ctx)) as never[]; + const many = Array.from({ length: 20 }, (_, i) => ({ ...(units[i % units.length] as object), id: `x${i}` })) as never[]; + assert.deepEqual(onscreenBatches(many, ctx).map((b) => b.length), [8, 8, 4]); + const small = { ...(ctx as object), handle: { deps: { ...p.deps, llm: { ollama: { baseUrl: ol.url, promptCapTokens: 1100 } } } } } as never; + const sizes = onscreenBatches(many, small).map((b) => b.length); + assert.ok(sizes.every((n) => n >= 1 && n < 8) && sizes.reduce((a, b) => a + b, 0) === 20, String(sizes)); +}); diff --git a/common/lib/report/draft/tasks/onscreen.ts b/common/lib/report/draft/tasks/onscreen.ts @@ -0,0 +1,264 @@ +// TASK onscreen — each clip's on-screen title and subtitle (release 28 M2). +// A STEP on a done iteration (./media.ts): one unit per clip entry (or the +// `entries` asked for), the field `onscreen.{title, subtitle}`. +// +// The evidence of a clip is what the report says of it: the claim it cites +// (its text and verdict), its section, its quote, its source and date. Several +// clips are asked in one call (`batch`), as many as fit the local model's +// prompt cap (at most ONSCREEN_BATCH_MAX); a re-ask carries only the clips +// refused. Code checks every line: the title at most 60 characters, the +// subtitle at most 90, one line each; the title quotes nothing, and the +// subtitle quotes only words of the clip's own quote, verbatim (inside +// quotation marks); no name or number the evidence does not have; and the +// narrator's third person outside a quotation. The better of two attempts is +// kept; a clip whose on-screen text is the operator's is never replaced. + +import { strictNormalize } from "../../../citations/verify"; +import { CHARS_PER_TOKEN, ollamaConfigOf, promptCapOf, providerOf, structuredPromptEstimate } from "../../../llm"; +import { firstPersonProblems, groundedProblems } from "../grounding"; +import type { ManifestEntry } from "../videoOps"; +import { cutCandidates } from "./cut"; +import { runMediaTask, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const ONSCREEN_TITLE_MAX = 60; +export const ONSCREEN_SUBTITLE_MAX = 90; +// The most clips one ask carries (an API model too: a review reads them as a set). +export const ONSCREEN_BATCH_MAX = 8; +// The room a re-ask's words take on top of a batch's prompt. +const RETRY_ROOM_CHARS = 1500; + +export type OnscreenInput = MediaTaskInput; + +export type OnscreenValue = { title: string; subtitle?: string }; + +type OnscreenUnit = MediaUnit & { + entry: ManifestEntry; + // The clip's own words: what the subtitle may quote. + quote: string; + // The evidence block shown to the model; names and numbers are grounded in it. + evidence: string; +}; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); + +// A quotation: double marks (straight or curly), guillemets, or curly singles. +const QUOTED_RE = /"([^"]*)"|“([^”]*)”|«([^»]*)»|‘([^’]*)’/g; +const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’/; + +/** The quoted parts of a line, and whether its marks pair up. */ +export function quotedParts(text: string): { parts: string[]; balanced: boolean } { + const parts: string[] = []; + for (const m of text.matchAll(QUOTED_RE)) parts.push((m[1] ?? m[2] ?? m[3] ?? m[4] ?? "").trim()); + const rest = text.replace(QUOTED_RE, " "); + return { parts, balanced: !/["“”«»„‟]/.test(rest) && !/‘/.test(rest) }; +} + +/** Is `part` the quote's own words, in order (punctuation and case aside)? */ +export function isVerbatimOf(part: string, quote: string): boolean { + const p = strictNormalize(part); + return !!p && ` ${strictNormalize(quote)} `.includes(` ${p} `); +} + +// The words a Title Case title leaves small, or capitalises with the rest: +// neither is ever a name. +const TITLE_SMALL = new Set( + `a an the and but or nor for so yet of to in on at by up as is it its from with into onto off out over under than +that this these those be been being was were are am has have had do does did not no never ever all any each every +more most much many some such own same other only just very too again once still also even then now here there +when where why how what who whom which whose while if after before about against between through during without +within upon via per vs`.split(/\s+/), +); +// Ordinary words a headline capitalises (say, deny, sell, …): never read as a +// name in a Title Case title, in the evidence or not. Kept short: a word not +// here and not in the evidence is a name's candidate, as before. +const TITLE_ORDINARY = new Set( + `say said says tell told claim claims claimed admit admits admitted deny denies denied refuse refuses refused want +wants wanted will would won't can can't could should must may might need needs get gets got make makes made take +takes took give gives gave go goes went come comes came keep keeps kept see sees saw know knows knew think thinks +thought call calls called ask asks asked answer answers answered change changes changed turn turns turned back +sell sells sold sale buy buys bought pay pays paid win wins won lose loses lost start starts started stop stops stopped stay stays +plan plans planned promise promises promised deal deals story stories question questions answer truth lie lies +side sides vote votes rule rules line lines word words first last next new old big small long short true false +real fake whole half day days week weeks month months year years time times later earlier late early again here +yes no never always often sometimes nobody everybody somebody anyone everyone someone nothing everything something +one two three four five six seven eight nine ten`.split(/\s+/), +); +const TITLE_WORD_RE = /[A-Za-z][A-Za-z'’-]*/g; +const stemOf = (w: string) => w.toLowerCase().replace(/['’]s$/, "").replace(/(ing|ed|es|s|ly)$/, ""); + +/** A title whose words (the small ones aside) all start with a capital, two at least. */ +export function isTitleCase(title: string): boolean { + const big = (title.match(TITLE_WORD_RE) ?? []).filter((w) => !TITLE_SMALL.has(w.toLowerCase())); + return big.length >= 2 && big.every((w) => /^[A-Z]/.test(w)); +} + +/** + * A Title Case title as the sentence it would be: past its first word, a word + * is lowercased when it is small, an ordinary headline word, or a word the + * evidence has in any case (by its stem); any other keeps its capital — a + * name's candidate, which the grounding then looks for. Any other title is + * returned as it is. + */ +export function titleAsSentence(title: string, evidence: string): string { + if (!isTitleCase(title)) return title; + const known = new Set((evidence.match(TITLE_WORD_RE) ?? []).map(stemOf)); + let first = true; + return title.replace(TITLE_WORD_RE, (w) => { + if (first) { + first = false; + return w; + } + const low = w.toLowerCase(); + return TITLE_SMALL.has(low) || TITLE_ORDINARY.has(low) || known.has(stemOf(w)) ? low : w; + }); +} + +/** Every code check of one clip's on-screen text: `hard` refuses it. */ +export function checkOnscreen(v: OnscreenValue, u: Pick<OnscreenUnit, "quote" | "evidence">): { hard: string[]; soft: string[] } { + const hard: string[] = []; + const title = v.title; + const sub = v.subtitle ?? ""; + if (!title.trim()) hard.push("no title"); + for (const [name, text, max] of [["title", title, ONSCREEN_TITLE_MAX], ["subtitle", sub, ONSCREEN_SUBTITLE_MAX]] as const) { + if (/[\r\n]/.test(text)) hard.push(`the ${name} is more than one line`); + if (text.trim().length > max) hard.push(`the ${name} is ${text.trim().length} characters (at most ${max})`); + } + if (QUOTE_MARKS_RE.test(title)) hard.push("the title has quotation marks: a title quotes nobody"); + const { parts, balanced } = quotedParts(sub); + if (!balanced) hard.push("the subtitle's quotation marks do not pair up"); + for (const part of parts) { + if (!isVerbatimOf(part, u.quote)) hard.push(`the subtitle quotes “${part}”, which is not the clip's quote word for word`); + } + // Names and numbers: in the evidence (a quoted part is the quote's own). A + // Title Case title is checked in its sentence case (titleAsSentence): its + // capitals are not a name's signal, so an ordinary word is lowercased and an + // unknown name still stands out. + const said = `${titleAsSentence(title, u.evidence)}. ${sub.replace(QUOTED_RE, " ")}`; + hard.push(...groundedProblems(said, u.evidence, "the clip's evidence")); + hard.push(...firstPersonProblems(`${title}. ${sub}`)); + return { hard: [...new Set(hard)], soft: [] }; +} + +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); + +function unitsOf(ctx: MediaContext<OnscreenInput>): OnscreenUnit[] { + const { manifest, report } = ctx; + const byEntry = new Map(cutCandidates(manifest, report).map((c) => [c.entry, c])); + const out: OnscreenUnit[] = []; + const seen = new Set<string>(); + let chapter = ""; + for (const e of manifest.timeline) { + if (e.type === "card" && e.style === "chapter") chapter = String(e.heading ?? ""); + if (e.type !== "clip" || seen.has(e.id)) continue; + seen.add(e.id); + const c = byEntry.get(e.id); + const verdict = c?.claim?.verdict ?? (isObj(e.claim) ? e.claim.verdict : undefined); + const quote = String(e.quote ?? c?.quote ?? ""); + const lines = [ + `Report: ${String(report.title ?? "")}`, + chapter ? `Section: ${chapter}` : "", + c?.claim ? `Claim${verdict ? ` [${verdict}]` : ""}: ${stripCites(c.claim.text)}` : verdict ? `Verdict: ${verdict}` : "", + quote ? `Quote: "${quote}"` : "", + [c?.label, c?.date || e.date].filter(Boolean).length ? `Source: ${[c?.label, c?.date || e.date].filter(Boolean).join(", ")}` : "", + ].filter(Boolean); + out.push({ id: e.id, target: { entry: e.id, field: "onscreen" }, label: chapter || undefined, entry: e, quote, evidence: lines.join("\n") }); + } + return out; +} + +export function onscreenSystem(): string { + const rules = [ + "For each clip, write the text shown on screen while it plays: a title that says what the clip shows, in plain words, and a subtitle that adds who, when or what is at stake.", + `The title is one line of at most ${ONSCREEN_TITLE_MAX} characters, and it has no quotation marks.`, + `The subtitle is one line of at most ${ONSCREEN_SUBTITLE_MAX} characters. It may quote the speaker only with words from that clip's quote, exactly as they are, inside double quotation marks.`, + "Use only names and numbers that appear in that clip's evidence.", + "Write in the third person, in sentence case: no I, me, my, we or our outside a quotation.", + "Say what the clip shows; do not add facts, and do not put the verdict in the speaker's mouth.", + ]; + return ( + "You write on-screen text for the clips of a short evidence video. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "entries": one {"id", "title", "subtitle"} per clip, its id exactly as given.' + ); +} + +const SCHEMA = { + type: "object", + properties: { + entries: { + type: "array", + items: { + type: "object", + properties: { id: { type: "string" }, title: { type: "string" }, subtitle: { type: "string" } }, + required: ["id", "title", "subtitle"], + }, + }, + }, + required: ["entries"], +}; + +const userOf = (units: OnscreenUnit[]) => + `${units.map((u) => `### Clip ${u.id}\n${u.evidence}`).join("\n\n")}\n\nWrite the on-screen title and subtitle of ${units.length === 1 ? "this clip" : `each of these ${units.length} clips`}.`; + +/** The units in asks: as many per ask as fit the local prompt cap, at most ONSCREEN_BATCH_MAX. */ +export function onscreenBatches(units: OnscreenUnit[], ctx: Pick<MediaContext<OnscreenInput>, "input" | "handle">): OnscreenUnit[][] { + const local = providerOf(ctx.input.model) === "local"; + const cap = local ? promptCapOf(ollamaConfigOf(ctx.handle.deps.llm, ctx.input.model)) - Math.ceil(RETRY_ROOM_CHARS / CHARS_PER_TOKEN) : Number.POSITIVE_INFINITY; + const system = onscreenSystem(); + const out: OnscreenUnit[][] = []; + let cur: OnscreenUnit[] = []; + for (const u of units) { + const next = [...cur, u]; + const fits = next.length <= ONSCREEN_BATCH_MAX && (!local || structuredPromptEstimate({ system, user: userOf(next), schema: SCHEMA }) <= cap); + if (fits || !cur.length) cur = next; + else { + out.push(cur); + cur = [u]; + } + } + if (cur.length) out.push(cur); + return out; +} + +/** One clip's answer to its value (a throw is a hard failure). */ +export function parseOnscreen(raw: unknown): OnscreenValue { + const o = isObj(raw) ? raw : {}; + const title = typeof o.title === "string" ? o.title.trim() : ""; + const subtitle = typeof o.subtitle === "string" ? o.subtitle.trim() : ""; + if (!title && !subtitle) throw new Error("no title and no subtitle"); + return { title, ...(subtitle ? { subtitle } : {}) }; +} + +/** On-screen text as a media task (./media.ts): one unit per clip, asked in batches. */ +export const ONSCREEN_SPEC: MediaTaskSpec<OnscreenUnit, OnscreenValue, OnscreenInput> = { + task: "onscreen", + noun: "clip", + verb: "titled", + progressMetric: "entries", + units: (ctx) => unitsOf(ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (u) => userOf([u]), + batch: { + group: (units, ctx) => onscreenBatches(units, ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (units) => userOf(units), + split(answer) { + const list = isObj(answer) && Array.isArray(answer.entries) ? answer.entries : []; + const out: Record<string, unknown> = {}; + for (const e of list) if (isObj(e) && typeof e.id === "string" && !(e.id.trim() in out)) out[e.id.trim()] = e; + return out; + }, + }, + parse: (raw) => parseOnscreen(raw), + check: (v, u) => checkOnscreen(v, u), + toField: (v) => ({ title: v.title, ...(v.subtitle ? { subtitle: v.subtitle } : {}) }), + describe: (v) => `${v.title}${v.subtitle ? ` — ${v.subtitle}` : ""}`, +}; + +export async function onscreen(input: OnscreenInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(ONSCREEN_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/panelTasks.test.ts b/common/lib/report/draft/tasks/panelTasks.test.ts @@ -0,0 +1,393 @@ +// The flips, threads and youtube drafts (release 28, M4–M6): every code check +// refuses what it should — dates, order, counts, lengths, ids, grounding — the +// better of two attempts, the repair, the one left panel, and the operator's +// field kept with the draft as an alternative. The fake ollama answers; the +// corpus is the synthetic one's records (their upload dates). + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { recordOf } from "../../../../testing/draft/corpus.mjs"; +import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; +import { groundingInputOf } from "../grounding"; +import { validateFlipEntries, validateFlips, validateThreadEntries, validateThreads } from "../../panels.mjs"; +import type { VideoManifest } from "../videoOps"; +import { isoDay, whenOf, type ClipFact } from "./clipEvidence"; +import { flips, planFlips, sideWords, swapEntries } from "./flips"; +import { planThreads, threads } from "./threads"; +import { summaryProblems, titleProblems, youtube, YOUTUBE_SUMMARY_MAX } from "./youtube"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +let tmp: string; +let ol: FakeOllama; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "panel-tasks-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +// The full manifest with no left panel (its threads taken off). +async function deckManifest() { + const m = await kit("manifests/full.video.manifest.json"); + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + return m; +} + +// The corpus as the tasks read it: get_video_metadata answers a record (no cues). +const corpus = { + source: "fake", + tools: [], + call: async (name: string, args: Record<string, unknown> = {}) => { + if (name !== "get_video_metadata") return ""; + const r = recordOf(String(args.channel), String(args.video_id)); + if (!r) throw new Error("video not found"); + const { cues: _c, ...meta } = r; + return JSON.stringify(meta); + }, +}; + +let caseN = 0; +async function project(manifest: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const input = (o: { force?: boolean } = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draftNow = async (task: string) => JSON.parse(await readFile(path.join(dir, `${task}-draft.json`), "utf8")) as DraftFile; + return { dir, deps, lines, input, manifestNow, draftNow, report }; +} + +const P = { task: "cut", model: "qwen3:8b", at: "2026-10-13T11:00:00.000Z", iteration: 1, attempt: 1 }; + +// ─── pure ─── + +test("dates and words are code's: isoDay, whenOf, sideWords verbatim and cut at a word", () => { + assert.equal(isoDay("20260105"), "2026-01-05"); + assert.equal(isoDay("2026-03-01T10:00:00Z"), "2026-03-01"); + assert.equal(isoDay("March"), null); + assert.equal(whenOf("2026-01-05"), "Jan 2026"); + assert.deepEqual(sideWords("I would never sell the bakery to a chain", "Never sell the BAKERY"), { words: "never sell the bakery" }); + assert.deepEqual(sideWords("I would never sell the bakery to a chain", "I'd never sell it"), { + words: "I would never sell the bakery to a chain", + soft: "its words are not the clip's quote: the quote is used", + }); + const long = Array.from({ length: 40 }, (_, i) => `word${i}`).join(" "); + const cut = sideWords(long, undefined).words; + assert.ok(cut.length <= 110 && cut.endsWith("…") && long.startsWith(cut.slice(0, -1)), cut); + assert.deepEqual( + swapEntries([{ type: "clip", id: "a" }, { type: "card", id: "x" }, { type: "clip", id: "b" }], [["a", "b"]]).map((e) => e.id), + ["b", "x", "a"], + ); +}); + +const clip = (id: string, index: number, date: string | null, quote = `the words of ${id}`, verdict?: string): ClipFact => ({ + id, + index, + quote, + claim: verdict ? { text: "", verdict } : null, + section: null, + date, + dateFrom: date ? "record" : null, +}); + +test("planFlips: ids, one pair per clip, dates (the earlier is THEN; one day is no pair), order, the topic's length and grounding", async () => { + const m = (await deckManifest()) as VideoManifest; + const g = groundingInputOf(await kit("reports/basic.report.json")); + const clips = [clip("c01", 2, "2026-01-05"), clip("c02", 3, "2026-01-05"), clip("c04", 6, "2026-02-10"), clip("c07", 9, "2026-03-01"), clip("c05", 7, null)]; + const unit = { clips, g, reorderable: false, dropThreads: false, maxPairs: 2 }; + // The model's THEN is the later recording: code turns it round. + const ok = planFlips({ pairs: [{ topic: "The bakery", then: "c07", now: "c01" }] }, unit, m); + assert.deepEqual(ok.problems, []); + assert.deepEqual(ok.flips.pairs[0], { + id: "the-bakery", + topic: "The bakery", + then: { entry: "c01", when: "Jan 2026", words: "the words of c01" }, + now: { entry: "c07", when: "Mar 2026", words: "the words of c07" }, + }); + const bad = planFlips( + { + pairs: [ + { topic: "The oven", then: "c01", now: "c02" }, + { topic: "The contest", then: "c99", now: "c04" }, + { topic: "The contest", then: "c05", now: "c04" }, + { topic: "A topic that is far too long for the panel", then: "c04", now: "c07" }, + ], + }, + unit, + m, + ); + const all = [...bad.problems, ...bad.pairProblems.flat()].join(" | "); + assert.match(all, /4 pairs: at most 2/); + assert.match(all, /c01 and c02 are of the same day \(2026-01-05\)/); + assert.match(all, /c99 is not a clip of the cut/); + assert.match(all, /c05's recording has no date/); + assert.match(all, /the topic is 42 characters \(at most 32\)/); + // A name the report does not have; a clip in two pairs. + const two = planFlips({ pairs: [{ topic: "The bakery of Gordon", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); + assert.match(two.pairProblems[0]!.join(" "), /name “Gordon” is not in the report/); + assert.equal(two.pairProblems[1]!.length, 0, "a refused pair leaves its clips free"); + const three = planFlips({ pairs: [{ topic: "The bakery", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); + assert.match(three.pairProblems[1]!.join(" "), /c07 is already in a pair/); +}); + +test("planFlips: THEN after NOW in the cut is refused when the order is the operator's, swapped when it is a draft; the build's validators pass", async () => { + const m = (await deckManifest()) as VideoManifest; + // c07 (Mar) before c01 (Jan) in the cut. + m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); + const g = groundingInputOf(await kit("reports/basic.report.json")); + const at = (id: string) => m.timeline.findIndex((e) => e.id === id); + const clips = [clip("c01", at("c01"), "2026-01-05"), clip("c07", at("c07"), "2026-03-01")]; + const v = { pairs: [{ topic: "The bakery", then: "c01", now: "c07" }] }; + const refused = planFlips(v, { clips, g, reorderable: false, dropThreads: false, maxPairs: 1 }, m); + assert.match(refused.pairProblems[0]!.join(" "), /THEN c01 \(2026-01-05\) plays after NOW c07 \(2026-03-01\) and the cut's order is not a draft/); + const swapped = planFlips(v, { clips, g, reorderable: true, dropThreads: false, maxPairs: 1 }, m); + assert.deepEqual([...swapped.problems, ...swapped.pairProblems.flat()], []); + assert.deepEqual(swapped.swaps, [["c01", "c07"]]); + const after = JSON.parse(JSON.stringify(m)); + after.timeline = swapEntries(after.timeline, swapped.swaps); + after.render.chrome.flips = swapped.flips; + assert.deepEqual([...validateFlips(swapped.flips), ...validateFlipEntries(after)], []); +}); + +test("planThreads: 2 to 4, labels, ids, assignments, every thread a clip; the outcome is the last clip's verdict in the manifest", async () => { + const m = (await deckManifest()) as VideoManifest; + const g = groundingInputOf(await kit("reports/basic.report.json")); + const at = (id: string) => m.timeline.findIndex((e) => e.id === id); + const clips = ["c01", "c02", "c03", "c04", "c05", "c06", "c07"].map((id) => clip(id, at(id), null)); + const unit = { clips, g, dropFlips: false }; + const one = planThreads({ threads: [{ id: "a", label: "The bakery" }], assign: [{ clip: "c01", thread: "a" }] }, unit, m); + assert.match(one.problems.join(" "), /1 thread\(s\): 2 to 4/); + const bad = planThreads( + { + threads: [ + { id: "bakery", label: "The bakery" }, + { id: "bakery", label: "The bakery again" }, + { id: "x y!", label: "A label that is much too long for the rail" }, + ], + assign: [ + { clip: "c01", thread: "bakery" }, + { clip: "c99", thread: "bakery" }, + { clip: "c02", thread: "nowhere" }, + { clip: "c03", thread: "bakery" }, + { clip: "c03", thread: "x y!" }, + ], + }, + unit, + m, + ); + const all = [...bad.problems, ...bad.threadProblems.flat()].join(" | "); + assert.match(all, /the id bakery is listed twice/); + assert.match(all, /the label is 42 characters \(at most 32\)/); + assert.match(all, /c99 is not a clip of the cut/); + assert.match(all, /c02 is put in nowhere, which is not a listed thread/); + assert.match(all, /c03 is put in two threads \(bakery, x-y\)/); + // The outcome: code's, from the manifest — c07 (CONTRADICTED) is the bakery's last clip; c06 (NOT_FOUND) the contest's. + const good = planThreads( + { + threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }], + assign: ["c01", "c02", "c03", "c07"].map((c) => ({ clip: c, thread: "bakery" })).concat(["c04", "c05"].map((c) => ({ clip: c, thread: "contest" }))), + }, + unit, + m, + ); + assert.deepEqual(good.problems, []); + assert.deepEqual(good.list, [ + { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } }, + { id: "contest", label: "The contest", outcome: { verdict: "PARTLY" } }, + ]); + const after = JSON.parse(JSON.stringify(m)); + after.render.chrome.threads = { list: good.list }; + for (const e of after.timeline) if (good.clips[e.id]) e.thread = good.clips[e.id]; + assert.deepEqual([...validateThreads({ list: good.list }), ...validateThreadEntries(after)], []); +}); + +test("youtube's checks: lengths, one line, links, third person, names and numbers, quotes word for word", async () => { + const g = groundingInputOf(await kit("reports/basic.report.json")); + assert.deepEqual(titleProblems("What the baker of Synth Kitchen says about the bakery", g).hard, []); + assert.match(titleProblems("x".repeat(101), g).hard.join(" "), /101 characters \(at most 100\)/); + assert.match(titleProblems("Synth Kitchen in 2027", g).hard.join(" "), /number 2027 is not in the report/); + assert.match(titleProblems("What Gordon says about the bakery", g).hard.join(" "), /name “Gordon” is not in the report/); + assert.match(summaryProblems("I would never sell it, she says.", g).hard.join(" "), /the narrator is third person/); + assert.deepEqual(summaryProblems('She says "I would never sell the bakery to a chain" on the bread day.', g).hard, []); + assert.match(summaryProblems('She says "I will sell the bakery".', g).hard.join(" "), /is not what a cited clip says, word for word/); + assert.match(summaryProblems("See 0:15 for the bakery.", g).hard.join(" "), /no links, timestamps/); + assert.match(summaryProblems("a ".repeat(YOUTUBE_SUMMARY_MAX), g).hard.join(" "), /at most 900/); +}); + +// ─── the tasks, over the fake ollama ─── + +test("flips refuses a cut with no deck, and one with threads unless forced over drafted threads — which it then replaces, and says so", async () => { + const basic = await project(await kit("manifests/basic.video.manifest.json")); + const none = await flips(basic.input(), basic.deps); + assert.equal(none.status, "failed"); + assert.match(none.summary, /drawn by the on-screen deck \(render\.chrome\), and this cut has none/); + + // The full manifest's threads are hand-written: the operator's, refused even forced. + const full = await project(await kit("manifests/full.video.manifest.json")); + assert.match((await flips(full.input(), full.deps)).summary, /share the left panel: the threads are the operator's/); + assert.match((await flips(full.input({ force: true }), full.deps)).summary, /the threads are the operator's — remove them first/); + + // Drafted threads: refused unforced, replaced forced. + const m = await kit("manifests/full.video.manifest.json"); + m.drafted = { "render.chrome.threads": P }; + const drafted = await project(m); + assert.match((await flips(drafted.input(), drafted.deps)).summary, /force replaces drafted threads/); + ol.push(jsonReply({ pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }] })); + const out = await flips(drafted.input({ force: true }), drafted.deps); + assert.equal(out.status, "done", `${out.summary}\n${drafted.lines.join("\n")}`); + const now = await drafted.manifestNow(); + assert.equal(now.render.chrome.threads, undefined); + assert.ok(now.timeline.every((e: { thread?: string }) => e.thread === undefined), "every clip's thread goes with the list"); + assert.equal(now.drafted["render.chrome.threads"], undefined); + assert.equal(now.drafted["render.chrome.flips"].task, "flips"); + assert.ok(drafted.lines.some((l) => /the drafted threads were removed/.test(l))); +}); + +test("flips: a pair the other way round in a drafted cut swaps the clips (the timeline re-marked); a refused pair dropped when the rest stand", async () => { + const m = await deckManifest(); + m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); + m.drafted = { timeline: { ...P, model: "code" } }; + const p = await project(m); + const bad = { pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }, { topic: "The lease and Gordon", then: "c04", now: "c02" }] }; + ol.push(jsonReply(bad), jsonReply(bad)); + const out = await flips(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0, "both attempts asked"); + const now = await p.manifestNow(); + assert.deepEqual(now.render.chrome.flips.pairs.map((x: { then: { entry: string }; now: { entry: string } }) => [x.then.entry, x.now.entry]), [["c01", "c07"]]); + assert.ok(now.timeline.findIndex((e: { id: string }) => e.id === "c01") < now.timeline.findIndex((e: { id: string }) => e.id === "c07")); + assert.equal(now.drafted.timeline.task, "flips", "the order is this draft's now"); + assert.deepEqual([...validateFlips(now.render.chrome.flips), ...validateFlipEntries(now)], []); + const file = await p.draftNow("flips"); + assert.match(JSON.stringify(file.units.flips!.chosen), /1 refused pair\(s\) dropped/); + assert.ok(p.lines.some((l) => /the cut's order changed so THEN plays first: c01 ⇄ c07/.test(l))); +}); + +test("flips: the operator's flips stand, forced or not; a forced draft is kept as an alternative", async () => { + const p = await project(await kit("manifests/flips.video.manifest.json")); + const skipped = await flips(p.input(), p.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p.draftNow("flips")).units.flips!.skipped), /the operator's/); + ol.push(jsonReply({ pairs: [{ topic: "The contest", then: "c04", now: "c07" }] })); + const out = await flips(p.input({ force: true }), p.deps); + assert.equal(out.status, "done", out.summary); + const now = await p.manifestNow(); + assert.equal(now.render.chrome.flips.pairs[0].id, "chain", "the operator's pairs stand"); + const alt = (await p.draftNow("flips")).alternatives; + assert.equal(alt.length, 1); + assert.equal(alt[0]!.reason, "operator"); + assert.deepEqual((alt[0]!.value as { pairs: { topic: string }[] }).pairs.map((x) => x.topic), ["The contest"]); +}); + +test("threads: refused with operator's flips; forced over drafted flips replaces them; a refused thread dropped when two stand", async () => { + const op = await project(await kit("manifests/flips.video.manifest.json")); + assert.match((await threads(op.input({ force: true }), op.deps)).summary, /the flips are the operator's — remove them first/); + const m = await kit("manifests/flips.video.manifest.json"); + m.drafted = { "render.chrome.flips": { ...P, task: "flips" } }; + const p = await project(m); + const answer = { + threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }, { id: "lease", label: "The lease and Gordon" }], + clips: [ + { clip: "c01", thread: "bakery" }, + { clip: "c02", thread: "bakery" }, + { clip: "c04", thread: "contest" }, + { clip: "c06", thread: "lease" }, + { clip: "c07", thread: "bakery" }, + ], + }; + ol.push(jsonReply(answer), jsonReply(answer)); + const out = await threads(p.input({ force: true }), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + const now = await p.manifestNow(); + assert.equal(now.render.chrome.flips, undefined); + assert.equal(now.drafted["render.chrome.flips"], undefined); + assert.deepEqual(now.render.chrome.threads.list.map((t: { id: string }) => t.id), ["bakery", "contest"]); + const thread = (id: string) => now.timeline.find((e: { id: string }) => e.id === id).thread; + assert.equal(thread("c06"), undefined, "the dropped thread's clip is in none"); + assert.equal(thread("c07"), "bakery"); + assert.deepEqual([...validateThreads(now.render.chrome.threads), ...validateThreadEntries(now)], []); + assert.ok(p.lines.some((l) => /the drafted flips were removed/.test(l))); +}); + +test("threads: a draft kept as an alternative carries the clips' assignments with the list (release 28 M9)", async () => { + const p = await project(await kit("manifests/full.video.manifest.json")); + const before = await p.manifestNow(); + const answer = { + threads: [{ id: "shop", label: "The bakery" }, { id: "prize", label: "The contest" }], + clips: [ + { clip: "c01", thread: "shop" }, + { clip: "c02", thread: "shop" }, + { clip: "c03", thread: "shop" }, + { clip: "c04", thread: "prize" }, + { clip: "c05", thread: "prize" }, + { clip: "c06", thread: "prize" }, + { clip: "c07", thread: "shop" }, + ], + }; + ol.push(jsonReply(answer), jsonReply(answer)); + const out = await threads(p.input({ force: true }), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + const now = await p.manifestNow(); + assert.deepEqual(now.render.chrome.threads, before.render.chrome.threads, "the operator's threads stand"); + const alt = (await p.draftNow("threads")).alternatives; + assert.equal(alt.length, 1); + assert.equal(alt[0]!.reason, "operator"); + const v = alt[0]!.value as { list: { id: string }[]; clips: Record<string, string> }; + assert.deepEqual(v.list.map((t) => t.id), ["shop", "prize"]); + assert.deepEqual(v.clips, { c01: "shop", c02: "shop", c03: "shop", c04: "prize", c05: "prize", c06: "prize", c07: "shop" }); +}); + +test("youtube: the better of two attempts, the summary's failing sentence removed; the operator's field kept and the draft an alternative", async () => { + const p = await project(await kit("manifests/basic.video.manifest.json")); + const title = "What the baker of Synth Kitchen says about the bakery"; + ol.push( + jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery. We think she is right." }), + jsonReply({ title: `${title} in 2027`, description: "She will not sell." }), + ); + const out = await youtube(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + const now = await p.manifestNow(); + assert.deepEqual(now.publish.youtube, { title, description: "Synth Kitchen's baker will not sell the bakery." }); + assert.equal(now.drafted["publish.youtube"].attempt, 2); + + // The operator edits it (the mark goes): a forced re-draft is an alternative. + now.publish.youtube.title = "The baker on the bakery"; + delete now.drafted; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(now)); + ol.push(jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery." })); + const again = await youtube(p.input({ force: true }), p.deps); + assert.equal(again.status, "done", again.summary); + assert.equal((await p.manifestNow()).publish.youtube.title, "The baker on the bakery"); + const alt = (await p.draftNow("youtube")).alternatives; + assert.equal(alt.at(-1)!.reason, "operator"); + assert.equal((alt.at(-1)!.value as { title: string }).title, title); +}); diff --git a/common/lib/report/draft/tasks/quotes.ts b/common/lib/report/draft/tasks/quotes.ts @@ -3,7 +3,9 @@ // // The check a GENERATED quote must pass is the strict one (D3): every quoted // fragment verbatim (normalised) in the record's cues within ±90 s of its -// cited second; a post's quote in the post's text. An outside verifier (the +// cited second; a post's quote in the post's text. And it may not be a +// FRAGMENT (release 28 Q2, lib/citations/fragment.ts): the problem then +// carries the full sentence, the repair round's hint. An outside verifier (the // editor's verify-quotes over the corpus on disk, which also reads the en-orig // track) may add problems. A finding whose quote fails after the one repair // round is DROPPED, never repaired by code. @@ -12,6 +14,7 @@ import { sweepToReport } from "../../convertSweep"; import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { Report } from "../../schema"; import { strictNormalize, strictQuoteCheck, strictTextCheck, quoteFragments } from "../../../citations/verify"; +import { fragmentHint, fragmentOf, fullSentenceFor } from "../../../citations/fragment"; import { evidenceOf, findingsOf, parseSweep, quotesOf, renderSweep, LINK_RE, type SweepDoc } from "../sweepModel"; import { parseCitationHref } from "../../convertShared"; import { mmss } from "../reportOps"; @@ -26,6 +29,10 @@ export type QuoteProblem = { why: string; // The transcript ±45 s around the cited second, for a repair. near?: string; + // A FRAGMENT (release 28 Q2): the words are there, but the quote stops + // mid-thought. `sentence` is the full sentence to quote instead (the repair + // hint), null when none fits. + fragment?: { why: string; part: string; sentence: string | null }; }; export type ConvertOutcome = @@ -78,6 +85,12 @@ export async function checkQuotes( const r = strictTextCheck(quote, text); if (!r.ok) { problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: `"${r.failed}" is not the post's words`, near: text }); + continue; + } + const frag = fragmentOf(quote); + if (frag) { + const sentence = fullSentenceFor(frag.part, [{ start: 0, end: 1, text }], 0); + problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: fragmentHint(frag, sentence), fragment: { ...frag, sentence } }); } continue; } @@ -101,12 +114,20 @@ export async function checkQuotes( why: `not verbatim within 90 s of ${Math.floor(c.start)} s: "${r.failed}"`, near, }); + continue; + } + const frag = fragmentOf(quote); + if (frag) { + const sentence = fullSentenceFor(frag.part, cues, c.start); + problems.push({ citation: cid, channel: c.channel, id: c.id, second: c.start, quote, why: fragmentHint(frag, sentence), fragment: { ...frag, sentence } }); } } if (deps.verifyReport) { const seen = new Set(problems.map((p) => p.citation)); for (const p of await deps.verifyReport(report)) { - if (seen.has(p.citation) || p.status === "ok" || p.status === "inexact") continue; + // A warning (inexact, fragment) is not a problem: the strict and + // fragment checks above are this run's own. + if (seen.has(p.citation) || p.status === "ok" || p.status === "inexact" || p.status === "fragment") continue; const c = report.citations?.[p.citation] as { channel?: string; id?: string; start?: number; quote?: string } | undefined; problems.push({ citation: p.citation, diff --git a/common/lib/report/draft/tasks/research.ts b/common/lib/report/draft/tasks/research.ts @@ -184,8 +184,10 @@ async function researchBody(h: TaskHandle, input: ResearchInput): Promise<TaskOu .filter(Boolean) .join(" "); const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); + if (e.type === "turn") { + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 60 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + } else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); else if (e.type === "note") h.log(e.text); }; const run = await runAgent({ diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts @@ -8,12 +8,28 @@ // corpus (the MCP's read tools), the operator's notes, and the web for context. // Then the link backstop, convert and the quote check: a NEW finding whose // quote fails is dropped, never repaired. +// +// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound +// ask (`structuredAnswer`) for the whole ops batch, over the numbered view +// trimmed to the model's prompt cap (sweepModel trimmedNumberedView: the +// sections the feedback names first, quotes shortened in the view only). The +// ops still number against the whole document. The API path is unchanged. -import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; +import { + CHARS_PER_TOKEN, + ollamaConfigOf, + promptCapOf, + providerOf, + runAgent, + structuredAnswer, + structuredPromptEstimate, + type AgentTool, + type LlmConfig, +} from "../../../llm"; import { lineage, readIterationFile, writeIterationFile } from "../../iterations"; -import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, momentLinkRule } from "../authoringRules"; +import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule } from "../authoringRules"; import { applyReportOps, strictCheckerOver, type AppliedOp, type RefusedOp } from "../reportOps"; -import { numberedView, parseSweep, renderSweep, type SweepDoc } from "../sweepModel"; +import { numberedView, parseSweep, renderSweep, trimmedNumberedView, type SweepDoc } from "../sweepModel"; import { extractJsonObject } from "../../../parseStdoutJson"; import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes"; @@ -31,9 +47,20 @@ export const COMMON_REVISE_RULES = (what: string) => "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words. When done, stop calling tools and say in one line what you changed.", ].join(" "); -export const REPORT_OPS_TEXT = (origin: string) => +// A local revision's rules: one answer, no tools (release 28 Q3). +export const LOCAL_REVISE_RULES = (what: string) => [ - "Operations (objects for apply_ops; `n` is a finding's number as read_doc shows it — one batch numbers against the document at its start):", + `You revise one ${what} of a report built from video transcripts, following the operator's feedback.`, + UNATTENDED_RULE, + "Answer with ONE batch of edit operations, the `ops` list, that carries out the feedback: code applies it and refuses any op that breaks a rule. The view may leave some of it out (it says what); an op may still name what is not shown.", + "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words.", + ].join(" "); + +export const REPORT_OPS_TEXT = (origin: string, local = false) => + [ + local + ? "Operations (objects in the `ops` list; `n` is a finding's number as the view shows it — the batch numbers against the report as shown):" + : "Operations (objects for apply_ops; `n` is a finding's number as read_doc shows it — one batch numbers against the document at its start):", '- {"op":"drop","n":N} remove finding N', '- {"op":"claim","n":N,"text":"..."} rewrite finding N\'s claim (its quote and link stay as they are)', '- {"op":"merge","n":N,"into":M,"text":"..."} fold finding N into finding M: M keeps every quote with its own link; "text" (optional) is M\'s new claim', @@ -43,6 +70,7 @@ export const REPORT_OPS_TEXT = (origin: string) => '- {"op":"title","text":"..."} / {"op":"summary","text":"..."}', CLAIM_QUOTES_RULE, VERBATIM_QUOTES_RULE, + WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule(origin), ].join("\n"); @@ -88,6 +116,29 @@ export type ReviseReportInput = { maxTurns?: number; }; +// A local ask's user text, fitted under the model's prompt cap: `build` makes +// it at a character budget, which shrinks until the whole request — system, +// user and the ops schema, counted as ollamaChat counts them — fits. +export function fitLocalAsk(o: { + llm: LlmConfig; + model: string; + system: string; + schema: object; + build: (maxChars: number) => string; +}): { user: string; tokens: number; cap: number } { + const cap = promptCapOf(ollamaConfigOf(o.llm, o.model)); + let maxChars = Math.floor(cap * CHARS_PER_TOKEN) - o.system.length - JSON.stringify(o.schema).length; + let user = ""; + let tokens = Number.POSITIVE_INFINITY; + for (let k = 0; k < 40 && maxChars >= 400; k++) { + user = o.build(maxChars); + tokens = structuredPromptEstimate({ system: o.system, user, schema: o.schema }); + if (tokens <= cap) break; + maxChars = Math.floor(maxChars * 0.85); + } + return { user, tokens, cap }; +} + // The nearest iteration in `n`'s lineage (n excluded) with a sweep.md. export async function parentSweep(h: Pick<TaskHandle, "article" | "n" | "paths">): Promise<{ from: number; md: string } | null> { const line = await lineage(h.article, h.n, h.paths); @@ -144,7 +195,17 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis const applied: AppliedOp[] = []; const refused: RefusedOp[] = []; const added: string[] = []; - h.log(`revising the report of i${parent.from} on ${model}`); + const local = providerOf(model) === "local"; + h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}`); + const applyOps = async (ops: unknown[]) => { + const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); + doc = r.doc; + applied.push(...r.applied); + refused.push(...r.refused); + for (const a of r.applied) if (a.op.op === "add") added.push(String(a.op.quote ?? "")); + h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + return r; + }; const tools: AgentTool[] = [ ...reviseCorpusTools(deps, rewrite), @@ -160,56 +221,72 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the report after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { - const ops = Array.isArray(inp?.ops) ? inp.ops : []; - const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); - doc = r.doc; - applied.push(...r.applied); - refused.push(...r.refused); - for (const a of r.applied) if (a.op.op === "add") added.push(String(a.op.quote ?? "")); - h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + const r = await applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return `${JSON.stringify({ applied: r.applied.length, refused: r.refused.map((x) => ({ index: x.index, op: x.op.op, why: x.why })) })}\n\nNow:\n${numberedView(doc)}`; }, }, ]; - const system = `${COMMON_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin)}`; - const run = await runAgent({ - llm: deps.llm, - model, - system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}`, - tools, - meter: h.meter, - maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) gets ONE schema-bound ask for the batch; nothing at all - // after that is a failing check, not a quiet "0 applied". - if (applied.length + refused.length === 0) { - const asked = await structuredAnswer<{ ops?: unknown[] }>({ + if (local) { + await localOpsBatch(h, { + model, + system: `${LOCAL_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin, true)}`, + what: "report", + build: (maxChars) => { + const v = trimmedNumberedView(doc, { maxChars: maxChars - feedback.length - 300, feedback }); + return ( + `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW (findings numbered [n]; in this view quotes are shortened ` + + `and links cut to their labels — the report keeps them whole):\n${v.text}\n\nAnswer with the ops batch that carries out the feedback.` + ); + }, + apply: applyOps, + }); + } else { + await apiRevision(); + } + async function apiRevision() { + const system = `${COMMON_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin)}`; + const run = await runAgent({ llm: deps.llm, model, system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}\n\nAnswer with the ops batch that carries out the feedback.`, - schema: OPS_SCHEMA, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}`, + tools, meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 30, + ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type !== "turn") return; + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - if (asked && Array.isArray(asked.ops) && asked.ops.length) { - h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); - await tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + h.turns(run.transcript); + if (run.stopReason === "cancelled") return; + // A model that ends without calling apply_ops gets ONE schema-bound ask for + // the batch; nothing at all after that is a failing check, not a quiet "0 + // applied". + if (applied.length + refused.length === 0) { + const asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + model, + system, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}\n\nAnswer with the ops batch that carries out the feedback.`, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) { + h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); + await applyOps(asked.ops); + } } } + if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, @@ -241,10 +318,17 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis } await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); h.check({ name: "convert", ok: true }); + // A fragment the parent already quoted is a warning, as verify-quotes says + // of an existing report (release 28 Q2); what fails the words is a failure. + const failing = problems.filter((p) => !p.fragment); + const fragments = problems.filter((p) => p.fragment); + const warn = fragments.length ? `; ${fragments.length} fragment quote(s) from the iteration revised (a warning)` : ""; h.check({ name: "quotes", - ok: problems.length === 0, - detail: problems.length ? `${problems.length} quote(s) fail the strict check (from the iteration revised): ${problems.map((p) => p.why).slice(0, 3).join("; ")}` : "every quote verbatim (strict)", + ok: failing.length === 0, + detail: failing.length + ? `${failing.length} quote(s) fail the strict check (from the iteration revised): ${failing.map((p) => p.why).slice(0, 3).join("; ")}${warn}` + : `every quote verbatim (strict)${warn}`, }); await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths); return { @@ -253,3 +337,32 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis patch: { ops }, }; } + +// A local revision's one ops batch: the view fitted under the prompt cap, one +// structuredAnswer, the ops applied. A failed ask is logged (the ops check +// 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> }, +): Promise<void> { + const { deps } = h; + const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema: OPS_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[] }>({ + llm: deps.llm, + model: o.model, + system: o.system, + user: fitted.user, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + if (deps.signal?.aborted) throw e; + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + h.turns([{ kind: "model", what: "ops batch", tokens: fitted.tokens, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: asked }]); + h.progress({ metric: "turns", current: 1, total: 1 }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) await o.apply(asked.ops); +} diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts @@ -8,13 +8,19 @@ // new cut is this iteration's project, seeded from the parent's: the report // and stills copied, the voices hard-linked. A video revision has no report of // its own (its article's report stays its nearest ancestor's). +// +// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound ask +// for the ops batch over the cut trimmed to the prompt cap (videoOps +// trimmedCutView: the chapters the feedback names first, quotes shortened in +// the view only), as revise-report does. The API path is unchanged. import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; import { readIteration, type Iteration } from "../../iterations"; -import { applyVideoOps, cutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; +import { applyVideoOps, cutView, trimmedCutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; import { rewriteMomentBases, slugResolver } from "./links"; import { projectDirOf, readManifest, readProjectReport, seedProject, writeManifest } from "./project"; -import { COMMON_REVISE_RULES, OPS_SCHEMA, reviseCorpusTools } from "./revise-report"; +import { fieldSignature, makeProvenance, stableStringify } from "../../drafted.mjs"; +import { COMMON_REVISE_RULES, LOCAL_REVISE_RULES, OPS_SCHEMA, localOpsBatch, reviseCorpusTools } from "./revise-report"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; @@ -23,12 +29,17 @@ export const VIDEO_OPS_TEXT = [ '- {"op":"drop","id":"<entry id>"} remove an entry', '- {"op":"move","id":"<entry id>","after":"<entry id, or \'start\'>"} reorder', '- {"op":"heading","id":"<card id>","text":"..."} a card\'s on-screen heading', - '- {"op":"narration","id":"<card id>","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', + '- {"op":"narration","id":"<card id>","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; third person — never I, me, my, we, us or our; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', '- {"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":"..."}', ].join("\n"); +const shortQuote = (q: string, words = 12) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q; +}; + export type ReviseVideoInput = { article: string; n: number; @@ -82,6 +93,14 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< .map(([cid, c]) => `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${String(c?.quote ?? "").slice(0, 160)}"`) .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 }); + manifest = r.manifest; + applied.push(...r.applied); + refused.push(...r.refused); + h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + return r; + }; h.log(`revising the cut of i${parent.it.n} on ${model}`); const tools: AgentTool[] = [ @@ -93,11 +112,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { - const r = applyVideoOps(manifest, Array.isArray(inp?.ops) ? inp.ops : [], { report, parent: parent.manifest }); - manifest = r.manifest; - applied.push(...r.applied); - refused.push(...r.refused); - h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return ( JSON.stringify({ applied: r.applied.map((a) => ({ index: a.index, op: a.op.op, ...(a.warnings ? { warnings: a.warnings } : {}) })), @@ -107,45 +122,83 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< }, }, ]; - const system = `${COMMON_REVISE_RULES("video cut (an evidence video: cards with spoken narration between clips of what was said)")}\n\n${VIDEO_OPS_TEXT}`; - const run = await runAgent({ - llm: deps.llm, - model, - system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, - tools, - meter: h.meter, - maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) gets ONE schema-bound ask for the batch; nothing at all - // after that is a failing check, not a quiet "0 applied". - if (applied.length + refused.length === 0) { - const asked = await structuredAnswer<{ ops?: unknown[] }>({ + const what = "video cut (an evidence video: cards with spoken narration between clips of what was said)"; + if (providerOf(model) === "local") { + // Release 28 Q3: one ops batch over the cut trimmed to the prompt cap. + const citeRows = Object.entries(report.citations ?? {}).map(([cid, c]) => ({ + cid, + line: `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${shortQuote(String(c?.quote ?? ""))}"`, + })); + const named = (cid: string) => new RegExp(`\\b${cid}\\b`).test(feedback); + const citeOrder = [...citeRows].sort((a, b) => Number(named(b.cid)) - Number(named(a.cid))); + await localOpsBatch(h, { + model, + system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`, + what: "cut", + build: (maxChars) => { + const budget = maxChars - feedback.length - 400; + const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback }); + let left = budget - cut.text.length; + const shown: string[] = []; + for (const c of citeOrder) { + if (c.line.length + 1 > left) continue; + left -= c.line.length + 1; + shown.push(c.cid); + } + const lines = citeRows.filter((c) => shown.includes(c.cid)).map((c) => c.line); + const more = citeRows.length - lines.length; + return ( + `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW (quotes shortened in this view only):\n${cut.text}\n\n` + + `REPORT CITATIONS (add_clip takes these ids${more ? `; ${more} more not shown` : ""}):\n${lines.join("\n")}\n\n` + + `THE REPORT IT IS CUT FROM: ${String(report.title ?? "")}\n\nAnswer with the ops batch that carries out the feedback.` + ); + }, + apply: async (ops) => applyOps(ops), + }); + } else { + const system = `${COMMON_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT}`; + const run = await runAgent({ llm: deps.llm, 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, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, + tools, meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 30, + ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type !== "turn") return; + h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - if (asked && Array.isArray(asked.ops) && asked.ops.length) { - h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); - await tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + h.turns(run.transcript); + if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; + // A model that ends without calling apply_ops gets ONE schema-bound ask for + // the batch; nothing at all after that is a failing check, not a quiet "0 + // applied". + if (applied.length + refused.length === 0) { + const asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + 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, + meter: h.meter, + signal: deps.signal, + }).catch((e: unknown) => { + h.log(`the ops ask failed: ${(e as Error).message}`); + return null; + }); + if (asked && Array.isArray(asked.ops) && asked.ops.length) { + h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); + applyOps(asked.ops); + } } } + if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, @@ -156,6 +209,15 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< applied: applied.map((a) => (a.warnings ? { ...a.op, warnings: a.warnings } : a.op)), refused: refused.map((r) => ({ ...r.op, why: r.why })), }; + // Release 28 (the M9 ruling): ops that change the cut's order make that + // order a model's draft — reviewable as the cut's row, and redrafted by the + // cut task only with force. An order they leave as it was keeps the + // parent's mark (or none). + if (timelineOrderChanged(parent.manifest, manifest)) { + const m = manifest as VideoManifest & { drafted?: Record<string, unknown> }; + m.drafted = { ...(m.drafted ?? {}), timeline: makeProvenance({ task: "revise-video", model, iteration: h.n, attempt: 1 }) }; + h.log(`the cut's order changed: marked a draft of revise-video on ${model}`); + } const dir = projectDirOf(iteration, input.projectsRoot); const seeded = await seedProject(parent.dir, dir, manifest); await writeManifest(dir, manifest); @@ -166,3 +228,8 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< patch: { ops, projectDir: dir }, }; } + +/** Whether the timeline's order (its entries' ids, the cut's drafted field) differs between two manifests. */ +export function timelineOrderChanged(before: unknown, after: unknown): boolean { + return stableStringify(fieldSignature(before, { field: "timeline" })) !== stableStringify(fieldSignature(after, { field: "timeline" })); +} diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -19,7 +19,7 @@ import { type IterationPatch, } from "../../iterations"; import { ArticleRegistryError } from "../../registry"; -import type { StorePaths, TaskDeps, TaskResult, TaskStatus } from "./types"; +import type { StorePaths, TaskDeps, TaskProgress, TaskResult, TaskStatus } from "./types"; export class TaskInputError extends Error {} @@ -38,6 +38,8 @@ export type TaskHandle = { deps: TaskDeps; paths: StorePaths | undefined; log(line: string): void; + // Progress for the job (deps.progress); a listener never stops the task. + progress(p: TaskProgress): void; // Turns for turns.jsonl (an agent's transcript, a pipeline's events). turns(entries: readonly unknown[]): void; check(c: IterationCheck): void; @@ -133,6 +135,13 @@ export async function runOnIteration( deps, paths, log, + progress: (p) => { + try { + deps.progress?.(p); + } catch { + // a listener never stops the task + } + }, turns: (entries) => turns.push(...entries), check: (c) => { const i = checks.findIndex((x) => x.name === c.name); diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -21,6 +21,7 @@ import { REPORT_STYLE_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, + WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule, } from "../authoringRules"; import { plainAnswer, userCharsFor } from "./llmText"; @@ -93,6 +94,7 @@ function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from `- ${ONE_QUOTE_PER_FINDING_RULE}`, `- ${CLAIM_QUOTES_RULE}`, `- ${VERBATIM_QUOTES_RULE}`, + `- ${WHOLE_SENTENCE_QUOTE_RULE}`, `- ${momentLinkRule(o.origin)}`, `- ${POST_CITATION_RULE}`, `- ${COVERAGE_RULE}`, @@ -109,7 +111,8 @@ const REPAIR_SYSTEM = [ "You repair a sweep report whose quote checks failed. You have the report tools only (read_report, edit_report, write_report); the transcript each fix needs is in the message.", `- ${VERBATIM_QUOTES_RULE}`, `- ${CLAIM_QUOTES_RULE}`, - "For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second), or remove the finding. Never invent words. Edit the report only, then stop.", + `- ${WHOLE_SENTENCE_QUOTE_RULE}`, + "For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second); a fragment's fix is the whole sentence given with it; or remove the finding. Never invent words. Edit the report only, then stop.", ].join("\n"); function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise<string>, count: { n: number }): AgentTool { @@ -197,8 +200,15 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta const web = input.web === false ? [] : (deps.web ?? []); const tools = [...corpusTools, extractTool(h, input, rewrite, extracts), ...file.tools, ...web]; const isApi = providerOf(model) === "api"; + const maxTurns = input.maxTurns ?? 150; + // The job's progress: every model turn, the repair round's included. + let turnsTaken = 0; const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + if (e.type === "turn") { + turnsTaken++; + h.progress({ metric: "turns", current: turnsTaken, total: Math.max(turnsTaken, maxTurns) }); + h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + } else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); else if (e.type === "note") h.log(e.text); }; @@ -210,7 +220,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta tools, meter: h.meter, maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? 150, + maxTurns, ...(isApi && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 5 } } : {}), signal: deps.signal, onEvent, @@ -238,7 +248,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta system: REPAIR_SYSTEM, user: "The quote checks refused these citations — the quoted words are not, word for word, what the transcript says " + - `at that moment:\n${describeProblems(problems)}\n\nThe report now:\n\n${file.text()}`, + `at that moment, or the quote is a fragment:\n${describeProblems(problems)}\n\nThe report now:\n\n${file.text()}`, tools: file.tools, meter: h.meter, maxUsd: h.meter.usd + allowance, diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -15,6 +15,7 @@ import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; import { writeIterationFile } from "../../iterations"; import { mmss } from "../reportOps"; import { strictNormalize } from "../../../citations/verify"; +import { fragmentOf, fullSentenceFor } from "../../../citations/fragment"; import { momentHref } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; @@ -53,7 +54,7 @@ export const TERMS_SCHEMA = { export const EXTRACT_SYSTEM = "You read excerpts of an automatic transcript and pick out evidence for a research question. Rules: (1) Only use the " + "excerpt; never add facts. (2) Each quote is copied EXACTLY, character for character, from consecutive transcript " + - "lines, without the bracketed timestamps; at least 8 and at most 40 words; do not fix grammar, spelling or names. " + + "lines, without the bracketed timestamps; at least 8 and at most 40 words, a whole sentence or clause; do not fix grammar, spelling or names. " + "(3) Each claim is one plain sentence saying what the speaker says in that quote, attributed to the speaker; keep " + "every negation (not, never, no) and every hedge (maybe, I think, allegedly, if) the quote has; do not state motives " + "or feelings; do not exaggerate; paraphrase in the third person in at most 20 words, do not repeat the quote. Set " + @@ -365,6 +366,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T let nChunks = 0; let nRelevant = 0; const readIds: string[] = []; + // The job's progress: the recordings gone through, of the worklist. + let visited = 0; + h.progress({ metric: "entries", current: 0, total: todo.length }); for (let b = 0; b < todo.length; b += READ_BATCH) { deps.signal?.throwIfAborted(); const batch = todo.slice(b, b + READ_BATCH); @@ -379,6 +383,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const p = parsed.get(v.id); if (!p || !p.lines.length) { event({ kind: "unread", video: v.id, why: "no windows returned" }); + h.progress({ metric: "entries", current: ++visited, total: todo.length }); continue; } readIds.push(v.id); @@ -419,16 +424,29 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { - const quote = String(raw.quote ?? "") + let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:]+\]\s*/, ""); const claim = String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); - const wc = quote.split(" ").filter(Boolean).length; const sec = locate(quote, ch); + // A quote that stops mid-thought (Q2) becomes its whole sentence + // when the window has one: code copies the words, still verbatim. + const frag = sec === null ? null : fragmentOf(quote); + if (frag) { + const lines = win.map(([s, t], i) => ({ start: s, end: win[i + 1]?.[0] ?? s + 1, text: t })); + const whole = fullSentenceFor(quote, lines, sec!, { windowSeconds: Number.MAX_SAFE_INTEGER }); + if (whole && whole.split(" ").length <= MAX_QUOTE_WORDS) { + event({ kind: "extended", video: v.id, quote, to: whole }); + quote = whole; + } + } + const wc = quote.split(" ").filter(Boolean).length; + const stillFragment = sec === null ? null : fragmentOf(quote); let why: string | null = null; if (sec === null) why = "not verbatim in its window"; + else if (stillFragment) why = `a fragment (${stillFragment.why})`; else if (wc < MIN_QUOTE_WORDS) why = `too short (${wc} words)`; else if (wc > MAX_QUOTE_WORDS) why = `too long (${wc} words)`; else if (!claim) why = "no claim"; @@ -456,6 +474,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T } } h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); + h.progress({ metric: "entries", current: ++visited, total: todo.length }); } } if (!kept.length) { diff --git a/common/lib/report/draft/tasks/tasks.test.ts b/common/lib/report/draft/tasks/tasks.test.ts @@ -15,6 +15,8 @@ import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { cardContext, chooseDraft } from "./narrate"; import { groundingInputOf } from "../grounding"; +const DRAFT_SWEEPS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../testing/draft/sweeps"); + const stubCorpus = (slugs: Record<string, string>) => ({ calls: [] as unknown[], async call(name: string, args: Record<string, unknown> = {}) { @@ -173,6 +175,27 @@ test("quotes: the strict check over cues and posts; the failing finding dropped, assert.ok(more.length > problems.length); }); +test("quotes: a generated fragment is a failing quote whose repair hint is the full sentence (testing/draft/sweeps/fragment.md)", async () => { + const md = await readFile(path.join(DRAFT_SWEEPS, "fragment.md"), "utf8"); + const c = await convertSweepText(md, { id: "frag", cuesOf }); + assert.ok(c.ok); + if (!c.ok) return; + const problems = await checkQuotes(c.report, { cuesOf }); + assert.equal(problems.length, 3); + const by = Object.fromEntries(problems.map((p) => [p.quote, p])); + assert.equal(by["I paid for the"]!.fragment!.sentence, "I paid for the new mixer myself"); + assert.match(by["I paid for the"]!.why, /a fragment \(ends on “the”\).*quote the whole sentence: "I paid for the new mixer myself"/); + assert.equal(by["my lawyer told me not to"]!.fragment!.sentence, "my lawyer told me not to talk about the lease"); + assert.match(by["I did not"]!.why, /under 4 words.*"I did not enter the contest this year"/); + // Still a fragment after the repair round: the finding goes, the whole one stays. + const d = dropFailedFindings(md, problems); + assert.equal(d.dropped.length, 3); + assert.ok(d.md.includes('"I have never met the other finalist"')); + // A verify-quotes `fragment` is a warning, not one more problem. + const more = await checkQuotes(c.report, { cuesOf, verifyReport: async () => [{ citation: "c04", status: "fragment" }] }); + assert.equal(more.length, 3); +}); + test("narrate: a card's evidence; the better draft kept, failing sentences removed, never rewritten", async () => { const report = { title: "The baker", diff --git a/common/lib/report/draft/tasks/teaser.test.ts b/common/lib/report/draft/tasks/teaser.test.ts @@ -0,0 +1,143 @@ +// TASK teaser (release 28 M3) over the S0 kit's manifests and the basic +// report, against the fake ollama: a cut with no teaser gets one after its +// last clip; each code check refuses what it should (count, length, one line, +// quotation marks, a quote's run, names and numbers, the build's own +// validateTeaser); the better of two kept; the operator's lines kept and the +// draft an alternative; the umtool lint passes on what is written. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; +import { loadDeckChecks, type DeckChecks } from "./deckChecks"; +import { checkTeaser, claimGist, parseTeaser, teaser, teaserEvidence } from "./teaser"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "../../../../.."); +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); +const run = promisify(execFile); + +let tmp: string; +let ol: FakeOllama; +let deck: DeckChecks; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "teaser-task-")); + ol = await startFakeOllama(); + deck = await loadDeckChecks(ROOT); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown, withDeck = true) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + now: () => new Date("2026-10-13T12:00:00.000Z"), + ...(withDeck ? { deckChecks: async () => deck } : {}), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "teaser-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, deps, lines, manifestNow, draft, input, report }; +} + +test("teaser, the recorded run: a cut with none gets one after its last clip; the better of two kept; the umtool lint passes", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const p = await project(m); + const r = await kit("runs/teaser.json"); + ol.push(...r.turns); + const out = await teaser(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + const after = await p.manifestNow(); + assert.deepEqual(after.timeline.map((e: { id: string }) => e.id).slice(-2), ["c06", "teaser"]); + const t = after.timeline.at(-1); + assert.deepEqual(t, { + type: "teaser", + id: "teaser", + lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"], + drafted: { lines: { task: "teaser", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 } }, + }); + const first = ((await p.draft()).units.teaser as { attempts: { hard: string[] }[] }).attempts[0]!.hard.join("\n"); + assert.match(first, /line 2 repeats a quote \("would never sell the bakery"\)/); + assert.match(first, /line 4: number “two” is not in the report/); + const lint = await run(process.execPath, [path.join(ROOT, "umtool/report-to-video/lint.mjs"), path.join(p.dir, "video.manifest.json"), "--json"]).catch((e) => e); + assert.deepEqual(JSON.parse(lint.stdout).errors, [], lint.stdout); +}); + +test("teaser's checks, each alone; the build's validateTeaser is one of them", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const u = { id: "teaser", entry: null, evidence: teaserEvidence(report, m), quotes: Object.values(report.citations).map((c) => (c as { quote: string }).quote), deck }; + const hard = (lines: string[], unit: typeof u = u) => checkTeaser(lines, unit).hard; + assert.deepEqual(hard(["Synth Kitchen", "The bakery", "The contest"]), []); + assert.match(hard(["Synth Kitchen", "The bakery"]).join(), /2 lines \(3 to 5\)/); + assert.match(hard(["Synth Kitchen", "The bakery", "The contest", "The bakery", "The contest", "Synth Kitchen"]).join(), /6 lines \(3 to 5\)/); + assert.match(hard(["Synth Kitchen", "The bakery", "x".repeat(71)]).join(), /line 3 is 71 characters \(at most 70\)/); + assert.match(hard(["Synth Kitchen", "The\nbakery", "The contest"]).join(), /line 2 is more than one line/); + assert.match(hard(["Synth Kitchen", "“The bakery”", "The contest"]).join(), /line 2 has quotation marks/); + assert.deepEqual(hard(["Synth Kitchen", "The baker's bakery", "The contest"]), [], "an apostrophe is not a quotation"); + assert.match(hard(["Synth Kitchen", "The bakery", "In 2025"]).join(), /line 3: number 2025 is not in the report/); + assert.match(hard(["Synth Kitchen", "The bakery", "Ask Marco"]).join(), /line 3: name “Marco” is not in the report/); + // A middle line is a title: past its row's fit the build refuses it. + assert.match(hard(["Synth Kitchen", "The bakery and the contest and the oven", "The contest"]).join(), /it would not build: .*lines\[1\]/); + // Without the build's check nothing is written. + assert.match(hard(["Synth Kitchen", "The bakery", "The contest"], { ...u, deck: null as never }).join(), /not available, so the lines are not written/); + assert.equal(claimGist('She says she would not sell: "I would never sell the bakery to a chain"'), "She says she would not sell"); + assert.deepEqual(parseTeaser({ lines: [" a ", { text: "b" }, ""] }), ["a", "b"]); + assert.throws(() => parseTeaser({}), /no "lines"/); +}); + +test("teaser: the operator's lines kept (forced, the draft an alternative); a teaser with no deck check is not written", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const p = await project(full); + const skipped = await teaser(p.input(), p.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p.draft()).units.fin!.skipped), /the operator's/); + ol.push(jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] })); + const forced = await teaser(p.input({ force: true }), p.deps); + assert.match(forced.summary, /^0 teaser\(s\) drafted, 1 as alternatives/); + assert.deepEqual((await p.manifestNow()).timeline.at(-1).lines, full.timeline.at(-1).lines); + assert.deepEqual((await p.draft()).alternatives.map((a) => [a.target.entry, a.reason]), [["fin", "operator"]]); + // Dates in the evidence: the full kit's clips carry none, the evidence says so by leaving them out. + assert.doesNotMatch(teaserEvidence(p.report, full), /Sources dated/); + const dated = structuredClone(full); + dated.timeline.find((e: { id: string }) => e.id === "c07").date = "2026-03-01"; + dated.timeline.find((e: { id: string }) => e.id === "c01").date = "2026-01-05"; + assert.match(teaserEvidence(p.report, dated), /Sources dated: January 2026 to March 2026/); + + const q = await project(await kit("manifests/basic.video.manifest.json"), false); + ol.push(jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] }), jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] })); + const none = await teaser(q.input(), q.deps); + assert.equal(none.status, "failed"); + assert.equal((await q.manifestNow()).timeline.some((e: { type: string }) => e.type === "teaser"), false, "no teaser added"); + assert.equal(ol.remaining(), 0); +}); diff --git a/common/lib/report/draft/tasks/teaser.ts b/common/lib/report/draft/tasks/teaser.ts @@ -0,0 +1,207 @@ +// TASK teaser — the lines of the cut's teaser card (release 28 M3). A STEP on +// a done iteration (./media.ts): one unit per teaser entry, the field `lines`. +// +// The evidence is the report as a whole: its title and subtitle, its section +// titles, each claim's gist (its words, the quoted ones taken out) and the +// days its sources are from. The lines are TEASER_MIN_LINES to +// TEASER_MAX_LINES, each one line of at most TEASER_LINE_MAX characters; the +// first is drawn as the overline, the middle ones as titles and the last as +// the kicker (a date, or the turn), and each must fit its role's row — which +// the build's own `validateTeaser` judges (umtool's deck.mjs, through +// `TaskDeps.deckChecks`; a teaser it cannot check is not written). No line +// reads a quote out: no quotation marks, and no run of TEASER_QUOTE_RUN words +// from any citation's quote. No name or number the evidence does not have. +// +// A cut with no teaser gets one: an entry `{type: "teaser", id: "teaser"}` +// after its last clip, its lines written through applyDraft as any empty +// field — the operator deletes it like any entry. + +import { strictNormalize } from "../../../citations/verify"; +import { applyDraft, entriesWithId } from "../../drafted.mjs"; +import { groundedProblems } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import type { DeckChecks } from "./deckChecks"; +import { runMediaTask, type MediaContext, type MediaReport, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const TEASER_MIN_LINES = 3; +export const TEASER_MAX_LINES = 5; +export const TEASER_LINE_MAX = 70; +// A run this long copied from a quote is the quote read out. +export const TEASER_QUOTE_RUN = 5; +// The row each role fits (deck.mjs TEASER_LIMITS.fit): the prompt's rule; the +// build's validator is the check. +const ROLE_FIT = { overline: 64, title: 34, kicker: 56 }; +export const NEW_TEASER_ID = "teaser"; + +export type TeaserInput = MediaTaskInput; + +type TeaserUnit = MediaUnit & { + // The teaser entry as it is (null: the cut has none, and the task adds it). + entry: ManifestEntry | null; + evidence: string; + quotes: string[]; + deck: DeckChecks | null; +}; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); +const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’|(^|\s)'[^']+'(?=[\s.,;:!?]|$)/; + +/** A claim's gist: its words with every quoted part (and the colon before it) taken out. */ +export function claimGist(text: string): string { + return stripCites(text) + .replace(/:?\s*("[^"]*"|“[^”]*”)/g, "") + .replace(/\s+/g, " ") + .replace(/[\s:,;]+$/, "") + .trim(); +} + +const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +/** The report as the teaser may use it: titles, section titles, claim gists, the days of its sources. */ +export function teaserEvidence(report: MediaReport, manifest: VideoManifest): string { + const lines = [`Report: ${String(report.title ?? "")}`]; + if (report.subtitle) lines.push(`Subtitle: ${String(report.subtitle)}`); + for (const s of Array.isArray(report.sections) ? report.sections : []) { + const gists = (Array.isArray(s?.claims) ? s.claims : []).map((c: Obj) => claimGist(String(c?.text ?? ""))).filter(Boolean); + if (!gists.length) continue; + lines.push(`Section: ${String(s.title ?? "")}`); + for (const g of gists.slice(0, 8)) lines.push(`- ${g}`); + } + const days = new Set<string>(); + for (const c of Object.values(isObj(report.citations) ? report.citations : {})) if (typeof (c as Obj)?.date === "string") days.add((c as Obj).date.slice(0, 10)); + for (const e of manifest.timeline) if (typeof e.date === "string") days.add(e.date.slice(0, 10)); + const sorted = [...days].filter((d) => /^\d{4}-\d{2}/.test(d)).sort(); + if (sorted.length) { + const month = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1] ?? ""} ${d.slice(0, 4)}`.trim(); + lines.push(`Sources dated: ${month(sorted[0]!)}${sorted.length > 1 && month(sorted.at(-1)!) !== month(sorted[0]!) ? ` to ${month(sorted.at(-1)!)}` : ""}`); + } + return lines.join("\n"); +} + +/** The quote words a line repeats in a run of TEASER_QUOTE_RUN or more, or null. */ +export function quoteRunIn(line: string, quotes: readonly string[]): string | null { + const said = ` ${strictNormalize(line)} `; + for (const q of quotes) { + const w = strictNormalize(q).split(" ").filter(Boolean); + for (let k = 0; k + TEASER_QUOTE_RUN <= w.length; k++) { + const run = w.slice(k, k + TEASER_QUOTE_RUN).join(" "); + if (said.includes(` ${run} `)) return run; + } + } + return null; +} + +/** The teaser entry these lines would make. */ +export const teaserEntryOf = (u: Pick<TeaserUnit, "entry" | "id">, lines: string[]): ManifestEntry => + ({ ...(u.entry ?? { type: "teaser", id: u.id }), lines }) as ManifestEntry; + +/** Every code check of a teaser's lines: `hard` refuses them. */ +export function checkTeaser(lines: string[], u: Pick<TeaserUnit, "entry" | "id" | "evidence" | "quotes" | "deck">): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (lines.length < TEASER_MIN_LINES || lines.length > TEASER_MAX_LINES) hard.push(`${lines.length} lines (${TEASER_MIN_LINES} to ${TEASER_MAX_LINES})`); + lines.forEach((l, i) => { + const n = `line ${i + 1}`; + if (!l.trim()) hard.push(`${n} is empty`); + if (/[\r\n]/.test(l)) hard.push(`${n} is more than one line`); + if (l.trim().length > TEASER_LINE_MAX) hard.push(`${n} is ${l.trim().length} characters (at most ${TEASER_LINE_MAX})`); + if (QUOTE_MARKS_RE.test(l)) hard.push(`${n} has quotation marks: a teaser reads no quote out`); + const run = quoteRunIn(l, u.quotes); + if (run) hard.push(`${n} repeats a quote ("${run}"): the clips say it; the teaser does not read it out`); + for (const p of groundedProblems(l, u.evidence, "the report")) hard.push(`${n}: ${p}`); + }); + if (!hard.length) { + if (!u.deck) hard.push("the build's teaser check (deck.mjs validateTeaser) is not available, so the lines are not written"); + else for (const e of u.deck.validateTeaser(teaserEntryOf(u, lines), `teaser ${u.id}`)) hard.push(`it would not build: ${e}`); + } + return { hard, soft: [] }; +} + +export function teaserSystem(): string { + const rules = [ + `Write ${TEASER_MIN_LINES} to ${TEASER_MAX_LINES} short lines, each one line of plain words.`, + `The first line is the overline (at most ${ROLE_FIT.overline} characters): who or what the video is about.`, + `The middle lines are titles (each at most ${ROLE_FIT.title} characters): the questions or findings the video turns on, without giving the answers away.`, + `The last line is the kicker (at most ${ROLE_FIT.kicker} characters): when, or the turn the video ends on.`, + "Read no quote out: no quotation marks, and do not repeat the speakers' words.", + "Use only names, numbers and dates that appear in the evidence.", + "Write in the third person.", + ]; + return ( + "You write the teaser card that closes a short evidence video: a few lines that slam in one after another. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "lines": the lines in order.' + ); +} + +const SCHEMA = { type: "object", properties: { lines: { type: "array", items: { type: "string" } } }, required: ["lines"] }; + +/** The model's answer to lines (a throw is a hard failure). */ +export function parseTeaser(answer: unknown): string[] { + const a = isObj(answer) ? answer : {}; + if (!Array.isArray(a.lines)) throw new Error('no "lines" in the answer'); + return a.lines.map((l: unknown) => (typeof l === "string" ? l : isObj(l) && typeof l.text === "string" ? l.text : String(l ?? "")).trim()).filter((l: string) => l !== ""); +} + +// A free id for a new teaser: "teaser", else "teaser-2", … +function freeId(manifest: VideoManifest): string { + const ids = new Set(manifest.timeline.map((e) => e.id)); + if (!ids.has(NEW_TEASER_ID)) return NEW_TEASER_ID; + for (let i = 2; ; i++) if (!ids.has(`${NEW_TEASER_ID}-${i}`)) return `${NEW_TEASER_ID}-${i}`; +} + +async function teaserUnits(ctx: MediaContext<TeaserInput>): Promise<TeaserUnit[]> { + const { manifest, report } = ctx; + let deck: DeckChecks | null = null; + try { + deck = (await ctx.handle.deps.deckChecks?.()) ?? null; + } catch (e) { + ctx.handle.log(` the build's teaser check is not loaded (${(e as Error).message})`); + } + const evidence = teaserEvidence(report, manifest); + const quotes = Object.values(isObj(report.citations) ? report.citations : {}) + .map((c) => String((c as Obj)?.quote ?? "")) + .concat(manifest.timeline.map((e) => String(e.quote ?? ""))) + .filter(Boolean); + const seen = new Set<string>(); + const teasers = manifest.timeline.filter((e) => e.type === "teaser" && !seen.has(e.id) && seen.add(e.id)); + const base = { evidence, quotes, deck }; + if (!teasers.length) { + const id = freeId(manifest); + return [{ id, target: { entry: id, field: "lines" }, label: "a new teaser after the last clip", entry: null, ...base }]; + } + return teasers.map((e) => ({ id: e.id, target: { entry: e.id, field: "lines" }, entry: e, ...base })); +} + +/** The teaser as a media task (./media.ts): one unit per teaser entry, or one new teaser. */ +export const TEASER_SPEC: MediaTaskSpec<TeaserUnit, string[], TeaserInput> = { + task: "teaser", + noun: "teaser", + verb: "drafted", + progressMetric: "entries", + units: (ctx) => teaserUnits(ctx), + schema: () => SCHEMA, + system: () => teaserSystem(), + user: (u) => `Evidence (the only facts you may use):\n${u.evidence}\n\nWrite the teaser's lines.`, + parse: (answer) => parseTeaser(answer), + check: (lines, u) => checkTeaser(lines, u), + apply(manifest, u, value, provenance, force) { + // No teaser yet: add one after the last clip, then write its lines as any + // empty field. + if (!u.entry && !entriesWithId(manifest, u.id).length) { + let at = -1; + manifest.timeline.forEach((e, i) => { + if (e.type === "clip") at = i; + }); + manifest.timeline.splice(at < 0 ? manifest.timeline.length : at + 1, 0, { type: "teaser", id: u.id } as ManifestEntry); + } + return applyDraft(manifest, { entry: u.id, field: "lines", value, provenance, force }); + }, + describe: (lines) => lines.join(" / "), +}; + +export async function teaser(input: TeaserInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(TEASER_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/threads.ts b/common/lib/report/draft/tasks/threads.ts @@ -0,0 +1,284 @@ +// TASK threads — the cut's clips grouped into the few lines of argument they +// make (release 28, M5): `render.chrome.threads.list` and each clip's +// `thread` key, drawn as the rail down the frame's left +// (umtool/report-to-video/threads.mjs). A STEP on a done iteration, on the +// media task scaffold (./media.ts): one unit, the whole field. +// +// The model names the threads (an id and a label) and puts each clip in one, +// or in none. CODE checks it all: +// - 2 to 4 threads (THREADS_TASK_COUNT; the rail takes up to +// THREADS_LIMITS.threads[1]), ids that are ids and not listed twice, +// labels of one line of at most THREADS_LIMITS.label characters whose +// names and numbers are the report's (grounding); +// - every assignment names a clip of the cut and a listed thread, a clip +// is in one thread at most, every thread has a clip; +// - a thread's OUTCOME is code's: the claim verdict its last clip carries in +// the manifest (`claim.verdict`), when it carries one — the model never +// sets a verdict; +// - the result passes the build's own validateThreads and +// validateThreadEntries (common's panels.mjs). +// A thread failing a check is dropped with its clips when at least two stand +// (the repair); the better of two attempts is kept. Applied: the list through +// applyDraft, then every clip's `thread` set (or removed: a clip in no thread +// has none) — the mark covers both. +// +// ONE LEFT PANEL: flips and threads share it. A cut with flips is refused — +// unless `force` and the flips are a draft: then the threads replace them and +// the log says so. A cut with no on-screen deck (`render.chrome`) is refused. + +import { applyDraft, clearDrafted, ownerOf } from "../../drafted.mjs"; +import { THREADS_LIMITS, flipsOn, validateThreadEntries, validateThreads } from "../../panels.mjs"; +import { VERDICTS } from "../../verdicts.mjs"; +import type { GroundingInput } from "../grounding"; +import type { VideoManifest } from "../videoOps"; +import { checkLine, clipFacts, clipLine, fitLines, type ClipFact } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import { TaskInputError } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export type ThreadsInput = MediaTaskInput; + +/** How many threads a draft makes. */ +export const THREADS_TASK_COUNT = Object.freeze([2, 4] as const); + +export type ProposedThread = { id: string; label: string }; +export type ThreadsValue = { threads: ProposedThread[]; assign: { clip: string; thread: string }[] }; + +export type Thread = { id: string; label: string; outcome?: { verdict: string } }; +export type ThreadsPlan = { + list: Thread[]; + // clip id → thread id, for every clip in a thread. + clips: Record<string, string>; + threadProblems: string[][]; + problems: string[]; + soft: string[]; +}; + +type ThreadsUnit = MediaUnit & { + manifest: VideoManifest; + clips: ClipFact[]; + g: GroundingInput; + dropFlips: boolean; + chosen?: ThreadsPlan; +}; + +const EVIDENCE_BUDGET = 14_000; +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** A thread id as code keeps it: the model's, else made from its label. */ +export function threadId(raw: string, label: string, i: number): string { + const id = oneLine(raw); + if (ID_RE.test(id)) return id; + const base = (id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); + return /^[a-z0-9]/.test(base) ? base : `thread-${i + 1}`; +} + +/** A clip's verdict as the manifest has it (`claim.verdict`), or null. */ +const manifestVerdict = (m: VideoManifest, id: string): string | null => { + const v = (m.timeline.find((e) => e.type === "clip" && e.id === id)?.claim as { verdict?: unknown } | undefined)?.verdict; + return typeof v === "string" && (VERDICTS as readonly string[]).includes(v) ? v : null; +}; + +/** Code's reading of a proposal over this cut (pure). */ +export function planThreads(value: ThreadsValue, unit: Pick<ThreadsUnit, "clips" | "g" | "dropFlips">, manifest: VideoManifest): ThreadsPlan { + const [lo, hi] = THREADS_TASK_COUNT; + const problems: string[] = []; + const soft: string[] = []; + const n = value.threads.length; + if (n < lo || n > hi) problems.push(`${n} thread(s): ${lo} to ${hi}`); + const byClip = new Map(unit.clips.map((c) => [c.id, c])); + // The model's id → code's, and each thread's problems. + const ids = new Map<string, string>(); + const seen = new Set<string>(); + const threadProblems: string[][] = value.threads.map((t, i) => { + const bad: string[] = []; + const label = oneLine(t.label); + const id = threadId(t.id, label, i); + const w = `thread ${i + 1} (${id})`; + if (seen.has(id)) bad.push(`${w}: the id ${id} is listed twice`); + seen.add(id); + if (!ids.has(oneLine(t.id))) ids.set(oneLine(t.id), id); + if (!label) bad.push(`${w}: no label`); + else if (label.length > THREADS_LIMITS.label) bad.push(`${w}: the label is ${label.length} characters (at most ${THREADS_LIMITS.label})`); + else for (const h of checkLine(label, unit.g).hard) bad.push(`${w}: the label: ${h}`); + return bad; + }); + const listed = value.threads.map((t, i) => threadId(t.id, oneLine(t.label), i)); + const clips: Record<string, string> = {}; + for (const a of value.assign) { + const clip = oneLine(a.clip); + const raw = oneLine(a.thread); + if (!raw) continue; // in no thread + const t = ids.get(raw) ?? (listed.includes(raw) ? raw : null); + if (!byClip.has(clip)) problems.push(`${clip || "(none)"} is not a clip of the cut`); + else if (!t) problems.push(`${clip} is put in ${raw}, which is not a listed thread`); + else if (clips[clip] !== undefined && clips[clip] !== t) problems.push(`${clip} is put in two threads (${clips[clip]}, ${t})`); + else clips[clip] = t; + } + listed.forEach((id, i) => { + if (!Object.values(clips).includes(id)) threadProblems[i]!.push(`thread ${i + 1} (${id}) has no clip`); + }); + // The outcome: the verdict its last clip (in the cut's order) carries. + const list: Thread[] = value.threads.map((t, i) => { + const id = listed[i]!; + const mine = unit.clips.filter((c) => clips[c.id] === id).sort((a, b) => a.index - b.index); + const verdict = mine.length ? manifestVerdict(manifest, mine.at(-1)!.id) : null; + return { id, label: oneLine(t.label), ...(verdict ? { outcome: { verdict } } : {}) }; + }); + if (!problems.length && !threadProblems.some((x) => x.length)) { + // The build's own checks, on the cut as it will be. + const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (after.render?.chrome) { + if (unit.dropFlips) delete after.render.chrome.flips; + after.render.chrome.threads = { list }; + } + setClipThreads(after, clips); + problems.push(...validateThreads({ list }), ...validateThreadEntries(after)); + } + return { list, clips, threadProblems, problems, soft }; +} + +/** Every clip's `thread`: the one it is in, or none. */ +export function setClipThreads(m: VideoManifest, clips: Record<string, string>) { + for (const e of m.timeline) { + if (e.type !== "clip") continue; + if (clips[e.id]) e.thread = clips[e.id]; + else delete e.thread; + } +} + +const allProblems = (p: ThreadsPlan) => [...p.problems, ...p.threadProblems.flat()]; + +export function threadsSystem(): string { + const [lo, hi] = THREADS_TASK_COUNT; + return ( + "You group the clips of a short evidence video into threads: the few lines of argument the clips make, drawn as a " + + `rail of cards beside the footage. Rules: (1) ${lo} to ${hi} threads; (2) each thread has an id (letters, digits ` + + `and -) and a label of at most ${THREADS_LIMITS.label} characters in plain words, no quotation marks, no first ` + + "person, nothing the evidence does not say; (3) put each clip in at most one thread, by its id from the list; a " + + "clip that fits none is left out; (4) every thread has at least one clip; (5) you never write a verdict or an " + + "outcome." + ); +} + +export const THREADS_SPEC: MediaTaskSpec<ThreadsUnit, ThreadsValue, ThreadsInput> = { + task: "threads", + noun: "thread rail", + async units(ctx: MediaContext<ThreadsInput>) { + const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; + if (!m.render?.chrome || typeof m.render.chrome !== "object") { + throw new TaskInputError("threads are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); + } + let dropFlips = false; + if (flipsOn(m.render)) { + const owner = ownerOf(m, { field: "render.chrome.flips" }); + if (!ctx.input.force || owner === "operator") { + throw new TaskInputError( + "this cut has flips (render.chrome.flips), and flips and threads share the left panel" + + (owner === "operator" ? ": the flips are the operator's — remove them first" : ": force replaces drafted flips"), + ); + } + dropFlips = true; + } + const clips = await clipFacts(m, ctx.report, null, { dates: false }); + if (clips.length < THREADS_TASK_COUNT[0]) { + return [{ id: "threads", skipped: `${clips.length} clip(s): ${THREADS_TASK_COUNT[0]} threads need at least ${THREADS_TASK_COUNT[0]}` }]; + } + return [{ id: "threads", target: { field: "render.chrome.threads" }, label: "Threads", manifest: m, clips, g: ctx.grounding, dropFlips }]; + }, + schema: () => ({ + type: "object", + properties: { + threads: { + type: "array", + items: { type: "object", properties: { id: { type: "string" }, label: { type: "string" } }, required: ["id", "label"] }, + }, + clips: { + type: "array", + items: { type: "object", properties: { clip: { type: "string" }, thread: { type: "string" } }, required: ["clip", "thread"] }, + }, + }, + required: ["threads", "clips"], + }), + system: () => threadsSystem(), + user(u, ctx) { + const r = ctx.report as { title?: string; summary?: string | null }; + const ev = fitLines(u.clips.map((c) => clipLine(c, { date: false })), EVIDENCE_BUDGET); + return ( + `Report: ${r.title ?? ""}` + + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + + `\n\nThe cut's clips, in order (id (chapter): "quote" — the claim it stands for):\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + + '\n\nName the threads, then give every clip its thread ("" for none).' + ); + }, + parse(answer) { + const a = answer as { threads?: unknown; clips?: unknown } | null; + if (!Array.isArray(a?.threads)) throw new Error("no threads list in the answer"); + const objs = (v: unknown) => (Array.isArray(v) ? v : []).filter((x): x is Record<string, unknown> => !!x && typeof x === "object"); + return { + threads: objs(a.threads).map((t) => ({ id: oneLine(t.id), label: oneLine(t.label) })), + assign: objs(a.clips).map((c) => ({ clip: oneLine(c.clip), thread: oneLine(c.thread) })), + }; + }, + check(value, u) { + const plan = planThreads(value, u, u.manifest); + return { hard: allProblems(plan), soft: plan.soft }; + }, + // The best attempt's threads that pass, with their clips, when at least two stand. + repair(attempts, u) { + let best: MediaAttempt<ThreadsValue> | null = null; + for (const a of attempts) { + if (!a.value) continue; + const plan = planThreads(a.value, u, u.manifest); + const keepIdx = plan.list.map((_, i) => i).filter((i) => !plan.threadProblems[i]?.length).slice(0, THREADS_TASK_COUNT[1]); + const keep = new Set(keepIdx.map((i) => plan.list[i]!.id)); + const v: ThreadsValue = { + threads: keepIdx.map((i) => ({ id: plan.list[i]!.id, label: plan.list[i]!.label })), + assign: Object.entries(plan.clips) + .filter(([, t]) => keep.has(t)) + .map(([clip, thread]) => ({ clip, thread })), + }; + if (v.threads.length < THREADS_TASK_COUNT[0]) continue; + const again = planThreads(v, u, u.manifest); + if (allProblems(again).length) continue; + if (!best || v.threads.length > best.value!.threads.length) { + best = { value: v, hard: [], soft: [...again.soft, `${a.value.threads.length - v.threads.length} refused thread(s) dropped`] }; + } + } + return best; + }, + // The field is `{list}`; what an alternative keeps also carries `clips`, the + // clip → thread assignments, so umtool's "Use this" sets each clip's thread + // with the list (release 28 M9). `apply` writes the list alone. + toField(value, u) { + u.chosen = planThreads(value, u, u.manifest); + return { list: u.chosen.list, clips: u.chosen.clips }; + }, + apply(manifest, u, value, provenance, force, ctx) { + const { list } = value as { list: unknown }; + const res = applyDraft(manifest, { field: "render.chrome.threads", value: { list }, provenance, force }); + if (!res.applied) return res; + setClipThreads(manifest, u.chosen?.clips ?? {}); + const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (u.dropFlips && m.render?.chrome) { + delete m.render.chrome.flips; + clearDrafted(m, { field: "render.chrome.flips" }); + ctx.handle.log(" the drafted flips were removed: flips and threads share the left panel"); + } + return res; + }, + describe(v, u) { + const plan = planThreads(v, u, u.manifest); + const count = (id: string) => Object.values(plan.clips).filter((t) => t === id).length; + return ( + plan.list.map((t) => `${t.label} (${count(t.id)} clip(s)${t.outcome ? `, ${t.outcome.verdict}` : ""})`).join("; ") + + (u.dropFlips ? " — replaces the drafted flips" : "") + ); + }, +}; + +export async function threads(input: ThreadsInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(THREADS_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -8,11 +8,13 @@ // log and the job's AbortSignal. Nothing here reads settings: the editor job // (S6) builds the deps from `settings.generation`. +import { MEDIA_STEP_TASKS } from "../../../generationSettings"; import type { AgentTool, LlmConfig } from "../../../llm"; import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { readIteration } from "../../iterations"; import type { Report } from "../../schema"; import type { ResearchEditor } from "../research/tools"; +import type { DeckChecks } from "./deckChecks"; // The iterations store's paths (S4 takes them on every call). export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>; @@ -28,6 +30,13 @@ export type CorpusToolsLike = { // the corpus on disk, which also sees the en-orig track). export type ExternalQuoteProblem = { citation: string; status: string; message?: string }; +// How far a task has got (release 28 F3): an agent's turns, a media task's +// cards, a pipeline's recordings read (or a media task's entries). `total`, +// when known, is the target (an agent's: its turn cap). The editor job maps it +// onto its JobProgress. +export type TaskProgressMetric = "turns" | "cards" | "entries"; +export type TaskProgress = { metric: TaskProgressMetric; current: number; total?: number }; + export type TaskDeps = { llm: LlmConfig; corpus: CorpusToolsLike; @@ -52,6 +61,12 @@ export type TaskDeps = { paths?: StorePaths; now?: () => Date; log?: (line: string) => void; + // Progress, as the task counts it (the editor job's setProgress). + progress?: (p: TaskProgress) => void; + // The build's validators (umtool's report-to-video, loaded from the + // checkout: ./deckChecks.ts) — a media task's checks that the cut it + // drafts still builds (release 28). + deckChecks?: () => Promise<DeckChecks>; signal?: AbortSignal; }; @@ -70,5 +85,8 @@ export type TaskResult = { minutes: number; }; -export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate", "research"] as const; +// The media tasks (narrate first; release 28's cut, onscreen, teaser, flips, +// threads and youtube) are generationSettings' MEDIA_STEP_TASKS: each a step +// on a done iteration (./media.ts). +export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", ...MEDIA_STEP_TASKS] as const; export type TaskName = (typeof TASK_NAMES)[number]; diff --git a/common/lib/report/draft/tasks/youtube.ts b/common/lib/report/draft/tasks/youtube.ts @@ -0,0 +1,160 @@ +// TASK youtube — the upload's title and summary (release 28, M6): +// `publish.youtube { title, description }`. A STEP on a done iteration, on the +// media task scaffold (./media.ts): one unit, the whole field. +// +// The model writes the title and ONE summary paragraph; the build composes +// out/youtube.txt from them (umtool/report-to-video/youtube.mjs: the chapters +// from its own chapter list, a moment link per cited clip), so the summary +// leaves room for those under YouTube's 5000. CODE checks: +// - the title is one line of at most PUBLISH_YOUTUBE_LIMITS.title +// characters; the summary one paragraph of at most YOUTUBE_SUMMARY_MAX; +// - grounded (./grounding.ts, ./clipEvidence.ts checkLine): every name and +// number is the evidence's (the report's title, summary, sections, claims +// and quotes, the cut's title and subtitle); no stock phrase; third person +// (Q1: a first-person word outside quotation marks is refused); words in +// quotation marks only when a cited quote says them word for word; +// - no links, timestamps or chapter list: those are code's. +// A summary failing a check loses its failing sentences when what is left +// stands (the repair); the better of two attempts is kept. + +import { PUBLISH_YOUTUBE_LIMITS } from "../../drafted.mjs"; +import { sentencesOf, type GroundingInput } from "../grounding"; +import type { VideoManifest } from "../videoOps"; +import { checkLine, fitLines } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export type YoutubeInput = MediaTaskInput; +export type YoutubeValue = { title: string; description: string }; + +/** The summary's limit: room under YouTube's 5000 for the chapters and the sources. */ +export const YOUTUBE_SUMMARY_MAX = 900; + +type YoutubeUnit = MediaUnit & { g: GroundingInput; evidence: string }; + +const EVIDENCE_BUDGET = 12_000; +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); +const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, ""); + +const LINK = /https?:\/\/|www\.|\b\d{1,2}:\d{2}\b|#\w/; + +/** The title's problems. */ +export function titleProblems(title: string, g: GroundingInput): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (!title) hard.push("the title: empty"); + else if (title.length > PUBLISH_YOUTUBE_LIMITS.title) hard.push(`the title is ${title.length} characters (at most ${PUBLISH_YOUTUBE_LIMITS.title})`); + if (LINK.test(title)) hard.push("the title: no links, timestamps or hashtags"); + const r = title ? checkLine(title, g, { quotes: true }) : { hard: [], soft: [] }; + return { hard: [...hard, ...r.hard.map((h) => `the title: ${h}`)], soft: r.soft.map((s) => `the title: ${s}`) }; +} + +/** The summary's problems. */ +export function summaryProblems(text: string, g: GroundingInput): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (!text) hard.push("the summary: empty"); + else if (text.length > YOUTUBE_SUMMARY_MAX) hard.push(`the summary is ${text.length} characters (at most ${YOUTUBE_SUMMARY_MAX})`); + if (LINK.test(text)) hard.push("the summary: no links, timestamps, chapters or hashtags — the build adds the chapters and the sources"); + const r = text ? checkLine(text, g, { quotes: true }) : { hard: [], soft: [] }; + return { hard: [...hard, ...r.hard.map((h) => `the summary: ${h}`)], soft: r.soft.map((s) => `the summary: ${s}`) }; +} + +export function youtubeSystem(): string { + return ( + "You write the YouTube title and the summary paragraph of the description for a short evidence video made from a " + + `cited report. Rules: (1) the title is one line of at most ${PUBLISH_YOUTUBE_LIMITS.title} characters: plain and ` + + "specific, no clickbait, no all-caps, no emoji; (2) the summary is one paragraph of at most " + + `${YOUTUBE_SUMMARY_MAX} characters saying what the video shows and what the evidence found; (3) third person: you ` + + "describe what the speaker said, never as the speaker (no I, me, my, we, us or our outside quotation marks); (4) every " + + "name and number comes from the evidence, and nothing goes beyond it; (5) words in quotation marks only when a quote " + + "below says them word for word; (6) no links, timestamps, chapter list or hashtags: the chapters and the sources are " + + "added after it." + ); +} + +/** The evidence a title and summary may draw on, and its grounding (the cut's title and subtitle added). */ +function evidenceOf(ctx: MediaContext<YoutubeInput>): { text: string; g: GroundingInput } { + const r = ctx.report as { + title?: string; + summary?: string | null; + sections?: { title?: string; claims?: { text?: string; verdict?: string }[] | null }[]; + citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null; + }; + const m = ctx.manifest as VideoManifest; + const head = [`Report title: ${r.title ?? ""}`]; + if (m.title && m.title !== r.title) head.push(`Video title: ${m.title}`); + if (m.subtitle) head.push(`Video subtitle: ${m.subtitle}`); + if (r.summary) head.push(`Report summary: ${oneLine(r.summary).slice(0, 1200)}`); + const lines: string[] = []; + for (const s of r.sections ?? []) { + const claims = (s.claims ?? []).map((c) => ` - ${oneLine(stripCites(c.text ?? "")).slice(0, 220)}${c.verdict ? ` [${c.verdict}]` : ""}`); + if (!claims.length) continue; + lines.push(`Section: ${s.title ?? ""}`, ...claims); + } + const ev = fitLines(lines, EVIDENCE_BUDGET); + const quotes = [...new Set(Object.values(r.citations ?? {}).map((c) => oneLine(c?.quote)).filter(Boolean))]; + const q = fitLines(quotes.map((x) => `- "${x.slice(0, 200)}"`), 4000); + return { + text: + `${head.join("\n")}\n\nWhat it found:\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more line(s) not shown)` : "") + + (q.text ? `\n\nQuotes (the only words you may put in quotation marks):\n${q.text}` : ""), + g: { ...ctx.grounding, reference: [ctx.grounding.reference, m.title ?? "", m.subtitle ?? ""].join("\n") }, + }; +} + +export const YOUTUBE_SPEC: MediaTaskSpec<YoutubeUnit, YoutubeValue, YoutubeInput> = { + task: "youtube", + noun: "YouTube text", + units(ctx) { + const { text, g } = evidenceOf(ctx); + return [{ id: "youtube", target: { field: "publish.youtube" }, label: "YouTube title and summary", g, evidence: text }]; + }, + schema: () => ({ + type: "object", + properties: { title: { type: "string" }, description: { type: "string" } }, + required: ["title", "description"], + }), + system: () => youtubeSystem(), + user: (u) => `${u.evidence}\n\nWrite the title and the summary.`, + parse(answer) { + const a = answer as { title?: unknown; description?: unknown } | null; + return { + title: oneLine(a?.title).replace(/^["“]+|["”]+$/g, ""), + // One paragraph: line breaks are spaces. + description: oneLine(a?.description), + }; + }, + check(v, u) { + const t = titleProblems(v.title, u.g); + const d = summaryProblems(v.description, u.g); + return { hard: [...t.hard, ...d.hard], soft: [...t.soft, ...d.soft] }; + }, + // A clean title, with the summary's failing sentences removed (never + // rewritten) and cut to the limit at a sentence. + repair(attempts, u) { + let best: MediaAttempt<YoutubeValue> | null = null; + for (const a of attempts) { + if (!a.value || titleProblems(a.value.title, u.g).hard.length) continue; + const kept: string[] = []; + for (const s of sentencesOf(a.value.description)) { + if (summaryProblems(s, u.g).hard.length) continue; + if ([...kept, s].join(" ").length > YOUTUBE_SUMMARY_MAX) break; + kept.push(s); + } + const description = kept.join(" "); + if (!description) continue; + const v = { title: a.value.title, description }; + const again = summaryProblems(description, u.g); + if (again.hard.length) continue; + if (!best || description.length > best.value!.description.length) { + best = { value: v, hard: [], soft: [...titleProblems(v.title, u.g).soft, ...again.soft, "trimmed: failing or overlong sentences removed"] }; + } + } + return best; + }, + describe: (v) => `${v.title} — ${v.description.slice(0, 120)}${v.description.length > 120 ? "…" : ""}`, +}; + +export async function youtube(input: YoutubeInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(YOUTUBE_SPEC, input, deps); +} diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { applyVideoOps, cutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; +import { applyVideoOps, chaptersNamedBy, chaptersOf, cutView, trimmedCutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; const DRAFT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft"); const json = async (p: string) => JSON.parse(await readFile(path.join(DRAFT, p), "utf8")); @@ -131,3 +131,19 @@ test("the cut as a model reads it", () => { assert.match(v, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUBTITLE: \n- card title \(title\) heading: /); assert.match(v, /\n- clip c01 synth-kitchen\/bread-day-01 15–19\.8 s quote: "I would never sell the bakery to a chain"/); }); + +test("trimmed cut view (Q3): the named chapter in full, every entry still listed by id", () => { + const full = cutView(manifest); + const chapters = chaptersOf(manifest); + assert.ok(chapters.length >= 3); + const last = chapters.at(-1)!; + const card = last.find((e) => e.type === "card")!; + const v = trimmedCutView(manifest, { maxChars: 600, feedback: `Rename ${card.id}.` }); + assert.deepEqual([...chaptersNamedBy(manifest, `Rename ${card.id}.`)], [chapters.length - 1]); + for (const e of last) assert.ok(v.full.includes(e.id), `${e.id} in full`); + for (const e of manifest.timeline) assert.ok(v.text.includes(` ${e.id}`), `${e.id} listed`); + assert.ok(v.short.length > 0); + assert.match(v.text, /\(not shown in full\)/); + assert.ok(v.text.length < full.length); + assert.equal(trimmedCutView(manifest, { maxChars: 1e6 }).short.length, 0); +}); diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts @@ -210,3 +210,88 @@ export function cutView(m: VideoManifest): string { } return lines.join("\n"); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// The cut in timeline order under a character budget: the chapters the +// feedback names (a card's heading or an entry's id, or "chapter N") are shown +// in full first, then the rest in order while the budget lasts; an entry left +// out is listed by its id alone, so an op may still name it. Quotes are +// shortened IN THE VIEW ONLY. + +export const CUT_VIEW_QUOTE_WORDS = 12; + +const shortQ = (q: string, words: number) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +}; + +const lowWords = (s: string) => + ` ${s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s-]/gu, " ") + .replace(/\s+/g, " ") + .trim()} `; + +export function entryLine(e: ManifestEntry, quoteWords = CUT_VIEW_QUOTE_WORDS): string { + if (e.type === "card") { + const n = e.narration?.text ?? ""; + return `- card ${e.id} (${e.style ?? ""}) heading: ${JSON.stringify(e.heading ?? "")}` + (n ? ` narration: ${JSON.stringify(n)}` : ""); + } + if (e.type === "clip") return `- clip ${e.id} ${e.channel}/${e.video} ${e.start}–${e.end} s quote: ${JSON.stringify(shortQ(e.quote ?? "", quoteWords))}`; + return `- ${e.type} ${e.id}`; +} + +// The chapters of a cut: each card starts one; entries before the first card +// are chapter 0's. +export function chaptersOf(m: VideoManifest): ManifestEntry[][] { + const out: ManifestEntry[][] = [[]]; + for (const e of m.timeline ?? []) { + if (e.type === "card" && out.at(-1)!.length) out.push([]); + out.at(-1)!.push(e); + } + return out.filter((c) => c.length); +} + +export function chaptersNamedBy(m: VideoManifest, feedback: string): Set<number> { + const fb = lowWords(feedback); + const out = new Set<number>(); + chaptersOf(m).forEach((ch, i) => { + for (const e of ch) { + if (fb.includes(lowWords(e.id))) out.add(i); + const h = lowWords(e.heading ?? "").trim(); + if (e.type === "card" && h.length >= 3 && fb.includes(` ${h} `)) out.add(i); + } + if (new RegExp(`\\bchapter\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + return out; +} + +export function trimmedCutView( + m: VideoManifest, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): { text: string; full: string[]; short: string[] } { + const head = [`TITLE: ${m.title ?? ""}`, `SUBTITLE: ${m.subtitle ?? ""}`]; + const chapters = chaptersOf(m); + const named = o.feedback ? chaptersNamedBy(m, o.feedback) : new Set<number>(); + const order = [...chapters.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + // Every entry costs at least its id line; the full line is bought from what is left. + const idLine = (e: ManifestEntry) => `- ${e.type} ${e.id} (not shown in full)`; + let used = head.join("\n").length + (m.timeline ?? []).reduce((n, e) => n + idLine(e).length + 1, 0); + const full = new Set<ManifestEntry>(); + for (const i of order) { + for (const e of chapters[i]!) { + const extra = entryLine(e, o.quoteWords).length - idLine(e).length; + if (used + extra > o.maxChars) continue; + used += extra; + full.add(e); + } + } + const lines = [...head]; + for (const e of m.timeline ?? []) lines.push(full.has(e) ? entryLine(e, o.quoteWords) : idLine(e)); + return { + text: lines.join("\n"), + full: [...full].map((e) => e.id), + short: (m.timeline ?? []).filter((e) => !full.has(e)).map((e) => e.id), + }; +} diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts @@ -0,0 +1,49 @@ +// Types for ./drafted.mjs (release 28, M0): the drafted marks, the one draft +// writer, and the validators. See the module's header for the rules. + +export type DraftedEntryField = "onscreen" | "narration" | "lines"; +export type DraftedManifestField = "timeline" | "render.chrome.flips" | "render.chrome.threads" | "publish.youtube"; +export type DraftedField = DraftedEntryField | DraftedManifestField; + +/** Where a draft goes: an entry's field (`entry` an id), or the manifest's (`entry` absent or null). */ +export type DraftTarget = { entry?: string | null; field: DraftedField | string }; + +/** Who drafted a field: `at` ISO, `attempt` the one kept (1 or 2). */ +export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: 1 | 2 }; + +export type ApplyDraftResult = { applied: true } | { applied: false; reason: "operator" | "drafted" | "missing" }; + +export const DRAFTED_ENTRY_FIELDS: Readonly<Record<DraftedEntryField, readonly string[] | null>>; +export const DRAFTED_MANIFEST_FIELDS: readonly DraftedManifestField[]; +export const FIELD_TASKS: Readonly<Record<DraftedField, string>>; +export const PROVENANCE_KEYS: readonly string[]; +export const PUBLISH_YOUTUBE_LIMITS: Readonly<{ title: number; description: number }>; + +export function isEntryField(field: string): field is DraftedEntryField; +export function isManifestField(field: string): field is DraftedManifestField; +export function provenanceProblems(v: unknown, where: string): string[]; +export function makeProvenance(p: { task: string; model: string; at?: Date | string; iteration?: number; attempt?: number }): Provenance; +/** A mark a code path made (`model: "code"`): needs no review (release 28 M1). */ +export function isCodeDraft(p: unknown): boolean; +export function entriesWithId(manifest: unknown, id: string): Record<string, any>[]; +export function readField(manifest: unknown, target: DraftTarget): unknown; +export function isEmptyField(field: string, v: unknown): boolean; +export function draftedOf(manifest: unknown, target: DraftTarget): Provenance | null; +export function ownerOf(manifest: unknown, target: DraftTarget): "empty" | "drafted" | "operator"; +export function applyDraft( + manifest: unknown, + o: { entry?: string | null; field: DraftedField | string; value: unknown; provenance: Provenance; force?: boolean }, +): ApplyDraftResult; +export function clearDrafted(manifest: unknown, target: DraftTarget): boolean; +export function stableStringify(v: unknown): string; +export function fieldSignature(manifest: unknown, target: DraftTarget): unknown; +export function valueKey(v: unknown): string; +export function fieldKey(manifest: unknown, target: DraftTarget): string; +export function draftedFields(manifest: unknown): { entry: string | null; field: DraftedField; provenance: Provenance; value: unknown }[]; +export function reviewAddress(target: DraftTarget): string; +export function parseReviewAddress(address: unknown): { task: string; entry: string | null; field: string } | null; +export function orphanDrafts(manifest: unknown): { where: string; entry: string | null; field: string }[]; +export function pruneDrafted(manifest: unknown): string[]; +export function clearEditedDrafts(before: unknown, after: unknown): { entry: string | null; field: string }[]; +export function validateDrafted(manifest: unknown): string[]; +export function validatePublish(manifest: unknown): string[]; diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs @@ -0,0 +1,530 @@ +// DRAFTED FIELDS — THE one copy of where a generated manifest field says it was +// drafted, the one writer every draft task goes through, and the rules that +// keep an operator's words from being overwritten (release 28, M0). +// +// Plain JS (with JSDoc types, and ./drafted.d.mts for TypeScript) for the +// reason ./verdicts.mjs is: umtool's report-to-video scripts and its manifest +// writer are `.mjs` run by bare `node`, and the common tasks are TypeScript; +// both read and write the same marks. +// +// WHERE THE MARK LIVES. A provenance is `{ task, model, at, iteration?, attempt }` +// (`at` ISO; `attempt` 1 or 2, the one kept). An ENTRY's field carries it on the +// entry, keyed by field — `entry.drafted = { onscreen, narration, lines }` (any +// entry's on-screen text, a card's narration, a teaser's lines). A MANIFEST +// field carries it in a top-level map keyed by path — `manifest.drafted = +// { "timeline", "render.chrome.flips", "render.chrome.threads", +// "publish.youtube" }` ("timeline" is the cut's ORDER; "render.chrome.threads" +// covers each clip's `thread` key too). Nowhere else. +// +// WHO OWNS A FIELD. Empty: nobody (a draft may fill it). Non-empty with a mark: +// the task that drafted it (a forced re-draft may replace it). Non-empty with +// NO mark: the operator — written by hand, or edited since it was drafted — +// and never replaced, forced or not (`applyDraft`). An edit through umtool's +// manifest writer removes the mark (`clearEditedDrafts`), which is what makes +// an edited field the operator's. +// +// A mark whose field is gone (an orphan) is dropped with a warning +// (`pruneDrafted`); a mark that is malformed or in a place no field may be +// drafted is refused (`validateDrafted`). + +import { createHash } from "node:crypto"; + +/** The entry fields that may be drafted, and the entry types each is on (null: any). */ +export const DRAFTED_ENTRY_FIELDS = Object.freeze({ + onscreen: null, + narration: Object.freeze(["card"]), + lines: Object.freeze(["teaser"]), +}); + +/** The manifest fields that may be drafted, by path. */ +export const DRAFTED_MANIFEST_FIELDS = Object.freeze(["timeline", "render.chrome.flips", "render.chrome.threads", "publish.youtube"]); + +/** + * Each draftable field's own task: the one that drafts it, and the `<task>` of + * its review address (`reviewAddress`), whichever task drafted it this time — + * so a field's review has ONE address. + */ +export const FIELD_TASKS = Object.freeze({ + onscreen: "onscreen", + narration: "narrate", + lines: "teaser", + timeline: "cut", + "render.chrome.flips": "flips", + "render.chrome.threads": "threads", + "publish.youtube": "youtube", +}); + +/** The keys of a provenance, in the order they are written. */ +export const PROVENANCE_KEYS = Object.freeze(["task", "model", "at", "iteration", "attempt"]); + +/** `publish.youtube`'s limits: YouTube's own (a title of 100, a description of 5000). */ +export const PUBLISH_YOUTUBE_LIMITS = Object.freeze({ title: 100, description: 5000 }); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** @param {string} field */ +export const isEntryField = (field) => Object.prototype.hasOwnProperty.call(DRAFTED_ENTRY_FIELDS, field); +/** @param {string} field */ +export const isManifestField = (field) => DRAFTED_MANIFEST_FIELDS.includes(field); + +/** + * Every reason `v` is not a provenance, naming `where` (empty: it is one). + * + * @param {unknown} v + * @param {string} where + * @returns {string[]} + */ +export function provenanceProblems(v, where) { + if (!isObj(v)) return [`${where} must be { task, model, at, iteration?, attempt }`]; + const errors = []; + for (const k of Object.keys(v)) if (!PROVENANCE_KEYS.includes(k)) errors.push(`${where}.${k} is not a provenance key (${PROVENANCE_KEYS.join(", ")})`); + const word = (k, max) => { + if (typeof v[k] !== "string" || !v[k].trim()) errors.push(`${where}.${k} must be a name`); + else if (v[k].length > max || /[\r\n]/.test(v[k])) errors.push(`${where}.${k} must be one line of at most ${max} characters`); + }; + word("task", 64); + word("model", 200); + if (typeof v.at !== "string" || Number.isNaN(Date.parse(v.at))) errors.push(`${where}.at must be an ISO date and time`); + if (v.iteration !== undefined && !(Number.isInteger(v.iteration) && v.iteration > 0)) errors.push(`${where}.iteration must be a positive whole number`); + if (v.attempt !== 1 && v.attempt !== 2) errors.push(`${where}.attempt must be 1 or 2 (the attempt kept)`); + return errors; +} + +/** + * A provenance, its keys in order. `at` defaults to now. + * + * @param {{ task: string, model: string, at?: Date | string, iteration?: number, attempt?: number }} p + */ +export function makeProvenance({ task, model, at = new Date(), iteration, attempt = 1 }) { + return { + task, + model, + at: typeof at === "string" ? at : at.toISOString(), + ...(iteration !== undefined && iteration !== null ? { iteration } : {}), + attempt, + }; +} + +/** + * A mark a CODE path made (`model: "code"`): the converter's timeline + * (release 28 M1). It says who made the field so a task may redraft it, and + * it needs no review — the drafts review and the final gate leave it out. + * + * @param {unknown} p + */ +export const isCodeDraft = (p) => isObj(p) && p.model === "code"; + +/** Every timeline entry with this id (a cut's `variant` twins share one). */ +export function entriesWithId(manifest, id) { + return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.id === id); +} + +const pathParts = (field) => field.split("."); + +function readPath(obj, field) { + let cur = obj; + for (const p of pathParts(field)) { + if (!isObj(cur)) return undefined; + cur = cur[p]; + } + return cur; +} + +/** + * A field's value: an entry's (`target.entry` an id; the first entry with it) + * or the manifest's (`target.entry` absent). "timeline" is the timeline itself. + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + */ +export function readField(manifest, { entry = null, field }) { + if (entry !== null && entry !== undefined) return entriesWithId(manifest, entry)[0]?.[field]; + return readPath(manifest, field); +} + +/** + * Is this value of this field empty -- nothing a person wrote? A narration with + * no words, an on-screen block with no text, a list with nothing in it. + * + * @param {string} field + * @param {unknown} v + */ +export function isEmptyField(field, v) { + if (v === undefined || v === null || v === "") return true; + if (field === "narration") return !(isObj(v) && typeof v.text === "string" && v.text.trim()); + if (field === "onscreen") return !(isObj(v) && ["title", "subtitle"].some((k) => typeof v[k] === "string" && v[k].trim())); + if (field === "render.chrome.flips") return !(isObj(v) && Array.isArray(v.pairs) && v.pairs.length); + if (field === "render.chrome.threads") return !(isObj(v) && Array.isArray(v.list) && v.list.length); + if (field === "publish.youtube") return !(isObj(v) && ["title", "description"].some((k) => typeof v[k] === "string" && v[k].trim())); + if (Array.isArray(v)) return v.length === 0; + if (isObj(v)) return Object.keys(v).length === 0; + return false; +} + +/** + * A field's drafted mark, or null. + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + */ +export function draftedOf(manifest, { entry = null, field }) { + if (entry !== null && entry !== undefined) { + const e = entriesWithId(manifest, entry)[0]; + const p = isObj(e?.drafted) ? e.drafted[field] : undefined; + return isObj(p) ? p : null; + } + const p = isObj(manifest?.drafted) ? manifest.drafted[field] : undefined; + return isObj(p) ? p : null; +} + +/** + * Who a field belongs to now: "empty", "drafted" or "operator". + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + * @returns {"empty" | "drafted" | "operator"} + */ +export function ownerOf(manifest, target) { + if (isEmptyField(target.field, readField(manifest, target))) return "empty"; + return draftedOf(manifest, target) ? "drafted" : "operator"; +} + +function assertTarget({ entry = null, field }) { + const onEntry = entry !== null && entry !== undefined; + if (onEntry && !isEntryField(field)) throw new Error(`${field} is not a field an entry's draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`); + if (!onEntry && !isManifestField(field)) throw new Error(`${field} is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")})`); +} + +function setMark(manifest, { entry = null, field }, provenance) { + if (entry !== null && entry !== undefined) { + for (const e of entriesWithId(manifest, entry)) e.drafted = { ...(isObj(e.drafted) ? e.drafted : {}), [field]: { ...provenance } }; + } else { + manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), [field]: { ...provenance } }; + } +} + +/** + * THE writer every draft task uses. Sets the field to `value` and marks it + * drafted -- unless the field is the operator's (non-empty, no mark), which is + * never replaced, `force` or not; or is a draft already and `force` is not set. + * The caller keeps a refused value as an alternative (`<task>-draft.json`). + * Mutates `manifest`. + * + * applied: true + * applied: false, reason "operator" a field somebody wrote or edited + * applied: false, reason "drafted" a draft already, and no `force` + * applied: false, reason "missing" no entry with that id, or (flips, + * threads) no `render.chrome` to hold it + * + * An entry id names every entry with it (variant twins). "timeline" takes the + * new timeline array; "render.chrome.threads" takes `{ list }` (the task sets + * each clip's `thread` key itself once applied). + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string, value: unknown, provenance: Record<string, unknown>, force?: boolean }} o + * @returns {{ applied: true } | { applied: false, reason: "operator" | "drafted" | "missing" }} + */ +export function applyDraft(manifest, { entry = null, field, value, provenance, force = false }) { + const target = { entry, field }; + assertTarget(target); + const bad = provenanceProblems(provenance, "provenance"); + if (bad.length) throw new Error(bad.join("; ")); + const onEntry = entry !== null && entry !== undefined; + if (onEntry) { + const es = entriesWithId(manifest, entry); + if (!es.length) return { applied: false, reason: "missing" }; + const types = DRAFTED_ENTRY_FIELDS[field]; + if (types && !es.every((e) => types.includes(e.type))) throw new Error(`${entry} is a ${es[0].type}: ${field} is drafted only on a ${types.join(" or ")}`); + } else if (field.startsWith("render.chrome.") && !isObj(manifest?.render?.chrome)) { + return { applied: false, reason: "missing" }; + } + const owner = ownerOf(manifest, target); + if (owner === "operator") return { applied: false, reason: "operator" }; + if (owner === "drafted" && !force) return { applied: false, reason: "drafted" }; + const copy = () => (value === undefined ? undefined : JSON.parse(JSON.stringify(value))); + if (onEntry) { + for (const e of entriesWithId(manifest, entry)) e[field] = copy(); + } else if (field === "timeline") { + manifest.timeline = copy(); + } else { + const parts = pathParts(field); + let cur = manifest; + for (const p of parts.slice(0, -1)) { + if (!isObj(cur[p])) cur[p] = {}; + cur = cur[p]; + } + cur[parts.at(-1)] = copy(); + } + setMark(manifest, target, provenance); + return { applied: true }; +} + +/** + * Remove a field's drafted mark (the operator's edit). True when there was one. + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + */ +export function clearDrafted(manifest, { entry = null, field }) { + let had = false; + if (entry !== null && entry !== undefined) { + for (const e of entriesWithId(manifest, entry)) { + if (!isObj(e.drafted) || !(field in e.drafted)) continue; + had = true; + delete e.drafted[field]; + if (!Object.keys(e.drafted).length) delete e.drafted; + } + return had; + } + if (isObj(manifest?.drafted) && field in manifest.drafted) { + had = true; + delete manifest.drafted[field]; + if (!Object.keys(manifest.drafted).length) delete manifest.drafted; + } + return had; +} + +/** JSON with every object's keys sorted: one text per value, whatever order it was built in. */ +export function stableStringify(v) { + if (Array.isArray(v)) return `[${v.map((x) => (x === undefined ? "null" : stableStringify(x))).join(",")}]`; + if (isObj(v)) { + return `{${Object.keys(v) + .filter((k) => v[k] !== undefined) + .sort() + .map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`) + .join(",")}}`; + } + return JSON.stringify(v ?? null); +} + +/** + * What a field IS, for telling an edit from no edit and for a review's key: the + * value -- except "timeline", whose draft is the ORDER (the entries' ids), and + * "render.chrome.threads", which is the list and every clip's `thread` key. + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + */ +export function fieldSignature(manifest, target) { + if ((target.entry === null || target.entry === undefined) && target.field === "timeline") { + return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).map((e) => e?.id ?? null); + } + if ((target.entry === null || target.entry === undefined) && target.field === "render.chrome.threads") { + const clips = {}; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && e.thread !== undefined) clips[e.id] = e.thread; + return { threads: readField(manifest, target) ?? null, clips }; + } + return readField(manifest, target) ?? null; +} + +/** A value's content key: sha256 of its stable JSON, hex. */ +export function valueKey(v) { + return createHash("sha256").update(stableStringify(v)).digest("hex"); +} + +/** + * A field's content key (`fieldSignature` hashed). A review's verdict is on + * this key, so an edit or a re-draft leaves it unapproved. (A card's narration + * is keyed by umtool's `narrationKey` instead -- the words and the voice -- + * report-to-video/drafts-review.mjs.) + */ +export function fieldKey(manifest, target) { + return valueKey(fieldSignature(manifest, target)); +} + +/** + * Every drafted field of a manifest, in timeline order then the manifest's: + * `{ entry, field, provenance, value }`. An entry id is listed once (variant + * twins share a field). Orphans (a mark on an empty field) are left out. + * + * @param {any} manifest + * @returns {{ entry: string | null, field: string, provenance: Record<string, unknown>, value: unknown }[]} + */ +export function draftedFields(manifest) { + const out = []; + const seen = new Set(); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (!isObj(e) || !isObj(e.drafted)) continue; + for (const [field, p] of Object.entries(e.drafted)) { + const k = `${e.id}\u0000${field}`; + if (seen.has(k) || !isEntryField(field) || !isObj(p) || isEmptyField(field, e[field])) continue; + seen.add(k); + out.push({ entry: e.id, field, provenance: p, value: e[field] }); + } + } + if (isObj(manifest?.drafted)) { + for (const field of DRAFTED_MANIFEST_FIELDS) { + const p = manifest.drafted[field]; + const value = readField(manifest, { field }); + if (!isObj(p) || isEmptyField(field, value)) continue; + out.push({ entry: null, field, provenance: p, value }); + } + } + return out; +} + +/** The review address of a field: `<its task>/<entry id or *>/<field>`. */ +export function reviewAddress({ entry = null, field }) { + const task = FIELD_TASKS[field] ?? "draft"; + return `${task}/${entry === null || entry === undefined ? "*" : entry}/${field}`; +} + +/** An address back to its parts, or null. */ +export function parseReviewAddress(address) { + if (typeof address !== "string") return null; + const m = /^([A-Za-z0-9_-]{1,64})\/([^/]{1,200})\/([A-Za-z0-9_.-]{1,64})$/.exec(address); + if (!m) return null; + const [, task, entry, field] = m; + return { task, entry: entry === "*" ? null : entry, field }; +} + +/** + * The marks whose field is gone or empty (or whose key is not a field at + * all), as `{ where, entry, field }`. Read-only: `pruneDrafted` drops them. + * + * @param {any} manifest + */ +export function orphanDrafts(manifest) { + const out = []; + (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => { + if (!isObj(e) || !isObj(e.drafted)) return; + for (const field of Object.keys(e.drafted)) { + if (isEntryField(field) && isEmptyField(field, e[field])) out.push({ where: `timeline[${i}] (${e.id}).drafted.${field}`, entry: e.id, field }); + } + }); + if (isObj(manifest?.drafted)) { + for (const field of Object.keys(manifest.drafted)) { + if (isManifestField(field) && isEmptyField(field, readField(manifest, { field }))) out.push({ where: `drafted["${field}"]`, entry: null, field }); + } + } + return out; +} + +/** + * Drop every orphan mark (and a `drafted` map left empty). Mutates; returns a + * sentence per mark dropped. + * + * @param {any} manifest + * @returns {string[]} + */ +export function pruneDrafted(manifest) { + const dropped = orphanDrafts(manifest); + for (const o of dropped) { + if (o.entry === null) clearDrafted(manifest, { field: o.field }); + else { + for (const e of Array.isArray(manifest.timeline) ? manifest.timeline : []) { + if (!isObj(e) || e.id !== o.entry || !isObj(e.drafted) || !(o.field in e.drafted) || !isEmptyField(o.field, e[o.field])) continue; + delete e.drafted[o.field]; + if (!Object.keys(e.drafted).length) delete e.drafted; + } + } + } + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && isObj(e.drafted) && !Object.keys(e.drafted).length) delete e.drafted; + if (isObj(manifest?.drafted) && !Object.keys(manifest.drafted).length) delete manifest.drafted; + return dropped.map((o) => `${o.where}: its field is gone, so the drafted mark is dropped`); +} + +/** + * The operator's write: every drafted field whose value differs between + * `before` and `after` loses its mark in `after` (it is the operator's now), + * and orphans are dropped. Mutates `after`; returns the fields cleared as + * `{ entry, field }`. What umtool's manifest writer runs on every write. + * + * @param {any} before + * @param {any} after + */ +export function clearEditedDrafts(before, after) { + const cleared = []; + for (const d of draftedFields(after)) { + const t = { entry: d.entry, field: d.field }; + // A mark that was not there before is the writer's own (a draft applied in + // this write): leave it. + if (!draftedOf(before, t)) continue; + if (stableStringify(fieldSignature(before, t)) !== stableStringify(fieldSignature(after, t))) { + clearDrafted(after, t); + cleared.push(t); + } + } + pruneDrafted(after); + return cleared; +} + +/** + * Every reason the manifest's drafted marks cannot be built: a mark that is + * not a provenance, or one in a place no field may be drafted (an unknown + * field, `narration` on a clip, `lines` on a card, a `drafted` key under the + * render block or `publish`). An orphan is NOT an error (`orphanDrafts`). + * + * @param {any} manifest + * @returns {string[]} + */ +export function validateDrafted(manifest) { + const errors = []; + if (manifest?.drafted !== undefined) { + if (!isObj(manifest.drafted)) errors.push("drafted must be an object of field path → provenance"); + else { + for (const [k, p] of Object.entries(manifest.drafted)) { + if (!isManifestField(k)) { + errors.push(`drafted["${k}"] is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")}; an entry's own fields are marked on the entry)`); + continue; + } + errors.push(...provenanceProblems(p, `drafted["${k}"]`)); + } + } + } + (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => { + if (!isObj(e)) return; + for (const field of Object.keys(DRAFTED_ENTRY_FIELDS)) { + if (isObj(e[field]) && "drafted" in e[field]) errors.push(`timeline[${i}] (${e.id}).${field}.drafted: the mark goes on the entry (drafted.${field}), not inside the field`); + } + if (e.drafted === undefined) return; + const w = `timeline[${i}] (${e.id}).drafted`; + if (!isObj(e.drafted)) { + errors.push(`${w} must be an object of field → provenance`); + return; + } + for (const [field, p] of Object.entries(e.drafted)) { + if (!isEntryField(field)) { + errors.push(`${w}.${field} is not an entry field a draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`); + continue; + } + const types = DRAFTED_ENTRY_FIELDS[field]; + if (types && !types.includes(e.type)) errors.push(`${w}.${field}: a ${e.type ?? "entry"} has no ${field} to draft (only a ${types.join(" or ")})`); + errors.push(...provenanceProblems(p, `${w}.${field}`)); + } + }); + if (isObj(manifest?.render) && "drafted" in manifest.render) errors.push("render.drafted: a manifest field's mark goes in the top-level drafted map"); + if (isObj(manifest?.publish)) { + if ("drafted" in manifest.publish) errors.push("publish.drafted: a manifest field's mark goes in the top-level drafted map"); + if (isObj(manifest.publish.youtube) && "drafted" in manifest.publish.youtube) errors.push("publish.youtube.drafted: the mark goes in the top-level drafted map"); + } + return errors; +} + +/** + * `publish` (release 28): what is published beside the video. Only + * `publish.youtube { title, description }`, two strings, for now (M6 fills it). + * + * @param {any} manifest + * @returns {string[]} + */ +export function validatePublish(manifest) { + const p = manifest?.publish; + if (p === undefined) return []; + if (!isObj(p)) return ["publish must be an object ({ youtube })"]; + const errors = []; + for (const k of Object.keys(p)) if (k !== "youtube" && k !== "drafted") errors.push(`publish.${k} is not a publish key (youtube)`); + const y = p.youtube; + if (y === undefined) return errors; + if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"]; + for (const k of Object.keys(y)) if (k !== "title" && k !== "description" && k !== "drafted") errors.push(`publish.youtube.${k} is not a YouTube field (title, description)`); + for (const k of ["title", "description"]) { + if (typeof y[k] !== "string") { + errors.push(`publish.youtube.${k} must be a string`); + continue; + } + if (y[k].length > PUBLISH_YOUTUBE_LIMITS[k]) errors.push(`publish.youtube.${k} is ${y[k].length} characters (at most ${PUBLISH_YOUTUBE_LIMITS[k]})`); + } + if (typeof y.title === "string" && /[\r\n]/.test(y.title)) errors.push("publish.youtube.title must be one line"); + return errors; +} diff --git a/common/lib/report/drafted.test.ts b/common/lib/report/drafted.test.ts @@ -0,0 +1,183 @@ +// drafted.mjs (release 28, M0): the marks, the one draft writer, the +// operator's edit, orphans, and the validators — over the S0 kit's `full` +// manifest (every media field a draft task writes). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { + applyDraft, + clearEditedDrafts, + draftedFields, + draftedOf, + fieldKey, + makeProvenance, + orphanDrafts, + ownerOf, + parseReviewAddress, + pruneDrafted, + reviewAddress, + validateDrafted, + validatePublish, +} from "./drafted.mjs"; + +const full = () => JSON.parse(readFileSync(new URL("../../testing/draft/manifests/full.video.manifest.json", import.meta.url), "utf8")); +const P = (o: Partial<{ task: string; attempt: number }> = {}) => + makeProvenance({ task: o.task ?? "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: o.attempt ?? 1 }); +const entry = (m: { timeline: Record<string, any>[] }, id: string) => m.timeline.find((e) => e.id === id)!; + +test("applyDraft: an empty field is drafted and marked; the operator's is never replaced, force or not", () => { + const m = full(); + // c02 has no on-screen text: a draft fills it and says so. + assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() }), { applied: true }); + assert.deepEqual(entry(m, "c02").onscreen, { title: "The oven" }); + assert.deepEqual(entry(m, "c02").drafted, { onscreen: { task: "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: 1 } }); + assert.equal(ownerOf(m, { entry: "c02", field: "onscreen" }), "drafted"); + // c01's was written by hand: kept, with or without force. + const before = JSON.stringify(entry(m, "c01")); + assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P() }), { applied: false, reason: "operator" }); + assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P(), force: true }), { applied: false, reason: "operator" }); + assert.equal(JSON.stringify(entry(m, "c01")), before); + // A draft is re-drafted only with force. + assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }) }), { applied: false, reason: "drafted" }); + assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }), force: true }), { applied: true }); + assert.equal(entry(m, "c02").onscreen.title, "Again"); + assert.equal(entry(m, "c02").drafted.onscreen.attempt, 2); + // No such entry; flips with no deck to hold them. + assert.deepEqual(applyDraft(m, { entry: "nope", field: "onscreen", value: { title: "x" }, provenance: P() }), { applied: false, reason: "missing" }); + const bare = { timeline: [] as unknown[] }; + assert.deepEqual(applyDraft(bare, { field: "render.chrome.flips", value: { pairs: [{}] }, provenance: P({ task: "flips" }) }), { applied: false, reason: "missing" }); + // A field in the wrong place is the task's bug, thrown. + assert.throws(() => applyDraft(m, { entry: "c01", field: "narration", value: { text: "x" }, provenance: P() }), /narration is drafted only on a card/); + assert.throws(() => applyDraft(m, { field: "title", value: "x", provenance: P() }), /not a manifest field/); + assert.throws(() => applyDraft(m, { entry: "c03", field: "onscreen", value: { title: "x" }, provenance: { ...P(), attempt: 3 } as never }), /attempt must be 1 or 2/); +}); + +test("applyDraft: manifest fields — the teaser's lines on the entry, publish.youtube made, the cut's order; marks in the top-level map", () => { + const m = full(); + // The fixture's teaser lines are hand-written: the operator's. + assert.deepEqual(applyDraft(m, { entry: "fin", field: "lines", value: ["a"], provenance: P({ task: "teaser" }), force: true }), { applied: false, reason: "operator" }); + assert.deepEqual(applyDraft(m, { field: "publish.youtube", value: { title: "T", description: "D" }, provenance: P({ task: "youtube" }) }), { applied: true }); + assert.deepEqual(m.publish, { youtube: { title: "T", description: "D" } }); + assert.equal(m.drafted["publish.youtube"].task, "youtube"); + // The threads exist and are the operator's. + assert.deepEqual(applyDraft(m, { field: "render.chrome.threads", value: { list: [] }, provenance: P({ task: "threads" }), force: true }), { applied: false, reason: "operator" }); + // A cut's timeline with no mark is the operator's (M1 decides what the converter's order counts as). + assert.equal(ownerOf(m, { field: "timeline" }), "operator"); + assert.deepEqual(validateDrafted(m), []); + assert.deepEqual(validatePublish(m), []); + assert.deepEqual(draftedFields(m).map((d) => [d.entry, d.field]), [[null, "publish.youtube"]]); +}); + +test("an operator's edit clears the mark; an untouched field keeps it; each field by its own signature", () => { + const m = full(); + applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() }); + m.drafted = { + timeline: P({ task: "cut" }), + "render.chrome.threads": P({ task: "threads" }), + "publish.youtube": P({ task: "youtube" }), + }; + m.publish = { youtube: { title: "T", description: "D" } }; + entry(m, "the-contest").drafted = { narration: P({ task: "narrate" }) }; + entry(m, "fin").drafted = { lines: P({ task: "teaser" }) }; + const base = JSON.parse(JSON.stringify(m)); + + // Each field edited alone clears only its own mark. + const edits: [string, (x: any) => void, string | null, string][] = [ + ["onscreen", (x) => (entry(x, "c02").onscreen = { title: "Hand" }), "c02", "onscreen"], + ["narration", (x) => (entry(x, "the-contest").narration.text = "Mine now."), "the-contest", "narration"], + ["lines", (x) => (entry(x, "fin").lines = ["One", "Two", "Three"]), "fin", "lines"], + ["order", (x) => x.timeline.splice(3, 0, x.timeline.splice(2, 1)[0]), null, "timeline"], + ["a clip's thread", (x) => (entry(x, "c02").thread = "contest"), null, "render.chrome.threads"], + ["youtube", (x) => (x.publish.youtube.title = "Mine"), null, "publish.youtube"], + ]; + for (const [what, edit, id, field] of edits) { + const after = JSON.parse(JSON.stringify(base)); + edit(after); + const cleared = clearEditedDrafts(base, after); + assert.deepEqual(cleared, [{ entry: id, field }], what); + assert.equal(draftedOf(after, { entry: id, field }), null, what); + assert.equal(ownerOf(after, { entry: id, field }), "operator", what); + assert.equal(draftedFields(after).length, draftedFields(base).length - 1, `${what}: the others keep theirs`); + } + // An edit elsewhere in the entry (its on-screen text) leaves the cut's order and the narration drafted. + const same = JSON.parse(JSON.stringify(base)); + entry(same, "c01").onscreen.title = "Edited"; + assert.deepEqual(clearEditedDrafts(base, same), []); + // A mark the write itself made (a draft applied in it) is the writer's, kept. + const fresh = JSON.parse(JSON.stringify(base)); + applyDraft(fresh, { entry: "c03", field: "onscreen", value: { title: "New" }, provenance: P() }); + assert.deepEqual(clearEditedDrafts(base, fresh), []); + assert.equal(draftedOf(fresh, { entry: "c03", field: "onscreen" })?.task, "onscreen"); +}); + +test("orphans: a mark whose field is gone is listed, then dropped with a sentence; validation does not refuse it", () => { + const m = full(); + entry(m, "c03").drafted = { onscreen: P() }; + m.drafted = { "render.chrome.flips": P({ task: "flips" }) }; + assert.deepEqual(validateDrafted(m), []); + assert.deepEqual(orphanDrafts(m).map((o) => o.where), ["timeline[4] (c03).drafted.onscreen", 'drafted["render.chrome.flips"]']); + const said = pruneDrafted(m); + assert.equal(said.length, 2); + assert.match(said[0]!, /its field is gone, so the drafted mark is dropped/); + assert.equal(entry(m, "c03").drafted, undefined); + assert.equal(m.drafted, undefined); + assert.deepEqual(orphanDrafts(m), []); +}); + +test("validateDrafted: a mark where no field may be drafted, or not a provenance, is refused", () => { + const m = full(); + entry(m, "c01").drafted = { onscreen: P(), quote: P() }; + entry(m, "title").drafted = { lines: P() }; + entry(m, "c02").drafted = { narration: P() }; + entry(m, "c04").drafted = { onscreen: { task: "", model: "m", at: "yesterday", attempt: 1, extra: true } }; + entry(m, "c05").onscreen = { title: "x", drafted: P() } as never; + m.drafted = { title: P(), timeline: P({ task: "cut" }) }; + m.render.drafted = {}; + const errors = validateDrafted(m); + for (const re of [ + /\(c01\)\.drafted\.quote is not an entry field a draft may set/, + /\(title\)\.drafted\.lines: a card has no lines to draft \(only a teaser\)/, + /\(c02\)\.drafted\.narration: a clip has no narration to draft \(only a card\)/, + /\(c04\)\.drafted\.onscreen\.extra is not a provenance key/, + /\(c04\)\.drafted\.onscreen\.task must be a name/, + /\(c04\)\.drafted\.onscreen\.at must be an ISO date and time/, + /\(c05\)\.onscreen\.drafted: the mark goes on the entry/, + /drafted\["title"\] is not a manifest field a draft may set/, + /render\.drafted: a manifest field's mark goes in the top-level drafted map/, + ]) { + assert.ok(errors.some((e) => re.test(e)), `${re}\n${errors.join("\n")}`); + } + assert.equal(errors.length, 9, errors.join("\n")); +}); + +test("validatePublish: publish.youtube is two strings, YouTube's limits; nothing else under publish", () => { + assert.deepEqual(validatePublish({}), []); + assert.deepEqual(validatePublish({ publish: { youtube: { title: "T", description: "" } } }), []); + const bad = validatePublish({ publish: { youtube: { title: "a\nb", description: 3, tags: [] }, x: 1 } }); + assert.deepEqual(bad, [ + "publish.x is not a publish key (youtube)", + "publish.youtube.tags is not a YouTube field (title, description)", + "publish.youtube.description must be a string", + "publish.youtube.title must be one line", + ]); + assert.match(validatePublish({ publish: { youtube: { title: "t".repeat(101), description: "" } } })[0]!, /101 characters \(at most 100\)/); + assert.deepEqual(validatePublish({ publish: [] }), ["publish must be an object ({ youtube })"]); +}); + +test("review addresses and keys: one address per field, a key that moves with the value", () => { + assert.equal(reviewAddress({ entry: "k1", field: "narration" }), "narrate/k1/narration"); + assert.equal(reviewAddress({ field: "render.chrome.flips" }), "flips/*/render.chrome.flips"); + assert.equal(reviewAddress({ entry: "c01", field: "onscreen" }), "onscreen/c01/onscreen"); + assert.deepEqual(parseReviewAddress("teaser/fin/lines"), { task: "teaser", entry: "fin", field: "lines" }); + assert.deepEqual(parseReviewAddress("cut/*/timeline"), { task: "cut", entry: null, field: "timeline" }); + assert.equal(parseReviewAddress("no"), null); + const m = full(); + const k = fieldKey(m, { entry: "c01", field: "onscreen" }); + assert.equal(fieldKey(JSON.parse(JSON.stringify(m)), { entry: "c01", field: "onscreen" }), k, "same value, same key"); + // Key order in the object does not matter. + entry(m, "c01").onscreen = { subtitle: entry(m, "c01").onscreen.subtitle, title: entry(m, "c01").onscreen.title }; + assert.equal(fieldKey(m, { entry: "c01", field: "onscreen" }), k); + entry(m, "c01").onscreen.title = "Edited"; + assert.notEqual(fieldKey(m, { entry: "c01", field: "onscreen" }), k); +}); diff --git a/common/lib/report/panels.d.mts b/common/lib/report/panels.d.mts @@ -0,0 +1,20 @@ +// Types for ./panels.mjs (release 28, M4/M5): the flips' and the threads' +// limits and validators. See the module's header. + +export type FlipSide = { entry: string; when: string; words: string }; +export type FlipPair = { id: string; topic: string; then: FlipSide; now: FlipSide }; +export type Flips = { pairs: FlipPair[] }; +export type ThreadOutcome = { verdict: string; label?: string }; +export type Thread = { id: string; label: string; outcome?: ThreadOutcome }; +export type Threads = { list: Thread[] }; + +export const FLIPS_LIMITS: Readonly<{ pairs: readonly [number, number]; topic: number; when: number; words: number }>; +export const THREADS_LIMITS: Readonly<{ threads: readonly [number, number]; label: number; outcome: number }>; + +export function flipsOn(render: unknown): boolean; +export function validateFlips(f: unknown, where?: string): string[]; +export function validateFlipEntries(manifest: unknown): string[]; +export function threadsOn(render: unknown): boolean; +export function validateThreads(t: unknown, where?: string): string[]; +export function threadOf(entry: unknown): string | null; +export function validateThreadEntries(manifest: unknown): string[]; diff --git a/common/lib/report/panels.mjs b/common/lib/report/panels.mjs @@ -0,0 +1,180 @@ +// THE LEFT PANEL'S RULES — THE one copy of what a cut's flips +// (`render.chrome.flips`) and threads (`render.chrome.threads`, each clip's +// `thread`) may be: their limits and their validators (release 28, M4/M5: +// moved here from umtool/report-to-video/flips.mjs and threads.mjs, which +// re-export them unchanged, so the flips and threads draft tasks check +// exactly what the build refuses). +// +// Plain JS (with ./panels.d.mts for TypeScript) for the reason +// ./verdicts.mjs is: umtool's report-to-video scripts are `.mjs` run by bare +// `node`, and the draft tasks are TypeScript. PURE: no fs. +// +// The two share the frame's left side: a cut has one or the other +// (umtool's deck.mjs validateChrome refuses both). + +import { VERDICTS } from "./verdicts.mjs"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +// ─── flips ─── + +/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */ +export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 }); + +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; +const oneLineMax = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max; + +/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */ +export function flipsOn(render) { + const f = render?.chrome?.flips; + return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0; +} + +/** + * Every reason `render.chrome.flips` cannot be built, as sentences. Shape + * only; `validateFlipEntries` checks the pairs against the timeline. + * + * @returns {string[]} + */ +export function validateFlips(f, where = "render.chrome.flips") { + if (f === undefined) return []; + if (!isObj(f)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`); + const [lo, hi] = FLIPS_LIMITS.pairs; + if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`]; + const ids = new Set(); + f.pairs.forEach((p, i) => { + const w = `${where}.pairs[${i}]`; + if (!isObj(p)) { errors.push(`${w} must be an object`); return; } + for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`); + if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`); + else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`); + else ids.add(p.id); + if (!oneLineMax(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`); + for (const side of ["then", "now"]) { + const s = p[side]; + const ws = `${w}.${side}`; + if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; } + for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`); + if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`); + if (!oneLineMax(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`); + if (!oneLineMax(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`); + } + }); + return errors; +} + +/** + * The pairs against the timeline: each side names an entry of the cut, a clip + * (not a teaser), the THEN side before the NOW side, and no entry in two pairs. + * + * @returns {string[]} + */ +export function validateFlipEntries(manifest) { + const render = manifest?.render ?? {}; + if (!flipsOn(render)) return []; + const errors = []; + const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }])); + const used = new Map(); + render.chrome.flips.pairs.forEach((p, i) => { + const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`; + const idx = {}; + for (const side of ["then", "now"]) { + const id = p?.[side]?.entry; + const hit = at.get(id); + if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; } + if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`); + if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`); + used.set(id, p.id); + idx[side] = hit.i; + } + if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`); + }); + return errors; +} + +// ─── threads ─── + +/** The limits: how many threads, a label's and an outcome label's characters. */ +export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 }); + +/** A thread id: letters, digits and `_ -`. */ +const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; + +const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v); + +/** Is the rail on: a `render.chrome.threads` with at least one thread. */ +export function threadsOn(render) { + const t = render?.chrome?.threads; + return isObj(t) && Array.isArray(t.list) && t.list.length > 0; +} + +/** + * Every reason `render.chrome.threads` cannot be built, as sentences (empty: + * it can). validateChrome calls this, so umtool's writer and the build refuse + * the same things. + * + * @returns {string[]} + */ +export function validateThreads(t, where = "render.chrome.threads") { + if (t === undefined) return []; + if (!isObj(t)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`); + const [lo, hi] = THREADS_LIMITS.threads; + if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) { + return [...errors, `${where}.list must be ${lo} to ${hi} threads`]; + } + const seen = new Set(); + t.list.forEach((th, i) => { + const w = `${where}.list[${i}]`; + if (!isObj(th)) { errors.push(`${w} must be an object`); return; } + for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`); + if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`); + else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`); + else seen.add(th.id); + if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) { + errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`); + } + if (th.outcome !== undefined) { + const o = th.outcome; + if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; } + for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`); + if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`); + if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) { + errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`); + } + } + }); + return errors; +} + +/** The thread an entry belongs to, or null. */ +export function threadOf(entry) { + return typeof entry?.thread === "string" && entry.thread ? entry.thread : null; +} + +/** + * Every `thread` in the timeline, checked against the list: it names a listed + * thread, it is not on a teaser, and every listed thread has a clip. The + * build refuses with these before it fetches. + * + * @returns {string[]} + */ +export function validateThreadEntries(manifest) { + const errors = []; + const render = manifest?.render ?? {}; + const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set(); + const used = new Set(); + (manifest?.timeline ?? []).forEach((e, i) => { + if (e?.thread === undefined || e?.thread === null) return; + const where = `timeline[${i}] (${e.id ?? "?"}).thread`; + if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; } + if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; } + if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; } + used.add(e.thread); + }); + for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`); + return errors; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -28,8 +28,11 @@ import { GENERATION_MODELS_FIELD_DOCS, GENERATION_RESEARCH_FIELD_DOCS, GENERATION_ROUTES_FIELD_DOCS, + GENERATION_CUT_FIELD_DOCS, GENERATION_SETTINGS_FIELD_DOCS, GENERATION_WEB_FIELD_DOCS, + GENERATION_VERDICTS_FIELD_DOCS, + GENERATION_VERDICT_BAR_FIELD_DOCS, SOCIAL_LINK_FIELD_DOCS, SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, @@ -287,6 +290,9 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, { path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) }, { path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) }, { path: "generation.research", docs: GENERATION_RESEARCH_FIELD_DOCS, defaults: fromObject(d.generation.research) }, + { path: "generation.cut", docs: GENERATION_CUT_FIELD_DOCS, defaults: fromObject(d.generation.cut) }, + { path: "generation.verdicts", docs: GENERATION_VERDICTS_FIELD_DOCS, defaults: fromObject(d.generation.verdicts) }, + { path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) }, ], }; } diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -82,11 +82,14 @@ import { sanitizeTts, type TtsSettings } from "./ttsSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { GENERATION_CAPS_FIELD_DOCS, + GENERATION_CUT_FIELD_DOCS, GENERATION_MODELS_FIELD_DOCS, GENERATION_RESEARCH_FIELD_DOCS, GENERATION_ROUTES_FIELD_DOCS, GENERATION_SETTINGS_FIELD_DOCS, GENERATION_WEB_FIELD_DOCS, + GENERATION_VERDICTS_FIELD_DOCS, + GENERATION_VERDICT_BAR_FIELD_DOCS, type GenerationSettings, } from "./generationSettings"; export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; diff --git a/common/package.json b/common/package.json @@ -35,6 +35,8 @@ "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/ports.mjs": "./lib/ports.mjs", + "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", + "./lib/report/panels.mjs": "./lib/report/panels.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", "./lib/toolProbe.mjs": "./lib/toolProbe.mjs", "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", diff --git a/common/publish/siteDelete.test.ts b/common/publish/siteDelete.test.ts @@ -0,0 +1,152 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { acquirePublishLock } from "./stageLock"; +import { deleteSiteByPlan, formatSiteDeletePlan, planSiteDelete, siteDeleteBlocked, SiteDeleteRefusedError } from "./siteDelete"; + +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/siteDelete.test.ts +// +// Release 28 H5: a site's delete over a temp transcripts/ and export/ — never +// the real ones. + +async function tree() { + const dir = await mkdtemp(path.join(os.tmpdir(), "site-delete-")); + const paths = { + sitesDir: path.join(dir, "transcripts", "sites"), + channelsDir: path.join(dir, "transcripts", "channels"), + exportDir: path.join(dir, "export"), + exportBuildsDir: path.join(dir, "export", ".export-builds"), + exportSitesIndexDir: path.join(dir, "export", ".export-index", "sites"), + }; + const site = async (id: string, json: Record<string, unknown> = {}, o: { reports?: string[]; builds?: boolean; deployed?: unknown } = {}) => { + const d = path.join(paths.sitesDir, id); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, channels: ["demo-channel"], audience: "private", ...json })); + await writeFile(path.join(d, "tags.json"), "{}"); + for (const r of o.reports ?? []) { + await mkdir(path.join(d, "reports", r), { recursive: true }); + await writeFile(path.join(d, "reports", r, "report.json"), "{}"); + } + if (o.builds !== false) { + const b = path.join(paths.exportBuildsDir, id); + await mkdir(path.join(b, "out"), { recursive: true }); + await writeFile(path.join(b, "built.json"), "{}"); + await writeFile(path.join(b, "out", "index.html"), "<html></html>"); + if (o.deployed) await writeFile(path.join(b, "deployed.json"), JSON.stringify(o.deployed)); + await mkdir(path.join(paths.exportSitesIndexDir, id, "report-media"), { recursive: true }); + await writeFile(path.join(paths.exportSitesIndexDir, id, "summary.json"), "{}"); + } + }; + // A channel the site's pool names: never touched. + await mkdir(path.join(paths.channelsDir, "demo-channel", "data", "v1"), { recursive: true }); + await writeFile(path.join(paths.channelsDir, "demo-channel", "config.json"), "{}"); + await writeFile(path.join(paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "{}"); + return { dir, paths, site, done: () => rm(dir, { recursive: true, force: true }) }; +} + +test("a private site with nothing deployed: the plan, then its three directories go, and nothing else", async () => { + const t = await tree(); + try { + await t.site("doomed"); + await t.site("keeper"); + const plan = await planSiteDelete("doomed", t.paths); + assert.equal(plan.exists, true); + assert.deepEqual(plan.refusals, []); + assert.deepEqual(plan.remove.map((e) => e.label), ["sites/doomed/", "export/.export-builds/doomed/", "export/.export-index/sites/doomed/"]); + assert.equal(plan.files, 5); + assert.ok(plan.kept.some((k) => k.what === "every channel's data")); + assert.match(formatSiteDeletePlan(plan)[0]!, /^delete site "doomed": 3 path\(s\)/); + const r = await deleteSiteByPlan("doomed", t.paths); + assert.equal(r.removed.length, 3); + assert.deepEqual(r.failed, []); + for (const e of plan.remove) assert.equal(existsSync(e.path), false, e.label); + // No park left behind; the other site and the channel untouched. + assert.deepEqual(await readdir(t.paths.sitesDir), ["keeper"]); + assert.deepEqual((await readdir(t.paths.exportBuildsDir)).filter((n) => !n.startsWith(".publish")), ["keeper"]); + assert.ok(existsSync(path.join(t.paths.exportSitesIndexDir, "keeper", "summary.json"))); + assert.equal(await readFile(path.join(t.paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "utf8"), "{}"); + // Gone means gone: a second delete has no site to delete. + await assert.rejects(deleteSiteByPlan("doomed", t.paths), (e: unknown) => e instanceof SiteDeleteRefusedError && /no site "doomed"/.test(e.message)); + } finally { + await t.done(); + } +}); + +test("a deploy target, a recorded deploy or reports of its own refuse unless force; force deletes and keeps the remote", async () => { + const t = await tree(); + try { + await t.site("public-one", { audience: "public", cloudflareProject: "demo-pages", siteUrl: "https://demo.example" }, { + reports: ["a-report"], + deployed: { v: 1, target: "public-one", previews: {}, production: { builtStampId: "x", builtAt: 1, kind: "production", url: "https://demo.example", at: 2, liveCheck: null } }, + }); + const plan = await planSiteDelete("public-one", t.paths); + assert.deepEqual( + plan.refusals.map((r) => [r.reason, r.forceable]), + [ + ['it deploys to the Cloudflare Pages project "demo-pages"', true], + ["it holds 1 report (a-report), which go with it", true], + ["the publish state records a deploy: production (https://demo.example)", true], + ], + ); + assert.equal(siteDeleteBlocked(plan), true); + assert.equal(siteDeleteBlocked(plan, true), false); + await assert.rejects(deleteSiteByPlan("public-one", t.paths), SiteDeleteRefusedError); + assert.ok(existsSync(path.join(t.paths.sitesDir, "public-one", "site.json")), "a refusal writes nothing"); + assert.ok(plan.kept.some((k) => k.what === 'the Pages project "demo-pages"')); + const r = await deleteSiteByPlan("public-one", t.paths, { force: true }); + assert.equal(r.removed.length, 3); + assert.equal(existsSync(path.join(t.paths.sitesDir, "public-one")), false); + } finally { + await t.done(); + } +}); + +test("never forceable: no such site, a site dir that is a link, a publish stage running", async () => { + const t = await tree(); + try { + const none = await planSiteDelete("ghost", t.paths); + assert.equal(none.exists, false); + assert.deepEqual(none.refusals, [{ reason: 'no site "ghost" (sites/ghost/site.json)', forceable: false }]); + // A link: refused, never followed. + await t.site("real", {}, { builds: false }); + await symlink(path.join(t.paths.sitesDir, "real"), path.join(t.paths.sitesDir, "alias")); + const link = await planSiteDelete("alias", t.paths); + assert.equal(siteDeleteBlocked(link, true), true); + assert.match(link.refusals[0]!.reason, /sites\/alias is a link/); + // A publish stage holds the lock (this process, alive): refused, force or not. + await t.site("busy"); + const lock = await acquirePublishLock(t.paths, { kind: "build-site", target: "other" }); + try { + const busy = await planSiteDelete("busy", t.paths); + assert.deepEqual(busy.refusals.map((r) => r.forceable), [false]); + assert.match(busy.refusals[0]!.reason, /a publish stage is running: build-site other/); + await assert.rejects(deleteSiteByPlan("busy", t.paths, { force: true }), SiteDeleteRefusedError); + } finally { + await lock.release(); + } + assert.ok(existsSync(path.join(t.paths.sitesDir, "busy", "site.json"))); + assert.equal((await deleteSiteByPlan("busy", t.paths)).removed.length, 3); + assert.ok((await lstat(path.join(t.paths.sitesDir, "real"))).isDirectory(), "the link's target is kept"); + } finally { + await t.done(); + } +}); + +test("export/out linking into the site's bundle is named and kept", async () => { + const t = await tree(); + try { + await t.site("linked"); + await mkdir(t.paths.exportDir, { recursive: true }); + const out = path.join(t.paths.exportDir, "out"); + await symlink(path.join(t.paths.exportBuildsDir, "linked", "out"), out); + const plan = await planSiteDelete("linked", t.paths); + assert.ok(plan.kept.some((k) => k.what === "export/out" && /next build makes it again/.test(k.why))); + await deleteSiteByPlan("linked", t.paths); + assert.equal(await readlink(out), path.join(t.paths.exportBuildsDir, "linked", "out")); + } finally { + await t.done(); + } +}); diff --git a/common/publish/siteDelete.ts b/common/publish/siteDelete.ts @@ -0,0 +1,250 @@ +// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops +// delete-site`, and since M9 the editor's Danger → Delete on /sites: +// `planSiteDeleteAction`, then `deleteSiteAction`). It says first what goes, +// what stays and what refuses. +// +// WHAT A SITE IS ON DISK (the survey, 2026-10-13): +// sites/<id>/ site.json (the pool: `channels`, +// `citedChannels`), tags.json, charts, +// its reports/ (each with history-git/) +// export/.export-builds/<id>/ built.json, deployed.json (the publish +// state), out/ (the last bundle), +// public/ and .r2-staging/ (docker builds) +// export/.export-index/sites/<id>/ compose's staging: report-media/, +// report-exports/, summaries, stats +// Nothing else names a site by id on disk: channel membership is site.json's +// own pool (a channel's config holds no site list), the hub lists the sites +// that are on disk with a siteUrl (its next build drops this one), and curated +// tags' site scoping is read against the sites that exist. +// +// REMOVED: the three directories. KEPT, always: every channel's data (never +// touched), the Cloudflare Pages project and anything already deployed to it +// or to R2 (remote: a deploy, not a delete, takes a site off the edge), a +// deployed hub until it is rebuilt, `export/out` when it links into this +// site's bundle (the next build makes it again). +// +// REFUSED — forceable: a deploy target (`cloudflareProject`), a deploy the +// publish state records (production, preview or local), a site that holds +// reports (they go with it). Never forceable: no such site; its directory is a +// link; a publish stage running (the publish lock held by a live holder). +// +// THE DELETE: under the site.json lock and the publish lock (taken without +// waiting: a stage running refuses), the plan is made again, then each +// directory is renamed aside to `.deleting-<id>-<stamp>` (not a site id, so no +// reader lists it); the bulk is removed after the locks are let go. + +import type { Dirent } from "node:fs"; +import { lstat, readdir, readlink, rename, rm } from "node:fs/promises"; +import path from "node:path"; +import { withJsonFileLock } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { getSite, siteConfigFile, siteDir } from "../lib/site"; +import { isValidSiteId } from "../lib/siteSchema"; +import { exportOutPath } from "./build"; +import { holderIsGone, LockWaitCancelled, acquirePublishLock, describeHolder, readLockHolder, type LockHolder } from "./stageLock"; +import { readDeployedFile, targetDir } from "./stamps"; + +export type SiteDeletePaths = Pick<Paths, "sitesDir" | "exportBuildsDir" | "exportSitesIndexDir" | "exportDir">; + +export type SiteDeleteEntry = { path: string; label: string; what: string; kind: "dir" | "link" | "file"; bytes: number; files: number }; +export type SiteDeleteKept = { what: string; why: string }; +export type SiteDeleteRefusal = { reason: string; forceable: boolean }; + +export type SiteDeletePlan = { + siteId: string; + exists: boolean; + refusals: SiteDeleteRefusal[]; + remove: SiteDeleteEntry[]; + kept: SiteDeleteKept[]; + bytes: number; + files: number; +}; + +export type SiteDeleteResult = { plan: SiteDeletePlan; removed: string[]; failed: { path: string; error: string }[] }; + +export class SiteDeleteRefusedError extends Error { + constructor( + message: string, + readonly plan: SiteDeletePlan, + ) { + super(message); + this.name = "SiteDeleteRefusedError"; + } +} + +export function siteDeleteBlocked(plan: Pick<SiteDeletePlan, "refusals">, force = false): boolean { + return plan.refusals.some((r) => !force || !r.forceable); +} + +async function measure(p: string): Promise<{ bytes: number; files: number }> { + let bytes = 0; + let files = 0; + const walk = async (dir: string) => { + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of entries) { + const child = path.join(dir, e.name); + if (e.isDirectory()) await walk(child); + else { + const s = await lstat(child).catch(() => null); + if (s) { + bytes += s.isSymbolicLink() ? 0 : s.size; + files += 1; + } + } + } + }; + await walk(p); + return { bytes, files }; +} + +async function lstatOrNull(p: string) { + return lstat(p).catch(() => null); +} + +export async function planSiteDelete( + siteId: string, + paths: SiteDeletePaths, + o: { measure?: boolean; ownLock?: LockHolder } = {}, +): Promise<SiteDeletePlan> { + if (!isValidSiteId(siteId)) throw new Error(`Invalid site id: ${String(siteId)}`); + const sizes = o.measure !== false; + const refusals: SiteDeleteRefusal[] = []; + const remove: SiteDeleteEntry[] = []; + const kept: SiteDeleteKept[] = [{ what: "every channel's data", why: "a site's delete never touches a channel" }]; + const dir = siteDir(paths as Paths, siteId); + const st = await lstatOrNull(dir); + const exists = !!st && (st.isSymbolicLink() || (st.isDirectory() && !!(await lstatOrNull(siteConfigFile(paths as Paths, siteId))))); + if (!exists) refusals.push({ reason: `no site "${siteId}" (sites/${siteId}/site.json)`, forceable: false }); + else if (st!.isSymbolicLink()) refusals.push({ reason: `sites/${siteId} is a link (to ${await readlink(dir).catch(() => "?")}): refused, never followed`, forceable: false }); + + const add = async (p: string, label: string, what: string) => { + const s = await lstatOrNull(p); + if (!s) return; + if (s.isSymbolicLink()) { + remove.push({ path: p, label, what, kind: "link", bytes: 0, files: 0 }); + return; + } + const m = sizes && s.isDirectory() ? await measure(p) : { bytes: s.isDirectory() ? 0 : s.size, files: s.isDirectory() ? 0 : 1 }; + remove.push({ path: p, label, what, kind: s.isDirectory() ? "dir" : "file", ...m }); + }; + + if (exists && !st!.isSymbolicLink()) { + const site = getSite(siteId, paths as Paths); + await add(dir, `sites/${siteId}/`, "the site: site.json, its pool and pages, tags, charts, reports"); + if (site.cloudflareProject?.trim()) { + refusals.push({ reason: `it deploys to the Cloudflare Pages project "${site.cloudflareProject.trim()}"`, forceable: true }); + kept.push({ what: `the Pages project "${site.cloudflareProject.trim()}"`, why: "remote: what it serves stays until the project is changed there" }); + } + const reports = (await readdir(path.join(dir, "reports"), { withFileTypes: true }).catch(() => [] as Dirent[])).filter((e) => e.isDirectory()).map((e) => e.name); + if (reports.length) { + refusals.push({ reason: `it holds ${reports.length} report${reports.length === 1 ? "" : "s"} (${reports.slice(0, 5).join(", ")}${reports.length > 5 ? ", …" : ""}), which go with it`, forceable: true }); + } + } + // The publish state and the last bundle. + const builds = targetDir(paths, siteId); + const deployed = await readDeployedFile(paths, siteId).catch(() => null); + if (deployed) { + const kinds = [ + ...(deployed.production ? [`production (${deployed.production.url ?? "no url"})`] : []), + ...Object.keys(deployed.previews ?? {}).map((b) => `preview ${b}`), + ...(deployed.local ? ["local"] : []), + ]; + if (kinds.length) { + refusals.push({ reason: `the publish state records a deploy: ${kinds.join(", ")}`, forceable: true }); + kept.push({ what: "what was deployed", why: "remote (or the local site volume): a delete does not undeploy" }); + } + } + await add(builds, `export/.export-builds/${siteId}/`, "its publish state (built.json, deployed.json) and last bundle"); + await add(path.join(paths.exportSitesIndexDir, siteId), `export/.export-index/sites/${siteId}/`, "compose's staging for it (report media and exports, summaries, stats)"); + // export/out linking into this site's bundle: named, kept. + const out = exportOutPath(paths); + const outLink = await readlink(out).catch(() => null); + if (outLink) { + const target = path.resolve(path.dirname(out), outLink); + if (target === builds || target.startsWith(builds + path.sep)) { + kept.push({ what: "export/out", why: `it links to this site's bundle (${target}); the next build makes it again` }); + } + } + kept.push({ what: "a deployed hub", why: "it lists the site until it is rebuilt (the next hub build drops it)" }); + // A publish stage running: never forceable. + const holder = await readLockHolder(paths); + const mine = o.ownLock && holder && holder.pid === o.ownLock.pid && holder.since === o.ownLock.since && holder.host === o.ownLock.host; + if (holder && !mine && !holderIsGone(holder)) refusals.push({ reason: `a publish stage is running: ${describeHolder(holder)}`, forceable: false }); + + return { + siteId, + exists, + refusals, + remove, + kept, + bytes: remove.reduce((s, e) => s + e.bytes, 0), + files: remove.reduce((s, e) => s + e.files, 0), + }; +} + +export async function deleteSiteByPlan(siteId: string, paths: SiteDeletePaths, o: { force?: boolean; now?: Date } = {}): Promise<SiteDeleteResult> { + const first = await planSiteDelete(siteId, paths); + if (siteDeleteBlocked(first, o.force)) { + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${first.refusals.map((r) => r.reason).join("; ")}`, first); + } + const stamp = (o.now ?? new Date()).toISOString().replace(/[-:.]/g, ""); + const parked: string[] = []; + // The publish lock, without waiting: a stage that started since the plan refuses. + let lock: Awaited<ReturnType<typeof acquirePublishLock>>; + try { + lock = await acquirePublishLock(paths, { kind: "delete-site", target: siteId }, { signal: AbortSignal.timeout(1500), pollMs: 250 }); + } catch (e) { + if (e instanceof LockWaitCancelled) { + const again = await planSiteDelete(siteId, paths, { measure: false }); + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: a publish stage is running`, again); + } + throw e; + } + try { + await withJsonFileLock(siteConfigFile(paths as Paths, siteId), async () => { + const plan = await planSiteDelete(siteId, paths, { measure: false, ownLock: lock.holder }); + if (siteDeleteBlocked(plan, o.force)) { + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${plan.refusals.map((r) => r.reason).join("; ")}`, plan); + } + for (const e of plan.remove) { + if (e.kind === "link") { + await rm(e.path, { force: true }); + parked.push(e.path); + continue; + } + const aside = path.join(path.dirname(e.path), `.deleting-${siteId}-${stamp}`); + await rename(e.path, aside); + parked.push(aside); + } + }); + } finally { + await lock.release(); + } + const removed: string[] = []; + const failed: { path: string; error: string }[] = []; + for (const p of parked) { + try { + await rm(p, { recursive: true, force: true }); + removed.push(p); + } catch (e) { + failed.push({ path: p, error: (e as Error).message }); + } + } + return { plan: first, removed, failed }; +} + +const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`); + +export function formatSiteDeletePlan(plan: SiteDeletePlan, o: { force?: boolean } = {}): string[] { + const blocked = siteDeleteBlocked(plan, o.force); + const out = [`delete site "${plan.siteId}": ${plan.remove.length} path(s), ${fmt(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`]; + for (const r of plan.refusals) out.push(` refused${r.forceable ? (o.force ? " (force answers it)" : " (unless force)") : ""}: ${r.reason}`); + for (const e of plan.remove) out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${fmt(e.bytes)} in ${e.files} file(s)`}`); + for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`); + return out; +} diff --git a/common/testing/README.md b/common/testing/README.md @@ -14,11 +14,13 @@ transcript, channel or person goes in these fixtures, ever. | `llm/fakeAnthropic.mjs` | A fake Messages API: scripted turns (`textTurn`, `toolTurn`, `pauseTurn`, `webSearchBlocks`, `thinkingBlock`, `errorTurn`, or a function of the request). It enforces the Sonnet 5.5 400s (temperature, forced `tool_choice`, `thinking: disabled`), signs thinking blocks so an edited history is refused, needs `x-api-key` = `FAKE_KEY`, and estimates usage, cache reads included. | | `llm/fakeOllama.mjs` | A fake ollama: `/api/chat` with `format` or tools, the 8k prompt cap and the 12k `num_ctx` cap as 400s, `stream: true` refused, `faultReply()` (`done: false`), the `keep_alive: 0` unload, `/api/tags`, `/api/ps`. | | `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. | -| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one). | +| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one), `two-line` (a finding's quote and link on the lines under its claim), `fragment` (verbatim quotes that stop mid-thought — on a function word, or under four words — and one whole sentence). | | `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. | | `web/fakeWeb.mjs` | A fake web on loopback: a DuckDuckGo-shaped HTML search (`POST /html/`, links in the `uddg` redirect, an ad), pages, plain text, a long page, redirects and a redirect loop, a PDF, a 429 that clears (`busyTimes`), a 503 that does not. `web.searchUrl` is what `webSearch` takes. | | `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. | -| `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`), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | +| `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. | +| `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`, 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. | As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and diff --git a/common/testing/draft/derive.ts b/common/testing/draft/derive.ts @@ -10,7 +10,7 @@ import { cuesOf, ORIGIN, POSTS } from "./corpus.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); -export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact", "two-line"] as const; +export const SWEEPS = ["basic", "quotes-in-claims", "multi-quote", "posts-only", "paragraphs", "inexact", "two-line", "fragment"] as const; export type SweepName = (typeof SWEEPS)[number]; // The sweeps whose report and manifest are committed. diff --git a/common/testing/draft/manifests/basic.video.manifest.json b/common/testing/draft/manifests/basic.video.manifest.json @@ -126,5 +126,13 @@ "cite": 40, "quote": "my lawyer told me not to talk about the lease" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/manifests/flips.video.manifest.json b/common/testing/draft/manifests/flips.video.manifest.json @@ -0,0 +1,214 @@ +{ + "schemaVersion": 1, + "slug": "synth-flips", + "title": "Synth Kitchen — what the baker says about the bakery", + "subtitle": "", + "generatedOn": "2026-10-13", + "provenance": { + "siteOrigin": "https://synth.example", + "channelSlug": "synth-kitchen", + "channel": "" + }, + "render": { + "width": 1920, + "height": 1080, + "fps": 30, + "audioRate": 48000, + "audioChannels": 2, + "maxHeightSource": 1080, + "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf", + "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf", + "palette": { + "bg": "#12100c", + "fg": "#f6f1e6", + "muted": "#a2957f", + "accent": "#c8752a", + "amber": "#ffc860" + }, + "transition": 0.4, + "fetchPad": 3, + "snapWindow": 1.6, + "silenceMinDur": 0.09, + "silenceRelDb": 6, + "headerHeight": 56, + "footerHeight": 0, + "crf": 21, + "preset": "slow", + "qr": { + "scale": 4, + "quiet": 3, + "ecc": "M", + "margin": 28 + }, + "chrome": { + "engine": "hyperframes", + "layout": "deck", + "factcheck": {}, + "flips": { + "pairs": [ + { + "id": "chain", + "topic": "The bakery's size", + "then": { + "entry": "c01", + "when": "Jan 2026", + "words": "I would never sell the bakery to a chain" + }, + "now": { + "entry": "c07", + "when": "Mar 2026", + "words": "it was always going to be a small place" + } + } + ] + } + }, + "narration": { + "engine": "kokoro", + "voice": "af_heart" + } + }, + "timelineNodes": [], + "timeline": [ + { + "type": "card", + "id": "title", + "style": "title", + "seconds": 4, + "heading": "Synth Kitchen — what the baker says about the bakery", + "sub": "", + "foot": "" + }, + { + "type": "card", + "id": "the-bakery", + "style": "chapter", + "seconds": 3.5, + "heading": "The bakery" + }, + { + "type": "clip", + "id": "c01", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "I would never sell the bakery to a chain", + "claim": { + "id": "k01", + "verdict": "CORROBORATED" + }, + "onscreen": { + "title": "Not for sale", + "subtitle": "The baker on selling to a chain" + } + }, + { + "type": "clip", + "id": "c02", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 25, + "end": 29.8, + "cite": 25, + "quote": "we never said that about the old oven", + "claim": { + "id": "k02", + "verdict": "PARTLY" + } + }, + { + "type": "clip", + "id": "c03", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 45, + "end": 49.8, + "cite": 45, + "quote": "I paid for the new mixer myself", + "claim": { + "id": "k03", + "verdict": "CORROBORATED" + } + }, + { + "type": "card", + "id": "the-contest", + "style": "chapter", + "seconds": 3.5, + "heading": "The contest", + "narration": { + "text": "A month later, the pie stream." + } + }, + { + "type": "clip", + "id": "c04", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 10, + "end": 14.8, + "cite": 10, + "quote": "I did not enter the contest this year", + "claim": { + "id": "k04", + "verdict": "CONTRADICTED" + }, + "onscreen": { + "title": "The contest" + } + }, + { + "type": "clip", + "id": "c05", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "the judges were friends of mine so it felt wrong", + "claim": { + "id": "k05", + "verdict": "PARTLY" + } + }, + { + "type": "clip", + "id": "c06", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 40, + "end": 44.8, + "cite": 40, + "quote": "my lawyer told me not to talk about the lease", + "claim": { + "id": "k06", + "verdict": "NOT_FOUND" + } + }, + { + "type": "clip", + "id": "c07", + "channel": "synth-kitchen", + "video": "qa-long-03", + "start": 210, + "end": 214.8, + "cite": 210, + "quote": "it was always going to be a small place", + "claim": { + "id": "k07", + "verdict": "CONTRADICTED" + } + }, + { + "type": "teaser", + "id": "fin", + "lines": [ + "Synth Kitchen", + "The bakery and the contest", + "March 2026" + ] + } + ] +} diff --git a/common/testing/draft/manifests/full.video.manifest.json b/common/testing/draft/manifests/full.video.manifest.json @@ -0,0 +1,218 @@ +{ + "schemaVersion": 1, + "slug": "synth-full", + "title": "Synth Kitchen — what the baker says about the bakery", + "subtitle": "", + "generatedOn": "2026-10-13", + "provenance": { + "siteOrigin": "https://synth.example", + "channelSlug": "synth-kitchen", + "channel": "" + }, + "render": { + "width": 1920, + "height": 1080, + "fps": 30, + "audioRate": 48000, + "audioChannels": 2, + "maxHeightSource": 1080, + "fontRegular": "/usr/share/fonts/TTF/FiraSans-Regular.ttf", + "fontBold": "/usr/share/fonts/TTF/FiraSans-Bold.ttf", + "palette": { + "bg": "#12100c", + "fg": "#f6f1e6", + "muted": "#a2957f", + "accent": "#c8752a", + "amber": "#ffc860" + }, + "transition": 0.4, + "fetchPad": 3, + "snapWindow": 1.6, + "silenceMinDur": 0.09, + "silenceRelDb": 6, + "headerHeight": 56, + "footerHeight": 0, + "crf": 21, + "preset": "slow", + "qr": { + "scale": 4, + "quiet": 3, + "ecc": "M", + "margin": 28 + }, + "chrome": { + "engine": "hyperframes", + "layout": "deck", + "factcheck": {}, + "threads": { + "list": [ + { + "id": "bakery", + "label": "The bakery", + "outcome": { + "verdict": "CONTRADICTED" + } + }, + { + "id": "contest", + "label": "The contest" + } + ] + } + }, + "narration": { + "engine": "kokoro", + "voice": "af_heart" + } + }, + "timelineNodes": [], + "timeline": [ + { + "type": "card", + "id": "title", + "style": "title", + "seconds": 4, + "heading": "Synth Kitchen — what the baker says about the bakery", + "sub": "", + "foot": "" + }, + { + "type": "card", + "id": "the-bakery", + "style": "chapter", + "seconds": 3.5, + "heading": "The bakery" + }, + { + "type": "clip", + "id": "c01", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "I would never sell the bakery to a chain", + "claim": { + "id": "k01", + "verdict": "CORROBORATED" + }, + "thread": "bakery", + "onscreen": { + "title": "Not for sale", + "subtitle": "The baker on selling to a chain" + } + }, + { + "type": "clip", + "id": "c02", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 25, + "end": 29.8, + "cite": 25, + "quote": "we never said that about the old oven", + "claim": { + "id": "k02", + "verdict": "PARTLY" + }, + "thread": "bakery" + }, + { + "type": "clip", + "id": "c03", + "channel": "synth-kitchen", + "video": "bread-day-01", + "start": 45, + "end": 49.8, + "cite": 45, + "quote": "I paid for the new mixer myself", + "claim": { + "id": "k03", + "verdict": "CORROBORATED" + }, + "thread": "bakery" + }, + { + "type": "card", + "id": "the-contest", + "style": "chapter", + "seconds": 3.5, + "heading": "The contest", + "narration": { + "text": "A month later, the pie stream." + } + }, + { + "type": "clip", + "id": "c04", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 10, + "end": 14.8, + "cite": 10, + "quote": "I did not enter the contest this year", + "claim": { + "id": "k04", + "verdict": "CONTRADICTED" + }, + "thread": "contest", + "onscreen": { + "title": "The contest" + } + }, + { + "type": "clip", + "id": "c05", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 15, + "end": 19.8, + "cite": 15, + "quote": "the judges were friends of mine so it felt wrong", + "claim": { + "id": "k05", + "verdict": "PARTLY" + }, + "thread": "contest" + }, + { + "type": "clip", + "id": "c06", + "channel": "synth-kitchen", + "video": "pie-stream-02", + "start": 40, + "end": 44.8, + "cite": 40, + "quote": "my lawyer told me not to talk about the lease", + "claim": { + "id": "k06", + "verdict": "NOT_FOUND" + }, + "thread": "contest" + }, + { + "type": "clip", + "id": "c07", + "channel": "synth-kitchen", + "video": "qa-long-03", + "start": 210, + "end": 214.8, + "cite": 210, + "quote": "it was always going to be a small place", + "claim": { + "id": "k07", + "verdict": "CONTRADICTED" + }, + "thread": "bakery" + }, + { + "type": "teaser", + "id": "fin", + "lines": [ + "Synth Kitchen", + "The bakery and the contest", + "March 2026" + ] + } + ] +} diff --git a/common/testing/draft/manifests/paragraphs.video.manifest.json b/common/testing/draft/manifests/paragraphs.video.manifest.json @@ -79,5 +79,13 @@ "cite": 5, "quote": "we tried the sourdough recipe from last week" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/manifests/posts-only.video.manifest.json b/common/testing/draft/manifests/posts-only.video.manifest.json @@ -76,5 +76,13 @@ "siteChannel": "synth-social", "postId": "1700000000000000002" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/reports/ruled.report.json b/common/testing/draft/reports/ruled.report.json @@ -0,0 +1,156 @@ +{ + "format": "archilyzer-report", + "version": 1, + "id": "synth-ruled", + "kind": "factcheck", + "title": "Synth Kitchen — what an article says about the baker, checked", + "summary": "Scope: channel `synth-kitchen`, every recording read. A synthetic fact-check whose verdicts stand for operator rulings.", + "sections": [ + { + "id": "the-bakery", + "title": "The bakery", + "claims": [ + { + "id": "r01", + "text": "The article says she has ruled out selling the bakery to a chain.", + "verdict": "CORROBORATED", + "findings": "She says so in Bread day.", + "citations": [ + "q01" + ] + }, + { + "id": "r02", + "text": "The article says the old oven was broken.", + "verdict": "PARTLY", + "findings": "She says it ran hot, and that it was fine.", + "citations": [ + "q02" + ] + }, + { + "id": "r03", + "text": "The article says she paid for all the kitchen's equipment herself.", + "verdict": "PARTLY", + "findings": "She says she paid for the mixer; nothing about the rest.", + "citations": [ + "q03" + ] + }, + { + "id": "r04", + "text": "The article says the second shop is a large store.", + "verdict": "CONTRADICTED", + "findings": "She calls it a small place.", + "citations": [ + "q04" + ] + }, + { + "id": "r05", + "text": "The article says she uses a bread machine.", + "verdict": "CONTRADICTED", + "findings": "She says she does not use one at all.", + "citations": [ + "q05" + ] + } + ] + }, + { + "id": "the-contest", + "title": "The contest", + "claims": [ + { + "id": "r06", + "text": "The article says she stayed out of this year's contest.", + "verdict": "CORROBORATED", + "findings": "She says she did not enter.", + "citations": [ + "q06" + ] + }, + { + "id": "r07", + "text": "The article says she named her lawyer on stream.", + "verdict": "NOT_FOUND", + "findings": "She mentions a lawyer, never by name.", + "citations": [ + "q07" + ] + }, + { + "id": "r08", + "text": "The article says she is the best baker in the county.", + "verdict": "UNTESTABLE", + "findings": "A judgement, not a statement of hers." + } + ] + } + ], + "citations": { + "q01": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 15, + "end": 19.8, + "quote": "I would never sell the bakery to a chain", + "label": "Bread day" + }, + "q02": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 30, + "end": 34.8, + "quote": "the oven was fine it just ran hot", + "label": "Bread day" + }, + "q03": { + "kind": "video", + "channel": "synth-kitchen", + "id": "bread-day-01", + "start": 45, + "end": 49.8, + "quote": "I paid for the new mixer myself", + "label": "Bread day" + }, + "q04": { + "kind": "video", + "channel": "synth-kitchen", + "id": "qa-long-03", + "start": 210, + "end": 214.8, + "quote": "it was always going to be a small place", + "label": "Questions and answers" + }, + "q05": { + "kind": "video", + "channel": "synth-kitchen", + "id": "qa-long-03", + "start": 10, + "end": 14.8, + "quote": "I do not use a bread machine at all", + "label": "Questions and answers" + }, + "q06": { + "kind": "video", + "channel": "synth-kitchen", + "id": "pie-stream-02", + "start": 10, + "end": 14.8, + "quote": "I did not enter the contest this year", + "label": "Pie stream" + }, + "q07": { + "kind": "video", + "channel": "synth-kitchen", + "id": "pie-stream-02", + "start": 40, + "end": 44.8, + "quote": "my lawyer told me not to talk about the lease", + "label": "Pie stream" + } + } +} diff --git a/common/testing/draft/runMediaStep.ts b/common/testing/draft/runMediaStep.ts @@ -0,0 +1,73 @@ +// A media draft run for real over a fixture iteration, its model the fake +// ollama scripted with the task's recorded run (`runs/<task>.json`) — what +// umtool's e2e editor stub does with a `report-draft` of a media task +// (release 28: umtool/e2e/media-draft.spec.ts). Test-only; synthetic. +// +// tsx common/testing/draft/runMediaStep.ts --task cut --article mdraft --n 1 \ +// --articles <ARTICLES_DIR> --projects <projectsRoot> [--model qwen3:8b] \ +// [--entries c01,c02] [--force] [--job <id>] +// +// The task records its own step on the iteration (running, then its end). The +// last line printed is `@@report-draft {article, iteration, task, status, +// summary}`; the exit code is 0 when the step is done. + +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { startFakeOllama } from "../llm/fakeOllama.mjs"; +import { isStepTask } from "../../lib/generationSettings"; +import { loadDeckChecks, runTask, type TaskInput } from "../../lib/report/draft/tasks/index"; + +const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); +const ROOT = path.resolve(/* turbopackIgnore: true */ HERE, "../../.."); + +const argv = process.argv.slice(2); +const flag = (name: string) => { + const i = argv.indexOf(`--${name}`); + return i < 0 ? undefined : argv[i + 1]; +}; +const task = flag("task") ?? ""; +const article = flag("article") ?? ""; +const n = Number(flag("n")); +const articlesDir = flag("articles") ?? ""; +const projectsRoot = flag("projects") ?? ""; +if (!isStepTask(task) || !article || !Number.isInteger(n) || !articlesDir || !projectsRoot) { + console.error("usage: runMediaStep.ts --task <media task> --article <id> --n <i> --articles <dir> --projects <dir> [--model m] [--entries a,b] [--force] [--job id]"); + process.exit(2); +} + +const run = JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ HERE, "runs", `${task}.json`), "utf8")) as { model: string; turns: unknown[] }; +const ol = await startFakeOllama(); +ol.push(...(run.turns as never[])); +const exportIndexDir = path.join(articlesDir, "..", ".export-index-media-draft"); +await mkdir(exportIndexDir, { recursive: true }); +const entries = flag("entries")?.split(",").map((x) => x.trim()).filter(Boolean); +const jobId = flag("job"); +const input = { + task, + article, + n, + model: flag("model") ?? run.model, + projectsRoot, + ...(entries?.length ? { entries } : {}), + ...(argv.includes("--force") ? { force: true } : {}), + ...(jobId ? { jobId } : {}), +} as TaskInput; +let code = 1; +try { + const res = await runTask(input, { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths: { articlesDir, exportIndexDir }, + log: (l) => console.log(l), + deckChecks: () => loadDeckChecks(ROOT), + }); + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task, status: res.status, summary: res.summary })}`); + code = res.status === "done" ? 0 : 1; +} catch (e) { + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "failed", summary: (e as Error).message })}`); +} finally { + await ol.close(); +} +process.exit(code); diff --git a/common/testing/draft/runs/cut.json b/common/testing/draft/runs/cut.json @@ -0,0 +1,20 @@ +{ + "task": "cut", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"groups\": [{\"heading\": \"The contest\", \"clips\": [\"c04\", \"c06\", \"c09\"]}, {\"heading\": \"The bakery\", \"clips\": [\"c03\", \"c01\", \"c01\"]}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"groups\": [{\"heading\": \"The contest\", \"clips\": [\"c04\", \"c06\"]}, {\"heading\": \"The bakery\", \"clips\": [\"c03\", \"c01\"]}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/flips.json b/common/testing/draft/runs/flips.json @@ -0,0 +1,21 @@ +{ + "task": "flips", + "model": "qwen3:8b", + "note": "Over the full manifest with its threads taken off (a deck, no left panel) and the basic report. The first answer is refused (a pair of one day; a number the report does not have) and re-asked; the second is the S0 flips manifest's pair.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c07\", \"now\": \"c01\"}, {\"topic\": \"The contest in 2027\", \"then\": \"c04\", \"now\": \"c05\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c01\", \"now\": \"c07\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/onscreen.json b/common/testing/draft/runs/onscreen.json @@ -0,0 +1,20 @@ +{ + "task": "onscreen", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c01\", \"title\": \"She will not sell to a chain\", \"subtitle\": \"\\\"I would never sell the bakery to a chain\\\"\"}, {\"id\": \"c02\", \"title\": \"\\\"Never said that\\\"\", \"subtitle\": \"On the old oven\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I bought the mixer\\\"\"}, {\"id\": \"c04\", \"title\": \"She did not enter the contest this year, she says, and explains it\", \"subtitle\": \"Pie stream\"}, {\"id\": \"c05\", \"title\": \"Why she stayed out\", \"subtitle\": \"The judges were her friends\"}, {\"id\": \"c06\", \"title\": \"Lease talks in 2024\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c02\", \"title\": \"The oven story, denied\", \"subtitle\": \"\\\"we never said that about the old oven\\\"\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I paid for the new mixer myself\\\"\"}, {\"id\": \"c04\", \"title\": \"Out of the contest this year\", \"subtitle\": \"From the pie stream\"}, {\"id\": \"c06\", \"title\": \"Lease talks with Marco\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/teaser.json b/common/testing/draft/runs/teaser.json @@ -0,0 +1,20 @@ +{ + "task": "teaser", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"lines\": [\"Synth Kitchen\", \"She would never sell the bakery\", \"The contest\", \"Two streams later\"]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"lines\": [\"Synth Kitchen\", \"The bakery\", \"The contest\", \"What the baker says\"]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/threads.json b/common/testing/draft/runs/threads.json @@ -0,0 +1,21 @@ +{ + "task": "threads", + "model": "qwen3:8b", + "note": "Over the full manifest with its threads taken off and the basic report. The first answer is refused (a label naming someone the report does not; a thread with no clip) and re-asked; the second groups the clips as the S0 full manifest does, the lease clip in the contest thread.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}, {\"id\": \"gordon\", \"label\": \"Talks with Gordon\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"contest\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/youtube.json b/common/testing/draft/runs/youtube.json @@ -0,0 +1,21 @@ +{ + "task": "youtube", + "model": "qwen3:8b", + "note": "Over the basic manifest and report. The first answer is refused (the summary speaks as the speaker; a link) and re-asked; the second is kept.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"She told us the bakery is not for sale. Watch it at https://synth.example.\"}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"Synth Kitchen's baker says \\\"I would never sell the bakery to a chain\\\" and that she paid for the new mixer herself. In a later stream she says she did not enter the contest this year, and she will not talk about the lease.\"}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/sweeps/fragment.md b/common/testing/draft/sweeps/fragment.md @@ -0,0 +1,11 @@ +# Fragment quotes + +Four quotes, every one verbatim: three stop mid-thought — two on a function word, one under four words — and one is a +whole sentence. + +## Findings + +- The mixer: "I paid for the" [Bread day @ 0:45](https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=45) +- The lease: "my lawyer told me not to" [Pie stream @ 0:40](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=40) +- The contest: "I did not" [Pie stream @ 0:10](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=10) +- The finalist: "I have never met the other finalist" [Pie stream @ 0:30](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=30) diff --git a/common/testing/fakes.test.ts b/common/testing/fakes.test.ts @@ -217,3 +217,17 @@ test("fixtures: the corpus has cues for every record and writes the shard layout await rm(dir, { recursive: true, force: true }); } }); + +test("fixtures: the ruled fact-check (release 28) validates, carries every verdict, and quotes the corpus", async () => { + const report = JSON.parse(await readFile(path.join(HERE, "draft", "reports", "ruled.report.json"), "utf8")); + assert.deepEqual(validateReport(report), []); + const claims = report.sections.flatMap((s: any) => s.claims ?? []); + assert.deepEqual( + [...new Set(claims.map((c: any) => c.verdict))].sort(), + ["CONTRADICTED", "CORROBORATED", "NOT_FOUND", "PARTLY", "UNTESTABLE"], + ); + for (const [id, c] of Object.entries<any>(report.citations)) { + const cue = (await cuesOf(c.channel, c.id))?.find((q: any) => q.start === c.start); + assert.equal(cue?.text, c.quote, id); + } +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,32 @@ # Changelog ## [Unreleased] +- **umtool drafts each section of a report video with a model you pick.** A video project made from an article's iteration has a **draft** section: for the cut, the on-screen titles, the teaser, the flips, the threads, the narration and the YouTube text, **Draft with** and a model (the generation policy's models, the task's route chosen first), **force** (re-drafts only what a model drafted; what you wrote or edited is never replaced), and for a per-entry task the entries to draft. The job's progress shows while it runs; when it ends the page shows what it wrote, skipped and had refused by a check, the **drafted by** badge with **Approve** and **Reject**, and any draft kept aside with **Use this**. A project not made from an iteration says so and offers none. The article's Iterations tab gains the same drafts beside **Narrate**. Needs a restart of umtool. +- **Draft everything.** One button on the Iterations tab (or `umtool chain <article> <n> --draft-all [--model M]`) runs the chain with every media draft in it, on the model you choose: the cut, on-screen, teaser, flips, threads and narration after the manifest, then the voices, a fast build and the podcast, then the YouTube text, whose chapters are re-muxed so `out/youtube.txt` is written. A draft the editor refuses or that fails is marked failed and the chain carries on; one with nothing to draft, or flips and threads with no on-screen deck (or with the other panel on), is skipped. It does not attach the video to the article: review the drafts first. Started again, it resumes after the last draft that ran. Needs a restart of umtool. +- **A site's Delete shows its plan before anything goes.** On `/sites`, **Delete** lists what would be removed (the site, its publish state and last bundle, its staging), how much, what is kept and what refuses; **Confirm delete** removes it. A site with a deploy target, a recorded deploy or reports of its own is refused unless you tick the box and press **Delete with force**; a site whose directory is a link, or a publish stage running, is refused outright. The delete is `pnpm ops delete-site`'s, so it now removes the build state too. +- **Use this on a threads draft sets each clip's thread too.** Taking a threads alternative writes the clips' assignments with the list, so no clip is left naming a thread that is gone. +- **A video revision that reorders the cut makes the order a draft.** The order then has a review row, and the cut task redrafts it only with force. A revision that leaves the order alone keeps the mark it had. +- **An on-screen title in Title Case is no longer refused as naming people.** Its capitals are not read as names: an ordinary word passes, and a name the clip's evidence lacks is still refused. +- **Claude Code's `generate` and `/gen` know the media drafts.** `/gen` maps "draft the on-screen titles", "make a teaser", "YouTube description" and the like to the media tasks; `generate` checks that a media draft names its iteration, and its answer for a done draft says what to check for that task and that the approval is yours in umtool's review page. `archilyzer gen run` takes a media task with `--iteration` and `--entries`. +- **The editor drafts a report video's cut, on-screen text and teaser.** `pnpm ops report-draft --json '{"task": "cut" | "onscreen" | "teaser", "article", "iteration", "model"?, "entries"?, "force"?}'` runs on a done iteration's video project, as a step on it, like narration. **Cut** picks which of the report's citations the video shows and in what order, grouped under the report's sections; the code builds the timeline from the entries the cut already had (windows, quotes and on-screen text untouched), keeps a chapter card only while its section has a clip, keeps the title card and the teaser where they are, never drops a clip a post or a flip needs, and refuses an order the build would refuse. At most `settings.generation.cut.maxClips` entries (new, default 20), at least 3. **On-screen** writes each clip's title (at most 60 characters, no quotation marks) and subtitle (at most 90; it may quote only the clip's own words, exactly), several clips to a request. **Teaser** writes 3 to 5 lines that fit the teaser card, quoting nobody; a cut with no teaser gets one after its last clip. Every name and number must be in the report. Each drafted field carries its `drafted` mark and goes through the drafts review; a field you wrote or edited is never replaced (with `force` its draft is kept aside as an alternative). Each media draft has its own route in the generation policy (narration's, in every preset), and its job shows the entries done. Needs a restart of the editor and umtool. +- **A starter cut's order is marked as the converter's.** `archilyzer reports to-manifest` marks the timeline it writes as drafted by code (`drafted.timeline`, model `code`), so the cut task may redraft it without `force`; a cut converted before this release counts the same while its clips are still in the converter's order. A code-made order needs no review and shows no badge. Reordering it in umtool makes it yours. +- **New settings key `generation.cut.maxClips`** (SETTINGS.md): the most entries a drafted cut keeps (default 20). +- **A research run on `auto` continues into its sweep by itself.** Once its acquisitions settle — every job it started has ended and nothing waits for your yes or no — the editor runs the same sweep **Continue into a sweep** would, on the run's own model, and the run's queue in umtool says **continued automatically by i<n>**. The caps hold: the sweep's per-job cap applies, and past the day's API total it is not started; the queue says so, and it is tried again the next day (UTC). A channel the run acquired into that is in no site build yet is left out of the sweep, with the warning "not in any build yet: <slug> — rebuild the site and continue again" on the queue and on the sweep; a run with nothing it could sweep waits for a newer build. `propose` and `limits` runs are still continued by you, and an editor booted idle (`ARCHILYZER_IDLE_BOOT`) continues nothing. Needs a restart of the editor and umtool. +- **The editor drafts a report video's flips, threads and YouTube text.** `pnpm ops report-draft --json '{"task": "flips" | "threads" | "youtube", "article", "iteration", "model"?, "force"?}'` runs on a done iteration's video project. **Flips** pairs a clip with a later one on the same topic: the model picks the clips and names the topic, and the dates (the recordings'), the THEN/NOW order, the `when` lines and the words (the clip's own quote, word for word) are set by code. **Threads** groups the clips into 2 to 4 labelled threads; a thread's verdict stamp is its last clip's ruling, never the model's. **YouTube** writes `publish.youtube`'s title and a one-paragraph summary, with every name and number from the report, in the third person, quoting only what a clip says. Flips and threads share the left panel, so each refuses a cut that has the other unless forced over a draft of it, which it then replaces. Each drafted field carries its `drafted` mark and goes through the drafts review. +- **A build writes the YouTube text: `out/youtube.txt`.** When the manifest has `publish.youtube`, the build writes the title, the summary, the chapters from its own chapter list, and a moment link for each cited clip, in cut order, each once. The chapters follow YouTube's rules: they start at 0:00, there are at least three, and each lasts ten seconds or more. A shorter one is folded into the one before it; when the list still falls short it is left out, and the build says why. umtool's project page shows the text with **Copy**. Before a build, it shows the same text without the chapters. +- **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`). +- **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes). +- **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts. +- **Generated narration that speaks as the speaker is refused.** The narrator is third person: a drafted narration sentence with I, me, my, we, us or our outside quotation marks fails its check ("the narrator is third person"), and when the sentence restates a cited quote the reason names whose line it is and its citation (`c03 (Bread day @ 0:45)`). A narration step drops such a sentence as it drops any other failing one; a video revision's narration op is refused with it. "US" in capitals and words that only contain the letters ("Iowa", "myth") are not caught; "mine" the noun is. +- **A generated quote that stops mid-sentence is refused, and the full sentence is offered.** A quote under four words, or one that ends on a word like "as", "to", "the", "and" or "my" without sentence punctuation, is a fragment. In a generated sweep it goes to the repair round with the transcript's whole sentence to quote instead (or is dropped if still a fragment); a revision's added finding is refused with the sentence; the local pipeline extends such a quote to its sentence itself. `archilyzer reports verify-quotes` reports an existing report's fragment quotes as **`fragment`**, a warning with the full sentence, after `drift`, `en-orig-drift` and `inexact`; the exit code is unchanged. Needs a restart of the editor. +- **Report and video revisions on the local model are one request.** A revision on the local model no longer runs a tool conversation: it asks once for the whole batch of edits, over the report or cut trimmed to fit the model's 8k-token prompt (the sections or chapters the feedback names first; long quotes shortened and links cut to their labels in what the model reads, never in the report). Revisions on the Claude API are unchanged. Needs a restart of the editor. +- **A sweep can name its own extractor.** `pnpm ops report-draft --json '{"task": "sweep", …, "extractorModel": "claude-haiku-5-5"}'` reads that sweep's batches with the named Claude model instead of `settings.generation.models.extractor`; the MCP's `generate` takes it too. In umtool, a sweep on a Claude model shows an **extractor** choice on `/articles/new`, beside **Copy with model**, and beside a research run's **Continue into a sweep**. A sweep on the local model has no extractor and says so. Needs a restart of the editor and umtool. +- **Report draft jobs show their progress.** A **Report draft** job's row on /jobs now shows the model turns taken against the task's turn limit (a sweep, a revision, a research run; the repair round counted on), or the recordings read of the worklist for a sweep on the local model. `pnpm ops get job <id>` carries the same as `progress`. Needs a restart of the editor. +- **The verdict bench: could a model propose a fact-check verdict well enough to review?** `archilyzer reports bench-verdicts --models claude-sonnet-5-5,claude-opus-5-5,qwen3:8b` asks each model about every claim of the fact-check articles that carries your verdict and a citation with a transcript — one claim per call, shown the claim, its quotes and the transcript a minute either side, never your findings or your verdict — and scores the answers against your rulings: agreement, CONTRADICTED and NOT_FOUND recall, PARTLY counted strictly and as close to CORROBORATED, beside a model that always says CORROBORATED, with the cost and the time each took. `--dry` lists the claims it would ask and what the run would cost, asking nothing. The run goes through the editor (`pnpm ops bench-verdicts`; a local model takes its turn on the GPU and is unloaded after), stops at `--max-usd` (default $5, the whole run), and a run with the same `--run` id carries on where it stopped. The results stay on this machine, in `.generation/bench/verdicts/`. +- **umtool: `/bench` shows a bench run, and is where you set the bar.** Per model its agreement and recalls against the always-CORROBORATED baseline and its cost, the confusion matrix (your verdict against the model's), and every claim with each model's verdict and reason, disagreements first, filtered by model or by your verdict. The bar — the least agreement, CONTRADICTED recall and NOT_FOUND recall a model must reach — is saved into the editor's settings (`settings.generation.verdicts`), each model reads as passing or failing it, and verdict proposals will run only on the passing models you tick. Linked from `/articles` ("verdict bench"). +- **`pnpm ops delete-site {"id", "dryRun"?, "force"?}` deletes a site, plan first.** It removes the site's directory (its settings, pages, tags, charts and reports), its last build and publish state, and its export staging, and says what it keeps: every channel's data (never touched), the Pages project and anything already deployed (a delete does not undeploy), a deployed hub until it is rebuilt. A site with a Pages project, a recorded deploy or reports of its own is refused unless `force`; a missing site, a linked site directory or a publish stage running is refused whatever. +- **A paused parakeet transcription no longer leaves its working files in the temp directory**, and each run clears what a crashed or killed run left there more than a day ago (unless another run still owns it). +- **New settings key `generation.verdicts`** (SETTINGS.md): the verdict bench's bar (`agreement`, `contradictedRecall`, `notFoundRecall`, fractions) and the passing models you ticked (`models`, never set automatically). - **umtool has a new look, in dark and light: the desk and the reader.** Tool chrome is a warm-ink desk (warm grey in light) and anything a source said — a quote, a post, a transcript window, the clip and claim benches' transcripts — sits on a pale green-grey reader surface, so a quote is never mistaken for a claim about it. Colours are roles: Signal (teal) only for focus, the lit line and the one primary action; Meter (violet) for counts and spend; the three verdicts always as glyph and word (✓ ? ✕), never on the reader. The faces are vendored (Archivo, IBM Plex Sans and Mono, Source Serif 4 for the reader) and load with no network. - **umtool: Auto / Light / Dark at the foot of the rail.** Auto follows the system; a choice is a cookie the server reads, so the page is served in it with no flash. - **umtool: every page has the rail.** The mark and the wordmark (home), the places (unchanged: home · browse · decisions · articles · mix · find · song ▸), + Create (a new article or a new project), Pinned, what umtool is running, and the theme. The page's name is its title under the breadcrumb. The clip, claim and takes benches drop the rail and take the full width. diff --git a/editor/app/api/ops/_autoContinue.ts b/editor/app/api/ops/_autoContinue.ts @@ -0,0 +1,16 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { armResearchAutoContinue } from "yt-dlp-transcript-common/controller/researchAutoContinue"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { researchEditor } from "./_researchEditor"; + +// AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1), armed by +// instrumentation.ts below the idle gate: the job-end listener and a boot +// scan now, the heartbeat's scan from then on. The deps are the report-draft +// route's own, so a continuation is the job "Continue into a sweep" posts. +// See common/controller/researchAutoContinue.ts. +export function armAutoContinue(): boolean { + return armResearchAutoContinue( + { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }), researchEditor }, + { log: (line) => console.log(line) }, + ); +} diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts @@ -0,0 +1,124 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { CHANNELS } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +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 { enqueueVerdictBench, parseBenchVerdictsBody } from "yt-dlp-transcript-common/controller/benchVerdicts"; +import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { readBenchRun } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_benchVerdicts.test.ts" +// +// The `bench-verdicts` job (release 28 M7) end to end in this process: the +// controller the route adapts, the ruled synthetic fact-check in a temp +// article store, the synthetic recordings' cues on disk, the fake Anthropic +// and ollama servers, a temp jobs dir, usage ledger and runs root. + +const RULED = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft/reports/ruled.report.json"); +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let paths: Paths; +let gen: GenerationSettings; +let root: string; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "bench-verdicts-")); + 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); + const report = JSON.parse(await readFile(RULED, "utf8")); + await mkdir(path.join(tmp, "reports", report.id), { recursive: true }); + await writeFile(path.join(tmp, "reports", report.id, "report.json"), JSON.stringify(report)); + for (const ch of CHANNELS) { + for (const r of ch.records) { + const rec = path.join(tmp, "channels", ch.slug, "data", r.id); + await mkdir(rec, { recursive: true }); + await writeFile(path.join(rec, "transcript.cues.json"), JSON.stringify({ cues: r.cues })); + } + } + paths = { + jobsDir: path.join(tmp, ".jobs"), + articlesDir: path.join(tmp, "reports"), + exportIndexDir: path.join(tmp, ".export-index"), + channelsDir: path.join(tmp, "channels"), + generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), + ollamaUrl: ol.url, + } as Paths; + root = path.join(tmp, ".generation", "bench", "verdicts"); + gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20 } }); +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const deps = (g: Partial<GenerationSettings> = {}) => ({ paths, root, settings: () => ({ generation: { ...gen, ...g } }) }); + +test("the body: models required, the run id and reports checked, numbers as numbers", () => { + assert.throws(() => parseBenchVerdictsBody({}), /"models" is a list/); + assert.throws(() => parseBenchVerdictsBody({ models: [] }), /at least one model/); + assert.throws(() => parseBenchVerdictsBody({ models: ["m"], run: "../x" }), /"run" is a run id/); + assert.throws(() => parseBenchVerdictsBody({ models: ["m"], reports: ["Bad Id"] }), /"reports" is a list of article ids/); + assert.throws(() => parseBenchVerdictsBody({ models: ["m"], window: "60" }), /"window" is a number/); + assert.deepEqual(parseBenchVerdictsBody({ models: "a, b", maxUsd: 2, limit: 3 }), { models: ["a", "b"], maxUsd: 2, limit: 3 }); +}); + +test("an API and a local model: a bench-verdicts job on draft:local, every answer on disk, the API spend in the ledger, ollama unloaded", async () => { + for (let i = 0; i < 7; i++) api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "she says so" })); + for (let i = 0; i < 7; i++) ol.push(jsonReply({ verdict: "NOT_FOUND", reason: "not in the window" })); + const out = await enqueueVerdictBench({ models: ["claude-sonnet-5-5", "qwen3:8b"], run: "vb-editor" }, deps()); + assert.ok(out.result.ok && "run" in out, (out.result as { error?: string }).error); + assert.equal(out.run, "vb-editor"); + const job = getRegistry().get(out.result.jobId)!; + assert.equal(job.kind, "bench-verdicts"); + assert.equal(job.queueKey, "draft:local"); + void out.result.stream.cancel(); + const done = await out.result.done; + const log = await readFile(job.logPath, "utf8"); + assert.equal(done.status, "done", log); + assert.match(log, /@@bench-verdicts \{"run":"vb-editor","status":"done","items":7,"skipped":1/); + assert.match(log, /unloaded qwen3:8b from ollama/); + assert.ok(!log.includes(FAKE_KEY), "the key is never in the log"); + assert.deepEqual(ol.unloads, ["qwen3:8b"]); + const run = (await readBenchRun(root, "vb-editor"))!; + assert.equal(run.results.length, 14); + const [sonnet, qwen] = run.summary.score.models; + assert.equal(sonnet!.agreed, 2); // the two CORROBORATED + assert.equal(qwen!.agreed, 1); // the one NOT_FOUND + const rows = await readGenerationUsage(paths.generationUsageFile); + assert.deepEqual(rows.map((r) => [r.model, r.task, r.jobId]), [["claude-sonnet-5-5", "bench-verdicts", out.result.jobId]]); + assert.ok(rows[0]!.usd > 0); + assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); +}); + +test("API models only run on draft:api; past the day's cap an API run is refused, a local one is not", async () => { + api.push(toolTurn("answer", { verdict: "CORROBORATED", reason: "ok" })); + const one = await enqueueVerdictBench({ models: ["claude-haiku-4-5"], run: "vb-api", limit: 1 }, deps()); + assert.ok(one.result.ok && "run" in one); + assert.equal(getRegistry().get(one.result.jobId)!.queueKey, "draft:api"); + void one.result.stream.cancel(); + assert.equal((await one.result.done).status, "done"); + await appendGenerationUsage(paths.generationUsageFile, [ + { at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }, + ]); + const refused = await enqueueVerdictBench({ models: ["claude-sonnet-5-5"], run: "vb-late" }, deps()); + assert.equal(refused.result.ok, false); + assert.match((refused.result as { error: string }).error, /daily cap/); + ol.push(jsonReply({ verdict: "CORROBORATED", reason: "ok" })); + const local = await enqueueVerdictBench({ models: ["qwen3:8b"], run: "vb-local", limit: 1 }, deps()); + assert.ok(local.result.ok && "run" in local); + void local.result.stream.cancel(); + assert.equal((await local.result.done).status, "done"); +}); diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -81,6 +81,32 @@ test("the body: each task's needs, and the refusals in words", () => { assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: " q ", channels: "x, y" }), { task: "sweep", article: "a", question: "q", channels: ["x", "y"] }); }); +test("a media draft (release 28): a step body as narrate's — its iteration, no copy; entries a step's; an unknown task refused", () => { + for (const task of ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]) { + assert.throws(() => parseReportDraftBody({ task, article: "a" }), task === "narrate" ? /names the iteration it voices/ : new RegExp(`a ${task} draft names the iteration it drafts on`)); + assert.throws(() => parseReportDraftBody({ task, article: "a", iteration: 1, copyOf: 1 }), /is a step, not an iteration: it has no copy/); + assert.deepEqual(parseReportDraftBody({ task, article: "a", iteration: 2, model: "qwen3:8b", entries: "c01, c02", force: true }), { + task, + article: "a", + iteration: 2, + model: "qwen3:8b", + entries: ["c01", "c02"], + force: true, + }); + } + assert.throws(() => parseReportDraftBody({ task: "revise-video", article: "a", iteration: 1, feedback: "f", entries: ["c01"] }), /"entries" is a media draft's/); + assert.throws(() => parseReportDraftBody({ task: "cuts", article: "a", iteration: 1 }), /"task" is one of .*cut, onscreen, teaser, flips, threads, youtube/); +}); + +test("extractorModel (release 28 F2): a sweep's, a Claude model the price table knows", () => { + const sweep = { task: "sweep", article: "a", question: "q", channels: ["x"] }; + assert.equal(parseReportDraftBody({ ...sweep, extractorModel: "claude-haiku-5-5" }).extractorModel, "claude-haiku-5-5"); + assert.equal(parseReportDraftBody({ ...sweep, extractorModel: "claude-haiku-4-5-20251001" }).extractorModel, "claude-haiku-4-5-20251001"); + assert.throws(() => parseReportDraftBody({ ...sweep, extractorModel: "qwen3:8b" }), /"extractorModel" is a Claude model id/); + assert.throws(() => parseReportDraftBody({ ...sweep, extractorModel: "claude-nonsense-9" }), /"extractorModel" is a Claude model id/); + assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f", extractorModel: "claude-haiku-5-5" }), /"extractorModel" is a sweep's/); +}); + test("refused before any iteration: a task routed to Claude Code with no model, a cap over max", async () => { const code = await enqueueReportDraft({ task: "sweep", article: "synth-refused", question: "q", channels: ["synth-kitchen"], source }, deps()); assert.equal(code.result.ok, false); @@ -115,6 +141,28 @@ test("an API sweep: a report-draft job on draft:api, the iteration done with its const jobId = out.result.jobId; assert.ok(rows.every((x) => x.jobId === jobId && x.article === "synth-api" && x.iteration === 1)); assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); + // The job's progress (release 28 F3): the agent's model turns, the runner's own count. + assert.deepEqual(job.progress, { metric: "turns", initial: 0, target: 150, current: 6 }); +}); + +test("an API sweep with its own extractorModel: the batches are read on it, its spend in the ledger", async () => { + const r = await run("sweep-agent"); + api.push(...r.turns); + const before = api.requests.length; + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-extractor", model: r.model, extractorModel: "claude-haiku-5-5", question: r.question, channels: r.channels, source }, + deps(), + ); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + const job = getRegistry().get(out.result.jobId)!; + assert.equal(done.status, "done", await readFile(job.logPath, "utf8")); + const models = api.requests.slice(before).map((q: { model: string }) => q.model); + assert.ok(models.includes("claude-haiku-5-5"), models.join(",")); + assert.ok(!models.includes("claude-haiku-4-5"), "not the settings' extractor"); + const it = (await readIteration("synth-extractor", out.iteration, paths))!; + assert.ok(it.usage["claude-haiku-5-5"]!.calls === 1); }); test("the daily cap: a job that would start past the day's total is refused, naming it", async () => { @@ -186,3 +234,25 @@ test("a local narration: draft:local, a step on the iteration, ollama unloaded w const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text); }); + +test("a media draft (youtube, release 28 M6): a step on the done iteration, through the job, its field written", async () => { + // synth-basic i1 is done (the narration test above). + const r = await run("youtube"); + ol.push(...r.turns); + const out = await enqueueReportDraft({ task: "youtube", article: "synth-basic", iteration: 1, model: r.model, source }, deps()); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + assert.equal(out.iteration, 1); + assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local"); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8")); + const it = (await readIteration("synth-basic", 1, paths))!; + assert.equal(it.status, "done", "the iteration is left as it was"); + const step = it.steps.find((s) => s.task === "youtube")!; + assert.equal(step.status, "done"); + const m = JSON.parse(await readFile(path.join(projectOf(gen.projectsRoot, "synth-basic", 1), "video.manifest.json"), "utf8")); + assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery"); + assert.equal(m.drafted["publish.youtube"].task, "youtube"); + const notDone = await enqueueReportDraft({ task: "cut", article: "synth-basic", iteration: 9, model: "qwen3:8b", source }, deps()); + assert.match((notDone.result as { error: string }).error, /has no iteration i9/); +}); diff --git a/editor/app/api/ops/bench-verdicts/route.ts b/editor/app/api/ops/bench-verdicts/route.ts @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { BENCH_VERDICTS_BODY_KEYS, enqueueVerdictBench } from "yt-dlp-transcript-common/controller/benchVerdicts"; +import { jobResponse, ops } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { models, run?, reports?, window?, maxUsd?, limit? } +// -> { ok: true, jobId, run } +// +// The verdict bench (release 28 M7), as a `bench-verdicts` job: every ruled +// claim of the registry's fact-checks (or of `reports`) asked of each of +// `models`, one claim per call, scored against the operator's rulings. On +// `draft:local` when any model is local — every ollama call through the GPU +// arbiter, ollama unloaded at the end — else `draft:api`. `maxUsd` caps the +// whole run (default 5); an API run is refused past the day's cap. `run` +// names a run to continue (its answered pairs are skipped). The results are +// local-only: `.generation/bench/verdicts/<run>/` (umtool's /bench reads +// them). `job cancel` stops it; the log ends `@@bench-verdicts {json}`. +// +// AN ADAPTER: the refusals are the controller's (controller/benchVerdicts.ts). +export async function POST(request: Request) { + return ops(request, BENCH_VERDICTS_BODY_KEYS, async (body) => { + const out = await enqueueVerdictBench(body, { paths: getPaths() }); + if (!out.result.ok || !("run" in out)) return jobResponse(out.result); + void out.result.stream.cancel(); + return NextResponse.json({ ok: true, jobId: out.result.jobId, run: out.run }); + }); +} diff --git a/editor/app/api/ops/delete-site/route.ts b/editor/app/api/ops/delete-site/route.ts @@ -0,0 +1,51 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { isValidSiteId } from "yt-dlp-transcript-common/lib/siteSchema"; +import { + SiteDeleteRefusedError, + deleteSiteByPlan, + planSiteDelete, + siteDeleteBlocked, +} from "yt-dlp-transcript-common/publish/siteDelete"; +import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { id: string, force?: boolean, dryRun?: boolean } +// -> { ok, applied, plan, removed?, failed? } +// +// DELETE A SITE (release 28 H5), plan first: `sites/<id>/` (site.json, its +// pool and pages, tags, charts, reports), its publish state and last bundle +// (`export/.export-builds/<id>/`) and compose's staging for it +// (`export/.export-index/sites/<id>/`) — through publish/siteDelete.ts, +// under the site.json lock and the publish lock. Channel data is never +// touched; the Pages project, what was deployed and a deployed hub are kept +// (remote: a delete does not undeploy). `dryRun` answers the plan and writes +// nothing. Refused (409, with the plan): a site with a deploy target +// (`cloudflareProject`), a deploy in its publish state, or reports of its own +// — unless `force`; no such site, a site dir that is a link, or a publish +// stage running — force or not. +// +// There is no undo, and transcripts/ is its own git repo — the only way back +// for sites/<id>/ is a commit there. +export async function POST(request: Request) { + return ops(request, ["id", "force", "dryRun"], async (body) => { + const id = reqString(body, "id"); + if (!isValidSiteId(id)) throw new OpsInputError(`"${id}" is not a site id`); + const force = optBool(body, "force") === true; + const paths = getPaths(); + try { + const plan = await planSiteDelete(id, paths); + if (siteDeleteBlocked(plan, force)) { + const why = plan.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason); + return opsFail(`refused: ${why.join("; ")}`, plan.exists ? 409 : 404, { plan }); + } + if (optBool(body, "dryRun") === true) return NextResponse.json({ ok: true, applied: false, plan }); + const r = await deleteSiteByPlan(id, paths, { force }); + return NextResponse.json({ ok: r.failed.length === 0, applied: true, plan: r.plan, removed: r.removed, failed: r.failed }); + } catch (err) { + if (err instanceof SiteDeleteRefusedError) return opsFail(err.message, 409, { plan: err.plan }); + throw err; + } + }); +} diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -7,9 +7,9 @@ import { researchEditor } from "../_researchEditor"; export const dynamic = "force-dynamic"; -// POST { task, article, iteration?, model?, feedback?, question?, channels?, -// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force?, -// autonomy? } +// POST { task, article, iteration?, model?, extractorModel?, feedback?, +// question?, channels?, from?, to?, copyOf?, maxUsd?, source?, build?, +// cards?, entries?, force?, autonomy? } // -> { ok: true, jobId, iteration, warnings? } // // A generation over an article's iteration (release 27 S6), as a @@ -18,7 +18,11 @@ export const dynamic = "force-dynamic"; // `from`/`to`); the API model runs the agent, a local model the pipeline; // - "revise-report" / "revise-video": a new iteration revising `iteration` // from `feedback`; -// - "narrate": a step on the done iteration `iteration` (`cards`, `force`); +// - a media draft — "narrate", "cut", "onscreen", "teaser", "flips", +// "threads", "youtube" (release 28): a step on the done iteration +// `iteration` that drafts fields of its video manifest (`entries`: only +// these entry ids; `force`: re-draft a field that is a draft already — +// never one the operator wrote; narrate's `cards`); // - "research" (S11): a new research run from `question` (`channels` // optional, `autonomy` propose | limits | auto, default the settings'): // it discovers, proposes, and enqueues what its autonomy allows through @@ -28,7 +32,8 @@ export const dynamic = "force-dynamic"; // while N still waits, unless `force`); // - `copyOf` N: iteration N again on `model` (same kind and inputs). // `model` defaults to settings.generation's route for the task (a task routed -// to `code` needs one named). An API job's cap is `maxUsd`, else the task's +// 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 // default (settings.generation.caps), never above `caps.max`; a job that would // start past the day's API total (`caps.daily`) is refused, naming it. The // corpus is `source` (a handle), `build` (a composed build's id), or the newest diff --git a/editor/app/api/ops/research-approve/route.ts b/editor/app/api/ops/research-approve/route.ts @@ -19,9 +19,10 @@ export const dynamic = "force-dynamic"; // their doors and queues; `approve: false` rejects them (`note`: why); // - no `ids`: the run's state now (the umtool queue polls this). // `research` is {article, iteration, status, phase, autonomy, limits, spent, -// proposals, waitingOn: {approval, jobs}, continuedBy}. A run whose job is -// still going is refused. The CONTINUATION is report-draft {task: "sweep", -// iteration: <this run>}. +// proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}. A run +// whose job is still going is refused. The CONTINUATION is report-draft +// {task: "sweep", iteration: <this run>}; an `auto` run's is asked by the +// editor itself (release 28 F1, controller/researchAutoContinue.ts). // // AN ADAPTER: the rules are the controller's (controller/researchRuns.ts). export async function POST(request: Request) { diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx @@ -159,6 +159,9 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = { backfills: "Backfill", scans: "Metadata scan", clips: "Clip windows", + turns: "Model turns", + cards: "Cards", + entries: "Entries", }; // Per-metric glyph for the compact line ("↓ 5/10"). @@ -169,6 +172,9 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = { backfills: "\u21ba ", scans: "\u2315 ", clips: "\u2702 ", + turns: "\u21c4 ", + cards: "\u25a4 ", + entries: "\u2261 ", }; const METRIC_FILL: Record<JobProgressMetric, string> = { @@ -178,6 +184,9 @@ const METRIC_FILL: Record<JobProgressMetric, string> = { backfills: "bg-warning", scans: "bg-info/60", clips: "bg-success/60", + turns: "bg-info", + cards: "bg-success/60", + entries: "bg-success/60", }; // One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left" diff --git a/editor/app/scheduler/heartbeat.ts b/editor/app/scheduler/heartbeat.ts @@ -73,6 +73,18 @@ async function fire(generation: number): Promise<void> { // already records its own outcome; the heartbeat just keeps beating. } + // An `auto` research run whose acquisitions settled continues into its + // sweep (release 28 F1). A no-op unless instrumentation armed it (never on + // an idle boot). See common/controller/researchAutoContinue.ts. + try { + const { researchAutoContinueTick } = await import( + "yt-dlp-transcript-common/controller/researchAutoContinue" + ); + await researchAutoContinueTick(); + } catch { + // the scan records its own outcomes on the runs it reads + } + // Re-read the cadence each fire so a live settings change is honored without a // restart. If it has been turned off (0), the loop simply stops here. if (generation !== state.generation) return; diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts @@ -13,7 +13,6 @@ import { import { getSite, writeSite, - deleteSite, isValidSiteId, reservedSiteIdProblem, parseRelatedSites, @@ -30,6 +29,13 @@ import { resolveDefaultGroupId, } from "yt-dlp-transcript-common/lib/channelGroups"; import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites"; +import { + SiteDeleteRefusedError, + deleteSiteByPlan, + planSiteDelete, + siteDeleteBlocked, + type SiteDeletePlan, +} from "yt-dlp-transcript-common/publish/siteDelete"; import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks"; import { formValues, type FormState, type FormValues } from "../lib/formState"; import { reportSiteKeysFromForm } from "./lib/reportSiteKeys"; @@ -316,12 +322,41 @@ export async function saveSiteAction( export type DeleteResult = { ok: true } | { ok: false; error: string }; +export type SiteDeletePlanResult = { ok: true; plan: SiteDeletePlan } | { ok: false; error: string }; + +// Danger → Delete is plan-first (release 28 M9, through H5's +// publish/siteDelete.ts, as `pnpm ops delete-site`): the plan — what is +// removed (sites/<id>/, its publish state and bundle, compose's staging), what +// is kept, what refuses — then the delete. Read only. +export async function planSiteDeleteAction(siteId: string): Promise<SiteDeletePlanResult> { + try { + return { ok: true, plan: await planSiteDelete(siteId, getPaths()) }; + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } +} + +// The delete, its plan made again under the locks. `force` answers the +// forceable refusals only (a deploy target, a deploy on record, reports of its +// own); no site, a site dir that is a link and a publish stage running refuse +// whatever. export async function deleteSiteAction( siteId: string, -): Promise<DeleteResult> { + opts: { force?: boolean } = {}, +): Promise<DeleteResult & { plan?: SiteDeletePlan }> { + const force = opts.force === true; try { - await deleteSite(siteId, getPaths()); + const plan = await planSiteDelete(siteId, getPaths()); + if (siteDeleteBlocked(plan, force)) { + const why = plan.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason); + return { ok: false, error: `refused: ${why.join("; ")}`, plan }; + } + const r = await deleteSiteByPlan(siteId, getPaths(), { force }); + if (r.failed.length) { + return { ok: false, error: `not everything was removed: ${r.failed.map((f) => `${f.path} (${f.error})`).join("; ")}`, plan: r.plan }; + } } catch (err) { + if (err instanceof SiteDeleteRefusedError) return { ok: false, error: err.message, plan: err.plan }; return { ok: false, error: err instanceof Error ? err.message : String(err) }; } // No revalidatePath: the button refreshes the page itself (release 24 H5, diff --git a/editor/app/sites/components/SiteListActions.tsx b/editor/app/sites/components/SiteListActions.tsx @@ -2,32 +2,129 @@ import { useState, useTransition } from "react"; import { useRouter } from "next/navigation"; -import { deleteSiteAction, migrateToSitesAction } from "../actions"; +import { deleteSiteAction, migrateToSitesAction, planSiteDeleteAction } from "../actions"; +import type { SiteDeletePlan } from "yt-dlp-transcript-common/publish/siteDelete"; // Both actions save without revalidating and refresh the page here (release 24 // H5, lib/formState.ts seedAfterSave says why). + +const size = (n: number) => + n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`; + +// Danger → Delete, plan first (release 28 M9): Delete asks for the plan — +// what goes, what stays, what refuses — and nothing is removed until Confirm. +// A plan refused only for reasons force answers (a deploy target, a deploy on +// record, reports of its own) offers force behind its own confirmation; any +// other refusal offers nothing. export function DeleteSiteButton({ siteId }: { siteId: string }) { const router = useRouter(); const [pending, start] = useTransition(); const [error, setError] = useState<string | null>(null); + const [plan, setPlan] = useState<SiteDeletePlan | null>(null); + const [forceOk, setForceOk] = useState(false); + const blocked = (force: boolean) => !!plan && plan.refusals.some((r) => !force || !r.forceable); + const run = (force: boolean) => + start(async () => { + setError(null); + const res = await deleteSiteAction(siteId, { force }); + if (!res.ok) { + setError(res.error); + if (res.plan) setPlan(res.plan); + } else { + setPlan(null); + router.refresh(); + } + }); return ( - <span className="flex items-center gap-2"> - <button - type="button" - disabled={pending} - onClick={() => { - if (!confirm(`Delete site "${siteId}"? This cannot be undone.`)) return; - start(async () => { - const res = await deleteSiteAction(siteId); - if (!res.ok) setError(res.error); - else router.refresh(); - }); - }} - className="px-2 py-1 rounded border border-destructive/30 text-xs text-destructive disabled:opacity-50" - > - {pending ? "Deleting…" : "Delete"} - </button> - {error && <span className="text-xs text-destructive">{error}</span>} + <span className="flex flex-col items-end gap-2"> + <span className="flex items-center gap-2"> + <button + type="button" + disabled={pending} + aria-expanded={!!plan} + onClick={() => + start(async () => { + setError(null); + setForceOk(false); + const res = await planSiteDeleteAction(siteId); + if (res.ok) setPlan(res.plan); + else setError(res.error); + }) + } + className="px-2 py-1 rounded border border-destructive/30 text-xs text-destructive disabled:opacity-50" + > + {pending && !plan ? "Planning…" : "Delete"} + </button> + {error && <span className="text-xs text-destructive">{error}</span>} + </span> + {plan && ( + <div + role="region" + aria-label={`delete site ${siteId}`} + data-site-delete-plan={siteId} + className="w-full max-w-xl rounded border border-destructive/40 bg-destructive/5 p-3 text-xs" + > + <p className="font-medium" data-plan-summary=""> + Delete site <code>{siteId}</code>: {plan.remove.length} path{plan.remove.length === 1 ? "" : "s"}, {size(plan.bytes)} in {plan.files} file + {plan.files === 1 ? "" : "s"} + </p> + {plan.refusals.length > 0 && ( + <ul className="mt-1 list-disc pl-4 text-destructive" aria-label="refusals"> + {plan.refusals.map((r) => ( + <li key={r.reason} data-refusal={r.forceable ? "forceable" : "final"}> + {r.reason} + {r.forceable ? " (force answers it)" : " (force does not)"} + </li> + ))} + </ul> + )} + <ul className="mt-1 list-disc pl-4" aria-label="removed"> + {plan.remove.map((e) => ( + <li key={e.path} data-remove={e.label}> + <code>{e.label}</code> — {e.what}, {e.kind === "link" ? "a link" : `${size(e.bytes)} in ${e.files} file${e.files === 1 ? "" : "s"}`} + </li> + ))} + </ul> + <ul className="mt-1 list-disc pl-4 text-muted-foreground" aria-label="kept"> + {plan.kept.map((k) => ( + <li key={k.what}> + keeps {k.what}: {k.why} + </li> + ))} + </ul> + <div className="mt-2 flex flex-wrap items-center gap-2"> + {!blocked(false) && ( + <button + type="button" + disabled={pending} + onClick={() => run(false)} + className="px-2 py-1 rounded bg-destructive text-white disabled:opacity-50" + > + {pending ? "Deleting…" : "Confirm delete"} + </button> + )} + {blocked(false) && !blocked(true) && ( + <> + <label className="flex items-center gap-1"> + <input type="checkbox" checked={forceOk} onChange={(e) => setForceOk(e.target.checked)} /> + I understand: the refusals above are overridden, and nothing deployed is undeployed + </label> + <button + type="button" + disabled={pending || !forceOk} + onClick={() => run(true)} + className="px-2 py-1 rounded bg-destructive text-white disabled:opacity-50" + > + {pending ? "Deleting…" : "Delete with force"} + </button> + </> + )} + <button type="button" disabled={pending} onClick={() => setPlan(null)} className="px-2 py-1 rounded border border-border"> + Cancel + </button> + </div> + </div> + )} </span> ); } diff --git a/editor/e2e/backfill.spec.ts b/editor/e2e/backfill.spec.ts @@ -512,9 +512,22 @@ test("a lane can be scoped to one operation from its console, and the scope is a ) .toEqual({ enabled: true, operations: ["diarization"] }); - // Switch it back off so an armed lane does not bleed into the next spec. - await lane.getByLabel("Enable auto-backfill").uncheck(); + // Switch it back off so an armed lane does not bleed into the next spec — + // once the first save has SETTLED on the page (its "Saved.", the button + // back, nothing unsaved). Unchecking while it was still settling was the + // release 28 flake: the form could adopt the saved copy after the uncheck, + // and the second save then wrote the lane on again. + const enable = lane.getByLabel("Enable auto-backfill"); + await expect(lane.getByRole("status")).toHaveText("Saved."); + await expect(lane.getByRole("button", { name: "Save policy" })).toBeEnabled(); + await expect(lane.getByText("Unsaved changes")).toHaveCount(0); + await expect(enable).toBeChecked(); + await enable.uncheck(); + await expect(enable).not.toBeChecked(); + await expect(lane.getByText("Unsaved changes")).toBeVisible(); await lane.getByRole("button", { name: "Save policy" }).click(); + await expect(lane.getByRole("button", { name: "Save policy" })).toBeEnabled(); + await expect(lane.getByText("Unsaved changes")).toHaveCount(0); await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false); }); diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -1,11 +1,11 @@ import { test, expect, type APIRequestContext } from "@playwright/test"; -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; // By relative path, as digest.spec.ts imports common: the test kit's fakes and // the synthetic corpus are plain .mjs. -import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; +import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; import { ORIGIN, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; import { baseUrl } from "./baseUrl"; import { resetData, testPaths, writeSettings } from "./helpers"; @@ -95,6 +95,8 @@ test("a sweep draft: enqueued over ops, followed to done, its iteration read bac expect(body.iteration).toBe(1); const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); + // The job's progress (release 28 F3): the agent's model turns, against its turn cap. + expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "turns", initial: 0, current: 6, target: 150 }); const it = await iterationJson("synth-e2e", 1); expect(it.status).toBe("done"); expect(it.jobId).toBe(body.jobId); @@ -155,3 +157,44 @@ test("the daily cap: a job that would start past the day's API total is refused, expect(body.error).toContain("$4.00 daily cap"); await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-daily", "iterations", "1", "iteration.json"))).rejects.toThrow(/ENOENT/); }); + +test("a media draft (release 28 M3): a teaser on the API, a step on the done iteration, checked by the build's own validator loaded in the editor", async ({ request }) => { + test.setTimeout(120_000); + await setup(); + // A done sweep iteration whose project holds the kit's basic cut and report. + const kit = join(RUNS, ".."); + const article = "synth-teaser"; + const project = join(keyDir, "projects", article, "i1"); + const report = JSON.parse(await readFile(join(kit, "reports", "basic.report.json"), "utf8")); + const itDir = join(testPaths().transcriptsDir, "reports", article, "iterations", "1"); + await mkdir(itDir, { recursive: true }); + await mkdir(project, { recursive: true }); + const at = new Date().toISOString(); + await writeFile( + join(itDir, "iteration.json"), + JSON.stringify({ + format: "archilyzer-iteration", version: 1, article, n: 1, kind: "sweep", parent: null, copyOf: null, model: "claude-sonnet-5-5", + question: "q", scope: { channels: ["synth-kitchen"] }, status: "done", usage: {}, steps: [], projectDir: project, createdAt: at, updatedAt: at, endedAt: at, + }), + ); + await writeFile(join(itDir, "report.json"), JSON.stringify(report)); + await writeFile(join(project, "report.json"), JSON.stringify(report)); + await writeFile(join(project, "video.manifest.json"), await readFile(join(kit, "manifests", "basic.video.manifest.json"), "utf8")); + api.push(toolTurn("answer", { lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] })); + const { status, body } = await draft(request, { task: "teaser", article, iteration: 1, model: "claude-sonnet-5-5" }); + expect(status, body.error).toBe(200); + expect(body.iteration).toBe(1); + const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); + expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); + expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "entries", initial: 0, current: 1, target: 1 }); + const it = await iterationJson(article, 1); + expect(it.steps.find((s: { task: string }) => s.task === "teaser")).toMatchObject({ status: "done", jobId: body.jobId }); + const m = JSON.parse(await readFile(join(project, "video.manifest.json"), "utf8")); + expect(m.timeline.at(-1)).toMatchObject({ type: "teaser", id: "teaser", lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] }); + expect(m.timeline.at(-1).drafted.lines).toMatchObject({ task: "teaser", model: "claude-sonnet-5-5", iteration: 1, attempt: 1 }); + // The editor ran the build's validateTeaser (a teaser it cannot check is not written). + const draftFile = JSON.parse(await readFile(join(project, "teaser-draft.json"), "utf8")); + expect(draftFile.units.teaser.applied).toBe("applied"); + expect(api.remaining()).toBe(0); +}); + diff --git a/editor/e2e/site-delete.spec.ts b/editor/e2e/site-delete.spec.ts @@ -0,0 +1,63 @@ +import { test, expect } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { pathExists, resetData, testPaths, writeSite } from "./helpers"; + +// Danger → Delete on /sites, plan first (release 28 M9, through H5's +// publish/siteDelete.ts): Delete shows what goes (sites/<id>/, its publish +// state and bundle, compose's staging), what stays and what refuses; nothing +// is removed until Confirm. A site with a deploy target is refused unless +// forced, and force has its own confirmation. Temp sites in the fixture +// corpus only. + +const sitesDir = () => join(testPaths().transcriptsDir, "sites"); + +test("Delete shows the plan; Cancel removes nothing; Confirm removes the site and its build state", async ({ page }) => { + await resetData("empty"); + await writeSite("scratch", { siteTitle: "Scratch Site" }); + // Its build state, as a publish leaves it. + const builds = join(testPaths().transcriptsDir, ".export-builds", "scratch"); + await mkdir(join(builds, "out"), { recursive: true }); + await writeFile(join(builds, "out", "index.html"), "<p>scratch</p>"); + await writeFile(join(builds, "built.json"), "{}"); + + await page.goto("/sites"); + const row = page.getByRole("listitem").filter({ hasText: "Scratch Site" }); + await row.getByRole("button", { name: /^delete$/i }).click(); + const plan = page.getByRole("region", { name: "delete site scratch" }); + await expect(plan).toBeVisible(); + await expect(plan.locator("[data-plan-summary]")).toContainText("Delete site scratch: 2 paths"); + await expect(plan.locator("[data-remove='sites/scratch/']")).toBeVisible(); + await expect(plan.locator("[data-remove='export/.export-builds/scratch/']")).toContainText("2 files"); + await expect(plan.getByRole("list", { name: "kept" })).toContainText("every channel's data"); + await expect(plan.locator("[data-refusal]")).toHaveCount(0); + + await plan.getByRole("button", { name: "Cancel" }).click(); + await expect(plan).toHaveCount(0); + expect(await pathExists(join(sitesDir(), "scratch", "site.json"))).toBe(true); + + await row.getByRole("button", { name: /^delete$/i }).click(); + await page.getByRole("region", { name: "delete site scratch" }).getByRole("button", { name: "Confirm delete" }).click(); + await expect(page.getByRole("link", { name: /Scratch Site/ })).toHaveCount(0); + expect(await pathExists(join(sitesDir(), "scratch"))).toBe(false); + expect(await pathExists(builds)).toBe(false); +}); + +test("a site with a deploy target is refused; force, behind its own confirmation, deletes it", async ({ page }) => { + await resetData("empty"); + await writeSite("deployed", { siteTitle: "Deployed Site", cloudflareProject: "deployed-pages" }); + + await page.goto("/sites"); + const row = page.getByRole("listitem").filter({ hasText: "Deployed Site" }); + await row.getByRole("button", { name: /^delete$/i }).click(); + const plan = page.getByRole("region", { name: "delete site deployed" }); + await expect(plan.locator("[data-refusal='forceable']")).toContainText('it deploys to the Cloudflare Pages project "deployed-pages" (force answers it)'); + await expect(plan.getByRole("list", { name: "kept" })).toContainText('the Pages project "deployed-pages"'); + await expect(plan.getByRole("button", { name: "Confirm delete" })).toHaveCount(0); + const force = plan.getByRole("button", { name: "Delete with force" }); + await expect(force).toBeDisabled(); + await plan.getByRole("checkbox", { name: /I understand/ }).check(); + await force.click(); + await expect(page.getByRole("link", { name: /Deployed Site/ })).toHaveCount(0); + expect(await pathExists(join(sitesDir(), "deployed"))).toBe(false); +}); diff --git a/editor/e2e/sites-crud.spec.ts b/editor/e2e/sites-crud.spec.ts @@ -128,8 +128,9 @@ test("delete removes the site config", async ({ page }) => { await writeSite("doomed", { siteTitle: "Doomed" }); await page.goto("/sites"); - page.once("dialog", (d) => d.accept()); - await page.getByRole("button", { name: /delete/i }).click(); + // Plan first (release 28 M9): nothing goes until Confirm. + await page.getByRole("button", { name: /^delete$/i }).click(); + await page.getByRole("region", { name: "delete site doomed" }).getByRole("button", { name: "Confirm delete" }).click(); await expect(page.getByText("Doomed")).toHaveCount(0); expect(await pathExists(`${testPaths().transcriptsDir}/sites/doomed/site.json`)).toBe( diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -236,6 +236,17 @@ export async function register() { /* a runner that fails to start must not block server readiness */ } + // AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end + // listener and one scan of the research runs now; the heartbeat scans again + // on each beat. Below the idle gate: a continuation is a generation job. + // See common/controller/researchAutoContinue.ts. + try { + const { armAutoContinue } = await import("./app/api/ops/_autoContinue"); + armAutoContinue(); + } catch { + /* auto-continue that fails to arm must not block server readiness */ + } + // NO SECOND RESUME HOOK. There used to be two more here, one per sweep, and // each re-launched a corpus-wide pass from its own persisted flag. Both lanes // are runner lanes now, so `startAutoRunnersIfEnabled` above resumes all four diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -22,6 +22,7 @@ import { projectOf, } from "yt-dlp-transcript-common/lib/report/iterations"; import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; +import type { TaskProgress } from "yt-dlp-transcript-common/lib/report/draft/tasks/types"; import { createCorpusTools, type CorpusTools } from "./callTool"; const RUNS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft/runs"); @@ -61,8 +62,9 @@ beforeEach(async () => { const postText = async (channel: string, id: string) => POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null; -function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[] } { +function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[]; progressed: TaskProgress[] } { const lines: string[] = []; + const progressed: TaskProgress[] = []; return { llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, @@ -74,6 +76,8 @@ function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[] } { paths, log: (l) => lines.push(l), lines, + progress: (p) => progressed.push(p), + progressed, ...extra, }; } @@ -147,6 +151,9 @@ test("sweep-agent: the plan, the corpus tools, extract_batch, the report file; t const turns = (await readIterationFile("synth-contest", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); assert.ok(turns.some((t) => t.kind === "tool" && t.name === "extract_batch")); assert.ok(turns.some((t) => t.kind === "note" && t.text === "repair round")); + // The job's progress: every model turn, the repair round's counted on (release 28 F3). + assert.deepEqual(d.progressed.map((p) => p.current), [1, 2, 3, 4, 5, 6]); + assert.ok(d.progressed.every((p) => p.metric === "turns" && p.total === 150)); }); test("sweep-agent: a quote the repair round does not fix is dropped, and the iteration is still done", async () => { @@ -162,6 +169,30 @@ test("sweep-agent: a quote the repair round does not fix is dropped, and the ite assert.match(after.checks!.find((c) => c.name === "quotes")!.detail!, /1 finding\(s\) dropped/); }); +test("sweep-agent: a fragment quote goes to the repair round with its full sentence, and the fix is kept (release 28 Q2)", async () => { + const r = await run("sweep-agent"); + const turns = structuredClone(r.turns); + const write = turns[3].content[0].input; + write.markdown = write.markdown.replace("the judges were friends of mine so it felt right", "the judges were friends of"); + turns[5] = { + content: [{ type: "tool_use", id: "toolu_f04", name: "edit_report", input: { old_text: 'friends of"', new_text: 'friends of mine so it felt wrong"' } }], + stop_reason: "tool_use", + }; + api.push(...turns); + const it = await createIteration("synth-frag", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-agent", article: "synth-frag", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const first = api.requests.at(-7); + assert.match(first.system[0].text, /Quote a whole sentence or clause/); + const repair = api.requests.at(-2); + assert.match(repair.messages[0].content, /a fragment \(ends on “of”\): "the judges were friends of" — quote the whole sentence: "the judges were friends of mine so it felt wrong"/); + const md = (await readIterationFile("synth-frag", it.n, "sweep.md", paths))!; + assert.ok(md.includes('"the judges were friends of mine so it felt wrong"')); + const after = (await readIteration("synth-frag", it.n, paths))!; + assert.deepEqual(after.checks?.map((c) => [c.name, c.ok]), [["convert", true], ["quotes", true]]); +}); + test("sweep-agent: the repair round has its own small allowance", async () => { const r = await run("sweep-agent"); // The repair round's first turn costs more than the allowance: it stops there. @@ -222,6 +253,8 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d assert.ok(md.includes(`${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10`)); assert.ok(!md.includes("I entered the contest and I won"), "the invented quote never made it"); assert.match(md, /## Coverage\n\nSearched synth-kitchen for contest, judges\. 1 video\(s\) matched; 1 read/); + // The job's progress: the recordings gone through, of the worklist (release 28 F3). + assert.deepEqual(d.progressed, [{ metric: "entries", current: 0, total: 1 }, { metric: "entries", current: 1, total: 1 }]); const report = JSON.parse((await readIterationFile("synth-pipe", it.n, "report.json", paths))!); assert.equal(Object.keys(report.citations).length, 2); const turns = (await readIterationFile("synth-pipe", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); @@ -303,8 +336,9 @@ test("narrate: a step on a done iteration; a quote read out is re-asked; the man assert.equal(revisions.length, 1); assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/); const draft = JSON.parse(await readFile(path.join(projectDir!, "narration-draft.json"), "utf8")); - assert.equal(draft["the-bakery"].attempts.length, 2); - assert.match(draft["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/); + assert.equal(draft.units["the-bakery"].attempts.length, 2); + assert.match(draft.units["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/); + assert.equal(cards["the-bakery"].drafted.narration.task, "narrate", "a narration it writes carries its drafted mark"); // The prompts carry rules, never worked examples, and no tag rule. const sys = ol.requests.at(-1).messages[0].content as string; assert.ok(!sys.includes("One file. No title."), "no worked example"); @@ -330,24 +364,200 @@ test("a task refuses an iteration that is not its own or not queued", async () = assert.ok(CHANNELS.length > 0); }); -test("revise-report on a local model that never calls apply_ops: one schema-bound ask for the batch, then the check says so", async () => { +test("revise-report on a local model: no tool loop — one schema-bound ask for the batch; nothing proposed is a failing check", async () => { await drainFake(); await doneSweep("synth-basic", "basic"); const it = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - // read_doc, then an empty answer (no tool call); then the ask answers with the batch. - ol.push(toolCallsReply([{ name: "read_doc", arguments: {} }]), reply(""), jsonReply({ ops: [{ op: "drop", n: 3 }] })); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 3 }] })); const d = deps(); const out = await runTask({ task: "revise-report", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one call"); + assert.deepEqual(d.progressed, [{ metric: "turns", current: 1, total: 1 }]); + const req = ol.requests.at(-1); + assert.ok(req.format, "schema-bound"); + assert.ok(!req.tools, "no tools"); + assert.ok(!/apply_ops|read_doc/.test(req.messages[0].content), "the local rules name no tools"); const after = (await readIteration("synth-basic", it.n, paths))!; assert.deepEqual((after.ops!.applied as { op: string }[]).map((o) => o.op), ["drop"]); assert.ok(after.checks!.some((c) => c.name === "ops" && c.ok)); assert.ok(!(await readIterationFile("synth-basic", it.n, "sweep.md", paths))!.includes("new mixer")); - // A model that proposes nothing even then: done, with a failing ops check. + // A model that proposes nothing: done, with a failing ops check. const it2 = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - ol.push(reply(""), jsonReply({ ops: [] })); + ol.push(jsonReply({ ops: [] })); await runTask({ task: "revise-report", article: "synth-basic", n: it2.n, origin: ORIGIN, maxUsd: 1 }, deps()); const after2 = (await readIteration("synth-basic", it2.n, paths))!; assert.ok(after2.checks!.some((c) => c.name === "ops" && !c.ok && /no edits/.test(String(c.detail)))); }); + +test("revise-report on a local model: a large report's view fits the 8k cap — the named section in it, one ops call, the numbers the document's", async () => { + await drainFake(); + await createIteration("synth-big", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const basic = JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")); + await writeIterationFile("synth-big", 1, "report.json", { ...basic, id: "synth-big" }, paths); + await updateIteration("synth-big", 1, { status: "done" }, paths); + // 40 sections of 6 findings over real corpus moments: ~45k characters, far past the cap. + const lines = ["# A large report", "", "The summary.", ""]; + const moments = [ + ["bread-day-01", 15, "I would never sell the bakery to a chain"], + ["bread-day-01", 45, "I paid for the new mixer myself"], + ["pie-stream-02", 10, "I did not enter the contest this year"], + ["pie-stream-02", 30, "I have never met the other finalist"], + ["pie-stream-02", 40, "my lawyer told me not to talk about the lease"], + ["bread-day-01", 30, "the oven was fine it just ran hot"], + ] as const; + let n = 0; + for (let s = 1; s <= 40; s++) { + lines.push(`## Topic ${s}`, ""); + for (const [id, t, q] of moments) { + n++; + lines.push(`- Finding number ${n} says something about topic ${s} at some length, to fill the view: "${q}" [${id} @ 0:${t}](${ORIGIN}/?v=synth-kitchen%2F${id}&t=${t})`); + } + lines.push(""); + } + const big = lines.join("\n"); + assert.ok(big.length > 40_000, String(big.length)); + await writeIterationFile("synth-big", 1, "sweep.md", big, paths); + const it = await createIteration("synth-big", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "In Topic 37, drop finding 220." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 220 }] })); + const d = deps(); + const out = await runTask({ task: "revise-report", article: "synth-big", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one ops call, sent (not refused by the cap)"); + const req = ol.requests.at(-1); + assert.ok(Math.ceil(JSON.stringify([req.messages, null, req.format]).length / 3.5) <= 8000, "under the client's 8k estimate"); + const user = req.messages[1].content as string; + assert.match(user, /## Topic 37\n\[217\] Finding number 217/, "the named section, in full"); + assert.ok(user.includes("[220] Finding number 220")); + assert.match(user, /not shown/, "what is left out is said"); + assert.ok(!user.includes(`${ORIGIN}/?v=`), "links cut to their labels in the view"); + const md = (await readIterationFile("synth-big", it.n, "sweep.md", paths))!; + assert.ok(!md.includes("Finding number 220 "), "the op numbered against the whole document"); + assert.ok(md.includes("Finding number 219 ") && md.includes("Finding number 221 ")); + assert.ok(md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=40)`), "links whole in the report"); +}); + +test("revise-video on a local model: one ops batch over the trimmed cut", async () => { + await drainFake(); + await doneSweep("synth-basic", "basic", { manifest: true }); + const it = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Rename the-bakery to About the bakery." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "heading", id: "the-bakery", text: "About the bakery" }] })); + const out = await runTask({ task: "revise-video", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps()); + assert.equal(out.status, "done", out.summary); + assert.equal(ol.requests.length - before, 1); + const req = ol.requests.at(-1); + assert.ok(req.format && !req.tools); + assert.match(req.messages[1].content, /- card the-bakery \(chapter\) heading: "The bakery"/); + assert.match(req.messages[1].content, /REPORT CITATIONS \(add_clip takes these ids\):\nc01: synth-kitchen\/bread-day-01/); + const m = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", it.n), "video.manifest.json"), "utf8")); + assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery"); +}); + +test("revise-video: ops that change the cut's order mark it a draft of revise-video; ops that do not keep the parent's mark (release 28 M9 ruling)", async () => { + await drainFake(); + await doneSweep("synth-basic", "basic", { manifest: true }); + const parentMark = JSON.parse(await readFile(path.join(DRAFT, "manifests", "basic.video.manifest.json"), "utf8")).drafted?.timeline; + // A move: the order changes. + const moved = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Put c03 first." }, paths); + ol.push(jsonReply({ ops: [{ op: "move", id: "c03", after: "title" }] })); + const a = await runTask({ task: "revise-video", article: "synth-basic", n: moved.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps()); + assert.equal(a.status, "done", a.summary); + const ma = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", moved.n), "video.manifest.json"), "utf8")); + assert.equal(ma.timeline[1].id, "c03"); + assert.deepEqual( + { task: ma.drafted.timeline.task, model: ma.drafted.timeline.model, iteration: ma.drafted.timeline.iteration, attempt: ma.drafted.timeline.attempt }, + { task: "revise-video", model: "qwen3:8b", iteration: moved.n, attempt: 1 }, + ); + // A heading only: the order is the parent's, and so is its mark. + const renamed = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Rename the-bakery." }, paths); + ol.push(jsonReply({ ops: [{ op: "heading", id: "the-bakery", text: "About the bakery" }] })); + const b = await runTask({ task: "revise-video", article: "synth-basic", n: renamed.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps()); + assert.equal(b.status, "done", b.summary); + const mb = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", renamed.n), "video.manifest.json"), "utf8")); + assert.deepEqual(mb.drafted?.timeline, parentMark); +}); + +// ─── release 28 M4–M6: flips, threads, youtube (lane E) ─── + +// i1 done with the basic report and the FULL manifest with its threads taken +// off: an on-screen deck with no left panel, seven clips over three recordings. +async function deckCut(article = "synth-basic") { + const { projectDir } = await doneSweep(article, "basic", { manifest: true }); + const m = JSON.parse(await readFile(path.join(DRAFT, "manifests", "full.video.manifest.json"), "utf8")); + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + await writeFile(path.join(projectDir!, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + return projectDir!; +} + +const manifestOf = async (dir: string) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + +test("flips: the pairs are code's — dates from the records, THEN before NOW, the quotes verbatim; the S0 flips shape (release 28 M4)", async () => { + await drainFake(); + const r = await run("flips"); + ol.push(...r.turns); + const dir = await deckCut(); + const d = deps(); + const out = await runTask({ task: "flips", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(dir); + const expected = JSON.parse(await readFile(path.join(DRAFT, "manifests", "flips.video.manifest.json"), "utf8")).render.chrome.flips; + const strip = (f: { pairs: { id: string }[] }) => f.pairs.map(({ id: _id, ...p }) => p); + assert.deepEqual(strip(m.render.chrome.flips), strip(expected), "one pair, c01 Jan 2026 → c07 Mar 2026, the quotes word for word"); + assert.equal(m.drafted["render.chrome.flips"].task, "flips"); + assert.equal(m.drafted["render.chrome.flips"].attempt, 2); + const draft = JSON.parse(await readFile(path.join(dir, "flips-draft.json"), "utf8")); + const first = draft.units.flips.attempts[0].hard.join(" | "); + assert.match(first, /c04 and c05 are of the same day \(2026-02-10\)/); + assert.match(first, /number 2027 is not in the report/); + // The dates came from the corpus records: the prompt shows them, the clips carry none. + const user = ol.requests.at(-1).messages[1].content as string; + assert.match(user, /- c01 \[2026-01-05\] \(chapter: The bakery\): "I would never sell the bakery to a chain"/); + assert.match(user, /- c07 \[2026-03-01\]/); + const step = (await readIteration("synth-basic", 1, paths))!.steps.find((s) => s.task === "flips")!; + assert.equal(step.status, "done"); +}); + +test("threads: 2 to 4 threads, every clip's thread set, the outcomes from the manifest's verdicts (release 28 M5)", async () => { + await drainFake(); + const r = await run("threads"); + ol.push(...r.turns); + const dir = await deckCut(); + const d = deps(); + const out = await runTask({ task: "threads", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(dir); + assert.deepEqual(m.render.chrome.threads.list, [ + { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } }, + { id: "contest", label: "The contest", outcome: { verdict: "NOT_FOUND" } }, + ]); + const byId = Object.fromEntries(m.timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string; thread?: string }) => [e.id, e.thread])); + assert.deepEqual(byId, { c01: "bakery", c02: "bakery", c03: "bakery", c04: "contest", c05: "contest", c06: "contest", c07: "bakery" }); + assert.equal(m.drafted["render.chrome.threads"].task, "threads"); + const draft = JSON.parse(await readFile(path.join(dir, "threads-draft.json"), "utf8")); + const first = draft.units.threads.attempts[0].hard.join(" | "); + assert.match(first, /name “Gordon” is not in the report/); + assert.match(first, /thread 3 \(gordon\) has no clip/); +}); + +test("youtube: the title and one summary paragraph, grounded and third person (release 28 M6)", async () => { + await drainFake(); + const r = await run("youtube"); + ol.push(...r.turns); + const { projectDir } = await doneSweep("synth-basic", "basic", { manifest: true }); + const d = deps(); + const out = await runTask({ task: "youtube", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(projectDir!); + assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery"); + assert.match(m.publish.youtube.description, /^Synth Kitchen's baker says "I would never sell the bakery to a chain"/); + assert.equal(m.drafted["publish.youtube"].task, "youtube"); + const draft = JSON.parse(await readFile(path.join(projectDir!, "youtube-draft.json"), "utf8")); + const first = draft.units.youtube.attempts[0].hard.join(" | "); + assert.match(first, /the summary: the narrator is third person \(“us”\)/); + assert.match(first, /no links, timestamps, chapters or hashtags/); +}); diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; +import { GENERATION_PRESETS, sanitizeGeneration } from "yt-dlp-transcript-common/lib/generationSettings"; import { GENERATE_POLL_MS, GENERATE_TASKS, @@ -34,7 +35,7 @@ type Sent = { url: string; method: string; body?: unknown }; // An editor that serves the policy, the day's usage, a report-draft POST, a // job that runs for `runPolls` polls and then ends `end`, and the iteration. -function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean } = {}) { +function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string } = {}) { let policy = { ...POLICY, ...(opts.policy ?? {}) }; let polls = 0; const runPolls = opts.runPolls ?? 0; @@ -55,19 +56,14 @@ function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end steps: [], ...(opts.iteration ?? {}), }; - const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; + const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: opts.task ?? "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; const fake = fakeEditor((s) => { const u = new URL(s.url); if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } }; if (u.pathname === "/api/ops/settings" && s.method === "POST") { const routes = (s.body as { patch: { generation: { routes: Record<string, string> } } }).patch.generation.routes; - const presets: Record<string, string> = { - "code,code,code,code,code": "code", - "api,api,api,api,api": "api", - "local,local,local,local,local": "local", - "code,api,local,local,api": "balanced", - }; - policy = { ...policy, routes: routes as typeof policy.routes, preset: presets[Object.values(routes).join(",")] ?? "custom" }; + // The editor's own sanitizer names the preset the routes are. + policy = { ...policy, routes: routes as typeof policy.routes, preset: sanitizeGeneration({ routes }).preset }; return { status: 200, body: { ok: true, changed: ["generation"], value: { generation: policy } } }; } if (u.pathname === "/api/ops/generation-usage") return { status: 200, body: { ok: true, day: "2026-10-13", usd: 1.75, jobs: 2, daily: 20 } }; @@ -130,7 +126,24 @@ test("generation_policy sets a preset as its routes, and one route alone", async assert.equal(a.isError, undefined, a.text); const post = e.sentOf("/api/ops/settings").find((s) => s.method === "POST")!; assert.deepEqual(post.body, { - patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, + patch: { + generation: { + routes: { + sweep: "api", + "revise-report": "api", + "revise-video": "api", + narrate: "api", + research: "api", + // The media drafts (release 28) take narrate's route in every preset. + cut: "api", + onscreen: "api", + teaser: "api", + flips: "api", + threads: "api", + youtube: "api", + }, + }, + }, }); assert.match(a.text, /^Set preset api\./); assert.match(a.text, /preset \*\*api\*\*/); @@ -139,7 +152,7 @@ test("generation_policy sets a preset as its routes, and one route alone", async const post2 = e.sentOf("/api/ops/settings").filter((s) => s.method === "POST")[1]; // The whole routes object (the writer merges one level; a nested object replaces). assert.deepEqual(post2.body, { - patch: { generation: { routes: { sweep: "local", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, + patch: { generation: { routes: { ...GENERATION_PRESETS.api, sweep: "local" } } }, }); assert.match(one.text, /^Routed sweep to local\./); assert.match(one.text, /preset \*\*custom\*\*/); @@ -158,8 +171,8 @@ test("generation_policy refuses a muddle before it asks the editor", async () => assert.match(a.text, re); } assert.equal(e.sent.length, 0); - const unknown = await generationPolicyTool({ task: "teaser", route: "api" }, e.deps as never); - assert.match(unknown.text, /no task "teaser" — the policy routes sweep, revise-report, revise-video, narrate, research/); + const unknown = await generationPolicyTool({ task: "nope", route: "api" }, e.deps as never); + assert.match(unknown.text, /no task "nope" — the policy routes sweep, revise-report, revise-video, narrate, research/); assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); const none = await generationPolicyTool({}, fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never); assert.equal(none.isError, true); @@ -258,8 +271,18 @@ test("generate: the arguments are checked before any request; research is a task assert.ok(GENERATE_TASKS.includes("research")); const ok = validateGenerateArgs({ task: "research", article: "synth-a", question: "what was said?", channels: ["synth-kitchen"] }); assert.equal(ok.ok, true); + // A sweep's extractor, per job (release 28 F2), passed through as the editor's key. + const ex = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], extractorModel: " claude-haiku-5-5 " }); + assert.ok(ex.ok && ex.request.kind === "start"); + if (ex.ok && ex.request.kind === "start") assert.equal(ex.request.body.extractorModel, "claude-haiku-5-5"); for (const [args, re] of [ - [{ task: "teaser", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research/], + [{ task: "nope", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research, cut, onscreen, teaser, flips, threads, youtube/], + [{ task: "cut", article: "a", iteration: 1, entries: [] }, /entries is a non-empty list/], + // The media drafts (release 28): a step on the iteration it names. + [{ task: "onscreen", article: "a" }, /a onscreen draft names the iteration it drafts on/], + [{ task: "teaser", article: "a", iteration: 1, copyOf: 1 }, /a teaser draft is a step on its iteration: it has no copyOf/], + [{ task: "youtube", article: "a", iteration: 1, feedback: "shorter" }, /feedback is not a youtube draft's/], + [{ task: "sweep", article: "a", question: "q", channels: ["c"], entries: ["c01"] }, /entries is a media draft's/], [{ task: "sweep", article: "Not An Id" }, /article is an article id/], [{ task: "sweep", article: "a", channels: [] }, /channels is a non-empty list/], [{ task: "sweep", article: "a", iteration: 0 }, /iteration is an iteration number/], @@ -268,6 +291,8 @@ test("generate: the arguments are checked before any request; research is a task [{ task: "sweep", article: "a", via: "api", model: "x" }, /model or via, not both/], [{ task: "sweep", article: "a", wait_seconds: -2 }, /wait_seconds/], [{ job: "../etc" }, /is not a job id/], + [{ task: "revise-report", article: "a", iteration: 1, feedback: "f", extractorModel: "claude-haiku-4-5" }, /extractorModel is a sweep's/], + [{ task: "sweep", article: "a", extractorModel: "qwen3:8b" }, /extractorModel is a Claude model id/], ] as const) { const v = validateGenerateArgs(args as Record<string, unknown>); assert.equal(v.ok, false, JSON.stringify(args)); @@ -275,6 +300,41 @@ test("generate: the arguments are checked before any request; research is a task } }); +test("generate: a media draft is a step on its iteration, routed like any task; done, the review is the operator's in umtool", async () => { + for (const task of ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]) { + assert.ok(GENERATE_TASKS.includes(task), task); + const v = validateGenerateArgs({ task, article: "synth-a", iteration: 3, entries: ["c01"], force: true }); + assert.equal(v.ok, true, task); + } + // Routed by the policy: the editor runs it on the route's model. + const e = editor({ + task: "onscreen", + policy: { routes: { ...POLICY.routes, onscreen: "local" } }, + iteration: { + kind: "sweep", + ops: undefined, + checks: [{ name: "onscreen", ok: false, detail: "3 title(s) written, 1 not written (a hard check)" }], + steps: [{ task: "onscreen", model: "qwen3:8b", status: "done", jobId: "job-1", detail: "3 title(s) written" }], + projectDir: "/srv/projects/synth-a/i3", + }, + }); + const a = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"], wait: true }, e.deps as never); + assert.ok(!a.isError, a.text); + assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"] }); + const queued = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3 }, e.deps as never); + assert.match(queued.text, /drafting its onscreen on synth-a i3 on the policy's model/); + assert.match(a.text, /onscreen: 3 title\(s\) written/); + assert.match(a.text, /\*\*Review the draft — the approval is the operator's\.\*\* It drafted each clip's on-screen title and subtitle in the video project \(`\/srv\/projects\/synth-a\/i3`\)/); + assert.match(a.text, /`onscreen-draft\.json`/); + assert.match(a.text, /never by writing `drafts\.review\.json` yourself/); + assert.match(a.text, /A final build refuses any drafted field not approved/); + assert.doesNotMatch(a.text, /Review it — you are the reviewer/); + // A task routed to code is this session's, as any. + const code = await generateTool({ task: "youtube", article: "synth-a", iteration: 3 }, editor({ policy: { routes: { ...POLICY.routes, youtube: "code" } } }).deps as never); + assert.equal(code.isError, true); + assert.match(code.text, /youtube is routed to Claude Code/); +}); + test("resultMarkerOf reads the job's @@report-draft line", () => { assert.deepEqual(resultMarkerOf(["x", '@@report-draft {"article":"a","iteration":2}', "y"]), { article: "a", iteration: 2 }); assert.equal(resultMarkerOf(["nothing here"]), null); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -3,12 +3,13 @@ import { GENERATION_PRESET_NAMES, GENERATION_ROUTES, GENERATION_TASKS, + isStepTask, type GenerationPreset, } from "yt-dlp-transcript-common/lib/generationSettings"; import { AUTONOMIES } from "yt-dlp-transcript-common/lib/report/draft/research/decide"; import { describeEditorFailure, editorGet, editorPost, type EditorAnswer } from "./editorOps"; import type { FetchClipDeps, PollProgress } from "./fetchClip"; -import { reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions"; +import { mediaReviewGuidance, reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions"; import type { ToolAnswer } from "./archivalTools"; // ─── The Claude Code balance (release 27 S9; D8) ─── @@ -242,13 +243,17 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (n === null) return bad(`${k} is an iteration number (1, 2, …)`); if (n !== undefined) body[k] = n; } - for (const k of ["model", "feedback", "question", "from", "to"] as const) { + for (const k of ["model", "extractorModel", "feedback", "question", "from", "to"] as const) { if (args[k] === undefined) continue; const v = trimmed(args[k]); if (!v) return bad(`${k} is text`); body[k] = v; } - for (const k of ["channels", "cards"] as const) { + if (body.extractorModel !== undefined) { + if (task !== "sweep") return bad("extractorModel is a sweep's (the extractor an API sweep reads batches with)"); + if (!String(body.extractorModel).startsWith("claude-")) return bad("extractorModel is a Claude model id: an API sweep's extractor runs on the API"); + } + for (const k of ["channels", "cards", "entries"] as const) { if (args[k] === undefined) continue; const v = args[k]; if (!Array.isArray(v) || v.length === 0 || v.some((x) => typeof x !== "string" || !x.trim())) { @@ -277,6 +282,14 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (body.model) return bad("give model or via, not both"); via = v; } + // A media draft (release 28) is a step on a done iteration: it names it. + if (isStepTask(task)) { + if (body.iteration === undefined) return bad(`a ${task} draft names the iteration it drafts on (iteration)`); + if (body.copyOf !== undefined) return bad(`a ${task} draft is a step on its iteration: it has no copyOf`); + for (const k of ["question", "feedback", "channels", "from", "to"] as const) { + if (body[k] !== undefined) return bad(`${k} is not a ${task} draft's: it drafts from the iteration's report and cut`); + } + } else if (body.entries !== undefined) return bad("entries is a media draft's (cut, onscreen, teaser, flips, threads, narrate, youtube)"); 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 } }; } @@ -377,13 +390,13 @@ export function renderIterationSummary( o: { task: string; article: string; jobId: string; marker: Marker | null; iteration: IterationView; dir?: string; files?: Record<string, string | null> }, ): string { const it = o.iteration; - const step = o.task === "narrate" ? [...(it.steps ?? [])].reverse().find((s) => s.task === "narrate" && s.jobId === o.jobId) : undefined; + const step = isStepTask(o.task) ? [...(it.steps ?? [])].reverse().find((s) => s.task === o.task && s.jobId === o.jobId) : undefined; const status = step?.status ?? o.marker?.status ?? it.status; const lines: string[] = []; lines.push(`generate: ${o.task} of ${o.article} i${it.n} — **${status}** on ${step?.model ?? it.model} (job ${o.jobId})`); if (o.marker?.summary) lines.push(o.marker.summary); if (it.error && status !== "done") lines.push(`error: ${it.error}`); - if (step?.detail) lines.push(`narration: ${step.detail}`); + if (step?.detail) lines.push(`${o.task === "narrate" ? "narration" : o.task}: ${step.detail}`); const per = Object.entries(it.usage ?? {}).filter(([, u]) => u.usd > 0); const total = step ? (step.cost ?? 0) : per.reduce((s, [, u]) => s + u.usd, 0); const minutes = o.marker?.minutes ?? it.minutes; @@ -416,7 +429,8 @@ export function renderIterationSummary( lines.push(`Research: phase ${r.phase ?? "?"}, autonomy ${r.autonomy ?? "?"}${r.continuedBy ? `, continued by i${r.continuedBy}` : ""}`); for (const note of (r.notes ?? []).slice(0, MAX_LISTED)) lines.push(` - ${note}`); if (status === "done") lines.push("", researchGuidance(o.article, it.n)); - } else if (status === "done") lines.push("", reviewGuidance()); + } else if (status === "done" && isStepTask(o.task)) lines.push("", mediaReviewGuidance(o.task, it.projectDir)); + else if (status === "done") lines.push("", reviewGuidance()); else if (status === "failed") lines.push("", "It failed: say why to the operator. Running it again, or here instead, is their call."); return lines.join("\n"); } @@ -542,7 +556,7 @@ export async function generateTool( const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : []; const head = `generate ${task}: queued as job ${jobId}` + - (n ? `, ${task === "narrate" ? "narrating" : "making"} ${article} i${n}` : ` for ${article}`) + + (n ? `, ${task === "narrate" ? "narrating" : isStepTask(task) ? `drafting its ${task} on` : "making"} ${article} i${n}` : ` for ${article}`) + (body.model ? ` on ${String(body.model)}` : " on the policy's model") + "." + warnings.map((w) => `\n⚠ ${w}`).join(""); @@ -566,7 +580,8 @@ export const GENERATION_TOOLS = [ name: "generation_policy", description: "The operator's generation balance (settings.generation, read from the local editor): for each " + - "generation task — sweep (a new cited report), revise-report, revise-video, narrate, research — whether this " + + "generation task — sweep (a new cited report), revise-report, revise-video, research, and the media drafts on a " + + "video cut (cut, onscreen, teaser, flips, threads, narrate, youtube) — whether this " + "Claude Code session does it (code), the Claude API does it (api) or the local model does it " + "(local), on which model; the spend caps; and the day's Claude API spend against the daily cap. " + "With preset (code, balanced, api, local) it routes every task at once; with task and route it " + @@ -580,7 +595,10 @@ export const GENERATION_TOOLS = [ enum: [...GENERATION_PRESET_NAMES], description: "Route every task by this preset: code (all here), balanced, api, local.", }, - task: { type: "string", description: "Route one task (with route): sweep, revise-report, revise-video, narrate, research." }, + task: { + type: "string", + description: "Route one task (with route): sweep, revise-report, revise-video, research, cut, onscreen, teaser, flips, threads, narrate, youtube.", + }, route: { type: "string", enum: [...GENERATION_ROUTES], description: "Where that task runs." }, }, additionalProperties: false, @@ -594,9 +612,13 @@ export const GENERATION_TOOLS = [ "with wait: true, follow it and return the iteration it made: status, cost, the ops applied and " + "refused, the checks, and where its files are on the editor's disk. task sweep makes a new " + "iteration of article from question over channels; revise-report and revise-video make one from " + - "iteration and feedback; narrate voices a done iteration's cut; research finds what the corpus lacks " + + "iteration and feedback; research finds what the corpus lacks " + "and proposes acquisitions under its autonomy (propose, limits, auto), and task sweep with a research " + "run's iteration continues it over the widened scope. copyOf runs an iteration again on another model. " + + "The media drafts are steps on a done iteration's video cut (iteration names it): cut (which cited clips, in " + + "what order), onscreen (each clip's title and subtitle), teaser (its lines), flips (THEN/NOW pairs), threads, " + + "narrate (each card's narration) and youtube (the upload's title and summary); each drafted field is marked " + + "for the operator's review, and a field the operator wrote is never replaced. " + "A task routed to code is refused: do it in this session. The wait is bounded (wait_seconds, " + "default 90, at most 300) and polite (one poll every 5 s, a progress notification each); if the " + "job is still running it answers its id — call again with job (and article, iteration) to keep " + @@ -611,7 +633,7 @@ export const GENERATION_TOOLS = [ type: "integer", minimum: 1, description: - "revise-report / revise-video: the iteration revised; narrate: the iteration voiced; sweep: the research run it continues; with job: the iteration to summarise.", + "revise-report / revise-video: the iteration revised; a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube): the done iteration whose cut it drafts; sweep: the research run it continues; with job: the iteration to summarise.", }, question: { type: "string", description: "sweep / research: the question, in words." }, channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." }, @@ -620,12 +642,18 @@ export const GENERATION_TOOLS = [ feedback: { type: "string", description: "A revision's feedback: what to change, concretely." }, copyOf: { type: "integer", minimum: 1, description: "Run this iteration again (same kind and inputs) on model or via." }, model: { type: "string", description: "The model to run on (else the route's)." }, + extractorModel: { + type: "string", + description: "sweep on the API: the Claude model its extractor reads batches with (else the settings' extractor).", + }, via: { type: "string", enum: ["api", "local"], description: "Run on this route's model instead of the policy's route — only when the operator asks." }, maxUsd: { type: "number", description: "An API job's cap in USD (else the task's default; never above the settings' max)." }, cards: { type: "array", items: { type: "string" }, description: "narrate: only these card ids." }, + entries: { type: "array", items: { type: "string" }, description: "A media draft (narrate, cut, onscreen, teaser, flips, threads, youtube): only these entry ids." }, force: { type: "boolean", - description: "narrate: redraft cards that already have narration; a sweep continuing a research run: continue while proposals still wait.", + description: + "A media draft: re-draft fields a model drafted (a field the operator wrote is never replaced; its draft is kept as an alternative); a sweep continuing a research run: continue while proposals still wait.", }, autonomy: { type: "string", diff --git a/mcp/src/instructions.test.ts b/mcp/src/instructions.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { NARRATION_HARD_RULE, NARRATION_WRITING_RULES, buildSweepInstructions, buildAskInstructions, narrationStep } from "./instructions"; +import { MEDIA_REVIEW, NARRATION_HARD_RULE, NARRATION_WRITING_RULES, buildSweepInstructions, buildAskInstructions, mediaReviewGuidance, narrationStep } from "./instructions"; +import { MEDIA_STEP_TASKS } from "yt-dlp-transcript-common/lib/generationSettings"; import { parsePromptRequest } from "./promptRequest"; import { TOOLS } from "./server"; @@ -318,3 +319,17 @@ test("every tool a routed plan names exists", () => { } } }); + +test("every media task has its review guidance: the draft file, the fields, the operator's approval in umtool", () => { + assert.deepEqual(Object.keys(MEDIA_REVIEW).sort(), [...MEDIA_STEP_TASKS].sort()); + for (const task of MEDIA_STEP_TASKS) { + const g = mediaReviewGuidance(task, "/p/a/i2"); + assert.match(g, new RegExp(`\`${task === "narrate" ? "narration" : task}-draft\\.json\``), task); + assert.ok(g.includes(MEDIA_REVIEW[task]!.check), task); + assert.match(g, /\/browse\/<project>\/review/); + assert.match(g, /never by writing `drafts\.review\.json` yourself/); + assert.match(g, /--drafts-unreviewed/); + assert.match(g, /Use this/); + } +}); + diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -3,6 +3,7 @@ import { NARRATION_HARD_RULE, NARRATION_WRITING_RULES, VERBATIM_QUOTES_RULE, + WHOLE_SENTENCE_QUOTE_RULE, } from "yt-dlp-transcript-common/lib/report/draft/authoringRules"; import { DEFAULT_DIRECTIVE, @@ -150,7 +151,7 @@ function batchStep(req: PromptRequest, ctx: PlanContext, reportPath: string): st `to that video's moment_base (full link = \`<moment_base><seconds>\`; no ` + `moment_base → link the \`source:\` URL instead). A POST finding has no ` + `timestamp — cite it as **\`[post by <author>, <date>](<source url>)\`**, ` + - `never with \`@ mm:ss\`. ${CLAIM_QUOTES_RULE} ${VERBATIM_QUOTES_RULE} ` + + `never with \`@ mm:ss\`. ${CLAIM_QUOTES_RULE} ${VERBATIM_QUOTES_RULE} ${WHOLE_SENTENCE_QUOTE_RULE} ` + `Then discard the fragment. Batches are ` + `independent, so you may dispatch several subagents in parallel.\n` + ` - **Fallback:** with no Task tool, do the batch inline — call ` + @@ -281,6 +282,63 @@ export function reviewGuidance(corpus?: string): string { ); } +// ─── The media drafts (release 28) ─── +// +// A media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a +// STEP on a done iteration's video manifest: it writes drafted fields, each +// marked with its provenance. The review is the operator's, in umtool, field +// by field — the agent reads what was drafted and says what it would approve. + +// What each media task drafts, and what its review checks beyond the code's. +export const MEDIA_REVIEW: Record<string, { what: string; check: string }> = { + cut: { + what: "the cut's clips and their order (ids from the report's citations only; the windows are untouched)", + check: "the order argues the report's case chapter by chapter, and no clip a conclusion rests on was dropped", + }, + onscreen: { + what: "each clip's on-screen title and subtitle", + check: "each title says what its clip shows, and a subtitle's quote is the clip's own words and its speaker's", + }, + teaser: { + what: "the teaser's 3 to 5 lines", + check: "the lines promise only what the cut delivers, and read no quote out", + }, + flips: { + what: "THEN/NOW pairs over the cut's clips (the dates and the order are code's)", + check: "both clips of a pair speak to the topic it names, so the change it shows is real", + }, + threads: { + what: "2 to 4 threads and each clip's thread (an outcome is its last clip's verdict)", + check: "each clip belongs to its thread, and each label names what the thread follows", + }, + narrate: { + what: "each card's narration", + check: "it is third person and says nothing the report does not, and no line restates a quote", + }, + youtube: { + what: "the upload's title and summary (the build adds the chapters and the sources to out/youtube.txt)", + check: "the summary says what the video shows, no more, and the title would not mislead", + }, +}; + +// The review of a media draft — the step Claude Code owns after `generate`. +export function mediaReviewGuidance(task: string, projectDir?: string): string { + const m = MEDIA_REVIEW[task]; + const where = projectDir ? ` (\`${projectDir}\`)` : ""; + return ( + `**Review the draft — the approval is the operator's.** It drafted ${m ? m.what : "fields of the cut"} in the video ` + + `project${where}. (1) Read the project's \`${task === "narrate" ? "narration" : task}-draft.json\`: what each unit wrote, ` + + `skipped, or had refused by a check, and the alternatives it kept. (2) Read the drafted fields in the manifest` + + (m ? `, and check that ${m.check}` : "") + + `; spot-check against the report and, where a field restates speech, \`get_transcript\`. (3) Tell me which ` + + `drafted fields you would approve or reject, and why. I approve or reject each one in umtool — the project page's ` + + `**Review drafts**, \`/browse/<project>/review\` — never by writing \`drafts.review.json\` yourself. A final build ` + + `refuses any drafted field not approved (\`--drafts-unreviewed\` overrides, and that is my call). A field I wrote ` + + `or edited is never replaced: a draft of it is kept as an alternative, which I take with **Use this**. To draft ` + + `again, call \`generate\` with the same task and iteration (force: true re-drafts only fields a model drafted).` + ); +} + // The generate call a routed sweep makes, with its scope settled. function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; model?: string; by: string }): string { const article = req.article diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9177,5 +9177,217 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **A fetch window's `from`/`to` are the padded window; `pad` is provenance** (S7): every caller pads before it asks. - **verify-quotes `inexact`** is a warning only (`QUOTE_WARNING_STATUSES`, `common/bin/reports-check.ts`); `drift` and `en-orig-drift` take precedence over it. +- **A two-line finding is a finding** (`0c7b088f`, found in the live smoke): a bullet whose first line is the claim and + whose quote and link sit on the lines under it is what the sweep agent writes. `evidenceOf()` (`sweepModel.ts`) gives a + finding's quotes and links wherever they sit; the numbered view, `quotesOf`, the drop and the quotes-in-claims lint + all read it. +- **A revision whose model never calls `apply_ops` gets one schema-bound ask** (`73292cea`, `revise-report.ts`): the + ops batch as a `structuredAnswer`; a revision with no ops at all is a failing `ops` check, never "done, 0 applied". - **The stopgap's `~/.config/archilyzer/generation.json` is retired** (absent on this machine at 2026-10-13); its runs come in once through `archilyzer reports import-local-runs` (`common/bin/reports-import-local-runs.ts`). + +## Drafted fields and the drafts review (verified 2026-10-13, release 28 M0, branch `r28/framework`) + +- **The mark.** `common/lib/report/drafted.mjs` (plain JS, typed by `drafted.d.mts`, exported as + `yt-dlp-transcript-common/lib/report/drafted.mjs`) is the one copy. A provenance is + `{ task, model, at, iteration?, attempt }` (`at` ISO, `attempt` 1 or 2). Entry fields: + `entry.drafted.{onscreen | narration | lines}` (on-screen on any entry, narration on a card, lines on a teaser). + Manifest fields: the top-level `drafted` map keyed by path — `timeline` (the cut's ORDER: the entries' ids), + `render.chrome.flips`, `render.chrome.threads` (the list AND every clip's `thread` key), `publish.youtube`. + `validateDrafted` refuses a mark anywhere else or not a provenance; an orphan (a mark whose field is empty) is + not an error: the lint warns, `pruneDrafted` drops it. +- **`publish` is a new top-level manifest key**: only `publish.youtube { title, description }`, two strings, title + one line ≤ 100, description ≤ 5000 (`validatePublish`; the build, the lint and umtool's structural writes run it). +- **Who owns a field** (`ownerOf`): empty → nobody; a value with a mark → the draft; a value with NO mark → the + operator. `applyDraft(manifest, { entry?, field, value, provenance, force? })` is the one writer every task + uses: `{ applied: true }` or `{ applied: false, reason: "operator" | "drafted" | "missing" }`. The operator's + field is never replaced, `force` or not; `force` only re-drafts a field still marked. An entry id names every + entry with it (variant twins). A timeline with no `drafted.timeline` is the operator's to `ownerOf` — but the cut + task counts the converter's order as code's (M1, below). +- **An edit clears the mark.** umtool's manifest writer (`lib/report/manifest.mjs` `writeManifestAtomic`) + re-reads the file and runs `clearEditedDrafts(before, after)` on EVERY write: a marked field whose + `fieldSignature` changed loses its mark; orphans go. A mark the write itself added is kept. `writeDraftedField` + is "Use this" (onscreen, lines, narration, flips, threads, publish.youtube; not `timeline`). +- **The review file** is `<project>/drafts.review.json`, `{ "<task>/<entry id | *>/<field>": { verdict: + "approved" | "rejected" | null, note, key, text, at } }` (`umtool/report-to-video/drafts-review.mjs`). The + address's task is the FIELD's own (`FIELD_TASKS`: onscreen→`onscreen`, narration→`narrate`, lines→`teaser`, + timeline→`cut`, flips→`flips`, threads→`threads`, publish.youtube→`youtube`), whichever task drafted it. + `key` is `narrationKey` for a narration (words + voice), else `fieldKey` (sha256 of the stable JSON of + `fieldSignature`). Release 25's `narration.review.json` (`{ <cardId>: row }`) is READ as + `narrate/<cardId>/narration`; the drafts file wins; nothing writes the old file. A cleared row the old file + still has stays in the drafts file as an empty verdict so the old approval does not show through. +- **The gate** (`draftsReviewProblems`, run by the lint): a marked field not approved on its current key is a + warning (one line) in preview/fast and an ERROR with `--final` unless `--drafts-unreviewed` + (`--narration-unreviewed` too for a narration); rejected is an error in final whatever the flags, a warning + otherwise. A narration with NO mark keeps release 25's rule in every build, where "the narration has a review" + now means a narration row in either file (an onscreen verdict does not start it). The driver's `final` preset + passes `--final`; `fast` and `preview` do not. +- **The media task scaffold** is `common/lib/report/draft/tasks/media.ts` (`runMediaTask(spec, input, deps)`, + exported from `tasks/index.ts`). A spec: `task`, `units(ctx)` (a unit `{ id, target: { entry?, field } }` or a + skip `{ id, skipped }`), `schema`, `system`, `user`, `parse`, `check` → `{ hard, soft }`, and optional `score`, + `repair`, `retry`, `toField`, `afterApply`, `apply`, `draftFile`, `snapshotOp`, `checkName`, `turnKind`, + `noun`, `verb`, `describe`. A unit whose field has a value is skipped unless `force`. The draft file + (`<task>-draft.json`; narrate keeps `narration-draft.json`) is `{ task, model, at, article, iteration, units: + { <id>: { target, attempts, chosen, applied | skipped } }, checks, alternatives: [{ target, value, provenance, + reason }] }`; alternatives from earlier runs are carried over, newest five per field. The step is recorded in + the iteration's `steps` (a done iteration's status is left). umtool reads alternatives from every + `*-draft.json` beside the manifest (`lib/report/drafts.mjs` `readAlternatives`). +- **The media steps (release 28, lane D).** `MEDIA_STEP_TASKS` / `isStepTask` (`generationSettings.ts`) is the one list + of tasks that run as a step on a done iteration (`narrate, cut, onscreen, teaser, flips, threads, youtube`); each has a + route (narrate's in every preset) and a narration's cap; a `report-draft` step body is `{task, article, iteration, + model?, entries?, force?}`. The scaffold reports progress per ask (`progressMetric`, default `entries`; narrate + `cards`), may batch units (`spec.batch`) and may say who owns a unit's field for the skip (`spec.owner`); the + writer is always `applyDraft`. A task reaches the build's validators through `TaskDeps.deckChecks` + (`tasks/deckChecks.ts`: umtool's `deck.mjs` `validateTeaser` and `lint.mjs` `validatorErrors`, imported natively + from the checkout; the editor job passes `loadDeckChecks(paths.monorepoRoot)`). +- **cut** (`tasks/cut.ts`): one unit, `drafted.timeline`. The model answers citation ids grouped under section + headings; code checks them (candidates only, once each, 3 to `generation.cut.maxClips` (20), pinned clips kept — + posts' `attachTo`, flips' entries — headings the cut's, no new `validatorErrors`) and BUILDS the timeline + (`buildCut`) from the entries it had. **A timeline marked `model: "code"` is nobody's**: `reportToManifest` marks + its own `{task: "convert", model: "code"}`, an unmarked timeline in the converter's clip order counts as code's + (`isConverterOrder`), the cut drafts over either without `force`; `isCodeDraft` marks need no review (no review + row, no final-gate error). +- **onscreen** (`tasks/onscreen.ts`): one unit per clip, asked in batches (≤ 8, within the local cap); title ≤ 60 + with no quotation marks, subtitle ≤ 90 quoting only the clip's own quote word for word, one line each, names and + numbers in the clip's evidence (`groundedProblems`), third person outside quotes. +- **teaser** (`tasks/teaser.ts`): one unit per teaser entry; none → a `{type: "teaser", id: "teaser"}` after the last + clip, through `applyDraft`. 3 to 5 lines ≤ 70, no quotation marks, no 5-word run of a quote, grounded, and + `validateTeaser` passes — without `deckChecks` nothing is written. +- **`groundedProblems(text, reference, where)`** (`grounding.ts`) is the names-and-numbers check narration, on-screen + and teaser share (a sentence's first word is not checked as a name). +- **umtool's e2e stub runs cut, onscreen and teaser for real** (`common/testing/draft/runMediaStep.ts`, a tsx child + over the fixture iteration's project, the fake ollama on `runs/<task>.json`); the task records its own step. +## Release 28 lane B: quality and progress (verified 2026-10-13, branch `r28/quality` @ `48dbc5de`) + +- **The narrator is third person** (`grounding.ts`): a first-person word outside double quotes is a HARD grounding problem whose text starts `the narrator is third person`. A media task that calls `checkNarration` refuses it with no change of its own. `GroundingInput.sources` (each quote's speaker and `c03 (label @ m:ss)`) names the line it restates; `groundingInputOf` fills it. +- **A fragment quote** (`lib/citations/fragment.ts`): `fragmentOf(quote)` → `{why, part} | null`; `fullSentenceFor(quote, cues, second)` → the cues' own words or null; `fragmentHint(f, sentence)` is the repair wording. A GENERATED fragment fails (`checkQuotes` problem with `fragment`, the add op's checker); an existing one is verify-quotes' warning `fragment`, after `drift` / `en-orig-drift` / `inexact`. +- **A local revision is one `structuredAnswer`**, never the tool loop: `localOpsBatch(h, {model, system, what, build, apply})` and `fitLocalAsk` (revise-report.ts) fit a view under the cap with `structuredPromptEstimate` (llm/structured.ts, the request localAnswer sends). `trimmedNumberedView` / `trimmedCutView` shorten quotes and links in the VIEW only. +- **`report-draft {extractorModel}`** is a sweep's, a Claude id `isKnownApiModel` accepts; it replaces `generation.models.extractor` for that job. +- **A report-draft job's progress** is the task's: `TaskDeps.progress?({metric: "turns" | "cards" | "entries", current, total?})` → `JobProgress {metric, initial: 0, target, current}`. A task calls `h.progress(...)` (TaskHandle; a throwing listener is swallowed). Media tasks report `cards` / `entries` the same way. + +## Release 28 lane C: the verdict bench, site delete (verified 2026-10-13, branch `r28/bench-house`) + +- **A verdict bench run** lives in `<repo>/.generation/bench/verdicts/<run>/` (`benchRootOf(paths)` = the usage ledger's + directory + `bench/verdicts`; gitignored, local-only): `items.jsonl` (one `BenchItem` per ruled claim — key + `<article>/<claim>`, the claim text, quotes, windows, and the operator's `verdict`, the answer key), `results.jsonl` + (one `BenchResult` per (item, model): `verdict` or null with `failure` `parse`|`error`, `reason` ≤ 300 chars, ms, usd, + tokens) and `summary.json` (format `archilyzer-verdict-bench`, status `running|done|capped|cancelled|failed`, + `stopped`, params, `spentUsd`, `skipped`, `score`). Every file is rewritten whole, atomically; the same run id + resumes (answered pairs skipped, failures asked again). Readers re-score from items + results (`scoreBench`), never + trust `summary.score` alone. Code: `common/lib/report/draft/bench/` (`index.ts`; import `…/bench/index`, a directory + import does not resolve through the package exports). +- **The bench runs as job kind `bench-verdicts`** (`controller/benchVerdicts.ts`, `POST /api/ops/bench-verdicts`): on + `draft:local` when any model is local (the GPU arbiter's `gpuGatedFetch`, ollama unloaded at the end), else + `draft:api`; refused past `caps.daily`; its API spend goes to the usage ledger as rows with `task: "bench-verdicts"`, + `article: ""`, `iteration: 0`. The cues are the local corpus's (`diskCuesOf`), not a build's. `archilyzer reports + bench-verdicts` is `--dry` (read only), through the editor (default), or `--here` (API models only). +- **`settings.generation.verdicts` = `{bar: {agreement, contradictedRecall, notFoundRecall}, models: string[]}`**: + fractions 0..1 (all 0 = no bar), and the passing models the operator ticked on umtool's `/bench` (never set + automatically). umtool writes the whole block through the editor's settings action (a nested object replaces). + `passesBar(score, bar)` (`bench/score.ts`) is the one pass rule: strict agreement and the two recalls; a recall with + nothing ruled that way is not a miss. +- **A site's delete** (`publish/siteDelete.ts`, `pnpm ops delete-site`) removes `sites/<id>/`, + `export/.export-builds/<id>/` and `export/.export-index/sites/<id>/`; nothing else on disk names a site by id + (channel membership is site.json's own pool). The editor's Danger → Delete (`deleteSiteAction` → `deleteSite`) still + removes `sites/<id>/` alone. +## Release 28 F1: an `auto` research run continues by itself (verified 2026-10-14, branch `r28/research-f`) + +- **`maybeAutoContinue(article, n, deps)`** (`common/controller/researchAutoContinue.ts`, `deps` = `ReportDraftDeps`) + is the one function; it answers `{outcome: "continued", by, jobId?, warnings} | {outcome: "held" | "refused", + reason} | {outcome: "not-now", why, final?}` and is idempotent. Only `auto` continues by itself; `propose` and + `limits` are final not-nows. The continuation is `enqueueReportDraft({task: "sweep", article, iteration: n, + model: <the research run's own model>, channels: <the kept ones>})` — Continue's own path, so `markContinued`, + caps.sweep and the daily cap at the ask and at the job's turn are unchanged. +- **The record** is `research.autoContinue` in the run's `iteration.json` (`AutoContinueRecord`, + `lib/report/draft/research/state.ts`): `{status: "claimed" | "continued" | "refused" | "held", at, by?, reason?, + warnings?, day?, buildsAt?}`, mirrored as `ResearchView.autoContinue` (research-approve's answer), plus a + `{kind: "auto-continue", outcome, …}` line in the run's `turns.jsonl`. **The claim is the once-only mark**, taken by + `updateIteration`'s function patch under the article store's lock; a claim is fresh for `CLAIM_STALE_MS` (10 min), + and a stale one with a sweep made after it (`parent` n) is recorded as the continuation. `refused` is retried + only on a later UTC day than `day`; `held` (nothing it would sweep is in any composed build) on a build newer than + `buildsAt` or a later day. A channel in no build (`listCorpusBuilds`) is left out with the warning `not in any + build yet: <slug> — rebuild the site and continue again`, also a failed `unbuilt channels` check on the sweep. +- **The triggers.** `onJobEnd(listener)` (`common/jobs/registry.ts`, new): every job's end, once, on a later turn + (`setImmediate`) after `finalize`. `settle` in `researchRuns.ts` watches an `auto` run's pending job ids + (`watchResearchJobs` / `takeWatchedRun`, in-process, bounded at 2000); the listener continues a watched job's + run, and the end of a `report-draft` job or a site build (`SCAN_ON_END`) runs the scan. `scanAutoContinue(deps)` reads every article's iteration + dirs holding a `proposals.json` (a run finished with is remembered, not re-read), one scan at a time. + `armResearchAutoContinue(deps, {log?, env?, bootScan?})` arms the listener and a boot scan and refuses an idle + boot (false); `researchAutoContinueTick()` is the heartbeat's call (`editor/app/scheduler/heartbeat.ts` `fire`) + and returns null unarmed. The editor arms it in `instrumentation.ts` BELOW the idle gate, through + `editor/app/api/ops/_autoContinue.ts` (the report-draft route's deps). +- **The heartbeat is off by default** (`syncScheduler.heartbeatSeconds` 0; the live `settings.json` has 0, verified + 2026-10-14): live, the job-end listener and the boot scan are the triggers, and a `refused` or `held` run is + retried only at the next end of a report-draft job or a site build, the next boot, or a heartbeat if one is + configured. + +## Release 28 lane E: flips, threads, the YouTube text (verified 2026-10-14, branch `r28/media-e`) + +- **The left panel's rules are common's** — `common/lib/report/panels.mjs` (+ `.d.mts`, exported as + `yt-dlp-transcript-common/lib/report/panels.mjs`): `FLIPS_LIMITS`, `flipsOn`, `validateFlips`, + `validateFlipEntries`, `THREADS_LIMITS`, `threadsOn`, `threadOf`, `validateThreads`, `validateThreadEntries`. + umtool's `report-to-video/flips.mjs` and `threads.mjs` re-export them unchanged; never copy them back. +- **A flips pair is code's but for its clips and topic.** The `flips` task (`tasks/flips.ts`) dates each clip + (`tasks/clipEvidence.ts` `clipFacts`): the entry's `date`, else the corpus record's `uploadDate` + (`get_video_metadata` through `deps.corpus`), else the report citation's `date`. The earlier is THEN; one day is + no pair; `when` is `Mon YYYY`; `words` is the clip's quote (or the model's part of it, when the quote says exactly + that), cut at a word to `FLIPS_LIMITS.words` with `…`; the pair id is the topic slugged. A THEN that plays after its + NOW swaps the two clips' places only when `ownerOf(timeline)` is `"drafted"` and the flips will be applied (the + timeline is rewritten through `applyDraft` with the flips provenance), else the pair is refused. +- **A thread's outcome is its last clip's `claim.verdict` in the manifest** (by timeline order), when it has one; the + `threads` task (`tasks/threads.ts`) makes 2 to 4 threads (`THREADS_TASK_COUNT`) and, once the list is applied, sets + every clip's `thread` (a clip in none has the key removed). +- **One left panel:** `flips` refuses a cut with threads and `threads` one with flips, unless `force` and the other is + a draft: then the other's field, its clips' `thread` keys (for threads) and its mark are removed, and the log says + so. Both refuse a cut with no `render.chrome`. +- **`publish.youtube` is drafted by `youtube`** (`tasks/youtube.ts`): title ≤ 100, one summary paragraph ≤ + `YOUTUBE_SUMMARY_MAX` (900), `checkLine(…, {quotes: true})` grounding (words in quotation marks must be a cited + quote's, word for word), no links, timestamps or hashtags. **`checkLine` does not check a line's FIRST word as a + name** (it is the narration grounding, which skips each sentence's first word), so a topic, label or title that + starts with an unknown name passes that check. +- **`out/youtube.txt`** (`youtube-<variant>.txt` for a variant other than `sourced`) is written by build-video after + every chapter mux (the full build, the deck build, `--rail-only`, `--chapters-only`; also under `--no-chapters`, + without chapters) when the manifest has a `publish.youtube` title. `muxChapters` returns `{chapters: [{start, end, + title}], total}`. The composition is `report-to-video/youtube.mjs` (`composeYoutubeText`, `youtubeChapters`, + `youtubeSources`, `momentLinkOf`, `youtubePreview`, `youtubeTextName`), exported as `umtool-report-to-video/youtube`. + +## Release 28 M9: the surfaces of the media drafts (verified 2026-10-14, branch `r28/surfaces`) + +- **Draft everything is a chain mode.** `umtool/lib/report/chain.mjs` `CHAIN_STEPS` carries every step with its + `modes` (`"video"`, `"draft-all"`); `chainStepsOf(mode)` is a chain's list. The generation steps are + `draft-<task>` (`optional: true`, `draft: <task>`), in the draft-all chain only: current → windows → prepare → + posts → manifest → draft-cut → draft-onscreen → draft-teaser → draft-flips → draft-threads → draft-narrate → + voices → video → podcast → draft-youtube. No attach, no dedupe. `CHAIN_STEP_NAMES` is still the default chain's + ten. The draft-all build never takes `--final`; `model` rides on the draft steps' argv (`--model`) only. +- **A draft step is one `report-draft` job through the editor** (`chain-run.mjs` `draftStep`: POST + `/api/ops/report-draft`, GET `/api/ops/job/<id>` every `CHAIN_DRAFT_POLL_MS` (2 s), a chain cancel cancels the + job). It records `chain:draft-<task>` as `done` (the job's summary), `skipped` (`draftPrecheck`: flips and + threads with no `render.chrome` or with the other panel on, never asked; or `draftOutcome`: every unit of + `<task>-draft.json` skipped) or `failed` (refused at the ask, or the job failed) — and an optional step exits 0 + either way, so the chain goes on. `doneSteps` counts an optional step `done`, `skipped` or `failed` as finished + (a resume passes it); a code step only `done`. The pure part is `chain-draft.mjs` (plain node). +- **draft-youtube re-muxes a built cut's chapters** (`build-video --chapters-only --no-xfade --skip-fetch`) so + `out/youtube.txt` is written; with no `out/<slug>.mp4` the next build writes it. +- **umtool's chain jobs are two kinds:** `chain <article> i<n>` and `draft-all <article> i<n>` (`chainKind(…, + mode)`); one umtool job runs at a time either way. `/api/articles/chain` takes `{draftAll, model}` and `?mode=`. +- **A project names its iteration by its path:** `projectIteration(dir)` (`umtool/lib/articles/projectDraft.ts`) + is `<projectsRoot>/<article>/i<n>/` whose iteration exists and names that directory as its project (or none). + Any other project has no "Draft with". `draftRunSummary` reads a task's last run from `<task>-draft.json`; + `/api/articles/draft?project=` answers both. +- **A threads alternative is `{list, clips}`** (`clips`: clip id → thread id); the task applies `{list}`. + `writeDraftedField` writes the list and sets each clip's `thread` from `clips` (removed from a clip in none), + refusing a clip the cut lacks and anything `validateThreadEntries` refuses. An alternative without `clips` writes + the list alone, as before. +- **A revise-video whose ops change the timeline's order** (its ids, `fieldSignature`) sets `drafted.timeline = + {task: "revise-video", model, iteration, attempt: 1}`; one that does not keeps the parent's mark. +- **onscreen checks a Title Case title in its sentence case** (`isTitleCase`, `titleAsSentence`): past the first + word a small word, an ordinary headline word (`TITLE_ORDINARY`) or a word the evidence has (by stem) is + lowercased; anything else keeps its capital and is a name's candidate. The first word is never checked as a + name (the grounding's rule, unchanged). +- **The editor's site Delete is plan-first:** `planSiteDeleteAction` / `deleteSiteAction(siteId, {force})` + (`editor/app/sites/actions.ts`) over `publish/siteDelete.ts`; `lib/site.ts` `deleteSite` has no caller in the + editor now (lane C's "still removes `sites/<id>/` alone" above no longer holds). +- **The umtool e2e stub drafts every media task:** the kit's article `mdraft` runs the real task (lane D's + `runMediaStep.ts`); the surfaces' article `msurf` is canned (`startCannedDraft`, through `applyDraft`, with a + draft file in the scaffold's shape and `entries` progress). + diff --git a/plans/STATE.md b/plans/STATE.md @@ -3,34 +3,21 @@ The working memory for the local-AI derived-corpus work. Rewritten at the end of every session, before context is cleared. See [`README.md`](README.md) for the protocol. -**Now (2026-10-13): release 27 — report and video generation inside the application — is built on -`r27/integration`, not on `main` and not live** (plan and record: [`release-27.md`](release-27.md); D1–D9 ratified as -recommended). `main` is `9f05d557`. -- **Merged into `r27/integration`:** S0 (test kit), S1 (providers and the agent loop), S2 (strict quote check and op - engines), S3 (corpus tools in process, `web-search` / `web-fetch`), S3b (`archive-search`, `archive-item`, - `import-post`, the acquisition tools), S4 (iterations store), S5 (tasks), S6 (`report-draft` jobs, GPU arbiter, caps, - `settings.generation`), S7 (the umtool chain and the four owed bugs), S8 (umtool `/articles/new`, Iterations, - compare, policy panel), S9 (`generation_policy` / `generate`, `/gen`, `archilyzer gen`), S11 (research runs, - `research-approve`, umtool's research queue). S10 (`archilyzer reports import-local-runs` and the docs) is on - `r27/migrate-docs`. -- **Owed, in order:** merge S10; the gate round on the integration tip (typecheck, unit suites, docs - checks, the four capped builds, `pnpm e2e:all` with `article-new`, `article-iterations`, `article-compare`, - `article-research` and `report-draft`), including the two runs no lane could make under the memory floor (a - standalone editor `next build`; umtool's `build.spec.ts` and its capped build); the privacy greps; fast-forward - `main`; the rollout (editor rebuild and restart, umtool build and restart, Claude Code restart for the MCP tools, - the homepage source-mirror publish; no public site changes); the live smoke on the operator's key (≤ $3, the list in - the plan's Gates). -- **Then the stopgap:** the operator reads the import's dry run (`pnpm archilyzer reports import-local-runs`), then - `--apply`; then the test runs, projects and drafts it lists are deleted on the operator's OK (15 items, 307 MB, three - of them registry drafts with no registry delete verb); the user-level `~/.claude/commands/gen.md` is retired; the - stopgap stays read-only until the operator deletes it. `runs/api-shondo-fishing` is neither imported nor deleted - (ruled 2026-10-13): it is on the operator's list. -- **Found during release 27, not fixed:** transcription leaves `/tmp/parakeet-stitch-*` directories behind (21 since - 2026-10-02, ~210 MB of the RAM tmpfs). `controller/relocateChannelMedia.test.ts` ("reconcile: an extra and a - changed file") failed once in a full common run on `r27/migrate-docs` and passes alone. -- **Later candidates:** a research run under `auto` continuing into its sweep by itself (r27 keeps continuing - explicit); a per-job extractor model (r27: policy-level only); a turns meter on the `report-draft` job; release 28's - media tasks on the same machinery (D5). +**Now (2026-10-13): release 28 — the remaining media tasks, generation quality, follow-ups and housekeeping — is in +flight on `r28/integration`** (plan and record: [`release-28.md`](release-28.md), ratified 2026-10-13). `main` is +`e8a5f49d`. +- **Release 27 is complete and live** (record: [`release-27.md`](release-27.md)): report and video generation in the + application — iterations, `report-draft` jobs on `draft:api` / `draft:local`, umtool's `/articles/new`, Iterations + tab, compare and policy panel, MCP `generate` / `generation_policy`, the repo's `/gen`, `archilyzer gen`, research + runs, and the delete paths (`archilyzer reports delete`, `pnpm ops delete-article|delete-iteration`). The stopgap's + kept runs were imported (`reports import-local-runs --apply`); its test leftovers and the smoke articles are deleted. +- **Release 28 in one line:** the media tasks (cut, on-screen, teaser, flips, threads, YouTube text) on one draft + framework with provenance and a review gate (`final` refuses unapproved drafts); a verdict bench before any verdict + task; quality checks (first person in narration, fragment quotes, local-first revisions); auto-continue for `auto` + research, a per-job extractor, `report-draft` progress; housekeeping (the parakeet-stitch temp-dir leak, three flaky + tests, `pnpm ops delete-site`, the hub tombstone deploy, stale worktrees, the stopgap retired). +- **Lanes:** phase 1 A (M0 framework), B (Q1–Q3, F2, F3), C (M7 bench, H1, H2, H5 code); phase 2 D (M1–M3), E + (M4–M6), F (F1); phase 3 M9, then M8 once the operator sets the bench's bar. **Previously (2026-10-09): release 18 is complete on `r18/integration`, and `main` is merged into it (`4cffda3f`, 94 commits ahead of `main` `e921f82f`, 0 behind: a fast-forward).** The merge brought main's ~70 commits since 2026-10-06 diff --git a/plans/release-28.md b/plans/release-28.md @@ -0,0 +1,983 @@ +# Release 28 — the remaining media tasks, generation quality, follow-ups and housekeeping + +Status: **RATIFIED 2026-10-13** — all four groups (media tasks, quality, follow-ups, housekeeping). S0 landed on +`r28/integration`. + +## Start here (the implementing session) + +Read before acting: +- `AGENTS.md`; +- `plans/STATE.md` ("Now") and `plans/FACTS.md`; +- `plans/tools/implementer-rules.md`; +- this plan, and `plans/release-27.md`'s record (the machinery this release builds on). + +**The orchestrator** runs in the primary checkout; the integration branch is in the worktree `~/Projects/r28-integration`: +- lane worktrees: `pnpm wt add <branch> --from r28/integration`, then `link-fixture-public.sh`; +- merges are `--no-ff`; `main` moves by `git merge --ff-only` after the gates; +- rollout scripts are `~/reports/release-27/scripts` copied to `~/reports/release-28/scripts`, MERGE and LIVE re-guarded. + +## Rulings (operator, 2026-10-13) + +- **Review gate:** the full gate. Drafted fields carry provenance and an approve/reject, a field the operator edited is + never overwritten, and a `final` build refuses unapproved drafts (the original plan's D2). +- **Verdicts:** bench first. A `verdicts` task ships only for models that pass the operator's bar, as AWAITING_REVIEW + proposals. +- **Cleanup is authorised without a per-item OK (after the gates):** prune stale worktrees, delete the stopgap folder and + the user-level `/gen`, delete the candalyzer site, finish and deploy the hub tombstone. + +## Facts found (survey, 2026-10-13) + +- None of the media tasks exist. `common/lib/report/draft/tasks/index.ts` has five (sweep-agent, sweep-pipeline, + revise-report, revise-video, narrate). No `drafted` provenance or general review exists anywhere. +- **The pattern to copy** is `narrate.ts`: evidence per entry → `structuredAnswer` against a schema → checks + (`grounding.ts`) → keep the better of two attempts → a `<task>-draft.json` audit file → `snapshotManifest` → + `writeManifest` (`tasks/project.ts`). +- **The gate to generalise** is release 25's narration review: `umtool/report-to-video/narration-review.mjs` (the + `NARRATION_REVIEW_FILE`) and `build-video.mjs:4137` (an un-approved narrated card refuses the build unless + `--narration-unreviewed`); `umtool/lib/report/narration-review.mjs` is umtool's view; `driver.mjs:55` has the + `final` mode. +- **Where each media field lives** (manifest; `umtool/report-to-video/README.md`): + - clips: timeline entries, today one per citation in report order (`convertManifest.ts:407`); + - on-screen: an entry's `onscreen.{title,subtitle}` (`umtool/lib/report/onscreen.mjs`, `OnscreenSection.tsx`; + validated by `deck.mjs` `normalizeOnscreen`); + - teaser: a `{type:"teaser", lines, …}` entry (`StructureEditors.tsx` hand editor); + - flips: `render.chrome.flips.pairs[]` (`flips.mjs` `validateFlips`, `validateFlipEntries`; no umtool UI); + - threads: `render.chrome.threads.list[]` and each clip's `thread` key (`threads.mjs` `validateThreads`, + `validateThreadEntries`; no UI; NOT social posts); + - YouTube title and description: no field anywhere (new); + - verdicts: the report's `Claim.verdict` (`schema.ts:80`), mirrored to the manifest's `claim.verdict`; no op sets it. +- **Q0 (binding for every prompt):** counts and lengths are enforced in code; prompts carry rules, never worked + examples; keep the better of two attempts; the local prompt is ≤ 8k tokens. +- **Quality gaps:** + - no check catches a speaker's first-person words in the narrator's mouth (`grounding.ts:179-237` is where the lints + live); + - nothing rejects a fragment quote ("I priced it as"; `citations/verify.ts`, `tasks/quotes.ts`); + - local revisions mostly fail in the tool loop (the r27 fallback asks once with `structuredAnswer`, and the numbered + view is never trimmed to the 8k cap). +- **Follow-ups:** + - research continuation is only request-driven (`researchRuns.ts` `continuationOf` / `markContinued`, called from + `reportDraft.ts:315,392`); + - the extractor is settings-only (`reportDraft.ts:465`); + - `report-draft` discards `setProgress` (`JobProgressMetric` in `common/jobs/registry.ts:17`; example + `controller/fetchWindows.ts:274`); + - `~/.claude/commands/gen.md` is the stale stopgap version (the repo's overrides it in this project). +- **Housekeeping:** + - `scripts/parakeet-stitch.mjs:346` mkdtemps, and the pause path `process.exit`s inside the `try` (:360), skipping the + `finally` rm (:379); + - flaky tests: `relocateChannelMedia.test.ts:1602` (real rsync in a shared temp dir), `scripts/queue-lock.test.mjs:792` + (timing), `editor/e2e/backfill.spec.ts:516` (unchecks before the previous save settles); + - A7: `~/reports/release-26/scripts/a7-fill-media.sh` (40 post captures via the editor, 2 windows, prepare, private + homepage); + - site delete is editor-only (`editor/app/sites/actions.ts:319` → `common/lib/site.ts:311`), with no ops verb; + - the hub tombstone code shipped (`common/publish/tombstones.ts`); a hub publish with its live tombstone probes, and + release 18's "open question 1", are owed; + - about 17 worktrees are on branches merged into `main` (unmerged: `mk/dedup-ums`, `export/gumroad-tip`, + `r13/phase-5`, `diet-series`; plus a detached `render-local-sources`); + - `plans/STATE.md` "Now" predates r27's rollout. + +## Shape + +**The draft framework (M0)** — one shape for every media task, narration included: +- A drafted manifest field carries `drafted: {task, model, at, iteration?, attempt}` beside it (an entry's `onscreen`, a + teaser's `lines`, `render.chrome.flips`, `render.chrome.threads`, `publish.youtube`, a card's `narration`; the + timeline order for `cut`). +- **No overwrite:** a field without `drafted` (the operator wrote or edited it) is never replaced. The new draft goes to + `<task>-draft.json` as an alternative with "use this" in umtool. Editing a drafted field in umtool removes its + `drafted` (it is the operator's now). +- **The review** generalises `narration.review.json` into one review file keyed by `task/entry/field`: approve or reject + with a note. `build-video` lints it: preview and fast builds pass with a warning; `final` refuses any + drafted-and-unapproved field (`--drafts-unreviewed` overrides, as `--narration-unreviewed` does). Narration moves + onto it, and existing narration reviews read unchanged. +- **A media task** = `(iteration, entries?, model, force?)` → evidence → `structuredAnswer` → code checks (counts, + lengths, ids that exist, grounding) → the better of two attempts → `<task>-draft.json` → snapshot → write with + `drafted`. Each task is registered in `tasks/index.ts`, runs as a `report-draft` step on the iteration (like narrate: + `steps[]`), and gets a route in `settings.generation.routes`. + +**The tasks:** +- **M1 cut** — selection and order from the report's citations. A cap on clip count (setting, default 20), ids only + from citations, order by argument; windows untouched (fetch and snap stay code). +- **M2 on-screen** — title (≤ 60 chars) and subtitle (≤ 90) per entry, grounded in the claim and quote. +- **M3 teaser** — 3 to 5 lines, each ≤ 70 chars, no quotes read out, grounded. +- **M4 flips** — THEN/NOW pairs over existing timeline ids. A pair needs two clips on one topic at different dates + (dates checked in code). `validateFlips` passes. +- **M5 threads** — a short list (2 to 4) and a `thread` key per clip. `validateThreads` passes. +- **M6 YouTube** — a new manifest field `publish.youtube {title, description}`: + - the model writes the title (≤ 100 chars) and a summary paragraph; + - code appends chapters from the build's chapter list, and source links from the citations (moment links); + - the build writes `out/youtube.txt`; + - umtool shows and copies it. +- **M7 verdict bench** (local-only data, counts-only in commits): + - one claim per call (claim, quote, the transcript window) over existing fact-checks with operator rulings; + - models: Sonnet 5.5, Opus 5.5 and qwen3:8b; + - per model: agreement, a confusion matrix, CONTRADICTED and NOT_FOUND recall, against an always-CORROBORATED + baseline; + - a umtool results page, audit-style; + - the operator then sets the bar. +- **M8 verdicts** (only after the bar is set, only for passing models): + - a `proposedVerdict {verdict, model, reason}` on claims; + - AWAITING_REVIEW in umtool, approve → `verdict`; + - never written to `verdict` directly. +- **M9 surfaces:** + - "Draft with <model>" per section in the project and Iterations pages; + - "Draft everything" = the chain's optional text steps (cut → windows → on-screen → teaser → flips → threads → + narration → voices → fast build → podcast → YouTube); + - MCP `generate` and `generation_policy` know the new tasks, and `/gen` and `archilyzer gen` follow. + +**Quality (Q):** +- **Q1** — a hard narration check: a first-person sentence (I/my/me/we/our outside a quote) is refused. The narrator is + third person by rule. If a sentence closely matches an evidence quote, the reason names it. +- **Q2** — a quote-fragment check: + - a generated quote under 4 words, or ending on a function word (as, to, the, and, of, a…), is `fragment`; + - code offers the full sentence from the cue window, and the repair round and revisions use it; + - verify-quotes reports `fragment` as a warning for existing reports; + - `authoringRules.ts` gains "quote a whole sentence or clause". +- **Q3** — local-first revisions: for an ollama model, skip the tool loop and make one `structuredAnswer` ops batch over + a numbered view trimmed to the 8k cap (sections the feedback names first, quotes shortened in the view only). The API + path is unchanged. + +**Follow-ups (F):** +- **F1** — auto-continue: an `auto` research run whose acquisitions settle continues into its sweep by itself (a check + on the editor's existing heartbeat, plus at each acquisition job's end). Channels not yet in any build are skipped, + with a warning, and the caps hold. +- **F2** — a per-job `extractorModel` body key (ops, umtool per-step model, MCP `generate`). +- **F3** — progress metrics on `report-draft`: `turns` for agent tasks, `cards` and `entries` for media tasks; a new + `JobProgressMetric` value, threaded through `TaskDeps`. +- **F4** — retire the stopgap: delete `~/reports/local-reports` and `~/.claude/commands/gen.md`; docs say the repo's + `/gen` is the one. + +**Housekeeping (H):** +- **H1** — parakeet-stitch: rm the temp dir before the pause `process.exit`, plus a start-up sweep of + `parakeet-stitch-*` older than 24 h that no running process holds; then remove today's 21 stale dirs. +- **H2** — the three flaky tests: an isolated temp dir and mtime tolerance; timing slack; wait for the save to settle + before unchecking. +- **H3** — `plans/STATE.md` "Now" rewritten for r27-live and r28; FACTS gains r27's facts (the two-line finding, the ops + ask, delete semantics). +- **H4** — the A7 leftovers: re-check the script against r27's CLI (`prepare --only`), then run it through the editor + (paced captures on the posts queue). +- **H5** — `pnpm ops delete-site {id}` (an adapter over `deleteSiteAction`, refusing a site that has a deployed project + unless `force`); then delete `candalyzer` with it. Channel data untouched; the Candace rule stands. +- **H6** — the hub: `archilyzer publish hub` build and production deploy; read the tombstone probes (plain and busted); + answer release 18's open question 1 in the record. +- **H7** — prune the worktrees whose branches are merged into `main` (branches kept; the unmerged four and + `render-local-sources` untouched); `r27-integration` is replaced by `r28-integration`. + +## Lanes (at most three Opus implementers; worktrees from `r28/integration`) + +- **S0 (orchestrator):** + - `r28/integration` from `main`; + - `plans/release-28.md` committed (this plan); + - test-kit additions: manifests with every field, a fact-check fixture with ruled claims (synthetic); + - H3. +- **Phase 1:** + - lane A: M0 (framework, review, the `final` refusal, badges, narration moved onto it); + - lane B: Q1 → Q2 → Q3 → F2 → F3; + - lane C: M7 bench → H1 → H2 → H5 (code). + - The orchestrator, meanwhile: F4, H4, H7, then H5's delete and H6 once their code and the gates allow. +- **Phase 2 (after M0):** lane D: M1 → M2 → M3; lane E: M4 → M5 → M6; lane F: F1. +- **Phase 3:** + - M9 (one lane); + - M8 once the operator has set the bench bar (the bench results page is the handoff); + - then the gate round and the rollout. + +Prelude and briefs follow r27's (`$T/r27-prelude.md` → `$T/r28-prelude.md`): the test kit, fakes, no real LLM calls in +tests, memory floor, single-spec e2e for lanes, records in this file. + +## Rules that bind every slice + +As release 27: +- no session links or trailers; the Co-Authored-By line alone; +- heavy work through the heavy slot (6 GB floor, one `next build` at a time); +- scratch in the job dir, never `/tmp`; +- no hand edits under `transcripts/**`; +- no yt-dlp, gallery-dl or ASR by hand; +- never print the key or the scrub files; +- Candace data never in fixtures — the M7 bench reads ruled claims locally and commits counts only; +- tests use the S0 fakes; real API calls only in the bench run (≤ $5) and the live smoke (≤ $3). + +## Verification + +- Gates on `r28/integration`: + - `pnpm typecheck`, `pnpm test`, `docs env|files|cli --check`, `settings example --check`; + - the four capped builds; + - `pnpm e2e:all`, plus new specs: `draft-review.spec` (badge, approve/reject, `final` refusal, the no-overwrite + alternative), `media-draft.spec` (each task over the fake LLM and the editor stub), `verdict-bench.spec`, and a + `report-draft` progress assertion. A red is re-run alone; a persistent red blocks. + - privacy counts; the source mirror's check. +- Unit: + - each task's code checks (counts, lengths, ids, dates for flips); + - Q1 (first-person refused); + - Q2 (fragment found, the full sentence offered); + - Q3 (a trimmed view under 8k; one ops call); + - F1 (an `auto` run continues once; caps hold); + - H1 (the pause path leaves no temp dir). +- Live smoke (the operator's key, ≤ $3, through umtool): + - "Draft everything" on a fresh small article; + - each media task on qwen and on Sonnet; + - approve and reject in the review; + - a `final` build refused, then passing after the approvals; + - `out/youtube.txt`; + - an `auto` research run that continues by itself; + - a cancel. +- Housekeeping checks: + - `/tmp` has no `parakeet-stitch-*` after a paused transcription; + - the three formerly flaky tests pass five runs each; + - candalyzer is gone from `/sites`; + - the hub's tombstone probes read ok; + - `pnpm wt list` shows only live worktrees. + +## Rollout + +Fast-forward `main`; editor and umtool build and restart (`~/reports/release-27/scripts` copied to +`~/reports/release-28/scripts`, MERGE and LIVE re-guarded); Claude Code picks up the MCP tools on restart; homepage +source-mirror publish; the hub deploy (H6). No public site changes otherwise. + +## Record + +### S0, as shipped (2026-10-13, orchestrator) + +`r28/integration` from `main` `e8a5f49d`, in the worktree `r28-integration`. + +| Commit | What | +| --- | --- | +| `cc1eca66` | the test kit: `draft/manifests/full` (on-screen, a narrated card, a teaser, `claim` verdicts, threads with a `thread` per clip) and `flips` (one THEN/NOW pair over clips of different dates), hand-written and kept lint-clean by `umtool/report-to-video/fixtures-r28.test.mjs`; `draft/reports/ruled.report.json`, a synthetic fact-check carrying every verdict | +| (this commit) | this plan | + +Gates: common tsc clean; `testing/fakes.test.ts` 10/10; `fixtures-r28.test.mjs` 3/3. + +### M0, as shipped (2026-10-13, lane A, `r28/framework`) + +The draft framework, the drafts review and the final gate, as the orchestrator's eight M0 rulings, with narration +moved onto them. The rulings held as given, with these as built: +- `applyDraft`'s refusals are `operator`, `drafted` (a draft already, no `force`) and `missing` (no such entry, or + flips/threads with no `render.chrome`); a field in the wrong place (narration on a clip) throws. +- A review address's `<task>` is the FIELD's own (`onscreen`, `narrate`, `teaser`, `cut`, `flips`, `threads`, + `youtube`), whichever task drafted it, so a field has one address; narration's is `narrate/<cardId>/narration`. +- A drafted narration follows the drafts gate (a warning in fast, refused in final); one with no mark keeps + release 25's rule in every build. "The narration has a review" is now a narration row in either file, so an + on-screen verdict does not start it. +- Narrate's audit file kept its name, `narration-draft.json`, in the scaffold's shape (`units`, `alternatives`); + `mcp/src/draftTasks.test.ts`'s narrate test reads `units[...]` (two lines, lane B's file) and asserts the mark. +- Badges (ruling 8): the narration page STAYS (it edits and plays the words) and writes the new file; the general + page is `/browse/<project>/review`, linked as **Review drafts — N**. Badges sit in the On-screen table's title + cell, the teaser editor and the narration page. +- "Use this" writes onscreen, lines, narration, flips, threads and publish.youtube; not the cut's order (an order + replaces every entry: the cut task's to apply). A timeline with no `drafted.timeline` is the operator's — M1 + decides what the converter's order counts as. + +| Commit | What | +| --- | --- | +| `e4fe6039` | common: `drafted.mjs` (+ `.d.mts`): the marks, `applyDraft`, `clearEditedDrafts`, `pruneDrafted`, `validateDrafted`, `validatePublish`, review addresses and keys; `tasks/media.ts`, the scaffold (`runMediaTask`); narrate refactored onto it | +| `994fc97b` | umtool: `report-to-video/drafts-review.mjs` (the file, release 25's read unchanged, the gate); the lint and build-video (`--final`, `--drafts-unreviewed`); the driver's `final` passes `--final`; the manifest writer clears an edited draft's mark; `writeDraftedField`; `lib/report/drafts.mjs` and `/api/report/drafts` | +| `1b185182` | umtool: the badges, the alternatives with **Use this**, `/browse/<project>/review` | +| `f281b714` | umtool: e2e `draft-review.spec.ts` and its fixtures; `narration-review.spec.ts` reads the drafts file | +| `da4b123e` | the README's drafts review section, umtool's report-video doc; the scaffold exported from `tasks/index.ts` | +| (this commit) | this record, FACTS "Drafted fields and the drafts review", CHANGELOG | + +Gates (from the worktree root): +- `pnpm -r exec tsc --noEmit`: clean at every commit. +- common: 4018 (2 failing, flaky at the branch's start) → 4029, all pass (+11: `drafted.test.ts` 7, + `media.test.ts` 4). +- `test:scripts`: 863 (+3 skipped) → 874; 869 pass + 3 skipped, 2 failing in `scripts/queue-lock.test.mjs` + (timing, H2's flake) under the full run, 37/37 alone (+11: `drafts-review.test.mjs` 7, `drafted-writer.test.mjs` + 3, `drafts.test.mjs` 1). +- mcp 343/343; editor 288/288. +- `docs env|files|cli --check` and `settings example --check`: clean. +- umtool capped build, corpus linked, through the heavy slot: compiled in 10.2 s (83 s with 50 s waiting for memory). +- umtool e2e, single specs in the foreground: `draft-review.spec.ts` 3/3 (6.9 s; a real offline final build: + refused, approved on the review page, built); `narration-review.spec.ts` + `build.spec.ts` 8 (1 failure: + narration-review read the old file, fixed) then `narration-review.spec.ts` + `onscreen.spec.ts` 10/10; + `timeline-edit.spec.ts` + `undo.spec.ts` 9/9. + +Left for phase 2: the media tasks themselves (M1–M6) on the scaffold; `TaskDeps.progress` (F3) is not wired. +### F4, H4, H6, as run (2026-10-13, orchestrator, phase 1) + +- **F4:** the stopgap retired. Its two remaining runs were already iterations (`piratesoftware-ai-friends` i1, + `api-shondo-recent` i1) and its one video project already copied to `~/reports/articles/piratesoftware-ai-friends/i1`; + no stopgap process alive. `~/reports/local-reports` (74 MB) and `~/.claude/commands/gen.md` deleted; OPERATING.md + says so (`b4d243fc`). +- **H4:** `~/reports/release-28/scripts/a7-fill-media.sh` is the r26 script with the two windows padded by the caller + (release 27 S7: `from`/`to` are the padded window, `pad` provenance). Run through the editor: 38 of 38 X post captures + done (posts queue, paced). Left, needing the operator: the two YouTube windows are unfetchable (both videos "This + video is unavailable"; cited by `deleted` and `nineteenth`), and the two Bluesky posts cannot be captured (the editor + has no Bluesky capture: "Bluesky (public AT Protocol) cannot capture posts"; cited by `polemic-groundbreaking` and + `polemic-onlyfangs`). `reports prepare --article deconstruction-fact-check` and the private homepage compose refuse + on exactly those four. +- **H6:** `archilyzer publish hub --deploy` from `main`: build `0mv7f27h8-98f6fc35` deployed to production + (`archilyzer-hub`), live check ok, nine withdrawn paths read as tombstones. + **Release 18's open question 1, answered:** after a deploy the hub's plain and cache-busted reads return the same new + build (`corpus.json` and all nine tombstones, read by the live check and again by hand), on 2026-10-09 and today. + The served headers carry no `s-maxage`: `corpus.json` is `public, max-age=0, must-revalidate`, the tombstones are + `no-store` (the `_headers` rule). Pages sends neither `cf-cache-status` nor `age`, so the live check cannot record + them. The 7-day edge TTL seen in release 18 is not observed after a deploy. +### Q1, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `03ece497` | `grounding.ts`: `FIRST_PERSON_WORDS`, `firstPersonWords`, `firstPersonProblems`, `THIRD_PERSON_MESSAGE`; `GroundingInput.sources` (`QuoteSource`, `reportQuoteSources`, filled by `groundingInputOf`); `checkNarration` adds each first-person sentence to `hard`; the taste's third-person rule; revise-video's narration op names it; 3 tests | + +- A sentence with I, I'm, I've, I'd, I'll, me, my, mine, myself, we, we're, we've, we'd, we'll, us, our, ours or ourselves outside double quotation marks is a HARD problem: `the narrator is third person (“I've”, “mine”): …`. When the sentence restates a cited quote (grounding's own `closest` match: two shared content words and half the sentence's), the reason names it: `this is the speaker's line from c03 (Bread day @ 0:45), “…”` (the citation's `speaker` when it has one). +- Word-bounded and case-insensitive; curly apostrophes read as straight. Not hits: "Iowa", "myth", "mineral", the all-caps "US". Accepted collateral: "mine" the noun, a roman numeral I. +- narrate needs no change: its grounding call puts the problem in `hard`, so the re-ask, the better attempt and the failing-sentence removal refuse it. videoOps' narration op is refused with it. +- The rule is stated once, in `NARRATION_TASTE` (narrate's prompt reads it). + +Gates: in the lane's totals below. + +### Q2, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `e023db71` | `citations/fragment.ts` (`FRAGMENT_END_WORDS`, `FRAGMENT_MIN_WORDS`, `fragmentOf`, `isFragmentQuote`, `fullSentenceFor`, `fragmentHint`); `checkQuotes` and `strictCheckerOver` refuse a fragment with its sentence; the pipeline extends one in code; revise-report's parent fragments a warning; verify-quotes `fragment`; `WHOLE_SENTENCE_QUOTE_RULE`; REPORT.md; `testing/draft/sweeps/fragment.md`; 8 tests | + +- **A fragment**: fewer than 4 words in the whole quote, or an ellipsis part ending on one of `FRAGMENT_END_WORDS` (the brief's list) without sentence punctuation (. ! ? …). A part ending on punctuation is a sentence whatever its last word. +- **`fullSentenceFor(quote, cues, second, {windowSeconds?, maxWords?})`** → the cues' own words from the quote's first word to sentence punctuation, or to a cue boundary whose next cue starts with a capital (not the pronoun I); unpunctuated, the end of the quote's cue, then one more cue while still a fragment; under 4 words, widened back to the sentence's start. Cap: max(30, quote + 15) words. Null when the quote is not there verbatim or nothing whole fits. The result passes the strict check wherever the quote did. +- **Generated quotes:** `checkQuotes` gives a fragment as a problem (`fragment: {why, part, sentence}`, `why` = `a fragment (ends on “of”): "…" — quote the whole sentence: "…"`), so the sweep agent's repair round is handed the sentence; still a fragment after it, the finding is dropped. The `add` op's checker (`strictCheckerOver`, `fragments: false` turns it off) refuses one with the same words. **sweep-pipeline** replaces a fragment with its sentence from the window in code (≤ 60 words), else drops it (`a fragment (…)`). +- **revise-report:** a fragment the parent already quoted is a warning in the `quotes` check, not a failure (as verify-quotes says of existing reports); one this revision added is dropped as before. +- **verify-quotes:** `fragment` is in `QUOTE_WARNING_STATUSES`; precedence `drift` / `en-orig-drift` > `inexact` > `fragment` > `ok`; the result carries `sentence`. The summary's note names whichever warnings occur. +- A `fragment` from the editor's verify-quotes is not one more problem in `checkQuotes` (its own check is the one). + +### Q3, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `f93ac191` | `structuredPromptEstimate` (llm/structured.ts); `sweepModel` `trimmedNumberedView`, `sectionsNamedBy`, `shortEvidence`; `videoOps` `trimmedCutView`, `chaptersOf`, `chaptersNamedBy`, `entryLine`; revise-report `LOCAL_REVISE_RULES`, `fitLocalAsk`, `localOpsBatch`, `REPORT_OPS_TEXT(origin, local?)`; revise-video's local path; 5 tests | + +- On an ollama model, revise-report and revise-video make ONE `structuredAnswer` (no tools; the rules name none) and apply its ops; the API path is the tool loop and its one-ask fallback, unchanged. +- **The fit:** `fitLocalAsk` builds the user text at a character budget from the model's prompt cap (`promptCapOf` × 3.5) and shrinks it by 15% until `structuredPromptEstimate` — the very messages and format localAnswer sends, counted as `ollamaChat` counts them — is under the cap. +- **The report view:** sections the feedback names first (a title, `section N`, or a finding number in what is left once titles are taken out; seconds and percentages are not finding numbers), then the rest in document order, finding by finding while the budget lasts; shown in document order; a section's left-out findings named (`(findings [96]–[100] not shown)`). Quotes over 12 words cut to 8 and `…`, links cut to their labels — in the view only; ops number against the whole document. +- **The cut view:** every entry listed in timeline order; the chapters the feedback names (an entry id, a card heading, `chapter N`) in full first, the rest while the budget lasts, else `- clip c07 (not shown in full)`; citations the feedback names first, then the rest, with the count left out. +- Unit, against fakeOllama: a 45k-character report's view under the 8k estimate, one request, the named section in full, the op landing on finding 220 of the whole document, links whole in the report; the cut's one batch. + +### F2, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `c9e99c51` | `report-draft {extractorModel}` (`REPORT_DRAFT_BODY_KEYS`, `parseReportDraftBody`, `isKnownApiModel`); the route's comment and the ops help; COMMANDS.md; the MCP's `generate` argument; umtool `ExtractorSelect` / `extractorBody` on `/articles/new`, Copy with model and a research continuation; `DRAFT_KEYS`; editor unit 2, MCP checks, umtool `article-new.spec` | + +- `extractorModel` is a sweep's (`task: "sweep"`, a copy of one or a research continuation included) and a Claude model id the price table knows (`isKnownApiModel`: a `PRICES` key, or a dated id of one). It replaces `settings.generation.models.extractor` for that job. On a sweep whose model is local it is unused and the answer carries a warning. +- The MCP's `generate` checks it (a sweep's, `claude-…`) and passes it through. +- umtool shows the extractor only beside a sweep on a Claude model and sends it only when it is not the policy's (so the bodies its specs pin are unchanged). + +### F3, as shipped (2026-10-13, lane B, `r28/quality`) + +| Commit | What | +| --- | --- | +| `48dbc5de` | `JobProgressMetric` `turns` / `cards` / `entries`; `TaskProgress`, `TaskDeps.progress`, `TaskHandle.progress`; `reportDraft.ts` wires `setProgress`; sweep-agent, revise-report, revise-video and research report turns, sweep-pipeline entries; the editor's bars label them; editor unit, MCP and `report-draft.spec` assertions | + +- `TaskDeps.progress?(p: {metric: "turns" | "cards" | "entries"; current: number; total?: number})`; a task calls `h.progress`, which never throws into it. The job maps it to `{metric, initial: 0, target: max(total ?? current, current), current}` — the runner's own `current`, as fetch-windows' clips. +- Agent tasks report every model turn against their turn cap (sweep-agent 150, the repair round counted on; revisions 30; research 60); a local revision's one batch is 1/1; sweep-pipeline reports the recordings gone through of its worklist (`entries`, from 0). The media tasks (narrate, phase 2's) are not wired here. +- `common/views/jobRowView.ts` imports the union (no re-spelling to change); `JobProgressBars.tsx`'s three records gained the metrics (Model turns ⇄, Cards ▤, Entries ≡). + +**Lane B's gates** (at `48dbc5de`; counts at the branch start → the tip): +- tsc clean (all packages) before every commit. +- common 4018 (1 failed at the start, not reproduced at the tip) → 4031/4031 (13 new); mcp 343 → 346/346; editor unit 288 → 290/290; `test:scripts` 860 + 3 skipped → 860 + 3 skipped. +- `docs cli|files|env --check`, `settings example --check`: clean. +- Editor build: the e2e prebuild's capped `next build` (heavy slot, 5 GB) at `48dbc5de`, clean. +- e2e `report-draft.spec.ts` (editor suite, alone): 3 passed, 0 failed, 17.8 s wall (after 40 s in the queue). +- umtool e2e `article-new.spec.ts` + `article-iterations.spec.ts`: 7 passed, 0 failed, 44.8 s (its prebuild's capped `next build` 35 s, clean). + +Not done here: the MCP's `sweep_plan` / `ask_plan` text (Claude Code's own /sweep) does not state `WHOLE_SENTENCE_QUOTE_RULE` (`mcp/src/instructions.ts` is not this lane's; one line where the claim-quotes and verbatim rules are). + +### Phase 1 merges (2026-10-13, orchestrator) + +`r28/framework` (M0) merged `172d07ae`; `r28/quality` (Q1–Q3, F2, F3) merged `900671ae`; `7e14a060` adds lane B's +`WHOLE_SENTENCE_QUOTE_RULE` to the `/sweep` plan's extractor directive (`mcp/src/instructions.ts`). Gates at +`7e14a060`: tsc clean; common 4041/4042 — `fetchPosts.test.ts` "a drain mid-page waits for the page's cursor…" failed +once under load and passes 3/3 alone (a flake candidate); mcp 346/346; editor 290/290; `test:scripts` 871 + 3 skipped. +### M7, as shipped (2026-10-13, lane C, `r28/bench-house`) + +The verdict bench: ruled fact-check claims asked of models one claim per call, scored against the operator's rulings. + +| Commit | What | +| --- | --- | +| `dc21f2c8` | `common/lib/report/draft/bench/` (`items.ts`, `prompt.ts`, `score.ts`, `store.ts`, `run.ts`, `index.ts`, `bench.test.ts`); `controller/benchVerdicts.ts`; job kind `bench-verdicts`; `POST /api/ops/bench-verdicts` (+ `_benchVerdicts.test.ts`); the ops ACTIONS row and help; `archilyzer reports bench-verdicts` (`bin/reports-bench-verdicts.ts` + test); `settings.generation.verdicts`; COMMANDS.md, SETTINGS.md, settings.json.example | +| `c31bedd0` | umtool `/bench` (`app/bench/page.tsx`, `components/bench/BarForm.tsx`, `lib/bench.ts`, `/api/bench/bar`), the `/articles` link; e2e `verdict-bench.spec.ts` + `fixtures/bench-fixture.mjs` | +| (this commit) | the records, FACTS, CHANGELOG | + +- **Items:** every claim of a `kind: "factcheck"` article (the registry's `listArticleDirs` / `articleFile` / `parseReport`) + with an operator `verdict` and a span citation whose recording has cues within ±`window` s (default 60) of the cited + span; overlapping windows of one recording merged. The rest are `skipped` with a reason (`no operator verdict`, `no + citation`, `no video or audio citation`, `no cited recording has cues around the cited seconds`). An item carries the + claim text, its quotes and windows, and the verdict (the answer key); `findings`, `gist`, `flag` and `title` are + never copied, and the prompt never reads the verdict. +- **The call:** `structuredAnswer` with `{verdict: VERDICTS enum, reason}`; the system prompt is the five verdicts' + meanings and "judge only the transcript shown" (no example); the reason is cut at 300 chars in code. A local prompt + is held under 7 800 estimated tokens (the client's 8k less a margin) by dropping the cues farthest from a cited span + first; the claim and quotes are never trimmed. +- **Where it runs (decided here):** not a `report-draft` (no iteration, no task) — a job of its own, `bench-verdicts`, + in the editor, because the GPU arbiter's holds are in-process there: any local model puts the run on `draft:local` + with `llmConfigOf(…, {onLog, signal})` (every ollama call through `gpuGatedFetch`) and ollama is unloaded at the end; + API-only runs go on `draft:api`. Calls are sequential. The day's cap refuses an API run at the ask and at its turn; + its spend is appended to the usage ledger (`task: "bench-verdicts"`). The CLI is `--dry` (offline, read only), + through the editor (`pnpm ops bench-verdicts`, the default), or `--here` (in process, API models only). +- **The cap:** `maxUsd` (default 5, refused above 50) for the whole run, resumed spend included, checked before each + API call against the spend so far plus that call's estimate; past it the run ends `capped` with what it did. A model + with three errors in a row is stopped and the run goes on. +- **Scoring (pure):** agreement (a failure counts as a miss), agreement with PARTLY ~ CORROBORATED, the 5×5 matrix (rows + operator) plus each row's unanswered, recall for CONTRADICTED, NOT_FOUND, PARTLY strict and adjacent, cost, latency + (mean, median, p90), parse failures and errors; the always-CORROBORATED baseline scored the same way. `passesBar`: + strict agreement and the two recalls (a recall with nothing ruled that way is not a miss). +- **Results:** `.generation/bench/verdicts/<run>/{items.jsonl, results.jsonl, summary.json}`, gitignored (`/.generation/`), + every write atomic and whole; the same `--run` resumes (answered pairs skipped, failures asked again). +- **umtool `/bench`:** the run picker; a tile per model and the baseline; the bar form (writes + `settings.generation.verdicts {bar, models}` whole through the editor's settings action; a model failing the typed bar + cannot be ticked); the confusion matrices; the items, disagreements first, filtered by model and by the operator's + verdict; the skipped list. Zero client JS but the form. Linked from `/articles` ("verdict bench"), the nav unchanged. +- **Labels (contracts):** link `verdict bench`; regions `models`, `the bar`, `confusion`, `items`; tables `confusion + <model>`; form `bar` with spinbuttons `minimum agreement`, `minimum CONTRADICTED recall`, `minimum NOT_FOUND + recall`, checkboxes `use <model>`, button `Save the bar`, status `Saved.`; attributes `data-bench-run`, + `data-status`, `data-model`, `data-pass`, `data-metric`, `data-cell`, `data-item`, `data-disagree`, `data-run`. + +**The real run (the orchestrator's):** + +``` +pnpm archilyzer reports bench-verdicts --models claude-sonnet-5-5,claude-opus-5-5,qwen3:8b --max-usd 5 --run vb-r28 --wait +``` + +through an editor that has this branch (the route is new). Its `--dry` over the registry (read only, 2026-10-13): 147 +items from 2 fact-checks, 44 claims skipped (23 no operator verdict, 12 no citation, 9 no video or audio citation); +ruled CORROBORATED 78, PARTLY 58, NOT_FOUND 6, CONTRADICTED 4, UNTESTABLE 1; estimate Sonnet 5.5 ~$1.29, Opus 5.5 +~$2.57, qwen $0 — ~$3.86 in all. With 4 CONTRADICTED and 6 NOT_FOUND items the two recalls move in steps of 25% and +17%. + +### H1, as shipped (2026-10-13, lane C, `r28/bench-house`) + +| Commit | What | +| --- | --- | +| `66fd4a04` | `scripts/parakeet-stitch.mjs`: the pause path breaks out of the window loop and exits after the `finally`; the start-up sweep; `main()` only as a program; `scripts/parakeet-stitch.test.mjs` (3) | + +- **The sweep:** a `parakeet-stitch-*` dir in the tmpdir older than 24 h (its mtime; a running run's dir changes with + every window) is removed unless held. **Chosen: an owner file** (`owner.json`: pid and that process's start time from + `/proc/<pid>/stat`, so a reused pid is not the owner), written at creation. A `/proc` scan of open files and cwds alone + would not do: a run holds nothing in its tmp dir between two windows. A dir with no owner file (today's stale ones) is + held while any other parakeet-stitch process runs (its cmdline), or while any process has a file or its cwd in it. +- Unit: the pause path (a fake parakeet-cli sends the SIGTERM mid-window) exits 0 with the window kept and no temp dir + left — red against the old script; the sweep removes an old unheld dir and keeps an owned, a held and a young one. +- The 21 live stale dirs in `/tmp` are the orchestrator's to remove after merge. + +### H2, as shipped (2026-10-13, lane C, `r28/bench-house`) + +| Commit | What | +| --- | --- | +| `4e941835` | the three flakes | + +- **`relocateChannelMedia.test.ts` "reconcile: an extra and a changed file":** each test already has its own + `mkdtemp`; the cause was a directory mtime. Writing `stale.json` moved the target's `v1/` mtime, and when the setup + crossed a second boundary rsync (whole seconds) itemized `.d..t v1/` as a third difference. Both trees' directory + mtimes are pinned now. Proved with a forced 1.1 s delay: red before, green after. + - Found, not changed (not this lane's file): `relocateDir.ts` `diffTrees` reports a directory-mtime-only line as + "changed" in the reconcile sentence, which the verify (`DIR_MTIME_ONLY`) already ignores. +- **`queue-lock.test.mjs` `--with` (:792), and "two weighted jobs" (:632), red in this branch's first run:** fixed holds + (700 ms, 1500 ms) raced the next run's start under parallel test files. The holding runs wait on a gate file the test + opens once what it checks has happened (capped at 20 s, so a wrong admission still fails the order assertion). +- **`backfill.spec.ts` (:516):** the lane is unchecked only once the first save has settled on the page ("Saved.", the + button back, nothing unsaved, still checked), and the second save is seen to settle before the lane is polled. +- Five runs each: `relocateChannelMedia.test.ts` 44/44 ×5; `queue-lock.test.mjs` 37/37 ×5; `backfill.spec.ts` 22/22 ×5 + (1.8, 1.8, 2.0, 1.3 and 0.7 min). + +### H5, as shipped (code) (2026-10-13, lane C, `r28/bench-house`) + +| Commit | What | +| --- | --- | +| `8b11cb7d` | the plan and the delete, `POST /api/ops/delete-site`, the ACTIONS row and help, COMMANDS.md, the unit test | +| `ebf9e60d` | moved to `common/publish/siteDelete.ts` (the architecture test: controller/ may not import publish/) | + +- **The survey — what a site leaves on disk:** `sites/<id>/` (site.json with its pool, tags.json, charts, reports with + their history-git), `export/.export-builds/<id>/` (built.json, deployed.json, out/, a docker build's public/ and + .r2-staging/) and `export/.export-index/sites/<id>/` (report media and exports, summaries, stats). Nothing else names + a site by id: channel membership is site.json's own pool, the hub lists the sites on disk with a siteUrl, and curated + tags' per-site file is in the site dir. +- **Plan, then apply** (as release 27's `reports delete`): `dryRun` answers the plan. Removed: the three directories. + Kept: every channel's data, the Pages project and what was deployed (a delete does not undeploy), a deployed hub until + rebuilt, `export/out` when it links into the site's bundle. Refused unless `force`: a `cloudflareProject`, a deploy + in deployed.json (production, a preview, local), reports of its own. Refused, force or not: no such site (404), a + site dir that is a link, a publish stage running (a live publish-lock holder). +- **The delete:** the publish lock taken without waiting (1.5 s; a stage that started refuses), the site.json lock, + the plan made again, each directory renamed aside to `.deleting-<id>-<stamp>`; the bulk removed after the locks. +- The editor's Danger → Delete (`deleteSiteAction` → `deleteSite`) is unchanged: it still removes `sites/<id>/` alone. +- **The candalyzer plan** (read only, 2026-10-13): not refused, 3 paths, 7 772 files, about 2.7 GiB. The orchestrator + runs `pnpm ops delete-site --json '{"id":"candalyzer"}'` after merge (a `dryRun` first). + +### Lane C gates (2026-10-13) + +- tsc clean (all packages) at every commit. +- Unit, at the branch's start → at its tip: + - common 4017 of 4018 (1 red: "a drain mid-page waits for the page's cursor", not this lane's; green since) → + 4034/4034 (16 new: `bench.test.ts` 8, `reports-bench-verdicts.test.ts` 3, `siteDelete.test.ts` 4, the verdicts + settings 1); + - editor 288 of 289 (1 red: `whisperFromContainer.test.ts`, not this lane's; green since) → 291/291 (3 new: `_benchVerdicts.test.ts`); + - `test:scripts` 858 pass, 2 red (the queue-lock pair H2 fixed), 3 skipped → 864 pass, 0 red, 2 skipped (3 new: + `parakeet-stitch.test.mjs`); + - mcp 343/343 (not touched). +- `docs env|files|cli --check`, `settings example --check`: clean. +- Builds (heavy slot, 5 GB cap): umtool 31 s with the corpus linked for the build only and removed (`/bench`, + `/api/bench/bar`); umtool's e2e start build 29 s; the editor's e2e start build 57 s at `66fd4a04` + (`/api/ops/bench-verdicts`); the editor at `ebf9e60d`, 123 s (`/api/ops/bench-verdicts`, `/api/ops/delete-site`). +- e2e: umtool `verdict-bench.spec.ts` 2/2, 14.2 s; editor `backfill.spec.ts` 22/22 five times (above). + +### Lane C merge and H1's clean-up (2026-10-13, orchestrator) + +`r28/bench-house` merged `8cd383dd`. Gates there: tsc clean; common 4058/4058; mcp 346/346; editor 293/293; +`test:scripts` 874 + 3 skipped, 0 failed. H1's leftovers: the 16 `parakeet-stitch-*` dirs left in `/tmp` (176 MB of the +RAM tmpfs; 5 had gone since the survey's 21) were removed with no parakeet-stitch process running and no process holding +a file in them. The real verdict bench runs once, after the rollout, through the live editor (`bench-verdicts` is a new +route, and qwen needs the editor's GPU arbiter); its results land in the primary checkout's `.generation/`. +Lane C's leftovers: `relocateDir.ts` reports a directory-mtime-only difference as "changed"; the editor's Danger → +Delete still removes only `sites/<id>/` (M9 routes it through the plan-first delete). +### F1, as shipped (2026-10-14, lane F, `r28/research-f`) + +An `auto` research run continues into its sweep by itself once its acquisitions settle. + +| Commit | What | +| --- | --- | +| `7739bce5` | `controller/researchAutoContinue.ts`: `maybeAutoContinue`, `scanAutoContinue`, `armResearchAutoContinue` / `researchAutoContinueTick`; `onJobEnd` in `jobs/registry.ts`; `researchRuns.ts` watches an `auto` run's pending jobs (`watchResearchJobs`, `takeWatchedRun`) and its view carries `autoContinue`; `AutoContinueRecord` in `research/state.ts`; the heartbeat's call; the editor arms it below the idle gate (`_autoContinue.ts`); 6 tests | +| `526261f1` | umtool: the research queue says "continued automatically by iN", or why not; the editor stub continues an `auto` run as the editor does; `article-research.spec` asserts it | +| `a3084416` | OPERATING.md's research section, the `autonomy` field doc and SETTINGS.md, research-approve's help and COMMANDS.md | +| `62f732d3` | a site build's end runs the scan too (`SCAN_ON_END`), so a held run continues after the rebuild; 1 test | +| (this commit) | this record, FACTS "Release 28 F1", CHANGELOG | + +- **Who continues by itself:** autonomy `auto` only. `propose` and `limits` are continued by the operator, as in r27. +- **When:** the run is done; nothing waits for a yes or no; every acquisition job has ended (done, failed or + cancelled); it is not continued already. +- **The once-only mark** is a claim taken under the article store's lock (`updateIteration`'s function patch), so a + heartbeat and a job end racing continue once. A claim is fresh for 10 minutes. A stale claim whose sweep exists is + recorded as the continuation, not made again. +- **What it asks:** Continue's own path, `report-draft {task: "sweep", iteration: n, model, channels}`. + - The model is the research run's own (the brief's "the run's model/route"). The umtool button still defaults to the + sweep route's. + - The per-job cap is `caps.sweep`; the daily cap is checked first, again at the ask, and again at the job's turn. + - A daily-cap refusal, like any refusal of the ask, is recorded as `refused` and tried again only on a later UTC + day. +- **Builds:** a channel in no composed build is left out. The warning `not in any build yet: <slug> — rebuild the site + and continue again` is on the run's record and is a failed `unbuilt channels` check on the sweep. With nothing left, + the run is `held` (nothing enqueued) until a build newer than the hold, or a later day. +- **Triggers:** + - the registry's new `onJobEnd`: a watched acquisition job's end continues its run; the end of a `report-draft` job + (the research job's own) or a site build runs the scan; + - the scan: on the heartbeat (`fire`, after the tick) and once at boot. + - The editor arms both in `instrumentation.ts` below the idle gate, and `armResearchAutoContinue` refuses an idle + boot itself. +- **On the run:** `research.autoContinue` (status, at, by, reason, warnings, day, buildsAt) in `iteration.json`, an + `auto-continue` line in `turns.jsonl`, `ResearchView.autoContinue` in research-approve's answer, and umtool's + queue line. +- **Found:** the editor's heartbeat is off by default (`syncScheduler.heartbeatSeconds` 0; the live `settings.json` + says 0). Live, the triggers are the job ends and the boot scan. A refused run is retried the next day only when a + report-draft or site-build job ends, the editor restarts, or a heartbeat is configured. +- **No change to `reportDraft.ts`:** the continuation is asked from code through `enqueueReportDraft`, and the daily + cap is pre-checked with `generationUsage`'s exports. No settings key was added; the `autonomy` doc says what `auto` + now does. + +Gates (from the worktree root; counts at the branch start → the tip): +- tsc clean (all packages) before every commit. +- common 4042 → 4049/4049 (7 new, `controller/researchAutoContinue.test.ts`, five runs each clean); editor unit + 290 → 290/290; mcp 345 of 346 at the start (1 failure, "a real editor that stops answering a poll hands back the + job", not reproduced since) → 346/346; `test:scripts` 870 + 3 skipped, 1 failure at the start (`queue-lock`, H2's + flake) → 871 + 3 skipped, 0 failed (874; the count unchanged, the failure not reproduced). +- `settings example --check`, `docs env|files|cli --check`: clean. +- Editor build (heavy slot, 5 GB cap): clean in 52 s. +- e2e, single specs in the foreground: + - umtool `article-research.spec.ts` 3/3 (31.2 s; its prebuild's capped build 29 s), the new auto-continue test included; + - umtool `article-iterations.spec.ts` + `article-new.spec.ts` 7/7 (40.6 s); + - editor `report-draft.spec.ts` 3/3 (19.2 s; its prebuild's capped build 48 s), with the new boot arming in its server. +### M4, as shipped (2026-10-14, lane E, `r28/media-e`) + +The flips draft (`flips`): THEN/NOW pairs over the cut's clips, `render.chrome.flips`. A step on a done iteration on +M0's scaffold, one unit (the whole field), replacing step 0's "not implemented" refusal. +- **The model** proposes pairs: a topic, two clip ids, and optionally a part of each clip's quote. Rules, no example. +- **Code** does the rest. It dates each clip: the entry's `date` (the operator's, what the header shows), else the + corpus record's `uploadDate` (`get_video_metadata`), else the citation's `date`. The earlier is THEN, whichever + way the model named them, and a pair of one day is refused. Each `when` is written from the date (`Jan 2026`). + A side's `words` is the clip's quote verbatim, or the model's part of it only when the quote says exactly that, + cut at a word to 110 with `…`. The pair id is the topic slugged. Code refuses unknown ids, a clip in two pairs, and + more pairs than `min(24, dated clips / 2)`. The topic is one line of at most 32 characters, grounded by + `checkLine`. +- **Order:** a THEN that plays after its NOW is refused, unless `ownerOf(timeline)` is `"drafted"` and the flips + will be applied. In that case the two clips swap places, and the timeline is written through `applyDraft` with the + flips provenance. A twin id refuses the swap. +- **The build's validators:** `validateFlips` and `validateFlipEntries` run on the cut as it will be, swaps + included. To make that possible they moved to common, as `common/lib/report/panels.mjs` (see M5). The repair keeps + the attempt's pairs that pass when one fails. +- **One left panel (the simplest correct rule):** a cut with threads is refused, unless `force` and the threads are + a draft. In that case the flips replace them: the list, every clip's `thread` and the mark are removed, and the log + says so. Operator's threads are refused even with `force`. A cut with no `render.chrome` is refused. +- Test kit: `draft/runs/flips.json`. Run over the full manifest with its threads taken off: the first answer is + refused (a pair of one day, a number the report lacks) and re-asked. The kept answer reproduces S0's flips manifest + pair, id aside. + +### M5, as shipped (2026-10-14, lane E, `r28/media-e`) + +The threads draft (`threads`): `render.chrome.threads.list` and each clip's `thread`. +- **The model** names the threads (`{id, label}`) and gives each clip a thread or `""`. +- **Code** checks the result: + - 2 to 4 threads (`THREADS_TASK_COUNT`); + - ids are slugged when invalid, and none is listed twice; + - labels are one line of at most 32 characters, grounded; + - every assignment names a clip of the cut and a listed thread, and no clip is in two threads; + - every thread has a clip; + - `validateThreads` and `validateThreadEntries` pass on the cut as it will be. +- **The outcome is code's:** the `claim.verdict` that the thread's last clip (in timeline order) carries in the + manifest, when it has one. The model never writes a verdict. +- **Applied:** `applyDraft(render.chrome.threads, {list})`, then every clip's `thread` is set, and removed from a + clip in no thread. The repair drops failing threads with their clips when two still stand. +- **Mirror of M4:** a cut with flips is refused unless `force` and the flips are a draft, which the threads then + replace. +- **`common/lib/report/panels.mjs`** is now the one copy of the flips' and the threads' limits and validators. + umtool's `flips.mjs` and `threads.mjs` re-export them unchanged (their tests, deck, lint and fixtures-r28 pass + unchanged). +- Test kit: `draft/runs/threads.json`. The first answer is refused (a label naming someone the report does not, a + thread with no clip). The kept answer: bakery CONTRADICTED (c07), contest NOT_FOUND (c06). + +### M6, as shipped (2026-10-14, lane E, `r28/media-e`) + +The YouTube draft (`youtube`), `out/youtube.txt`, and umtool's panel. +- **The task** writes `publish.youtube {title, description}`: a title of one line, at most 100 characters, and one + summary paragraph of at most 900 (`YOUTUBE_SUMMARY_MAX`, room under `validatePublish`'s 5000). Both are grounded + by `checkLine(…, {quotes: true})`: + - names and numbers come from the report and the cut's title and subtitle; + - no stock phrase; + - third person (Q1's `firstPersonProblems`); + - words in quotation marks only when a cited quote says them word for word; + - no links, timestamps or hashtags. + The repair drops a failing sentence of the summary when the title is clean and something is left. +- **`out/youtube.txt`** is composed by code (`umtool/report-to-video/youtube.mjs`, pure; exported + `umtool-report-to-video/youtube`): + - the title, a blank line, the summary; + - `Chapters` from the build's own chapter list: `muxChapters` now returns `{chapters, total}`, the list it muxed; + - `Sources`: a moment link per cited clip, in cut order, each once — `citeUrl`, else the archive's page at + `cite`. +- **Chapters follow YouTube's rules** (ruled here): the first at 0:00, at least three, each at least ten seconds. A + shorter one is folded into the one before it. A list that still falls short, or does not start at 0:00, is left + out, and the build's `youtube` event names why. +- **When it is written:** after every chapter mux (the full build, the deck build, `--rail-only`, + `--chapters-only`), and under `--no-chapters` without the block, whenever the manifest has a `publish.youtube` + title. The file is `youtube-<variant>.txt` for a variant other than `sourced`, as the mp4 is named. +- **umtool:** `YoutubeSection` on the project page shows `out/youtube.txt` (its age; a note when `publish.youtube` + changed since), else the same text composed without chapters (`youtubePreview`), with **Copy** and "drafted by + <model>". Nothing when neither exists. M9 does "Draft with". +- Test kit: `draft/runs/youtube.json`. The first answer is refused (speaks as the speaker, a link). The editor's + `_reportDraft.test.ts` runs a youtube step through the job (step 0's "not implemented" case is now this). + +| Commit | What | +| --- | --- | +| `e4dff898` | `common/lib/report/panels.mjs` (+ `.d.mts`, package export), flips.mjs and threads.mjs re-export it; `report-to-video/youtube.mjs` + `youtube.test.mjs` (6); `muxChapters` returns its list; `writeYoutubeText` after every chapter mux; the `youtube` event | +| `2d97a52c` | `tasks/clipEvidence.ts` (`clipFacts`, `isoDay`, `whenOf`, `checkLine`), `tasks/flips.ts`, `tasks/threads.ts`, `tasks/youtube.ts`, the dispatcher; `panelTasks.test.ts` (10); runs `flips` / `threads` / `youtube`; the MCP's end-to-end tests (3); the editor's report-draft youtube step; the kit README | +| `f4884f7f` | umtool `YoutubeSection` on the project page; e2e `media-draft-e.spec.ts`, `fixtures/youtube-fixture.mjs` | +| `45355fb8` | report-to-video README: the drafted panels, `publish.youtube` and `out/youtube.txt` | +| (this commit) | these records, FACTS "Release 28 lane E", CHANGELOG | + +Lane E's gates (from the worktree root, at `45355fb8`; counts at the branch's start `381156ae` → its tip): +- tsc clean (all packages) before every commit. +- common 4059 → 4069 (+10, `panelTasks.test.ts`); 4068 passed, 1 failed: `fetchPosts.test.ts` "a drain mid-page + waits for the page's cursor…", the phase-1 flake candidate, 8/8 alone. +- mcp 346 → 349/349 (+3); editor 295/295 (one test rewritten, none added); `test:scripts` 874 + 3 skipped → + 880 + 3 skipped (+6, `youtube.test.mjs`). +- `docs env|files|cli --check`, `settings example --check`: clean (nothing regenerated). +- umtool e2e, single specs in the foreground: + - `media-draft-e.spec.ts` 1/1 (5.0 s; a real offline fast build: three chapters, two folded, and the sources); + - `draft-review.spec.ts` + `report-narration.spec.ts` 6/6; + - `projects.spec.ts` + `build.spec.ts` 29/29. + - Each run's prebuild was umtool's capped `next build`, 29 s. +- umtool capped build, corpus linked, through the heavy slot (5 GB): ok, 29 s with 8.5 GB available; the link removed. + +Found and left: +- `checkLine` does not check a line's FIRST word as a name. It is the narration grounding, which skips each + sentence's first word, so a topic, label or title starting with an unknown name passes that check. The tests use a + name mid-line. +- "Use this" on a threads alternative writes the list alone (M0's `writeDraftedField`), not the clips' `thread` + keys the draft assigned. A threads alternative arises only when the operator's threads are forced over, and its + Use this may then leave clips naming the operator's old ids, which the build refuses. +- The media tasks report no progress in this branch. Lane D's scaffold change (`h.progress` per unit, + `progressMetric`) covers these three once merged; they set no `progressMetric` (default `entries`). +- umtool's editor stub answers a media step only for `narrate` (any other task makes a new iteration in the stub). + That is M9's to extend with its buttons. + +### Phase 2 merges (2026-10-13/14, orchestrator) + +`r28/research-f` (F1) merged `165e766d` (gates: common 4065/4065, mcp 346, editor 293, `test:scripts` 874 + 3 skipped); +`r28/media-e` (lane D's step-0 wiring `ea4e9072`, then M4–M6) merged `f7b8dae9` (common 4076/4076, mcp 349, editor 295, +`test:scripts` 880 + 3 skipped; `docs cli --check` clean after regenerating COMMANDS.md). Rulings on the lanes' +questions: F1 continues only `auto` runs, on the research run's model, and needs no timer of its own while the live +heartbeat is off (an acquisition job's end is the trigger); lane E's first-word name check stays as built; a threads +alternative's "Use this" carries the clips' assignments (M9). M9 (lane G, `r28/surfaces`) started from `f7b8dae9` +beside lane D. +### Media wiring, as shipped (2026-10-13, lane D, `r28/media-d`) + +Step 0: the six new media tasks are steps, as narrate was, through one list. Committed first and alone (`ea4e9072`); +lane E branched from it. +- `MEDIA_STEP_TASKS` (`narrate, cut, onscreen, teaser, flips, threads, youtube`) and `isStepTask` in + `generationSettings.ts` are the one list. `GENERATION_TASKS` and `TASK_NAMES` contain them. Every `=== "narrate"` + step check asks `isStepTask`: the controller's body, enqueue, job and usage row; the MCP's step lookup and wording; + the ops row; the route's doc. +- **Routes:** each new task takes narrate's route in every preset (`balanced`: local). +- **A settings file from before:** one that routes release 27's first four tasks keeps its preset. A task it does not + name takes that preset's route; S11's research rule is generalised. A partial patch names no preset. +- **The body** of a media draft is `{task, article, iteration, model?, entries?, force?}` (narrate's `cards` kept). It + is refused as narrate's is: no iteration, a `copyOf`, `entries` on a non-step task. Its cap is a narration's. +- The tasks not yet built refused at the job as a failed step, "not implemented in this build". All six are built + now, and the refusal is gone at the merge. +- umtool's generate forwards `entries`. +- SETTINGS.md, settings.json.example and COMMANDS.md regenerated. + +### M1, as shipped (2026-10-13, lane D, `r28/media-d`) + +The cut task (`cut`): which of the report's citations the video keeps, and in what order. It is one unit, the +timeline's ORDER (`drafted.timeline`). +- **Candidates** (`cutCandidates`): each clip or still whose id is a report citation (the converter's rule), else the + video citation of its recording and second. The model sees them by the chapter they sit in, with: + - each claim's text and verdict; + - the source and date; + - the quote, shortened step by step until the local prompt fits (`fitLocalAsk`). +- **The answer** is citation ids grouped under the section headings. +- **Code refuses:** + - an id not a candidate; + - an id twice; + - more than `settings.generation.cut.maxClips` (new; default 20; a whole number from 3) or fewer than 3; + - a dropped clip a post rides on or a flip names (`pinnedEntries`); + - a heading not the cut's, or one heading two groups; + - any error the build's own validators (`lint.mjs` `validatorErrors`) give the built cut that the cut as read did + not have (compared with timeline positions taken out). A thread left with no clip is caught this way. +- **Code builds the timeline** (`buildCut`), never inventing an entry: + - the chosen entries, untouched, with variant twins together; + - a chapter card where its group keeps an entry; a card with nothing left is dropped (S7's rule); + - everything before the first chapter or citation entry first, and everything after the last one last (the + teaser); + - an entry no citation names stays with its chapter, after its card. +- **The build's validators** reach a common task through `TaskDeps.deckChecks` (`tasks/deckChecks.ts`): umtool's + `deck.mjs` and `lint.mjs`, loaded natively from the checkout (`import(/* turbopackIgnore: true */ …)`). The editor + job passes `loadDeckChecks(paths.monorepoRoot)`. The editor's e2e proves it in the built server. +- **The ruling on lane A's question, as built:** + - `reportToManifest` marks its timeline `drafted.timeline {task: "convert", model: "code", at, attempt: 1}`, `at` + the day it was made (`today`). The kit's derived manifests were regenerated. + - An unmarked timeline whose clip order is exactly the converter's from the project's report is code's too + (`isConverterOrder`). + - A code-made order is drafted over without `force`. The cut's `apply` gives an unmarked one the converter's mark + first, then writes through `applyDraft`. One marked by a model needs `force`. Any other is the operator's: its + draft is kept as an alternative. + - `isCodeDraft` (drafted.mjs): `draftsReviewRows` leaves a code mark out, so there is no row, no badge and no + final-gate error. umtool's "Review drafts — N" count leaves it out too. These are lane A's files; the change is + additive, a filter and an import each. + - An operator's reorder in umtool clears the mark as any edit does. +- **The scaffold** (`media.ts`, additive): + - `spec.owner`, who owns a unit's field for the skip. The writer is still `applyDraft`. + - `spec.batch` (M2). + - Progress: `h.progress({metric: spec.progressMetric ?? "entries", current, total})` at 0 and after each ask. + Narrate's metric is `cards`. Lane E's three get `entries` for free. + +### M2, as shipped (2026-10-13, lane D, `r28/media-d`) + +The on-screen task (`onscreen`): each clip's `onscreen.{title, subtitle}`. One unit per clip entry (or the `entries` +asked for). +- **Evidence:** the report's title, the clip's section, its claim (text, verdict), its quote and source. +- **Batches:** several clips per ask (`spec.batch`) — as many as fit the local prompt cap measured by + `structuredPromptEstimate`, at most `ONSCREEN_BATCH_MAX` (8). The re-ask carries only the clips refused, with each + one's reasons. +- **Code refuses:** + - a title over 60 characters or a subtitle over 90; + - more than one line; + - a title with any quotation marks (an apostrophe is not one); + - a subtitle quoting anything but the clip's own quote, word for word (`strictNormalize`, whole words), or with + marks that do not pair up; + - a name or number the clip's evidence lacks; + - the first person outside a quotation (Q1's `firstPersonProblems`). +- **`grounding.ts` `groundedProblems(text, reference, where)`:** the names and numbers check `checkNarration` ran + inline, now one function that both use. The wording is unchanged for narration. + +### M3, as shipped (2026-10-13, lane D, `r28/media-d`) + +The teaser task (`teaser`): a teaser's `lines`. One unit per teaser entry. +- **A cut with no teaser** gets one: `{type: "teaser", id: "teaser"}` (else `teaser-2`, …) after its last clip, its + lines written through `applyDraft` as an empty field. Nothing is added when the draft is refused. +- **Evidence:** the report's title and subtitle, section titles, claim gists (`claimGist`: the quoted words taken + out), and the months its sources and clips are dated. +- **Code refuses:** + - fewer than 3 or more than 5 lines; + - a line over 70 characters, or on two lines; + - quotation marks; + - a run of 5 words from any quote; + - a name or number the evidence lacks; + - anything `deck.mjs` `validateTeaser` refuses (the row each role fits: overline, title, kicker). Without that + check (no `deckChecks`), nothing is written. +- **The prompt** states each role's fit as a rule; the check is the build's. + +| Commit | What | +| --- | --- | +| `ea4e9072` | step 0: `MEDIA_STEP_TASKS`, `isStepTask`, routes in every preset, the old-file preset rule, the step body with `entries`, the not-implemented refusal; the MCP, the ops row, the route doc; SETTINGS.md, COMMANDS.md | +| `54400684` | the scaffold: `spec.batch`, `spec.owner`, progress; `tasks/deckChecks.ts` and `TaskDeps.deckChecks`; a batch test | +| `fbf1e11d` | M1: `tasks/cut.ts` (+ 5 tests), `generation.cut.maxClips`, the converter's code mark, `isCodeDraft` and the review's exemption, `runs/cut.json`, the kit regenerated | +| `1a47547c` | M2: `tasks/onscreen.ts` (+ 3 tests), `groundedProblems`, `runs/onscreen.json` | +| `2cd6e68d` | M3: `tasks/teaser.ts` (+ 3 tests), `runs/teaser.json` | +| `c11db375` | umtool e2e `media-draft.spec.ts`: the stub runs a media step for real (`testing/draft/runMediaStep.ts`, a tsx child, the fake ollama on the kit's run); fixture `mdraft` | +| `6ff39f31` | merge of `r28/integration` (lanes C, E, F): cut beside verdicts in the settings, the dispatcher with all six | +| `4d0dee5c` | editor e2e: a teaser through the real editor job on the fake API; the runner's paths opt out of tracing | +| (this commit) | these records, FACTS, CHANGELOG | + +Lane D's gates (from the worktree root): +- **tsc** (all packages): clean before every commit. +- **Unit suites**, counted at the branch's start (`7e14a060`), after the merge, and at the tip: + - common: 4042 at the start (3 failing: two settings-doc tests read mid-edit, and the `fetchPosts` drain flake); 4050/4050 at M1; 4089/4089 after the merge; 4089/4089 at the tip. + - editor: 290 → 292 at step 0 → 295 after the merge; 295/295 at the tip. + - mcp: 346 → 349 after the merge; 349/349 at the tip. + - `test:scripts`: 874 (870 pass, 3 skipped, 1 `queue-lock` timing flake) at the start → 875 at M1 (+1, the code-mark review test) → 884 after the merge; 884 at the tip (881 pass, 2 skipped, 1 `queue-lock.test.mjs` timing failure under the full run's load, 37/37 alone). +- **Docs:** `docs env|files|cli --check` and `settings example --check` clean. +- **umtool e2e**, single specs in the foreground: + - `media-draft.spec.ts` 3/3 (14.6 s; the first run failed 3/3 waiting on a tab that does not poll a job it did not + start, so the spec now polls the iterations API, then opens the tab); + - `article-iterations.spec.ts` + `draft-review.spec.ts` 7/7 (40.3 s). + - The first run's prebuild was umtool's capped build. +- **Editor e2e** `report-draft.spec.ts` alone: 4/4 (17.9 s). Its prebuild was the editor's capped `next build`: + compiled in 21.8 s, 52 s in all, heavy slot, 5 GB. +- **umtool capped build**, corpus linked, through the heavy slot (5 GB): compiled in 9.1 s; the link removed. + +Found and left: +- **Lane E's flips swap** a THEN after its NOW when `ownerOf(timeline)` is `"drafted"`. With the converter's mark, a + converter-made cut is `"drafted"`, so flips may reorder it. This is consistent with the ruling: a code-made order is + nobody's. +- **A revise-video iteration copies its parent's manifest, mark included.** An order it changed through its ops + stays marked as code's or the cut's, and the cut task may redraft it. Its ops are a model's work from the operator's + feedback; whether that order is the operator's is a ruling for M9. +- **Folding lane E's tasks into `media-draft.spec.ts` was not cheap.** flips needs the corpus's records for its + dates, and the stub's runner has no corpus tools (common cannot import the MCP's). Both specs stay. +- **The Iterations tab does not follow a step it did not start.** A media draft asked through the API shows on reload. + M9's buttons start their own. + +### Lane D merge (2026-10-14, orchestrator) + +`r28/media-d` (step 0, M1–M3, the framework hooks) merged `726d4494`. Gates: tsc clean; common 4089/4089; mcp 349; editor +295; `test:scripts` 881 + 3 skipped, 0 failed; `docs env|files|cli --check` and `settings example --check` clean. +Rulings on lane D's questions, built in M9: a video revision whose ops change the clip order marks `drafted.timeline` +with `revise-video` and its model (a model draft: reviewable, and the cut task needs `force`); an on-screen title in +Title Case is not refused for its capitals. +### M9, as shipped (2026-10-14, lane G, `r28/surfaces`) + +The surfaces of the media drafts: "Draft with <model>" per section, Draft everything, the MCP and `/gen`, the two +leftovers, and the two rulings added to the lane. +- **Draft with <model>** is a **draft** section on a report-video project page (`DraftPanel.tsx`), one row per task: + the cut, on-screen titles, the teaser, flips, threads, narration, the YouTube text. A row has **Draft with** and the + model (the policy's API and local models, the task's route preselected), **force** (re-drafts only what a model + drafted; the UI says a field the operator wrote or edited is never replaced) and, for a per-entry task (on-screen, + teaser, narration), the entries to draft. It posts `report-draft {task, article, iteration, model, entries?, + force?}` through `/api/articles/generate` and follows the job (status, the queue, F3's progress, the last log line, + Cancel). When the job ends the page re-reads the manifest, the drafts and the server sections, and the row shows the + task's last run from its `<task>-draft.json`: written, kept as an alternative, refused by a check (with the reason), + skipped, the failing checks. The cut, flips, threads and YouTube rows carry M0's badge and alternatives with **Use + this**; per-entry fields keep theirs in the sections and on the review page. Flips and threads on a cut with no + deck say why and offer no button. +- **Which iteration:** a project `<projectsRoot>/<article>/i<n>/` whose iteration exists and names that directory + (or none) (`projectIteration`). Any other project shows one line why and no control; an iteration not done says so. +- **The Iterations tab** gains the six media drafts beside **Narrate** (a task select, a model, force, **Draft**) and + **Draft everything** (a model and the button, which opens and starts a chain panel in its own mode). +- **Draft everything** (`chain.mjs`): `CHAIN_STEPS` carries each step's `modes`; the draft-all chain is current → + windows → prepare → posts → manifest → draft-cut → draft-onscreen → draft-teaser → draft-flips → draft-threads → + draft-narrate → voices → video → podcast → draft-youtube. + - Ruled here: the drafts sit after `manifest`, because a media task drafts the project's manifest, and the windows + are fetched from the report's citations before prepare, not from the cut. The brief's "cut → windows" cannot hold. + YouTube sits after the podcast as the brief says, and its step re-muxes a built cut's chapters + (`--chapters-only`), so `out/youtube.txt` is written then. + - No attach and no dedupe: a cut whose drafts nobody reviewed is not made the article's video. + - The build is the existing `video` step without `--final` (fast: `--no-xfade`). The default chain is unchanged, + its ten steps and labels as they were. + - A draft step is one `report-draft` job through the editor, followed every 2 s, cancelled with the chain. It is + recorded done, skipped or failed, and exits 0 either way: a missing draft never blocks a build. + - Skipped: flips with threads on, or threads with flips on (the pre-check; the second of the pair is never asked + once the first applied a panel), either with no deck, or a draft file whose every unit was skipped. + - Failed: refused at the ask, or the job failed. + - A resume passes an optional step that ran (done, skipped or failed); `--from` names one. + - `umtool chain <article> <n> --draft-all [--model M]`; `--final` with it is refused. The umtool job kind is + `draft-all <article> i<n>`. +- **MCP and `/gen`:** + - `generate` refuses a media draft with no iteration, a `copyOf`, a question, feedback, channels or dates, and + `entries` on a task that is not a media draft. The tools' texts name the media tasks. + - A done media draft's answer is `mediaReviewGuidance(task, projectDir)`: read `<task>-draft.json`, read the + drafted fields and check what that task needs (`MEDIA_REVIEW`), say what to approve; the operator approves or + rejects in umtool's review page, never by writing `drafts.review.json`; the final gate; force's rule. + - `.claude/commands/gen.md` maps phrasings to each media task and says Draft everything is umtool's. + - `archilyzer gen run <media task> --iteration <n> [--entries a,b] [--force]` takes no words; COMMANDS.md + regenerated. +- **Leftovers:** + - The editor's site **Delete** on `/sites` is plan-first through H5's `publish/siteDelete.ts` + (`planSiteDeleteAction`, `deleteSiteAction(id, {force})`). The plan shows the paths, files and size removed, + what is kept and the refusals; then **Confirm delete**. A plan refused only for forceable reasons offers + **Delete with force** behind an "I understand" box; any other refusal offers nothing. It now also removes the + site's build state and staging. + - **Use this on a threads alternative** writes the clips' assignments too. The threads task's alternative is + `{list, clips}` and the task applies `{list}`. `writeDraftedField` sets each clip's `thread`, removes it from a + clip in none, and refuses a clip the cut lacks or what `validateThreadEntries` refuses. An alternative without + `clips` writes the list alone, as before. +- **The two rulings added to the lane:** + - **A revise-video that reorders the cut** (its timeline's ids, `fieldSignature`) sets `drafted.timeline = + {task: "revise-video", model, iteration, attempt: 1}`. The reorder is then a model's draft: it has the cut's + review row, and the cut task needs `force` to redraft it. A revision that keeps the order keeps the parent's mark + (or none). + - **A Title Case on-screen title** (every word but the small ones capitalised, two at least) is checked in its + sentence case (`titleAsSentence`): past the first word, a small word, an ordinary headline word + (`TITLE_ORDINARY`) or a word the clip's evidence has (by stem) is lowercased; any other keeps its capital and + is looked for as a name. So "She Refuses To Sell To A Chain" passes, "The Bakery Stays, Says Marco" still fails + on Marco. The first word is never a name's candidate (the grounding's rule, unchanged). + +| Commit | What | +| --- | --- | +| `f6de9a9e` | umtool: the chain's optional generation steps (`chain.mjs` modes, `chain-run.mjs` `draftStep`, `chain-draft.mjs`), `umtool chain --draft-all [--model]`; `chain-draft.test.mjs` (6), `chain.test.mjs` (+2) | +| `18e2542e` | umtool: `DraftPanel.tsx` on the project page, the Iterations tab's drafts and Draft everything, `ChainPanel` modes, `/api/articles/draft`, the chain route's `draftAll`/`model`, `entries` in report-draft bodies, job progress in umtool's job view | +| `ea232bbc` | merge of `r28/integration` (lane D) | +| `81da836d` | common: revise-video's order mark; onscreen's Title Case check; MCP `draftTasks.test.ts` (+1), `onscreen.test.ts` (+1) | +| `d1dda928` | threads' alternative `{list, clips}`; `writeDraftedField` sets the clips' threads; `panelTasks.test.ts` (+1), `drafted-writer.test.mjs` (+1) | +| `82fd4ab8` | MCP `generate` checks and `mediaReviewGuidance`; `/gen`; `archilyzer gen run` media tasks; COMMANDS.md; `generation.test.ts` (+1), `instructions.test.ts` (+1), `gen.test.ts` (+1) | +| `e3b6af2e` | editor: the site Delete plan-first; e2e `site-delete.spec.ts` (2), `sites-crud.spec.ts` follows the plan | +| `189bc376` | umtool e2e `media-surfaces.spec.ts` (2), `fixtures/media-surfaces-fixture.mjs` (msurf), the stub's canned drafts for every media task | +| `c4235bb5` | OPERATING.md "Generate and iterate" (the media tasks' table, Draft everything, the gate), `umtool/docs/authoring.md` | +| `2d257fbe` | the stub's narration makes its card auto-length; msurf's clips inside the cached window | +| (this commit) | this record, FACTS "Release 28 M9", CHANGELOG; `publish/siteDelete.ts`'s header names the editor's path | + +Gates (from the worktree root; counts at the branch's start `f7b8dae9`, after the merge of lane D `ea232bbc`, and at +the tip): +- tsc (all packages) clean before every commit. +- common 4076 → 4089 after the merge → 4092/4092 (+3). +- mcp 349 → 349 → 352/352 (+3). +- editor unit 295 → 295 → 295/295 (none added). +- `test:scripts` 880 + 3 skipped → 881 + 3 skipped after the merge → 890 + 3 skipped, 0 failed (+9). +- `docs cli|files|env --check`, `settings example --check`: clean (COMMANDS.md regenerated in `82fd4ab8`). +- umtool e2e, single specs in the foreground (the prebuild's capped `next build`: 396 s, most of it waiting for + memory beside the integration suite): + - `media-surfaces.spec.ts`: 1 passed, 1 failed twice (the chain's fast build: a stub narration longer than its + card, then a clip outside the cached window — fixture fixes in `2d257fbe`), then 2/2 in 48.8 s. + - `article-iterations.spec.ts` + `projects.spec.ts` 27/27 (52.0 s); `media-draft.spec.ts` + `draft-review.spec.ts` + 6/6 (28.8 s); `media-draft-e.spec.ts` + `onscreen.spec.ts` 9/9 (42.3 s). +- Editor e2e `site-delete.spec.ts` + `sites-crud.spec.ts` 22/22 (34.9 s; its prebuild's capped `next build`, 76 s). +- umtool capped build with the corpus linked, through the heavy slot (5 GB): ok, 301 s wall (most of it waiting for + the slot); the link removed. + +Found and left: +- `draft-youtube`'s re-mux passes `--no-xfade`, Draft everything's build. A cut built final before it would be + re-muxed with hard-cut offsets; Draft everything never builds final. +- The iteration's draft steps (`onscreen`, …) and the chain's (`chain:draft-onscreen`) are two records of one run; + the Iterations tab shows the first beside the step list. +- `generate`'s summary of a media draft still lists the iteration's directory files (sweep.md, report.json) above + the video project; harmless, not trimmed. + +### Gate round (2026-10-14, orchestrator) + +**Gate 1, at `726d4494`** (nothing after it touches export or homepage but a comment in `publish/siteDelete.ts`): the +four capped builds — editor 230 s, export 261 s, homepage 115 s, umtool 159 s (corpus linked, then removed); e2e export +275 passed, 1 failed (`charts.spec.ts:234`, a chart pixel test — re-run alone in the final round), report 46/46, hub +39/39, homepage 110/110. + +`r28/surfaces` (M9) merged `339e07e5`; its rulings stand (the drafts run after `manifest`, the YouTube step re-muxes +the built cut's chapters, Draft everything neither attaches nor dedupes). `docs env|files|cli --check`, +`settings example --check` clean there. + +**Final round, at `339e07e5`:** tsc clean; common 4092/4092; mcp 352/352; editor 295/295; `test:scripts` 890 + 3 +skipped, 0 failed; capped builds editor 154 s, umtool 102 s; e2e editor 694 passed, 12 skipped, 0 failed (21.6 min); +`charts.spec.ts` alone 11/11; umtool 316 passed, 1 failed — `browse.spec.ts:342` ("a new song gets the shape"), a 404 on +a just-scaffolded project, red alone too; it passed at release 27's gate, and `main` had meanwhile moved (the umtool +redesign, P0–P2a and P1, live) with `f36632a0` fixing exactly it (one project cache, cleared by a scaffold). Privacy +counts on `main..r28/integration` (68 commits): 0 session trailers or links, 0 key-like strings, 0 config paths, 0 home +paths; 3 mentions of the Candace rule and of ids `main` already carries. + +**`main` merged in** at `af153e2e` (the redesign touched none of release 28's files; only the CHANGELOG conflicted, both +kept). Re-gate there: install ok; tsc clean; `test:scripts` 918 + 3 skipped, 0 failed; umtool unit ok; umtool capped +build 33 s; umtool e2e 333 passed, 6 skipped, 0 failed (`browse.spec` included). Nothing outside umtool changed on +`main` but the CHANGELOG, a plan and the `test:scripts` glob, so the other suites' results stand. + +## Not in this release + +Comment and thread generation for social posts (X/Bluesky promotion); auto-publishing to YouTube (r28 writes the text +only). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -58,6 +58,7 @@ // pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}' // pnpm ops delete-article --json '{"id":"demo-article","force":true}' // pnpm ops delete-iteration --json '{"id":"demo-article","n":3}' +// pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}' // pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' // pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}' // pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}' @@ -108,6 +109,7 @@ // pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait // pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}' // pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}' +// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait // // --file reads the BODY from a JSON file, which is how a big one gets sent: a // four-thousand-id tag-videos body is written by a script, not typed by a model @@ -270,6 +272,9 @@ const ACTIONS = [ // Synchronous; no job. "delete-article", "delete-iteration", + // Delete a site ({id, force?, dryRun?}): the plan, then sites/<id>/, its + // publish state and its staging. Channel data is never touched. Synchronous. + "delete-site", // The channel's lifecycle: the New channel form, and the channel page's // Danger → Rename and Danger → Delete. Synchronous; no job. "create-channel", @@ -396,13 +401,18 @@ const ACTIONS = [ "import-post", // GENERATION (release 27 S6): a sweep, a report or video revision, or a // narration step over an article's iteration ({task, article, iteration?, - // model?, feedback?, question?, channels?, copyOf?, maxUsd?, …}), as a - // report-draft job on draft:api or draft:local. `job cancel` stops it. + // model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?, + // …}), as a report-draft job on draft:api or draft:local. `job cancel` stops + // it. "report-draft", // RESEARCH RUNS (release 27 S11): a research run's acquisitions, after its // job — refreshed from their jobs, then approved (run through the editor) or // rejected ({article, iteration, ids?, approve?, note?}). Synchronous. "research-approve", + // THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each + // model, one per call ({models, run?, reports?, window?, maxUsd?, limit?}), + // as a bench-verdicts job on draft:local (any local model) or draft:api. + "bench-verdicts", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -415,6 +425,9 @@ export const TTS_RESULT_MARKER = "@@tts-result "; // The same for a generation (REPORT_DRAFT_RESULT_MARKER in // common/controller/reportDraft.ts). export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft "; +// The same for the verdict bench (BENCH_VERDICTS_RESULT_MARKER in +// common/controller/benchVerdicts.ts). +export const BENCH_VERDICTS_RESULT_MARKER = "@@bench-verdicts "; // The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in // common/controller/remoteListing.ts). export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing "; @@ -642,6 +655,7 @@ export function parseArgs(argv) { ...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}), ...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}), ...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}), + ...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}), wait, quiet, waitTimeout, @@ -980,6 +994,18 @@ export function usage() { ' from, the current video, a queued or running one, one another revises', ' or copies.', "", + 'delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan', + " — every path with its size, what is kept and why — and write nothing),", + ' "force"? It removes sites/<id>/ (site.json, its pool and pages, tags,', + " charts, its reports), its publish state and last bundle", + " (export/.export-builds/<id>/) and compose's staging for it", + " (export/.export-index/sites/<id>/). Channel data is never touched; the", + " Pages project, what was deployed and a deployed hub are kept (a delete", + ' does not undeploy). Refused with the plan (409) unless "force": a deploy', + " target (cloudflareProject), a deploy in its publish state, reports of its", + " own. Refused, force or not: no such site (404), a site dir that is a link,", + " a publish stage running.", + "", 'create-channel is the New channel form: {"fields": {"name", "handling":', ' "youtube"|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?,', ' "socialHandle"?, …}} with channel-config\'s patch keys; "slug"? (else', @@ -1189,12 +1215,18 @@ export function usage() { "", 'report-draft runs a generation over an article\'s iteration as a', ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |', - ' "narrate" | "research", "article", ...} -> {jobId, iteration, warnings?}.', - ' A sweep takes "question"', + ' "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', - ' narration takes "iteration" (a done one; "cards"?, "force"?) and is a step', - ' on it. "copyOf" N runs iteration N again on "model". "model" defaults to', + ' "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", @@ -1218,13 +1250,28 @@ export function usage() { ' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->', " {outcomes: [{id, status?, jobId?, note?, error?}], research: {phase,", " autonomy, limits, spent, proposals, waitingOn: {approval, jobs},", - " continuedBy}}. It first refreshes every enqueued acquisition from its", + " continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its", " jobs (all done: done; one failed: failed, naming it). approve: true runs", " each proposal through the editor's own action (past the run's autonomy and", " caps, never past a standing rule); false rejects it, note saying why. No", " ids: the run's state now. The phase is wait (approvals or jobs pending),", ' ready (nothing pending: continue with report-draft {"task": "sweep",', - ' "iteration": N}) or continued. Refused while the run\'s job is going.', + ' "iteration": N}) or continued. An `auto` run is continued by the editor', + " itself once ready; autoContinue says how (continued by, held for a build,", + " refused by a cap, and why). Refused while the run's job is going.", + "", + 'bench-verdicts runs the verdict bench as a bench-verdicts job: {"models":', + ' ["…"], "run"?, "reports"?: ["<article>"], "window"? (seconds, default 60),', + ' "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the', + " registry's fact-checks (or of \"reports\") with the operator's verdict and a", + " citation with cues is asked of each model, one claim per call (the claim,", + " its quotes, the transcript within the window; never the findings or the", + " verdict), and scored against the rulings. On draft:local when any model is", + " local (through the GPU arbiter; unloaded at the end), else draft:api; the", + " run stops at maxUsd, and an API run is refused past caps.daily. A \"run\"", + " that exists continues (answered pairs are skipped). Results stay local, in", + " .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with", + " @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}.", "", "Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,", " ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").", diff --git a/scripts/parakeet-stitch.mjs b/scripts/parakeet-stitch.mjs @@ -55,10 +55,11 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises"; +import { existsSync, readFileSync, realpathSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; const execFileP = promisify(execFile); @@ -266,6 +267,150 @@ function workDirFor(absAudio) { const PARTIAL_PAUSE_CODE = 0; +// ─── The temp dir: removed on every exit; a stale one swept at start-up ─── +// +// Each run slices its windows into a `parakeet-stitch-*` dir under the +// tmpdir (a RAM tmpfs on some hosts). It is removed in a `finally`, and the +// pause path leaves the loop rather than exiting inside it, so the `finally` +// runs there too. What a kill -9 or a crash leaves behind is swept by the next +// run: a dir older than STALE_MS that no running process holds. +// +// "Holds" is decided by an OWNER FILE written into the dir at creation — the +// pid and that process's start time (/proc/<pid>/stat, field 22), so a reused +// pid is not taken for the owner. A scan of /proc for open files or a cwd in +// the dir would not do: a run holds nothing in it between two windows. A dir +// with no owner file (from before this change) is held while any other +// parakeet-stitch process is running (its cmdline), or while any process has a +// file or its cwd in it — the conservative reading. + +export const TMP_PREFIX = "parakeet-stitch-"; +export const OWNER_FILE = "owner.json"; +export const STALE_MS = 24 * 60 * 60 * 1000; + +// A process's start time in clock ticks since boot, or null (no such pid, no /proc). +export function procStartTime(pid) { + try { + const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); + const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + // rest[0] is field 3 (state); field 22 (starttime) is rest[19]. + return rest[19] ?? null; + } catch { + return null; + } +} + +function pidAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (e) { + return e?.code === "EPERM"; + } +} + +async function procPids() { + try { + return (await readdir("/proc")).filter((n) => /^\d+$/.test(n)).map(Number); + } catch { + return []; + } +} + +// The live system's answers; tests pass their own. +export const liveProc = { + // The owner file's process is the same process, still running. + ownerAlive(owner) { + if (!owner || !Number.isInteger(owner.pid) || !pidAlive(owner.pid)) return false; + const start = procStartTime(owner.pid); + return owner.start == null || start == null || String(start) === String(owner.start); + }, + // Some process has its cwd or an open file inside `dir`. + async holds(dir) { + const inside = (p) => p === dir || p.startsWith(dir + path.sep); + for (const pid of await procPids()) { + try { + if (inside(await readlink(`/proc/${pid}/cwd`))) return true; + } catch { + // gone, or not ours to read + } + let fds = []; + try { + fds = await readdir(`/proc/${pid}/fd`); + } catch { + continue; + } + for (const fd of fds) { + try { + if (inside(await readlink(`/proc/${pid}/fd/${fd}`))) return true; + } catch { + // closed meanwhile + } + } + } + return false; + }, + // Another parakeet-stitch process is running. + async stitchRunning() { + for (const pid of await procPids()) { + if (pid === process.pid) continue; + try { + if (readFileSync(`/proc/${pid}/cmdline`, "utf8").includes("parakeet-stitch")) return true; + } catch { + // gone + } + } + return false; + }, +}; + +export async function writeOwnerFile(dir, pid = process.pid) { + await writeFile(path.join(dir, OWNER_FILE), JSON.stringify({ pid, start: procStartTime(pid) })); +} + +// Remove every stale, unheld `parakeet-stitch-*` dir under `tmpdir`. +// Answers what was removed and what was kept, with why. +export async function sweepStaleTempDirs({ tmpdir = os.tmpdir(), now = Date.now(), staleMs = STALE_MS, proc = liveProc } = {}) { + const removed = []; + const kept = []; + let names = []; + try { + names = (await readdir(tmpdir, { withFileTypes: true })).filter((e) => e.isDirectory() && e.name.startsWith(TMP_PREFIX)).map((e) => e.name); + } catch { + return { removed, kept }; + } + for (const name of names) { + const dir = path.join(tmpdir, name); + let st; + try { + st = await stat(dir); + } catch { + continue; + } + if (now - st.mtimeMs < staleMs) { + kept.push({ dir, why: "young" }); + continue; + } + let owner = null; + try { + owner = JSON.parse(await readFile(path.join(dir, OWNER_FILE), "utf8")); + } catch { + owner = null; + } + const held = owner ? proc.ownerAlive(owner) : (await proc.stitchRunning()) || (await proc.holds(dir)); + if (held) { + kept.push({ dir, why: "held" }); + continue; + } + try { + await rm(dir, { recursive: true, force: true }); + removed.push(dir); + } catch { + kept.push({ dir, why: "not removable" }); + } + } + return { removed, kept }; +} + async function main() { const opts = parseArgs(process.argv.slice(2)); if (!opts.audio) fail("missing <audioFile>\n\n" + HELP); @@ -343,7 +488,12 @@ async function main() { process.on("SIGTERM", onStop); process.on("SIGINT", onStop); - const tmp = await mkdtemp(path.join(os.tmpdir(), "parakeet-stitch-")); + // What a crashed or killed run left in the tmpdir goes first. + const swept = await sweepStaleTempDirs().catch(() => ({ removed: [] })); + if (swept.removed.length) progress(`removed ${swept.removed.length} stale temp dir(s) from earlier runs`); + const tmp = await mkdtemp(path.join(os.tmpdir(), TMP_PREFIX)); + await writeOwnerFile(tmp); + let paused = false; const segTimes = []; // measured wall-time (ms) per freshly-transcribed window, for ETA let done = 0; // windows present (cached or freshly done) try { @@ -356,8 +506,9 @@ async function main() { continue; } if (stopRequested) { - progress(`paused after ${done}/${N} window(s) — re-run to resume`); - process.exit(PARTIAL_PAUSE_CODE); + // Leave the loop, never exit inside it: the `finally` removes the temp dir. + paused = true; + break; } const isLast = i === N - 1; // Last window runs to EOF (no -t) so we never miss a trailing fragment. @@ -380,6 +531,10 @@ async function main() { } finally { if (!opts.keepTemp) await rm(tmp, { recursive: true, force: true }); } + if (paused) { + progress(`paused after ${done}/${N} window(s) — re-run to resume`); + process.exit(PARTIAL_PAUSE_CODE); + } // All windows present — load the raw payloads and stitch the final transcript. const windowWords = []; @@ -435,6 +590,16 @@ async function main() { if (!opts.keepTemp) await rm(workDir, { recursive: true, force: true }); } -main().catch((err) => { - fail(err?.stack || String(err), 1); -}); +// Run as a program (the app's binary, or the CLI), not when a test imports it. +const isMain = (() => { + try { + return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); +if (isMain) { + main().catch((err) => { + fail(err?.stack || String(err), 1); + }); +} diff --git a/scripts/parakeet-stitch.test.mjs b/scripts/parakeet-stitch.test.mjs @@ -0,0 +1,118 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { OWNER_FILE, STALE_MS, TMP_PREFIX, sweepStaleTempDirs, writeOwnerFile } from "./parakeet-stitch.mjs"; + +// Run with: node --test scripts/parakeet-stitch.test.mjs +// +// Release 28 H1: the temp dir a run slices its windows into is removed on the +// pause path too, and a run sweeps the stale ones a crash or a kill left. + +const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "parakeet-stitch.mjs"); + +function sh(file, body) { + writeFileSync(file, `#!/bin/sh\n${body}\n`); + chmodSync(file, 0o755); + return file; +} + +test("the pause path: a SIGTERM mid-run finishes the window, keeps it, exits 0 — and leaves no temp dir", () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-pause-")); + try { + const tmpdir = path.join(root, "tmp"); + const bin = path.join(root, "bin"); + const work = path.join(root, "video"); + mkdirSync(tmpdir); + mkdirSync(bin); + mkdirSync(work); + writeFileSync(path.join(work, "audio.wav"), "not audio"); + writeFileSync(path.join(root, "model.gguf"), "not a model"); + sh(path.join(bin, "ffprobe"), "echo 1000"); + // ffmpeg: write the window wav (its last argument). + sh(path.join(bin, "ffmpeg"), 'for a; do last="$a"; done; echo wav > "$last"'); + // parakeet-cli: the operator pauses during the first window (a SIGTERM to + // the script, its parent), and the window still completes. + sh(path.join(bin, "parakeet-cli"), 'kill -TERM $PPID; echo \'{"words":[{"w":"hello","start":1,"end":1.5}]}\''); + const r = spawnSync( + process.execPath, + [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), path.join(work, "audio.wav"), path.join(work, "out.json")], + { env: { ...process.env, TMPDIR: tmpdir }, encoding: "utf8", timeout: 30_000 }, + ); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stderr, /paused after 1\/3 window\(s\)/); + assert.deepEqual(readdirSync(tmpdir).filter((n) => n.startsWith(TMP_PREFIX)), [], "no temp dir left"); + // The completed window is kept for the resume; nothing was stitched. + assert.ok(existsSync(path.join(work, ".audio.wav.parakeet", "win-0000.json"))); + assert.ok(!existsSync(path.join(work, "out.json"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("the sweep: an old unheld dir goes; a held one (its owner alive, or a process in it) and a young one stay", async () => { + const tmpdir = mkdtempSync(path.join(os.tmpdir(), "stitch-sweep-")); + try { + const now = Date.now(); + const make = (name, ageMs) => { + const d = path.join(tmpdir, name); + mkdirSync(d); + writeFileSync(path.join(d, "win-0000.wav"), "wav"); + const t = (now - ageMs) / 1000; + utimesSync(d, t, t); + return d; + }; + const old = make(`${TMP_PREFIX}old`, STALE_MS + 60_000); + const owned = path.join(tmpdir, `${TMP_PREFIX}owned`); + mkdirSync(owned); + await writeOwnerFile(owned, 4242); + utimesSync(owned, (now - STALE_MS * 2) / 1000, (now - STALE_MS * 2) / 1000); + const legacyHeld = make(`${TMP_PREFIX}legacy-held`, STALE_MS * 3); + const young = make(`${TMP_PREFIX}young`, 60_000); + const other = make("something-else", STALE_MS * 5); + const proc = { + ownerAlive: (o) => o.pid === 4242, + holds: async (dir) => dir === legacyHeld, + stitchRunning: async () => false, + }; + const out = await sweepStaleTempDirs({ tmpdir, now, proc }); + assert.deepEqual(out.removed, [old]); + assert.deepEqual( + out.kept.map((k) => [path.basename(k.dir), k.why]).sort(), + [ + [`${TMP_PREFIX}legacy-held`, "held"], + [`${TMP_PREFIX}owned`, "held"], + [`${TMP_PREFIX}young`, "young"], + ], + ); + assert.ok(existsSync(owned) && existsSync(legacyHeld) && existsSync(young) && existsSync(other)); + assert.ok(existsSync(path.join(owned, OWNER_FILE))); + // The owner gone: the dir goes. A dir with no owner file waits while + // another parakeet-stitch runs. + const later = await sweepStaleTempDirs({ tmpdir, now, proc: { ...proc, ownerAlive: () => false, stitchRunning: async () => true } }); + assert.deepEqual(later.removed, [owned]); + assert.ok(existsSync(legacyHeld)); + } finally { + rmSync(tmpdir, { recursive: true, force: true }); + } +}); + +test("the live owner check: this process owns a dir it marked; a dead pid does not", async () => { + const { liveProc } = await import("./parakeet-stitch.mjs"); + const dir = mkdtempSync(path.join(os.tmpdir(), "stitch-owner-")); + try { + await writeOwnerFile(dir); + const mine = JSON.parse((await import("node:fs")).readFileSync(path.join(dir, OWNER_FILE), "utf8")); + assert.equal(mine.pid, process.pid); + assert.equal(liveProc.ownerAlive(mine), true); + // The same pid with another start time is a reused pid, not the owner. + assert.equal(liveProc.ownerAlive({ pid: process.pid, start: "1" }), mine.start === null); + const child = spawnSync(process.execPath, ["-e", "console.log(process.pid)"], { encoding: "utf8" }); + assert.equal(liveProc.ownerAlive({ pid: Number(child.stdout.trim()), start: null }), false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -97,6 +97,26 @@ function markerCmd(logFile, id, holdMs) { ]; } +// The same, held until `gateFile` exists (or `maxMs` passes) rather than for a +// fixed time: a test opens the gate once what it means to see has happened, so +// a loaded machine's slow start of the NEXT run cannot outlast the hold. (A +// fixed hold was the release 28 flake: under `test:scripts`' parallel files, +// the second run sometimes started after the first had already ended.) The +// cap keeps a run that should have been admitted, and was not, from hanging +// the test: it ends, and the order assertion names what went wrong. +function gateCmd(logFile, id, gateFile, maxMs = 20_000) { + return [ + process.execPath, + "-e", + `const fs=require("fs");` + + `fs.appendFileSync(${JSON.stringify(logFile)},"S${id}");` + + `const t0=Date.now();` + + `const tick=()=>{if(fs.existsSync(${JSON.stringify(gateFile)})||Date.now()-t0>${maxMs}){fs.appendFileSync(${JSON.stringify(logFile)},"E${id}");}else setTimeout(tick,20);};` + + `tick();`, + ]; +} +const openGate = (gateFile) => fs.writeFileSync(gateFile, ""); + const delay = (ms) => new Promise((r) => setTimeout(r, ms)); test("serializes concurrent invocations", async () => { @@ -636,12 +656,16 @@ test("two weighted jobs run side by side; a third waits for headroom, named in t meminfo(env.HEAVY_MEMINFO_FILE, 8000); const jobs = path.join(dir, "heavy.lock.jobs"); const tickets = () => (fs.existsSync(jobs) ? fs.readdirSync(jobs).filter((n) => n.endsWith(".json")).length : 0); - const a = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "a", 1500)], env); + // a and b hold until c has been seen waiting: their overlap, and c's wait, + // are then by the gate, not by how fast this machine starts a process. + const gate = path.join(dir, "gate-ab"); + const a = startLock(["--heavy", "--estimate", "1500", "--", ...gateCmd(log, "a", gate)], env); await until(() => tickets() === 1); - const b = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "b", 1500)], env); + const b = startLock(["--heavy", "--estimate", "1500", "--", ...gateCmd(log, "b", gate)], env); await until(() => tickets() === 2); const c = startLock(["--heavy", "--estimate", "1500", "--", ...markerCmd(log, "c", 50)], env); await c.waitFor(/waiting for memory — 8000 MB available, 3000 MB promised to 2 running jobs, the floor is 6000 MB/); + openGate(gate); const [ra, rb, rc] = await Promise.all([a.done, b.done, c.done]); assert.equal(ra.code, 0, ra.stderr); assert.equal(rb.code, 0, rb.stderr); @@ -793,11 +817,15 @@ test("--with: a suite that shares a tree holds the other suite's queue too", asy const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); - const editor = startLock(["--name", "e2e-editor", "--with", "e2e-export", "--estimate", "100", "--", ...markerCmd(log, "e", 700)], env); + // The editor holds until umtool has run: umtool's start "beside the editor" + // is then the lock's doing, not a race against a 700 ms hold. + const gate = path.join(dir, "gate-e"); + const editor = startLock(["--name", "e2e-editor", "--with", "e2e-export", "--estimate", "100", "--", ...gateCmd(log, "e", gate)], env); await until(() => fs.existsSync(path.join(dir, "q.lock.e2e-export.holder.json"))); const exp = startLock(["--name", "e2e-export", "--estimate", "100", "--", ...markerCmd(log, "x", 50)], env); await exp.waitFor(/waiting for the e2e queue — held by .*pid \d+/); const umtool = await runLock(["--name", "e2e-umtool", "--estimate", "100", "--", ...markerCmd(log, "u", 50)], env); + openGate(gate); for (const r of [await editor.done, await exp.done, umtool]) assert.equal(r.code, 0, r.stderr); const order = fs.readFileSync(log, "utf8"); assert.ok(order.indexOf("Sx") > order.indexOf("Ee"), `export ran beside the editor: ${order}`); diff --git a/settings.json.example b/settings.json.example @@ -244,7 +244,13 @@ "revise-report": "api", "revise-video": "local", "narrate": "local", - "research": "api" + "research": "api", + "cut": "local", + "onscreen": "local", + "teaser": "local", + "flips": "local", + "threads": "local", + "youtube": "local" }, "models": { "api": "claude-sonnet-5-5", @@ -268,6 +274,9 @@ "searchUrl": "" }, "citationOrigin": "", + "cut": { + "maxClips": 20 + }, "research": { "autonomy": "propose", "maxItemsPerRun": 20, @@ -275,6 +284,14 @@ "maxTranscribeHours": 6, "newChannelsNeedApproval": true, "postWalksNeedApproval": true + }, + "verdicts": { + "bar": { + "agreement": 0, + "contradictedRecall": 0, + "notFoundRecall": 0 + }, + "models": [] } } } diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts @@ -2,7 +2,7 @@ import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; import { cancelJob, getJob, startJob } from "@/lib/jobs"; import { ARTICLES_DIR } from "@/lib/paths"; import { planChain } from "@/lib/report/chain.mjs"; -import { chainKind, chainViewOf, errorResponse, projectsRootOf, readArticleIterations, readPolicy } from "@/lib/articles/generation"; +import { chainKind, chainViewOf, errorResponse, projectsRootOf, readArticleIterations, readPolicy, type ChainMode } from "@/lib/articles/generation"; export const dynamic = "force-dynamic"; @@ -12,9 +12,13 @@ export const dynamic = "force-dynamic"; // iteration's `steps`, so a start resumes at the first step not done, or at // `from`. The projects root is the editor's policy's (generation.projectsRoot). // -// GET ?article=<id>&n=<n> -> { chain } the steps, where it resumes, its job -// POST { article, n, from? } -> { ok, job } started -// POST { cancel: <jobId> } -> { cancelled } +// GET ?article=<id>&n=<n>[&mode=draft-all] -> { chain } the steps, where it resumes, its job +// POST { article, n, from?, draftAll?, model? } -> { ok, job } started +// POST { cancel: <jobId> } -> { cancelled } +// +// `draftAll` is Draft everything (release 28 M9): the chain with its +// generation steps — each a report-draft job on `model` (else the task's +// route) — and the fast build; a job of its own kind, resumed as the chain is. function parse(article: unknown, n: unknown): { article: string; n: number } | string { const a = String(article ?? ""); const k = Number(n); @@ -23,19 +27,21 @@ function parse(article: unknown, n: unknown): { article: string; n: number } | s return { article: a, n: k }; } -async function chainOf(article: string, n: number) { +async function chainOf(article: string, n: number, mode: ChainMode = "video") { const its = await readArticleIterations(article); const it = its.iterations.find((r) => r.n === n); if (!it) return null; - return chainViewOf(article, it); + return chainViewOf(article, it, mode); } +const modeOf = (v: unknown): ChainMode => (v === "draft-all" || v === true ? "draft-all" : "video"); + export async function GET(request: Request) { const url = new URL(request.url); const p = parse(url.searchParams.get("article"), url.searchParams.get("n")); if (typeof p === "string") return Response.json({ error: p }, { status: 400 }); try { - const chain = await chainOf(p.article, p.n); + const chain = await chainOf(p.article, p.n, modeOf(url.searchParams.get("mode"))); if (!chain) return Response.json({ error: `no iteration i${p.n}` }, { status: 404 }); return Response.json({ chain }, { headers: { "cache-control": "no-store" } }); } catch (err) { @@ -44,7 +50,7 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown }; + const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown }; if (body.cancel !== undefined) { const id = String(body.cancel); if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 }); @@ -60,10 +66,13 @@ export async function POST(request: Request) { projectsRoot = undefined; // the editor unreachable: the chain reads settings.json itself } const from = body.from ? String(body.from) : null; - const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, ...(projectsRoot ? { projectsRoot } : {}) }); - if (plan.steps.length === 0) return Response.json({ error: "every step of the chain is done — pick a step to run from" }, { status: 400 }); - const job = startJob(chainKind(p.article, p.n), plan.steps); - return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n) }); + const mode = modeOf(body.draftAll === true); + const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined; + if (model && mode !== "draft-all") return Response.json({ error: "a model is Draft everything's (draftAll): the model its drafts run on" }, { status: 400 }); + const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) }); + if (plan.steps.length === 0) return Response.json({ error: `every step of ${mode === "draft-all" ? "Draft everything" : "the chain"} is done — pick a step to run from` }, { status: 400 }); + const job = startJob(chainKind(p.article, p.n, mode), plan.steps); + return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode) }); } catch (err) { return Response.json({ error: (err as Error).message }, { status: 400 }); } diff --git a/umtool/app/api/articles/delete/route.ts b/umtool/app/api/articles/delete/route.ts @@ -55,7 +55,12 @@ export async function POST(request: Request) { try { const plan: DeletePlan = n === null ? await planArticleDelete(article, opts) : await planIterationDelete(article, n, opts); const job = runningJob(); - if (job && (n === null ? job.kind.startsWith(`chain ${article} `) : job.kind === chainKind(article, n))) { + if ( + job && + (n === null + ? job.kind.startsWith(`chain ${article} `) || job.kind.startsWith(`draft-all ${article} `) + : job.kind === chainKind(article, n) || job.kind === chainKind(article, n, "draft-all")) + ) { plan.refusals.push({ reason: `${job.kind} is running here: cancel the chain, or wait for it`, forceable: false }); } if (n === null) { diff --git a/umtool/app/api/articles/draft/route.ts b/umtool/app/api/articles/draft/route.ts @@ -0,0 +1,21 @@ +import { resolveReport } from "@/lib/report/serve.mjs"; +import { draftRuns, projectIteration } from "@/lib/articles/projectDraft"; + +export const dynamic = "force-dynamic"; + +// A VIDEO PROJECT'S DRAFTS (release 28 M9): the iteration it was made from +// (the media tasks are report-draft steps on it; a project that names none +// has no "Draft with") and each task's last run, from its `<task>-draft.json`. +// A draft is STARTED through /api/articles/generate (the editor's +// report-draft), never here: this route reads. +// +// GET ?project=<id> -> { link: {ok, article, n, status} | {ok: false, why}, runs: {<task>: summary} } +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + return Response.json( + { link: await projectIteration(r.project.dir), runs: await draftRuns(r.project.dir) }, + { headers: { "cache-control": "no-store" } }, + ); +} diff --git a/umtool/app/api/articles/generate/route.ts b/umtool/app/api/articles/generate/route.ts @@ -3,14 +3,19 @@ import { enqueueDraft, errorResponse } from "@/lib/articles/generation"; export const dynamic = "force-dynamic"; // START A GENERATION (release 27 S8): the body is `pnpm ops report-draft`'s — -// { task, article, iteration?, model?, feedback?, question?, channels?, from?, -// to?, copyOf?, maxUsd?, cards?, force?, autonomy? } — forwarded to the editor, which +// { task, article, iteration?, model?, extractorModel?, feedback?, question?, +// channels?, from?, to?, copyOf?, maxUsd?, cards?, entries?, force?, autonomy? } — +// forwarded to the editor, which // creates the iteration and runs the job. Answers { ok, jobId, iteration }. // -// a new article task sweep, question, channels (from, to) +// a new article task sweep, question, channels (from, to); on Claude, +// extractorModel (release 28 F2: else the settings') // a new iteration task revise-report | revise-video, iteration, feedback // copy with model the iteration's task, copyOf, model // narration task narrate, iteration, model (a step) +// a media draft task cut | onscreen | teaser | flips | threads | +// youtube, iteration, model, entries?, force? (a step, +// release 28) // research task research, question, channels?, model, autonomy // (release 27 S11: its queue is /api/articles/research) // continue research task sweep, iteration (the research run), model diff --git a/umtool/app/api/bench/bar/route.ts b/umtool/app/api/bench/bar/route.ts @@ -0,0 +1,27 @@ +import { errorResponse } from "@/lib/articles/generation"; +import { readVerdictsPolicy, writeVerdictsPolicy } from "@/lib/bench"; + +export const dynamic = "force-dynamic"; + +// THE VERDICT BENCH'S BAR (release 28 M7): settings.generation.verdicts — the +// operator's bar and the passing models they ticked — read from and written +// through the editor's settings action (POST /api/ops/settings), whole. +// +// GET -> { verdicts } +// POST { bar: {agreement, contradictedRecall, notFoundRecall}, models } -> { ok, verdicts } +export async function GET() { + try { + return Response.json({ verdicts: await readVerdictsPolicy() }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} + +export async function POST(request: Request) { + try { + const body = await request.json().catch(() => null); + return Response.json({ ok: true, verdicts: await writeVerdictsPolicy(body) }, { headers: { "cache-control": "no-store" } }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -0,0 +1,85 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, writeDraftedField } from "@/lib/report/manifest.mjs"; +import { alternativeById, draftsView } from "@/lib/report/drafts.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review"; + +export const dynamic = "force-dynamic"; + +// The drafts review (release 28, M0): every drafted field of a cut, its +// review, and the alternatives the draft tasks kept. +// +// GET ?project=<id> the view (lib/report/drafts.mjs) and the token +// POST { project, action, ... } one action: +// approve { address, note? } approved on the field's CURRENT value +// reject { address, note } rejected; the note says what is wrong (required) +// clear { address } no verdict (the note is kept) +// note { address, note } the note alone +// use { alternative, token? } "Use this": the alternative (`<file>#<i>`) written +// through the manifest writer as the operator's edit +// (snapshot, validators, the edit-notes guard) +// +// Verdicts live in <project>/drafts.review.json (report-to-video's +// drafts-review.mjs); a final build refuses a drafted field not approved. + +type Body = Record<string, unknown>; +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + return Response.json({ ...(await draftsView(r.project.dir, r.manifest)), token: await manifestToken(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + let body: Body; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const dir = r.project.dir; + const note = typeof body.note === "string" ? body.note : undefined; + let editNotes = null; + try { + if (body.action === "use") { + const alt = await alternativeById(dir, String(body.alternative ?? "")); + if (!alt) return Response.json({ error: `no alternative ${String(body.alternative ?? "")}` }, { status: 404 }); + const token = typeof body.token === "string" ? body.token : null; + const w = await withEditNotes(r.project, () => writeDraftedField(dir, { entry: alt.entry, field: alt.field, value: alt.value }, { token })); + editNotes = w.editNotes; + invalidateProjects(); + } else { + const address = String(body.address ?? ""); + const row = draftsReviewRows(r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address); + if (!row) return Response.json({ error: `${address || "(no address)"} is not a field this cut has to review` }, { status: 404 }); + switch (body.action) { + case "approve": + await setDraftReview(dir, address, { verdict: "approved", key: row.key, text: row.text, ...(note !== undefined ? { note } : {}) }); + break; + case "reject": + await setDraftReview(dir, address, { verdict: "rejected", key: row.key, text: row.text, note: note ?? "" }); + break; + case "clear": + await setDraftReview(dir, address, { verdict: null }); + break; + case "note": + await setDraftReview(dir, address, { note: note ?? "" }); + break; + default: + return Response.json({ error: "action must be approve, reject, clear, note or use" }, { status: 400 }); + } + } + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + const fresh = await resolveReport(String(body.project)); + const manifest = "error" in fresh ? r.manifest : fresh.manifest; + return Response.json({ ok: true, ...(await draftsView(dir, manifest)), token: await manifestToken(dir), editNotes }, { headers: noStore }); +} diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts @@ -21,9 +21,11 @@ export const dynamic = "force-dynamic"; // writer (snapshot, validators, the edit-notes // guard); an edit clears the verdict // -// Verdicts live in <project>/narration.review.json (report-to-video's -// narration-review.mjs, takes/verdicts.json's shape); the build refuses an -// un-approved narrated card once that file exists. +// Verdicts live in <project>/drafts.review.json as `narrate/<cardId>/narration` +// (report-to-video's narration-review.mjs over drafts-review.mjs; release 25's +// narration.review.json is still read); the build refuses an un-approved +// narrated card once the cut's narration has a verdict, and a final build a +// drafted one. type Body = Record<string, unknown>; const noStore = { "cache-control": "no-store" }; diff --git a/umtool/app/articles/page.tsx b/umtool/app/articles/page.tsx @@ -63,6 +63,9 @@ export default async function ArticlesPage({ searchParams }: { searchParams: Pro <Link href="/sites" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> site pages </Link> + <Link href="/bench" className="ml-2 text-[12px] text-[var(--color-dim)] hover:text-[var(--color-text)]"> + verdict bench + </Link> </div> {pending.length > 0 && ( <section aria-label="in the making" className="mb-4"> diff --git a/umtool/app/bench/page.tsx b/umtool/app/bench/page.tsx @@ -0,0 +1,305 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import BarForm from "@/components/bench/BarForm"; +import { badgeVariants } from "@/components/ui/badge"; +import { + BASELINE_MODEL, + VERDICTS, + filterBenchRows, + passesBar, + readBenchRuns, + readBenchView, + readVerdictsPolicy, +} from "@/lib/bench"; +import type { ModelScore } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; + +export const dynamic = "force-dynamic"; + +// THE VERDICT BENCH (release 28 M7): could a model propose a fact-check +// verdict well enough to be worth a review? One run at a time: per model its +// agreement with the operator's rulings and its CONTRADICTED and NOT_FOUND +// recall beside the always-CORROBORATED baseline, its cost; the confusion +// matrix; every item with each model's verdict and reason, disagreements +// first. The bar (settings.generation.verdicts) is set here, and each model's +// pass or fail read against it — the handoff for the verdict proposals. The +// runs are local-only (`archilyzer reports bench-verdicts`); zero client JS +// but the bar's form. + +type Search = { run?: string; model?: string; verdict?: string }; + +const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 1000) / 10}%`); + +export default async function BenchPage({ searchParams }: { searchParams: Promise<Search> }) { + const sp = await searchParams; + const runs = await readBenchRuns(); + const id = sp.run && runs.some((r) => r.id === sp.run) ? sp.run : runs[0]?.id; + const view = id ? await readBenchView(id) : null; + let policy: GenerationVerdicts | null = null; + let policyError: string | null = null; + try { + policy = await readVerdictsPolicy(); + } catch (e) { + policyError = (e as Error).message; + } + const qs = (next: Partial<Search>) => { + const p = new URLSearchParams(); + for (const [k, v] of Object.entries({ ...sp, run: id, ...next })) if (v) p.set(k, String(v)); + return `/bench?${p.toString()}`; + }; + + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + active="articles" + crumbs={[{ label: "articles", href: "/articles" }, { label: "verdict bench" }]} + note={`${runs.length} run${runs.length === 1 ? "" : "s"}`} + /> + <main className="deck-main flex-1 p-4 text-[12px]"> + {runs.length === 0 ? ( + <p className="text-[var(--color-dim)]"> + no bench runs — <code className="font-mono">archilyzer reports bench-verdicts --models …</code> + </p> + ) : ( + <> + <nav aria-label="runs" className="mb-3 flex flex-wrap items-center gap-1.5"> + <span className="micro">run</span> + {runs.map((r) => ( + <Link + key={r.id} + href={`/bench?run=${r.id}`} + data-run={r.id} + aria-current={r.id === id ? "true" : undefined} + className={badgeVariants({ variant: r.id === id ? "on" : "neutral" })} + > + {r.id} · {r.status} · {r.items} + </Link> + ))} + </nav> + {!view ? ( + <p role="alert" className="text-[var(--color-bad)]"> + run {id} cannot be read + </p> + ) : ( + <RunView view={view} policy={policy} policyError={policyError} sp={sp} qs={qs} /> + )} + </> + )} + </main> + </div> + ); +} + +function RunView({ + view, + policy, + policyError, + sp, + qs, +}: { + view: NonNullable<Awaited<ReturnType<typeof readBenchView>>>; + policy: GenerationVerdicts | null; + policyError: string | null; + sp: Search; + qs: (n: Partial<Search>) => string; +}) { + const { summary: s, score } = view; + const bar = policy?.bar ?? null; + const rows = filterBenchRows(view.items, { model: sp.model, verdict: sp.verdict }); + const models = sp.model ? s.models.filter((m) => m === sp.model) : s.models; + return ( + <div data-bench-run={s.id} data-status={s.status} className="flex flex-col gap-4"> + <p role="status" className="text-[var(--color-dim)]"> + {s.status} · {s.items} items · {s.skipped.length} skipped · a {s.windowS} s window · ${s.spentUsd.toFixed(4)} of ${s.maxUsd} ·{" "} + {new Date(s.createdAt).toISOString().slice(0, 16).replace("T", " ")} UTC + {s.stopped?.length ? ` · stopped: ${s.stopped.join("; ")}` : ""} + </p> + <section aria-label="models" className="flex flex-wrap gap-2"> + {[...score.models, score.baseline].map((m) => ( + <ModelTile key={m.model} m={m} baseline={m.model === BASELINE_MODEL ? null : score.baseline} pass={bar && m.model !== BASELINE_MODEL ? passesBar(m, bar) : null} /> + ))} + </section> + <section aria-label="the bar" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> + {policy ? ( + <BarForm initial={policy} models={score.models} /> + ) : ( + <p role="alert" className="text-[var(--color-bad)]"> + the bar cannot be read: {policyError} + </p> + )} + </section> + <section aria-label="confusion" className="flex flex-wrap gap-4"> + {score.models.map((m) => ( + <Matrix key={m.model} m={m} /> + ))} + </section> + <section aria-label="items"> + <div className="mb-2 flex flex-wrap items-center gap-1.5"> + <span className="micro">model</span> + <Chip href={qs({ model: "" })} on={!sp.model} label="all" /> + {s.models.map((m) => ( + <Chip key={m} href={qs({ model: m })} on={sp.model === m} label={m} /> + ))} + <span className="micro ml-3">operator</span> + <Chip href={qs({ verdict: "" })} on={!sp.verdict} label="all" /> + {VERDICTS.filter((v) => score.ruled[v] > 0).map((v) => ( + <Chip key={v} href={qs({ verdict: v })} on={sp.verdict === v} label={`${v} ${score.ruled[v]}`} /> + ))} + </div> + <table className="w-full border-collapse"> + <thead> + <tr className="micro text-left"> + <th className="py-1 pr-2">claim</th> + <th className="py-1 pr-2">operator</th> + {models.map((m) => ( + <th key={m} className="py-1 pr-2 font-mono"> + {m} + </th> + ))} + </tr> + </thead> + <tbody> + {rows.map((r) => ( + <tr key={r.key} data-item={r.key} data-disagree={r.disagree.length ? r.disagree.join(" ") : undefined} className="border-t border-[var(--color-line)] align-top"> + <td className="max-w-[28rem] py-1.5 pr-2"> + <div className="font-mono text-[10px] text-[var(--color-dim)]">{r.key}</div> + {r.text} + </td> + <td className="py-1.5 pr-2 font-mono">{r.verdict}</td> + {models.map((m) => { + const a = r.answers[m]; + return ( + <td key={m} data-model={m} data-verdict={a?.verdict ?? "none"} className="max-w-[20rem] py-1.5 pr-2"> + {!a ? ( + <span className="text-[var(--color-dim)]">not asked</span> + ) : a.verdict ? ( + <> + <span className={`font-mono ${a.verdict === r.verdict ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}`}>{a.verdict}</span> + {a.reason && <div className="text-[var(--color-dim)]">{a.reason}</div>} + </> + ) : ( + <span className="text-[var(--color-bad)]"> + {a.failure}: {a.error} + </span> + )} + </td> + ); + })} + </tr> + ))} + </tbody> + </table> + </section> + {s.skipped.length > 0 && ( + <details> + <summary className="micro cursor-pointer">skipped {s.skipped.length}</summary> + <ul aria-label="skipped" className="mt-1 flex flex-col gap-0.5"> + {s.skipped.map((k) => ( + <li key={k.key} className="font-mono text-[var(--color-dim)]"> + {k.key} — {k.reason} + </li> + ))} + </ul> + </details> + )} + </div> + ); +} + +function ModelTile({ m, baseline, pass }: { m: ModelScore; baseline: ModelScore | null; pass: { pass: boolean; misses: string[] } | null }) { + const vs = (v: number | null, b: number | null | undefined) => (baseline ? `${pct(v)} (baseline ${pct(b ?? null)})` : pct(v)); + return ( + <div + data-model={m.model} + data-pass={pass ? String(pass.pass) : undefined} + className="min-w-[15rem] rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2" + > + <div className="mb-1 flex items-center gap-2"> + <span className="font-mono text-[var(--color-text)]">{m.model}</span> + {pass && ( + <span className={badgeVariants({ variant: pass.pass ? "on" : "blocking", size: "sm" })} title={pass.misses.join("; ") || undefined}> + {pass.pass ? "passes" : "fails"} the bar + </span> + )} + </div> + <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5"> + <dt className="text-[var(--color-dim)]">agreement</dt> + <dd data-metric="agreement">{vs(m.agreement, baseline?.agreement)}</dd> + <dt className="text-[var(--color-dim)]">with PARTLY ~ CORROBORATED</dt> + <dd>{vs(m.agreementAdjacent, baseline?.agreementAdjacent)}</dd> + <dt className="text-[var(--color-dim)]">CONTRADICTED recall</dt> + <dd data-metric="contradicted"> + {vs(m.recall.CONTRADICTED.recall, baseline?.recall.CONTRADICTED.recall)} of {m.recall.CONTRADICTED.ruled} + </dd> + <dt className="text-[var(--color-dim)]">NOT_FOUND recall</dt> + <dd data-metric="not-found"> + {vs(m.recall.NOT_FOUND.recall, baseline?.recall.NOT_FOUND.recall)} of {m.recall.NOT_FOUND.ruled} + </dd> + <dt className="text-[var(--color-dim)]">PARTLY recall</dt> + <dd> + {pct(m.recall.PARTLY.recall)} · adjacent {pct(m.recall.PARTLY_ADJACENT.recall)} + </dd> + {baseline && ( + <> + <dt className="text-[var(--color-dim)]">cost</dt> + <dd data-metric="cost">${m.usd.toFixed(4)}</dd> + <dt className="text-[var(--color-dim)]">latency</dt> + <dd>{m.latency.medianMs === null ? "—" : `${(m.latency.medianMs / 1000).toFixed(1)} s median, ${((m.latency.p90Ms ?? 0) / 1000).toFixed(1)} s p90`}</dd> + <dt className="text-[var(--color-dim)]">answered</dt> + <dd> + {m.answered} of {m.asked} + {m.parseFailures ? ` · ${m.parseFailures} parse failures` : ""} + {m.errors ? ` · ${m.errors} errors` : ""} + </dd> + </> + )} + </dl> + </div> + ); +} + +function Matrix({ m }: { m: ModelScore }) { + return ( + <table aria-label={`confusion ${m.model}`} className="border-collapse font-mono text-[11px]"> + <caption className="micro mb-1 text-left"> + {m.model} — rows: operator, columns: model + </caption> + <thead> + <tr> + <th /> + {VERDICTS.map((v) => ( + <th key={v} className="px-1.5 py-0.5 text-[var(--color-dim)]" title={v}> + {v.slice(0, 4)} + </th> + ))} + <th className="px-1.5 py-0.5 text-[var(--color-dim)]">none</th> + </tr> + </thead> + <tbody> + {VERDICTS.map((op, i) => ( + <tr key={op}> + <th className="pr-1.5 text-left text-[var(--color-dim)]">{op}</th> + {VERDICTS.map((v, j) => ( + <td + key={v} + data-cell={`${op}:${v}`} + className={`border border-[var(--color-line)] px-1.5 py-0.5 text-right ${i === j && m.matrix[i]![j]! > 0 ? "text-[var(--color-good)]" : m.matrix[i]![j]! > 0 ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`} + > + {m.matrix[i]![j]} + </td> + ))} + <td className="border border-[var(--color-line)] px-1.5 py-0.5 text-right text-[var(--color-dim)]">{m.unanswered[i]}</td> + </tr> + ))} + </tbody> + </table> + ); +} + +function Chip({ href, on, label }: { href: string; on: boolean; label: string }) { + return ( + <Link href={href} aria-current={on ? "true" : undefined} className={badgeVariants({ variant: on ? "on" : "neutral" })}> + {label} + </Link> + ); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -25,8 +25,10 @@ // umtool corrections <project> what the report got wrong, as markdown for the next pass // umtool build <project> [--preset preview|fast|final] [--only ID] [--dry] // umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] +// [--draft-all [--model M]] // an iteration's pipeline: current, windows, prepare, posts, manifest, -// voices, video, podcast, attach, dedupe (resumes at the first step not done) +// voices, video, podcast, attach, dedupe (resumes at the first step not done); +// --draft-all is Draft everything: the drafts between manifest and the fast build // umtool index [--rebuild] [--prune] [--since MS] [--json] // umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>] // [--site-origin URL] [--seed chapters] [--brand archilyzer-media] @@ -70,7 +72,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; -import { CHAIN_STEP_NAMES, planChain } from "../lib/report/chain.mjs"; +import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs"; import { spawn } from "node:child_process"; import { openIndex, signRecord } from "../lib/projects/index-db.mjs"; import { pipelineProcessesFor } from "../lib/report/busy.mjs"; @@ -698,9 +700,11 @@ function usage() { " an empty value (--title '') deletes the field", " umtool corrections <project> what the report got wrong + the walk's coverage", " umtool build <project> [--preset preview|fast|final] [--only ID]", - " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]", + " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M]]", ` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`, " (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)", + ` --draft-all (Draft everything): ${chainStepsOf("draft-all").map((s) => s.name).join(", ")} —`, + " each draft a report-draft job on --model (else its route); a draft that fails does not stop it", " umtool index [--rebuild] [--prune] [--since MS] [--json]", " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters]", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", @@ -971,8 +975,11 @@ async function cmdChain() { const article = positional[0]; const n = Number(positional[1]); if (!article || !Number.isInteger(n) || n < 1) { - die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]"); + die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M]]"); } + const draftAll = has("--draft-all"); + if (val("--model") && !draftAll) die("--model is Draft everything's (--draft-all): the model its drafts run on"); + if (draftAll && has("--final")) die("--draft-all builds the fast cut: a final build refuses drafts nobody has reviewed"); let plan; try { plan = planChain({ @@ -983,14 +990,16 @@ async function cmdChain() { ...(val("--projects-root") ? { projectsRoot: path.resolve(val("--projects-root")) } : {}), ...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}), final: has("--final"), + ...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}) } : {}), }); } catch (err) { die(err.message); } const { start, steps } = plan; + const again = `umtool chain ${article} ${n}${draftAll ? " --draft-all" : ""}`; if (json && has("--dry")) return out({ article, n, start, steps }); if (steps.length === 0) { - console.log(`${article} i${n}: every step of the chain is done (--from <step> runs one again)`); + console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`); return; } console.log(`# ${article} i${n} — the chain from "${start}"`); @@ -1007,7 +1016,7 @@ async function cmdChain() { child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); }); if (code !== 0) { - console.error(`chain: stopped at "${s.label}" (exit ${code}); run \`umtool chain ${article} ${n}\` again to resume there`); + console.error(`chain: stopped at "${s.label}" (exit ${code}); run \`${again}\` again to resume there`); process.exit(1); } } diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx @@ -1,9 +1,9 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { badgeVariants } from "@/components/ui/badge"; -import type { ChainView } from "@/lib/articles/generation"; +import type { ChainMode, ChainView } from "@/lib/articles/generation"; // MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten // steps (lib/report/chain.mjs) as a umtool job — what each step last did, where @@ -15,16 +15,33 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut failed: "blocking", running: "open", cancelled: "info", + skipped: "neutral", }; -export default function ChainPanel({ article, n, label }: { article: string; n: number; label: string }) { +export default function ChainPanel({ + article, + n, + label, + mode = "video", + model, + autoStart = false, +}: { + article: string; + n: number; + label: string; + mode?: ChainMode; + model?: string; + autoStart?: boolean; +}) { + const draftAll = mode === "draft-all"; + const started = useRef(false); const [chain, setChain] = useState<ChainView | null>(null); const [from, setFrom] = useState<string>(""); const [error, setError] = useState(""); const [sending, setSending] = useState(false); const load = useCallback(async () => { - const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" }); + const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? "&mode=draft-all" : ""}`, { cache: "no-store" }); const b = await r.json(); if (!r.ok) { setError(b.error ?? `HTTP ${r.status}`); @@ -32,7 +49,7 @@ export default function ChainPanel({ article, n, label }: { article: string; n: } setChain(b.chain); return b.chain as ChainView; - }, [article, n]); + }, [article, n, draftAll]); const running = chain?.job?.state === "running"; useEffect(() => { @@ -44,11 +61,14 @@ export default function ChainPanel({ article, n, label }: { article: string; n: return () => clearInterval(t); }, [running, load]); - async function start() { + const start = useCallback(async () => { setError(""); setSending(true); try { - const r = await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ article, n, ...(from ? { from } : {}) }) }); + const r = await fetch("/api/articles/chain", { + method: "POST", + body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}) } : {}) }), + }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); if (b.chain) setChain(b.chain); @@ -58,7 +78,15 @@ export default function ChainPanel({ article, n, label }: { article: string; n: } finally { setSending(false); } - } + }, [article, n, from, draftAll, model, load]); + + useEffect(() => { + if (!autoStart || started.current) return; + started.current = true; + void start(); + // Once, on mount: a re-render must not start it again. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [autoStart]); async function cancel() { if (!chain?.job) return; @@ -68,16 +96,31 @@ export default function ChainPanel({ article, n, label }: { article: string; n: const startAt = from || chain?.resumeAt || ""; return ( - <section aria-label={`${label} video chain`} data-chain={label} className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]"> + <section + aria-label={`${label} ${draftAll ? "Draft everything" : "video chain"}`} + data-chain={label} + data-chain-mode={mode} + className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]" + > + {draftAll && ( + <p className="mb-1 text-[11px] text-[var(--color-dim)]"> + {model ? <span className="font-mono">{model}</span> : "each task's route"} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build + </p> + )} {chain && ( - <ol className="grid gap-x-4 gap-y-0.5 sm:grid-flow-col sm:grid-rows-5"> + <ol className={`grid gap-x-4 gap-y-0.5 sm:grid-flow-col ${draftAll ? "sm:grid-rows-8" : "sm:grid-rows-5"}`}> {chain.steps.map((s, i) => ( - <li key={s.name} data-chain-step={s.name} data-step-status={s.status} className="flex items-center gap-2"> + <li key={s.name} data-chain-step={s.name} data-step-status={s.status} title={s.detail ?? undefined} className="flex items-center gap-2"> <span className="num w-5 text-right text-[var(--color-dim)]">{i + 1}</span> - <span className={s.name === startAt && !running ? "text-[var(--color-sel)]" : ""}>{s.label}</span> + <span className={s.name === startAt && !running ? "text-[var(--color-sel)]" : s.optional ? "italic" : ""}>{s.label}</span> {s.status !== "pending" && ( <span className={badgeVariants({ variant: STATUS_VARIANT[s.status] ?? "neutral", size: "sm" })}>{s.status}</span> )} + {s.optional && s.status !== "pending" && s.status !== "running" && s.detail && ( + <span data-chain-step-detail="" className="truncate text-[11px] text-[var(--color-dim)]"> + {s.detail} + </span> + )} </li> ))} </ol> @@ -110,8 +153,8 @@ export default function ChainPanel({ article, n, label }: { article: string; n: ))} </select> </label> - <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={start}> - Run the chain + <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}> + {draftAll ? "Run Draft everything" : "Run the chain"} </Button> </> )} diff --git a/umtool/components/articles/ExtractorSelect.tsx b/umtool/components/articles/ExtractorSelect.tsx @@ -0,0 +1,40 @@ +"use client"; + +// THE EXTRACTOR OF ONE SWEEP (release 28 F2): an API sweep reads its batches +// with a cheap Claude model, `settings.generation.models.extractor` unless a +// job names its own (`report-draft {extractorModel}`). Shown beside a sweep's +// model when that model is Claude's; a choice equal to the policy's sends +// nothing (the editor's default is the same model). + +const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; + +/** The body key for a sweep on `model`: `{extractorModel}` when it is not the policy's. */ +export function extractorBody(model: string, extractor: string, policyExtractor: string | undefined): { extractorModel?: string } { + return model.startsWith("claude-") && extractor && extractor !== policyExtractor ? { extractorModel: extractor } : {}; +} + +export default function ExtractorSelect({ + label, + value, + onChange, + models, +}: { + label: string; + value: string; + onChange: (v: string) => void; + /** Claude's models (an API sweep's extractor runs on the API). */ + models: string[]; +}) { + return ( + <label className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">extractor</span> + <select aria-label={label} className={`${field} font-mono`} value={value} onChange={(e) => onChange(e.target.value)}> + {[...new Set([value, ...models].filter((m) => m && m.startsWith("claude-")))].map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + ); +} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"; import { badgeVariants } from "@/components/ui/badge"; import ChainPanel from "@/components/articles/ChainPanel"; import ResearchSlot from "@/components/articles/ResearchSlot"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import DeletePlan from "@/components/DeletePlan"; import { usd, type Today } from "@/components/articles/PolicyPanel"; import type { ArticleIterations, DraftJobView, IterationRow, PolicyView } from "@/lib/articles/generation"; @@ -28,6 +29,17 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut cancelled: "info", }; +// The media drafts beside narrate (release 28): each a report-draft STEP on a +// done iteration's video manifest. +const MEDIA_TASKS: { task: string; label: string }[] = [ + { task: "cut", label: "the cut" }, + { task: "onscreen", label: "on-screen titles" }, + { task: "teaser", label: "the teaser" }, + { task: "flips", label: "flips" }, + { task: "threads", label: "threads" }, + { task: "youtube", label: "YouTube text" }, +]; + // The report-draft task that made an iteration of this kind (a copy re-runs it). const TASK_OF: Record<string, string | null> = { sweep: "sweep", "revise-report": "revise-report", "revise-video": "revise-video", research: "research" }; @@ -196,10 +208,18 @@ function IterationCard({ comparing: boolean; onCompare: (on: boolean) => void; }) { - const [open, setOpen] = useState<"new" | "chain" | null>(null); + const [open, setOpen] = useState<"new" | "chain" | "draft-all" | null>(null); const g = ctx.policy?.generation; + const routeModel = (t: string) => (g?.routes[t as keyof typeof g.routes] === "api" ? g?.models.api : g?.models.local) ?? ""; + const [mediaTask, setMediaTask] = useState(MEDIA_TASKS[0].task); + const [mediaModel, setMediaModel] = useState(() => routeModel(MEDIA_TASKS[0].task)); + const [mediaForce, setMediaForce] = useState(false); + const [allModel, setAllModel] = useState(() => routeModel("onscreen")); + // Each press of Draft everything mounts a fresh panel that starts it. + const [allRun, setAllRun] = useState(0); const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model); const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? "")); + const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? ""); const done = it.status === "done"; const active = it.status === "queued" || it.status === "running"; const runningStep = it.steps.find((s) => s.status === "running" && s.jobId && !s.task.startsWith("chain:")); @@ -307,6 +327,8 @@ function IterationCard({ post={ctx.post} models={ctx.allModels} sweepModel={g?.routes.sweep === "local" ? g.models.local : (g?.models.api ?? "")} + apiModels={ctx.policy?.models.api ?? []} + extractor={g?.models.extractor} /> )} @@ -324,7 +346,21 @@ function IterationCard({ {task && !active && ( <span className="flex items-center gap-1"> <ModelSelect label={`copy ${it.label} on model`} value={copyModel} onChange={setCopyModel} models={ctx.allModels} /> - <Button size="sm" onClick={() => void ctx.post({ task, article: ctx.article, copyOf: it.n, model: copyModel })}> + {task === "sweep" && copyModel.startsWith("claude-") && ( + <ExtractorSelect label={`extractor for the copy of ${it.label}`} value={copyExtractor} onChange={setCopyExtractor} models={ctx.policy?.models.api ?? []} /> + )} + <Button + size="sm" + onClick={() => + void ctx.post({ + task, + article: ctx.article, + copyOf: it.n, + model: copyModel, + ...(task === "sweep" ? extractorBody(copyModel, copyExtractor, g?.models.extractor) : {}), + }) + } + > Copy with model </Button> </span> @@ -337,6 +373,53 @@ function IterationCard({ </Button> </span> )} + {done && it.hasManifest && !runningStep && ( + <span className="flex items-center gap-1" data-media-draft={it.n}> + <select + aria-label={`draft task for ${it.label}`} + className={field} + value={mediaTask} + onChange={(e) => { + setMediaTask(e.target.value); + setMediaModel(routeModel(e.target.value)); + }} + > + {MEDIA_TASKS.map((t) => ( + <option key={t.task} value={t.task}> + {t.label} + </option> + ))} + </select> + <ModelSelect label={`draft model for ${it.label}`} value={mediaModel} onChange={setMediaModel} models={ctx.allModels} /> + <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title="re-draft fields a model drafted; a field you wrote or edited is never replaced"> + <input type="checkbox" checked={mediaForce} onChange={(e) => setMediaForce(e.target.checked)} aria-label={`force: re-draft drafted fields of ${it.label}`} /> + force + </label> + <Button + size="sm" + onClick={() => + void ctx.post({ task: mediaTask, article: ctx.article, iteration: it.n, model: mediaModel, ...(mediaForce ? { force: true } : {}) }) + } + > + Draft + </Button> + </span> + )} + {done && it.reportFrom !== null && ( + <span className="flex items-center gap-1"> + <ModelSelect label={`Draft everything model for ${it.label}`} value={allModel} onChange={setAllModel} models={ctx.allModels} /> + <Button + size="sm" + aria-expanded={open === "draft-all"} + onClick={() => { + setOpen("draft-all"); + setAllRun((k) => k + 1); + }} + > + Draft everything + </Button> + </span> + )} {done && it.reportFrom !== null && ( <Button size="sm" aria-expanded={open === "chain"} onClick={() => setOpen(open === "chain" ? null : "chain")}> Make the video @@ -358,6 +441,9 @@ function IterationCard({ </div> {open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />} {open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />} + {open === "draft-all" && ( + <ChainPanel key={allRun} article={ctx.article} n={it.n} label={it.label} mode="draft-all" model={allModel} autoStart={allRun > 0} /> + )} </article> ); } diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import PolicyPanel, { type Today } from "@/components/articles/PolicyPanel"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // /articles/new (release 27 S8): a question over channels becomes an article's @@ -117,6 +118,7 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia : (policy?.models.local ?? []); const routeModel = begin === "research" ? researchModel : task === "agent" ? policy?.generation.models.api : policy?.generation.models.local; const [model, setModel] = useState(routeModel ?? ""); + const [extractor, setExtractor] = useState(policy?.generation.models.extractor ?? ""); // A cap is a Claude run's: the agent, or research on a Claude model. const capped = begin === "research" ? model.startsWith("claude-") : task === "agent"; const capDefault = policy?.generation.caps.sweep ?? 5; @@ -153,6 +155,7 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia question, ...(channels.length ? { channels } : {}), model, + ...(begin === "sweep" ? extractorBody(model, extractor, policy?.generation.models.extractor) : {}), ...(from ? { from } : {}), ...(to ? { to } : {}), ...(capped ? { maxUsd } : {}), @@ -264,6 +267,9 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia ))} </select> </label> + {begin === "sweep" && model.startsWith("claude-") && ( + <ExtractorSelect label="extractor for this sweep" value={extractor} onChange={setExtractor} models={policy?.models.api ?? []} /> + )} {capped && ( <label className="flex flex-col gap-1"> <span className="micro">cap $</span> diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; +import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; import { badgeVariants } from "@/components/ui/badge"; import type { IterationRow } from "@/lib/articles/generation"; import type { ResearchProposal, ResearchView } from "@/lib/articles/research"; @@ -18,6 +19,11 @@ import type { ResearchProposal, ResearchView } from "@/lib/articles/research"; // /api/articles/research), which refreshes the enqueued acquisitions from // their jobs; it is re-read every 4 s while the run's job or an acquisition's // is going. +// +// An `auto` run continues by itself once its acquisitions settle (release 28 +// F1, the editor's researchAutoContinue): the queue says "continued +// automatically" with the channels it left out, or why it has not (held for +// a build, refused by a cap). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; @@ -37,6 +43,29 @@ const PHASE_SAYS: Record<ResearchView["phase"], string> = { continued: "continued", }; +// An `auto` run's own continuation: done (by which sweep, and what it left +// out), or why not yet. +function AutoContinued({ ac }: { ac: NonNullable<ResearchView["autoContinue"]> }) { + if (ac.status === "continued") { + return ( + <div data-auto-continued={ac.by ?? ""} className="flex flex-col gap-0.5"> + <span className="text-[var(--color-text)]">continued automatically{ac.by ? ` by i${ac.by}` : ""}</span> + {(ac.warnings ?? []).map((w, i) => ( + <span key={i} className="text-[var(--color-dirty)]"> + {w} + </span> + ))} + </div> + ); + } + if (ac.status === "claimed") return <span data-auto-continue="claimed">continuing automatically…</span>; + return ( + <p data-auto-continue={ac.status} className="text-[var(--color-dirty)]"> + {ac.status === "held" ? "not continued automatically yet" : "not continued automatically today"}: {ac.reason} + </p> + ); +} + // What an acquisition is for, in one line: its channel and what it fetches. function target(p: ResearchProposal): string { const a = p.args; @@ -176,6 +205,8 @@ export default function ResearchSlot({ post, models, sweepModel, + apiModels = [], + extractor, }: { article: string; iteration: IterationRow; @@ -184,12 +215,16 @@ export default function ResearchSlot({ models: string[]; /** The sweep route's model, the continuation's default. */ sweepModel: string; + /** Claude's models, and the policy's extractor: a continuation on Claude may name its own (release 28 F2). */ + apiModels?: string[]; + extractor?: string; }) { const n = iteration.n; const [view, setView] = useState<ResearchView | null>(null); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [model, setModel] = useState(sweepModel); + const [extractorModel, setExtractorModel] = useState(extractor ?? ""); const active = iteration.status === "queued" || iteration.status === "running"; const load = useCallback(async () => { @@ -266,6 +301,7 @@ export default function ResearchSlot({ </> )} </div> + {view?.autoContinue && <AutoContinued ac={view.autoContinue} />} {view?.notes && <p className="whitespace-pre-wrap text-[13px] text-[var(--color-text)]">{view.notes}</p>} {view && view.proposals.length === 0 && !active && <p className="text-[var(--color-dim)]">no acquisitions proposed</p>} {view && view.proposals.length > 0 && ( @@ -289,7 +325,15 @@ export default function ResearchSlot({ </option> ))} </select> - <Button size="sm" variant="primary" disabled={busy} onClick={() => void post({ task: "sweep", article, iteration: n, model })}> + {model.startsWith("claude-") && ( + <ExtractorSelect label={`continuation extractor for ${iteration.label}`} value={extractorModel} onChange={setExtractorModel} models={apiModels} /> + )} + <Button + size="sm" + variant="primary" + disabled={busy} + onClick={() => void post({ task: "sweep", article, iteration: n, model, ...extractorBody(model, extractorModel, extractor) })} + > Continue into a sweep </Button> </div> diff --git a/umtool/components/bench/BarForm.tsx b/umtool/components/bench/BarForm.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { passesBar, type ModelScore, type VerdictBar } from "yt-dlp-transcript-common/lib/report/draft/bench/score"; +import type { GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; + +// THE BAR (release 28 M7): the least agreement, CONTRADICTED recall and +// NOT_FOUND recall a model must reach on this run, and the passing models the +// operator ticks for the verdict proposals — settings.generation.verdicts, +// written whole through /api/bench/bar (the editor's settings action). A +// model is never ticked automatically, and one that fails the bar as typed +// cannot be ticked. + +const KEYS: { key: keyof VerdictBar; label: string }[] = [ + { key: "agreement", label: "minimum agreement" }, + { key: "contradictedRecall", label: "minimum CONTRADICTED recall" }, + { key: "notFoundRecall", label: "minimum NOT_FOUND recall" }, +]; +const field = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; +const toPct = (v: number) => String(Math.round(v * 1000) / 10); + +export default function BarForm({ initial, models }: { initial: GenerationVerdicts; models: ModelScore[] }) { + const [typed, setTyped] = useState(() => Object.fromEntries(KEYS.map((k) => [k.key, toPct(initial.bar[k.key])])) as Record<keyof VerdictBar, string>); + const [ticked, setTicked] = useState<string[]>(initial.models); + const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); + const [busy, setBusy] = useState(false); + const bar = Object.fromEntries(KEYS.map((k) => [k.key, Math.min(100, Math.max(0, Number(typed[k.key]) || 0)) / 100])) as VerdictBar; + // A model ticked in settings but not in this run is kept as it is. + const here = new Set(models.map((m) => m.model)); + + async function save(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + setStatus(null); + const keep = ticked.filter((m) => !here.has(m) || passesBar(models.find((x) => x.model === m)!, bar).pass); + try { + const r = await fetch("/api/bench/bar", { method: "POST", body: JSON.stringify({ bar, models: keep }) }); + const body = await r.json(); + if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); + const v = body.verdicts as GenerationVerdicts; + setTyped(Object.fromEntries(KEYS.map((k) => [k.key, toPct(v.bar[k.key])])) as Record<keyof VerdictBar, string>); + setTicked(v.models); + setStatus({ ok: true, text: "Saved." }); + } catch (err) { + setStatus({ ok: false, text: (err as Error).message }); + } finally { + setBusy(false); + } + } + + return ( + <form aria-label="bar" onSubmit={save} className="flex flex-col gap-2 text-[12px]"> + <div className="flex flex-wrap items-center gap-3"> + <span className="micro">the bar</span> + {KEYS.map((k) => ( + <label key={k.key} className="flex items-center gap-1"> + <span className="text-[var(--color-dim)]">{k.label}</span> + <input + aria-label={k.label} + className={field} + type="number" + min={0} + max={100} + step={0.1} + value={typed[k.key]} + onChange={(e) => setTyped({ ...typed, [k.key]: e.target.value })} + /> + <span className="text-[var(--color-dim)]">%</span> + </label> + ))} + </div> + <div className="flex flex-wrap items-center gap-3"> + <span className="micro">verdict proposals on</span> + {models.map((m) => { + const check = passesBar(m, bar); + const on = ticked.includes(m.model) && check.pass; + return ( + <label key={m.model} data-model={m.model} data-pass={String(check.pass)} className="flex items-center gap-1" title={check.misses.join("; ") || undefined}> + <input + type="checkbox" + aria-label={`use ${m.model}`} + checked={on} + disabled={!check.pass} + onChange={(e) => setTicked(e.target.checked ? [...new Set([...ticked, m.model])] : ticked.filter((x) => x !== m.model))} + /> + <span className="font-mono">{m.model}</span> + <span className={check.pass ? "text-[var(--color-good)]" : "text-[var(--color-bad)]"}>{check.pass ? "passes" : "fails"}</span> + </label> + ); + })} + <Button type="submit" size="sm" disabled={busy}> + Save the bar + </Button> + {status && ( + <span role="status" className={status.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}> + {status.text} + </span> + )} + </div> + </form> + ); +} diff --git a/umtool/components/projects/DraftPanel.tsx b/umtool/components/projects/DraftPanel.tsx @@ -0,0 +1,355 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts"; +import { announceManifestChanged } from "./timelineApi"; +import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; + +// DRAFT WITH <MODEL> (release 28 M9): each draftable section of the cut — +// the cut, on-screen, teaser, flips, threads, narration, YouTube — drafted by +// a model as a `report-draft` step on the iteration the project was made +// from (umtool's /api/articles/generate → the editor). The models are the +// policy's, the task's route preselected; `force` re-drafts only fields a +// model drafted (a field you wrote or edited is never replaced — its draft is +// kept as an alternative); a per-entry task may be limited to the entries +// ticked. While the job runs its progress shows; when it ends the page is +// re-read: the badges, the alternatives with Use this, and what the task's +// draft file says it wrote, skipped and refused. + +type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } }; +type JobView = { status: string; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; tail: string[] }; + +const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; +const ENDED = ["done", "failed", "cancelled"]; + +function RunLine({ run }: { run: DraftRunSummary }) { + const c = run.counts; + const parts = [ + c.applied ? `${c.applied} written` : "", + c.kept ? `${c.kept} kept as an alternative` : "", + c.refused ? `${c.refused} refused by a check` : "", + c.skipped ? `${c.skipped} skipped` : "", + c.none ? `${c.none} with no draft` : "", + ].filter(Boolean); + const failing = run.checks.filter((ch) => !ch.ok); + const problems = run.units.filter((u) => u.outcome === "refused" || u.outcome === "kept" || u.outcome === "none"); + return ( + <div data-draft-run={run.task} className="mt-1 text-[11px] text-[var(--color-dim)]"> + <span> + last run{run.model ? <span className="font-mono"> {run.model}</span> : null} + {run.at ? `, ${new Date(run.at).toLocaleString()}` : ""}: {parts.join(" · ") || "nothing"} + </span> + {failing.map((ch) => ( + <p key={ch.name} data-draft-check={ch.name} className="text-[var(--color-dirty)]"> + check {ch.name}: {ch.detail ?? "failed"} + </p> + ))} + {problems.length > 0 && ( + <ul className="list-disc pl-4"> + {problems.slice(0, 8).map((u) => ( + <li key={u.id} data-draft-unit={u.id} data-draft-outcome={u.outcome}> + <span className="font-mono">{u.label ?? u.id}</span>: {u.why ?? u.outcome} + </li> + ))} + {problems.length > 8 && <li>… and {problems.length - 8} more ({run.file})</li>} + </ul> + )} + </div> + ); +} + +function DraftRow({ + project, + row, + link, + policy, + run, + runningJob, + view, + onEnded, +}: { + project: string; + row: DraftRowView; + link: Extract<ProjectIteration, { ok: true }>; + policy: Policy | null; + run: DraftRunSummary | undefined; + runningJob: string | null; + view: ReturnType<typeof useDrafts>; + onEnded: () => void | Promise<void>; +}) { + const g = policy?.generation; + const routeModel = g ? (g.routes[row.task] === "api" ? g.models.api : g.models.local) : ""; + const models = policy ? [...new Set([routeModel, ...policy.models.api, ...policy.models.local].filter(Boolean))] : []; + const [model, setModel] = useState(routeModel); + useEffect(() => { + if (!model && routeModel) setModel(routeModel); + }, [routeModel, model]); + const [force, setForce] = useState(false); + const [picked, setPicked] = useState<string[]>([]); + const [jobId, setJobId] = useState<string | null>(runningJob); + const [job, setJob] = useState<JobView | null>(null); + const [error, setError] = useState(""); + const [sending, setSending] = useState(false); + + useEffect(() => { + if (runningJob) setJobId(runningJob); + }, [runningJob]); + + // The latest callback, so the poll below depends on the job alone; and each + // job's end is told once (a re-render after the refresh must not tell it again). + const ended = useRef(onEnded); + ended.current = onEnded; + const told = useRef<string | null>(null); + useEffect(() => { + if (!jobId) return; + let alive = true; + let stop = false; + const tick = async () => { + if (stop) return; + try { + const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=6`, { cache: "no-store" }); + const b = await r.json(); + if (!alive) return; + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setJob(b.job); + if (ENDED.includes(b.job.status)) { + stop = true; + if (told.current !== jobId) { + told.current = jobId; + void ended.current(); + } + } + } catch (e) { + if (alive) setError((e as Error).message); + } + }; + void tick(); + const t = setInterval(tick, 2000); + return () => { + alive = false; + clearInterval(t); + }; + }, [jobId]); + + const active = !!jobId && !!job && !ENDED.includes(job.status); + const start = async () => { + setError(""); + setSending(true); + try { + const body = { + task: row.task, + article: link.article, + iteration: link.n, + ...(model ? { model } : {}), + ...(force ? { force: true } : {}), + ...(picked.length ? { entries: picked } : {}), + }; + const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify(body) }); + const b = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setJob(null); + setJobId(String(b.jobId)); + } catch (e) { + setError((e as Error).message); + } finally { + setSending(false); + } + }; + const cancel = async () => { + if (!jobId) return; + const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) }); + if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`); + }; + const p = job?.progress; + const queued = job?.status === "queued" && (job.queue?.position ?? 0) > 0; + + return ( + <li data-draft-task={row.task} data-draft-job={job?.status ?? (jobId ? "asking" : "")} className="border-t border-[var(--color-line)] py-1.5 first:border-t-0"> + <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> + <h3 className="text-[13px] text-[var(--color-text)]">{row.label}</h3> + <span className="text-[11px] text-[var(--color-dim)]">{row.writes}</span> + <span data-draft-state="" className="ml-auto text-[11px]"> + {row.state} + </span> + </div> + {row.blocked ? ( + <p data-draft-blocked="" className="text-[11px] text-[var(--color-dim)]"> + {row.blocked} + </p> + ) : ( + <div className="mt-1 flex flex-wrap items-center gap-2"> + <Button size="sm" variant="primary" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}> + Draft with + </Button> + <select aria-label={`model for ${row.label}`} className={`${field} font-mono`} value={model} onChange={(e) => setModel(e.target.value)} disabled={!policy}> + {models.map((m) => ( + <option key={m} value={m}> + {m} + {m === routeModel ? " (route)" : ""} + </option> + ))} + </select> + <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]"> + <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label={`force: re-draft ${row.label}`} /> + force — re-drafts only what a model drafted; a field you wrote or edited is never replaced + </label> + {row.entries && row.entries.length > 0 && ( + <details className="text-[11px]"> + <summary className="cursor-pointer text-[var(--color-dim)]">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary> + <div className="mt-1 flex max-h-40 flex-col gap-0.5 overflow-auto"> + {row.entries.map((e) => ( + <label key={e.id} className="flex items-center gap-1"> + <input + type="checkbox" + aria-label={`only ${e.id} (${row.label})`} + checked={picked.includes(e.id)} + onChange={(ev) => setPicked(ev.target.checked ? [...picked, e.id] : picked.filter((x) => x !== e.id))} + /> + <span className="font-mono">{e.label}</span> + </label> + ))} + </div> + </details> + )} + </div> + )} + {jobId && job && !ENDED.includes(job.status) && ( + <div data-draft-progress={row.task} className="mt-1 flex flex-wrap items-center gap-2 text-[11px]"> + <span role="status" className="text-[var(--color-dirty)]"> + {queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status} + {p ? ` — ${p.metric} ${p.current}/${p.target}` : ""} + </span> + {job.tail.length > 0 && <span className="truncate font-mono text-[var(--color-dim)]">{job.tail[job.tail.length - 1]}</span>} + <Button size="sm" variant="destructive" aria-label={`Cancel the ${row.label} draft`} onClick={() => void cancel()}> + Cancel + </Button> + </div> + )} + {jobId && job && ENDED.includes(job.status) && ( + <p data-draft-ended={job.status} className={`mt-1 text-[11px] ${job.status === "done" ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}`}> + the draft {job.status === "done" ? "is done" : job.status} + {job.status !== "done" && job.tail.length ? `: ${job.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""} + </p> + )} + {run && <RunLine run={run} />} + {row.address && ( + <div className="mt-1"> + <DraftBadge address={row.address} view={view.view} act={view.act} compact /> + <DraftAlternatives address={row.address} view={view.view} act={view.act} /> + </div> + )} + {!row.address && run && run.alternatives > 0 && ( + <Link href={`/browse/${project}/review`} className="text-[11px] text-[var(--color-sel)] hover:underline"> + {run.alternatives} alternative(s) kept — review them + </Link> + )} + {error && ( + <p role="alert" className="mt-1 text-[11px] text-[var(--color-bad)]"> + {error} + </p> + )} + </li> + ); +} + +export default function DraftPanel({ + project, + link, + rows, + runs: initialRuns, +}: { + project: string; + link: ProjectIteration; + rows: DraftRowView[]; + runs: Partial<Record<string, DraftRunSummary>>; +}) { + const router = useRouter(); + const view = useDrafts(project); + const [policy, setPolicy] = useState<Policy | null>(null); + const [policyError, setPolicyError] = useState(""); + const [runs, setRuns] = useState(initialRuns); + const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {}); + + useEffect(() => { + if (!link.ok) return; + let alive = true; + void (async () => { + const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null); + const b = r ? await r.json().catch(() => ({})) : {}; + if (!alive) return; + if (r?.ok && b.policy) setPolicy(b.policy as Policy); + else setPolicyError(b.error ?? "the editor did not answer"); + })(); + return () => { + alive = false; + }; + }, [link.ok]); + + // A draft ended: the manifest changed under every section — re-read it all. + const onEnded = useCallback(async (): Promise<void> => { + const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null); + if (r?.ok) { + const b = await r.json(); + setRuns(b.runs ?? {}); + if (b.link?.ok) setRunning(b.link.running ?? {}); + } + announceManifestChanged(project); + announceDraftsChanged(project); + router.refresh(); + }, [project, router]); + + return ( + <section aria-label="draft with a model" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <div className="mb-1 flex flex-wrap items-baseline gap-3"> + <h2 className="micro">draft</h2> + {link.ok && ( + <span className="text-[11px] text-[var(--color-dim)]"> + steps on{" "} + <Link href={`/articles/${link.article}?tab=iterations`} className="font-mono text-[var(--color-sel)] hover:underline"> + {link.article} i{link.n} + </Link> + </span> + )} + {link.ok && ( + <span className={badgeVariants({ variant: "info", size: "sm" })}>a final build refuses a draft nobody approved</span> + )} + </div> + {!link.ok ? ( + <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]"> + {link.why} + </p> + ) : link.status !== "done" ? ( + <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]"> + {link.article} i{link.n} is {link.status}: a draft runs over a done iteration + </p> + ) : ( + <> + {policyError && ( + <p role="alert" className="text-[12px] text-[var(--color-bad)]"> + {policyError}: drafting needs the editor + </p> + )} + <ul> + {rows.map((row) => ( + <DraftRow + key={row.task} + project={project} + row={row} + link={link} + policy={policy} + run={runs[row.task]} + runningJob={running[row.task] ?? null} + view={view} + onEnded={onEnded} + /> + ))} + </ul> + </> + )} + </section> + ); +} diff --git a/umtool/components/projects/DraftsReview.tsx b/umtool/components/projects/DraftsReview.tsx @@ -0,0 +1,89 @@ +"use client"; + +import Link from "next/link"; +import { DraftAlternatives, DraftBadge, useDrafts, type DraftsView } from "./drafts"; + +// `/browse/<project>/review`'s list (release 28, M0): every drafted field of +// the cut -- who drafted it, its value as words, its review -- and every +// alternative a draft task kept, with "Use this". A narration's words are +// edited and played on the narration page; here they are judged like any +// other draft. + +export default function DraftsReview({ project, initial }: { project: string; initial: DraftsView }) { + const { view, act } = useDrafts(project, initial); + const v = view ?? initial; + const drafted = v.rows.filter((r) => r.drafted); + const shown = new Set(drafted.map((r) => r.address)); + // Alternatives for fields that are not drafted (the operator's), by field. + const loose = [...new Set(v.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))]; + const where = (entry: string | null, field: string) => (entry ? `${entry}` : field); + return ( + <div className="space-y-3"> + <p + data-drafts-gate={v.gate.errors.length ? "refuses" : "passes"} + data-gate-errors={v.gate.errors.length} + className="text-[11px] text-[var(--color-dim)]" + > + {v.error ? ( + <span className="text-[var(--color-bad)]">{v.error}</span> + ) : v.gate.errors.length ? ( + <> + A final build refuses {v.gate.errors.length} field{v.gate.errors.length === 1 ? "" : "s"} until approved ( + <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one). + </> + ) : ( + <>A final build takes every draft as it is.</> + )}{" "} + Verdicts in <code className="font-mono">{v.file}</code>. + </p> + {drafted.length === 0 && loose.length === 0 && ( + <p data-drafts-empty="" className="text-[12px] text-[var(--color-dim)]"> + Nothing in this cut was drafted.{" "} + <Link href={`/browse/${project}`} className="text-[var(--color-sel)] hover:underline"> + back to {project} + </Link> + </p> + )} + {drafted.map((r) => ( + <article + key={r.address} + data-draft-row={r.address} + data-state={r.state} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="font-mono text-[12px] text-[var(--color-text)]">{where(r.entry, r.field)}</span> + <span className="micro">{r.label}</span> + {r.field === "narration" && ( + <Link href={`/browse/${project}/narration`} className="text-[11px] text-[var(--color-sel)] hover:underline"> + edit and play on the narration page + </Link> + )} + </div> + <p data-draft-text="" className="mb-1 whitespace-pre-wrap text-[13px] text-[var(--color-text)]"> + {r.text || "—"} + </p> + {r.state === "edited" && r.judgedText && ( + <p className="mb-1 text-[11px] text-[var(--color-dim)]"> + {r.verdict} on: <span className="italic">{r.judgedText}</span> + </p> + )} + <DraftBadge address={r.address} view={v} act={act} /> + <DraftAlternatives address={r.address} view={v} act={act} /> + </article> + ))} + {loose.map((address) => { + const a = v.alternatives.find((x) => x.address === address)!; + return ( + <article key={address} data-draft-row={address} data-state="operator" className="rounded border border-[var(--color-line)] px-3 py-2"> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="font-mono text-[12px] text-[var(--color-text)]">{where(a.entry, a.field)}</span> + <span className="micro">{a.label} · yours; a draft was kept aside</span> + </div> + <DraftAlternatives address={address} view={v} act={act} /> + </article> + ); + })} + </div> + ); +} diff --git a/umtool/components/projects/NarrationPage.tsx b/umtool/components/projects/NarrationPage.tsx @@ -9,8 +9,9 @@ import NarrationReview, { type NarrationView } from "./NarrationReview"; // `/browse/<project>/narration` -- the cut's narration script, card by card, // before synthesis (release 25, T5): each narrated card's words beside what // the card shows, approved, edited or rejected, and played through the editor. -// Verdicts are <project>/narration.review.json; the build refuses an -// un-approved card once that file exists. +// Verdicts are <project>/drafts.review.json (release 25's +// narration.review.json still read); the build refuses an un-approved card +// once the cut's narration has a verdict, and a final build a drafted one. export default async function NarrationPage({ project }: { project: ProjectRef }) { const manifest = await readManifest(project.dir); const view = (await narrationReviewView(project.dir, manifest ?? {})) as NarrationView; diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx @@ -3,6 +3,8 @@ import { useEffect, useRef, useState } from "react"; import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; +import { MANIFEST_CHANGED } from "./timelineApi"; +import { DraftAlternatives, useDrafts, type DraftAct, type DraftsView } from "./drafts"; // The narration script of one cut, card by card (release 25, T5). // @@ -27,6 +29,8 @@ export type NarrationRow = { estimate: number; seconds: number | string | null; screen: { kicker: string | null; heading: string | null; sub: string | null; title: string | null; style: string | null }; + /** Who drafted these words (release 28); null: written by hand. */ + drafted: { task: string; model: string; at: string; iteration?: number; attempt: number } | null; state: "approved" | "rejected" | "edited" | "unreviewed"; verdict: "approved" | "rejected" | null; note: string; @@ -57,6 +61,17 @@ export default function NarrationReview({ project, initial, token: initialToken const [token, setToken] = useState(initialToken); const [ready, setReady] = useState(false); useEffect(() => setReady(true), []); + // The alternatives a draft task kept for a card whose words are the + // operator's (release 28); "Use this" rewrites the manifest, so re-read. + const drafts = useDrafts(project); + useEffect(() => { + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void refresh(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + return () => window.removeEventListener(MANIFEST_CHANGED, on); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project]); const act = async (card: string, action: string, extra: Record<string, unknown> = {}) => { const r = await fetch("/api/report/narration", { @@ -88,18 +103,18 @@ export default function NarrationReview({ project, initial, token: initialToken ) : view.exists ? ( <> Verdicts in <code className="font-mono">{view.file}</code>: a build refuses any narrated card not approved on - its current words (<code className="font-mono">--narration-unreviewed</code> builds them anyway; never a - rejected one). + its current words — a drafted one, a final build (<code className="font-mono">--narration-unreviewed</code>{" "} + builds them anyway; never a rejected one). </> ) : ( <> Nothing judged yet. The first verdict writes <code className="font-mono">{view.file}</code>, and from then on a - build refuses any narrated card not approved. + build refuses any narrated card not approved (a drafted one: a final build, judged or not). </> )} </p> {view.rows.map((r) => ( - <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} /> + <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} /> ))} </div> ); @@ -111,12 +126,16 @@ function NarrationCard({ ready, act, refresh, + drafts, + draftAct, }: { project: string; row: NarrationRow; ready: boolean; act: (card: string, action: string, extra?: Record<string, unknown>) => Promise<void>; refresh: () => Promise<NarrationView | null>; + drafts: DraftsView | null; + draftAct: DraftAct; }) { const [text, setText] = useState(r.text); const [note, setNote] = useState(r.note); @@ -192,6 +211,15 @@ function NarrationCard({ <span data-narration-state="" className={badgeVariants({ variant: STATE[r.state].tone, size: "sm" })}> {STATE[r.state].label} </span> + {r.drafted && ( + <span + data-narration-drafted={r.drafted.model} + className={badgeVariants({ variant: "info", size: "sm" })} + title={`drafted by ${r.drafted.task} on ${r.drafted.model}, ${r.drafted.at}`} + > + drafted by {r.drafted.model} + </span> + )} <span className="font-mono text-[11px] text-[var(--color-dim)]" data-narration-voice=""> {r.engine} · {r.voice} {r.speed !== 1 ? ` · ×${r.speed}` : ""} @@ -290,6 +318,7 @@ function NarrationCard({ <audio ref={audio} controls preload="none" src={audioSrc(project, r)} data-narration-audio="" className="h-8 w-full" /> )} {r.kept && <p className="text-[11px] text-[var(--color-dim)]">{r.kept.disclosure}</p>} + <DraftAlternatives address={`narrate/${r.id}/narration`} view={drafts} act={draftAct} /> {error && ( <p data-narration-error="" className="text-[11px] text-[var(--color-bad)]"> {error} diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -4,6 +4,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { TimedVideo } from "@/components/notes/TimedNotes"; import StructureEditors from "./StructureEditors"; import { MANIFEST_CHANGED } from "./timelineApi"; +import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts"; import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { badgeVariants } from "@/components/ui/badge"; @@ -835,6 +836,9 @@ export default function OnscreenSection({ // The switch as pressed, while its write is in flight: the box follows the // hand at once and falls back to the manifest's answer if the write fails. const [switching, setSwitching] = useState<boolean | null>(null); + // The drafts review (release 28): a drafted title's badge, and the + // alternatives kept for a title that is the operator's. + const review = useDrafts(project); // One token for the manifest, shared by both writers here: a settings save // moves it, and the table's next save must carry the moved one. A ref, as // in the clip bench, because two saves can be in flight before a render. @@ -1133,6 +1137,8 @@ export default function OnscreenSection({ return next; }); setNote(`saved ${Object.keys(saved).length} row${Object.keys(saved).length === 1 ? "" : "s"}`); + // An edited draft is the operator's now: the badges re-read. + announceDraftsChanged(project); }), [queued, dirtyIds, project, draftMap, rows], ); @@ -1415,6 +1421,8 @@ export default function OnscreenSection({ }} className={`${field} w-full ${over(shown) ? "border-[var(--color-dirty)]" : "border-[var(--color-line)]"}`} /> + <DraftBadge address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} compact /> + <DraftAlternatives address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} /> </td> <td className={`num px-1.5 py-1 text-right font-mono text-[11px] ${over(shown) ? "text-[var(--color-dirty)]" : "text-[var(--color-dim)]"}`} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -8,6 +8,7 @@ import ClaimBenchPage from "./ClaimBenchPage"; import SweepProject from "./SweepProject"; import TakesPage from "./TakesPage"; import NarrationPage from "./NarrationPage"; +import ReviewPage from "./ReviewPage"; // --------------------------------------------------------------------------- // The one place a kind id is matched against a component. @@ -57,6 +58,9 @@ export default async function ProjectView({ // `/browse/<project>/narration` -- the narration script, card by card, // approved / edited / rejected before synthesis. if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />; + // `/browse/<project>/review` -- every drafted field, approved / rejected + // before a final build, and the alternatives a draft task kept. + if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -20,7 +20,11 @@ import { listSnapshots, readSnapshot } from "@/lib/report/snapshots.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { podcastFor } from "@/lib/report/serve.mjs"; import { narrationsOf } from "umtool-report-to-video/narration"; +import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { readAlternatives } from "@/lib/report/drafts.mjs"; import DeliverSection from "./DeliverSection"; +import DraftPanel from "./DraftPanel"; +import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/projectDraft"; import FetchUnfetchedButton from "./FetchUnfetchedButton"; import OnscreenSection from "./OnscreenSection"; import PodcastExport from "./PodcastExport"; @@ -28,6 +32,7 @@ import ReportBuildChain from "./ReportBuildChain"; import SnapshotButton from "./SnapshotButton"; import DeleteProject from "./DeleteProject"; import TagCitedButton from "./TagCitedButton"; +import YoutubeSection from "./YoutubeSection"; import { RowControls, RowNotes, TimelineList } from "./TimelineEditor"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { NotesProvider } from "@/components/notes/NotesProvider"; @@ -149,6 +154,14 @@ export default async function ReportProject({ const podcasts = new Map(await Promise.all(variants.map(async (v) => [v, await podcastOf(v)] as const))); const takes = await listTakes(project.dir); const narrated = narrationsOf(m).length; + // The drafts review (release 28): drafted fields, and alternatives kept. + // (A field a code path made — the converter's timeline — is not a draft to review.) + const draftedCount = draftedFields(m).filter((d) => !isCodeDraft(d.provenance)).length; + const alternativesCount = (await readAlternatives(project.dir)).length; + // "Draft with" (release 28 M9): the iteration the project was made from, and + // each media task's last run here. + const draftLink = await projectIteration(project.dir); + const draftRunsNow = draftLink.ok ? await draftRuns(project.dir) : {}; // Provenance splits by SHAPE: a scalar or a URL stays in the table; a long // string, or one with a newline, is prose the author wrote and reads as a @@ -261,6 +274,17 @@ export default async function ReportProject({ Narration — {narrated} </Link> )} + {/* Every drafted field, judged before a final build -- only when a + draft task wrote one, or kept an alternative. */} + {(draftedCount > 0 || alternativesCount > 0) && ( + <Link + href={`/browse/${project.id}/review`} + data-review-link={draftedCount} + className={buttonVariants({ size: "lg" })} + > + Review drafts — {draftedCount} + </Link> + )} {takes.exists && ( <Link href={`/browse/${project.id}/takes`} @@ -459,6 +483,13 @@ export default async function ReportProject({ entries={entries.map((e) => ({ id: e.id, kind: e.kind }))} /> + {/* --- drafting it ----------------------------------------------- */} + {/* Each draftable section drafted by a model, as a step on the + iteration the project was made from. After the build chain (a + draft changes what the next build makes), before the sections it + writes into. */} + <DraftPanel project={project.id} link={draftLink} rows={draftRowsOf(m as Record<string, unknown>)} runs={draftRunsNow} /> + {/* --- what is drawn over it --------------------------------------- */} {/* The on-screen panel: its settings, its words and a live preview of both. After the build chain, because "re-render on-screen" is a run @@ -743,6 +774,9 @@ export default async function ReportProject({ )} </section> + {/* --- the upload's text (out/youtube.txt, or its preview) --------- */} + <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> + {/* --- exports --------------------------------------------------- */} <section data-exports="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> <h2 className="micro mb-1">export</h2> diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx @@ -0,0 +1,39 @@ +import BrowseHeader from "@/components/BrowseHeader"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { manifestToken } from "@/lib/report/manifest.mjs"; +import { draftsView } from "@/lib/report/drafts.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import DraftsReview from "./DraftsReview"; +import type { DraftsView } from "./drafts"; + +// `/browse/<project>/review` -- every drafted field of the cut, approved or +// rejected before a final build (release 28, M0). Verdicts are +// <project>/drafts.review.json; a final build refuses a drafted field not +// approved on its current value. The narration page is the narration's own +// view of the same verdicts. +export default async function ReviewPage({ project }: { project: ProjectRef }) { + const manifest = await readManifest(project.dir); + const view = { ...((await draftsView(project.dir, manifest ?? {})) as DraftsView), token: await manifestToken(project.dir) }; + const { counts } = view; + return ( + <div className="flex h-full flex-col"> + <BrowseHeader + crumbs={[ + { href: "/browse", label: "projects" }, + { href: `/browse/${project.id}`, label: project.id }, + { label: "review" }, + ]} + note={ + view.drafted + ? `${view.drafted} drafted · ${counts.approved} approved` + + (counts.rejected ? ` · ${counts.rejected} rejected` : "") + + (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "") + : undefined + } + /> + <main className="deck-main flex-1 space-y-4 p-4"> + <DraftsReview project={project.id} initial={view} /> + </main> + </div> + ); +} diff --git a/umtool/components/projects/StructureEditors.tsx b/umtool/components/projects/StructureEditors.tsx @@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider"; import { buttonVariants } from "@/components/ui/button"; import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from "./timelineApi"; +import { DraftAlternatives, DraftBadge, useDrafts, type DraftAct, type DraftsView } from "./drafts"; // The parts of the cut that are lists, edited in place: each teaser's lines // and timing, the posts, and the fact-check's labels and colours. Every save @@ -34,6 +35,8 @@ export default function StructureEditors({ project }: { project: string }) { const [doc, setDoc] = useState<Doc | null>(null); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); + // The drafts review (release 28): a drafted teaser's badge and alternatives. + const drafts = useDrafts(project); const load = useCallback(async () => { const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" }); @@ -79,7 +82,14 @@ export default function StructureEditors({ project }: { project: string }) { </p> )} {doc.teasers.map((t) => ( - <TeaserEditor key={`${t.id}@${t.at}`} teaser={t} busy={busy} save={(patch) => run("teaser", { id: t.id, at: t.at, patch })} /> + <TeaserEditor + key={`${t.id}@${t.at}`} + teaser={t} + busy={busy} + save={(patch) => run("teaser", { id: t.id, at: t.at, patch })} + drafts={drafts.view} + act={drafts.act} + /> ))} <PostsEditor posts={doc.posts} busy={busy} save={(post) => run("post", { post })} remove={(id) => run("post-remove", { id })} /> {doc.deckOn && <FactcheckEditor doc={doc} busy={busy} save={(factcheck) => run("factcheck", { factcheck })} />} @@ -87,7 +97,19 @@ export default function StructureEditors({ project }: { project: string }) { ); } -function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean; save: (patch: Record<string, unknown>) => Promise<boolean> }) { +function TeaserEditor({ + teaser: t, + busy, + save, + drafts, + act, +}: { + teaser: Teaser; + busy: boolean; + save: (patch: Record<string, unknown>) => Promise<boolean>; + drafts: DraftsView | null; + act: DraftAct; +}) { // Plain lines edit as one per row; a teaser whose lines carry settings // (break, role, replace…) edits as the JSON it is, so nothing is dropped. const plain = t.lines.every((l) => typeof l === "string"); @@ -147,6 +169,8 @@ function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean </button> {local && <span className="text-[var(--color-bad)]">{local}</span>} </div> + <DraftBadge address={`teaser/${t.id}/lines`} view={drafts} act={act} /> + <DraftAlternatives address={`teaser/${t.id}/lines`} view={drafts} act={act} /> </div> ); } diff --git a/umtool/components/projects/YoutubeSection.tsx b/umtool/components/projects/YoutubeSection.tsx @@ -0,0 +1,53 @@ +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import CopyButton from "@/components/CopyButton"; +import { fmtAgo } from "@/lib/format"; +import { youtubePreview, youtubeTextName } from "umtool-report-to-video/youtube"; + +// The upload's text (release 28 M6): what the build wrote to +// out/youtube.txt — the title, the summary, the chapters and the sources — +// or, before a build, the same text composed from the manifest without the +// chapters. Shown with Copy. Nothing when the cut has no publish.youtube and +// no built text. + +type Props = { dir: string; manifest: Record<string, unknown> }; + +export default async function YoutubeSection({ dir, manifest }: Props) { + const file = path.join(dir, "out", youtubeTextName("sourced")); + const built = await readFile(file, "utf8").catch(() => null); + const mtimeMs = built === null ? null : await stat(file).then((s) => s.mtimeMs, () => null); + const preview = youtubePreview(manifest); + const text = built ?? preview.text; + if (!text) return null; + const yt = (manifest.publish as { youtube?: { title?: string; description?: string } } | undefined)?.youtube; + // The built text starts with the title and the summary as they were then. + const head = [yt?.title?.trim(), yt?.description?.trim()].filter(Boolean).join("\n\n"); + const stale = built !== null && !!head && !built.startsWith(head); + const drafted = (manifest.drafted as Record<string, { model?: string }> | undefined)?.["publish.youtube"]; + return ( + <section + data-youtube={built !== null ? "built" : "preview"} + aria-label="YouTube text" + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <div className="mb-1 flex flex-wrap items-baseline gap-3"> + <h2 className="micro">youtube</h2> + <span className="num text-[11px] text-[var(--color-dim)]" data-youtube-status=""> + {built !== null + ? `out/${youtubeTextName("sourced")}${mtimeMs ? `, built ${fmtAgo(mtimeMs)}` : ""}${stale ? " — the title or summary has changed since: rebuild" : ""}` + : `preview — ${preview.note}`} + {drafted ? ` · drafted by ${drafted.model ?? "a model"}` : ""} + </span> + <span className="ml-auto"> + <CopyButton text={text} label="Copy" title="copy the YouTube title and description" /> + </span> + </div> + <pre + data-youtube-text="" + className="max-h-[40vh] overflow-y-auto whitespace-pre-wrap break-words font-mono text-[11px] text-[var(--color-text)]" + > + {text} + </pre> + </section> + ); +} diff --git a/umtool/components/projects/drafts.tsx b/umtool/components/projects/drafts.tsx @@ -0,0 +1,233 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { MANIFEST_CHANGED, announceManifestChanged } from "./timelineApi"; + +// The drafts review on the page (release 28, M0): who drafted a field, its +// review state, Approve / Reject (with a note), and the alternatives a draft +// task kept for a field it was not allowed to replace, each with "Use this". +// +// One view per section (`useDrafts`), read from /api/report/drafts and +// re-read after any write to the manifest (MANIFEST_CHANGED) or the review +// (DRAFTS_CHANGED), so a badge in the On-screen table and one on the review +// page agree. The server is the word on every state: each action answers with +// the whole view. + +export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: number }; +export type DraftRow = { + address: string; + entry: string | null; + field: string; + label: string; + drafted: Provenance | null; + text: string; + state: "approved" | "rejected" | "edited" | "unreviewed"; + verdict: "approved" | "rejected" | null; + note: string; + judgedText: string; + judgedAt: string; +}; +export type DraftAlternative = { + id: string; + file: string; + address: string; + entry: string | null; + field: string; + label: string; + text: string; + value: unknown; + provenance: Provenance | null; + reason: string; + inUse: boolean; +}; +export type DraftsView = { + file: string; + exists: boolean; + error: string | null; + rows: DraftRow[]; + alternatives: DraftAlternative[]; + counts: Record<DraftRow["state"], number>; + drafted: number; + gate: { errors: string[]; warnings: string[] }; + token?: string | null; +}; + +export const DRAFTS_CHANGED = "umtool:drafts-changed"; +export function announceDraftsChanged(project: string) { + window.dispatchEvent(new CustomEvent(DRAFTS_CHANGED, { detail: { project } })); +} + +export type DraftAct = (action: string, extra?: Record<string, unknown>) => Promise<void>; + +/** The project's drafts view, kept fresh; `act` runs one action and adopts the answer. */ +export function useDrafts(project: string, initial: DraftsView | null = null): { view: DraftsView | null; act: DraftAct; reload: () => Promise<void> } { + const [view, setView] = useState<DraftsView | null>(initial); + const reload = useCallback(async () => { + const r = await fetch(`/api/report/drafts?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + if (r.ok) setView((await r.json()) as DraftsView); + }, [project]); + useEffect(() => { + if (!initial) void reload(); + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void reload(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + window.addEventListener(DRAFTS_CHANGED, on); + return () => { + window.removeEventListener(MANIFEST_CHANGED, on); + window.removeEventListener(DRAFTS_CHANGED, on); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project, reload]); + const act = useCallback<DraftAct>( + async (action, extra = {}) => { + const r = await fetch("/api/report/drafts", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, action, ...extra }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as DraftsView & { ok?: boolean; error?: string; errors?: string[] }; + if (!r.ok || !j.ok) throw new Error(j.errors?.length ? j.errors.join("; ") : (j.error ?? `HTTP ${r.status}`)); + setView(j); + // A taken alternative changed the manifest: every editor re-reads it. + if (action === "use") announceManifestChanged(project); + else announceDraftsChanged(project); + }, + [project], + ); + return { view, act, reload }; +} + +const STATE: Record<DraftRow["state"], { label: string; tone: BadgeVariants["variant"] }> = { + approved: { label: "approved", tone: "meter" }, + rejected: { label: "rejected", tone: "blocking" }, + edited: { label: "changed since approved", tone: "on" }, + unreviewed: { label: "not reviewed", tone: "open" }, +}; + +/** + * "drafted by <model>", its review state, and Approve / Reject (+ note) for the + * field at `address`. Nothing when the field is not drafted. + */ +export function DraftBadge({ address, view, act, compact = false }: { address: string; view: DraftsView | null; act: DraftAct; compact?: boolean }) { + const row = view?.rows.find((r) => r.address === address && r.drafted) ?? null; + const [note, setNote] = useState(row?.note ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [ready, setReady] = useState(false); + useEffect(() => setReady(true), []); + useEffect(() => setNote(row?.note ?? ""), [row?.note]); + if (!row || !row.drafted) return null; + const run = async (action: string, extra: Record<string, unknown> = {}) => { + setBusy(true); + setError(null); + try { + await act(action, { address, ...extra }); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + const s = STATE[row.state]; + return ( + <div data-draft-badge={address} data-state={row.state} className={`flex flex-wrap items-center gap-1 ${compact ? "mt-0.5" : ""} text-[11px]`}> + <span + data-draft-by="" + className={badgeVariants({ variant: "info", size: "sm" })} + title={`drafted by ${row.drafted.task} on ${row.drafted.model}, ${row.drafted.at}${row.drafted.iteration ? ` (i${row.drafted.iteration})` : ""}, attempt ${row.drafted.attempt}`} + > + drafted by {row.drafted.model} + </span> + <span data-draft-state="" className={badgeVariants({ variant: s.tone, size: "sm" })}> + {s.label} + </span> + <button + type="button" + data-draft-action="approve" + aria-pressed={row.state === "approved"} + disabled={!ready || busy} + title="approve this draft as it is now" + className={buttonVariants({ variant: row.state === "approved" ? "primary" : "outline", size: "sm" })} + onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })} + > + {row.state === "approved" ? "Approved" : "Approve"} + </button> + <button + type="button" + data-draft-action="reject" + aria-pressed={row.state === "rejected"} + disabled={!ready || busy} + title="reject this draft; the note says what is wrong" + className={buttonVariants({ variant: row.state === "rejected" ? "destructive" : "outline", size: "sm" })} + onClick={() => void run(row.state === "rejected" ? "clear" : "reject", row.state === "rejected" ? {} : { note })} + > + {row.state === "rejected" ? "Rejected" : "Reject"} + </button> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + onBlur={() => { + if (note.trim() !== row.note && row.verdict) void run("note", { note }); + }} + disabled={!ready || busy} + placeholder="note (a rejection needs one)" + aria-label={`note on the draft of ${address}`} + data-draft-note="" + maxLength={2000} + className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + {error && ( + <span data-draft-error="" className="basis-full text-[var(--color-bad)]"> + {error} + </span> + )} + </div> + ); +} + +/** The alternatives kept for the field at `address`, each with "Use this". */ +export function DraftAlternatives({ address, view, act }: { address: string; view: DraftsView | null; act: DraftAct }) { + const alts = (view?.alternatives ?? []).filter((a) => a.address === address && !a.inUse); + const [busy, setBusy] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const [ready, setReady] = useState(false); + useEffect(() => setReady(true), []); + if (!alts.length) return null; + return ( + <div data-draft-alternatives={address} className="mt-0.5 space-y-0.5 text-[11px]"> + {alts.map((a) => ( + <div key={a.id} data-draft-alternative={a.id} className="flex flex-wrap items-center gap-1.5 text-[var(--color-dim)]"> + <span className="micro">alternative{a.provenance ? ` · ${a.provenance.model}` : ""}</span> + <span data-draft-alternative-text="" className="italic text-[var(--color-text)]"> + {a.text || "(empty)"} + </span> + <button + type="button" + data-draft-use="" + disabled={!ready || busy !== null} + title="write this instead of what the field holds, as your own edit" + className={buttonVariants({ size: "sm" })} + onClick={() => { + setBusy(a.id); + setError(null); + act("use", { alternative: a.id }) + .catch((e) => setError(e instanceof Error ? e.message : String(e))) + .finally(() => setBusy(null)); + }} + > + {busy === a.id ? "writing…" : "Use this"} + </button> + </div> + ))} + {error && ( + <p data-draft-error="" className="text-[var(--color-bad)]"> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/docs/authoring.md b/umtool/docs/authoring.md @@ -117,6 +117,7 @@ sweep** makes the report once it is in (OPERATING.md, "Research runs"). ```sh pnpm ops report-draft --json '{"task":"sweep","article":"<id>","question":"…","channels":["<slug>"]}' --wait umtool chain <id> <n> # the iteration to a video and a podcast +umtool chain <id> <n> --draft-all # Draft everything: the media drafts, voices, the fast cut, the podcast pnpm ops report-draft --json '{"task":"revise-video","article":"<id>","iteration":<n>,"feedback":"…"}' --wait pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n>}' --wait ``` @@ -137,6 +138,22 @@ pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n> is removed. The manifest before it is kept in `revisions/<stamp>-auto-before-narration.manifest.json`, the draft in `narration-draft.json`. +- **The media drafts** (cut, on-screen, teaser, flips, threads, narration, + YouTube) each draft fields of the iteration's cut, marked as drafts: the + project page's **draft** section (**Draft with** a model per task), the + Iterations tab, or `pnpm ops report-draft` with `iteration`. A field you + wrote or edited is never replaced; the draft waits in `<task>-draft.json` + as an alternative (**Use this**). `force` re-drafts a model's field only. + The limits per task are OPERATING.md's table ("Generate and iterate"). +- **Draft everything** (`umtool chain <id> <n> --draft-all [--model M]`) + drafts them all in the chain's order, then voices, builds the fast cut and + the podcast, then drafts the YouTube text and writes `out/youtube.txt`. A + failed draft does not stop it; flips and threads need the deck, and one + panel only. +- **Review every draft before a final build:** `/browse/<project>/review`, + approve or reject with a note. A fast build warns; `--preset final` + refuses an unapproved or rejected draft (`--drafts-unreviewed` overrides + the unapproved). - **Then review it as a hand-made cut:** `umtool check`, steps 4–6, and a fast pass watched end to end. A generated window is the cue span plus its pad, so widen or lock it as in step 4. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -811,14 +811,27 @@ rules and the validator. **The narration review** — `/browse/<project>/narration`, linked from the project page as **Narration — N** — is the script card by card before synthesis: -the words beside what the card shows, Approve / Reject (a note required) / Save -words / Play. Verdicts live in `narration.review.json` beside the manifest -(the shape of `takes/verdicts.json`); `GET|POST /api/report/narration`, +the words beside what the card shows, who drafted them, Approve / Reject (a note +required) / Save words / Play. `GET|POST /api/report/narration`, `POST /api/report/narration/play` (a job: `narrate-via-editor.mjs --only`), -`GET /api/report/narration/audio`. Once the file exists, a build refuses any -narrated card not approved on its current words (`--narration-unreviewed` -builds unreviewed and edited ones; a rejected one never). The README's "The -narration review" has the rules. +`GET /api/report/narration/audio`. Once a narration verdict exists, a build +refuses any hand-written narrated card not approved on its current words +(`--narration-unreviewed` builds unreviewed and edited ones; a rejected one +never). + +**The drafts review** (release 28) — `/browse/<project>/review`, linked as +**Review drafts — N** when a draft task wrote a field — lists every drafted +field (on-screen text, a narration, a teaser's lines, the cut's order, the +flips, the threads, the YouTube text): who drafted it, its value, Approve / +Reject (a note required), and the alternatives a task kept for a field that is +the operator's, each with **Use this**. The same badge sits beside the field in +the On-screen table, the teaser editor and on the narration page. Verdicts — +the narration's included — live in `drafts.review.json` beside the manifest +(release 25's `narration.review.json` is still read); `GET|POST +/api/report/drafts`. A final build refuses a drafted field not approved on its +current value (`--drafts-unreviewed` builds the unapproved; a rejected one +never); a preview or fast build warns. An edit in umtool makes a drafted field +the operator's: its mark goes. The README's "The drafts review" has the rules. ## Re-checking sources across projects diff --git a/umtool/e2e/article-new.spec.ts b/umtool/e2e/article-new.spec.ts @@ -91,14 +91,20 @@ test("a new article: question, channels, the local pipeline — its first iterat await form.getByRole("button", { name: "Start" }).click(); await expect(form.getByRole("alert")).toContainText("at most the policy's $5"); + // The agent's extractor is the policy's unless this sweep names its own (release 28 F2). + await expect(form.getByRole("combobox", { name: "extractor for this sweep" })).toHaveValue("claude-haiku-4-5"); + await form.getByRole("combobox", { name: "extractor for this sweep" }).selectOption("claude-haiku-5-5"); + await form.getByRole("radio", { name: /pipeline/ }).check(); await expect(form.getByRole("combobox", { name: "model" })).toHaveValue("qwen3:8b"); + await expect(form.getByRole("combobox", { name: "extractor for this sweep" }), "the pipeline has no extractor").toHaveCount(0); await form.getByRole("button", { name: "Start" }).click(); await expect(page).toHaveURL(new RegExp(`/articles/${ARTICLE}\\?tab=iterations$`)); const asked = stubAsked("report-draft").at(-1)!; expect(asked).toMatchObject({ task: "sweep", article: ARTICLE, question: "What did the channel say about the vote?", channels: ["sitechan"], model: "qwen3:8b" }); expect(asked).not.toHaveProperty("maxUsd"); + expect(asked).not.toHaveProperty("extractorModel"); const first = page.locator("[data-iteration='1']"); await expect(first).toHaveAttribute("data-kind", "sweep"); diff --git a/umtool/e2e/article-research.spec.ts b/umtool/e2e/article-research.spec.ts @@ -25,7 +25,10 @@ test.beforeAll(async ({ playwright }) => { test.setTimeout(WARM_TIMEOUT); await warm(playwright, ["/articles/new", "/api/articles/policy", "/api/articles/channels", "/articles/zeta?tab=iterations"]); }); -test.afterAll(() => rmSync(path.join(FIXTURE, "articles", ARTICLE), { recursive: true, force: true })); +const AUTO = "research-auto-e2e"; +test.afterAll(() => { + for (const a of [ARTICLE, AUTO]) rmSync(path.join(FIXTURE, "articles", a), { recursive: true, force: true }); +}); test("research: started with an autonomy, its queue answered yes and no, its job followed, then continued into a sweep", async ({ page }) => { test.setTimeout(120_000); @@ -110,6 +113,33 @@ test("research: started with an autonomy, its queue answered yes and no, its job await expect(page.locator("[data-iteration='1'] [data-continued-by]")).toHaveAttribute("data-continued-by", "2"); }); +// Release 28 F1: an `auto` run whose acquisitions settled is continued by the +// editor itself — umtool asks for nothing, and its queue says so. +test("research: an auto run continues into its sweep by itself, and the queue says so", async ({ page }) => { + test.setTimeout(120_000); + await page.goto("/articles/new"); + const form = page.getByRole("form", { name: "new article" }); + await form.getByRole("radio", { name: /^research/ }).check(); + await form.getByRole("combobox", { name: "autonomy" }).selectOption("auto"); + await form.getByRole("textbox", { name: "question" }).fill("Where did the recount story start?"); + await form.getByRole("textbox", { name: "article id" }).fill(AUTO); + await form.getByRole("button", { name: "Start" }).click(); + await expect(page).toHaveURL(new RegExp(`/articles/${AUTO}\\?tab=iterations$`)); + expect(stubAsked("report-draft").at(-1)).toMatchObject({ task: "research", article: AUTO, autonomy: "auto" }); + + const slot = page.locator("[data-iteration='1']").getByRole("region", { name: "i1 research" }); + await expect(slot.locator("[data-auto-continued]")).toHaveAttribute("data-auto-continued", "2", { timeout: 20_000 }); + await expect(slot.locator("[data-auto-continued]")).toContainText("continued automatically by i2"); + await expect(slot.locator("[data-auto-continued]")).toContainText("not in any build yet: radio-tape"); + await expect(slot).toHaveAttribute("data-research-phase", "continued"); + const sweep = page.locator("[data-iteration='2']"); + await expect(sweep).toHaveAttribute("data-kind", "sweep"); + await expect(sweep).toContainText("of i1"); + await expect(sweep).toContainText("unbuilt channels: not in any build yet: radio-tape"); + // Umtool posted no sweep: the editor made it. + expect(stubAsked("report-draft").filter((r) => r.article === AUTO).map((r) => r.task)).toEqual(["research"]); +}); + test("the research route refuses what is not a decision", async ({ request }) => { const bad = await request.post("/api/articles/research", { data: { article: ARTICLE, n: 1, ids: ["p01"] } }); expect(bad.status()).toBe(400); diff --git a/umtool/e2e/draft-review.spec.ts b/umtool/e2e/draft-review.spec.ts @@ -0,0 +1,125 @@ +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// The drafts review (release 28, M0). A drafted field shows "drafted by +// <model>" and its review state beside it, with Approve / Reject (a note +// required); an edit makes it the operator's (the mark goes); the review page +// lists every drafted field, and an alternative a draft task kept for the +// operator's field is written with "Use this"; a FINAL build refuses a drafted +// field until it is approved, then builds. Verdicts are drafts.review.json +// beside the manifest. Fixtures: e2e/fixtures/draft-review-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/draft-review-fixture"; +const DIR = path.join(FIXTURE, "reports", "draft-review-fixture"); +const BUILD_PROJECT = "reports/draft-review-build-fixture"; +const BUILD_DIR = path.join(FIXTURE, "reports", "draft-review-build-fixture"); + +type Entry = { id: string; onscreen?: { title?: string }; drafted?: Record<string, unknown>; lines?: unknown[] }; +const manifest = (dir = DIR) => JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")) as { timeline: Entry[] }; +const entry = (id: string, dir = DIR) => manifest(dir).timeline.find((e) => e.id === id)!; +const review = (dir = DIR): Record<string, { verdict: string | null; note: string }> => { + const f = path.join(dir, "drafts.review.json"); + return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : {}; +}; + +test("badges: drafted by <model>, approve, reject with a note; an edit makes the field the operator's", async ({ page }) => { + await page.goto(`/browse/${PROJECT}`); + await expect(page.locator("[data-review-link]")).toHaveAttribute("data-review-link", "3"); + + // The On-screen table (folded: the deck is off) -- c02's title was drafted, c01's was not. + await page.getByTestId("onscreen-words-folded").locator("summary").click(); + const c02 = page.locator('[data-draft-badge="onscreen/c02/onscreen"]'); + await expect(c02).toHaveAttribute("data-state", "unreviewed"); + await expect(c02.locator("[data-draft-by]")).toHaveText("drafted by qwen3:8b"); + await expect(page.locator('[data-draft-badge="onscreen/c01/onscreen"]')).toHaveCount(0); + await c02.locator('[data-draft-action="approve"]').click(); + await expect(c02).toHaveAttribute("data-state", "approved"); + expect(review()["onscreen/c02/onscreen"].verdict).toBe("approved"); + + // The teaser's lines: a rejection needs its note. + await page.getByTestId("structure-folded").locator("summary").click(); + const t01 = page.locator('[data-draft-badge="teaser/t01/lines"]'); + await expect(t01.locator("[data-draft-by]")).toHaveText("drafted by claude-sonnet-5-5"); + await t01.locator('[data-draft-action="reject"]').click(); + await expect(t01.locator("[data-draft-error]")).toContainText("a rejection needs its note"); + await t01.locator("[data-draft-note]").fill("the lease is not next season"); + await t01.locator('[data-draft-action="reject"]').click(); + await expect(t01).toHaveAttribute("data-state", "rejected"); + expect(review()["teaser/t01/lines"]).toMatchObject({ verdict: "rejected", note: "the lease is not next season" }); + + // Edit c02's drafted title: saved through the manifest writer, it is the + // operator's now -- no mark, no badge. + const row = page.locator('[data-testid="onscreen-row"][data-entry="c02"]'); + await row.getByTestId("onscreen-title").fill("My own title"); + await page.getByTestId("onscreen-save").click(); + await expect(c02).toHaveCount(0); + expect(entry("c02").onscreen).toEqual({ title: "My own title" }); + expect(entry("c02").drafted).toBeUndefined(); +}); + +test("the review page: every drafted field, the narration's badge, and Use this for the operator's field", async ({ page }) => { + await page.goto(`/browse/${PROJECT}`); + await page.locator("[data-review-link]").click(); + await expect(page).toHaveURL(new RegExp(`/browse/${PROJECT}/review$`)); + // The narration and the teaser are drafted; a final build would refuse them. + const k01 = page.locator('[data-draft-row="narrate/k01/narration"]'); + await expect(k01).toHaveAttribute("data-state", "unreviewed"); + await expect(k01.locator("[data-draft-text]")).toHaveText("Half a year on, the county said yes."); + await expect(page.locator('[data-draft-row="teaser/t01/lines"]')).toBeVisible(); + await expect(page.locator("[data-drafts-gate]")).toHaveAttribute("data-drafts-gate", "refuses"); + + // c01's title is the operator's: the draft that could not replace it is an + // alternative under it. Use this writes it as the operator's edit. + const alt = page.locator('[data-draft-alternatives="onscreen/c01/onscreen"]'); + await expect(alt.locator("[data-draft-alternative-text]")).toHaveText("Kept aside title"); + await alt.locator("[data-draft-use]").click(); + await expect(alt).toHaveCount(0); + expect(entry("c01").onscreen).toEqual({ title: "Kept aside title" }); + expect(entry("c01").drafted).toBeUndefined(); + + // Approve the narration here; the narration page shows who drafted it, and its state. + await k01.locator('[data-draft-action="approve"]').click(); + await expect(k01).toHaveAttribute("data-state", "approved"); + await page.goto(`/browse/${PROJECT}/narration`); + const card = page.locator('[data-narration-card="k01"]'); + await expect(card.locator("[data-narration-drafted]")).toHaveText("drafted by qwen3:8b"); + await expect(card).toHaveAttribute("data-state", "approved"); +}); + +async function build(request: APIRequestContext, replace = false) { + const start = await request.post(`/api/report/build${replace ? "?replace=1" : ""}`, { data: { project: BUILD_PROJECT, preset: "final" } }); + expect(start.ok(), await start.text()).toBeTruthy(); + const { job } = (await start.json()) as { job: { id: string } }; + let done: { state: string; error: string | null } = { state: "running", error: null }; + const until = Date.now() + 240_000; + while (Date.now() < until) { + done = (await (await request.get(`/api/report/build?job=${job.id}`)).json()) as typeof done; + if (done.state !== "running") break; + await new Promise((r) => setTimeout(r, 400)); + } + return done; +} + +test("a final build refuses an unapproved draft, and builds once it is approved", async ({ page, request }) => { + test.setTimeout(360_000); + const refused = await build(request); + expect(refused.state).toBe("failed"); + expect(JSON.stringify(refused)).toContain("timeline c02: its on-screen text (drafted by qwen3:8b) is not approved"); + expect(existsSync(path.join(BUILD_DIR, "out", "draft-review-build-fixture.mp4"))).toBe(false); + + await page.goto(`/browse/${BUILD_PROJECT}/review`); + const row = page.locator('[data-draft-row="onscreen/c02/onscreen"]'); + await row.locator('[data-draft-action="approve"]').click(); + await expect(row).toHaveAttribute("data-state", "approved"); + await expect(page.locator("[data-drafts-gate]")).toHaveAttribute("data-drafts-gate", "passes"); + + const done = await build(request); + expect(done.state, done.error ?? "").toBe("done"); + expect(existsSync(path.join(BUILD_DIR, "out", "draft-review-build-fixture.mp4"))).toBe(true); +}); diff --git a/umtool/e2e/fixtures/bench-fixture.mjs b/umtool/e2e/fixtures/bench-fixture.mjs @@ -0,0 +1,79 @@ +// A verdict bench run, synthetic (release 28 M7), for verdict-bench.spec.ts: +// four invented claims ruled CORROBORATED, PARTLY, CONTRADICTED and +// NOT_FOUND, asked of two models — one right on three (it calls the PARTLY +// one CORROBORATED), one that always says CORROBORATED and fails to parse +// once. Written as `archilyzer reports bench-verdicts` writes a run +// (common/lib/report/draft/bench/store.ts); the page scores it again. + +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const BENCH_RUN = "vb-e2e"; +export const SONNET = "claude-sonnet-5-5"; +export const QWEN = "qwen3:8b"; + +const claims = [ + ["c1", "The article says she opened the shop in spring.", "CORROBORATED"], + ["c2", "The article says the oven was broken for a month.", "PARTLY"], + ["c3", "The article says she sold the van.", "CONTRADICTED"], + ["c4", "The article says she named the supplier.", "NOT_FOUND"], +]; +const said = { + [SONNET]: ["CORROBORATED", "CORROBORATED", "CONTRADICTED", "NOT_FOUND"], + [QWEN]: ["CORROBORATED", "CORROBORATED", "CORROBORATED", null], +}; + +export function makeBenchRun(root) { + const dir = path.join(root, BENCH_RUN); + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir, { recursive: true }); + const items = claims.map(([id, text, verdict], i) => ({ + key: `synth-bench/${id}`, + report: "synth-bench", + claim: id, + text, + verdict, + quotes: [{ citation: `q${i}`, channel: "synth-kitchen", id: "bread-day-01", start: 10 + i * 15, end: 14 + i * 15, quote: "a line" }], + windows: [{ channel: "synth-kitchen", id: "bread-day-01", from: 0, to: 80, cited: [{ start: 10 + i * 15, end: 14 + i * 15 }], cues: [{ start: 10 + i * 15, end: 14 + i * 15, text: "a line" }] }], + })); + const results = []; + for (const [model, verdicts] of Object.entries(said)) { + items.forEach((it, i) => { + const v = verdicts[i]; + results.push({ + key: it.key, + model, + verdict: v, + ...(v ? { reason: `${model} read the window for ${it.claim}` } : { failure: "parse", error: "the answer is not JSON" }), + ms: 1200 + i * 100, + usd: model === SONNET ? 0.004 : 0, + inputTokens: 900, + outputTokens: 60, + at: "2026-10-13T12:00:00.000Z", + }); + }); + } + const jsonl = (rows) => rows.map((r) => `${JSON.stringify(r)}\n`).join(""); + writeFileSync(path.join(dir, "items.jsonl"), jsonl(items)); + writeFileSync(path.join(dir, "results.jsonl"), jsonl(results)); + writeFileSync( + path.join(dir, "summary.json"), + JSON.stringify({ + format: "archilyzer-verdict-bench", + version: 1, + id: BENCH_RUN, + createdAt: "2026-10-13T12:00:00.000Z", + updatedAt: "2026-10-13T12:05:00.000Z", + status: "done", + models: [SONNET, QWEN], + windowS: 60, + maxUsd: 5, + reports: [], + spentUsd: 0.016, + items: items.length, + skipped: [{ key: "synth-bench/c5", report: "synth-bench", claim: "c5", reason: "no citation" }], + score: {}, + }), + ); + return dir; +} diff --git a/umtool/e2e/fixtures/draft-review-fixture.mjs b/umtool/e2e/fixtures/draft-review-fixture.mjs @@ -0,0 +1,80 @@ +// What draft-review.spec.ts reviews (release 28, M0): two report projects whose +// fields carry drafted marks, so the badges, the review page, "Use this" and +// the final build's refusal have something to act on. Their own, so the other +// specs' projects are never touched. +// +// reports/draft-review-fixture/ writable, deck off, never built: +// c01 on-screen text written BY HAND (the operator's), and an +// alternative for it in onscreen-draft.json (a draft that was not +// allowed to replace it) +// c02 on-screen text DRAFTED by qwen3:8b +// k01 a chapter card whose narration was DRAFTED +// t01 a teaser whose lines were DRAFTED by claude-sonnet-5-5 +// reports/draft-review-build-fixture/ two clips over the cached window, c02's +// on-screen text DRAFTED: a final build refuses it until approved +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const AT = "2026-10-13T10:00:00.000Z"; +const P = (task, model = "qwen3:8b") => ({ task, model, at: AT, iteration: 1, attempt: 1 }); + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string }} o + * `manifest` is make-fixture's manifest(slug, title, provenance, timeline); + * `cachedWindow` the vid1 0-9 s window the build fixtures share. + */ +export function makeDraftReviewFixture({ reports, manifest, cachedWindow }) { + const ui = path.join(reports, "draft-review-fixture"); + write( + ui, + "video.manifest.json", + manifest("draft-review-fixture", "The Draft Review Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because", onscreen: { title: "Hand title" } }, + { + type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence", + onscreen: { title: "Drafted title" }, drafted: { onscreen: P("onscreen") }, + }, + { + type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "The county", + narration: { text: "Half a year on, the county said yes." }, drafted: { narration: P("narrate") }, + }, + { + type: "teaser", id: "t01", lines: ["Next Season", "The lease", "Spring 2027"], + drafted: { lines: P("teaser", "claude-sonnet-5-5") }, + }, + ]), + ); + write(ui, "onscreen-draft.json", { + task: "onscreen", + model: "qwen3:8b", + at: AT, + article: "draft-review", + iteration: 1, + units: {}, + checks: [], + alternatives: [{ target: { entry: "c01", field: "onscreen" }, value: { title: "Kept aside title" }, provenance: P("onscreen"), reason: "operator" }], + }); + + const build = path.join(reports, "draft-review-build-fixture"); + write( + build, + "video.manifest.json", + manifest("draft-review-build-fixture", "The Draft Review Build Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" }, + { + type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence", + onscreen: { title: "Drafted title" }, drafted: { onscreen: P("onscreen") }, + }, + ]), + ); + mkdirSync(path.join(build, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(build, "out", "clips-raw", path.basename(cachedWindow))); + return { ui, build }; +} diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -16,10 +16,12 @@ // entry, ready when its own endpoint answers. import http from "node:http"; -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import path from "node:path"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { fileURLToPath } from "node:url"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -111,6 +113,9 @@ function writeWindow(dir, name, seconds) { // `iteration` continues a research run, as the editor does. // Sentinels: a question or feedback containing "slow" keeps running until // cancelled; feedback "refuse" is refused (400) as the editor refuses. +// A media draft (release 28) runs the real task over the kit's article +// (mdraft; startMediaDraft), canned over the surfaces' (msurf; +// startCannedDraft) — every isStepTask step answered. const ARTICLES = process.env.ARTICLES_DIR ?? ""; const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? ""; const PRESETS = { @@ -185,11 +190,12 @@ function finishDraft(job) { } const claude = it.model.startsWith("claude-"); const usage = claude ? { [it.model]: { usd: 0.37, inputTokens: 41000, outputTokens: 2100, calls: 6 } } : {}; - const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [{ name: "strict-quotes", ok: true }] }; + // A check written beside the job (auto-continue's) is kept, as the task's own merge does. + const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [...(it.checks ?? []).filter((c) => c.name !== "strict-quotes"), { name: "strict-quotes", ok: true }] }; if (it.kind === "research") { const autonomy = job.autonomy ?? "propose"; writeFileSync(path.join(itDir(article, n), "proposals.json"), JSON.stringify(stubProposals(autonomy), null, 2) + "\n"); - patch.research = { autonomy, phase: "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." }; + patch.research = { autonomy, phase: autonomy === "auto" ? "ready" : "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." }; delete patch.checks; } else if (it.kind === "sweep") { writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, `Sweep: ${it.question ?? "a copy"}`), null, 2) + "\n"); @@ -212,6 +218,20 @@ function finishDraft(job) { patchIt(article, n, patch); job.status = "done"; job.log.push("stub: wrote the iteration", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`); + if (it.kind === "research" && job.autonomy === "auto") autoContinue(article, n); +} + +// An `auto` run's acquisitions have settled: the editor continues it by +// itself (release 28 F1, controller/researchAutoContinue.ts) — a sweep on the +// run's model over the channels in a build (the new channel is in none: left +// out, with the warning), recorded on the run and as a failed check on the sweep. +function autoContinue(article, n) { + const r = readIt(article, n); + const warning = "not in any build yet: radio-tape — rebuild the site and continue again"; + const { iteration: by } = startDraft({ task: "sweep", article, iteration: n, model: r.model, channels: ["sitechan"] }); + patchIt(article, by, { checks: [{ name: "unbuilt channels", ok: false, detail: warning }] }); + const now = readIt(article, n); + patchIt(article, n, { research: { ...now.research, autoContinue: { status: "continued", at: new Date().toISOString(), by, warnings: [warning] } } }); } // ─── research (release 27 S11) ─── @@ -219,6 +239,18 @@ function finishDraft(job) { // What the stub's research run proposes: as the real run under `propose` // (every acquisition waits; the Twitch VOD refused by the standing rule). function stubProposals(autonomy) { + // Under `auto` (release 28 F1): the import ran and the channel was made; + // the Twitch VOD is refused in every mode. + if (autonomy === "auto") { + const base = stubProposals("propose"); + const doneAt = new Date().toISOString(); + base.autonomy = "auto"; + base.spent = { items: 1, gb: 0.2, transcribeHours: 0 }; + base.proposals[0] = { ...base.proposals[0], status: "done", jobId: "stub-acq-auto", doneAt }; + base.proposals[1] = { ...base.proposals[1], status: "done", channel: "radio-tape", doneAt }; + for (const p of base.proposals.slice(0, 2)) delete p.note; + return base; + } return { format: "archilyzer-research-proposals", version: 1, @@ -295,6 +327,7 @@ function researchView(article, n, st) { }, continuedBy: rec.continuedBy ?? [], ...(rec.notes ? { notes: rec.notes } : {}), + ...(rec.autoContinue ? { autoContinue: rec.autoContinue } : {}), }; } @@ -342,7 +375,7 @@ function settleResearch(body) { // A sweep continuing research run `rn`: its question, its channels widened by // what was acquired (refused while it waits, unless force). -function continuation(article, rn, force) { +function continuation(article, rn, force, given) { const r = readIt(article, rn); if (r.kind !== "research") throw new Error(`a sweep with "iteration" continues a research run; "${article}" i${rn} is a ${r.kind} iteration`); if (r.status !== "done") throw new Error(`"${article}" i${rn} is ${r.status}: only a done research run is continued`); @@ -355,13 +388,199 @@ function continuation(article, rn, force) { if (p.status !== "done") continue; for (const c of [p.channel, p.args?.slug]) if (typeof c === "string" && !channels.includes(c)) channels.push(c); } - return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels } }; + return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels: given ?? channels } }; +} + +// The media drafts (release 28) run FOR REAL: the common task over the +// fixture iteration's project, its model the fake ollama scripted with the +// test kit's recorded run (common/testing/draft/runMediaStep.ts, a child under +// tsx). The task records its own step; the job follows the child. +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); +const MEDIA_RUN = new Set(["cut", "onscreen", "teaser"]); +function startMediaDraft(body, id) { + const { task, article } = body; + const n = body.iteration; + const it = readIt(article, n); + if (it.status !== "done") throw new Error(`"${article}" i${n} is ${it.status}: a ${task} draft runs over a done iteration`); + const job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub: the task, the fake model)`], timers: [], child: null }; + draftJobs.set(id, job); + const args = [ + path.join(REPO, "common/testing/draft/runMediaStep.ts"), + "--task", task, "--article", article, "--n", String(n), "--articles", ARTICLES, "--projects", GEN_PROJECTS, "--job", id, + ...(body.model ? ["--model", body.model] : []), + ...(Array.isArray(body.entries) ? ["--entries", body.entries.join(",")] : []), + ...(body.force ? ["--force"] : []), + ]; + job.timers.push( + setTimeout(() => { + if (job.status !== "queued") return; + job.status = "running"; + const child = spawn(path.join(REPO, "node_modules/.bin/tsx"), args, { cwd: REPO, stdio: ["ignore", "pipe", "pipe"] }); + job.child = child; + let buf = ""; + const take = (d) => { + buf += d; + const lines = buf.split("\n"); + buf = lines.pop(); + job.log.push(...lines.filter(Boolean)); + }; + child.stdout.on("data", take); + child.stderr.on("data", take); + child.on("close", (code) => { + if (buf) job.log.push(buf); + if (job.status === "cancelled") return; + job.status = code === 0 ? "done" : "failed"; + }); + }, 500), + ); + return { jobId: id, iteration: n }; +} + +// The surfaces' article (release 28 M9, media-surfaces-fixture.mjs) is drafted +// CANNED, every media task: its fixed value written through applyDraft — +// the mark, the operator's field never replaced (kept as an alternative), a +// field already written skipped unless force — and a `<task>-draft.json` +// beside the manifest in the scaffold's shape, the step recorded on the +// iteration and the job's progress reported as `entries`. What each task +// does on msurf's cuts (no deck, no teaser entry): +// cut its two clips swapped done +// onscreen a title and subtitle per clip (entries) done +// teaser refused by a check (the stub's) failed +// flips, threads no deck to draw on failed +// narrate a line on each card that has none done +// youtube a title and a summary done +const CANNED_ARTICLES = new Set(["msurf"]); +const MEDIA_TASKS = new Set(["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +function cannedUnits(task, m, body) { + const tl = m.timeline ?? []; + const pick = (es) => (Array.isArray(body.entries) ? es.filter((e) => body.entries.includes(e.id)) : es); + switch (task) { + case "cut": { + const clips = tl.filter((e) => e.type === "clip").map((e) => e.id); + const at = clips.slice(0, 2).map((id) => tl.findIndex((e) => e.id === id)); + const order = [...tl]; + if (at.length === 2) [order[at[0]], order[at[1]]] = [order[at[1]], order[at[0]]]; + return [{ id: "cut", target: { field: "timeline" }, value: order }]; + } + case "onscreen": + return pick(tl.filter((e) => e.type === "clip")).map((e) => ({ + id: e.id, + target: { entry: e.id, field: "onscreen" }, + value: { title: `What ${e.id} shows`, subtitle: "From the county vote" }, + })); + case "teaser": + return [{ id: "teaser", target: { entry: "teaser", field: "lines" }, value: ["The county", "The vote"], hard: ["(the stub) 2 lines: a teaser has 3 to 5"] }]; + case "flips": + case "threads": + return { refused: `the cut has no on-screen deck (render.chrome) to draw the ${task} on` }; + case "narrate": + return pick(tl.filter((e) => e.type === "card")).map((e) => ({ + id: e.id, + target: { entry: e.id, field: "narration" }, + value: { text: `${e.heading ?? "This part"}, as the channel told it.` }, + })); + case "youtube": + return [{ id: "youtube", target: { field: "publish.youtube" }, value: { title: "The county vote, as the channel told it", description: "The channel said it twice, and the county voted." } }]; + } + return []; +} + +function readFieldOf(m, t) { + if (t.entry) return (m.timeline ?? []).find((e) => e.id === t.entry)?.[t.field]; + if (t.field === "timeline") return m.timeline; + if (t.field === "publish.youtube") return m.publish?.youtube; + return undefined; +} + +function cannedRun(job, body) { + const { task, article, n } = job; + const it = readIt(article, n); + const dir = it.projectDir; + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(readFileSync(file, "utf8")); + const model = body.model ?? generation.models.local; + const at = new Date().toISOString(); + const draftFile = path.join(dir, task === "narrate" ? "narration-draft.json" : `${task}-draft.json`); + const earlier = existsSync(draftFile) ? (JSON.parse(readFileSync(draftFile, "utf8")).alternatives ?? []) : []; + const units = {}; + const alternatives = []; + let applied = 0; + let summary; + const planned = cannedUnits(task, m, body); + if (!Array.isArray(planned)) { + summary = planned.refused; + } else { + planned.forEach((u, i) => { + job.progress = { metric: "entries", initial: 0, current: i, target: planned.length }; + const has = readFieldOf(m, u.target) !== undefined && !(u.target.field === "timeline" && isCodeDraft(draftedOf(m, u.target))); + if (has && !body.force) { + units[u.id] = { target: u.target, skipped: `the field has a value (${ownerOf(m, u.target)}'s): force re-drafts a draft` }; + return; + } + const chosen = { value: u.value, hard: u.hard ?? [], soft: [] }; + units[u.id] = { target: u.target, attempts: [chosen], chosen }; + if (chosen.hard.length) return; + const provenance = makeProvenance({ task, model, at, iteration: n, attempt: 1 }); + const force = !!body.force || (u.target.field === "timeline" && isCodeDraft(draftedOf(m, u.target))); + const r = applyDraft(m, { ...u.target, value: u.value, provenance, force }); + units[u.id].applied = r.applied ? "applied" : r.reason; + // As narrate's afterApply: a narrated card is as long as its words. + if (r.applied && u.target.field === "narration") for (const e of m.timeline) if (e.id === u.target.entry) e.seconds = "auto"; + if (r.applied) applied++; + else alternatives.push({ target: u.target, value: u.value, provenance, reason: r.reason }); + }); + job.progress = { metric: "entries", initial: 0, current: planned.length, target: planned.length }; + if (applied) writeFileSync(file, JSON.stringify(m, null, 2) + "\n"); + const refused = Object.values(units).filter((u) => u.chosen?.hard?.length).length; + summary = + applied || alternatives.length + ? `${applied} ${task} field(s) drafted${alternatives.length ? `, ${alternatives.length} as alternatives (see ${path.basename(draftFile)})` : ""}` + : `no ${task} drafted (see ${path.basename(draftFile)})${refused ? `: ${refused} refused by a check` : ""}`; + } + const ok = applied > 0 || alternatives.length > 0; + writeFileSync( + draftFile, + JSON.stringify( + { task, model, at, article, iteration: n, units, checks: [{ name: task, ok, detail: summary }], alternatives: [...earlier, ...alternatives].slice(-5) }, + null, + 2, + ) + "\n", + ); + const status = ok ? "done" : "failed"; + const cur = readIt(article, n); + patchIt(article, n, { steps: cur.steps.map((s) => (s.jobId === job.id ? { ...s, status, endedAt: at, minutes: 0.1, detail: summary } : s)) }); + job.status = status; + job.log.push(`${task}: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task, status, summary })}`); +} + +function startCannedDraft(body, id) { + const { task, article } = body; + const n = body.iteration; + const it = readIt(article, n); + if (it.status !== "done") throw new Error(`"${article}" i${n} is ${it.status}: a ${task} draft runs over a done iteration`); + const model = body.model ?? generation.models.local; + patchIt(article, n, { steps: [...it.steps, { task, model, status: "running", startedAt: new Date().toISOString(), jobId: id }] }); + const job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub: canned)`], timers: [] }; + draftJobs.set(id, job); + job.timers.push( + setTimeout(() => { + job.status = "running"; + job.progress = { metric: "entries", initial: 0, current: 0, target: 1 }; + job.log.push(`drafting the ${task} (stub)`); + }, 400), + ); + job.timers.push(setTimeout(() => cannedRun(job, body), 1600)); + return { jobId: id, iteration: n }; } function startDraft(body) { const { task, article } = body; const now = new Date().toISOString(); const id = `stub-draft-${nextJob++}`; + if (MEDIA_TASKS.has(task) && CANNED_ARTICLES.has(article)) return startCannedDraft(body, id); + if (MEDIA_RUN.has(task)) return startMediaDraft(body, id); let n; if (task === "narrate") { n = body.iteration; @@ -377,7 +596,7 @@ function startDraft(body) { } else if (task === "research") { base = { kind: "research", parent: null, copyOf: null, question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}) } }; } else if (task === "sweep" && body.iteration) { - base = continuation(article, body.iteration, body.force === true); + base = continuation(article, body.iteration, body.force === true, Array.isArray(body.channels) ? body.channels : undefined); } else if (task === "sweep") { base = { kind: "sweep", parent: null, copyOf: null, question: body.question, scope: { channels: body.channels, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }; } else { @@ -413,8 +632,9 @@ function cancelDraft(id) { for (const t of job.timers) clearTimeout(t); job.status = "cancelled"; job.log.push("cancelled"); + job.child?.kill(); const it = readIt(job.article, job.n); - if (job.task === "narrate") { + 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)) }); } else { patchIt(job.article, job.n, { status: "cancelled", endedAt: new Date().toISOString() }); @@ -511,7 +731,13 @@ function generationRoute(req, res, url, auth) { const tail = Number(url.searchParams.get("tail") ?? 0); return json(res, 200, { ok: true, - job: { id: j.id, kind: j.kind ?? "report-draft", status: j.status, ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}) }, + job: { + id: j.id, + kind: j.kind ?? "report-draft", + status: j.status, + ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}), + ...(j.progress ? { progress: j.progress } : {}), + }, ...(tail ? { tail: j.log.slice(-tail) } : {}), }); } diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -24,7 +24,11 @@ import { SONG_DATA } from "../../song/paths.mjs"; import { songCapabilities } from "./song-capabilities.mjs"; import { makeSitesFixture } from "./sites-fixture.mjs"; import { makeIterationsFixture } from "./iterations-fixture.mjs"; +import { makeMediaDraftFixture } from "./media-draft-fixture.mjs"; +import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs"; import { makeDeleteFixture } from "./delete-fixture.mjs"; +import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; +import { makeYoutubeFixture } from "./youtube-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")); @@ -1652,6 +1656,12 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR ); } +// Release 28: drafted fields to review, and a final build they hold +// (draft-review.spec.ts). +makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). +makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); + // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. // @@ -1911,6 +1921,10 @@ writeProject("timeline-fixture", { const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); // Release 27: an article in the making (zeta), its projects, today's usage. makeIterationsFixture({ dest, articles: ARTICLES }); +// Release 28: the media drafts' article (mdraft), one iteration per task. +makeMediaDraftFixture({ dest, articles: ARTICLES }); +// Release 28 M9: "Draft with" and Draft everything (msurf), drafted canned by the stub. +makeMediaSurfacesFixture({ dest, articles: ARTICLES, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // The release 27 follow-up's deletes: psi (in the making) and // reports/delete-fixture (a project with two takes); article-delete.spec.ts // writes its draft (omega) itself. @@ -1952,4 +1966,6 @@ console.log(` deliver-stop-fixture (writable: six confirmed clips to console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`); console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`); console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`); +console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`); +console.log(` youtube-fixture (writable: a drafted publish.youtube, built fast to out/youtube.txt)`); console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`); diff --git a/umtool/e2e/fixtures/media-draft-fixture.mjs b/umtool/e2e/fixtures/media-draft-fixture.mjs @@ -0,0 +1,58 @@ +// What media-draft.spec.ts drafts on (release 28 M1–M3; lane E's tasks add +// iterations): `mdraft`, an article in the making whose done iterations each +// have a video project made from the S0 test kit's basic report — the +// converter's cut, its order marked as code's. One iteration per task, so no +// spec depends on another's draft: +// +// articles/mdraft/iterations/{1,2,3} sweep, qwen3:8b, done; the kit's report +// gen-projects/mdraft/i{1,2,3}/ video.manifest.json (the kit's basic +// cut) and report.json +// i1 the cut task's i2 the onscreen task's i3 the teaser task's +// +// The editor stub runs the media task for real over it, its model the fake +// ollama scripted with the kit's recorded run (common/testing/draft/ +// runMediaStep.ts). Synthetic: the kit's invented channel and lines. +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const KIT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../common/testing/draft"); +const AT = "2026-10-13T10:00:00.000Z"; +export const MEDIA_DRAFT_ARTICLE = "mdraft"; +export const MEDIA_DRAFT_ITERATIONS = { cut: 1, onscreen: 2, teaser: 3 }; + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); +}; + +export function makeMediaDraftFixture({ dest, articles }) { + const report = JSON.parse(readFileSync(path.join(KIT, "reports", "basic.report.json"), "utf8")); + const manifest = readFileSync(path.join(KIT, "manifests", "basic.video.manifest.json"), "utf8"); + for (const n of Object.values(MEDIA_DRAFT_ITERATIONS)) { + const dir = path.join(articles, MEDIA_DRAFT_ARTICLE, "iterations", String(n)); + const project = path.join(dest, "gen-projects", MEDIA_DRAFT_ARTICLE, `i${n}`); + put(path.join(dir, "iteration.json"), { + format: "archilyzer-iteration", + version: 1, + article: MEDIA_DRAFT_ARTICLE, + n, + kind: "sweep", + parent: null, + copyOf: null, + model: "qwen3:8b", + question: "What does the baker say about the bakery?", + scope: { channels: ["synth-kitchen"] }, + status: "done", + usage: {}, + steps: [], + projectDir: project, + createdAt: AT, + updatedAt: AT, + endedAt: AT, + }); + put(path.join(dir, "report.json"), { ...report, id: MEDIA_DRAFT_ARTICLE }); + put(path.join(project, "video.manifest.json"), manifest); + put(path.join(project, "report.json"), { ...report, id: MEDIA_DRAFT_ARTICLE }); + } +} diff --git a/umtool/e2e/fixtures/media-surfaces-fixture.mjs b/umtool/e2e/fixtures/media-surfaces-fixture.mjs @@ -0,0 +1,83 @@ +// What media-surfaces.spec.ts drafts on (release 28 M9): `msurf`, an article +// in the making whose two done iterations each have a video project that +// builds offline (two clips inside the cached 0–9 s window the build +// fixtures share, its fetchPad included; a title card and a chapter card; no +// deck) — the chain recorded done to its +// manifest, so Draft everything starts at its first draft: +// +// articles/msurf/iterations/{1,2} sweep, qwen3:8b, done; current … manifest done +// gen-projects/msurf/i1/ "Draft with" on the project page: the cut +// (the converter's order), on-screen, and an +// operator's publish.youtube (forced: an alternative) +// gen-projects/msurf/i2/ Draft everything on the Iterations tab +// +// The editor stub drafts this article's media CANNED (editor-stub.mjs +// cannedDraft): every media task, its field written through applyDraft with its +// mark and a `<task>-draft.json` beside it. Synthetic: the fixture's own +// channel and invented lines. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const MEDIA_SURFACES_ARTICLE = "msurf"; +const AT = "2026-10-13T10:00:00.000Z"; +const CODE = { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 }; +const CITE = (start, end, quote) => ({ kind: "video", channel: "testchan", id: "vid1", start, end, quote, speaker: "Test Channel", date: "2024-03-15" }); + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); +}; + +/** + * @param {{ dest: string, articles: string, manifest: Function, cachedWindow: string }} o + * `manifest` is make-fixture's manifest(slug, title, provenance, timeline); + * `cachedWindow` the vid1 0-9 s window the build fixtures share. + */ +export function makeMediaSurfacesFixture({ dest, articles, manifest, cachedWindow }) { + const report = { + format: "archilyzer-report", + version: 1, + id: MEDIA_SURFACES_ARTICLE, + kind: "sweep", + title: "The county vote, as the channel told it", + citations: { c01: CITE(3, 4.5, "and because"), c02: CITE(4.5, 6, "another whole sentence") }, + sections: [{ id: "s1", title: "The county", body: "She said it [and because](cite:c01), then [another whole sentence](cite:c02)." }], + }; + for (const n of [1, 2]) { + const dir = path.join(articles, MEDIA_SURFACES_ARTICLE, "iterations", String(n)); + const project = path.join(dest, "gen-projects", MEDIA_SURFACES_ARTICLE, `i${n}`); + put(path.join(dir, "iteration.json"), { + format: "archilyzer-iteration", + version: 1, + article: MEDIA_SURFACES_ARTICLE, + n, + kind: "sweep", + parent: null, + copyOf: null, + model: "qwen3:8b", + question: "What did the channel say about the county vote?", + scope: { channels: ["testchan"] }, + status: "done", + usage: {}, + steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done", startedAt: AT, endedAt: AT, minutes: 0.1, detail: "the fixture's" })), + projectDir: project, + createdAt: AT, + updatedAt: AT, + endedAt: AT, + }); + put(path.join(dir, "report.json"), report); + const m = manifest(`msurf-i${n}`, "The county vote", { siteOrigin: "https://archive.example" }, [ + { type: "card", id: "title", style: "title", seconds: 4, heading: "The county vote" }, + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 4.5, cite: 3, section: 0, lock: true, quote: "and because" }, + { type: "card", id: "k01", style: "chapter", seconds: 3, heading: "The county" }, + { type: "clip", id: "c02", video: "vid1", start: 4.5, end: 6.0, cite: 4.5, section: 0, lock: true, quote: "another whole sentence" }, + ]); + m.drafted = { timeline: CODE }; + // i1's YouTube text is the operator's: a forced draft is kept as an alternative. + if (n === 1) m.publish = { youtube: { title: "The operator's own title", description: "Written by hand." } }; + put(path.join(project, "video.manifest.json"), m); + put(path.join(project, "report.json"), report); + mkdirSync(path.join(project, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(project, "out", "clips-raw", path.basename(cachedWindow))); + } +} diff --git a/umtool/e2e/fixtures/youtube-fixture.mjs b/umtool/e2e/fixtures/youtube-fixture.mjs @@ -0,0 +1,32 @@ +// What media-draft-e.spec.ts reads (release 28, M6): a cut whose +// publish.youtube was drafted, three cards long enough to make YouTube +// chapters, and two clips over the cached window the build fixtures share — +// so the project page previews the YouTube text, and a fast build writes +// out/youtube.txt with its chapters and sources. Its own, so the other specs' +// projects are never touched. Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const P = (task, model = "qwen3:8b") => ({ task, model, at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string }} o + * `manifest` is make-fixture's manifest(slug, title, provenance, timeline); + * `cachedWindow` the vid1 0-9 s window the build fixtures share. + */ +export function makeYoutubeFixture({ reports, manifest, cachedWindow }) { + const dir = path.join(reports, "youtube-fixture"); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + const m = manifest("youtube-fixture", "The YouTube Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "card", id: "title", style: "title", seconds: 10, heading: "The YouTube Fixture" }, + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" }, + { type: "card", id: "k01", style: "chapter", seconds: 10, heading: "The county" }, + { type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" }, + { type: "card", id: "k02", style: "chapter", seconds: 10, heading: "Then" }, + ]); + m.publish = { youtube: { title: "The county said yes", description: "Half a year on, the county said yes, and the fixture says so." } }; + m.drafted = { "publish.youtube": P("youtube") }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow))); + return { dir }; +} diff --git a/umtool/e2e/media-draft-e.spec.ts b/umtool/e2e/media-draft-e.spec.ts @@ -0,0 +1,69 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// Release 28 lane E's media drafts, as umtool shows them (M6): the project +// page's YouTube text — previewed from publish.youtube before a build (the +// sources, no chapters), copied with Copy, then as a fast build writes it to +// out/youtube.txt with the build's own chapters (YouTube's rules) and a moment +// link per cited clip. The flips, threads and youtube tasks themselves run +// over the fake LLM in common's and the MCP's suites; umtool's "Draft with" +// buttons are M9's. Fixture: e2e/fixtures/youtube-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/youtube-fixture"; +const DIR = path.join(FIXTURE, "reports", "youtube-fixture"); +const TITLE = "The county said yes"; +const SUMMARY = "Half a year on, the county said yes, and the fixture says so."; +const SOURCES = ["https://archive.example/?v=testchan%2Fvid1&t=3", "https://archive.example/?v=testchan%2Fvid1&t=9"]; + +test("the YouTube text: a preview before the build, Copy, then out/youtube.txt with chapters and sources", async ({ page, request, context }) => { + test.setTimeout(300_000); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto(`/browse/${PROJECT}`); + const section = page.locator("[data-youtube]"); + await expect(section).toHaveAttribute("data-youtube", "preview"); + await expect(section.locator("[data-youtube-status]")).toContainText("chapters are added by the build"); + await expect(section.locator("[data-youtube-status]")).toContainText("drafted by qwen3:8b"); + const preview = await section.locator("[data-youtube-text]").textContent(); + expect(preview).toBe(`${TITLE}\n\n${SUMMARY}\n\nSources\n${SOURCES.join("\n")}\n`); + await section.getByRole("button", { name: "Copy" }).click(); + await expect(section.locator("[data-copy]")).toHaveAttribute("data-state", "done"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(preview); + + // A fast build (hard cuts) writes the text with the build's chapters. + const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } }); + expect(start.ok(), await start.text()).toBeTruthy(); + const { job } = (await start.json()) as { job: { id: string } }; + let done: { state: string; error: string | null } = { state: "running", error: null }; + const until = Date.now() + 240_000; + while (Date.now() < until) { + done = (await (await request.get(`/api/report/build?job=${job.id}`)).json()) as typeof done; + if (done.state !== "running") break; + await new Promise((r) => setTimeout(r, 400)); + } + expect(done.state, done.error ?? "").toBe("done"); + const file = path.join(DIR, "out", "youtube.txt"); + expect(existsSync(file)).toBe(true); + const text = readFileSync(file, "utf8"); + const [title, , summary, , chaptersHead, ...rest] = text.split("\n"); + expect([title, summary, chaptersHead]).toEqual([TITLE, SUMMARY, "Chapters"]); + // Five entries; the two under ten seconds after a chapter are folded: three + // chapters, the first at 0:00 (the title card), the clips' at 0:10 and 0:2x. + const chapters = rest.slice(0, rest.indexOf("")); + expect(chapters.length).toBe(3); + expect(chapters[0]).toBe("0:00 The YouTube Fixture"); + expect(chapters[1]).toMatch(/^0:1\d /); + expect(chapters[2]).toMatch(/^0:2\d /); + expect(text.endsWith(`\n\nSources\n${SOURCES.join("\n")}\n`)).toBe(true); + + // The page shows the built text now. + await page.reload(); + await expect(section).toHaveAttribute("data-youtube", "built"); + await expect(section.locator("[data-youtube-status]")).toContainText("out/youtube.txt, built"); + expect(await section.locator("[data-youtube-text]").textContent()).toBe(text); +}); diff --git a/umtool/e2e/media-draft.spec.ts b/umtool/e2e/media-draft.spec.ts @@ -0,0 +1,87 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// The media drafts (release 28 M1–M3; lane E adds flips, threads, youtube): +// each task asked through umtool's generate, run by the editor stub FOR REAL +// — the common task over the fixture iteration's project, its model the fake +// ollama scripted with the test kit's recorded run — and followed on the +// iteration to its step's end, shown on the Iterations tab. Then the project's manifest +// says what was drafted, marked with its provenance. +// +// mdraft an article in the making; i1, i2, i3 each a done sweep with the +// kit's basic cut (fixtures/media-draft-fixture.mjs) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const ARTICLE = "mdraft"; +const manifestOf = (n: number) => JSON.parse(readFileSync(path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`, "video.manifest.json"), "utf8")); +const draftFileOf = (n: number, task: string) => JSON.parse(readFileSync(path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`, `${task}-draft.json`), "utf8")); +const lastAsked = () => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === "report-draft").at(-1); +const ids = (m: { timeline: { id: string }[] }) => m.timeline.map((e) => e.id); +const entry = (m: { timeline: { id: string }[] }, id: string) => m.timeline.find((e) => e.id === id) as Record<string, any>; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [`/articles/${ARTICLE}`, `/api/articles/iterations?article=${ARTICLE}`, "/api/articles/policy"]); +}); + +// Ask for the task on iteration n, and follow its step to its end on the tab. +async function draft(page: Page, task: string, n: number, status = "done") { + const r = await page.request.post("/api/articles/generate", { data: { task, article: ARTICLE, iteration: n, model: "qwen3:8b" } }); + expect(r.status(), await r.text()).toBe(200); + expect(await r.json()).toMatchObject({ ok: true, iteration: n }); + expect(lastAsked()).toMatchObject({ task, article: ARTICLE, iteration: n, model: "qwen3:8b", authorization: "Bearer umtool-e2e-token" }); + // The job runs in the stub (a child under tsx); its step is the iteration's. + await expect + .poll( + async () => { + const list = (await (await page.request.get(`/api/articles/iterations?article=${ARTICLE}`)).json()) as { + iterations: { n: number; steps: { task: string; status: string }[] }[]; + }; + return list.iterations.find((i) => i.n === n)?.steps.find((s) => s.task === task)?.status ?? "none"; + }, + { timeout: 60_000, intervals: [1000] }, + ) + .toBe(status); + await page.goto(`/articles/${ARTICLE}?tab=iterations`); + await expect(page.locator(`[data-iteration='${n}'] [data-step='${task}']`)).toHaveAttribute("data-step-status", status); +} + +test("cut: the clips and their order drafted from the report's citations, the timeline built from the entries it had", async ({ page }) => { + test.setTimeout(120_000); + const before = manifestOf(1); + expect(before.drafted.timeline).toMatchObject({ task: "convert", model: "code" }); + await draft(page, "cut", 1); + const m = manifestOf(1); + expect(ids(m)).toEqual(["title", "the-contest", "c04", "c06", "the-bakery", "c03", "c01"]); + expect(entry(m, "c04")).toEqual(entry(before, "c04")); + expect(m.drafted.timeline).toMatchObject({ task: "cut", model: "qwen3:8b", iteration: 1, attempt: 2 }); + expect(draftFileOf(1, "cut").units.cut.applied).toBe("applied"); +}); + +test("onscreen: each clip's title and subtitle, several to an ask; a clip with no clean draft left as it was", async ({ page }) => { + test.setTimeout(120_000); + await draft(page, "onscreen", 2); + const m = manifestOf(2); + expect(entry(m, "c01").onscreen).toEqual({ title: "She will not sell to a chain", subtitle: '"I would never sell the bakery to a chain"' }); + expect(entry(m, "c01").drafted.onscreen).toMatchObject({ task: "onscreen", model: "qwen3:8b", iteration: 2, attempt: 1 }); + expect(entry(m, "c04").drafted.onscreen.attempt).toBe(2); + expect(entry(m, "c06").onscreen).toBeUndefined(); + expect(draftFileOf(2, "onscreen").units.c06.attempts).toHaveLength(2); +}); + +test("teaser: a cut with none gets one after its last clip, its lines drafted and checked by the build's validator", async ({ page }) => { + test.setTimeout(120_000); + await draft(page, "teaser", 3); + const m = manifestOf(3); + expect(ids(m).slice(-2)).toEqual(["c06", "teaser"]); + expect(entry(m, "teaser")).toMatchObject({ type: "teaser", lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] }); + expect(entry(m, "teaser").drafted.lines).toMatchObject({ task: "teaser", attempt: 2 }); +}); diff --git a/umtool/e2e/media-surfaces.spec.ts b/umtool/e2e/media-surfaces.spec.ts @@ -0,0 +1,144 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// Release 28 M9, the surfaces of the media drafts: +// - "Draft with <model>" per section on a project page: the job asked of the +// editor (its model, its entries, its force), followed to its end; then +// the section re-read — the badge, the last run, the alternative kept for +// the operator's field and Use this; a project made from no iteration +// offers none, and says why; +// - Draft everything on the Iterations tab: the chain with its drafts, a +// refused draft recorded failed and passed, the panels skipped, the +// voices, the fast build and the podcast, then the YouTube draft and +// out/youtube.txt. +// The editor stub drafts this article canned (fixtures/editor-stub.mjs +// cannedDraft); the build, the voices (the stub's tone) and the podcast are +// real. Fixture: fixtures/media-surfaces-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const ARTICLE = "msurf"; +const PROJECT = `gen-projects/${ARTICLE}/i1`; +const projectDir = (n: number) => path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`); +const manifestOf = (n: number) => JSON.parse(readFileSync(path.join(projectDir(n), "video.manifest.json"), "utf8")); +const asked = () => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; article?: string; [k: string]: unknown }[]).filter((r) => r.route === "report-draft" && r.article === ARTICLE); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [`/browse/${PROJECT}`, `/api/articles/draft?project=${encodeURIComponent(PROJECT)}`, "/api/articles/policy", `/articles/${ARTICLE}?tab=iterations`]); +}); + +test("Draft with <model> per section: the job followed, the badge, the last run, an alternative and Use this", async ({ page }) => { + test.setTimeout(180_000); + await page.goto(`/browse/${PROJECT}`); + const panel = page.getByRole("region", { name: "draft with a model" }); + await expect(panel).toHaveAttribute("data-draft-panel", `${ARTICLE}/i1`); + // Seven sections; flips and threads say why they cannot draft on this cut. + await expect(panel.locator("[data-draft-task]")).toHaveCount(7); + await expect(panel.locator("[data-draft-task='flips'] [data-draft-blocked]")).toContainText("this cut has none (render.chrome)"); + const cut = panel.locator("[data-draft-task='cut']"); + // The policy's models, the route's preselected. + await expect(cut.getByRole("combobox", { name: "model for the cut" })).toHaveValue("qwen3:8b"); + + // The cut: drafted over the converter's order; its badge and its review. + await cut.getByRole("combobox", { name: "model for the cut" }).selectOption("claude-sonnet-5-5"); + await cut.getByRole("button", { name: "Draft the cut" }).click(); + await expect(cut).toHaveAttribute("data-draft-job", "done", { timeout: 30_000 }); + expect(asked().at(-1)).toMatchObject({ task: "cut", article: ARTICLE, iteration: 1, model: "claude-sonnet-5-5", authorization: "Bearer umtool-e2e-token" }); + await expect(cut.locator("[data-draft-badge='cut/*/timeline'] [data-draft-by]")).toHaveText("drafted by claude-sonnet-5-5"); + await expect(cut.locator("[data-draft-run='cut']")).toContainText("1 written"); + expect(manifestOf(1).timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string }) => e.id)).toEqual(["c02", "c01"]); + await cut.locator("[data-draft-badge='cut/*/timeline']").getByRole("button", { name: "Approve" }).click(); + await expect(cut.locator("[data-draft-badge='cut/*/timeline']")).toHaveAttribute("data-state", "approved"); + + // On-screen, limited to the entry ticked. + const onscreen = panel.locator("[data-draft-task='onscreen']"); + await onscreen.locator("summary").click(); + await onscreen.getByRole("checkbox", { name: "only c01 (on-screen titles)" }).check(); + await onscreen.getByRole("button", { name: "Draft on-screen titles" }).click(); + await expect(onscreen).toHaveAttribute("data-draft-job", "done", { timeout: 30_000 }); + expect(asked().at(-1)).toMatchObject({ task: "onscreen", entries: ["c01"] }); + await expect(onscreen.locator("[data-draft-run='onscreen']")).toContainText("1 written"); + const m = manifestOf(1); + const c01 = m.timeline.find((e: { id: string }) => e.id === "c01"); + expect(c01.onscreen).toEqual({ title: "What c01 shows", subtitle: "From the county vote" }); + expect(c01.drafted.onscreen).toMatchObject({ task: "onscreen", model: "qwen3:8b", iteration: 1 }); + expect(m.timeline.find((e: { id: string }) => e.id === "c02").onscreen).toBeUndefined(); + + // YouTube: the operator's text. Unforced, nothing to draft; forced, the + // draft is kept as an alternative, and Use this writes it. + const yt = panel.locator("[data-draft-task='youtube']"); + await yt.getByRole("button", { name: "Draft YouTube text" }).click(); + await expect(yt).toHaveAttribute("data-draft-job", "failed", { timeout: 30_000 }); + await expect(yt.locator("[data-draft-run='youtube']")).toContainText("1 skipped"); + await yt.getByRole("checkbox", { name: "force: re-draft YouTube text" }).check(); + await yt.getByRole("button", { name: "Draft YouTube text" }).click(); + await expect(yt.locator("[data-draft-run='youtube']")).toContainText("1 kept as an alternative", { timeout: 30_000 }); + expect(asked().at(-1)).toMatchObject({ task: "youtube", force: true }); + expect(manifestOf(1).publish.youtube.title).toBe("The operator's own title"); + const alt = yt.locator("[data-draft-alternatives='youtube/*/publish.youtube']"); + await expect(alt).toContainText("The county vote, as the channel told it"); + await alt.getByRole("button", { name: "Use this" }).click(); + await expect.poll(() => manifestOf(1).publish.youtube.title, { timeout: 15_000 }).toBe("The county vote, as the channel told it"); + // Taken, it is the operator's: no mark. + expect(manifestOf(1).drafted?.["publish.youtube"]).toBeUndefined(); + + // A project made from no iteration offers no draft, and says why. + await page.goto("/browse/reports/youtube-fixture"); + await expect(page.getByRole("region", { name: "draft with a model" }).locator("[data-draft-unlinked]")).toContainText("not made from an article's iteration"); +}); + +test("Draft everything: every draft in order on the model chosen, a refused one passed, the panels skipped, then the fast build, the podcast and out/youtube.txt", async ({ page }) => { + test.setTimeout(420_000); + await page.goto(`/articles/${ARTICLE}?tab=iterations`); + const two = page.locator("[data-iteration='2']"); + // The Iterations tab's per-step drafts, beside Narrate. + await expect(two.getByRole("combobox", { name: "draft task for i2" })).toBeVisible(); + await two.getByRole("combobox", { name: "Draft everything model for i2" }).selectOption("qwen3:8b"); + const before = asked().length; + await two.getByRole("button", { name: "Draft everything" }).click(); + const chain = page.getByRole("region", { name: "i2 Draft everything" }); + await expect(chain.locator("[data-chain-step]")).toHaveCount(15); + const step = (name: string) => chain.locator(`[data-chain-step='${name}']`); + await expect(step("draft-youtube")).toHaveAttribute("data-step-status", "done", { timeout: 360_000 }); + await expect(chain.locator("[data-chain-job]")).toHaveAttribute("data-chain-job", "done", { timeout: 30_000 }); + for (const [name, status] of [ + ["current", "done"], + ["manifest", "done"], + ["draft-cut", "done"], + ["draft-onscreen", "done"], + ["draft-teaser", "failed"], + ["draft-flips", "skipped"], + ["draft-threads", "skipped"], + ["draft-narrate", "done"], + ["voices", "done"], + ["video", "done"], + ["podcast", "done"], + ["draft-youtube", "done"], + ] as const) { + await expect(step(name), name).toHaveAttribute("data-step-status", status); + } + await expect(step("draft-flips")).toContainText("no on-screen deck"); + // The drafts the editor was asked for, in order, on the model chosen (flips + // and threads never asked: no deck to draw them on). + const drafts = asked().slice(before); + expect(drafts.map((r) => r.task)).toEqual(["cut", "onscreen", "teaser", "narrate", "youtube"]); + expect(drafts.every((r) => r.model === "qwen3:8b" && r.iteration === 2)).toBe(true); + const m = manifestOf(2); + expect(m.drafted.timeline).toMatchObject({ task: "cut", model: "qwen3:8b" }); + expect(m.timeline.find((e: { id: string }) => e.id === "k01").narration.text).toBe("The county, as the channel told it."); + expect(m.publish.youtube.title).toBe("The county vote, as the channel told it"); + // The fast build, the podcast and the YouTube text are on disk. + const out = path.join(projectDir(2), "out"); + expect(existsSync(path.join(out, "msurf-i2.mp4"))).toBe(true); + const text = readFileSync(path.join(out, "youtube.txt"), "utf8"); + expect(text.split("\n")[0]).toBe("The county vote, as the channel told it"); + expect(text).toContain("Sources"); +}); diff --git a/umtool/e2e/narration-review.spec.ts b/umtool/e2e/narration-review.spec.ts @@ -8,19 +8,23 @@ import { fileURLToPath } from "node:url"; // card, before synthesis. Approve / reject (a note required) / edit the words // (which un-approves them) / play one card through the editor -- the suite's // stub, whose "voice" is an ffmpeg tone -- and a build that refuses what is not -// approved once verdicts exist. Verdicts are narration.review.json beside the -// manifest. +// approved once verdicts exist. Verdicts are drafts.review.json beside the +// manifest (release 28; release 25's narration.review.json is still read). // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIXTURE = path.join(HERE, "..", ".e2e-song"); const PROJECT = "reports/narration-review-fixture"; const DIR = path.join(FIXTURE, "reports", "narration-review-fixture"); -const REVIEW = path.join(DIR, "narration.review.json"); +// Since release 28 the verdicts are the drafts review's: a card's are +// `narrate/<cardId>/narration` in drafts.review.json. +const REVIEW = path.join(DIR, "drafts.review.json"); const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); -const review = (): Record<string, { verdict: string | null; note: string; text: string }> => - existsSync(REVIEW) ? JSON.parse(readFileSync(REVIEW, "utf8")) : {}; +const review = (): Record<string, { verdict: string | null; note: string; text: string }> => { + const all = existsSync(REVIEW) ? (JSON.parse(readFileSync(REVIEW, "utf8")) as Record<string, { verdict: string | null; note: string; text: string }>) : {}; + return Object.fromEntries(Object.entries(all).map(([address, row]) => [address.replace(/^narrate\/(.+)\/narration$/, "$1"), row])); +}; const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: { id: string; narration?: { text: string } }[] }; const ttsAsks = (): { route?: string; text?: string }[] => { try { diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts @@ -0,0 +1,97 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; +import { BENCH_RUN, QWEN, SONNET, makeBenchRun } from "./fixtures/bench-fixture.mjs"; + +// --------------------------------------------------------------------------- +// The verdict bench's page (release 28 M7) over a synthetic run in the +// fixture's `.generation`-style root (GENERATION_USAGE_FILE is the fixture's, +// so the runs root is <fixture>/bench/verdicts): the tiles against the +// baseline, the confusion matrix, the items with disagreements first and the +// filters, and the bar — written through the (stubbed) editor's settings +// action, each model's pass or fail read against it, and a failing model +// never tickable. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ROOT = path.join(FIXTURE, "bench", "verdicts"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +const stubAsked = (route: string) => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + makeBenchRun(ROOT); + await warm(playwright, ["/bench", "/api/bench/bar"]); +}); +test.afterAll(async ({ request }) => { + await request.post("/api/bench/bar", { data: { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] } }); + rmSync(path.join(ROOT, BENCH_RUN), { recursive: true, force: true }); +}); + +test("the run: each model's tile against the baseline, the matrix, the items with disagreements first, the filters", async ({ page }) => { + await page.goto("/articles"); + await page.getByRole("link", { name: "verdict bench" }).click(); + await expect(page).toHaveURL(/\/bench$/); + await expect(page.locator(`[data-bench-run="${BENCH_RUN}"]`)).toHaveAttribute("data-status", "done"); + const models = page.getByRole("region", { name: "models" }); + const sonnet = models.locator(`[data-model="${SONNET}"]`); + await expect(sonnet.locator('[data-metric="agreement"]')).toHaveText("75% (baseline 25%)"); + await expect(sonnet.locator('[data-metric="contradicted"]')).toHaveText("100% (baseline 0%) of 1"); + await expect(sonnet.locator('[data-metric="not-found"]')).toHaveText("100% (baseline 0%) of 1"); + await expect(sonnet.locator('[data-metric="cost"]')).toHaveText("$0.0160"); + const qwen = models.locator(`[data-model="${QWEN}"]`); + await expect(qwen.locator('[data-metric="agreement"]')).toHaveText("25% (baseline 25%)"); + await expect(qwen).toContainText("3 of 4 · 1 parse failures"); + await expect(models.locator('[data-model="always-CORROBORATED"]')).toBeVisible(); + // The matrix: rows the operator, columns the model. + const m = page.getByRole("table", { name: `confusion ${SONNET}` }); + await expect(m.locator('[data-cell="PARTLY:CORROBORATED"]')).toHaveText("1"); + await expect(m.locator('[data-cell="CONTRADICTED:CONTRADICTED"]')).toHaveText("1"); + // The items: every disagreement first. + const rows = page.getByRole("region", { name: "items" }).locator("tbody tr"); + await expect(rows).toHaveCount(4); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2"); + await expect(rows.nth(3)).toHaveAttribute("data-item", "synth-bench/c1"); + await expect(rows.nth(0).locator(`[data-model="${SONNET}"]`)).toContainText("read the window for c2"); + await expect(rows.nth(2).locator(`[data-model="${QWEN}"]`)).toContainText("parse: the answer is not JSON"); + // By model: that model's disagreements first, its column alone. + await page.getByRole("region", { name: "items" }).getByRole("link", { name: SONNET, exact: true }).click(); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c2"); + await expect(rows.nth(1)).toHaveAttribute("data-item", "synth-bench/c1"); + await expect(page.getByRole("region", { name: "items" }).locator(`thead th`)).toHaveCount(3); + // By the operator's verdict. + await page.getByRole("region", { name: "items" }).getByRole("link", { name: "CONTRADICTED 1" }).click(); + await expect(rows).toHaveCount(1); + await expect(rows.nth(0)).toHaveAttribute("data-item", "synth-bench/c3"); + await expect(page.getByText("skipped 1")).toBeVisible(); +}); + +test("the bar: saved through the editor's settings action; a passing model ticked, a failing one never", async ({ page }) => { + await page.goto(`/bench?run=${BENCH_RUN}`); + const form = page.getByRole("form", { name: "bar" }); + await form.getByRole("spinbutton", { name: "minimum agreement" }).fill("50"); + await form.getByRole("spinbutton", { name: "minimum CONTRADICTED recall" }).fill("50"); + await form.getByRole("spinbutton", { name: "minimum NOT_FOUND recall" }).fill("50"); + await expect(form.getByRole("checkbox", { name: `use ${QWEN}` })).toBeDisabled(); + await expect(form.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false"); + const use = form.getByRole("checkbox", { name: `use ${SONNET}` }); + await expect(use).toBeEnabled(); + await use.check(); + await form.getByRole("button", { name: "Save the bar" }).click(); + await expect(form.getByRole("status")).toHaveText("Saved."); + expect(stubAsked("settings").at(-1)).toMatchObject({ + patch: { generation: { verdicts: { bar: { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models: [SONNET] } } }, + authorization: "Bearer umtool-e2e-token", + }); + // Read back: the tiles say who passes the saved bar. + await page.reload(); + const models = page.getByRole("region", { name: "models" }); + await expect(models.locator(`[data-model="${SONNET}"]`)).toHaveAttribute("data-pass", "true"); + await expect(models.locator(`[data-model="${QWEN}"]`)).toHaveAttribute("data-pass", "false"); + await expect(page.getByRole("form", { name: "bar" }).getByRole("checkbox", { name: `use ${SONNET}` })).toBeChecked(); + await expect(page.getByRole("form", { name: "bar" }).getByRole("spinbutton", { name: "minimum agreement" })).toHaveValue("50"); +}); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -22,7 +22,7 @@ import { } from "yt-dlp-transcript-common/lib/generationSettings"; import { PRICES } from "yt-dlp-transcript-common/lib/llm/prices"; import { agentToken } from "@/lib/annotations/agentAuth.mjs"; -import { CHAIN_STEPS, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, doneSteps } from "@/lib/report/chain.mjs"; +import { DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, chainStepsOf, doneSteps } from "@/lib/report/chain.mjs"; import { recentJobs, type Job } from "@/lib/jobs"; import { sitesPaths } from "./sites"; @@ -189,6 +189,8 @@ export type DraftJobView = { kind: string | null; status: string; queue: { key?: string; position?: number } | null; + /** The job's progress (release 28 F3: a draft's `turns`, `cards` or `entries`), when it reports one. */ + progress: { metric: string; current: number; target: number } | null; tail: string[]; }; @@ -200,11 +202,16 @@ export async function readDraftJob(id: string, tail = 12): Promise<DraftJobView> ); const job = answer.job ?? {}; const queue = (answer.queue ?? job.queue ?? null) as DraftJobView["queue"]; + const p = job.progress as { metric?: unknown; current?: unknown; target?: unknown } | undefined; return { id, kind: typeof job.kind === "string" ? job.kind : null, status: String(job.status ?? "unknown"), queue, + progress: + p && typeof p.current === "number" + ? { metric: typeof p.metric === "string" ? p.metric : "progress", current: p.current, target: typeof p.target === "number" ? p.target : p.current } + : null, tail: Array.isArray(answer.tail) ? answer.tail.map(String) : [], }; } @@ -216,7 +223,7 @@ export async function cancelDraftJob(id: string): Promise<void> { // The body umtool sends to `report-draft`: the action's own keys, nothing else // (the editor refuses an unknown key; this refuses it first, by name). -const DRAFT_KEYS = ["task", "article", "iteration", "model", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "force", "autonomy"]; +const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy"]; export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> { const out: Record<string, unknown> = {}; @@ -262,8 +269,10 @@ export type IterationRow = { currentVideo: boolean; }; +export type ChainMode = "video" | "draft-all"; export type ChainView = { - steps: { name: string; label: string; status: string }[]; + mode: ChainMode; + steps: { name: string; label: string; status: string; optional: boolean; detail: string | null }[]; /** Where a start resumes: the first step not done, or null (all done). */ resumeAt: string | null; job: { id: string; state: string; stepIndex: number; of: number; label: string; error: string | null; log: string[] } | null; @@ -372,26 +381,28 @@ export async function readToday(daily: number): Promise<{ day: string; usd: numb // ─── The chain ("make the video") ─── -/** The chain job's kind for an iteration, as lib/jobs.ts records it. */ -export const chainKind = (article: string, n: number) => `chain ${article} ${iterationLabel(n)}`; +/** The chain job's kind for an iteration, as lib/jobs.ts records it (Draft everything's is its own). */ +export const chainKind = (article: string, n: number, mode: ChainMode = "video") => + `${mode === "draft-all" ? "draft-all" : "chain"} ${article} ${iterationLabel(n)}`; /** The projects root the editor's policy names (`~` expanded), else the default. */ export function projectsRootOf(gen: GenerationSettings): string { return gen.projectsRoot ? expandHome(gen.projectsRoot) : DEFAULT_PROJECTS_ROOT; } -export function chainViewOf(article: string, it: IterationRow): ChainView { +export function chainViewOf(article: string, it: IterationRow, mode: ChainMode = "video"): ChainView { const done = new Set(doneSteps({ steps: it.steps })); - const byTask = new Map(it.steps.map((s) => [s.task, s.status])); - const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n)); + const byTask = new Map(it.steps.map((s) => [s.task, s])); + const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n, mode)); + const defs = chainStepsOf(mode) as { name: string; label: string; optional?: boolean }[]; return { - steps: CHAIN_STEPS.map((s: { name: string; label: string }) => ({ - name: s.name, - label: s.label, - status: byTask.get(`chain:${s.name}`) ?? "pending", - })), + mode, + steps: defs.map((s) => { + const rec = byTask.get(`chain:${s.name}`); + return { name: s.name, label: s.label, status: rec?.status ?? "pending", optional: s.optional === true, detail: rec?.detail ?? null }; + }), // chain.mjs's JSDoc types `done` by its default ([]), so it is cast. - resumeAt: (chainStart as (o: { done: string[] }) => string | null)({ done: [...done] }), + resumeAt: (chainStart as (o: { done: string[]; mode: string }) => string | null)({ done: [...done], mode }), job: job ? { id: job.id, diff --git a/umtool/lib/articles/projectDraft.ts b/umtool/lib/articles/projectDraft.ts @@ -0,0 +1,230 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { readIteration } from "yt-dlp-transcript-common/lib/report/iterations"; +import { draftedFields, ownerOf, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { draftFileOf } from "@/lib/report/chain-draft.mjs"; +import { sitesPaths } from "./sites"; + +// "DRAFT WITH" ON A PROJECT PAGE (release 28 M9): which iteration a video +// project was made from — the media tasks are report-draft STEPS on a done +// iteration, so a project that names none has nothing to draft with — and +// what each task's last run left in its `<task>-draft.json` beside the +// manifest (what it wrote, what it skipped, what a check refused, what it +// kept as an alternative). Read only. SERVER-ONLY. + +/** The media tasks a project page drafts, in Draft everything's order. */ +export const PROJECT_DRAFT_TASKS = ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"] as const; +export type ProjectDraftTask = (typeof PROJECT_DRAFT_TASKS)[number]; + +export type ProjectIteration = + | { ok: true; article: string; n: number; status: string; running: Record<string, string> } + | { ok: false; why: string }; + +/** + * The iteration a project directory belongs to: `<projectsRoot>/<article>/i<n>/` + * (common's projectOf), whose iteration exists and names this directory as its + * project (or names none). Else why not, in one line. + */ +export async function projectIteration(dir: string): Promise<ProjectIteration> { + const abs = path.resolve(dir); + const m = /^i(\d+)$/.exec(path.basename(abs)); + const article = path.basename(path.dirname(abs)); + if (!m || !isReportId(article)) { + return { ok: false, why: "this project was not made from an article's iteration (its folder is not <article>/i<n>), so no draft task can name one" }; + } + const n = Number(m[1]); + const it = await readIteration(article, n, sitesPaths()).catch(() => null); + if (!it) return { ok: false, why: `no iteration i${n} of the article "${article}": the drafts are steps on an iteration` }; + if (it.projectDir && path.resolve(it.projectDir) !== abs) { + return { ok: false, why: `${article} i${n} names another project (${it.projectDir})` }; + } + // A draft still running on it (a step with its job): the page follows it. + const running: Record<string, string> = {}; + for (const s of it.steps) if (s.status === "running" && s.jobId && !s.task.startsWith("chain:")) running[s.task] = s.jobId; + return { ok: true, article, n, status: it.status, running }; +} + +export type DraftUnitSummary = { + id: string; + label: string | null; + /** applied | skipped | refused (a hard check) | kept (an alternative: the field is the operator's, or a draft without force) | none */ + outcome: "applied" | "skipped" | "refused" | "kept" | "none"; + why: string | null; +}; +export type DraftRunSummary = { + task: ProjectDraftTask; + file: string; + model: string | null; + at: string | null; + units: DraftUnitSummary[]; + counts: Record<DraftUnitSummary["outcome"], number>; + checks: { name: string; ok: boolean; detail: string | null }[]; + alternatives: number; +}; + +type RawUnit = { + label?: unknown; + skipped?: unknown; + applied?: unknown; + chosen?: { hard?: unknown } | null; +}; + +const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); + +/** One task's last run, from its draft file, or null (never run here, or unreadable). */ +export async function draftRunSummary(dir: string, task: ProjectDraftTask): Promise<DraftRunSummary | null> { + const file = draftFileOf(task); + let doc: Record<string, unknown>; + try { + doc = JSON.parse(await readFile(path.join(dir, file), "utf8")); + } catch { + return null; + } + if (!doc || typeof doc !== "object" || Array.isArray(doc)) return null; + const units: DraftUnitSummary[] = []; + const raw = doc.units && typeof doc.units === "object" ? (doc.units as Record<string, RawUnit>) : {}; + for (const [id, u] of Object.entries(raw)) { + const label = typeof u?.label === "string" ? u.label : null; + if (typeof u?.skipped === "string") units.push({ id, label, outcome: "skipped", why: u.skipped }); + else if (u?.applied === "applied") units.push({ id, label, outcome: "applied", why: null }); + else if (typeof u?.applied === "string") units.push({ id, label, outcome: "kept", why: u.applied === "operator" ? "the field is yours: kept as an alternative" : `kept as an alternative (${u.applied})` }); + else { + const hard = strings(u?.chosen?.hard); + units.push({ id, label, outcome: hard.length ? "refused" : "none", why: hard.length ? hard.join("; ") : u?.chosen ? null : "no draft" }); + } + } + const counts = { applied: 0, skipped: 0, refused: 0, kept: 0, none: 0 }; + for (const u of units) counts[u.outcome] += 1; + const checks = Array.isArray(doc.checks) + ? (doc.checks as { name?: unknown; ok?: unknown; detail?: unknown }[]) + .filter((c) => typeof c?.name === "string") + .map((c) => ({ name: String(c.name), ok: c.ok === true, detail: typeof c.detail === "string" ? c.detail : null })) + : []; + return { + task, + file, + model: typeof doc.model === "string" ? doc.model : null, + at: typeof doc.at === "string" ? doc.at : null, + units, + counts, + checks, + alternatives: Array.isArray(doc.alternatives) ? doc.alternatives.length : 0, + }; +} + +/** Every task's last run in this project. */ +export async function draftRuns(dir: string): Promise<Partial<Record<ProjectDraftTask, DraftRunSummary>>> { + const out: Partial<Record<ProjectDraftTask, DraftRunSummary>> = {}; + for (const t of PROJECT_DRAFT_TASKS) { + const s = await draftRunSummary(dir, t); + if (s) out[t] = s; + } + return out; +} + +// ─── The rows the project page's Draft section draws ─── + +export type DraftRowView = { + task: ProjectDraftTask; + /** The section's name. */ + label: string; + /** What the task writes, and the code's limits. */ + writes: string; + /** What the field holds now, in a few words. */ + state: string; + /** The review address of a whole-cut field (its badge and alternatives), else null (per entry: the review page). */ + address: string | null; + /** The entries a per-entry task may be limited to, else null. */ + entries: { id: string; label: string }[] | null; + /** Why it cannot draft on this cut (no deck for flips and threads), else null. */ + blocked: string | null; +}; + +type Entry = { id?: unknown; type?: unknown; heading?: unknown; onscreen?: { title?: unknown; subtitle?: unknown }; narration?: { text?: unknown }; lines?: unknown }; + +const ownerWords = (o: "empty" | "drafted" | "operator") => (o === "empty" ? "empty" : o === "drafted" ? "drafted" : "yours (never replaced)"); + +/** The Draft section's rows for a manifest, in Draft everything's order. */ +export function draftRowsOf(manifest: Record<string, unknown>): DraftRowView[] { + const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[]; + const drafted = draftedFields(manifest); + const nDrafted = (field: string) => drafted.filter((d) => d.field === field).length; + const ids = (es: Entry[]) => [...new Set(es.map((e) => (typeof e.id === "string" ? e.id : "")).filter(Boolean))]; + const labelOf = (e: Entry) => `${String(e.id)}${typeof e.heading === "string" && e.heading ? ` — ${e.heading}` : ""}`; + const listOf = (es: Entry[]) => ids(es).map((id) => ({ id, label: labelOf(es.find((e) => e.id === id)!) })); + const render = (manifest.render ?? {}) as { chrome?: unknown }; + const deck = !!render.chrome && typeof render.chrome === "object"; + const clips = tl.filter((e) => e.type === "clip"); + const cards = tl.filter((e) => e.type === "card"); + const teasers = tl.filter((e) => e.type === "teaser"); + const withOnscreen = tl.filter((e) => e.onscreen && (typeof e.onscreen.title === "string" || typeof e.onscreen.subtitle === "string")).length; + const narrated = cards.filter((e) => typeof e.narration?.text === "string" && e.narration.text.trim()).length; + const withLines = teasers.filter((e) => Array.isArray(e.lines) && e.lines.length > 0).length; + const whole = (field: string) => reviewAddress({ field }); + return [ + { + task: "cut", + label: "the cut", + writes: "which cited clips, in what order (ids from the citations only; windows untouched)", + state: `${clips.length} clip(s); the order is ${ownerWords(ownerOf(manifest, { field: "timeline" }))}`, + address: whole("timeline"), + entries: null, + blocked: null, + }, + { + task: "onscreen", + label: "on-screen titles", + writes: "a title (≤ 60) and a subtitle (≤ 90) per entry, grounded in its claim and quote", + state: `${withOnscreen} of ${tl.length} entries written, ${nDrafted("onscreen")} drafted`, + address: null, + entries: listOf(tl), + blocked: null, + }, + { + task: "teaser", + label: "the teaser", + writes: "3 to 5 lines of ≤ 70, no quote read out", + state: teasers.length ? `${withLines} of ${teasers.length} teaser(s) written, ${nDrafted("lines")} drafted` : "no teaser entry in the cut", + address: null, + entries: teasers.length ? listOf(teasers) : null, + blocked: null, + }, + { + task: "flips", + label: "flips", + writes: "THEN/NOW pairs over the cut's clips, of different dates (the left panel)", + state: deck ? `the flips are ${ownerWords(ownerOf(manifest, { field: "render.chrome.flips" }))}` : "no on-screen deck", + address: whole("render.chrome.flips"), + entries: null, + blocked: deck ? null : "flips are drawn by the on-screen deck, and this cut has none (render.chrome)", + }, + { + task: "threads", + label: "threads", + writes: "2 to 4 threads and each clip's thread (the left panel; not with flips)", + state: deck ? `the threads are ${ownerWords(ownerOf(manifest, { field: "render.chrome.threads" }))}` : "no on-screen deck", + address: whole("render.chrome.threads"), + entries: null, + blocked: deck ? null : "threads are drawn by the on-screen deck, and this cut has none (render.chrome)", + }, + { + task: "narrate", + label: "narration", + writes: "each card's narration, third person, every line grounded", + state: `${narrated} of ${cards.length} card(s) narrated, ${nDrafted("narration")} drafted`, + address: null, + entries: cards.length ? listOf(cards) : null, + blocked: null, + }, + { + task: "youtube", + label: "YouTube text", + writes: "a title (≤ 100) and a summary (≤ 900); the build adds chapters and sources to out/youtube.txt", + state: `the title and description are ${ownerWords(ownerOf(manifest, { field: "publish.youtube" }))}`, + address: whole("publish.youtube"), + entries: null, + blocked: null, + }, + ]; +} diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts @@ -0,0 +1,118 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + benchRootOf, + listBenchRuns, + passesBar, + readBenchRun, + scoreBench, + BASELINE_MODEL, + type BenchItem, + type BenchResult, + type BenchScore, + type BenchSummary, + type VerdictBar, +} from "yt-dlp-transcript-common/lib/report/draft/bench/index"; +import { VERDICTS, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; +import { sanitizeGeneration, type GenerationVerdicts } from "yt-dlp-transcript-common/lib/generationSettings"; +import { askEditor, EditorError } from "@/lib/articles/generation"; + +// THE VERDICT BENCH, AS UMTOOL SEES IT (release 28 M7): the runs `archilyzer +// reports bench-verdicts` wrote under the checkout's `.generation/bench/ +// verdicts/` (local-only; read here, never written), scored again from their +// items and results so the page and the files cannot disagree, and the +// operator's bar — settings.generation.verdicts — read from and written +// through the editor's settings action, as the generation policy is. +// +// SERVER-ONLY. + +export type BenchRunRow = Pick<BenchSummary, "id" | "createdAt" | "status" | "models" | "items" | "spentUsd" | "maxUsd">; + +export type BenchItemRow = { + key: string; + report: string; + claim: string; + text: string; + verdict: Verdict; + answers: Record<string, { verdict: Verdict | null; reason?: string; failure?: string; error?: string }>; + // A model whose answer is not the operator's (failures included). + disagree: string[]; +}; + +export type BenchView = { + summary: BenchSummary; + score: BenchScore; + items: BenchItemRow[]; +}; + +export function benchRoot(): string { + return benchRootOf(getPaths()); +} + +export async function readBenchRuns(): Promise<BenchRunRow[]> { + return (await listBenchRuns(benchRoot())).map((s) => ({ + id: s.id, + createdAt: s.createdAt, + status: s.status, + models: s.models, + items: s.items, + spentUsd: s.spentUsd, + maxUsd: s.maxUsd, + })); +} + +function rowsOf(items: readonly BenchItem[], results: readonly BenchResult[], models: readonly string[]): BenchItemRow[] { + const by = new Map<string, BenchResult>(); + for (const r of results) by.set(`${r.model}\u0000${r.key}`, r); + return items.map((it) => { + const answers: BenchItemRow["answers"] = {}; + const disagree: string[] = []; + for (const m of models) { + const r = by.get(`${m}\u0000${it.key}`); + if (!r) continue; + answers[m] = { verdict: r.verdict, ...(r.reason ? { reason: r.reason } : {}), ...(r.failure ? { failure: r.failure } : {}), ...(r.error ? { error: r.error } : {}) }; + if (r.verdict !== it.verdict) disagree.push(m); + } + return { key: it.key, report: it.report, claim: it.claim, text: it.text, verdict: it.verdict, answers, disagree }; + }); +} + +export async function readBenchView(id: string): Promise<BenchView | null> { + const run = await readBenchRun(benchRoot(), id).catch(() => null); + if (!run) return null; + const score = scoreBench(run.items, run.results, run.summary.models); + return { summary: run.summary, score, items: rowsOf(run.items, run.results, run.summary.models) }; +} + +// The rows a filter keeps, disagreements first (then in item order). +export function filterBenchRows(rows: readonly BenchItemRow[], f: { model?: string; verdict?: string }): BenchItemRow[] { + const kept = rows.filter( + (r) => (!f.verdict || r.verdict === f.verdict) && (!f.model || f.model in r.answers), + ); + const disagrees = (r: BenchItemRow) => (f.model ? r.disagree.includes(f.model) : r.disagree.length > 0); + return [...kept.filter(disagrees), ...kept.filter((r) => !disagrees(r))]; +} + +export { passesBar, BASELINE_MODEL, VERDICTS }; +export type { VerdictBar }; + +// ─── The bar (settings.generation.verdicts) ─── + +export async function readVerdictsPolicy(): Promise<GenerationVerdicts> { + const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation"); + return sanitizeGeneration(answer.value ?? {}).verdicts; +} + +/** Write the bar and the ticked models whole (a nested block replaces). Answers it as read back. */ +export async function writeVerdictsPolicy(v: unknown): Promise<GenerationVerdicts> { + if (!v || typeof v !== "object" || Array.isArray(v)) throw new EditorError("send {bar, models}", 400); + const o = v as Record<string, unknown>; + const b = (o.bar ?? {}) as Record<string, unknown>; + for (const k of ["agreement", "contradictedRecall", "notFoundRecall"]) { + const x = b[k]; + if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new EditorError(`bar.${k} is a fraction from 0 to 1`, 400); + } + if (!Array.isArray(o.models) || !o.models.every((m) => typeof m === "string")) throw new EditorError("models is a list of model names", 400); + const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models } }).verdicts; + await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: { verdicts } } } }); + return readVerdictsPolicy(); +} diff --git a/umtool/lib/report/chain-draft.mjs b/umtool/lib/report/chain-draft.mjs @@ -0,0 +1,35 @@ +// Draft everything's generation steps (release 28 M9), the pure part: what a +// draft would draw nothing on, and how a draft that did not end done is +// recorded. Plain node (common's panels.mjs is plain JS too), so the tests +// and the Next app may import it; ./chain-run.mjs executes the steps. + +import { flipsOn, threadsOn } from "yt-dlp-transcript-common/lib/report/panels.mjs"; + +/** The audit file each task writes beside the manifest (narrate's kept its old name). */ +export const draftFileOf = (task) => (task === "narrate" ? "narration-draft.json" : `${task}-draft.json`); + +/** + * Why a draft would draw nothing on this cut, before the editor is asked, or + * null: flips and threads need the on-screen deck, and share its left panel + * (the task refuses the other panel; Draft everything never forces). + */ +export function draftPrecheck(task, manifest) { + if (task !== "flips" && task !== "threads") return null; + const render = manifest?.render ?? {}; + if (!render.chrome || typeof render.chrome !== "object") return `the cut has no on-screen deck (render.chrome) to draw the ${task} on`; + if (task === "threads" && flipsOn(render)) return "the cut has flips: flips and threads share the left panel"; + if (task === "flips" && threadsOn(render)) return "the cut has threads: flips and threads share the left panel"; + return null; +} + +/** + * How a draft that did not finish done is recorded: skipped when its draft + * file says every unit was skipped (each field already written), else failed. + */ +export function draftOutcome(draftFile) { + const units = draftFile && typeof draftFile.units === "object" && draftFile.units ? Object.values(draftFile.units) : []; + if (units.length > 0 && units.every((u) => u && typeof u.skipped === "string")) { + return { status: "skipped", detail: `nothing to draft: ${units.length} field(s) already written (a re-draft of a draft is “Draft with” with force)` }; + } + return { status: "failed", detail: null }; +} diff --git a/umtool/lib/report/chain-draft.test.mjs b/umtool/lib/report/chain-draft.test.mjs @@ -0,0 +1,232 @@ +// Draft everything's generation steps (release 28 M9), run as the job runner +// runs them — one process a step under tsx — against a fake editor in this +// process (the report-draft and job routes, the way the editor answers them) +// over a temp article store: a draft done, a draft with nothing to draft +// (skipped), a draft the editor refuses and one whose job fails (failed, and +// the process exits 0 so the chain goes on), the left panel's pre-check, the +// YouTube draft with no build, and a cancel that cancels the editor's job. +// +// Run with: node --test umtool/lib/report/chain-draft.test.mjs + +import assert from "node:assert/strict"; +import test, { after, before } from "node:test"; +import { spawn } from "node:child_process"; +import http from "node:http"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { CHAIN_RUN, REPO_ROOT } from "./chain.mjs"; +import { draftOutcome, draftPrecheck, draftFileOf } from "./chain-draft.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const KIT = path.join(HERE, "..", "..", "..", "common", "testing", "draft"); +const ROOT = mkdtempSync(path.join(os.tmpdir(), "umtool-chain-draft-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const TRANSCRIPTS = path.join(ROOT, "transcripts"); +const ARTICLES = path.join(TRANSCRIPTS, "reports"); +const PROJECTS = path.join(ROOT, "projects"); +const PROJECT = path.join(PROJECTS, "synth-basic", "i1"); +const TOKEN = "chain-draft-token"; +const put = (file, data) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof data === "string" ? data : `${JSON.stringify(data, null, 2)}\n`); +}; +const json = (file) => JSON.parse(readFileSync(file, "utf8")); +const NOW = "2026-10-13T12:00:00.000Z"; +const itFile = path.join(ARTICLES, "synth-basic", "iterations", "1", "iteration.json"); +put(path.join(ROOT, "settings.json"), {}); +put(itFile, { + format: "archilyzer-iteration", + version: 1, + article: "synth-basic", + n: 1, + kind: "sweep", + model: "qwen3:8b", + parent: null, + copyOf: null, + question: "What does the baker say?", + status: "done", + usage: {}, + steps: [], + createdAt: NOW, + updatedAt: NOW, + projectDir: PROJECT, +}); +put(path.join(ARTICLES, "synth-basic", "iterations", "1", "report.json"), json(path.join(KIT, "reports", "basic.report.json"))); +const baseManifest = json(path.join(KIT, "manifests", "basic.video.manifest.json")); +put(path.join(PROJECT, "video.manifest.json"), baseManifest); + +// ─── The fake editor ─── +// What each task's job does: done (with a summary), fail (with a draft file), +// refuse (400 at the ask), slow (runs until cancelled). +const plan = { + cut: { end: "done", summary: "4 clips kept, in argument order" }, + onscreen: { end: "failed", summary: "no title(s) drafted (see onscreen-draft.json)", file: { units: { c01: { skipped: "the field has a value" }, c02: { skipped: "the field has a value" } } } }, + teaser: { refuse: "a teaser draft needs a teaser entry in the cut" }, + narrate: { end: "failed", summary: "no narration drafted", file: { units: { "the-bakery": { target: {}, attempts: [], chosen: null } } } }, + youtube: { end: "done", summary: "1 title and description drafted" }, + flips: { end: "slow" }, +}; +const requests = []; +const jobs = new Map(); +let next = 1; +const answer = (res, status, body) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); +}; +const editor = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + if (req.headers.authorization !== `Bearer ${TOKEN}`) return answer(res, 401, { ok: false, error: "no token" }); + const body = raw ? JSON.parse(raw) : null; + const url = new URL(req.url, "http://x"); + if (req.method === "POST" && url.pathname === "/api/ops/report-draft") { + requests.push(body); + const p = plan[body.task]; + if (!p || p.refuse) return answer(res, 400, { ok: false, error: p?.refuse ?? "unknown task" }); + const id = `job-${next++}`; + jobs.set(id, { id, task: body.task, polls: 0, status: "queued" }); + const it = json(itFile); + it.steps.push({ task: body.task, model: body.model ?? "qwen3:8b", status: "running", jobId: id, startedAt: NOW }); + put(itFile, it); + return answer(res, 202, { ok: true, jobId: id, iteration: 1 }); + } + if (req.method === "POST" && url.pathname === "/api/ops/job") { + requests.push({ cancel: body.ids }); + for (const id of body.ids ?? []) if (jobs.has(id)) jobs.get(id).status = "cancelled"; + return answer(res, 200, { ok: true }); + } + const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && m && jobs.has(m[1])) { + const j = jobs.get(m[1]); + const p = plan[j.task]; + j.polls += 1; + if (j.status !== "cancelled" && p.end !== "slow" && j.polls >= 2) { + j.status = p.end; + if (p.file) put(path.join(PROJECT, draftFileOf(j.task)), { task: j.task, ...p.file }); + const it = json(itFile); + it.steps = it.steps.map((s) => (s.jobId === j.id ? { ...s, status: p.end, detail: p.summary } : s)); + put(itFile, it); + } else if (j.status === "queued") j.status = "running"; + const ended = ["done", "failed", "cancelled"].includes(j.status); + return answer(res, 200, { + ok: true, + job: { id: j.id, kind: "report-draft", status: j.status, ...(j.status === "running" ? { progress: { metric: "cards", initial: 0, current: 1, target: 3 } } : {}) }, + tail: ["turn 1", ...(ended && p.summary ? [`@@report-draft ${JSON.stringify({ article: "synth-basic", iteration: 1, task: j.task, status: j.status, summary: p.summary })}`] : [])], + }); + } + return answer(res, 404, { ok: false, error: "no route" }); + }); +}); +let ENV; +before(async () => { + await new Promise((r) => editor.listen(0, "127.0.0.1", r)); + ENV = { + ...process.env, + TRANSCRIPTS_DIR: TRANSCRIPTS, + SITES_DIR: path.join(TRANSCRIPTS, "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + ARCHILYZER_EDITOR_URL: `http://127.0.0.1:${editor.address().port}`, + WORKER_TOKEN: TOKEN, + CHAIN_DRAFT_POLL_MS: "50", + }; + delete ENV.ARTICLES_DIR; +}); +after(() => editor.close()); + +function step(name, ...extra) { + return new Promise((resolve) => { + const child = spawn(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-basic", "1", name, "--projects-root", PROJECTS, ...extra], { cwd: REPO_ROOT, env: ENV }); + let out = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (out += d)); + const done = new Promise((r) => child.on("exit", (code, signal) => r({ code: signal ? 128 + 15 : code, out }))); + resolve({ child, done, out: () => out }); + }); +} +const recorded = (name) => [...json(itFile).steps].reverse().find((s) => s.task === `chain:${name}`); + +test("a draft done: one report-draft job on the model asked, followed to its end, its summary recorded", async () => { + const r = await (await step("draft-cut", "--model", "qwen3:8b")).done; + assert.equal(r.code, 0, r.out); + assert.deepEqual(requests.at(-1), { task: "cut", article: "synth-basic", iteration: 1, model: "qwen3:8b" }); + assert.match(r.out, /cut draft running — cards 1\/3/); + const s = recorded("draft-cut"); + assert.equal(s.status, "done"); + assert.equal(s.detail, "4 clips kept, in argument order"); +}); + +test("nothing to draft is skipped; a refused ask and a failed job are failed — and the chain goes on (exit 0)", async () => { + const skipped = await (await step("draft-onscreen")).done; + assert.equal(skipped.code, 0, skipped.out); + assert.equal(requests.at(-1).model, undefined, "no --model: the task's route chooses"); + assert.equal(recorded("draft-onscreen").status, "skipped"); + assert.match(recorded("draft-onscreen").detail, /nothing to draft: 2 field\(s\) already written/); + + const refused = await (await step("draft-teaser")).done; + assert.equal(refused.code, 0, refused.out); + assert.equal(recorded("draft-teaser").status, "failed"); + assert.match(recorded("draft-teaser").detail, /the editor refused the teaser draft: a teaser draft needs a teaser entry/); + assert.match(refused.out, /the chain goes on without it/); + + const failed = await (await step("draft-narrate")).done; + assert.equal(failed.code, 0, failed.out); + assert.equal(recorded("draft-narrate").status, "failed"); + assert.match(recorded("draft-narrate").detail, /^no narration drafted \(job job-\d+\)$/); +}); + +test("the left panel: no deck skips flips; flips on the cut skip threads — the editor is not asked", async () => { + const asked = requests.length; + const noDeck = await (await step("draft-flips")).done; + assert.equal(noDeck.code, 0, noDeck.out); + assert.equal(recorded("draft-flips").status, "skipped"); + assert.match(recorded("draft-flips").detail, /no on-screen deck \(render\.chrome\) to draw the flips on/); + const withFlips = { ...baseManifest, render: { ...(baseManifest.render ?? {}), chrome: { flips: { pairs: [{ id: "p" }] } } } }; + put(path.join(PROJECT, "video.manifest.json"), withFlips); + const threads = await (await step("draft-threads")).done; + assert.equal(threads.code, 0, threads.out); + assert.equal(recorded("draft-threads").status, "skipped"); + assert.match(recorded("draft-threads").detail, /the cut has flips: flips and threads share the left panel/); + assert.equal(requests.length, asked); + put(path.join(PROJECT, "video.manifest.json"), baseManifest); +}); + +test("the YouTube draft with no build yet: done, and the next build writes out/youtube.txt", async () => { + const r = await (await step("draft-youtube")).done; + assert.equal(r.code, 0, r.out); + assert.equal(recorded("draft-youtube").status, "done"); + assert.equal(recorded("draft-youtube").detail, "1 title and description drafted; the next build writes out/youtube.txt"); +}); + +test("a cancel of the chain cancels the editor's job, and the step is recorded cancelled", async () => { + put(path.join(PROJECT, "video.manifest.json"), { ...baseManifest, render: { ...(baseManifest.render ?? {}), chrome: {} } }); + const s = await step("draft-flips"); + const until = Date.now() + 60_000; + while (!/flips draft running/.test(s.out()) && Date.now() < until) await new Promise((r) => setTimeout(r, 50)); + s.child.kill("SIGTERM"); + const r = await s.done; + assert.equal(r.code, 143, r.out); + const job = requests.find((q) => q.cancel); + assert.ok(job, "the editor's job was cancelled"); + assert.equal(jobs.get(job.cancel[0]).task, "flips"); + assert.equal(recorded("draft-flips").status, "cancelled"); +}); + +test("draftPrecheck and draftOutcome, pure", () => { + assert.equal(draftPrecheck("cut", {}), null); + assert.match(draftPrecheck("threads", { render: {} }), /no on-screen deck/); + assert.equal(draftPrecheck("threads", { render: { chrome: {} } }), null); + assert.match(draftPrecheck("flips", { render: { chrome: { threads: { list: [{ id: "a" }] } } } }), /the cut has threads/); + assert.equal(draftOutcome(null).status, "failed"); + assert.equal(draftOutcome({ units: {} }).status, "failed"); + assert.equal(draftOutcome({ units: { a: { skipped: "x" }, b: { chosen: null } } }).status, "failed"); + assert.equal(draftOutcome({ units: { a: { skipped: "x" } } }).status, "skipped"); + assert.equal(draftFileOf("narrate"), "narration-draft.json"); + assert.equal(draftFileOf("cut"), "cut-draft.json"); +}); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -2,7 +2,7 @@ // own process — // // node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step> -// [--projects-root <dir>] [--site-origin <url>] [--final] +// [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] // // — under tsx, because the article registry, the iterations store and the // reports CLIs it calls are common's TypeScript. The Next app never imports @@ -14,6 +14,13 @@ // TTS here): `pnpm ops fetch-windows` / `capture-posts` and // narrate-via-editor.mjs, with the editor's URL and token read from the // environment or the editor's env files at run time — never put in a step. +// +// A generation step (`draft-<task>`, release 28 M9) is a `report-draft` job +// the editor runs: POST /api/ops/report-draft, then GET /api/ops/job/<id> +// until it ends (its progress and log lines printed), and a cancel of the +// chain cancels the job. The step is OPTIONAL: refused or failed, it is +// recorded failed and the process exits 0 so the chain goes on; with nothing +// to draft (every field already written) it is recorded skipped. import { spawn } from "node:child_process"; import { copyFile, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; @@ -38,7 +45,8 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; -import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; @@ -47,6 +55,8 @@ const SCREENSHOT_MISSING = /no captured screenshot/; /** A step that ends early with a reason: failed, with that line. */ class StepFailed extends Error {} +/** A step with nothing to do: skipped, with that line (an optional step's). */ +class StepSkipped extends Error {} const exists = async (p) => !!(await stat(p).catch(() => null)); @@ -244,6 +254,125 @@ const STEPS = { }, }; +// ─── The generation steps (release 28 M9): one report-draft job each ─── + +// How often a draft step asks the editor about its job. +const DRAFT_POLL_MS = Number(process.env.CHAIN_DRAFT_POLL_MS) > 0 ? Number(process.env.CHAIN_DRAFT_POLL_MS) : 2000; +// A run of failed polls this long ends the step (the job keeps running in the editor). +const DRAFT_POLL_GIVE_UP = 60; +const RESULT_MARKER = "@@report-draft "; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** One call to the editor's ops API: `{ ok, status, body }` or `{ ok: false, error }`. Never throws. */ +async function editorCall(env, method, route, body) { + const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, ""); + try { + const res = await fetch(`${base}${route}`, { + method, + headers: { ...(env.WORKER_TOKEN ? { authorization: `Bearer ${env.WORKER_TOKEN}` } : {}), "content-type": "application/json" }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok || json?.ok === false) return { ok: false, status: res.status, error: String(json?.error ?? `HTTP ${res.status}`) }; + return { ok: true, status: res.status, body: json }; + } catch (err) { + return { ok: false, status: 0, error: `the editor at ${base} did not answer: ${err?.message ?? err}` }; + } +} + +/** The task's report-draft marker in a job's log tail, or null. */ +function markerOf(tail) { + for (let i = tail.length - 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; +} + +const readJsonOr = async (file) => { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +}; + +async function draftStep(ctx, task) { + const file = path.join(ctx.project, "video.manifest.json"); + const manifest = await readJsonOr(file); + if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); + const why = draftPrecheck(task, manifest); + if (why) throw new StepSkipped(why); + const env = await editorEnv(); + const body = { task, article: ctx.article, iteration: ctx.n, ...(ctx.model ? { model: ctx.model } : {}) }; + const started = await editorCall(env, "POST", "/api/ops/report-draft", body); + if (!started.ok) throw new StepFailed(`the editor refused the ${task} draft: ${started.error}`); + const jobId = String(started.body.jobId ?? ""); + if (!jobId) throw new StepFailed(`the editor started no job for the ${task} draft`); + console.log(`chain: ${task} draft — job ${jobId}${ctx.model ? ` on ${ctx.model}` : " on the route's model"}`); + ctx.onCancel(() => editorCall(env, "POST", "/api/ops/job", { verb: "cancel", ids: [jobId] })); + let job = null; + let tail = []; + let misses = 0; + let said = ""; + for (;;) { + const r = await editorCall(env, "GET", `/api/ops/job/${encodeURIComponent(jobId)}?tail=200`); + if (!r.ok) { + if (++misses >= DRAFT_POLL_GIVE_UP) throw new StepFailed(`lost the ${task} draft's job ${jobId}: ${r.error} (it may still be running in the editor)`); + } else { + misses = 0; + job = r.body.job ?? {}; + tail = Array.isArray(r.body.tail) ? r.body.tail.map(String) : []; + const p = job.progress; + const now = `${job.status}${p && typeof p.current === "number" ? ` — ${p.metric ?? "progress"} ${p.current}/${p.target ?? "?"}` : ""}`; + if (now !== said) { + console.log(`chain: ${task} draft ${now}`); + said = now; + } + if (["done", "failed", "cancelled"].includes(job.status)) break; + } + await sleep(DRAFT_POLL_MS); + } + for (const line of tail.filter((l) => !l.includes(RESULT_MARKER)).slice(-8)) console.log(` ${line}`); + const marker = markerOf(tail); + const it = await readIteration(ctx.article, ctx.n, ctx.paths).catch(() => null); + const step = [...(it?.steps ?? [])].reverse().find((s) => s.task === task && s.jobId === jobId); + const words = marker?.summary ?? step?.detail ?? null; + if (job.status === "done") return words ?? `${task} drafted`; + if (job.status === "cancelled") throw new StepFailed(`the ${task} draft's job ${jobId} was cancelled in the editor`); + const outcome = draftOutcome(await readJsonOr(path.join(ctx.project, draftFileOf(task)))); + if (outcome.status === "skipped") throw new StepSkipped(outcome.detail); + throw new StepFailed(`${words ?? `the ${task} draft failed`} (job ${jobId})`); +} + +// After the YouTube draft, a built cut re-muxes its chapters, which writes +// out/youtube.txt (build-video --chapters-only; Draft everything's build is +// the fast one). Not built yet: the next build writes it. +async function youtubeText(ctx) { + const file = path.join(ctx.project, "video.manifest.json"); + const manifest = await readJsonOr(file); + const out = path.join(ctx.project, "out"); + if (!manifest || !(await exists(path.join(out, `${manifest.slug ?? ctx.article}.mp4`)))) return "; the next build writes out/youtube.txt"; + const code = await run( + [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), file, "--out", out, "--chapters-only", "--no-xfade", "--skip-fetch"], + { cwd: PIPELINE_DIR }, + ); + return code === 0 ? "; out/youtube.txt written" : `; out/youtube.txt not written (build-video --chapters-only ended ${code})`; +} + +for (const name of ["cut", "onscreen", "teaser", "flips", "threads", "narrate"]) { + STEPS[`draft-${name}`] = (ctx) => draftStep(ctx, name); +} +STEPS["draft-youtube"] = async (ctx) => { + const said = await draftStep(ctx, "youtube"); + return `${said}${await youtubeText(ctx)}`; +}; + async function writeJson(file, value) { const tmp = `${file}.tmp-${process.pid}`; await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); @@ -266,10 +395,11 @@ async function sweepOrigin(ctx) { * @returns {Promise<number>} the exit code: 0 done, 1 failed, 2 refused */ export async function runChainStep(article, n, name, opts = {}) { - if (!CHAIN_STEP_NAMES.includes(name)) { - console.error(`chain: no step "${name}" (${CHAIN_STEP_NAMES.join(", ")})`); + if (!ALL_CHAIN_STEP_NAMES.includes(name)) { + console.error(`chain: no step "${name}" (${ALL_CHAIN_STEP_NAMES.join(", ")})`); return 2; } + const optional = chainStepDef(name)?.optional === true; const paths = opts.paths ?? getPaths(); const iteration = await readIteration(article, n, paths).catch((err) => { console.error(`chain: ${err.message}`); @@ -294,6 +424,11 @@ export async function runChainStep(article, n, name, opts = {}) { project: projectOf(projectsRoot, article, n), siteOrigin: opts.siteOrigin, final: opts.final === true, + model: opts.model, + cancels: [], + onCancel(fn) { + this.cancels.push(fn); + }, }; const task = chainTask(name); const startedAt = new Date(); @@ -313,7 +448,11 @@ export async function runChainStep(article, n, name, opts = {}) { await record("running"); // A cancel (the job runner's SIGTERM to the step's process group) is recorded, best effort. const onTerm = () => { - record("cancelled", "cancelled").finally(() => process.exit(143)); + // What the step started elsewhere (a draft's editor job) is cancelled first. + const hooks = Promise.allSettled(ctx.cancels.map((f) => f())); + Promise.race([hooks, sleep(5000)]) + .then(() => record("cancelled", "cancelled")) + .finally(() => process.exit(143)); }; process.once("SIGTERM", onTerm); console.log(`chain: ${article} i${n} — ${name}`); @@ -323,8 +462,18 @@ export async function runChainStep(article, n, name, opts = {}) { console.log(`chain: ${name} done — ${detail}`); return 0; } catch (err) { + if (err instanceof StepSkipped) { + await record("skipped", err.message).catch(() => {}); + console.log(`chain: ${name} skipped — ${err.message}`); + return 0; + } const detail = err instanceof StepFailed ? err.message : `${err?.name ?? "Error"}: ${err?.message ?? String(err)}`; await record("failed", detail).catch(() => {}); + if (optional) { + // A missing draft never blocks the chain. + console.error(`chain: ${name} failed — ${detail}; the chain goes on without it`); + return 0; + } console.error(`chain: ${name} failed — ${detail}`); return 1; } finally { @@ -346,6 +495,7 @@ function parseArgs(argv) { projectsRoot: flag("--projects-root"), siteOrigin: flag("--site-origin"), final: rest.includes("--final"), + model: flag("--model"), }; } @@ -353,7 +503,7 @@ const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToP if (isMain) { const a = parseArgs(process.argv.slice(2)); if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) { - console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final]"); + console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]"); process.exit(2); } runChainStep(a.article, a.n, a.name, a).then( diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs @@ -20,6 +20,25 @@ // dedupe hard-link identical segments and voices across the article's // projects (./iterations.mjs) // +// DRAFT EVERYTHING (release 28 M9) is the same chain with the generation +// steps in it, each OPTIONAL — `draft-<task>` runs one `report-draft` job on +// the iteration through the editor and waits for it: +// +// current → windows → prepare → posts → manifest → draft-cut → +// draft-onscreen → draft-teaser → draft-flips → draft-threads → +// draft-narrate → voices → video (fast, never --final) → podcast → +// draft-youtube +// +// The drafts go after `manifest` (a media task drafts the project's manifest) +// and before `voices` (narration is voiced) and the build (the drafts are in +// it); YouTube's after the build, which then re-muxes its chapters so +// out/youtube.txt is written. No attach and no dedupe: a cut whose drafts are +// not reviewed is not made the article's video. A draft step that the editor +// refuses, or whose job fails, is recorded failed and the chain goes on (a +// missing draft never blocks a build); one with nothing to draft is skipped. +// A resume counts an optional step that ran (done, skipped or failed) as +// finished. The default chain ("make the video") has no optional step. +// // Each step is ONE PROCESS — `node --import tsx chain-run.mjs step <id> <n> // <step>` — so lib/jobs.ts runs the chain as a job like any other (detached // process group, cancel, per-step timeout), and `umtool chain` runs the same @@ -36,19 +55,53 @@ import os from "node:os"; import path from "node:path"; import { UMTOOL_DIR } from "./driver.mjs"; +// `draft`: the report-draft task an optional generation step runs. +// `modes`: the chains a step is in ("video" — make the video; "draft-all"). +const BOTH = ["video", "draft-all"]; +const DRAFT_ONLY = ["draft-all"]; +const VIDEO_ONLY = ["video"]; +const DRAFT_TIMEOUT = 3 * 60 * 60_000; + export const CHAIN_STEPS = [ - { name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000 }, - { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000 }, - { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000 }, - { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000 }, - { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000 }, - { name: "voices", label: "voice the narration (editor TTS)", timeoutMs: 3 * 60 * 60_000, ndjson: true }, - { name: "video", label: "build the video", timeoutMs: 4 * 60 * 60_000, ndjson: true }, - { name: "podcast", label: "build the podcast", timeoutMs: 30 * 60_000, ndjson: true }, - { name: "attach", label: "attach the video to the article", timeoutMs: 30 * 60_000 }, - { name: "dedupe", label: "share identical segments and voices", timeoutMs: 15 * 60_000 }, + { name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000, modes: BOTH }, + { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: BOTH }, + { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000, modes: BOTH }, + { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000, modes: BOTH }, + { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000, modes: BOTH }, + { name: "draft-cut", label: "draft the cut: which clips, in what order", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "cut" }, + { name: "draft-onscreen", label: "draft the on-screen titles", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "onscreen" }, + { name: "draft-teaser", label: "draft the teaser", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "teaser" }, + { name: "draft-flips", label: "draft the flips (THEN/NOW pairs)", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "flips" }, + { name: "draft-threads", label: "draft the threads", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "threads" }, + { name: "draft-narrate", label: "draft the narration", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "narrate" }, + { name: "voices", label: "voice the narration (editor TTS)", timeoutMs: 3 * 60 * 60_000, ndjson: true, modes: BOTH }, + { name: "video", label: "build the video", timeoutMs: 4 * 60 * 60_000, ndjson: true, modes: BOTH }, + { name: "podcast", label: "build the podcast", timeoutMs: 30 * 60_000, ndjson: true, modes: BOTH }, + { name: "draft-youtube", label: "draft the YouTube title and description", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "youtube" }, + { name: "attach", label: "attach the video to the article", timeoutMs: 30 * 60_000, modes: VIDEO_ONLY }, + { name: "dedupe", label: "share identical segments and voices", timeoutMs: 15 * 60_000, modes: VIDEO_ONLY }, ]; -export const CHAIN_STEP_NAMES = CHAIN_STEPS.map((s) => s.name); + +/** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */ +export const CHAIN_MODES = ["video", "draft-all"]; + +/** A chain's steps, in order. */ +export function chainStepsOf(mode = "video") { + if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`); + return CHAIN_STEPS.filter((s) => s.modes.includes(mode)); +} + +/** Every step's name, either chain's (what the executor runs). */ +export const ALL_CHAIN_STEP_NAMES = CHAIN_STEPS.map((s) => s.name); +/** The generation steps' tasks, in Draft everything's order. */ +export const DRAFT_STEP_TASKS = CHAIN_STEPS.filter((s) => s.draft).map((s) => s.draft); +/** The step that drafts a task (`draft-<task>`). */ +export const draftStepName = (task) => `draft-${task}`; +/** The step's definition, or undefined. */ +export const chainStepDef = (name) => CHAIN_STEPS.find((s) => s.name === name); + +/** The default chain's step names (make the video). */ +export const CHAIN_STEP_NAMES = chainStepsOf("video").map((s) => s.name); // How a step is named in the iteration's `steps`. export const chainTask = (name) => `chain:${name}`; @@ -94,25 +147,32 @@ export function chainProject(projectsRoot, article, n) { /** * Where a chain starts: `from` when given, else the first step the iteration - * has not recorded done (`done`: the step names recorded done), else nothing - * (the whole chain is done: null). + * has not recorded finished (`done`: the step names recorded finished, + * doneSteps), else nothing (the whole chain is done: null). */ -export function chainStart({ from = null, done = [] } = {}) { +export function chainStart({ from = null, done = [], mode = "video" } = {}) { + const names = chainStepsOf(mode).map((s) => s.name); if (from !== null && from !== undefined) { - if (!CHAIN_STEP_NAMES.includes(from)) throw new Error(`--from must be one of ${CHAIN_STEP_NAMES.join(", ")}`); + if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`); return from; } const finished = new Set(done); - return CHAIN_STEP_NAMES.find((s) => !finished.has(s)) ?? null; + return names.find((s) => !finished.has(s)) ?? null; } -/** The step names an iteration.json records done, from its `steps`. */ +// A step that ran to an end a resume goes past: done; for an optional step +// (a draft) also skipped or failed — a missing draft never blocks the chain. +const FINISHED = ["done"]; +const OPTIONAL_FINISHED = ["done", "skipped", "failed"]; + +/** The step names an iteration.json records finished, from its `steps`. */ export function doneSteps(iteration) { const out = []; for (const s of iteration?.steps ?? []) { if (typeof s?.task !== "string" || !s.task.startsWith("chain:")) continue; const name = s.task.slice("chain:".length); - if (s.status === "done") out.push(name); + const ends = chainStepDef(name)?.optional ? OPTIONAL_FINISHED : FINISHED; + if (ends.includes(s.status)) out.push(name); } return out; } @@ -132,28 +192,35 @@ export function readIterationRecord(articlesDir, article, n) { * The chain's steps for lib/jobs.ts (and `umtool chain`), from `start` * (chainStart) to the end. No secret rides in a step: the executor reads the * editor's URL and token itself (jobView shows a step's env to the browser). + * `mode` "draft-all" is Draft everything: its build is the fast one whatever + * `final` says, and `model` rides on the draft steps (else each task's route). * - * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string }} o + * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string }} o * @returns {import("../trim").Step[]} */ export function chainSteps(o) { const projectsRoot = o.projectsRoot ?? configuredProjectsRoot(); chainProject(projectsRoot, o.article, o.n); - const start = o.start === undefined ? CHAIN_STEP_NAMES[0] : o.start; + const mode = o.mode ?? "video"; + const defs = chainStepsOf(mode); + const start = o.start === undefined ? defs[0].name : o.start; if (start === null) return []; - const at = CHAIN_STEP_NAMES.indexOf(start); + const at = defs.findIndex((s) => s.name === start); if (at < 0) throw new Error(`no chain step "${start}"`); + if (o.model !== undefined && (typeof o.model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(o.model))) { + throw new Error(`"${o.model}" is not a model name`); + } const extra = [ "--projects-root", projectsRoot, ...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []), - ...(o.final ? ["--final"] : []), + ...(o.final && mode === "video" ? ["--final"] : []), ]; - return CHAIN_STEPS.slice(at).map((s, i) => ({ - label: `${at + i + 1}/${CHAIN_STEPS.length} ${s.label}`, + return defs.slice(at).map((s, i) => ({ + label: `${at + i + 1}/${defs.length} ${s.label}`, cwd: REPO_ROOT, env: {}, - argv: [o.node ?? process.execPath, "--import", "tsx", CHAIN_RUN, "step", o.article, String(o.n), s.name, ...extra], + argv: [o.node ?? process.execPath, "--import", "tsx", CHAIN_RUN, "step", o.article, String(o.n), s.name, ...extra, ...(s.draft && o.model ? ["--model", o.model] : [])], timeoutMs: s.timeoutMs, ...(s.ndjson ? { ndjson: true } : {}), })); @@ -166,22 +233,25 @@ export function chainSteps(o) { * iteration not done, or an unknown `from`. `steps` is empty when every step * is done. * - * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean }} o + * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string }} o */ export function planChain(o) { const record = readIterationRecord(o.articlesDir, o.article, o.n); if (!record) throw new Error(`"${o.article}" has no iteration i${o.n} under ${o.articlesDir}`); if (record.status !== "done") throw new Error(`${o.article} i${o.n} is ${record.status}: the chain runs over a done iteration`); - const start = chainStart({ from: o.from ?? null, done: doneSteps(record) }); + const mode = o.mode ?? "video"; + const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode }); const steps = chainSteps({ article: o.article, n: o.n, start, + mode, + ...(o.model ? { model: o.model } : {}), ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}), ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}), final: o.final === true, }); - return { record, start, steps }; + return { record, start, steps, mode }; } const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs @@ -21,6 +21,8 @@ import { chainStart, chainSteps, chainWindows, + chainStepsOf, + DRAFT_STEP_TASKS, doneSteps, originFromSweep, } from "./chain.mjs"; @@ -68,6 +70,57 @@ test("resume: the first step not recorded done; --from names one; all done is no assert.throws(() => chainStart({ from: "nope" }), /--from must be one of/); }); +test("Draft everything: the drafts between the manifest and the fast build, YouTube after it; the default chain unchanged", () => { + const names = chainStepsOf("draft-all").map((s) => s.name); + assert.deepEqual(names, [ + "current", "windows", "prepare", "posts", "manifest", + "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate", + "voices", "video", "podcast", "draft-youtube", + ]); + assert.deepEqual(chainStepsOf("video").map((s) => s.name), CHAIN_STEP_NAMES); + assert.ok(chainStepsOf("video").every((s) => !s.optional), "make the video has no optional step"); + assert.deepEqual(DRAFT_STEP_TASKS, ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]); + assert.throws(() => chainStepsOf("nope"), /no chain "nope"/); + + const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", final: true }); + assert.equal(steps.length, 15); + assert.equal(steps[5].label, "6/15 draft the cut: which clips, in what order"); + // The model rides on the draft steps only; the build is the fast one (--final is ignored). + for (const s of steps) { + const draft = s.argv[7].startsWith("draft-"); + assert.equal(s.argv.includes("--model"), draft, s.argv[7]); + assert.ok(!s.argv.includes("--final"), s.argv[7]); + } + assert.deepEqual(steps[5].argv.slice(8), ["--projects-root", "/p", "--model", "qwen3:8b"]); + // No model: each task's route chooses. + assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all" }).every((s) => !s.argv.includes("--model"))); + assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", model: "a b" }), /not a model name/); + // attach is not in Draft everything. + assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", start: "attach" }), /no chain step "attach"/); +}); + +test("Draft everything resumes past a draft that ran — done, skipped or failed — but not past a failed code step", () => { + const it = { + steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done" })).concat([ + { task: "chain:draft-cut", status: "done" }, + { task: "chain:draft-onscreen", status: "failed" }, + { task: "chain:draft-teaser", status: "skipped" }, + { task: "chain:draft-flips", status: "cancelled" }, + ]), + }; + const done = doneSteps(it); + assert.deepEqual(done.slice(5), ["draft-cut", "draft-onscreen", "draft-teaser"]); + assert.equal(chainStart({ done, mode: "draft-all" }), "draft-flips"); + // The default chain never sees the drafts: it resumes at voices. + assert.equal(chainStart({ done }), "voices"); + const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "failed" }] }; + assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "windows"); + assert.equal(chainStart({ from: "draft-threads", mode: "draft-all" }), "draft-threads"); + assert.throws(() => chainStart({ from: "draft-threads" }), /--from must be one of/); + const all = chainStepsOf("draft-all").map((s) => s.name); + assert.equal(chainStart({ done: all, mode: "draft-all" }), null); +}); + test("chainWindows: each cited moment padded to the cut's fetchPad and the citation's own pad, rounded outward, once", () => { const report = { id: "art", @@ -117,6 +170,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus assert.match(text, /\(cd .* && .*chain-run\.mjs step art 2 video/); assert.throws(() => run("art", "9", "--dry"), (e) => /has no iteration i9/.test(String(e.stderr))); assert.throws(() => run("art", "2", "--dry", "--from", "nope"), (e) => /--from must be one of/.test(String(e.stderr))); + // --draft-all: the same resume point, the drafts in the plan, the model on them. + const all = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--model", "claude-sonnet-5-5", "--projects-root", path.join(ROOT, "projects"))); + assert.equal(all.start, "prepare"); + assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate"]); + assert.equal(all.steps.at(-1).argv[7], "draft-youtube"); + assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5")); + assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr))); + assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr))); }); test("planChain: the record, the resume point and the steps; a queued iteration is refused", async () => { diff --git a/umtool/lib/report/drafted-writer.test.mjs b/umtool/lib/report/drafted-writer.test.mjs @@ -0,0 +1,127 @@ +// The manifest writer is the operator (release 28, M0): every umtool write +// that changes a drafted field removes its drafted mark -- one test per field +// -- an unrelated write keeps every mark, a re-save of the same value keeps +// it, an orphan is dropped, and "Use this" (writeDraftedField) writes an +// alternative as the operator's. Over the S0 kit's `full` manifest. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + MANIFEST_NAME, StructureRefused, moveEntry, updateChrome, updateNarration, updateOnscreen, updateTeaser, writeDraftedField, +} from "./manifest.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8")); +const P = (task) => ({ task, model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); + +// Every field drafted: c02's on-screen text, the contest card's narration, +// the teaser's lines, the threads, the cut's order, the YouTube text. +function drafted() { + const m = full(); + const e = (id) => m.timeline.find((x) => x.id === id); + e("c02").onscreen = { title: "The oven" }; + e("c02").drafted = { onscreen: P("onscreen") }; + e("the-contest").drafted = { narration: P("narrate") }; + e("fin").drafted = { lines: P("teaser") }; + m.publish = { youtube: { title: "T", description: "D" } }; + m.drafted = { timeline: P("cut"), "render.chrome.threads": P("threads"), "publish.youtube": P("youtube") }; + return m; +} + +async function project(t, manifest = drafted()) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-drafted-")); + t.after(() => rm(dir, { recursive: true, force: true })); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + const read = async () => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + return { dir, read }; +} + +/** Every mark, as `<entry or *>:<field>`. */ +const marks = (m) => [ + ...m.timeline.flatMap((e) => Object.keys(e.drafted ?? {}).map((f) => `${e.id}:${f}`)), + ...Object.keys(m.drafted ?? {}).map((f) => `*:${f}`), +]; +const ALL = ["c02:onscreen", "the-contest:narration", "fin:lines", "*:timeline", "*:render.chrome.threads", "*:publish.youtube"]; + +test("each field: the operator's edit removes its mark, and only its own", async (t) => { + const edits = [ + ["on-screen text", (dir) => updateOnscreen(dir, { c02: { title: "Mine" } }), "c02:onscreen"], + ["teaser lines", (dir) => updateTeaser(dir, "fin", { lines: ["One", "Two", "Three"] }), "fin:lines"], + ["narration words", (dir) => updateNarration(dir, "the-contest", "My own words."), "the-contest:narration"], + ["the cut's order", (dir) => moveEntry(dir, "c03", 3), "*:timeline"], + ["the threads", async (dir) => { + const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + const chrome = { ...m.render.chrome, threads: { list: [...m.render.chrome.threads.list.map((x) => ({ ...x })), { id: "lease", label: "The lease" }] } }; + return updateChrome(dir, chrome); + }, "*:render.chrome.threads"], + ["the YouTube text", (dir) => writeDraftedField(dir, { field: "publish.youtube", value: { title: "Mine", description: "D" } }), "*:publish.youtube"], + ]; + for (const [what, edit, mark] of edits) { + const p = await project(t); + assert.deepEqual(marks(await p.read()), ALL); + await edit(p.dir); + assert.deepEqual(marks(await p.read()), ALL.filter((x) => x !== mark), what); + } +}); + +test("a write that leaves a drafted field as it was keeps its mark; an orphan is dropped", async (t) => { + const p = await project(t); + // c01's text (the operator's) changes; c02's re-saved exactly as it is. + await updateOnscreen(p.dir, { c01: { title: "Edited" }, c02: { title: "The oven" } }); + assert.deepEqual(marks(await p.read()), ALL); + // A chrome save that leaves the threads alone keeps their mark. + const m = await p.read(); + await updateChrome(p.dir, { ...m.render.chrome, factcheck: { stamp: { seconds: 2 } } }); + assert.deepEqual(marks(await p.read()), ALL); + // Clearing c02's text leaves its mark an orphan: dropped by the write. + await updateOnscreen(p.dir, { c02: null }); + assert.deepEqual(marks(await p.read()), ALL.filter((x) => x !== "c02:onscreen")); +}); + +test("writeDraftedField: Use this writes an alternative as the operator's, checked as its editor checks it", async (t) => { + const p = await project(t); + // c01's text is the operator's; an alternative replaces it, unmarked. + await writeDraftedField(p.dir, { entry: "c01", field: "onscreen", value: { title: "Not for sale?" } }); + const m = await p.read(); + assert.deepEqual(m.timeline.find((e) => e.id === "c01").onscreen, { title: "Not for sale?" }); + assert.equal(m.timeline.find((e) => e.id === "c01").drafted, undefined); + // A drafted field taken from an alternative is the operator's too. + await writeDraftedField(p.dir, { entry: "fin", field: "lines", value: ["Synth Kitchen", "Next: the lease"] }); + assert.ok(!marks(await p.read()).includes("fin:lines")); + // Refusals leave the file as it was. + const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"); + await assert.rejects(writeDraftedField(p.dir, { entry: "fin", field: "lines", value: [] }), StructureRefused); + await assert.rejects(writeDraftedField(p.dir, { field: "timeline", value: [] }), /applied by the cut task/); + await assert.rejects(writeDraftedField(p.dir, { entry: "c01", field: "quote", value: "x" }), /not a drafted field/); + await assert.rejects(writeDraftedField(p.dir, { field: "publish.youtube", value: { title: 3 } }), StructureRefused); + assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before); +}); + +test("writeDraftedField: a threads alternative's clips set each clip's thread with the list (release 28 M9)", async (t) => { + const p = await project(t); + const clipIds = (await p.read()).timeline.filter((e) => e.type === "clip").map((e) => e.id); + const [first, ...others] = clipIds; + const clips = Object.fromEntries([[first, "solo"], ...others.map((id) => [id, "rest"])]); + const list = [{ id: "solo", label: "One clip" }, { id: "rest", label: "The others" }]; + await writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips } }); + const m = await p.read(); + assert.deepEqual(m.render.chrome.threads, { list }, "the field is the list alone"); + assert.equal(m.timeline.find((e) => e.id === first).thread, "solo"); + assert.ok(others.every((id) => m.timeline.find((e) => e.id === id).thread === "rest")); + assert.ok(!marks(m).includes("*:render.chrome.threads"), "taken, it is the operator's"); + // A clip the cut lacks, or a thread left with no clip, is refused; the file stays. + const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"); + await assert.rejects(writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips: { nope: "solo" } } }), /clips this cut does not have: nope/); + await assert.rejects( + writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips: Object.fromEntries(clipIds.map((id) => [id, "rest"])) } }), + /thread solo has no clip/, + ); + assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before); +}); diff --git a/umtool/lib/report/drafts.mjs b/umtool/lib/report/drafts.mjs @@ -0,0 +1,117 @@ +// The drafts review's view of a project (release 28, M0): every drafted field +// of the manifest (every cut's) and every narrated card, with who drafted it, +// its value as words, its review state (report-to-video's drafts-review.mjs), +// the alternatives the draft tasks kept for it (`<task>-draft.json`), and what +// a final build of the default cut would say. What the review page and the +// badges draw, and what the route answers after each action -- one shape. +// +// Plain ESM: `node --test` runs it with no TypeScript. +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; +import { + DRAFTS_REVIEW_FILE, FIELD_LABELS, draftsReviewProblems, draftsReviewRows, judgedText, readDraftsReview, +} from "umtool-report-to-video/drafts-review"; +import { fieldSignature, reviewAddress, stableStringify } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; + +/** A task's draft file beside the manifest: `<task>-draft.json`. */ +export const DRAFT_FILE_RE = /^[a-z0-9][a-z0-9-]{0,62}-draft\.json$/; + +/** + * Every alternative the draft tasks kept in this project, in file order: + * `{ id: "<file>#<i>", file, index, address, entry, field, value, provenance, reason }`. + * A file that does not parse is skipped (its task wrote it; it is not this + * view's to repair). + * + * @param {string} projectDir + */ +export async function readAlternatives(projectDir) { + let names = []; + try { + names = (await readdir(projectDir)).filter((n) => DRAFT_FILE_RE.test(n)).sort(); + } catch { + return []; + } + const out = []; + for (const file of names) { + let doc; + try { + doc = JSON.parse(await readFile(path.join(projectDir, file), "utf8")); + } catch { + continue; + } + const list = Array.isArray(doc?.alternatives) ? doc.alternatives : []; + list.forEach((a, index) => { + const t = a?.target; + if (!t || typeof t.field !== "string" || a.value === undefined) return; + const entry = typeof t.entry === "string" && t.entry ? t.entry : null; + out.push({ + id: `${file}#${index}`, + file, + index, + address: reviewAddress({ entry, field: t.field }), + entry, + field: t.field, + value: a.value, + provenance: a.provenance ?? null, + reason: typeof a.reason === "string" ? a.reason : "operator", + }); + }); + } + return out; +} + +/** One alternative by its id, or null. */ +export async function alternativeById(projectDir, id) { + return (await readAlternatives(projectDir)).find((a) => a.id === id) ?? null; +} + +/** + * @param {string} projectDir + * @param {any} manifest the whole manifest, as written + */ +export async function draftsView(projectDir, manifest) { + const review = await readDraftsReview(projectDir); + const m = manifest && typeof manifest === "object" ? manifest : { timeline: [] }; + const alternatives = (await readAlternatives(projectDir)).map((a) => { + const current = fieldSignature(m, { entry: a.entry, field: a.field }); + // "in use": the field holds this value now (somebody took it). + const proposed = a.field === "timeline" ? null : a.value; + return { ...a, label: FIELD_LABELS[a.field] ?? a.field, text: judgedText(a.field, a.value), inUse: proposed !== null && stableStringify(current) === stableStringify(proposed) }; + }); + const rows = draftsReviewRows(m, review).map((r) => ({ + address: r.address, + entry: r.entry, + field: r.field, + label: FIELD_LABELS[r.field] ?? r.field, + drafted: r.provenance, + text: r.text, + key: r.key, + state: r.state, + verdict: r.row?.verdict ?? null, + note: r.row?.note ?? "", + judgedText: r.row?.text ?? "", + judgedAt: r.row?.at ?? "", + })); + const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 }; + for (const r of rows) if (r.drafted) counts[r.state] += 1; + // What a final build of the default cut would say of the review. + let gate = { errors: [], warnings: [] }; + try { + const cut = selectVariant(m, DEFAULT_VARIANT); + const fin = draftsReviewProblems(cut, review, { final: true }); + gate = { errors: fin.errors, warnings: fin.warnings }; + } catch (e) { + gate = { errors: [e instanceof Error ? e.message : String(e)], warnings: [] }; + } + return { + file: DRAFTS_REVIEW_FILE, + exists: review.exists, + error: review.error ?? null, + rows, + alternatives, + counts, + drafted: rows.filter((r) => r.drafted).length, + gate, + }; +} diff --git a/umtool/lib/report/drafts.test.mjs b/umtool/lib/report/drafts.test.mjs @@ -0,0 +1,59 @@ +// The drafts review's umtool view (release 28, M0): the drafted rows, the +// alternatives read from every `<task>-draft.json`, "in use" once taken, and +// what a final build would say. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { draftsView, readAlternatives } from "./drafts.mjs"; +import { MANIFEST_NAME, writeDraftedField } from "./manifest.mjs"; +import { setDraftReview } from "umtool-report-to-video/drafts-review"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8")); +const P = (task) => ({ task, model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); + +test("the view: drafted rows, alternatives from the draft files, in use once taken, the final gate", async (t) => { + const dir = mkdtempSync(path.join(tmpdir(), "umtool-drafts-view-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const m = full(); + m.timeline.find((e) => e.id === "c02").onscreen = { title: "The oven" }; + m.timeline.find((e) => e.id === "c02").drafted = { onscreen: P("onscreen") }; + writeFileSync(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + writeFileSync( + path.join(dir, "onscreen-draft.json"), + JSON.stringify({ task: "onscreen", alternatives: [{ target: { entry: "c01", field: "onscreen" }, value: { title: "Not for sale?" }, provenance: P("onscreen"), reason: "operator" }] }), + ); + writeFileSync(path.join(dir, "broken-draft.json"), "{ nope"); + writeFileSync(path.join(dir, "notes.json"), JSON.stringify({ alternatives: [{ target: { field: "onscreen" }, value: 1 }] })); + const alts = await readAlternatives(dir); + assert.deepEqual(alts.map((a) => [a.id, a.address]), [["onscreen-draft.json#0", "onscreen/c01/onscreen"]], "only <task>-draft.json files, and only those that parse"); + + const v = await draftsView(dir, m); + assert.equal(v.drafted, 1); + // The rows: c02's drafted text, and the contest card's hand-written narration. + assert.deepEqual(v.rows.map((r) => [r.address, r.drafted?.model ?? null, r.state]), [ + ["onscreen/c02/onscreen", "qwen3:8b", "unreviewed"], + ["narrate/the-contest/narration", null, "unreviewed"], + ]); + assert.equal(v.alternatives[0].text, "Not for sale?"); + assert.equal(v.alternatives[0].inUse, false); + assert.equal(v.gate.errors.length, 1); + assert.match(v.gate.errors[0], /timeline c02: its on-screen text \(drafted by qwen3:8b\) is not approved/); + + // Approved: the gate passes. + await setDraftReview(dir, "onscreen/c02/onscreen", { verdict: "approved", key: v.rows[0].key, text: v.rows[0].text }); + const ok = await draftsView(dir, m); + assert.deepEqual(ok.gate.errors, []); + assert.equal(ok.counts.approved, 1); + + // Use this: the alternative is the field's value now, and in use. + await writeDraftedField(dir, { entry: "c01", field: "onscreen", value: { title: "Not for sale?" } }); + const after = JSON.parse(readFileSync(path.join(dir, MANIFEST_NAME), "utf8")); + assert.equal((await draftsView(dir, after)).alternatives[0].inUse, true); +}); diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -52,7 +52,9 @@ const script = (name) => path.join(/* turbopackIgnore: true */ PIPELINE_DIR, nam export const PRESETS = { preview: { label: "preview one clip", xfade: false, chapters: false, only: true }, fast: { label: "fast pass (hard cuts)", xfade: false, chapters: true, only: false }, - final: { label: "final", xfade: true, chapters: true, only: false }, + // `final` is the deliverable: the build is told so (`--final`), and refuses a + // drafted field the drafts review has not approved (drafts-review.mjs). + final: { label: "final", xfade: true, chapters: true, only: false, final: true }, }; /** A build's timeout, scaled to the work rather than to a global guess. */ @@ -179,6 +181,7 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = if (!p.chapters) buildArgv.push("--no-chapters"); if (skipFetch) buildArgv.push("--skip-fetch"); if (p.only && only) buildArgv.push("--only", only); + if (p.final) buildArgv.push("--final"); if (options.chaptersOnly) buildArgv.push("--chapters-only"); if (options.chromeOnly) buildArgv.push("--chrome-only"); if (options.preview) buildArgv.push("--preview", String(options.preview.at), String(options.preview.dur)); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -31,12 +31,16 @@ import { } from "umtool-report-to-video/ledger-totals"; 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 { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; import { validateNarration } from "umtool-report-to-video/narration"; import { parseMuteFrom } from "./playback.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; +import { + DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, pruneDrafted, validateDrafted, validatePublish, +} from "yt-dlp-transcript-common/lib/report/drafted.mjs"; // Its own write queue, not lib/state.ts's. // @@ -100,8 +104,18 @@ async function backupOnce(file) { await copyFile(file, bak).catch(() => {}); } +/** + * THIS WRITER IS THE OPERATOR (release 28, M0): a drafted field whose value + * this write changes loses its drafted mark -- it is the operator's now, and + * no draft task replaces it again -- and a mark whose field is gone is + * dropped (drafted.mjs `clearEditedDrafts`). Compared with the file as it is + * on disk, which every caller read inside the same lock. + */ async function writeManifestAtomic(dir, manifest) { const file = manifestFile(dir); + const before = await readFile(file, "utf8").then((t) => JSON.parse(t), () => null); + if (before) clearEditedDrafts(before, manifest); + else pruneDrafted(manifest); await backupOnce(file); const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; await writeFile(tmp, serialise(manifest), "utf8"); @@ -866,6 +880,8 @@ function structureErrors(manifest) { ...validateClaims(manifest), ...validateTeasers(manifest), ...validateNarration(manifest), + ...validateDrafted(manifest), + ...validatePublish(manifest), ]; } @@ -1083,6 +1099,99 @@ export async function updateNarration(dir, id, text, { token = null, at = null } }); } +/** + * A drafted field's whole value, written as THE OPERATOR's (release 28, M0): + * what umtool's "Use this" under an alternative (`<task>-draft.json`) runs. + * Checked as the field's own editor checks it; a structural write (snapshot + * first). Written without a drafted mark -- and the one it had, if any, goes + * (writeManifestAtomic): an alternative taken is the operator's choice. + * + * onscreen any entry's `{ title?, subtitle? }` + * lines a teaser's lines (validateTeaser) + * narration a card's narration object (validateNarration) + * render.chrome.flips the deck's flips (validateChrome) + * render.chrome.threads the deck's thread list (validateChrome); a value + * that carries `clips` ({clip id: thread id}, what a + * threads draft keeps, release 28 M9) sets each + * clip's `thread` too — removed from a clip in none + * — and the entries are checked as the build checks + * them (validateThreadEntries) + * publish.youtube `{ title, description }` (validatePublish) + * + * The cut's order ("timeline") is not taken this way: an order replaces every + * entry, and is the cut task's to apply. + * + * @param {string} dir + * @param {{ entry?: string | null, field: string, value: unknown }} draft + * @param {{ token?: string | null }} [opts] + */ +export async function writeDraftedField(dir, { entry = null, field, value }, { token = null } = {}) { + const onEntry = entry !== null && entry !== undefined && entry !== ""; + if (onEntry ? !isEntryField(field) : !DRAFTED_MANIFEST_FIELDS.includes(field)) throw new Error(`${field} is not a drafted field`); + if (field === "timeline") throw new Error("a cut's order is applied by the cut task, not taken field by field"); + if (value === undefined) throw new Error("no value to write"); + return structural(dir, "use-draft", token, (m) => { + const copy = () => JSON.parse(JSON.stringify(value)); + if (onEntry) { + const es = (m.timeline ?? []).filter((e) => e?.id === entry); + if (!es.length) throw new Error(`no timeline entry with id ${entry}`); + for (const e of es) { + if (field === "onscreen") setOnscreen(e, value); + else if (field === "lines") { + if (e.type !== "teaser") throw new Error(`${entry} is a ${e.type ?? "non-teaser"} entry, not a teaser`); + e.lines = copy(); + const errors = validateTeaser(e); + if (errors.length) throw new StructureRefused(errors); + } else if (field === "narration") { + if (e.type !== "card") throw new Error(`${entry} is not a card`); + e.narration = copy(); + } + } + return { entry, field, value: es[0][field] ?? null }; + } + if (field === "publish.youtube") { + m.publish = { ...(m.publish && typeof m.publish === "object" ? m.publish : {}), youtube: copy() }; + const errors = validatePublish(m); + if (errors.length) throw new StructureRefused(errors); + return { entry: null, field, value: m.publish.youtube }; + } + const render = m.render ?? {}; + if (!render.chrome || typeof render.chrome !== "object") { + throw new Error("flips and threads are drawn by the on-screen deck, and this manifest has none — turn the deck on first"); + } + const key = field === "render.chrome.flips" ? "flips" : "threads"; + const v = copy(); + // A threads draft's assignments ride beside its list; the field is the list. + let clips = null; + if (key === "threads" && v && typeof v === "object" && !Array.isArray(v) && "clips" in v) { + clips = v.clips; + delete v.clips; + if (!clips || typeof clips !== "object" || Array.isArray(clips) || Object.values(clips).some((t) => typeof t !== "string" || !t)) { + throw new StructureRefused(["the threads' clips must map a clip id to a thread id"]); + } + const known = new Set((m.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); + const strays = Object.keys(clips).filter((id) => !known.has(id)); + if (strays.length) throw new StructureRefused([`the threads name clips this cut does not have: ${strays.join(", ")}`]); + } + const chrome = { ...render.chrome, [key]: v }; + const { chrome: _old, ...rest } = render; + const already = new Set(validateChrome(render.chrome, rest)); + const errors = validateChrome(chrome, rest).filter((e) => !already.has(e)); + if (errors.length) throw new StructureRefused(errors); + m.render = { ...render, chrome }; + if (clips) { + for (const e of m.timeline ?? []) { + if (e?.type !== "clip") continue; + if (clips[e.id]) e.thread = clips[e.id]; + else delete e.thread; + } + const entryErrors = validateThreadEntries(m); + if (entryErrors.length) throw new StructureRefused(entryErrors); + } + return { entry: null, field, value: chrome[key] }; + }); +} + const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant"]; /** diff --git a/umtool/lib/report/narration-review.mjs b/umtool/lib/report/narration-review.mjs @@ -3,13 +3,15 @@ // card shows on screen, its review state (report-to-video's // narration-review.mjs), and whether its voice is already kept beside the // build (`out/narration/`, from a play or a build). What the page draws and -// what the route answers after each action -- one shape. +// what the route answers after each action -- one shape. Since release 28 the +// verdicts are the drafts review's (drafts.review.json, narration's rows +// `narrate/<cardId>/narration`; release 25's narration.review.json still read). // // Plain ESM: `node --test` runs it with no TypeScript. import path from "node:path"; import { stat } from "node:fs/promises"; import { estimatedNarratedCardSeconds, narrationWords } from "umtool-report-to-video/narration"; -import { NARRATION_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review"; +import { DRAFTS_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review"; import { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store"; /** @@ -43,6 +45,8 @@ export async function narrationReviewView(projectDir, manifest) { title: e.onscreen?.title ?? null, style: e.style ?? null, }, + // Who drafted these words (release 28; null: written by hand). + drafted: e.drafted?.narration && typeof e.drafted.narration === "object" ? e.drafted.narration : null, state: r.state, verdict: r.row?.verdict ?? null, note: r.row?.note ?? "", @@ -53,5 +57,5 @@ export async function narrationReviewView(projectDir, manifest) { } const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 }; for (const r of rows) counts[r.state] += 1; - return { file: NARRATION_REVIEW_FILE, exists: review.exists, error: review.error ?? null, rows, counts }; + return { file: DRAFTS_REVIEW_FILE, exists: review.exists, error: review.error ?? null, rows, counts }; } diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -675,6 +675,39 @@ holds one pair while it plays. - **Punch.** The panel is built for short clips — the line and nothing else — and near-hard cuts (`transition` 0.12); a smaller `footageScale` gives it room. +The flips and the threads can be drafted (release 28): the `flips` and +`threads` tasks (`common/lib/report/draft/tasks/`) write these fields with a +`drafted` mark, through the checks this section describes — the limits and +validators are one copy, `common/lib/report/panels.mjs`, which `flips.mjs` and +`threads.mjs` re-export. A pair's dates, `when`s and words are code's (the +recordings' dates; the quote, verbatim); a thread's outcome is its last clip's +`claim.verdict`. Each task refuses a cut that has the other panel, unless +forced over a draft of it, which it then replaces. + +### `publish.youtube` — the upload's text (`out/youtube.txt`) + +```jsonc +"publish": { "youtube": { "title": "…", // one line, ≤ 100 characters + "description": "…" } } // the summary paragraph (≤ 5000; the youtube task keeps it ≤ 900) +``` + +Every build that muxes chapters (or would have, under `--no-chapters`) writes +`out/youtube.txt` (`youtube-<variant>.txt` for another variant) when the +manifest has `publish.youtube`, composed by code (`youtube.mjs`): + +- the title, a blank line, the description; +- `Chapters`: the build's own chapter list as `m:ss Title`, on YouTube's rules — + the first at 0:00, at least three, each at least ten seconds (a shorter one is + folded into the one before it). A list that still falls short is left out, + and the build's `youtube` event says why; +- `Sources`: a moment link per cited clip, in cut order, each once — its + `citeUrl`, else the archive's page at its `cite` second (a `src` clip without + a `citeUrl` has none). + +umtool's project page shows the text with **Copy** — the built file, or before +a build the same text without the chapters. The `youtube` task drafts the title +and the summary (grounded, third person, quotes only word for word). + ### The `image` entry type A still: the receipts a clip cannot say out loud — a post, a thread, a DM, a @@ -1205,25 +1238,68 @@ so the vote lands last), the length of the sentences, one beat, and a short punch to end each paragraph. No tag: nothing in it is a sound a person would make; and nothing says the council *ignored* anyone — the minutes do not. -#### The narration review +#### The drafts review (and the narration review) + +A field a draft task wrote (release 28) says so: **`drafted`**, a provenance +`{ task, model, at, iteration?, attempt }` (`at` ISO; `attempt` the one of two +kept). An entry's field carries it on the entry, keyed by field — +`"drafted": { "onscreen": {…}, "narration": {…}, "lines": {…} }` (any entry's +on-screen text, a card's narration, a teaser's lines); a manifest field carries +it in a top-level map keyed by path — `"drafted": { "timeline": {…}, +"render.chrome.flips": {…}, "render.chrome.threads": {…}, "publish.youtube": {…} }` +(the cut's order; the flips; the threads, each clip's `thread` key included; the +YouTube title and description, `publish.youtube { title, description }`, a new +top-level key). The one copy of these rules is +`common/lib/report/drafted.mjs`; the build and the lint refuse a mark anywhere +else (`validateDrafted`) and warn of one whose field is gone. + +- **No overwrite.** A field with a value and no mark is the operator's: no + draft task replaces it, forced or not. Its draft is kept as an + **alternative** in `<task>-draft.json` beside the manifest + (`narration-draft.json` for narration), shown under the field in umtool with + **Use this**, which writes it as the operator's own edit. +- **An edit makes it the operator's.** umtool's manifest writer removes a + field's mark whenever a write changes that field (`clearEditedDrafts`). +- **The review.** `/browse/<project>/review` lists every drafted field of the + cut — who drafted it, its value, **Approve**, **Reject** (with a note) — and + every alternative; the same badge sits beside the field on the project page + (the On-screen table's title, the teaser editor) and on the narration page. + Verdicts are `<project>/drafts.review.json` (`drafts-review.mjs`): + `{ "<task>/<entry id | *>/<field>": { verdict: "approved" | "rejected" | null, + note, key, text, at } }`, the task being the field's own (`onscreen/c01/onscreen`, + `narrate/k01/narration`, `teaser/fin/lines`, `threads/*/render.chrome.threads`). + A verdict is on the value it was given on (`key`), so **an edit or a re-draft + leaves it "changed since approved"**. +- **The gate.** A drafted field not approved on its current value is a + **warning** in a preview or fast build and an **error** in a final one + (`--final`, which the driver's `final` preset passes): `--drafts-unreviewed` + builds the unapproved anyway, never a rejected one. A rejected draft is a + warning in a fast build and refuses a final one. `/browse/<project>/narration` in umtool reviews the script card by card before synthesis: each narrated card's words beside what the card shows on screen, its -engine and voice, **Approve**, **Reject** (with a note saying what is wrong), -the words edited in place (**Save words**, through the manifest writer: -snapshot, validators, the generated-manifest note), and **Play**, which asks the -editor for that one card (`narrate-via-editor.mjs --only <id>`) and plays it. - -Verdicts are `<project>/narration.review.json` (`narration-review.mjs`; the -shape of `takes/verdicts.json`): `{ "<cardId>": { verdict: "approved" | -"rejected" | null, note, key, text, at } }`. A verdict is on the words and voice -it was given on (`key` is the narration's key), so **an edit or a voice change -leaves the card "edited" — not approved** — and the page's edit clears the -verdict as well. - -- **No review file**: nothing is held — a cut narrated before reviews existed - builds as it did — and the lint WARNS that the narration has no review. -- **A review file**: every narrated card in the cut must be approved on its +engine and voice, who drafted it, **Approve**, **Reject** (with a note saying +what is wrong), the words edited in place (**Save words**, through the manifest +writer: snapshot, validators, the generated-manifest note), and **Play**, which +asks the editor for that one card (`narrate-via-editor.mjs --only <id>`) and +plays it. + +Its verdicts are the drafts review's rows `narrate/<cardId>/narration` +(`narration-review.mjs` is that view of it). Release 25's +`<project>/narration.review.json` — `{ "<cardId>": { verdict, note, key, text, +at } }` — is still READ, unchanged; the drafts file wins on a card both have, +and every new verdict goes to the drafts file. A verdict is on the words and +voice it was given on (`key` is the narration's key), so **an edit or a voice +change leaves the card "edited" — not approved** — and the page's edit clears +the verdict as well. + +A narration that carries a `drafted` mark follows the drafts gate above. One +written by hand (or before release 28) keeps release 25's rule, in every build: + +- **No narration verdict anywhere**: nothing is held — a cut narrated before + reviews existed builds as it did — and the lint WARNS that the narration has + no review. +- **Once there is one**: every narrated card in the cut must be approved on its current words. An unreviewed or edited card refuses the build (a lint error) unless `--narration-unreviewed`; a **rejected** card refuses it always — rewrite it and approve it, or take the narration out. diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -57,6 +57,12 @@ // --narration-unreviewed Build narrated cards the narration review has not // approved (unreviewed, or edited since); a rejected one // still refuses. Without a review file nothing is held. +// --final The deliverable (the driver's `final` preset passes it): +// every DRAFTED field (drafts-review.mjs) must be approved +// on its current value -- unapproved or rejected refuses. +// Without it they are warnings. +// --drafts-unreviewed With --final: build drafted fields the review has not +// approved; a rejected one still refuses. // --no-xfade Hard cuts instead of crossfades (much faster; concat copy) // --progress ndjson One JSON event per line instead of prose (for umtool) // --continue-on-error Record a failed entry and carry on, instead of aborting @@ -137,6 +143,8 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +// The upload's text (release 28 M6): composed by code, written beside the cut. +import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs"; // A card's `narration` (release 25): validated, resolved and levelled in // narration.mjs (pure); its synthesized sound is kept in out/narration/ // (narration-store.mjs) by asking the editor (narrate-via-editor.mjs). @@ -145,7 +153,8 @@ import { cardNarrationSeconds, resolveNarrationRender, validateNarration, } from "./narration.mjs"; import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs"; -import { readNarrationReview } from "./narration-review.mjs"; +import { readDraftsReview } from "./drafts-review.mjs"; +import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; // The lint a build runs before it renders, and the prune after its final mux. import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs"; import { pruneChromeFrames } from "./prune-frames.mjs"; @@ -401,7 +410,7 @@ export function variantPaths(outRoot, slug, variant) { // printed -- this is a formatting switch, not new instrumentation. // // Events: start, card, clip, fetch, snap, segment, entry-failed, concat, -// chapters, chrome, narrate, note, done. +// chapters, youtube, chrome, narrate, note, done. const HUMAN = { start: (e) => `${e.title} — ${e.entries} entr(ies)`, card: (e) => `card ${e.id}`, @@ -425,6 +434,7 @@ const HUMAN = { "entry-failed": (e) => ` ** ${e.id} failed: ${e.message}`, concat: (e) => `${e.mode === "xfade" ? "crossfading" : "hard-cutting"} ${e.n} segments…`, chapters: (e) => `chapters: ${e.n} marker(s) -> ${e.file}`, + youtube: (e) => `youtube: ${e.file}${e.chapters ? ` (${e.chapters} chapter(s))` : ""}${e.note ? ` — ${e.note}` : ""}`, // The deck's steps. `phase` is schedule | compose | render | cached | overlay. chrome: (e) => `chrome ${e.phase}` + @@ -3940,23 +3950,29 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] }); } +// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`, +// seconds) -- the list out/youtube.txt's Chapters are made from -- or null +// when the cut is one segment and gets none. async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null, { disclosure = null } = {}) { - if (segments.length < 2) return; + if (segments.length < 2) return null; // The cut's own offsets: under the deck a held clip is longer in the cut // than its file, and every chapter after it starts that much later. const { starts, total } = await cutOffsets(segments, D, fps, joins); const lines = [";FFMETADATA1", ""]; + const chapters = []; for (let i = 0; i < entries.length; i += 1) { // Land just PAST the crossfade, so the marker opens on the incoming clip // rather than on the outgoing one mid-dissolve. const start = i === 0 ? 0 : starts[i] + D; const end = i === entries.length - 1 ? total : starts[i + 1] + D; + const title = await chapterTitle(entries[i], i, provenance, { deck }); + chapters.push({ start, end, title }); lines.push( "[CHAPTER]", "TIMEBASE=1/1000", `START=${Math.round(start * 1000)}`, `END=${Math.round(end * 1000)}`, - `title=${ffmetaEscape(await chapterTitle(entries[i], i, provenance, { deck }))}`, + `title=${ffmetaEscape(title)}`, "", ); } @@ -3977,6 +3993,28 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, ); await rename(tmp, finalPath); EMIT("chapters", { n: entries.length, file: path.basename(metaPath) }); + return { chapters, total }; +} + +/** + * `out/youtube.txt` (youtube.mjs): the cut's `publish.youtube` title and + * description, the chapters the build just muxed (YouTube's rules, else left + * out with a note) and a moment link per cited clip. Written by every build + * that muxes chapters -- or would have, under --no-chapters -- when the + * manifest has `publish.youtube`; nothing otherwise. + * + * @param {{ chapters: Array<{ start: number, end: number, title: string }>, total: number } | null} muxed + * @param {string | null} [why] why there are no chapters (`--no-chapters`) + */ +async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why = null) { + const youtube = manifest.publish?.youtube; + if (!youtube?.title) return null; + const { chapters, note } = muxed ? youtubeChapters(muxed.chapters, muxed.total) : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` }; + const text = composeYoutubeText({ youtube, chapters, sources: youtubeSources(entries, manifest.provenance) }); + const file = path.join(outRoot, youtubeTextName(variant)); + await writeFile(file, text, "utf8"); + EMIT("youtube", { file: path.basename(file), chapters: chapters?.length ?? 0, note }); + return file; } /** @@ -4118,7 +4156,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly { const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), - ...validateFlipEntries(whole), ...validateNarration(whole), + ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } @@ -4134,14 +4172,17 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // scan at 720p, a teaser line over house style. The validators above have // spoken already; `--only` lints its one entry. Enforced below, once the runs // that render nothing (a bench fetch, the thumbnail) are out of the way. - // The narration review (narration-review.mjs) is part of the lint: an - // un-approved narrated card refuses the build, unless --narration-unreviewed; - // a narrated cut with no review file at all is a warning. + // The drafts review (drafts-review.mjs) is part of the lint: a drafted + // field not approved refuses a --final build (unless --drafts-unreviewed) + // and is a warning in any other; a hand-written narration keeps release + // 25's rule (narration-review.mjs) -- un-approved refuses once the cut's + // narration has a review, unless --narration-unreviewed. const lint = opts.noLint ? { errors: [], warnings: [] } : lintManifest(manifest, { manifestDir, whole, only: only ?? null, validators: false, - narrationReview: await readNarrationReview(manifestDir), narrationUnreviewed: opts.narrationUnreviewed === true, + draftsReview: await readDraftsReview(manifestDir), narrationUnreviewed: opts.narrationUnreviewed === true, + final: opts.final === true, draftsUnreviewed: opts.draftsUnreviewed === true, }); // Where each post's QR goes: its page on the archive (`posts.links` @@ -4442,7 +4483,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // Under the deck the cut's offsets include the holds: measured, not written. const joins = deck ? segmentJoins(await measureChromeSchedule({ manifest, entries, segments: segs, D })) : null; - await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed); return { out: finalPath, failures: [] }; } @@ -4476,9 +4518,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly await assertConcatLength(out, railPlan.total, render.fps, "rail build"); // applyRail re-encodes, so the chapters muxed onto the previous final are // gone. Put them back, or --rail-only quietly ships a chapterless cut. - if (!opts.noChapters) { - await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); - } + const muxed = opts.noChapters + ? null + : await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); } EMIT("done", { out, failures: [] }); return { out, failures: [] }; @@ -4584,7 +4627,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build"); // The overlay re-encodes, so the chapters on the previous final are gone. - if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = opts.noChapters + ? null + : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -4707,7 +4753,10 @@ 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"); - if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = opts.noChapters + ? null + : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. @@ -4854,6 +4903,7 @@ async function main() { " [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" + " [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" + " [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" + + " [--final] [--drafts-unreviewed] (the deliverable: drafted fields must be approved / build the unapproved anyway)\n" + " [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" + " [--thumbnail] (render.brand only: out/<slug>.thumbnail.png and stop)", ); @@ -4890,6 +4940,8 @@ async function main() { keepFrames: argv.includes("--keep-frames"), noLint: argv.includes("--no-lint"), narrationUnreviewed: argv.includes("--narration-unreviewed"), + final: argv.includes("--final"), + draftsUnreviewed: argv.includes("--drafts-unreviewed"), }; try { Object.assign(opts, chromeFlags(argv)); @@ -4909,7 +4961,10 @@ async function main() { // The lint alone: every warning and error, exit 1 on an error. if (argv.includes("--lint")) { - const lint = await lintManifestFile(manifestPath, { variant: opts.variant, only: flag("--only") ?? null, narrationUnreviewed: opts.narrationUnreviewed }); + const lint = await lintManifestFile(manifestPath, { + variant: opts.variant, only: flag("--only") ?? null, narrationUnreviewed: opts.narrationUnreviewed, + final: opts.final, draftsUnreviewed: opts.draftsUnreviewed, + }); for (const w of lint.warnings) EMIT("note", { message: `lint: ${w}` }); for (const e of lint.errors) EMIT("note", { message: `lint ERROR: ${e}` }); EMIT("note", { message: `lint: ${lint.errors.length} error(s), ${lint.warnings.length} warning(s)` }); diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs @@ -0,0 +1,377 @@ +// THE DRAFTS REVIEW — one file of verdicts on every drafted field of a cut, +// and the gate a build applies with it (release 28, M0; release 25's +// narration review, generalised). +// +// <project>/drafts.review.json beside video.manifest.json +// { "<task>/<entry id | *>/<field>": { "verdict": "approved" | "rejected" | null, +// "note": string, "key": "<the field's key when judged>", "text": "<what was judged>", "at": ISO } } +// +// The address is drafted.mjs's `reviewAddress`: the field's own task (narrate, +// onscreen, teaser, cut, flips, threads, youtube), the entry it is on (`*` for a +// manifest field), the field -- `narrate/<cardId>/narration` for a card's +// narration. The shape and its rules are the narration review's: every row +// carries every key, a row with no verdict and no note is REMOVED, its own +// write queue, tmp + rename, a file that does not parse is an ERROR (never +// overwritten, never read as empty), and a rejection needs its note. +// +// A verdict is about THE VALUE IT WAS GIVEN ON: the row keeps its key +// (`draftKey`: a card's narration by narration.mjs `narrationKey` -- the words +// and the voice; any other field by drafted.mjs `fieldKey`), so an edit or a +// re-draft leaves it "edited", not approved, without anything having to +// remember to clear it. +// +// RELEASE 25's FILES READ UNCHANGED. `narration.review.json` ({ "<cardId>": +// row }) is read beside the drafts file, its rows as `narrate/<cardId>/narration`; +// the drafts file wins on an address both have. Every write goes to the drafts +// file -- a cleared row whose address the old file still approves is kept in +// the drafts file as an empty verdict, so the old approval does not show +// through. +// +// THE GATE (`draftsReviewProblems`), per field the cut carries: +// - a DRAFTED field (it carries a drafted mark) must be approved on its +// current value. Unapproved (unreviewed, or edited since): a WARNING in a +// preview or fast build, an ERROR in a `final` one unless +// `--drafts-unreviewed` (`--narration-unreviewed` for a narration). Rejected: +// an ERROR in `final` (no flag lets it through), a warning otherwise; +// - a NARRATION with no drafted mark (written by hand, or before release 28) +// keeps release 25's rule in every build: until the cut's narration has a +// review (a narration row in either file) it is a warning; once it has one, +// every narrated card must be approved -- unreviewed or edited refuses unless +// `--narration-unreviewed` (or `--drafts-unreviewed`), rejected refuses always. +// +// Pure but for the files' read and write. +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { draftedFields, fieldKey, isCodeDraft, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { narrationsOf } from "./narration.mjs"; + +export const DRAFTS_REVIEW_FILE = "drafts.review.json"; +/** Release 25's file, read unchanged; never written any more. */ +export const NARRATION_REVIEW_FILE = "narration.review.json"; +export const REVIEW_VERDICTS = Object.freeze(["approved", "rejected"]); +export const REVIEW_NOTE_LIMIT = 2000; + +/** `<manifest's directory>/drafts.review.json`. */ +export const draftsReviewFileOf = (manifestDir) => path.join(manifestDir, DRAFTS_REVIEW_FILE); + +/** The narration review address of a card. */ +export const narrationAddress = (cardId) => reviewAddress({ entry: cardId, field: "narration" }); + +const str = (v) => (typeof v === "string" ? v : ""); +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** One row, cleaned to the contract's shape. */ +export function cleanRow(row) { + return { + verdict: REVIEW_VERDICTS.includes(row?.verdict) ? row.verdict : null, + note: str(row?.note), + key: str(row?.key), + text: str(row?.text), + at: str(row?.at), + }; +} + +/** A drafts file's rows: those whose address is an address, cleaned. */ +export function cleanDraftsReview(raw) { + const out = {}; + if (!isObj(raw)) return out; + for (const [address, row] of Object.entries(raw)) { + if (!parseReviewAddress(address) || !isObj(row)) continue; + out[address] = cleanRow(row); + } + return out; +} + +const isCardId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200; + +/** Release 25's file: rows by card id, cleaned. */ +export function cleanNarrationRows(raw) { + const out = {}; + if (!isObj(raw)) return out; + for (const [id, row] of Object.entries(raw)) { + if (!isCardId(id) || !isObj(row)) continue; + out[id] = cleanRow(row); + } + return out; +} + +async function readJson(file, name) { + let text; + try { + text = await readFile(file, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return { exists: false, value: null }; + return { exists: true, value: null, error: `${name} cannot be read: ${err?.message ?? err}` }; + } + try { + return { exists: true, value: JSON.parse(text) }; + } catch { + return { exists: true, value: null, error: `${name} does not parse; fix or remove it` }; + } +} + +/** + * The review of a cut: both files merged by address. + * exists either file is there + * rows address → row (the drafts file wins) + * files which of the two are there + * narration the cut's narration has a review (release 25's rule) + * error a file that does not parse -- a build must not read that as + * "nothing approved", nor a writer overwrite it + * + * @param {string} manifestDir + */ +export async function readDraftsReview(manifestDir) { + const [drafts, legacy] = await Promise.all([ + readJson(draftsReviewFileOf(manifestDir), DRAFTS_REVIEW_FILE), + readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE), + ]); + const files = { drafts: drafts.exists, narration: legacy.exists }; + const error = drafts.error ?? legacy.error; + if (error) return { exists: true, rows: {}, files, narration: true, error }; + const rows = {}; + for (const [id, row] of Object.entries(cleanNarrationRows(legacy.value))) rows[narrationAddress(id)] = row; + Object.assign(rows, cleanDraftsReview(drafts.value)); + return reviewOf(rows, files); +} + +function reviewOf(rows, files) { + const narration = files.narration || Object.keys(rows).some((a) => parseReviewAddress(a)?.field === "narration"); + return { exists: files.drafts || files.narration, rows, files, narration }; +} + +/** + * A release 25 narration review (`{ exists, rows: { <cardId>: row }, error? }`, + * narration-review.mjs `readNarrationReview`) as a drafts review. + */ +export function draftsReviewFromNarration(review) { + if (!review) return null; + if (review.error) return { exists: true, rows: {}, files: { drafts: false, narration: true }, narration: true, error: review.error }; + const rows = {}; + for (const [id, row] of Object.entries(review.rows ?? {})) rows[narrationAddress(id)] = cleanRow(row); + return { ...reviewOf(rows, { drafts: false, narration: !!review.exists }), exists: !!review.exists }; +} + +/** + * The key a verdict on this field is given on: a card's narration by its + * words and voice (narrationKey), anything else by its value (fieldKey). + * + * @param {any} manifest + * @param {{ entry?: string | null, field: string }} target + */ +export function draftKey(manifest, target) { + if (target.field === "narration" && target.entry) { + return narrationsOf(manifest).find((n) => n.id === target.entry)?.key ?? fieldKey(manifest, target); + } + return fieldKey(manifest, target); +} + +/** A row's state on a field's current key: approved, rejected, edited (judged on another value) or unreviewed. */ +export function draftReviewState(key, row) { + if (!row?.verdict) return "unreviewed"; + if (row.key !== key) return "edited"; + return row.verdict; +} + +/** The words a verdict is given on: a short text of the field's value. */ +export function judgedText(field, value) { + if (value === undefined || value === null) return ""; + if (field === "narration") return str(value?.text).trim(); + if (field === "onscreen") return [value?.title, value?.subtitle].filter((s) => typeof s === "string" && s).join(" — "); + if (field === "lines" && Array.isArray(value)) return value.map((l) => (typeof l === "string" ? l : str(l?.text))).join(" / "); + if (field === "publish.youtube") return str(value?.title); + if (field === "timeline" && Array.isArray(value)) return value.map((e) => e?.id).join(", "); + return JSON.stringify(value).slice(0, 500); +} + +/** How a field reads in a sentence. */ +export const FIELD_LABELS = Object.freeze({ + onscreen: "on-screen text", + narration: "narration", + lines: "teaser lines", + timeline: "cut (its order)", + "render.chrome.flips": "flips", + "render.chrome.threads": "threads", + "publish.youtube": "YouTube title and description", +}); + +/** + * Every field the review covers, in timeline order then the manifest's: each + * drafted field (drafted.mjs `draftedFields`) and each narrated card (drafted + * or not, as the narration page lists them). Each row: + * { address, entry, field, provenance (null: not drafted), key, text, row, state } + * + * @param {any} manifest + * @param {{ rows?: Record<string, any> } | null} review + */ +export function draftsReviewRows(manifest, review) { + const out = []; + const seen = new Set(); + const push = (entry, field, provenance, value) => { + const address = reviewAddress({ entry, field }); + if (seen.has(address)) return; + seen.add(address); + const key = draftKey(manifest, { entry, field }); + const row = review?.rows?.[address] ?? null; + out.push({ address, entry, field, provenance, key, text: judgedText(field, value), row, state: draftReviewState(key, row) }); + }; + // A field a CODE path made (the converter's timeline, release 28 M1) needs + // no approval: no row, so no badge and no gate. + const drafted = draftedFields(manifest).filter((d) => !isCodeDraft(d.provenance)); + const byAddress = new Map(drafted.map((d) => [reviewAddress(d), d])); + // Narration rows in timeline order, interleaved with the other entry fields. + const narrated = new Map(narrationsOf(manifest).map((n) => [n.id, n])); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + for (const field of ["onscreen", "narration", "lines"]) { + const d = byAddress.get(reviewAddress({ entry: e?.id, field })); + if (d) push(d.entry, field, d.provenance, d.value); + else if (field === "narration" && narrated.has(e?.id)) push(e.id, "narration", null, e.narration); + } + } + for (const d of drafted) if (d.entry === null) push(null, d.field, d.provenance, d.value); + return out; +} + +const whereOf = (r) => (r.entry ? `timeline ${r.entry}` : r.field); +const LIST_AT_MOST = 8; + +/** + * What the review says about building this cut: `errors` refuse it, `notes` + * and `warnings` are said. + * + * @param {any} manifest the cut + * @param {{ exists: boolean, rows: Record<string, any>, narration?: boolean, error?: string } | null} review + * null: not read (a run that says nothing about reviews) + * @param {{ final?: boolean, allowUnreviewed?: boolean, allowNarrationUnreviewed?: boolean, only?: string | null }} [opts] + */ +export function draftsReviewProblems(manifest, review, { final = false, allowUnreviewed = false, allowNarrationUnreviewed = false, only = null } = {}) { + const errors = []; + const notes = []; + const warnings = []; + if (!review) return { errors, notes, warnings }; + const rows = draftsReviewRows(manifest, review).filter((r) => !only || r.entry === only); + if (!rows.length) return { errors, notes, warnings }; + if (review.error) return { errors: [review.error], notes, warnings }; + + // Release 25's rule, for a narration nobody drafted. + const hand = rows.filter((r) => r.field === "narration" && !r.provenance); + if (hand.length && !review.narration) { + warnings.push( + `the narration (${hand.length} card${hand.length === 1 ? "" : "s"}) has no review — ${DRAFTS_REVIEW_FILE} has no narration verdicts; ` + + "review it card by card on umtool's narration page before it is published", + ); + } else if (hand.length) { + for (const r of hand) { + if (r.state === "approved") continue; + if (r.state === "rejected") { + errors.push( + `timeline ${r.entry}: its narration was rejected${r.row?.note ? ` ("${r.row.note}")` : ""} — rewrite it and approve it, or take the narration out`, + ); + continue; + } + const why = r.state === "edited" ? "edited since it was approved" : "not reviewed"; + if (allowNarrationUnreviewed || allowUnreviewed) { + notes.push(`timeline ${r.entry}: its narration is ${why} — built anyway (${allowNarrationUnreviewed ? "--narration-unreviewed" : "--drafts-unreviewed"})`); + } else errors.push(`timeline ${r.entry}: its narration is ${why} — approve it on umtool's narration page, or build with --narration-unreviewed`); + } + } + + // The drafted fields. + const pending = []; + for (const r of rows.filter((x) => x.provenance)) { + if (r.state === "approved") continue; + const what = `${whereOf(r)}: its ${FIELD_LABELS[r.field] ?? r.field} (drafted by ${r.provenance.model})`; + if (r.state === "rejected") { + const said = `${what} was rejected${r.row?.note ? ` ("${r.row.note}")` : ""}`; + if (final) errors.push(`${said} — redraft or rewrite it and approve it; a final build takes no rejected draft`); + else warnings.push(`${said} — a final build refuses it`); + continue; + } + const why = r.state === "edited" ? "changed since it was approved" : "not approved"; + if (!final) { + pending.push(r); + continue; + } + const flag = allowUnreviewed ? "--drafts-unreviewed" : allowNarrationUnreviewed && r.field === "narration" ? "--narration-unreviewed" : null; + if (flag) notes.push(`${what} is ${why} — built anyway (${flag})`); + else errors.push(`${what} is ${why} — approve it on umtool's review page, or build with --drafts-unreviewed`); + } + if (pending.length) { + const names = pending.slice(0, LIST_AT_MOST).map((r) => r.address); + warnings.push( + `${pending.length} drafted field${pending.length === 1 ? " is" : "s are"} not approved (${names.join(", ")}` + + `${pending.length > LIST_AT_MOST ? `, and ${pending.length - LIST_AT_MOST} more` : ""}) — a final build refuses ${pending.length === 1 ? "it" : "them"} until approved`, + ); + } + return { errors, notes, warnings }; +} + +/** @type {Promise<unknown>} */ +let queue = Promise.resolve(); +function withReviewLock(fn) { + const run = queue.then(fn, fn); + queue = run.then( + () => undefined, + () => undefined, + ); + return run; +} + +/** + * Set one field's review. `patch.verdict` "approved" | "rejected" | null (null + * clears it); `note` replaces the note; `key` and `text` are the value the + * verdict is about (a key is required with a verdict). A rejection needs its + * note. Returns the row as stored (null when removed) and every row of the + * merged review. Writes the drafts file only. + * + * @param {string} manifestDir + * @param {string} address + * @param {{ verdict?: string | null, note?: string, key?: string, text?: string }} patch + */ +export async function setDraftReview(manifestDir, address, patch) { + if (!parseReviewAddress(address)) throw new Error(`${JSON.stringify(address)} is not a review address (<task>/<entry or *>/<field>)`); + if (patch.verdict !== undefined && patch.verdict !== null && !REVIEW_VERDICTS.includes(patch.verdict)) { + throw new Error(`verdict must be one of ${REVIEW_VERDICTS.join(", ")} or null`); + } + if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string"); + if (patch.verdict && !(typeof patch.key === "string" && patch.key && typeof patch.text === "string")) { + throw new Error("a verdict is given on words: key and text are required"); + } + const file = draftsReviewFileOf(manifestDir); + return withReviewLock(async () => { + const cur = await readDraftsReview(manifestDir); + if (cur.error) throw new Error(cur.error); + const own = await readJson(file, DRAFTS_REVIEW_FILE); + if (own.error) throw new Error(own.error); + const map = cleanDraftsReview(own.value); + const prev = cur.rows[address] ?? { verdict: null, note: "", key: "", text: "", at: "" }; + const row = { + verdict: patch.verdict === undefined ? prev.verdict : patch.verdict, + note: patch.note === undefined ? prev.note : patch.note.slice(0, REVIEW_NOTE_LIMIT).trim(), + key: patch.verdict ? patch.key : patch.verdict === null ? "" : prev.key, + text: patch.verdict ? patch.text : patch.verdict === null ? "" : prev.text, + at: new Date().toISOString(), + }; + if (row.verdict === "rejected" && !row.note) { + throw new Error("a rejection needs its note: say what is wrong with the words"); + } + // An empty row goes -- unless release 25's file still has this address, + // whose row would show through: then the empty row stays, and wins. + const target = parseReviewAddress(address); + let legacyHas = false; + if (target.field === "narration" && target.entry && cur.files.narration) { + const legacy = await readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE); + legacyHas = isObj(legacy.value) && isObj(legacy.value[target.entry]); + } + if (row.verdict === null && !row.note && !legacyHas) delete map[address]; + else map[address] = row; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); + await rename(tmp, file); + const stored = row.verdict === null && !row.note ? null : row; + const rows = { ...cur.rows, ...map }; + if (!map[address]) delete rows[address]; + return { entry: stored, rows }; + }); +} diff --git a/umtool/report-to-video/drafts-review.test.mjs b/umtool/report-to-video/drafts-review.test.mjs @@ -0,0 +1,227 @@ +// drafts-review.mjs (release 28, M0): one review file for every drafted +// field, release 25's narration file read unchanged, the edit-unapproves rule, +// and the gate -- a warning in a preview or fast build, refused in a final one +// -- over the S0 kit's `full` manifest. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { buildVideo, setProgressMode } from "./build-video.mjs"; +import { + DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, draftKey, draftsReviewProblems, draftsReviewRows, readDraftsReview, setDraftReview, +} from "./drafts-review.mjs"; +import { lintManifest, lintManifestFile } from "./lint.mjs"; +import { narrationsOf } from "./narration.mjs"; +import { readNarrationReview, setNarrationReview } from "./narration-review.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const full = () => JSON.parse(readFileSync(path.join(HERE, "../../common/testing/draft/manifests/full.video.manifest.json"), "utf8")); +const P = (task, model = "qwen3:8b") => ({ task, model, at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); +const entry = (m, id) => m.timeline.find((e) => e.id === id); +const tmp = (t, name) => { + const dir = mkdtempSync(path.join(tmpdir(), `rtv-drafts-${name}-`)); + t.after(() => rmSync(dir, { recursive: true, force: true })); + return dir; +}; + +// The full fixture with drafted fields: c01's on-screen text and the teaser's +// lines and the threads drafted; the contest card's narration drafted. +function drafted() { + const m = full(); + entry(m, "c01").drafted = { onscreen: P("onscreen") }; + entry(m, "fin").drafted = { lines: P("teaser", "claude-sonnet-5-5") }; + entry(m, "the-contest").drafted = { narration: P("narrate") }; + m.drafted = { "render.chrome.threads": P("threads") }; + return m; +} +const review = (rows = {}, o = {}) => ({ exists: true, rows, files: { drafts: true, narration: false }, narration: false, ...o }); +const approve = (m, entryId, field) => ({ verdict: "approved", key: draftKey(m, { entry: entryId, field }), text: "", note: "", at: "" }); + +test("the rows: every drafted field and every narrated card, in timeline order, with its address and key", () => { + const m = drafted(); + const rows = draftsReviewRows(m, null); + assert.deepEqual(rows.map((r) => [r.address, r.provenance?.task ?? null, r.state]), [ + ["onscreen/c01/onscreen", "onscreen", "unreviewed"], + ["narrate/the-contest/narration", "narrate", "unreviewed"], + ["teaser/fin/lines", "teaser", "unreviewed"], + ["threads/*/render.chrome.threads", "threads", "unreviewed"], + ]); + assert.equal(rows[0].text, "Not for sale — The baker on selling to a chain"); + // A narration's key is narration.mjs's: the words and the voice. + assert.equal(rows[1].key, narrationsOf(m).find((n) => n.id === "the-contest").key); +}); + +test("the gate: preview and fast warn in one line; final refuses each; --drafts-unreviewed lets the unapproved through", () => { + const m = drafted(); + const none = review(); + const fast = draftsReviewProblems(m, none); + assert.deepEqual(fast.errors, []); + assert.equal(fast.warnings.length, 1); + assert.match(fast.warnings[0], /^4 drafted fields are not approved \(onscreen\/c01\/onscreen, narrate\/the-contest\/narration, teaser\/fin\/lines, threads\/\*\/render\.chrome\.threads\) — a final build refuses them until approved$/); + const fin = draftsReviewProblems(m, none, { final: true }); + assert.equal(fin.errors.length, 4, fin.errors.join("\n")); + assert.match(fin.errors[0], /^timeline c01: its on-screen text \(drafted by qwen3:8b\) is not approved — approve it on umtool's review page, or build with --drafts-unreviewed$/); + assert.match(fin.errors[2], /^timeline fin: its teaser lines \(drafted by claude-sonnet-5-5\) is not approved/); + assert.match(fin.errors[3], /^render\.chrome\.threads: its threads \(drafted by qwen3:8b\) is not approved/); + const through = draftsReviewProblems(m, none, { final: true, allowUnreviewed: true }); + assert.deepEqual(through.errors, []); + assert.equal(through.notes.length, 4); + assert.match(through.notes[0], /built anyway \(--drafts-unreviewed\)/); + // --narration-unreviewed is the alias for the narration rows only. + const narr = draftsReviewProblems(m, none, { final: true, allowNarrationUnreviewed: true }); + assert.equal(narr.errors.length, 3); + assert.match(narr.notes[0], /timeline the-contest: its narration \(drafted by qwen3:8b\) is not approved — built anyway \(--narration-unreviewed\)/); + // `only` keeps one entry's rows. + assert.equal(draftsReviewProblems(m, none, { final: true, only: "c01" }).errors.length, 1); + // Not read: nothing said. + assert.deepEqual(draftsReviewProblems(m, null, { final: true }), { errors: [], notes: [], warnings: [] }); +}); + +test("the gate: approved passes; an edit or re-draft leaves it unapproved; a rejected one refuses a final build, flag or not", () => { + const m = drafted(); + const rows = { + "onscreen/c01/onscreen": approve(m, "c01", "onscreen"), + "narrate/the-contest/narration": approve(m, "the-contest", "narration"), + "teaser/fin/lines": { ...approve(m, "fin", "lines"), verdict: "rejected", note: "too long" }, + "threads/*/render.chrome.threads": approve(m, null, "render.chrome.threads"), + }; + const fin = draftsReviewProblems(m, review(rows), { final: true, allowUnreviewed: true }); + assert.deepEqual(fin.errors, [ + 'timeline fin: its teaser lines (drafted by claude-sonnet-5-5) was rejected ("too long") — redraft or rewrite it and approve it; a final build takes no rejected draft', + ]); + const fast = draftsReviewProblems(m, review(rows)); + assert.deepEqual(fast.errors, []); + assert.match(fast.warnings[0], /timeline fin: its teaser lines .* was rejected \("too long"\) — a final build refuses it/); + // A re-draft (or any change of value) of an approved field: edited, not approved. + entry(m, "c01").onscreen.title = "Redrafted"; + entry(m, "c02").thread = "contest"; + const after = draftsReviewRows(m, review(rows)); + assert.equal(after.find((r) => r.address === "onscreen/c01/onscreen").state, "edited"); + assert.equal(after.find((r) => r.address === "threads/*/render.chrome.threads").state, "edited"); + assert.equal(after.find((r) => r.address === "narrate/the-contest/narration").state, "approved"); + const again = draftsReviewProblems(m, review(rows), { final: true }); + assert.match(again.errors.find((e) => e.startsWith("timeline c01")), /is changed since it was approved/); + // Another voice un-approves a narration, as in release 25. + m.timeline.find((e) => e.id === "the-contest").narration.voice = "am_adam"; + assert.equal(draftsReviewRows(m, review(rows)).find((r) => r.field === "narration").state, "edited"); +}); + +test("a hand-written narration keeps release 25's rule in every build: no review, a warning even in final", () => { + const m = full(); // the contest card's narration has no drafted mark + const fin = draftsReviewProblems(m, review({}, { exists: false, files: { drafts: false, narration: false } }), { final: true }); + assert.deepEqual(fin.errors, []); + assert.match(fin.warnings[0], /the narration \(1 card\) has no review/); + // Once the cut's narration has a review, it must be approved -- in any build. + const started = review({ "narrate/other/narration": { verdict: null, note: "x", key: "", text: "", at: "" } }, { narration: true }); + assert.match(draftsReviewProblems(m, started).errors[0], /timeline the-contest: its narration is not reviewed — approve it on umtool's narration page, or build with --narration-unreviewed/); + assert.deepEqual(draftsReviewProblems(m, started, { allowUnreviewed: true }).errors, []); +}); + +test("the files: release 25's narration.review.json reads unchanged; the drafts file wins; writes go to the drafts file", async (t) => { + const dir = tmp(t, "files"); + const m = drafted(); + const [n] = narrationsOf(m); + assert.deepEqual(await readDraftsReview(dir), { exists: false, rows: {}, files: { drafts: false, narration: false }, narration: false }); + // A release 25 file, as it was written. + writeFileSync(path.join(dir, NARRATION_REVIEW_FILE), JSON.stringify({ "the-contest": { verdict: "approved", note: "", key: n.key, text: n.text, at: "2026-10-10T00:00:00.000Z" } })); + const r = await readDraftsReview(dir); + assert.equal(r.rows["narrate/the-contest/narration"].verdict, "approved"); + assert.equal(r.narration, true); + assert.equal(draftsReviewRows(m, r).find((x) => x.field === "narration").state, "approved"); + assert.deepEqual((await readNarrationReview(dir)).rows["the-contest"].verdict, "approved"); + // A verdict on another field writes the drafts file; the old file is untouched. + const before = readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"); + await setDraftReview(dir, "onscreen/c01/onscreen", { verdict: "approved", key: draftKey(m, { entry: "c01", field: "onscreen" }), text: "t" }); + assert.equal(readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"), before); + assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))), ["onscreen/c01/onscreen"]); + // Clearing the old file's approval: the drafts file keeps an empty row, which wins. + await setNarrationReview(dir, "the-contest", { verdict: null }); + const cleared = await readDraftsReview(dir); + assert.equal(cleared.rows["narrate/the-contest/narration"].verdict, null); + assert.equal(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))["narrate/the-contest/narration"].verdict, null); + // The drafts file wins on an address both have. + await setNarrationReview(dir, "the-contest", { verdict: "rejected", key: n.key, text: n.text, note: "no" }); + assert.equal((await readDraftsReview(dir)).rows["narrate/the-contest/narration"].verdict, "rejected"); + // Refusals. + await assert.rejects(setDraftReview(dir, "nope", { verdict: null }), /not a review address/); + await assert.rejects(setDraftReview(dir, "onscreen/c02/onscreen", { verdict: "rejected", key: "k", text: "t" }), /a rejection needs its note/); + // A drafts file that does not parse is an error, never overwritten. + writeFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "{ nope"); + assert.match((await readDraftsReview(dir)).error, /drafts\.review\.json does not parse/); + await assert.rejects(setDraftReview(dir, "onscreen/c01/onscreen", { verdict: null }), /does not parse/); + assert.equal(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"), "{ nope"); +}); + +test("the lint: severities per mode, an orphan mark warned, a misplaced one refused", async (t) => { + const dir = tmp(t, "lint"); + const m = drafted(); + const file = path.join(dir, "video.manifest.json"); + writeFileSync(file, JSON.stringify(m)); + const fast = await lintManifestFile(file); + assert.deepEqual(fast.errors, []); + assert.ok(fast.warnings.some((w) => /^4 drafted fields are not approved/.test(w)), fast.warnings.join("\n")); + const fin = await lintManifestFile(file, { final: true }); + assert.equal(fin.errors.filter((e) => /is not approved — approve it on umtool's review page/.test(e)).length, 4, fin.errors.join("\n")); + assert.deepEqual((await lintManifestFile(file, { final: true, draftsUnreviewed: true })).errors, []); + // Approve them all through the file: the final lint is clean. + for (const r of draftsReviewRows(m, null)) await setDraftReview(dir, r.address, { verdict: "approved", key: r.key, text: r.text }); + assert.deepEqual((await lintManifestFile(file, { final: true })).errors, []); + // An orphan is a warning; a mark where no field may be drafted is an error. + const o = drafted(); + entry(o, "c02").drafted = { onscreen: P("onscreen") }; + entry(o, "c03").drafted = { narration: P("narrate") }; + const lint = lintManifest(o, {}); + assert.ok(lint.warnings.some((w) => /timeline\[3\] \(c02\)\.drafted\.onscreen: its field is gone — the drafted mark is an orphan/.test(w)), lint.warnings.join("\n")); + assert.ok(lint.errors.some((e) => /\(c03\)\.drafted\.narration: a clip has no narration to draft/.test(e)), lint.errors.join("\n")); + // publish: a YouTube text is accepted, anything else refused. + assert.deepEqual(lintManifest({ ...full(), publish: { youtube: { title: "T", description: "D" } } }, {}).errors, []); + assert.ok(lintManifest({ ...full(), publish: { tiktok: {} } }, {}).errors.some((e) => /publish\.tiktok is not a publish key/.test(e))); +}); + +async function quietly(fn) { + const events = []; + setProgressMode((e) => events.push(e)); + try { + return { result: await fn().catch((err) => ({ err })), events }; + } finally { + setProgressMode("human"); + } +} + +test("the build: --final refuses an unapproved draft before anything is fetched; approved, it goes on", async (t) => { + const dir = tmp(t, "build"); + const manifestPath = path.join(dir, "video.manifest.json"); + const m = { + slug: "rv", title: "RV", render: { transition: 0, audioRate: 48000, audioChannels: 2, fps: 10 }, + timeline: [{ type: "card", id: "k1", heading: "K", seconds: 1, onscreen: { title: "Drafted" }, drafted: { onscreen: P("onscreen") } }], + }; + writeFileSync(manifestPath, JSON.stringify(m)); + const held = await quietly(() => buildVideo({ manifestPath, opts: { final: true, skipFetch: true } })); + assert.match(String(held.result?.err?.message), /lint: timeline k1: its on-screen text \(drafted by qwen3:8b\) is not approved/); + // Not final: the lint says it, and nothing is refused for it. + const fast = await quietly(() => buildVideo({ manifestPath, opts: { skipFetch: true, out: dir } })); + assert.ok(fast.events.some((e) => e.ev === "note" && /lint: 1 drafted field is not approved \(onscreen\/k1\/onscreen\)/.test(e.message)), JSON.stringify(fast.events.slice(0, 5))); + assert.doesNotMatch(String(fast.result?.err?.message ?? ""), /is not approved/); + await setDraftReview(dir, "onscreen/k1/onscreen", { verdict: "approved", key: draftKey(m, { entry: "k1", field: "onscreen" }), text: "Drafted" }); + const ok = await quietly(() => buildVideo({ manifestPath, opts: { final: true, skipFetch: true } })); + assert.doesNotMatch(String(ok.result?.err?.message ?? ""), /is not approved/); +}); + +test("a field a code path made (release 28 M1: the converter's timeline) needs no review: no row, no gate", () => { + const m = full(); + m.drafted = { timeline: { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 } }; + const timelineRows = () => draftsReviewRows(m, null).filter((r) => r.field === "timeline"); + assert.deepEqual(timelineRows(), []); + // (The full kit's hand narration keeps release 25's rule; nothing else is said.) + const ok = review({}, { narration: true, rows: { "narrate/the-contest/narration": approve(m, "the-contest", "narration") } }); + assert.deepEqual(draftsReviewProblems(m, ok, { final: true }).errors, []); + // The cut task's own order is a draft like any other. + m.drafted = { timeline: P("cut") }; + assert.deepEqual(timelineRows().map((r) => r.address), ["cut/*/timeline"]); + assert.equal(draftsReviewProblems(m, ok, { final: true }).errors.length, 1); +}); diff --git a/umtool/report-to-video/fixtures-r28.test.mjs b/umtool/report-to-video/fixtures-r28.test.mjs @@ -0,0 +1,35 @@ +// The release 28 test kit's manifests (common/testing/draft/manifests/full and +// flips): every media field a draft task writes, as the build accepts it today. +// The media tasks' tests start from these, so they must stay valid. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { validateChrome } from "./deck.mjs"; +import { lintManifest } from "./lint.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const MANIFESTS = path.join(HERE, "../../common/testing/draft/manifests"); +const load = (n) => JSON.parse(readFileSync(path.join(MANIFESTS, `${n}.video.manifest.json`), "utf8")); + +for (const name of ["full", "flips"]) { + test(`the ${name} fixture manifest lints clean`, () => { + const m = load(name); + const { chrome, ...rest } = m.render; + assert.deepEqual(validateChrome(chrome, rest), []); + assert.deepEqual(lintManifest(m, {}).errors, []); + }); +} + +test("the full fixture carries every media field", () => { + const m = load("full"); + const tl = m.timeline; + assert.ok(tl.some((e) => e.onscreen?.title && e.onscreen?.subtitle)); + assert.ok(tl.some((e) => e.type === "teaser" && e.lines.length >= 3)); + assert.ok(tl.some((e) => e.narration?.text)); + assert.ok(tl.filter((e) => e.type === "clip").every((e) => e.thread && e.claim?.verdict)); + assert.ok(m.render.chrome.threads.list.length >= 2); + assert.equal(load("flips").render.chrome.flips.pairs.length, 1); +}); diff --git a/umtool/report-to-video/flips.mjs b/umtool/report-to-video/flips.mjs @@ -15,10 +15,12 @@ // threadsGeometry); the two are one region and a cut has one or the other. // // PURE, like threads.mjs. chrome-flips.mjs draws the panel. +// The limits and the validators are common's (lib/report/panels.mjs, release +// 28): the flips draft task checks exactly what the build refuses. +import { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips } from "yt-dlp-transcript-common/lib/report/panels.mjs"; import { planCues } from "./threads.mjs"; -/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */ -export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 }); +export { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips }; /** * The panel's motion, in seconds: a pair rises in over `enter`, its NOW card @@ -32,80 +34,6 @@ export const FLIP_MOTION = Object.freeze({ /** How bright the THEN card rests once NOW has landed. */ export const THEN_DIM = 0.5; -const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; -const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); -const oneLine = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max; - -/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */ -export function flipsOn(render) { - const f = render?.chrome?.flips; - return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0; -} - -/** - * Every reason `render.chrome.flips` cannot be built, as sentences. Shape - * only; `validateFlipEntries` checks the pairs against the timeline. - * - * @returns {string[]} - */ -export function validateFlips(f, where = "render.chrome.flips") { - if (f === undefined) return []; - if (!isObj(f)) return [`${where} must be an object`]; - const errors = []; - for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`); - const [lo, hi] = FLIPS_LIMITS.pairs; - if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`]; - const ids = new Set(); - f.pairs.forEach((p, i) => { - const w = `${where}.pairs[${i}]`; - if (!isObj(p)) { errors.push(`${w} must be an object`); return; } - for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`); - if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`); - else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`); - else ids.add(p.id); - if (!oneLine(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`); - for (const side of ["then", "now"]) { - const s = p[side]; - const ws = `${w}.${side}`; - if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; } - for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`); - if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`); - if (!oneLine(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`); - if (!oneLine(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`); - } - }); - return errors; -} - -/** - * The pairs against the timeline: each side names an entry of the cut, a clip - * (not a teaser), the THEN side before the NOW side, and no entry in two pairs. - * - * @returns {string[]} - */ -export function validateFlipEntries(manifest) { - const render = manifest?.render ?? {}; - if (!flipsOn(render)) return []; - const errors = []; - const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }])); - const used = new Map(); - render.chrome.flips.pairs.forEach((p, i) => { - const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`; - const idx = {}; - for (const side of ["then", "now"]) { - const id = p?.[side]?.entry; - const hit = at.get(id); - if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; } - if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`); - if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`); - used.set(id, p.id); - idx[side] = hit.i; - } - if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`); - }); - return errors; -} - /** The years between two `when`s, when both carry one (`2019`, `May 2019`): else null. */ export function yearsBetween(a, b) { const y = (s) => { diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -2,7 +2,7 @@ // THE MANIFEST LINT — what a render would get wrong that no validator refuses, // said before a single frame is drawn. // -// node umtool/report-to-video/lint.mjs <manifest.json> [--variant sourced|full] [--json] +// node umtool/report-to-video/lint.mjs <manifest.json> [--variant sourced|full] [--final] [--json] // node umtool/report-to-video/build-video.mjs <manifest.json> --lint [--variant …] // // Both print every warning and error and exit 1 on an error. A build runs the @@ -27,13 +27,25 @@ // - a narrated card not approved on its current words when the cut has a // narration review (narration-review.mjs): rejected, edited since it was // approved, or not reviewed -- the last two pass with `--narration-unreviewed`; +// - in a `--final` build, a DRAFTED field (drafts-review.mjs: an entry's +// on-screen text, a card's narration, a teaser's lines, the cut's order, +// the flips, the threads, the YouTube text) not approved on its current +// value -- `--drafts-unreviewed` lets the unapproved through, never a +// rejected one; +// - a `drafted` mark that is malformed or where no field may be drafted, and +// a `publish` block that is not `{ youtube: { title, description } }` +// (drafted.mjs `validateDrafted`, `validatePublish`); // - a narrated card whose `seconds` is a number shorter than its narration // needs (the lead, the words, the tail). The words' length is known once // the voice is synthesized: the build checks it then, and `--lint` reads // the kept narrations (out/narration/) and checks those it finds. // WARNINGS -// - a narrated cut with no review file at all (narration.review.json): a -// cut narrated before reviews existed builds as it did, and is told so; +// - a narrated cut with no narration review at all: a cut narrated before +// reviews existed builds as it did, and is told so; +// - in a preview or fast build, the drafted fields not approved yet (one +// line), and each rejected one: a final build refuses them; +// - a `drafted` mark whose field is gone (an orphan): umtool's next write +// drops it; // - a teaser line over TEASER_HOUSE_CHARS -- an overline's or a kicker's // first tier, or any line's break: house style, not a fit. (A title's // first tier is held to the same 34 by the frame itself, TEASER_LIMITS.fit, @@ -73,7 +85,8 @@ import { validateFlipEntries } from "./flips.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; -import { readNarrationReview, reviewProblems } from "./narration-review.mjs"; +import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs"; +import { orphanDrafts, validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; export const TEASER_HOUSE_CHARS = 34; export const MIN_QR_PX_PER_MODULE_720P = 1.5; @@ -209,6 +222,8 @@ export function validatorErrors(whole) { ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), // The podcast's settings: its render refuses them, and `--lint` says so first. ...validatePodcast(whole), + // Release 28: where a field says it was drafted, and the publish block. + ...validateDrafted(whole), ...validatePublish(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); @@ -247,16 +262,22 @@ export function narrationLengthErrors(manifest, secondsById, { only = null } = { * @param {any} manifest the cut, as selectVariant returns it * @param {{ manifestDir?: string, whole?: any, exists?: (p: string) => boolean, * only?: string|null, validators?: boolean, narrationSeconds?: Map<string, number> | null, - * narrationReview?: { exists: boolean, rows: object, error?: string } | null, narrationUnreviewed?: boolean }} [opts] + * narrationReview?: { exists: boolean, rows: object, error?: string } | null, narrationUnreviewed?: boolean, + * draftsReview?: { exists: boolean, rows: object, narration?: boolean, error?: string } | null, + * final?: boolean, draftsUnreviewed?: boolean }} [opts] * `whole` is the manifest as written (what the validators read); * `validators: false` leaves them out (a build has run them already); * `only` lints one timeline entry (and the posts attached to it); - * `narrationSeconds` the kept narrations' seconds by card id (null: not read). + * `narrationSeconds` the kept narrations' seconds by card id (null: not read); + * `draftsReview` the cut's drafts review (drafts-review.mjs `readDraftsReview`; + * null: not read -- `narrationReview`, release 25's shape, is read as one); + * `final` a final build (drafted fields not approved refuse it); + * `draftsUnreviewed` / `narrationUnreviewed` let the unapproved through. * @returns {{ errors: string[], warnings: string[] }} */ export function lintManifest(manifest, { manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, narrationSeconds = null, - narrationReview = null, narrationUnreviewed = false, + narrationReview = null, narrationUnreviewed = false, draftsReview = null, final = false, draftsUnreviewed = false, } = {}) { const errors = []; const warnings = []; @@ -306,12 +327,17 @@ export function lintManifest(manifest, { } } - // The narration review: `narrationReview` null when it was not read. + // The drafts review, narration's included: null when it was not read. { - const r = reviewProblems(manifest, narrationReview, { only, allowUnreviewed: narrationUnreviewed }); + const review = draftsReview ?? draftsReviewFromNarration(narrationReview); + const r = draftsReviewProblems(manifest, review, { + final, only, allowUnreviewed: draftsUnreviewed, allowNarrationUnreviewed: narrationUnreviewed, + }); errors.push(...r.errors); warnings.push(...r.warnings, ...r.notes); } + // A mark whose field is gone: dropped by umtool's next write, said here. + if (!only) for (const o of orphanDrafts(whole)) warnings.push(`${o.where}: its field is gone — the drafted mark is an orphan (umtool's next write drops it)`); if (narrationSeconds) { errors.push(...narrationLengthErrors(manifest, narrationSeconds, { only })); @@ -332,7 +358,9 @@ export function lintManifest(manifest, { * * @returns {Promise<{ errors: string[], warnings: string[], variant: string }>} */ -export async function lintManifestFile(manifestPath, { variant = "sourced", only = null, narrationUnreviewed = false } = {}) { +export async function lintManifestFile(manifestPath, { + variant = "sourced", only = null, narrationUnreviewed = false, final = false, draftsUnreviewed = false, +} = {}) { const { readFile } = await import("node:fs/promises"); const { selectVariant } = await import("./build-video.mjs"); const whole = JSON.parse(await readFile(manifestPath, "utf8")); @@ -347,8 +375,11 @@ export async function lintManifestFile(manifestPath, { variant = "sourced", only const recs = await readNarrationRecords(narrationDir(path.join(manifestDir, "out")), narrationsOf(manifest)); narrationSeconds = new Map([...recs].map(([id, r]) => [id, r.seconds])); } - const narrationReview = await readNarrationReview(manifestDir); - return { ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, narrationReview, narrationUnreviewed }), variant }; + const draftsReview = await readDraftsReview(manifestDir); + return { + ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, draftsReview, narrationUnreviewed, final, draftsUnreviewed }), + variant, + }; } catch (err) { return { errors: [err?.message ?? String(err)], warnings: [], variant }; } @@ -369,10 +400,15 @@ if (import.meta.url === `file://${process.argv[1]}`) { const valued = new Set(["--variant"]); const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1])); if (!manifestPath) { - console.error("usage: lint.mjs <manifest.json> [--variant sourced|full] [--json]"); + console.error("usage: lint.mjs <manifest.json> [--variant sourced|full] [--final] [--drafts-unreviewed] [--narration-unreviewed] [--json]"); process.exit(2); } - lintManifestFile(manifestPath, { variant: flag("--variant") ?? "sourced" }).then((r) => { + lintManifestFile(manifestPath, { + variant: flag("--variant") ?? "sourced", + final: argv.includes("--final"), + draftsUnreviewed: argv.includes("--drafts-unreviewed"), + narrationUnreviewed: argv.includes("--narration-unreviewed"), + }).then((r) => { if (argv.includes("--json")) console.log(JSON.stringify(r, null, 2)); else for (const line of lintReport(r)) console.log(line); process.exit(r.errors.length ? 1 : 0); diff --git a/umtool/report-to-video/narration-review.mjs b/umtool/report-to-video/narration-review.mjs @@ -1,7 +1,10 @@ // The review of a cut's narration script, card by card, before synthesis -// (release 25, T5). +// (release 25, T5) -- since release 28 (M0) a view of the drafts review +// (drafts-review.mjs), whose rows for a card's narration are +// `narrate/<cardId>/narration`. // -// <project>/narration.review.json beside video.manifest.json +// <project>/drafts.review.json every verdict, written here +// <project>/narration.review.json release 25's file, READ UNCHANGED: // { "<cardId>": { "verdict": "approved" | "rejected" | null, "note": string, // "key": "<narrationKey when judged>", "text": "<the words judged>", "at": ISO } } // @@ -16,64 +19,47 @@ // approved any more, without anything having to remember to clear it. The // writer that edits the words (umtool's narration page) clears it as well. // -// The rule the build applies (`reviewProblems`): with NO review file, nothing -// is held -- a cut narrated before reviews existed builds as it did, and the -// lint says the file is missing (a warning). With one, every narrated card in -// the cut must be approved on its current words: an unreviewed or edited card -// refuses the build unless `--narration-unreviewed`; a REJECTED card refuses -// it always (rewrite and approve it, or take the narration out). +// The rule the build applies is drafts-review.mjs's `draftsReviewProblems`: +// a narration with no drafted mark keeps this file's `reviewProblems` rule -- +// with NO narration verdict anywhere, nothing is held (a warning); once there +// is one, every narrated card must be approved on its current words, an +// unreviewed or edited card refusing unless `--narration-unreviewed` and a +// REJECTED card always. A DRAFTED narration (release 28) follows the drafts +// rule: a warning until a `final` build, which refuses it unapproved. // -// Pure but for the file's read and write. -import { readFile, rename, writeFile } from "node:fs/promises"; -import path from "node:path"; - +// Pure but for the files' read and write. import { narrationsOf } from "./narration.mjs"; +import { + DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, REVIEW_NOTE_LIMIT, REVIEW_VERDICTS, cleanNarrationRows, narrationAddress, + readDraftsReview, setDraftReview, +} from "./drafts-review.mjs"; -export const NARRATION_REVIEW_FILE = "narration.review.json"; -export const REVIEW_VERDICTS = Object.freeze(["approved", "rejected"]); -export const REVIEW_NOTE_LIMIT = 2000; - -/** `<manifest's directory>/narration.review.json`. */ -export const reviewFileOf = (manifestDir) => path.join(manifestDir, NARRATION_REVIEW_FILE); - -const isCardId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200; -const str = (v) => (typeof v === "string" ? v : ""); +export { DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, REVIEW_NOTE_LIMIT, REVIEW_VERDICTS }; /** Rows that are not the contract's shape are dropped on read, never repaired on disk. */ -export function cleanReview(raw) { +export const cleanReview = cleanNarrationRows; + +/** A drafts review's narration rows, by card id. */ +function narrationRowsOf(rows) { const out = {}; - if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out; - for (const [id, row] of Object.entries(raw)) { - if (!isCardId(id) || !row || typeof row !== "object") continue; - out[id] = { - verdict: REVIEW_VERDICTS.includes(row.verdict) ? row.verdict : null, - note: str(row.note), - key: str(row.key), - text: str(row.text), - at: str(row.at), - }; + for (const [address, row] of Object.entries(rows ?? {})) { + const m = /^narrate\/([^/]+)\/narration$/.exec(address); + if (m && m[1] !== "*") out[m[1]] = row; } return out; } /** - * The review file of a cut: `{ exists, rows }`, or `{ exists: true, rows: {}, - * error }` when it does not parse -- a build must not read that as "nothing - * approved", nor a writer overwrite it. + * The narration review of a cut: `{ exists, rows }` -- `exists` when any + * narration verdict or note is kept (either file), `rows` by card id -- or + * `{ exists: true, rows: {}, error }` when a file does not parse: a build must + * not read that as "nothing approved", nor a writer overwrite it. */ export async function readNarrationReview(manifestDir) { - let text; - try { - text = await readFile(reviewFileOf(manifestDir), "utf8"); - } catch (err) { - if (err?.code === "ENOENT") return { exists: false, rows: {} }; - return { exists: true, rows: {}, error: `${NARRATION_REVIEW_FILE} cannot be read: ${err?.message ?? err}` }; - } - try { - return { exists: true, rows: cleanReview(JSON.parse(text)) }; - } catch { - return { exists: true, rows: {}, error: `${NARRATION_REVIEW_FILE} does not parse; fix or remove it` }; - } + const r = await readDraftsReview(manifestDir); + if (r.error) return { exists: true, rows: {}, error: r.error }; + const rows = narrationRowsOf(r.rows); + return { exists: r.narration, rows }; } /** @@ -114,7 +100,7 @@ export function reviewProblems(manifest, review, { only = null, allowUnreviewed if (review.error) return { errors: [review.error], notes, warnings }; if (!review.exists) { warnings.push( - `the narration (${rows.length} card${rows.length === 1 ? "" : "s"}) has no review — ${NARRATION_REVIEW_FILE} is not there; ` + + `the narration (${rows.length} card${rows.length === 1 ? "" : "s"}) has no review — ${DRAFTS_REVIEW_FILE} has no narration verdicts; ` + "review it card by card on umtool's narration page before it is published", ); return { errors, notes, warnings }; @@ -134,58 +120,20 @@ export function reviewProblems(manifest, review, { only = null, allowUnreviewed return { errors, notes, warnings }; } -/** @type {Promise<unknown>} */ -let queue = Promise.resolve(); -function withReviewLock(fn) { - const run = queue.then(fn, fn); - queue = run.then( - () => undefined, - () => undefined, - ); - return run; -} - /** * Set one card's review. `patch.verdict` "approved" | "rejected" | null (null * clears it); `note` replaces the note; `key` and `text` are the words and * voice the verdict is about (required with a verdict). A rejection needs its * note -- what is wrong with the words -- as an incorrect clip does. Returns - * the row as stored (null when removed) and every row. + * the row as stored (null when removed) and every narration row. Written to + * drafts.review.json as `narrate/<cardId>/narration`. * * @param {string} manifestDir * @param {string} cardId * @param {{ verdict?: string | null, note?: string, key?: string, text?: string }} patch */ export async function setNarrationReview(manifestDir, cardId, patch) { - if (!isCardId(cardId)) throw new Error("not a card id"); - if (patch.verdict !== undefined && patch.verdict !== null && !REVIEW_VERDICTS.includes(patch.verdict)) { - throw new Error(`verdict must be one of ${REVIEW_VERDICTS.join(", ")} or null`); - } - if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string"); - if (patch.verdict && !(typeof patch.key === "string" && patch.key && typeof patch.text === "string")) { - throw new Error("a verdict is given on words: key and text are required"); - } - const file = reviewFileOf(manifestDir); - return withReviewLock(async () => { - const cur = await readNarrationReview(manifestDir); - if (cur.error) throw new Error(cur.error); - const map = cur.rows; - const prev = map[cardId] ?? { verdict: null, note: "", key: "", text: "", at: "" }; - const row = { - verdict: patch.verdict === undefined ? prev.verdict : patch.verdict, - note: patch.note === undefined ? prev.note : patch.note.slice(0, REVIEW_NOTE_LIMIT).trim(), - key: patch.verdict ? patch.key : patch.verdict === null ? "" : prev.key, - text: patch.verdict ? patch.text : patch.verdict === null ? "" : prev.text, - at: new Date().toISOString(), - }; - if (row.verdict === "rejected" && !row.note) { - throw new Error("a rejection needs its note: say what is wrong with the words"); - } - if (row.verdict === null && !row.note) delete map[cardId]; - else map[cardId] = row; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; - await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); - await rename(tmp, file); - return { entry: map[cardId] ?? null, rows: map }; - }); + if (!(typeof cardId === "string" && cardId.length > 0 && cardId.length <= 200 && !cardId.includes("/"))) throw new Error("not a card id"); + const r = await setDraftReview(manifestDir, narrationAddress(cardId), patch); + return { entry: r.entry, rows: narrationRowsOf(r.rows) }; } diff --git a/umtool/report-to-video/narration-review.test.mjs b/umtool/report-to-video/narration-review.test.mjs @@ -14,7 +14,7 @@ import { buildVideo, setProgressMode } from "./build-video.mjs"; import { lintManifest } from "./lint.mjs"; import { narrationsOf } from "./narration.mjs"; import { - NARRATION_REVIEW_FILE, cleanReview, readNarrationReview, reviewProblems, reviewRows, reviewState, setNarrationReview, + DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, cleanReview, readNarrationReview, reviewProblems, reviewRows, reviewState, setNarrationReview, } from "./narration-review.mjs"; const card = (id, text, extra = {}) => ({ type: "card", id, heading: id, seconds: "auto", narration: { text, ...extra } }); @@ -51,7 +51,9 @@ test("setNarrationReview: a verdict is on words; a rejection needs its note; an // No verdict and no note: removed. const gone = await setNarrationReview(dir, "k2", { note: "" }); assert.equal(gone.entry, null); - assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"))), ["k1"]); + // Written to the drafts review, by the card's address. + assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))), ["narrate/k1/narration"]); + assert.deepEqual(Object.keys((await readNarrationReview(dir)).rows), ["k1"]); }); test("states: approved on its words; an edit or another voice leaves it edited; none is unreviewed", () => { @@ -80,7 +82,7 @@ test("reviewProblems: no file warns; a file holds every un-approved card; the fl }; const none = reviewProblems(m, { exists: false, rows: {} }); assert.deepEqual(none.errors, []); - assert.match(none.warnings[0], /the narration \(3 cards\) has no review — narration\.review\.json is not there/); + assert.match(none.warnings[0], /the narration \(3 cards\) has no review — drafts\.review\.json has no narration verdicts/); const held = reviewProblems(m, review); assert.equal(held.errors.length, 2, held.errors.join("\n")); assert.match(held.errors[0], /timeline k2: its narration is not reviewed — approve it on umtool's narration page, or build with --narration-unreviewed/); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -24,6 +24,7 @@ "./compose-chrome": "./compose-chrome.mjs", "./cues": "./cues.mjs", "./deck": "./deck.mjs", + "./drafts-review": "./drafts-review.mjs", "./factcheck": "./factcheck.mjs", "./ledger-totals": "./ledger-totals.mjs", "./lint": "./lint.mjs", @@ -39,6 +40,7 @@ "./resolve-windows": "./resolve-windows.mjs", "./shoot-page": "./shoot-page.mjs", "./sources": "./sources.mjs", - "./verify-build": "./verify-build.mjs" + "./verify-build": "./verify-build.mjs", + "./youtube": "./youtube.mjs" } } diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs @@ -19,10 +19,12 @@ // PURE, like factcheck.mjs: the settings, their validation, the schedule and // the cues. No fs. deck.mjs imports this file -- never the other way round. // chrome-threads.mjs draws the rail. -import { resolveFactcheck, VERDICTS } from "./factcheck.mjs"; +import { resolveFactcheck } from "./factcheck.mjs"; +// The limits and the validators are common's (lib/report/panels.mjs, release +// 28): the threads draft task checks exactly what the build refuses. +import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs"; -/** The limits: how many threads, a label's and an outcome label's characters. */ -export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 }); +export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads }; /** * The rail's motion, in seconds: a card lights over `light` and its string @@ -37,17 +39,7 @@ export const THREAD_MOTION = Object.freeze({ /** How long before its thread's last clip ends the outcome lands, at most. */ export const OUTCOME_LEAD = 1.8; -/** A thread id: letters, digits and `_ -`. */ -const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; - const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); -const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v); - -/** Is the rail on: a `render.chrome.threads` with at least one thread. */ -export function threadsOn(render) { - const t = render?.chrome?.threads; - return isObj(t) && Array.isArray(t.list) && t.list.length > 0; -} /** * The threads with their outcomes resolved: `[{ id, label, outcome: { verdict, @@ -68,75 +60,6 @@ export function resolveThreads(render) { } /** - * Every reason `render.chrome.threads` cannot be built, as sentences (empty: - * it can). validateChrome calls this, so umtool's writer and the build refuse - * the same things. - * - * @returns {string[]} - */ -export function validateThreads(t, where = "render.chrome.threads") { - if (t === undefined) return []; - if (!isObj(t)) return [`${where} must be an object`]; - const errors = []; - for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`); - const [lo, hi] = THREADS_LIMITS.threads; - if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) { - return [...errors, `${where}.list must be ${lo} to ${hi} threads`]; - } - const seen = new Set(); - t.list.forEach((th, i) => { - const w = `${where}.list[${i}]`; - if (!isObj(th)) { errors.push(`${w} must be an object`); return; } - for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`); - if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`); - else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`); - else seen.add(th.id); - if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) { - errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`); - } - if (th.outcome !== undefined) { - const o = th.outcome; - if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; } - for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`); - if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`); - if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) { - errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`); - } - } - }); - return errors; -} - -/** The thread an entry belongs to, or null. */ -export function threadOf(entry) { - return typeof entry?.thread === "string" && entry.thread ? entry.thread : null; -} - -/** - * Every `thread` in the timeline, checked against the list: it names a listed - * thread, it is not on a teaser, and every listed thread has a clip. The - * build refuses with these before it fetches. - * - * @returns {string[]} - */ -export function validateThreadEntries(manifest) { - const errors = []; - const render = manifest?.render ?? {}; - const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set(); - const used = new Set(); - (manifest?.timeline ?? []).forEach((e, i) => { - if (e?.thread === undefined || e?.thread === null) return; - const where = `timeline[${i}] (${e.id ?? "?"}).thread`; - if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; } - if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; } - if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; } - used.add(e.thread); - }); - for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`); - return errors; -} - -/** * The rail's schedule, in the cut's clock. `segments` are the schedule's, in * order, each `{ id, start, duration, thread }`; `moves` are the footage's * moves for popup posts (deck.mjs footageMoves). diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs @@ -0,0 +1,147 @@ +// THE YOUTUBE TEXT (release 28, M6): what a cut's upload says, composed by +// CODE from `publish.youtube { title, description }` (drafted by the youtube +// task or written by hand), the build's own chapter list and the cut's +// citations. The build writes it to `out/youtube.txt` (`out/youtube-<variant>.txt` +// for a variant other than `sourced`, as the cut's mp4 is named); umtool shows +// and copies it, and previews it the same way, without chapters, before a build. +// +// <title> +// +// <description> +// +// Chapters +// 0:00 <chapter> +// … +// +// Sources +// <a moment link per cited clip, in cut order, each once> +// +// The chapters are YouTube's: the first at 0:00, at least three, each at +// least ten seconds. A chapter shorter than that is folded into the one +// before it (a first one shorter than that takes the next one's span). A list +// that is still too short, or does not start at 0:00, is left out -- and the +// result's `notes` say why. +// +// PURE: no fs. build-video.mjs writes the file. + +/** YouTube's rules for a description's chapters. */ +export const YOUTUBE_CHAPTERS = Object.freeze({ min: 3, minSeconds: 10 }); + +/** `m:ss`, or `h:mm:ss` from an hour. */ +export function chapterStamp(seconds) { + const s = Math.max(0, Math.floor(seconds)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const ss = String(s % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +} + +const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** + * The chapters as YouTube takes them, from the build's list (`{ start, end?, + * title }`, seconds, in order; `total` the cut's length for the last one's + * span): `{ chapters, note }` -- `chapters` null when the block is left out, + * `note` saying what was folded or why the block is left out. + * + * @param {Array<{ start: number, end?: number, title: string }> | null | undefined} list + * @param {number | null} [total] + */ +export function youtubeChapters(list, total = null) { + if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" }; + const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" })); + if (all[0].start !== 0) return { chapters: null, note: `no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00` }; + const end = Number.isFinite(Number(total)) && total !== null + ? Math.floor(Number(total)) + : Math.floor(Number(list.at(-1).end ?? all.at(-1).start + YOUTUBE_CHAPTERS.minSeconds)); + const kept = [all[0]]; + let folded = 0; + for (const c of all.slice(1)) { + if (c.start - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) { + folded++; + // A first chapter too short to stand takes the next one's span under its own 0:00. + continue; + } + kept.push(c); + } + // The last must run ten seconds too. + while (kept.length > 1 && end - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) { + kept.pop(); + folded++; + } + const foldNote = folded ? `${folded} chapter(s) under ${YOUTUBE_CHAPTERS.minSeconds} s folded into the one before` : ""; + if (kept.length < YOUTUBE_CHAPTERS.min) { + return { + chapters: null, + note: `no chapters: ${kept.length} of at least ${YOUTUBE_CHAPTERS.min}` + (foldNote ? ` (${foldNote})` : ""), + }; + } + return { chapters: kept, note: foldNote }; +} + +/** + * A clip's moment link: its `citeUrl` when it has one, else the archive's page + * at the cited second (`cite`, else `start`) -- the link the citation makes + * (`<origin>/?v=<channel>%2F<video>&t=<s>`). A clip from a file beside the + * manifest (`src`) with no `citeUrl` has none; nor has any other entry. + */ +export function momentLinkOf(entry, provenance = {}) { + if (entry?.type !== "clip") return null; + if (entry.citeUrl) return entry.citeUrl; + if (entry.src != null) return null; + const origin = String(provenance?.siteOrigin ?? "").replace(/\/+$/, ""); + const channel = entry.channel ?? provenance?.channelSlug; + if (!origin || !channel || !entry.video) return null; + const at = Number.isFinite(Number(entry.cite)) ? Number(entry.cite) : Number(entry.start); + return `${origin}/?v=${encodeURIComponent(`${channel}/${entry.video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`; +} + +/** The cut's moment links, in cut order, each once. */ +export function youtubeSources(entries, provenance = {}) { + const out = []; + const seen = new Set(); + for (const e of entries ?? []) { + const href = momentLinkOf(e, provenance); + if (!href || seen.has(href)) continue; + seen.add(href); + out.push(href); + } + return out; +} + +/** + * The text. `chapters` is youtubeChapters' (null: no block); `sources` the + * links. Null when the manifest has no `publish.youtube` title. + * + * @param {{ youtube?: { title?: string, description?: string } | null, chapters?: Array<{ start: number, title: string }> | null, sources?: string[] }} o + * @returns {string | null} + */ +export function composeYoutubeText({ youtube, chapters = null, sources = [] }) { + const title = oneLine(youtube?.title); + if (!title) return null; + const parts = [title]; + const description = String(youtube?.description ?? "").trim(); + if (description) parts.push(description); + if (chapters?.length) parts.push(["Chapters", ...chapters.map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`)].join("\n")); + if (sources.length) parts.push(["Sources", ...sources].join("\n")); + return `${parts.join("\n\n")}\n`; +} + +/** The file a variant's text is written to, in the project's `out/`. */ +export function youtubeTextName(variant = "sourced") { + return variant === "sourced" ? "youtube.txt" : `youtube-${variant}.txt`; +} + +/** + * The preview umtool shows before a build: composed the same way, without + * chapters (the build makes them), over the default cut's entries -- an entry + * tagged with another `variant` is left out, as build-video's selectVariant + * leaves it out of `sourced`. + * + * @returns {{ text: string | null, note: string }} + */ +export function youtubePreview(manifest) { + const entries = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => !e?.variant || e.variant === "sourced"); + const text = composeYoutubeText({ youtube: manifest?.publish?.youtube, chapters: null, sources: youtubeSources(entries, manifest?.provenance) }); + return { text, note: "chapters are added by the build" }; +} diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs @@ -0,0 +1,91 @@ +// out/youtube.txt's composition (release 28 M6): the title, the summary, the +// chapters on YouTube's rules (0:00 first, at least three, ten seconds each), +// the sources in cut order, each once. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { + chapterStamp, composeYoutubeText, momentLinkOf, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS, +} from "./youtube.mjs"; + +const FULL = new URL("../../common/testing/draft/manifests/full.video.manifest.json", import.meta.url); +const YT = { title: "What the baker says about the bakery", description: "Synth Kitchen on the bakery and the contest." }; + +test("stamps: m:ss, h:mm:ss from an hour", () => { + assert.equal(chapterStamp(0), "0:00"); + assert.equal(chapterStamp(65.9), "1:05"); + assert.equal(chapterStamp(3725), "1:02:05"); +}); + +test("chapters: 0:00 first, at least three, each ten seconds — short ones folded into the one before", () => { + const list = [ + { start: 0, title: "Title" }, + { start: 4, title: "The bakery" }, // 4 s after the first: folded + { start: 12.4, title: "Not for sale" }, + { start: 30, title: "The contest" }, + { start: 55, title: "Last" }, // 5 s before the end: folded + ]; + const r = youtubeChapters(list, 60); + assert.deepEqual(r.chapters.map((c) => [c.start, c.title]), [[0, "Title"], [12, "Not for sale"], [30, "The contest"]]); + assert.match(r.note, /2 chapter\(s\) under 10 s folded/); + assert.equal(YOUTUBE_CHAPTERS.min, 3); +}); + +test("chapters: fewer than three, or not starting at 0:00, are left out — and the note says why", () => { + const two = youtubeChapters([{ start: 0, title: "A" }, { start: 20, title: "B" }], 40); + assert.equal(two.chapters, null); + assert.match(two.note, /^no chapters: 2 of at least 3/); + const late = youtubeChapters([{ start: 2, title: "A" }, { start: 20, title: "B" }, { start: 40, title: "C" }], 60); + assert.equal(late.chapters, null); + assert.match(late.note, /first starts at 0:02, not 0:00/); + assert.match(youtubeChapters(null).note, /made none/); +}); + +test("sources: a moment link per cited clip in cut order, each once; citeUrl wins; a src clip and a card have none", () => { + const prov = { siteOrigin: "https://synth.example/", channelSlug: "synth-kitchen" }; + const entries = [ + { type: "card", id: "t" }, + { type: "clip", id: "c02", video: "bread-day-01", start: 24.2, cite: 25 }, + { type: "clip", id: "c01", channel: "synth-kitchen", video: "bread-day-01", start: 15 }, + { type: "clip", id: "c02b", video: "bread-day-01", start: 25, cite: 25.9 }, // the same moment again + { type: "clip", id: "x", citeUrl: "https://x.example/post/1" }, + { type: "clip", id: "local", src: "a.mp4", start: 0 }, + ]; + assert.deepEqual(youtubeSources(entries, prov), [ + "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25", + "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15", + "https://x.example/post/1", + ]); + assert.equal(momentLinkOf({ type: "clip", video: "v" }, {}), null, "no origin: no link"); +}); + +test("the text: title, a blank, the summary, Chapters, Sources; nothing without a title", () => { + const text = composeYoutubeText({ + youtube: YT, + chapters: [{ start: 0, title: "Title" }, { start: 12, title: "Not for sale" }, { start: 75, title: "The contest" }], + sources: ["https://a.example/1", "https://a.example/2"], + }); + assert.equal( + text, + "What the baker says about the bakery\n\nSynth Kitchen on the bakery and the contest.\n\nChapters\n0:00 Title\n0:12 Not for sale\n1:15 The contest\n\nSources\nhttps://a.example/1\nhttps://a.example/2\n", + ); + assert.equal(composeYoutubeText({ youtube: { title: " ", description: "x" } }), null); + assert.equal(composeYoutubeText({ youtube: { title: "T" } }), "T\n"); + assert.equal(youtubeTextName(), "youtube.txt"); + assert.equal(youtubeTextName("full"), "youtube-full.txt"); +}); + +test("the preview: the default cut's sources, no chapters", async () => { + const m = JSON.parse(await readFile(FULL, "utf8")); + m.publish = { youtube: YT }; + m.timeline.push({ type: "clip", id: "only-full", variant: "full", channel: "synth-kitchen", video: "qa-long-03", start: 5, cite: 5 }); + const p = youtubePreview(m); + const lines = p.text.split("\n"); + assert.equal(lines[0], YT.title); + assert.ok(!p.text.includes("Chapters")); + const sources = lines.slice(lines.indexOf("Sources") + 1).filter(Boolean); + assert.equal(sources.length, 7, "seven clips, seven moments"); + assert.ok(!p.text.includes("qa-long-03&t=5"), "an entry of another variant is not in the default cut"); + assert.equal(youtubePreview({ timeline: [] }).text, null); +});