Archilyzer · Source

archilyzer

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

commit d3c61e05f7b7de993cbd92c28f53a42a9af1431a
parent 4f7829b4f51eefba6d26f5cf4e24341dadb309d1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 08:26:15 -0400

Merge r29/gen-debts (G1 deck option, G2 social text, D1 debts) into r29/integration

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
M.claude/commands/gen.md | 4+++-
MCOMMANDS.md | 4++--
MOPERATING.md | 8++++++--
MSETTINGS.md | 2++
Mcommon/bin/archilyzer.ts | 4++--
Mcommon/bin/gen.ts | 2+-
Mcommon/controller/fetchPosts.test.ts | 61++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/controller/relocateDir.test.ts | 39+++++++++++++++++++++++++++++++++------
Mcommon/controller/relocateDir.ts | 57++++++++++++++++++++++++++++++++++++---------------------
Mcommon/controller/reportDraft.ts | 9+++++----
Mcommon/lib/generationSettings.test.ts | 9++++++++-
Mcommon/lib/generationSettings.ts | 7++++---
Acommon/lib/report/draft/tasks/deckOption.test.ts | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 5+++++
Acommon/lib/report/draft/tasks/social.test.ts | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/social.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/youtube.ts | 7+++++--
Mcommon/lib/report/drafted.d.mts | 3++-
Mcommon/lib/report/drafted.mjs | 31++++++++++++++++++++++++-------
Mcommon/lib/report/drafted.test.ts | 23++++++++++++++++++++---
Acommon/lib/report/social.d.mts | 20++++++++++++++++++++
Acommon/lib/report/social.mjs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/testing/README.md | 2+-
Acommon/testing/draft/runs/social.json | 28++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 6++++++
Aeditor/app/api/active-site/route.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 2+-
Meditor/app/components/SiteScopeProvider.tsx | 57+++++++++++++++++++++++++++++++++++----------------------
Meditor/app/components/SiteScopeSelect.tsx | 9+++++----
Meditor/app/lib/activeSite.ts | 3++-
Deditor/app/lib/activeSiteActions.ts | 31-------------------------------
Meditor/app/lib/activeSiteServer.ts | 2+-
Meditor/app/storage/actions.ts | 7++++++-
Meditor/app/storage/components/HealthTimingForm.tsx | 10+++++++++-
Meditor/e2e/publish-lane.spec.ts | 14++++++++++----
Meditor/e2e/site-scope.spec.ts | 16++++++++++------
Meditor/e2e/storage-locations.spec.ts | 20++++++++++++++++++--
Mmcp/src/generation.test.ts | 24+++++++++++++++++++++++-
Mmcp/src/generation.ts | 19++++++++++++-------
Mmcp/src/instructions.ts | 6+++++-
Mplans/FACTS.md | 41+++++++++++++++++++++++++++++++++++++++++
Mplans/release-29.md | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/queue-lock.test.mjs | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Msettings.json.example | 1+
Mumtool/app/api/articles/chain/route.ts | 20++++++++++++--------
Mumtool/bin/umtool.mjs | 18+++++++++++-------
Mumtool/components/articles/ChainPanel.tsx | 14+++++++++-----
Mumtool/components/projects/MediaDrafts.tsx | 17+++++++++++++++--
Mumtool/components/projects/OnscreenSection.tsx | 3++-
Aumtool/components/projects/SocialPostSection.tsx | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/MediaTab.tsx | 6+++++-
Mumtool/docs/authoring.md | 8+++++---
Mumtool/e2e/fixtures/editor-stub.mjs | 24++++++++++++++++++++----
Mumtool/e2e/fixtures/media-draft-fixture.mjs | 7++++---
Mumtool/e2e/fixtures/media-surfaces-fixture.mjs | 7++++++-
Mumtool/e2e/media-draft.spec.ts | 24++++++++++++++++++++++++
Mumtool/e2e/media-surfaces.spec.ts | 49+++++++++++++++++++++++++++++++++++++++++++------
Mumtool/lib/articles/generation.ts | 14+++++++++++---
Mumtool/lib/articles/projectDraft.ts | 11++++++++++-
Mumtool/lib/create/create.test.mjs | 6+++---
Mumtool/lib/create/policy.mjs | 3++-
Mumtool/lib/report/chain-draft.mjs | 16++++++++++++++++
Mumtool/lib/report/chain-draft.test.mjs | 43+++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/chain-run.mjs | 44+++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/chain.mjs | 52+++++++++++++++++++++++++++++++++++++++-------------
Mumtool/lib/report/chain.test.mjs | 44+++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/report/drafted-writer.test.mjs | 18++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 36+++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/README.md | 26++++++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 21+++++++++++++++++++++
Mumtool/report-to-video/drafts-review.mjs | 3+++
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/social.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/social.test.mjs | 47+++++++++++++++++++++++++++++++++++++++++++++++
75 files changed, 2029 insertions(+), 264 deletions(-)

diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -18,7 +18,9 @@ each task. Use the archilyzer MCP tools only; run no script for it. - `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". + - `youtube` — "YouTube title", "YouTube description", "the upload text"; + - `social` — "a tweet", "an X post", "a Bluesky post", "promote it", "the social text" (text only: nothing is + posted; the link and the length limits are code's). "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. diff --git a/COMMANDS.md b/COMMANDS.md @@ -40,8 +40,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `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, 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 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, social) | +| `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, social) 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) | diff --git a/OPERATING.md b/OPERATING.md @@ -209,6 +209,7 @@ umtool chain example-article 3 --draft-all --model qwen3:8b | `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** | +| `social` | `publish.x`, `publish.bluesky` `{post, thread?}` | X 280 (a URL is 23), Bluesky 300 graphemes; up to 4 posts under the first; the link appended by code (`publish.videoUrl`, else a public article's page); text only, never posted; `out/x.txt`, `out/bluesky.txt` | the Social posts section (Copy), **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 @@ -217,9 +218,12 @@ umtool chain example-article 3 --draft-all --model qwen3:8b **Reject**, and heads each section with **Draft with <model>** (force, the entries, the job's progress, the last run's written, skipped and refused). A project not made from an iteration (`<projectsRoot>/<id>/i<n>/`) offers none ("Drafting is off: no article iteration made this project."). -- **Draft everything** (the Media tab, or `umtool chain <id> <n> --draft-all [--model M]`) is the chain with +- **Draft everything** (the Media tab, or `umtool chain <id> <n> --draft-all [--model M] [--deck]`) 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). + narration → voices → the fast build → podcast → YouTube (its chapters re-muxed so `out/youtube.txt` is written) + → the social posts (`out/x.txt`, `out/bluesky.txt`). **With the deck** (the checkbox, `--deck`; off by default) a + step before the flips adds the minimal on-screen deck to a cut with none (a snapshot first; a cut with a deck is + left as it is), so the flips and threads are drafted on a converted cut. 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 the Media tab or the review bench, diff --git a/SETTINGS.md b/SETTINGS.md @@ -1004,6 +1004,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `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. | +| `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. | | `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. | #### `generation.models` @@ -1090,6 +1091,7 @@ Default: "flips": "local", "threads": "local", "youtube": "local", + "social": "local", "verdicts": "local" }, "models": { diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -444,14 +444,14 @@ export const COMMANDS: Command[] = [ }, { path: ["gen", "set"], - 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)", + 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, social)", 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] [--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)", + "<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, social) 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", diff --git a/common/bin/gen.ts b/common/bin/gen.ts @@ -7,7 +7,7 @@ // archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait] // enqueue a report-draft job (`pnpm ops report-draft`); // a media draft (cut, onscreen, teaser, flips, threads, -// narrate, youtube) takes --iteration, --entries, --force +// narrate, youtube, social) 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 diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -7,6 +7,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { writeFileSync } from "node:fs"; import { chmod, mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -25,8 +26,11 @@ process.env.FAKE_ARGS_LOG = ARGS_LOG; // blocks on a "rate limit" (the real stall); given the cursor after page 2 it // emits page 3 and exits cleanly. FAKE_MODE=known emits page 1 then endless // tweets older than the watermark, to prove the early stop kills it. -// FAKE_MODE=pages emits six pages, each followed (after a pause) by an info -// line, then its cursor: a walk with a page boundary every few hundred ms. +// FAKE_MODE=pages walks six pages, each its records, an info line, then its +// cursor — and the walk is the TEST's to step, not a clock's (release 29 D1): +// a page's cursor waits for the file `cursor-<p>` in FAKE_GATES, the next page +// for `page-<p+1>` (polled; 30 s and it gives up), so a drain lands exactly +// between a page's records and its cursor however loaded the machine is. await writeFile( BIN, `#!/usr/bin/env node @@ -63,17 +67,21 @@ if (process.env.FAKE_MODE === "known") { log("[twitter][error] AbortExtraction: 404 Not Found (GraphQL query id rotated)"); process.exit(4); } else if (process.env.FAKE_MODE === "pages") { + const { existsSync } = await import("node:fs"); + const gate = (name, then) => { + const file = process.env.FAKE_GATES + "/" + name; + const t = setInterval(() => { if (existsSync(file)) { clearInterval(t); then(); } }, 10); + }; + setTimeout(() => process.exit(3), 30_000); let p = 0; const next = () => { page(p); - setTimeout(() => { - log("[twitter][info] page " + p + " read"); - setTimeout(() => { - log("[twitter][debug] Cursor: 1/PAGES-P" + p); - p++; - if (p < 6) setTimeout(next, 300); else process.exit(0); - }, 300); - }, 100); + log("[twitter][info] page " + p + " read"); + gate("cursor-" + p, () => { + log("[twitter][debug] Cursor: 1/PAGES-P" + p); + p++; + if (p < 6) gate("page-" + p, next); else process.exit(0); + }); }; next(); } else if (cursor === "1/AFTER-P2") { @@ -238,7 +246,11 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th const root = await makeChannel(slug); const drain = new AbortController(); const log: string[] = []; + const gates = path.join(ROOT, `gates-${slug}`); + await mkdir(gates, { recursive: true }); + const open = (name: string) => writeFileSync(path.join(gates, name), ""); process.env.FAKE_MODE = "pages"; + process.env.FAKE_GATES = gates; let result; try { result = await fetchPosts({ @@ -248,12 +260,21 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th drain: drain.signal, onLog: (line) => { log.push(line); - // Page 1's records are in; its cursor is not yet. - if (/page 1 read/.test(line)) drain.abort(); + // Page 0 read: its cursor, then page 1. Page 1's records are in and its + // cursor is not yet: drain, THEN let the cursor come. Page 2 is never let. + if (/page 0 read/.test(line)) { + open("cursor-0"); + open("page-1"); + } + if (/page 1 read/.test(line)) { + drain.abort(); + open("cursor-1"); + } }, }); } finally { delete process.env.FAKE_MODE; + delete process.env.FAKE_GATES; } assert.equal(result.ok, true, log.join("\n")); assert.equal(result.drained, true); @@ -267,16 +288,26 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th assert.equal(log.some((l) => /page 2 read/.test(l)), false, log.join("\n")); assert.ok(log.some((l) => /Drained; the next run resumes from the last page read/.test(l)), log.join("\n")); - // The next run resumes there (cancelled once it has started: only its argv - // is wanted). + // The next run resumes there (cancelled once the fake has logged its argv: + // only that is wanted — a file, not a fixed wait). const cancel = new AbortController(); + const argvLines = async () => (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const had = await argvLines(); await fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, signal: cancel.signal, onLog: (line) => { - if (/^Running /.test(line)) setTimeout(() => cancel.abort(), 200); + if (!/^Running /.test(line)) return; + const t = setInterval(() => { + void argvLines().then((n) => { + if (n > had) { + clearInterval(t); + cancel.abort(); + } + }); + }, 10); }, }); assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/PAGES-P1")); diff --git a/common/controller/relocateDir.test.ts b/common/controller/relocateDir.test.ts @@ -502,13 +502,40 @@ test("rsync's itemized lines sort into extra, missing and changed", () => { "v50t5yt/.audio.mp3.parakeet/", ]); assert.deepEqual(d.missing, ["v51/transcript.json", "v52/"]); - assert.deepEqual(d.changed, [ - "v1/transcript.json", - "v1/", - "rsync: something it wanted to say", - ]); + // A directory whose only difference is its mtime is not "changed" (release 29 D1). + assert.deepEqual(d.changed, ["v1/transcript.json", "rsync: something it wanted to say"]); + assert.deepEqual(d.mtimeOnly, ["v1/"]); assert.equal( - describeDifferences({ extra: [], missing: ["a", "b", "c", "d", "e", "f", "g"], changed: [] }), + describeDifferences({ extra: [], missing: ["a", "b", "c", "d", "e", "f", "g"], changed: [], mtimeOnly: [] }), "0 extra on the destination, 7 missing on the destination (a, b, c, d, e, … 2 more), 0 changed", ); + assert.equal( + describeDifferences({ extra: [], missing: [], changed: ["v2/x.json"], mtimeOnly: ["v1/", "v3/"] }), + "0 extra on the destination, 0 missing on the destination, 1 changed (v2/x.json), and 2 directories differ only in mtime (v1/, v3/)", + ); +}); + +test("a reconcile whose only drift is directory timestamps says so — not that anything changed — and settles them", async () => { + await withTrees(async ({ src, dest }) => { + await put(src, "v1/audio.mp3", "one".repeat(10)); + await put(src, "v2/audio.mp3", "two".repeat(10)); + await put(dest, "v1/audio.mp3", "one".repeat(10)); + await put(dest, "v2/audio.mp3", "two".repeat(10)); + // Same bytes, same file times; only the two directories' mtimes differ. + const t = new Date("2026-01-05T00:00:00Z"); + for (const f of ["v1/audio.mp3", "v2/audio.mp3"]) { + await utimes(path.join(src, f), t, t); + await utimes(path.join(dest, f), t, t); + } + await utimes(path.join(src, "v1"), t, t); + await utimes(path.join(src, "v2"), t, t); + await utimes(src, t, t); + await utimes(dest, t, t); + const lines: string[] = []; + await copyMirrorVerify({ rsyncBin: "rsync", src, dest, live: src, cancelled, reconcile: true, log: (m) => lines.push(m) }); + const said = lines.find((l) => l.startsWith("Reconciling:")) ?? ""; + assert.match(said, /content already matches the source; 2 directories differ only in mtime \(v1\/, v2\/\)/); + assert.doesNotMatch(said, /\d+ changed/); + assert.equal((await stat(path.join(dest, "v1"))).mtimeMs, t.getTime(), "the mirror pass settled them"); + }); }); diff --git a/common/controller/relocateDir.ts b/common/controller/relocateDir.ts @@ -382,12 +382,15 @@ function driftLines(output: string): string[] { // The differences a verify's dry run reports, sorted into what the operator can // act on: a path the destination has and the source does not ("extra on the // destination" — the realcandaceo scratch dir), one the destination lacks -// ("missing on the destination"), and one both have that differs ("changed", -// a directory's timestamp included). Paths are relative to the tree. +// ("missing on the destination"), and one both have that differs ("changed"). +// A directory whose only difference is its modification time (DIR_MTIME_ONLY) +// is no content in question and is counted apart ("differ only in mtime"), as +// the verify treats it (release 29 D1). Paths are relative to the tree. export type CopyDifferences = { extra: string[]; missing: string[]; changed: string[]; + mtimeOnly: string[]; }; // rsync's itemize line is `YXcstpoguax path`: Y the update type, X the file @@ -395,9 +398,11 @@ export type CopyDifferences = { // does not exist on the receiving side yet. A deletion is `*deleting path`. // Anything else (a warning rsync printed) is reported whole, as changed. export function classifyDrift(lines: ReadonlyArray<string>): CopyDifferences { - const out: CopyDifferences = { extra: [], missing: [], changed: [] }; + const out: CopyDifferences = { extra: [], missing: [], changed: [], mtimeOnly: [] }; for (const line of lines) { - if (line.startsWith("*deleting")) { + if (DIR_MTIME_ONLY.test(line)) { + out.mtimeOnly.push(line.replace(/^\S+\s+/, "")); + } else if (line.startsWith("*deleting")) { out.extra.push(line.replace(/^\S+\s+/, "")); } else if (/^[<>ch.][fdLDS]\+{5,}\s/.test(line)) { out.missing.push(line.replace(/^\S+\s+/, "")); @@ -410,25 +415,31 @@ export function classifyDrift(lines: ReadonlyArray<string>): CopyDifferences { return out; } -function countDifferences(d: CopyDifferences): number { +// What differs in content: a directory's timestamp alone is not counted. +function countContentDifferences(d: CopyDifferences): number { return d.extra.length + d.missing.length + d.changed.length; } +const paths5 = (n: string[]) => `${n.slice(0, 5).join(", ")}${n.length > 5 ? `, … ${n.length - 5} more` : ""}`; + +// "N directories differ only in mtime (v1/, v2/)", or "" for none. +export function describeMtimeOnly(d: Pick<CopyDifferences, "mtimeOnly">): string { + const n = d.mtimeOnly?.length ?? 0; + if (n === 0) return ""; + return `${n} ${n === 1 ? "directory differs" : "directories differ"} only in mtime (${paths5(d.mtimeOnly)})`; +} + // "2 extra on the destination (v1/.x/meta.json, v1/.x/win-0000.json), 0 // missing on the destination, 1 changed (v2/transcript.json)" — at most five -// paths of each kind, the rest counted. +// paths of each kind, the rest counted — and, when there are any, "and 3 +// directories differ only in mtime (…)". export function describeDifferences(d: CopyDifferences): string { - const kind = (n: string[], words: string) => { - if (n.length === 0) return `0 ${words}`; - const shown = n.slice(0, 5).join(", "); - const more = n.length > 5 ? `, … ${n.length - 5} more` : ""; - return `${n.length} ${words} (${shown}${more})`; - }; - return [ - kind(d.extra, "extra on the destination"), - kind(d.missing, "missing on the destination"), - kind(d.changed, "changed"), - ].join(", "); + const kind = (n: string[], words: string) => (n.length === 0 ? `0 ${words}` : `${n.length} ${words} (${paths5(n)})`); + const mtime = describeMtimeOnly(d); + return ( + [kind(d.extra, "extra on the destination"), kind(d.missing, "missing on the destination"), kind(d.changed, "changed")].join(", ") + + (mtime ? `, and ${mtime}` : "") + ); } // A verify that the second mirror pass did not settle. Carries the differences @@ -590,11 +601,14 @@ export async function copyMirrorVerify(opts: { if (opts.reconcile) { const before = await diffTrees({ rsyncBin, src, dest, log, signal }); log( - countDifferences(before) === 0 - ? "Reconciling: the destination copy already matches the source." - : `Reconciling: the destination copy differs from the source — ` + + countContentDifferences(before) > 0 + ? `Reconciling: the destination copy differs from the source — ` + `${describeDifferences(before)}. The mirror pass makes it match ` + - `the source; the source is not changed.`, + `the source; the source is not changed.` + : before.mtimeOnly.length > 0 + ? `Reconciling: the destination copy's content already matches the source; ` + + `${describeMtimeOnly(before)}, which the mirror pass settles. The source is not changed.` + : "Reconciling: the destination copy already matches the source.", ); } else { const { exitCode } = await rsyncTree({ @@ -769,6 +783,7 @@ async function verifyMirrored(opts: { ...differences.extra, ...differences.missing, ...differences.changed, + ...differences.mtimeOnly, ][0]; throw new CopyVerificationError( `Verification failed: after a second mirror pass the copy still differs ` + diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -4,7 +4,7 @@ // // 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) +// youtube | social (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 @@ -26,7 +26,7 @@ // 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 +// youtube, social; 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 @@ -365,7 +365,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod 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)'); + if (out.entries && !isStepTask(out.task)) fail('"entries" is a media draft\'s (narrate, cut, onscreen, teaser, flips, threads, youtube, social)'); return out; } @@ -733,7 +733,8 @@ async function runReportDraft( case "teaser": case "flips": case "threads": - case "youtube": { + case "youtube": + case "social": { // A media draft: a step on the done iteration n (./tasks/media.ts). const step = { article: body.article, diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -79,7 +79,7 @@ test("research (S11): a route of its own, a file from before it keeps its preset }); 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"]); + assert.deepEqual([...MEDIA_STEP_TASKS], ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"]); for (const t of MEDIA_STEP_TASKS) { assert.ok(isStepTask(t)); assert.ok((GENERATION_TASKS as readonly string[]).includes(t)); @@ -103,6 +103,13 @@ test("the media drafts (release 28): steps, each with narrate's route in every p 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"); + // A file from release 28 (every task but social, release 29 G2) keeps its preset; social takes its route. + for (const p of ["code", "balanced", "api", "local"] as const) { + const { social: _s, ...r28 } = GENERATION_PRESETS[p]; + const old = sanitizeGeneration({ routes: r28 }); + assert.equal(old.preset, p); + assert.equal(old.routes.social, GENERATION_PRESETS[p].narrate); + } }); test("cut (release 28 M1): the most entries a drafted cut keeps, 20 by default, a whole number from 3", () => { diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -14,14 +14,14 @@ import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, type Autonomy } from "./report/dra // 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 const MEDIA_STEP_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"] 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); // `verdicts` (release 29 M8): verdict proposals for a fact-check's unruled // claims — no iteration, no step: a sidecar beside the article, and only on a // model in `verdicts.models` (the bench's bar). -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "verdicts"] as const; +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts"] 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"]; @@ -30,7 +30,7 @@ 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; +const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const; export const GENERATION_PRESETS = { code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code" }, @@ -181,6 +181,7 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { 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.", + social: "A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code.", verdicts: "Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.", }; diff --git a/common/lib/report/draft/tasks/deckOption.test.ts b/common/lib/report/draft/tasks/deckOption.test.ts @@ -0,0 +1,149 @@ +// Draft everything's deck option (release 29 G1), the common side: a cut the +// converter made has no deck, so flips and threads have nothing to draw on +// (draftPrecheck skips them, the tasks refuse). umtool's deck step adds the +// minimal deck through its manifest writer (manifest.mjs addDeckChrome, with +// chain-draft.mjs deckChrome — loaded from the checkout, as deckChecks loads +// report-to-video); then the flips and the threads draft on that cut over the +// fake ollama, with the synthetic corpus's upload dates. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, 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 { flips } from "./flips"; +import { threads } from "./threads"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const UMTOOL = new URL("../../../../../umtool/lib/report/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +type DeckStep = { + addDeckChrome: (dir: string, chrome: Record<string, unknown>) => Promise<{ added: boolean }>; + deckChrome: () => Record<string, unknown>; + draftPrecheck: (task: string, manifest: unknown) => string | null; +}; + +let tmp: string; +let ol: FakeOllama; +let umtool: DeckStep; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "deck-option-")); + ol = await startFakeOllama(); + const manifest = await import(new URL("manifest.mjs", UMTOOL).href); + const chainDraft = await import(new URL("chain-draft.mjs", UMTOOL).href); + umtool = { addDeckChrome: manifest.addDeckChrome, deckChrome: chainDraft.deckChrome, draftPrecheck: chainDraft.draftPrecheck }; +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +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; +// The kit's basic report and the cut the converter makes of it (no render.chrome). +async function convertedCut() { + 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 }); + const manifest = await kit("manifests/basic.video.manifest.json"); + assert.equal(manifest.render.chrome, undefined, "the converter's cut has no deck"); + 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 deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus, + cuesOf: async () => null, + paths, + log: () => {}, + now: () => new Date("2026-10-15T12:00:00.000Z"), + }; + const input = { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + return { dir, deps, input, manifestNow }; +} + +test("a converted cut: no deck, the flips refused; the deck step adds the minimal deck (a snapshot first), then the flips draft", async () => { + const p = await convertedCut(); + assert.match(umtool.draftPrecheck("flips", await p.manifestNow()) ?? "", /no on-screen deck/); + const refused = await flips(p.input, p.deps); + assert.equal(refused.status, "failed"); + + const r = await umtool.addDeckChrome(p.dir, umtool.deckChrome()); + assert.equal(r.added, true); + const m = await p.manifestNow(); + assert.deepEqual(m.render.chrome, { engine: "hyperframes", layout: "deck", deck: {} }); + assert.equal(umtool.draftPrecheck("flips", m), null); + assert.ok((await readdir(path.join(p.dir, "revisions"))).some((f) => f.includes("auto-before-deck")), "the cut before the deck is kept"); + + ol.push(jsonReply({ pairs: [{ topic: "The bakery", then: "c01", now: "c04" }] })); + const res = await flips(p.input, p.deps); + assert.equal(res.status, "done", res.summary); + const after = await p.manifestNow(); + assert.equal(after.render.chrome.flips.pairs.length, 1); + assert.equal(after.render.chrome.flips.pairs[0].then.entry, "c01"); + assert.equal(after.render.chrome.flips.pairs[0].now.entry, "c04"); + assert.equal(after.drafted["render.chrome.flips"].task, "flips"); +}); + +test("the deck step on a cut with a deck leaves it as it is; the threads draft on a converted cut given the deck", async () => { + const p = await convertedCut(); + assert.equal((await umtool.addDeckChrome(p.dir, umtool.deckChrome())).added, true); + const once = await readFile(path.join(p.dir, "video.manifest.json"), "utf8"); + assert.equal((await umtool.addDeckChrome(p.dir, umtool.deckChrome())).added, false); + assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), once, "byte for byte"); + + ol.push( + jsonReply({ + 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" }, + ], + }), + ); + const res = await threads(p.input, p.deps); + assert.equal(res.status, "done", res.summary); + const m = await p.manifestNow(); + assert.deepEqual(m.render.chrome.threads.list.map((t: { id: string }) => t.id), ["bakery", "contest"]); + assert.equal(m.timeline.find((e: { id: string }) => e.id === "c05").thread, "contest"); +}); + +test("a cut whose deck the operator set is never touched by the deck step", async () => { + const p = await convertedCut(); + const m = await p.manifestNow(); + m.render.chrome = { engine: "hyperframes", layout: "deck", deck: { height: 200 } }; + await writeFile(path.join(p.dir, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + const before = await readFile(path.join(p.dir, "video.manifest.json"), "utf8"); + assert.equal((await umtool.addDeckChrome(p.dir, umtool.deckChrome())).added, false); + assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), before); +}); diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -17,6 +17,7 @@ import { TaskInputError, runOnIteration } from "./run"; import { threads } from "./threads"; import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types"; import { youtube } from "./youtube"; +import { social } from "./social"; import { refresh, type RefreshInput } from "../refresh/task"; export * from "./types"; @@ -55,6 +56,8 @@ export { 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"; +// Release 29 G2: the promotion text for X and Bluesky. +export { social, SOCIAL_SPEC, postBudget, postProblems, type SocialInput, type SocialValue } from "./social"; 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"; @@ -103,6 +106,8 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { return threads(input, deps); case "youtube": return youtube(input, deps); + case "social": + return social(input, deps); case "cut": return cut(input, deps); case "onscreen": diff --git a/common/lib/report/draft/tasks/social.test.ts b/common/lib/report/draft/tasks/social.test.ts @@ -0,0 +1,206 @@ +// The social posts (release 29 G2): the counts are code's — X 280 with every +// URL weighed as 23 (and an emoji as 2), Bluesky 300 graphemes — the link is +// code's (appended under the first post: the video's URL, else a public +// article's page, else none), and the checks refuse a post that speaks as the +// speaker, names what the report does not, quotes words nobody said, or +// carries a link, a hashtag or an @mention. The fake ollama answers, scripted +// by the kit's recorded run (runs/social.json) or inline. + +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 { PROJECT_URL } from "../../../project"; +import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; +import { blueskyLength, graphemes, SOCIAL_LIMITS, socialLinkOf, validateSocialPost, withLink, xLength } from "../../social.mjs"; +import { groundingInputOf } from "../grounding"; +import type { DraftFile } from "./media"; +import { postBudget, postProblems, social, socialSystem } from "./social"; +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(), "social-task-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +// ─── the counts (social.mjs) ─── + +test("X weighs a URL as 23 whatever its length, an emoji as 2, a CJK character as 2; a URL-heavy post at the limit", () => { + assert.equal(xLength("hello"), 5); + assert.equal(xLength("https://example.com/a/very/long/path/that/goes/on/and/on?with=query&and=more"), 23); + assert.equal(xLength("see www.example.org/x now"), 4 + 23 + 4); + assert.equal(xLength("🙂"), 2); + assert.equal(xLength("👩‍👩‍👧‍👦"), 2, "a family is one emoji"); + assert.equal(xLength("日本"), 4); + // Three long links and the text between them: 205 + 3 × (1 + 23) + 3 = 280, at the limit. + const link = (i: number) => `https://archive.example/moment/${"x".repeat(60)}/${i}`; + const text = `${"a".repeat(205)} ${link(1)} ${link(2)} ${link(3)} bb`; + assert.equal(xLength(text), 280); + assert.ok(text.length > 400, "far longer than 280 as written"); + assert.deepEqual(validateSocialPost("x", { post: text }), []); + assert.deepEqual(validateSocialPost("x", { post: `${text}b` }), ["publish.x.post is 281 characters as X counts them (at most 280)"]); +}); + +test("Bluesky counts graphemes: an emoji-heavy post is counted by what a reader sees", () => { + const family = "👨‍👩‍👧"; + assert.equal(family.length, 8, "eight UTF-16 units"); + assert.equal(graphemes(family).length, 1); + assert.equal(blueskyLength(`${family} ok`), 4); + assert.equal(blueskyLength("é"), 1, "a decomposed accent normalised"); + const post = `${"🧁".repeat(150)}${"👍🏽".repeat(150)}`; + assert.equal(blueskyLength(post), 300); + assert.deepEqual(validateSocialPost("bluesky", { post }), []); + assert.deepEqual(validateSocialPost("bluesky", { post: `${post}!` }), ["publish.bluesky.post is 301 graphemes (at most 300)"]); + assert.ok(post.length > 600); +}); + +test("the link: the video's URL first, else the article's page, else none; under the post after a blank line", () => { + const article = `${PROJECT_URL}/articles/a/`; + assert.equal(socialLinkOf({ publish: { videoUrl: "https://video.example/v/1" } }, { articleUrl: article }), "https://video.example/v/1"); + assert.equal(socialLinkOf({ publish: { videoUrl: "not a url" } }, { articleUrl: article }), article); + assert.equal(socialLinkOf({}, {}), null); + assert.equal(withLink(" The post. ", article), `The post.\n\n${article}`); + assert.equal(withLink("The post.", null), "The post."); + // The budget the prompt names leaves the link's room: 280 − (2 + 23) on X. + assert.equal(postBudget("x", article), 255); + assert.equal(postBudget("bluesky", article), 300 - 2 - article.length); + assert.equal(postBudget("x", null), 280); + const s = socialSystem("x", 255, true); + assert.match(s, /at most 255 characters; a link to the video is added under it/); + assert.doesNotMatch(s, /https?:\/\//, "rules, no example"); +}); + +test("the checks: third person, grounded, quotes only verbatim, no link, hashtag, mention or emoji; the first post counted with its link", async () => { + const report = await kit("reports/basic.report.json"); + const u = { platform: "x" as const, link: `${PROJECT_URL}/articles/synth-basic/`, g: groundingInputOf(report) }; + assert.deepEqual(postProblems("Synth Kitchen's baker says she paid for the new mixer herself.", u, "the post", true).hard, []); + const hard = (t: string) => postProblems(t, u, "the post", true).hard.join(" | "); + assert.match(hard("I think the baker would never sell."), /the narrator is third person/); + assert.match(hard("The baker told Gordon she would never sell."), /Gordon/); + assert.match(hard('The baker says "I will sell the bakery" now.'), /is not what a cited clip says, word for word/); + assert.match(hard("Synth Kitchen's baker on the bakery: https://synth.example"), /no links, timestamps, hashtags or @mentions/); + assert.match(hard("Synth Kitchen's baker on the bakery #bread"), /no links, timestamps, hashtags or @mentions/); + assert.match(hard("Synth Kitchen's baker on the bakery @synthkitchen"), /no links, timestamps, hashtags or @mentions/); + assert.match(hard("Synth Kitchen's baker on the bakery 🍞"), /no emoji/); + // 255 characters fit beside the link; 256 do not. + const words = (n: number) => `Synth Kitchen's baker says she paid for the new mixer herself${".".repeat(n - 61)}`; + assert.equal(words(255).length, 255); + assert.doesNotMatch(hard(words(255)), /characters as X counts/); + assert.match(hard(words(256)), /the post is 281 characters as X counts them with its link \(at most 280\)/); + assert.equal(SOCIAL_LIMITS.thread, 4); +}); + +// ─── the task, over the kit ─── + +let caseN = 0; +async function project(o: { publicArticle?: boolean; videoUrl?: string } = {}) { + 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); + if (o.publicArticle) { + await writeFile(path.join(paths.articlesDir, "synth-basic", "report.json"), JSON.stringify({ ...report, audience: "public" })); + await writeFile(path.join(paths.articlesDir, "index.json"), JSON.stringify({ published: ["synth-basic"] })); + } + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + const manifest = await kit("manifests/basic.video.manifest.json"); + if (o.videoUrl) manifest.publish = { videoUrl: o.videoUrl }; + 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-15T12:00:00.000Z"), + }; + const input = { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draftNow = async () => JSON.parse(await readFile(path.join(dir, "social-draft.json"), "utf8")) as DraftFile; + return { dir, deps, lines, input, manifestNow, draftNow }; +} + +test("the recorded run: X's first answer refused and re-asked, Bluesky's kept; no link for a private article, said in the log", async () => { + const run = await kit("runs/social.json"); + const p = await project(); + ol.push(...run.turns); + const res = await social(p.input, p.deps); + assert.equal(res.status, "done", res.summary); + const m = await p.manifestNow(); + assert.deepEqual(m.publish.x, { + post: 'Synth Kitchen\'s baker says "I would never sell the bakery to a chain" and that she paid for the new mixer herself.', + thread: ["In a later stream she says she did not enter the contest this year.", "She will not talk about the lease."], + }); + assert.equal(m.publish.bluesky.thread.length, 1); + assert.equal(m.drafted["publish.x"].task, "social"); + assert.equal(m.drafted["publish.x"].attempt, 2); + assert.equal(m.drafted["publish.bluesky"].attempt, 1); + assert.ok(p.lines.some((l) => /no link: the manifest has no publish\.videoUrl and "synth-basic" is not a public article/.test(l)), p.lines.join("\n")); + const d = await p.draftNow(); + const firstX = (d.units.x as { attempts: { hard: string[] }[] }).attempts[0]!.hard.join(" | "); + assert.match(firstX, /the narrator is third person/); + assert.match(firstX, /no links, timestamps, hashtags or @mentions/); + // The request carried rules, never the link nor an example. + const ask = ol.requests.at(-3) as { messages: { role: string; content: string }[] }; + assert.doesNotMatch(ask.messages[0]!.content, /https?:\/\//); +}); + +test("the link appended by code: a public article's page on the homepage, else the video's URL the manifest names", async () => { + const pub = await project({ publicArticle: true }); + ol.push( + jsonReply({ post: "Synth Kitchen's baker says she paid for the new mixer herself.", thread: [] }), + jsonReply({ post: "Synth Kitchen's baker says she paid for the new mixer herself.", thread: [] }), + ); + assert.equal((await social(pub.input, pub.deps)).status, "done"); + const page = `${PROJECT_URL}/articles/synth-basic/`; + const m = await pub.manifestNow(); + assert.equal(m.publish.x.post, `Synth Kitchen's baker says she paid for the new mixer herself.\n\n${page}`); + assert.equal(m.publish.x.thread, undefined, "no thread: the key is left out"); + assert.ok(m.publish.bluesky.post.endsWith(`\n\n${page}`)); + // The system prompt named the budget the link leaves. + const sys = (ol.requests.at(-2) as { messages: { content: string }[] }).messages[0]!.content; + assert.match(sys, /at most 255 characters/); + + const vid = await project({ publicArticle: true, videoUrl: "https://video.example/watch/1" }); + ol.push( + jsonReply({ post: "Synth Kitchen's baker says she paid for the new mixer herself.", thread: [] }), + jsonReply({ post: "Synth Kitchen's baker says she paid for the new mixer herself.", thread: [] }), + ); + assert.equal((await social(vid.input, vid.deps)).status, "done"); + assert.ok((await vid.manifestNow()).publish.x.post.endsWith("\n\nhttps://video.example/watch/1")); +}); + +test("a post over its count with its link is trimmed at a sentence; a failing thread post dropped; five thread posts refused, then cut to four", async () => { + const p = await project({ publicArticle: true }); + const long = "Synth Kitchen's baker says she would not sell the bakery to a chain.".padEnd(240, " ") + " She says she paid for the new mixer herself."; + const bad = { post: long.replace(/\s{2,}/g, " ") + " She says she did not enter the contest this year.", thread: ["The bakery.", "I think so.", "The mixer.", "The contest.", "The lease."] }; + ol.push(jsonReply(bad), jsonReply(bad), jsonReply({ post: "Synth Kitchen's baker says she paid for the new mixer herself.", thread: [] })); + const res = await social(p.input, p.deps); + assert.equal(res.status, "done", res.summary); + const m = await p.manifestNow(); + assert.ok(xLength(m.publish.x.post) <= 280); + assert.ok(m.publish.x.post.startsWith("Synth Kitchen's baker says she would not sell the bakery to a chain.")); + assert.deepEqual(m.publish.x.thread, ["The bakery.", "The mixer.", "The contest.", "The lease."]); + const d = await p.draftNow(); + const hard = (d.units.x as { attempts: { hard: string[] }[] }).attempts[0]!.hard.join(" | "); + assert.match(hard, /the thread has 5 posts \(at most 4\)/); + assert.match(hard, /thread post 2: .*the narrator is third person/); +}); diff --git a/common/lib/report/draft/tasks/social.ts b/common/lib/report/draft/tasks/social.ts @@ -0,0 +1,176 @@ +// TASK social — the promotion text for X and Bluesky (release 29 G2): +// `publish.x` and `publish.bluesky`, each `{ post, thread? }`. TEXT ONLY: +// nothing posts it. A STEP on a done iteration, on the media task scaffold +// (./media.ts): one unit per platform. +// +// The model writes a first post and up to SOCIAL_LIMITS.thread short posts +// under it. CODE does the rest: +// - the LINK is code's: appended under the first post (social.mjs +// `withLink`): the video's public URL when the manifest has one +// (`publish.videoUrl`), else the article's page on the homepage when the +// article is published there and public; else none (said in the log). The +// model never writes a URL; +// - the COUNTS are code's (social.mjs): X 280 with every URL weighed as 23 +// and an emoji as 2; Bluesky 300 graphemes. The first post is counted +// with its link; +// - grounded (./grounding.ts via ./clipEvidence.ts checkLine): every name +// and number is the evidence's (the report and the cut's title, as the +// YouTube text's); 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, hashtags, @mentions, timestamps or emoji in what the model +// writes. +// A post past its count, or a thread post failing a check, is repaired by +// dropping sentences or thread posts (never rewriting); the better of two +// attempts is kept. + +import { PROJECT_URL } from "../../../project"; +import { readArticleState } from "../../registry"; +import { ARTICLES_REPORTS_BASE } from "../../routes"; +import { SOCIAL_LIMITS, SOCIAL_NAMES, socialLength, socialLinkOf, withLink, type SocialPlatform, type SocialPost } from "../../social.mjs"; +import { reportPagePath } from "../../views"; +import { sentencesOf, type GroundingInput } from "../grounding"; +import { checkLine } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; +import { evidenceOf } from "./youtube"; + +export type SocialInput = MediaTaskInput; +/** What the model writes (no link): the first post and the thread under it. */ +export type SocialValue = { post: string; thread: string[] }; + +type SocialUnit = MediaUnit & { platform: SocialPlatform; link: string | null; g: GroundingInput; evidence: string }; + +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); +// What the model may not write: a link, a timestamp, a hashtag, an @mention. +const NOT_WRITTEN = /https?:\/\/|www\.|\b\d{1,2}:\d{2}\b|(^|\s)#\w|(^|\s)@\w/; +const EMOJI = /\p{Extended_Pictographic}/u; + +/** Room the link takes under the first post (its blank line included). */ +export function linkRoom(platform: SocialPlatform, link: string | null): number { + return link ? socialLength(platform, withLink("", link)) : 0; +} + +/** The first post's limit before its link. */ +export const postBudget = (platform: SocialPlatform, link: string | null) => SOCIAL_LIMITS[platform] - linkRoom(platform, link); + +const unitLabel = (p: SocialPlatform) => `${SOCIAL_NAMES[p]} post`; + +/** One post's problems (`first`: counted with the link under it). */ +export function postProblems(text: string, u: Pick<SocialUnit, "platform" | "link" | "g">, where: string, first: boolean): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (!text) hard.push(`${where}: empty`); + const limit = SOCIAL_LIMITS[u.platform]; + const n = socialLength(u.platform, first ? withLink(text, u.link) : text); + if (n > limit) hard.push(`${where} is ${n} ${u.platform === "bluesky" ? "graphemes" : "characters as X counts them"}${first && u.link ? " with its link" : ""} (at most ${limit})`); + if (NOT_WRITTEN.test(text)) hard.push(`${where}: no links, timestamps, hashtags or @mentions — the link is added after it`); + if (EMOJI.test(text)) hard.push(`${where}: no emoji`); + const r = text ? checkLine(text, u.g, { quotes: true }) : { hard: [], soft: [] }; + return { hard: [...hard, ...r.hard.map((h) => `${where}: ${h}`)], soft: r.soft.map((s) => `${where}: ${s}`) }; +} + +export function socialSystem(platform: SocialPlatform, budget: number, hasLink: boolean): string { + const name = SOCIAL_NAMES[platform]; + const counted = platform === "x" ? "characters" : "characters (emoji and accented letters count as one)"; + return ( + `You write a post for ${name} that promotes a short evidence video made from a cited report, and optionally a short ` + + `thread under it. Rules: (1) the first post is at most ${budget} ${counted}${hasLink ? "; a link to the video is added under it after you write it" : ""}; ` + + `(2) the thread is 0 to ${SOCIAL_LIMITS.thread} more posts, each at most ${SOCIAL_LIMITS[platform]} characters, each adding a finding the ` + + "first post does not; (3) plain and specific, no clickbait, no all-caps; (4) third person: you describe what the speaker " + + "said, never as the speaker (no I, me, my, we, us or our outside quotation marks); (5) every name and number comes from " + + "the evidence, and nothing goes beyond it; (6) words in quotation marks only when a quote below says them word for word; " + + "(7) no links, hashtags, @mentions, timestamps or emoji." + ); +} + +/** The article's page on the homepage, when the article is published there and public; else null. */ +async function articleUrlOf(ctx: MediaContext<SocialInput>): Promise<string | null> { + const state = await readArticleState(ctx.input.article, ctx.handle.paths).catch(() => null); + if (!state?.exists || !state.published || state.audience !== "public") return null; + return `${PROJECT_URL.replace(/\/+$/, "")}${reportPagePath(ctx.input.article, ARTICLES_REPORTS_BASE)}`; +} + +// The first post cut to its budget at a sentence, its failing sentences +// dropped; the thread's failing posts dropped and the rest kept to the limit. +function trimmed(v: SocialValue, u: SocialUnit): SocialValue | null { + const kept: string[] = []; + for (const s of sentencesOf(v.post)) { + if (postProblems(s, u, "the post", false).hard.length) continue; + if (postProblems([...kept, s].join(" "), u, "the post", true).hard.length) break; + kept.push(s); + } + const post = kept.join(" "); + if (!post) return null; + const thread = v.thread.filter((t) => !postProblems(t, u, "a thread post", false).hard.length).slice(0, SOCIAL_LIMITS.thread); + return { post, thread }; +} + +const valueProblems = (v: SocialValue, u: SocialUnit) => { + const first = postProblems(v.post, u, "the post", true); + const hard = [...first.hard]; + const soft = [...first.soft]; + if (v.thread.length > SOCIAL_LIMITS.thread) hard.push(`the thread has ${v.thread.length} posts (at most ${SOCIAL_LIMITS.thread})`); + v.thread.forEach((t, i) => { + const r = postProblems(t, u, `thread post ${i + 1}`, false); + hard.push(...r.hard); + soft.push(...r.soft); + }); + return { hard, soft }; +}; + +export const SOCIAL_SPEC: MediaTaskSpec<SocialUnit, SocialValue, SocialInput> = { + task: "social", + noun: "social post", + async units(ctx) { + const { text, g } = evidenceOf(ctx); + const link = socialLinkOf(ctx.manifest, { articleUrl: await articleUrlOf(ctx) }); + // Not a check (the model cannot fix it): said once in the log. + ctx.handle.log(link ? `the posts link ${link}` : `no link: the manifest has no publish.videoUrl and "${ctx.input.article}" is not a public article on the homepage`); + return (["x", "bluesky"] as const).map((platform) => ({ + id: platform, + target: { field: `publish.${platform}` }, + label: unitLabel(platform), + platform, + link, + g, + evidence: text, + })); + }, + schema: () => ({ + type: "object", + properties: { post: { type: "string" }, thread: { type: "array", items: { type: "string" } } }, + required: ["post", "thread"], + }), + system: (u) => socialSystem(u.platform, postBudget(u.platform, u.link), !!u.link), + user: (u) => `${u.evidence}\n\nWrite the ${SOCIAL_NAMES[u.platform]} post and its thread.`, + parse(answer) { + const a = answer as { post?: unknown; thread?: unknown } | null; + const clean = (s: unknown) => oneLine(s).replace(/^["“]+|["”]+$/g, ""); + return { + post: clean(a?.post), + thread: (Array.isArray(a?.thread) ? a.thread : []).map(clean).filter(Boolean), + }; + }, + check: (v, u) => valueProblems(v, u), + repair(attempts, u) { + let best: MediaAttempt<SocialValue> | null = null; + for (const a of attempts) { + if (!a.value) continue; + const v = trimmed(a.value, u); + if (!v) continue; + const again = valueProblems(v, u); + if (again.hard.length) continue; + if (!best || v.post.length + v.thread.join("").length > best.value!.post.length + best.value!.thread.join("").length) { + best = { value: v, hard: [], soft: [...again.soft, "trimmed: failing or overlong sentences and thread posts removed"] }; + } + } + return best; + }, + // The field: the first post with its link under it, and the thread when there is one. + toField: (v, u): SocialPost => ({ post: withLink(v.post, u.link), ...(v.thread.length ? { thread: v.thread } : {}) }), + describe: (v, u) => `${SOCIAL_NAMES[u.platform]}: ${v.post.slice(0, 100)}${v.post.length > 100 ? "…" : ""}${v.thread.length ? ` (+${v.thread.length} in the thread)` : ""}`, +}; + +export async function social(input: SocialInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(SOCIAL_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/youtube.ts b/common/lib/report/draft/tasks/youtube.ts @@ -71,8 +71,11 @@ export function youtubeSystem(): string { ); } -/** 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 } { +/** + * The evidence a title and summary may draw on, and its grounding (the cut's + * title and subtitle added). The social posts (./social.ts) draw on the same. + */ +export function evidenceOf(ctx: MediaContext<YoutubeInput>): { text: string; g: GroundingInput } { const r = ctx.report as { title?: string; summary?: string | null; diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts @@ -2,7 +2,7 @@ // 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 DraftedManifestField = "timeline" | "render.chrome.flips" | "render.chrome.threads" | "publish.youtube" | "publish.x" | "publish.bluesky"; export type DraftedField = DraftedEntryField | DraftedManifestField; /** Where a draft goes: an entry's field (`entry` an id), or the manifest's (`entry` absent or null). */ @@ -17,6 +17,7 @@ export const DRAFTED_ENTRY_FIELDS: Readonly<Record<DraftedEntryField, readonly s export const DRAFTED_MANIFEST_FIELDS: readonly DraftedManifestField[]; export const FIELD_TASKS: Readonly<Record<DraftedField, string>>; export const PROVENANCE_KEYS: readonly string[]; +export const PUBLISH_KEYS: readonly string[]; export const PUBLISH_YOUTUBE_LIMITS: Readonly<{ title: number; description: number }>; export function isEntryField(field: string): field is DraftedEntryField; diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs @@ -13,7 +13,7 @@ // 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" +// "publish.youtube", "publish.x", "publish.bluesky" }` ("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: @@ -28,6 +28,7 @@ // drafted is refused (`validateDrafted`). import { createHash } from "node:crypto"; +import { SOCIAL_PLATFORMS, validateSocialPost } from "./social.mjs"; /** The entry fields that may be drafted, and the entry types each is on (null: any). */ export const DRAFTED_ENTRY_FIELDS = Object.freeze({ @@ -37,7 +38,7 @@ export const DRAFTED_ENTRY_FIELDS = Object.freeze({ }); /** 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"]); +export const DRAFTED_MANIFEST_FIELDS = Object.freeze(["timeline", "render.chrome.flips", "render.chrome.threads", "publish.youtube", "publish.x", "publish.bluesky"]); /** * Each draftable field's own task: the one that drafts it, and the `<task>` of @@ -52,11 +53,16 @@ export const FIELD_TASKS = Object.freeze({ "render.chrome.flips": "flips", "render.chrome.threads": "threads", "publish.youtube": "youtube", + "publish.x": "social", + "publish.bluesky": "social", }); /** The keys of a provenance, in the order they are written. */ export const PROVENANCE_KEYS = Object.freeze(["task", "model", "at", "iteration", "attempt"]); +/** The keys `publish` may hold (release 29 G2 adds the social posts and the video's URL). */ +export const PUBLISH_KEYS = Object.freeze(["youtube", "x", "bluesky", "videoUrl"]); + /** `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 }); @@ -156,6 +162,7 @@ export function isEmptyField(field, v) { 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 (field === "publish.x" || field === "publish.bluesky") return !(isObj(v) && typeof v.post === "string" && v.post.trim()); if (Array.isArray(v)) return v.length === 0; if (isObj(v)) return Object.keys(v).length === 0; return false; @@ -496,14 +503,20 @@ export function validateDrafted(manifest) { 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"); + for (const k of ["youtube", ...SOCIAL_PLATFORMS]) { + if (isObj(manifest.publish[k]) && "drafted" in manifest.publish[k]) errors.push(`publish.${k}.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). + * `publish` (release 28; release 29 G2): what is published beside the video. + * `publish.youtube { title, description }`, two strings (M6 fills it); + * `publish.x` and `publish.bluesky` `{ post, thread? }` (the social task's: + * each post within its platform's count, ./social.mjs); `publish.videoUrl`, + * the video's public URL once it is up (the operator's: what a social post + * links, else the article's page). * * @param {any} manifest * @returns {string[]} @@ -511,9 +524,13 @@ export function validateDrafted(manifest) { export function validatePublish(manifest) { const p = manifest?.publish; if (p === undefined) return []; - if (!isObj(p)) return ["publish must be an object ({ youtube })"]; + if (!isObj(p)) return ["publish must be an object ({ youtube, x, bluesky, videoUrl })"]; const errors = []; - for (const k of Object.keys(p)) if (k !== "youtube" && k !== "drafted") errors.push(`publish.${k} is not a publish key (youtube)`); + for (const k of Object.keys(p)) if (!PUBLISH_KEYS.includes(k) && k !== "drafted") errors.push(`publish.${k} is not a publish key (${PUBLISH_KEYS.join(", ")})`); + if (p.videoUrl !== undefined && !(typeof p.videoUrl === "string" && /^https?:\/\/\S+$/i.test(p.videoUrl.trim()))) { + errors.push("publish.videoUrl must be the video's http(s) URL"); + } + for (const k of SOCIAL_PLATFORMS) if (p[k] !== undefined) errors.push(...validateSocialPost(k, p[k]).filter((e) => !e.endsWith(".drafted: the mark goes in the top-level drafted map"))); const y = p.youtube; if (y === undefined) return errors; if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"]; diff --git a/common/lib/report/drafted.test.ts b/common/lib/report/drafted.test.ts @@ -154,15 +154,32 @@ test("validateDrafted: a mark where no field may be drafted, or not a provenance 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 } }); + const bad = validatePublish({ publish: { youtube: { title: "a\nb", description: 3, tags: [] }, tiktok: 1 } }); assert.deepEqual(bad, [ - "publish.x is not a publish key (youtube)", + "publish.tiktok is not a publish key (youtube, x, bluesky, videoUrl)", "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 })"]); + assert.deepEqual(validatePublish({ publish: [] }), ["publish must be an object ({ youtube, x, bluesky, videoUrl })"]); +}); + +test("validatePublish (release 29 G2): the social posts within their platform's count, a thread of at most 4, the video's URL", () => { + const link = "https://archilyzer.example/articles/synth-basic/"; + assert.deepEqual(validatePublish({ publish: { x: { post: `A post.\n\n${link}` }, bluesky: { post: "A post.", thread: ["Two.", "Three."] }, videoUrl: "https://video.example/v/1" } }), []); + // X: a URL weighs 23 whatever its length, so 255 characters and a long link is 280. + assert.deepEqual(validatePublish({ publish: { x: { post: `${"a".repeat(255)}\n\n${link}${"z".repeat(80)}` } } }), []); + assert.deepEqual(validatePublish({ publish: { x: { post: `${"a".repeat(256)}\n\n${link}` } } }), ["publish.x.post is 281 characters as X counts them (at most 280)"]); + // Bluesky counts graphemes: 300 flags are 300, not 600 code points. + assert.deepEqual(validatePublish({ publish: { bluesky: { post: "🇫🇷".repeat(300) } } }), []); + assert.deepEqual(validatePublish({ publish: { bluesky: { post: "🇫🇷".repeat(301) } } }), ["publish.bluesky.post is 301 graphemes (at most 300)"]); + assert.deepEqual(validatePublish({ publish: { x: { post: "", thread: ["a", "b", "c", "d", "e"], tags: 1 }, videoUrl: "video" } }), [ + "publish.videoUrl must be the video's http(s) URL", + "publish.x.tags is not a social post field (post, thread)", + "publish.x.post must be a post (a string)", + "publish.x.thread has 5 posts (at most 4)", + ]); }); test("review addresses and keys: one address per field, a key that moves with the value", () => { diff --git a/common/lib/report/social.d.mts b/common/lib/report/social.d.mts @@ -0,0 +1,20 @@ +// Types for ./social.mjs (release 29 G2): how a post for X or Bluesky is +// counted, its link, and what `publish.x` / `publish.bluesky` may hold. + +export type SocialPlatform = "x" | "bluesky"; +/** `publish.x` / `publish.bluesky`: the first post (its link in it) and up to 4 more under it. */ +export type SocialPost = { post: string; thread?: string[] }; + +export const SOCIAL_PLATFORMS: readonly SocialPlatform[]; +export const SOCIAL_LIMITS: Readonly<{ x: number; bluesky: number; thread: number; urlWeight: number }>; +export const SOCIAL_NAMES: Readonly<Record<SocialPlatform, string>>; +export const SOCIAL_URL_RE: RegExp; + +export function graphemes(text: unknown): string[]; +export function xLength(text: unknown): number; +export function blueskyLength(text: unknown): number; +export function socialLength(platform: SocialPlatform, text: unknown): number; +export function socialLimit(platform: SocialPlatform): number; +export function withLink(post: unknown, link: string | null | undefined): string; +export function validateSocialPost(platform: SocialPlatform, v: unknown, where?: string): string[]; +export function socialLinkOf(manifest: unknown, o?: { articleUrl?: string | null }): string | null; diff --git a/common/lib/report/social.mjs b/common/lib/report/social.mjs @@ -0,0 +1,144 @@ +// SOCIAL PROMOTION TEXT (release 29 G2) — THE one copy of how a post for X or +// Bluesky is counted, what its link is, and what `publish.x` / +// `publish.bluesky` may hold. Text only: nothing here (or anywhere) posts. +// +// Plain JS (with ./social.d.mts) for the reason ./drafted.mjs is: the common +// task (TypeScript), the manifest's validators (drafted.mjs `validatePublish`), +// umtool's report-to-video composer and its page all count the same way. No +// node imports, so the page may import it. +// +// THE FIELD. `{ post, thread? }`: `post` the first post, and `thread` up to +// SOCIAL_LIMITS.thread more short posts under it. The link is in `post`: the +// social task APPENDS it in code (`withLink`), the model never writes one. +// +// THE COUNTS. X: 280, weighed as X weighs a post (twitter-text's v3 rules): +// every URL is 23 (t.co), an emoji 2, a character in the Latin and common +// punctuation ranges 1, any other 2. Bluesky: 300 GRAPHEMES (what a reader +// sees as one character: an emoji with its modifiers, a flag), the link +// counted as written. + +/** The platforms a social post is drafted for: X and Bluesky. */ +export const SOCIAL_PLATFORMS = Object.freeze(["x", "bluesky"]); + +/** Each platform's limit per post; `thread` the most posts under the first. */ +export const SOCIAL_LIMITS = Object.freeze({ x: 280, bluesky: 300, thread: 4, urlWeight: 23 }); + +/** What the page calls each platform. */ +export const SOCIAL_NAMES = Object.freeze({ x: "X", bluesky: "Bluesky" }); + +/** A URL as X sees one in a post (scheme, or a www. host). */ +export const SOCIAL_URL_RE = /\bhttps?:\/\/[^\s<>"]+|\bwww\.[^\s<>"]+\.[a-z]{2,}[^\s<>"]*/giu; + +const X_LIGHT = [ + [0, 4351], + [8192, 8205], + [8208, 8223], + [8242, 8247], +]; +const EMOJI = /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u; + +const segmenter = () => new Intl.Segmenter(undefined, { granularity: "grapheme" }); + +/** The graphemes of a text: what a reader counts as characters. */ +export function graphemes(text) { + return Array.from(segmenter().segment(String(text ?? "")), (s) => s.segment); +} + +/** How long a post is on X: 280 is the limit; a URL is 23, an emoji 2. */ +export function xLength(text) { + const t = String(text ?? "").normalize("NFC"); + let n = 0; + let at = 0; + const weigh = (s) => { + for (const g of graphemes(s)) { + if (EMOJI.test(g)) { + n += 2; + continue; + } + for (const ch of g) { + const cp = ch.codePointAt(0) ?? 0; + n += X_LIGHT.some(([lo, hi]) => cp >= lo && cp <= hi) ? 1 : 2; + } + } + }; + for (const m of t.matchAll(SOCIAL_URL_RE)) { + weigh(t.slice(at, m.index)); + n += SOCIAL_LIMITS.urlWeight; + at = (m.index ?? 0) + m[0].length; + } + weigh(t.slice(at)); + return n; +} + +/** How long a post is on Bluesky: its graphemes (300 is the limit). */ +export function blueskyLength(text) { + return graphemes(String(text ?? "").normalize("NFC")).length; +} + +/** A post's length as its platform counts it. */ +export function socialLength(platform, text) { + if (platform === "x") return xLength(text); + if (platform === "bluesky") return blueskyLength(text); + throw new Error(`no social platform "${platform}" (${SOCIAL_PLATFORMS.join(", ")})`); +} + +/** The limit of one post on a platform. */ +export const socialLimit = (platform) => SOCIAL_LIMITS[platform]; + +/** The post with its link under it (a blank line between); no link: the post. */ +export function withLink(post, link) { + const p = String(post ?? "").trim(); + return link ? `${p}\n\n${link}` : p; +} + +/** + * Every reason a `publish.<platform>` value cannot be published as it is + * (empty: it can). `where` names it in the sentences. + * + * @param {"x" | "bluesky"} platform + * @param {unknown} v + * @param {string} [where] + * @returns {string[]} + */ +export function validateSocialPost(platform, v, where = `publish.${platform}`) { + if (v === null || typeof v !== "object" || Array.isArray(v)) return [`${where} must be { post, thread? }`]; + const errors = []; + for (const key of Object.keys(v)) { + if (key === "drafted") errors.push(`${where}.drafted: the mark goes in the top-level drafted map`); + else if (key !== "post" && key !== "thread") errors.push(`${where}.${key} is not a social post field (post, thread)`); + } + const limit = socialLimit(platform); + const one = (text, at) => { + if (typeof text !== "string" || !text.trim()) { + errors.push(`${at} must be a post (a string)`); + return; + } + const n = socialLength(platform, text); + if (n > limit) errors.push(`${at} is ${n} ${platform === "bluesky" ? "graphemes" : "characters as X counts them"} (at most ${limit})`); + }; + one(v.post, `${where}.post`); + if (v.thread !== undefined) { + if (!Array.isArray(v.thread)) errors.push(`${where}.thread must be a list of posts`); + else { + if (v.thread.length > SOCIAL_LIMITS.thread) errors.push(`${where}.thread has ${v.thread.length} posts (at most ${SOCIAL_LIMITS.thread})`); + v.thread.forEach((t, i) => one(t, `${where}.thread[${i}]`)); + } + } + return errors; +} + +/** + * The link a social post carries: the video's public URL when the manifest + * has one (`publish.videoUrl`, the operator's), else the article's public + * page (`articleUrl`, the caller's: a public article's page on the homepage), + * else none. + * + * @param {any} manifest + * @param {{ articleUrl?: string | null }} [o] + * @returns {string | null} + */ +export function socialLinkOf(manifest, { articleUrl = null } = {}) { + const v = manifest?.publish?.videoUrl; + if (typeof v === "string" && /^https?:\/\/\S+$/i.test(v.trim())) return v.trim(); + return articleUrl && /^https?:\/\/\S+$/i.test(articleUrl) ? articleUrl : null; +} diff --git a/common/package.json b/common/package.json @@ -37,6 +37,7 @@ "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", "./lib/report/panels.mjs": "./lib/report/panels.mjs", + "./lib/report/social.mjs": "./lib/report/social.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/testing/README.md b/common/testing/README.md @@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | | `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | -| `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/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and diff --git a/common/testing/draft/runs/social.json b/common/testing/draft/runs/social.json @@ -0,0 +1,28 @@ +{ + "task": "social", + "model": "qwen3:8b", + "note": "Over the basic manifest and report, with no link (the article is not public on the homepage and the manifest has no publish.videoUrl). The X post's first answer is refused (it speaks as the speaker, writes a link and a hashtag) and re-asked; the second is kept. The Bluesky post is kept at the first answer.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"post\": \"I watched the baker of Synth Kitchen say she would never sell. Watch it at https://synth.example #bakery\", \"thread\": []}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"post\": \"Synth Kitchen's baker says \\\"I would never sell the bakery to a chain\\\" and that she paid for the new mixer herself.\", \"thread\": [\"In a later stream she says she did not enter the contest this year.\", \"She will not talk about the lease.\"]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"post\": \"What the baker of Synth Kitchen says about the bakery: she would not sell it to a chain, and she paid for the new mixer herself.\", \"thread\": [\"She says she did not enter the contest this year, and she will not talk about the lease.\"]}" + }, + "done": true + } + ] +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] - **A model can propose verdicts for a fact-check's unruled claims, for you to approve or reject.** `pnpm ops report-draft --json '{"task":"verdicts","article":"<id>"}'` asks each claim with no verdict, with the verdict bench's own prompt, and keeps each proposed verdict, its reason, the model and the prompt version in `verdicts.proposed.json` beside the article, never in `report.json`. It runs only on a model you ticked on the verdict bench (`settings.generation.verdicts.models`, empty until you do), and never sets a verdict itself. umtool's Inbox shows "N verdicts proposed" under Review; **Review verdicts** opens the article, where each proposal has **Approve** (the claim gets that verdict) and **Reject** (the claim stays unruled), with an optional note. A claim you have ruled, or whose proposal you have reviewed, is not asked again. `pnpm ops verdict-review` does the same from the command line. Needs a restart of the editor and umtool. +- **Draft everything can add the on-screen deck first.** Tick **with the deck** beside **Draft everything** on a cut's Media tab (or `umtool chain <article> <n> --draft-all --deck`): before the flips, a step adds the on-screen deck with every setting at its default to a cut that has none, so the flips and threads are drafted on a cut the converter made. A copy of the cut as it was is kept in its revisions first. A cut that already has a deck is left as it is, and the step says "deck added" or "deck already there". Off by default: without the tick, Draft everything is as it was. Needs a restart of umtool. +- **Posts for X and Bluesky, drafted for you to copy — never posted.** A new media draft, `social`, writes a post for X and one for Bluesky, each with up to four more posts under it, from the article's evidence: third person, every name and number from the report, quotation marks only around words a cited clip says, and no links, hashtags, @mentions or emoji of its own. The link under the first post is added by code: the video's URL when the cut's manifest has one (`publish.videoUrl`, yours to set once the video is up), else the article's page on the homepage when the article is public there. The lengths are counted as each platform counts them — on X a link is 23 and an emoji 2, at most 280; on Bluesky 300 characters as a reader sees them — and a post over it is cut at a sentence or refused, never sent long. The Media tab's **Social posts** shows each post with its counted length and **Copy**; every build that writes `out/youtube.txt` also writes `out/x.txt` and `out/bluesky.txt`, and Draft everything drafts them after the YouTube text. Draft it alone from the Media tab's **Social** row, `archilyzer gen run social --iteration <n>`, or `generate` in the MCP. It takes narration's route in every preset. Needs a restart of the editor and umtool. +- **The site picker no longer loses your place in the history, or lags under load.** Choosing another site on a site's own page could, now and then, replace the page you chose it on in the browser's history, so Back skipped it; and on a busy machine a new site could take seconds to show on Dashboard or Channels. The choice is now written first and the page then moves or re-renders, every time. Needs a restart of the editor. +- **The drive health timing on `/storage` says "Saved." at once** — it could wait about five seconds (the next automatic refresh), as Settings' save did before. Needs a restart of the editor. +- **A storage move's Reconcile and resume no longer calls a folder whose date alone differs "changed".** It says "N directories differ only in mtime" apart from what was added, missing or changed, and a reconcile with nothing else to settle says the copy's content already matches. +- **`generate`'s answer for a media draft names the video project first**, above the iteration's own files. - **The verdict bench asks to the operator's standard, and says which prompt it asked with.** What each verdict means is written once (`common/lib/report/verdicts.mjs`) and read by the bench's prompt, REPORT.md and umtool's bench page: CORROBORATED when the substance of the claim is shown by the cited words (framing, emphasis or a detail the transcript does not show does not demote it), PARTLY only when a part is shown overstated or wrong, and when in doubt between the two, CORROBORATED. The model now writes its reason before its verdict, and sees the report's title, the claim's section, and each cited line's speaker and recording date. Each run records its prompt version and a hash of its items; a run made before this is version 1, and a run is never resumed under another version. Needs a restart of the editor and umtool. - **`archilyzer reports bench-verdicts` takes `--items-from <run>`, `--window-mode seconds|turn` and a stratified `--limit`.** `--items-from vb-r28` asks the same items again (for example a local model on a new prompt, at no cost). `--window-mode turn` shows the cited speaker's turn instead of a fixed number of seconds either side, bounded by `--window`. `--limit` keeps every verdict the operator ruled, in proportion. A re-run of a run asks only the models it names, so a local-only re-run never asks a paid model again. A citation that gives no transcript is listed with its reason instead of being left out silently. `pnpm ops bench-verdicts` takes the same keys (`itemsFrom`, `windowMode`, `limit`). - **umtool's verdict bench compares runs and takes your marks.** `/tools/bench` shows each run's prompt version and items hash, and **compare with** lists the runs over the same items: each model's agreement in both and every claim whose answer changed. Each disagreement has **Right** and **Wrong** (was the model right?), kept beside the run, and the not-CORROBORATED precision and recall beside the bar are shown as ruled and with your marks, so the bar can be set from what you marked. "What the verdicts mean" lists the definitions. diff --git a/editor/app/api/active-site/route.ts b/editor/app/api/active-site/route.ts @@ -0,0 +1,55 @@ +import { cookies } from "next/headers"; +import { ACTIVE_SITE_COOKIE_MAX_AGE, isStorableActiveSite } from "../../lib/activeSite"; +import { activeSiteCookieForRequest } from "../../lib/activeSiteServer"; + +export const dynamic = "force-dynamic"; + +// THE ONE WRITER of the active-site cookie (see app/lib/activeSite.ts): POST +// `{ value }` from SiteScopeProvider — the picker's choice, a site's own page +// recording itself, the localStorage migration — answers `{ ok }`. +// +// A ROUTE, NOT A SERVER ACTION (release 29 D1). A cookie set in a server action +// makes Next re-render the page in the action's answer and apply it through +// the router — answered BEFORE that applies, so a navigation the caller made +// next (the picker on a site's page pushes the other site's) discarded the +// pending action and replayed it as a refresh after the push, and when React +// committed the two together the push's history entry was written as a +// replace (Back skipped the page the choice was made on); and under load the +// re-render waited on in-flight prefetches, so a re-scope came seconds late +// (site-scope.spec). Here the write is only a write: the provider refreshes, +// or the picker navigates, itself. +// +// Same-origin only (a cross-site page could otherwise flip an operator's +// scope): JSON, and an Origin, when sent, that is this host. The value is only +// SHAPE-checked (a site id or "__all__"): whether it names a configured site is +// decided at every read, so a site deleted later resolves as no selection. +export async function POST(request: Request): Promise<Response> { + const origin = request.headers.get("origin"); + const host = request.headers.get("host"); + if (origin !== null && (() => { + try { + return new URL(origin).host !== host; + } catch { + return true; + } + })()) { + return Response.json({ ok: false, error: "cross-origin" }, { status: 403 }); + } + if (!(request.headers.get("content-type") ?? "").startsWith("application/json")) { + return Response.json({ ok: false, error: "expected JSON" }, { status: 415 }); + } + const body = (await request.json().catch(() => null)) as { value?: unknown } | null; + const value = body?.value; + if (typeof value !== "string" || !isStorableActiveSite(value)) { + return Response.json({ ok: false, error: "not a site id or __all__" }, { status: 400 }); + } + const name = await activeSiteCookieForRequest(); + (await cookies()).set(name, value, { + path: "/", + sameSite: "lax", + maxAge: ACTIVE_SITE_COOKIE_MAX_AGE, + // Only the server reads it: the page gets it through the layout. + httpOnly: true, + }); + return Response.json({ ok: true }, { headers: { "cache-control": "no-store" } }); +} diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -20,7 +20,7 @@ export const dynamic = "force-dynamic"; // - "revise-report" / "revise-video": a new iteration revising `iteration` // from `feedback`; // - a media draft — "narrate", "cut", "onscreen", "teaser", "flips", -// "threads", "youtube" (release 28): a step on the done iteration +// "threads", "youtube" (release 28), "social" (release 29): 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`); diff --git a/editor/app/components/SiteScopeProvider.tsx b/editor/app/components/SiteScopeProvider.tsx @@ -17,7 +17,21 @@ import { isStorableActiveSite, siteIdFromPathname, } from "../lib/activeSite"; -import { setActiveSiteAction } from "../lib/activeSiteActions"; + +// The cookie's one writer (app/api/active-site/route.ts): true when it is set. +async function writeActiveSite(value: string): Promise<boolean> { + try { + const res = await fetch("/api/active-site", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ value }), + cache: "no-store", + }); + return res.ok && ((await res.json()) as { ok?: boolean }).ok === true; + } catch { + return false; + } +} // THE SITE SCOPE, supplied once by the root layout (see app/lib/activeSite.ts). // @@ -46,8 +60,8 @@ import { setActiveSiteAction } from "../lib/activeSiteActions"; // cookie gets it copied into the cookie, then the key is removed. That is the // only localStorage read, and the one paint it may cost is on the first visit // after the update. -// Both only WRITE the cookie (`record`); the value comes back through the -// server's re-render. They run as the page hydrates, and a state change there +// Both only WRITE the cookie (`record`), then refresh: the value comes back +// through the server's re-render. They run as the page hydrates, and a state change there // would re-render the picker before React replays a choice made on the // server-rendered select before hydration: the re-render resets the select to // its old value, and the replayed change reads that instead of the choice. @@ -56,10 +70,12 @@ type SiteScope = { // The stored selection: a site id or "__all__". The picker resolves it // against the path and a `?site=` param; it is not the effective scope alone. stored: string; - // Store a choice: shown at once, written through setActiveSiteAction. Resolves - // once the cookie is set (and the server has re-rendered with it) to true, or - // to false with the previous selection put back when the write failed. - choose: (value: string) => Promise<boolean>; + // Store a choice: shown at once, written through /api/active-site. Resolves + // once the cookie is set to true — the page then refreshes to re-render with + // it, unless `navigating` (the caller moves the URL itself, and the next page + // renders with the cookie) — or to false with the previous selection put + // back when the write failed. + choose: (value: string, o?: { navigating?: boolean }) => Promise<boolean>; }; const SiteScopeContext = createContext<SiteScope | null>(null); @@ -116,38 +132,35 @@ export function SiteScopeProvider({ } }, []); - const choose = useCallback(async (value: string): Promise<boolean> => { + const choose = useCallback(async (value: string, o: { navigating?: boolean } = {}): Promise<boolean> => { const previous = storedRef.current; storedRef.current = value; setStored(value); setWriting((n) => n + 1); - let ok = false; - try { - ok = await setActiveSiteAction(value); - } catch { - ok = false; - } + const ok = await writeActiveSite(value); setWriting((n) => n - 1); if (ok) { announce(value); + // The route only writes (no server action's implicit re-render): the + // page and the layout re-render with the cookie now — unless the caller + // navigates, whose next page does. + if (!o.navigating) router.refresh(); } else { storedRef.current = previous; setStored(previous); } return ok; - }, [announce]); + }, [announce, router]); // Write a value the page did not choose — no optimistic state (see above). const record = useCallback(async (value: string): Promise<boolean> => { - let ok = false; - try { - ok = await setActiveSiteAction(value); - } catch { - ok = false; + const ok = await writeActiveSite(value); + if (ok) { + announce(value); + router.refresh(); } - if (ok) announce(value); return ok; - }, [announce]); + }, [announce, router]); // Visiting a site's own page records it: once per arrival at that site's // pages (a re-run of the effect — StrictMode, Fast Refresh — does not write diff --git a/editor/app/components/SiteScopeSelect.tsx b/editor/app/components/SiteScopeSelect.tsx @@ -55,7 +55,7 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { // of the other site, or the family page for "All sites". The cookie is // written FIRST, so a page opened right after the URL moves reads it. setPending({ urlKey, value }); - if (!(await choose(value))) { + if (!(await choose(value, { navigating: true }))) { setPending(null); return; } @@ -67,15 +67,16 @@ export function SiteScopeSelect({ sites }: { sites: SiteScopeOption[] }) { return; } if (param === null) { - // The common case: the stored value is what shows, and the cookie write - // re-renders this page (Dashboard, Channels) in the new scope. + // The common case: the stored value is what shows, and the provider + // refreshes this page (Dashboard, Channels) in the new scope once the + // cookie is written. await choose(value); return; } // A `?site=` link's page: the choice replaces the link's scope, so the // param goes — after the cookie is written, so the new URL renders with it. setPending({ urlKey, value }); - if (!(await choose(value))) { + if (!(await choose(value, { navigating: true }))) { setPending(null); return; } diff --git a/editor/app/lib/activeSite.ts b/editor/app/lib/activeSite.ts @@ -7,7 +7,8 @@ // `SiteScopeProvider`; Dashboard and Channels read it through the same helper. // So the server renders the picker, and the scoped pages, with the stored // selection on the first paint — nothing is reconciled after it. It is written -// only by `setActiveSiteAction` (app/lib/activeSiteActions.ts). +// only by `POST /api/active-site` (app/api/active-site/route.ts; a server action +// until release 29), which SiteScopeProvider calls. // // A `?site=<id>` LINK still works: a valid param governs that one request (the // server pages read it from `searchParams`, the picker from the URL), and is not diff --git a/editor/app/lib/activeSiteActions.ts b/editor/app/lib/activeSiteActions.ts @@ -1,31 +0,0 @@ -"use server"; - -import { cookies } from "next/headers"; -import { - ACTIVE_SITE_COOKIE_MAX_AGE, - isStorableActiveSite, -} from "./activeSite"; -import { activeSiteCookieForRequest } from "./activeSiteServer"; - -// THE ONE WRITER of the active-site cookie (see ./activeSite.ts). Called by the -// picker's onChange, by SiteScopeProvider when a site's own page is visited, and -// once by its localStorage migration. Setting a cookie in a server action makes -// Next re-render the current page and its layouts with the new value, so the -// root layout hands the provider the new selection and Dashboard or Channels -// re-scope, with no refresh of our own. -// -// The value is only SHAPE-checked (a site id or "__all__"): whether it names a -// configured site is decided at every read, so a site deleted later resolves as -// no selection. Returns false, writing nothing, for anything else. -export async function setActiveSiteAction(value: string): Promise<boolean> { - if (!isStorableActiveSite(value)) return false; - const name = await activeSiteCookieForRequest(); - (await cookies()).set(name, value, { - path: "/", - sameSite: "lax", - maxAge: ACTIVE_SITE_COOKIE_MAX_AGE, - // Only the server reads it: the page gets it through the layout. - httpOnly: true, - }); - return true; -} diff --git a/editor/app/lib/activeSiteServer.ts b/editor/app/lib/activeSiteServer.ts @@ -13,7 +13,7 @@ import { // result to SiteScopeProvider; Dashboard and Channels call it with their // `searchParams.site`, which wins for that request when it names a site or // "__all__". Nothing is written here: a server component cannot set a cookie, -// and only setActiveSiteAction does. +// and only POST /api/active-site does. export type ActiveSiteRead = ResolvedActiveSite & { // The cookie's raw value, or null when the request carried none — which is // what tells the provider a visitor may still have the old localStorage key. diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts @@ -521,7 +521,12 @@ export async function saveHealthTimingsAction( return { ok: false, error: (e as Error).message, values }; } const t = applyHealthTimings(getSettings().storage.health); - revalidatePath("/storage"); + // NO revalidatePath here (release 29 D1, as saveSettingsAction since + // aaba3723): with it, the form's "Saved." waited on the client router + // applying the revalidated /storage tree, which a save made while the page's + // prefetches were in flight did only at the next AutoRefresh pulse + // (storage-locations.spec:723's late "timing saved"). The form refreshes the + // tree itself once the answer is in (HealthTimingForm). return { ok: true, note: diff --git a/editor/app/storage/components/HealthTimingForm.tsx b/editor/app/storage/components/HealthTimingForm.tsx @@ -1,6 +1,7 @@ "use client"; -import { useActionState } from "react"; +import { useActionState, useEffect } from "react"; +import { useRouter } from "next/navigation"; import { HEALTH_TIMING_BOUNDS, HEALTH_TIMING_DEFAULTS, @@ -40,6 +41,13 @@ export function HealthTimingForm({ stored }: { stored: StorageHealthSettings }) HealthTimingsResult | undefined, FormData >(saveHealthTimingsAction, undefined); + // A save answers first ("Saved. …"), THEN the page re-renders what reads the + // timings (the summary's count): the action does not revalidate, so its + // answer never waits on the router (saveHealthTimingsAction). + const router = useRouter(); + useEffect(() => { + if (state?.ok) router.refresh(); + }, [state, router]); const tuned = HEALTH_TIMING_FIELDS.filter((f) => stored[f.key] !== undefined).length; return ( diff --git a/editor/e2e/publish-lane.spec.ts b/editor/e2e/publish-lane.spec.ts @@ -101,10 +101,14 @@ test("enabled and started, the lane updates the index; a hold mid-stage stops th const [index] = await metasOf("publish-update-index"); expect(index.spec?.params?.runId).toMatch(/^lane-/); - // Hold the lane while that stage is in flight. + // Hold the lane while that stage is in flight. The hold is the lane's state + // (publishStatus): wait on THAT, then read the page fresh — the button's own + // re-render waits on the router applying the action's revalidated tree, + // which under load can come seconds late (release 29 D1). await page.getByRole("button", { name: "pause publishing" }).click(); + await expect.poll(async () => (await publishStatus(request)).lane.held, { timeout: 30_000 }).toBe(true); + await page.reload(); await expect(page.getByRole("button", { name: "resume publishing" })).toBeVisible(); - expect((await publishStatus(request)).lane.held).toBe(true); const settings = await readJson<{ publish?: { held?: boolean } }>(testPaths().settingsFile); expect(settings.publish?.held).toBe(true); // The stage is still queued behind the holder; let the holder go. @@ -126,10 +130,12 @@ test("enabled and started, the lane updates the index; a hold mid-stage stops th .toContain("no next stage dispatched"); expect(await metasOf("publish-build-site")).toEqual([]); - // Resume, then Drain: the runner finishes what it is doing and stops. + // Resume (waited on the lane's state, then the page read fresh), then Drain: + // the runner finishes what it is doing and stops. await page.getByRole("button", { name: "resume publishing" }).click(); + await expect.poll(async () => (await publishStatus(request)).lane.held, { timeout: 30_000 }).toBe(false); + await page.reload(); await expect(page.getByRole("button", { name: "pause publishing" })).toBeVisible(); - expect((await publishStatus(request)).lane.held).toBe(false); await page.getByRole("button", { name: "Drain publish lane" }).click(); await expect(async () => { await page.reload(); diff --git a/editor/e2e/site-scope.spec.ts b/editor/e2e/site-scope.spec.ts @@ -198,13 +198,17 @@ function pickerValues(page: Page): Promise<string[]> { ); } -// Hydrated = React has attached its props to the select. It is the one React -// internal this spec peeks at; there is no public signal. Effects follow it. +// Hydrated = the picker's `data-hydrated`, which its own effect stamps by a +// re-render: so every effect of the first commit has run by then — the site +// provider's above it too (its BroadcastChannel subscription, its visit +// record). React's props on the select (what this waited for before release +// 29 D1) come BEFORE those effects, and a tab that was "hydrated" that way +// could miss another tab's broadcast posted in the gap. async function hydrated(page: Page) { - await page.waitForFunction((selector) => { - const el = document.querySelector(selector); - return !!el && Object.keys(el).some((k) => k.startsWith("__reactProps")); - }, PICKER); + await page.waitForFunction( + (selector) => document.querySelector(selector)?.getAttribute("data-hydrated") === "true", + PICKER, + ); } // A hydration mismatch is logged by React in development; fail on any. diff --git a/editor/e2e/storage-locations.spec.ts b/editor/e2e/storage-locations.spec.ts @@ -677,14 +677,30 @@ test("evicting at any age needs the tick as well as the preview", async ({ // ARMED BY THE ANSWER, NOT BY THE CLICK. The action returns as soon as the // job is enqueued, so a gate flipped in the trigger would already be open - // here — which is the whole thing it exists to stop. + // here — which is the whole thing it exists to stop. Watched in the page, + // the moment it happens (release 29 D1): a check of "still disabled" just + // after the click raced a preview that answers at once on a small fixture. + await page.evaluate(() => { + const w = window as unknown as { __armedBeforeAnswer?: boolean | null }; + w.__armedBeforeAnswer = null; + const check = () => { + const button = [...document.querySelectorAll("button")].find((b) => b.textContent?.trim() === "Evict fetched windows"); + if (!button || button.disabled || w.__armedBeforeAnswer !== null) return; + const said = document.querySelector('[aria-label="Preview eviction output"]')?.textContent ?? ""; + w.__armedBeforeAnswer = !/Would evict/.test(said); + }; + new MutationObserver(check).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true }); + }); await page.getByRole("button", { name: "Preview eviction" }).click(); - await expect(evict).toBeDisabled(); await expect(page.getByLabel("Preview eviction output")).toContainText( /Would evict/, { timeout: 60_000 }, ); await expect(evict).toBeEnabled(); + expect( + await page.evaluate(() => (window as unknown as { __armedBeforeAnswer?: boolean | null }).__armedBeforeAnswer), + "the gate opened before the preview's answer", + ).toBe(false); // CHANGING THE AGE DISARMS BOTH. A preview of "any age" says nothing about // what a narrower sweep would take, and vice versa. diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -8,6 +8,7 @@ import { generateTool, generationPolicyTool, planGeneration, + renderIterationSummary, resultMarkerOf, validateGenerateArgs, } from "./generation"; @@ -141,6 +142,7 @@ test("generation_policy sets a preset as its routes, and one route alone", async flips: "api", threads: "api", youtube: "api", + social: "api", // Verdict proposals (release 29 M8): on a model in verdicts.models only. verdicts: "api", }, @@ -303,7 +305,7 @@ 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"]) { + for (const task of ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube", "social"]) { 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); @@ -337,6 +339,26 @@ test("generate: a media draft is a step on its iteration, routed like any task; assert.match(code.text, /youtube is routed to Claude Code/); }); +test("a media draft's answer puts its video project first, above the iteration's files (release 29 D1); any other task's keeps it under them", () => { + const iteration = { + n: 3, + kind: "sweep", + model: "qwen3:8b", + status: "done", + usage: {}, + steps: [{ task: "social", model: "qwen3:8b", status: "done", jobId: "job-9", detail: "2 social posts drafted" }], + projectDir: "/srv/projects/synth-a/i3", + }; + const files = { "sweep.md": "/srv/reports/synth-a/iterations/3/sweep.md", "report.json": "/srv/reports/synth-a/iterations/3/report.json" }; + const step = renderIterationSummary({ task: "social", article: "synth-a", jobId: "job-9", marker: null, iteration: iteration as never, dir: "/srv/reports/synth-a/iterations/3", files }).split("\n"); + assert.match(step[0]!, /^generate: social of synth-a i3 — \*\*done\*\*/); + assert.equal(step[1], "Video project: /srv/projects/synth-a/i3"); + assert.equal(step.filter((l) => l.startsWith("Video project:")).length, 1); + assert.ok(step.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3") > 1); + const revise = renderIterationSummary({ task: "revise-video", article: "synth-a", jobId: "job-8", marker: null, iteration: { ...iteration, kind: "revise-video", steps: [] } as never, dir: "/srv/reports/synth-a/iterations/3", files }).split("\n"); + assert.ok(revise.indexOf("Video project: /srv/projects/synth-a/i3") > revise.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3")); +}); + 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 @@ -289,7 +289,7 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; 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)"); + } else if (body.entries !== undefined) return bad("entries is a media draft's (cut, onscreen, teaser, flips, threads, narrate, youtube, social)"); 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 } }; } @@ -394,6 +394,10 @@ export function renderIterationSummary( 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})`); + // A media draft's work is the video project's (release 29 D1): it comes + // first, above the iteration's own files. + const projectFirst = isStepTask(o.task) && !!it.projectDir; + if (projectFirst) lines.push(`Video project: ${it.projectDir}`); if (o.marker?.summary) lines.push(o.marker.summary); if (it.error && status !== "done") lines.push(`error: ${it.error}`); if (step?.detail) lines.push(`${o.task === "narrate" ? "narration" : o.task}: ${step.detail}`); @@ -423,7 +427,7 @@ export function renderIterationSummary( lines.push(`Where (the editor's disk): ${o.dir}`); for (const [name, p] of present) if (name !== "turns.jsonl" && name !== "trace.jsonl") lines.push(` - ${name}: ${p}`); } - if (it.projectDir) lines.push(`Video project: ${it.projectDir}`); + if (it.projectDir && !projectFirst) lines.push(`Video project: ${it.projectDir}`); if (it.kind === "research") { const r = it.research ?? {}; lines.push(`Research: phase ${r.phase ?? "?"}, autonomy ${r.autonomy ?? "?"}${r.continuedBy ? `, continued by i${r.continuedBy}` : ""}`); @@ -581,7 +585,7 @@ export const GENERATION_TOOLS = [ 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, research, and the media drafts on a " + - "video cut (cut, onscreen, teaser, flips, threads, narrate, youtube) — whether this " + + "video cut (cut, onscreen, teaser, flips, threads, narrate, youtube, social) — 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 " + @@ -597,7 +601,7 @@ export const GENERATION_TOOLS = [ }, task: { type: "string", - description: "Route one task (with route): sweep, revise-report, revise-video, research, cut, onscreen, teaser, flips, threads, narrate, youtube.", + description: "Route one task (with route): sweep, revise-report, revise-video, research, cut, onscreen, teaser, flips, threads, narrate, youtube, social.", }, route: { type: "string", enum: [...GENERATION_ROUTES], description: "Where that task runs." }, }, @@ -617,7 +621,8 @@ export const GENERATION_TOOLS = [ "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 " + + "narrate (each card's narration), youtube (the upload's title and summary) and social (posts for X and Bluesky, " + + "text only, the link added by code); 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 " + @@ -633,7 +638,7 @@ export const GENERATION_TOOLS = [ type: "integer", minimum: 1, description: - "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.", + "revise-report / revise-video: the iteration revised; a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social): 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." }, @@ -649,7 +654,7 @@ export const GENERATION_TOOLS = [ 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." }, + entries: { type: "array", items: { type: "string" }, description: "A media draft (narrate, cut, onscreen, teaser, flips, threads, youtube, social): only these entry ids." }, force: { type: "boolean", description: diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -284,7 +284,7 @@ export function reviewGuidance(corpus?: string): string { // ─── The media drafts (release 28) ─── // -// A media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a +// A media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) 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. @@ -319,6 +319,10 @@ export const MEDIA_REVIEW: Record<string, { what: string; check: string }> = { 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", }, + social: { + what: "a post for X and one for Bluesky, each with up to 4 more under it (text only; the link under the first post and the counts are code's; out/x.txt and out/bluesky.txt)", + check: "each post says what the video shows and would not mislead out of context, and every quoted word is the speaker's", + }, }; // The review of a media draft — the step Claude Code owns after `generate`. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9540,3 +9540,44 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri (`umtool/lib/articles/verdicts.ts` `readArticleProposals`), group Review, action "Review verdicts" → `/articles/<id>?tab=article`, whose region `verdict proposals` approves or rejects through `/api/articles/verdicts` → `POST /api/ops/verdict-review`. + + +## Release 29 lane C: the deck step, the social posts, the active-site write (verified 2026-10-15, branch `r29/gen-debts`) + +- **A chain step may carry an `option`** (`umtool/lib/report/chain.mjs`, `CHAIN_OPTIONS = ["deck"]`): it is in a + chain only when that option is on — `chainStepsOf(mode, {deck})`, and `chainStart` / `chainSteps` / `planChain` + take `deck` (refused with the video chain). Draft everything with `deck` has the optional, model-less step `deck` + between `draft-teaser` and `draft-flips`; without it the draft-all list is release 28's plus `draft-social` at the + end (16 steps; 17 with the deck). The chain route takes `deck` (POST) / `&deck=1` (GET); `chainViewOf` lists the + step when asked or when the iteration recorded `chain:deck`. +- **The minimal deck is `deckChrome()`** (`umtool/lib/report/chain-draft.mjs`; the On-screen switch's too), and the + writer that adds it only to a cut with none is `addDeckChrome(dir, chrome)` (`lib/report/manifest.mjs`: a set + `render.chrome` is never touched; else `validateChrome`, an `auto-before-deck` snapshot, the write). Its defaults + do not fit a small frame (640×360 refuses: the deck needs ~294 px of footage height). +- **`publish` holds `youtube`, `x`, `bluesky`, `videoUrl`** (`PUBLISH_KEYS`, `validatePublish`, `drafted.mjs`). + `publish.x` / `publish.bluesky` are `{post, thread?}`, drafted fields of the `social` task (`FIELD_TASKS`; review + addresses `social/*/publish.x`, `social/*/publish.bluesky`); the stored first post INCLUDES its link (under a blank + line). `publish.videoUrl` is the operator's (an http(s) URL; nothing drafts it). +- **How a social post is counted is `common/lib/report/social.mjs`** (exported, no node imports): X 280 with every + `http(s)://` / `www.` URL 23, an emoji grapheme 2, a code point in 0–4351, 8192–8205, 8208–8223 or 8242–8247 1, any + other 2 (`xLength`); Bluesky 300 NFC graphemes (`blueskyLength`); a thread of at most 4 (`SOCIAL_LIMITS`). + `socialLinkOf(manifest, {articleUrl})`: `publish.videoUrl`, else the article URL the caller gives. +- **The `social` task** (`common/lib/report/draft/tasks/social.ts`) is a media step with narrate's route in every + preset: one unit per platform; the link is resolved once per run (`publish.videoUrl`, else `PROJECT_URL` + + `/articles/<id>/` when the registry has the article published and public, else none — logged, not a check); + `toField` appends it. `out/x.txt` / `out/bluesky.txt` are `report-to-video/social.mjs` `composeSocialText` (the first + post, then `— k/n —` and each thread post), written by build-video at the top of `writeYoutubeText` (a platform with + no post loses its file) and by Draft everything's `draft-social`. +- **The active-site cookie is written by `POST /api/active-site`** (`editor/app/api/active-site/route.ts`: JSON + `{value}`, an Origin that is not this host refused, `{ok}`), not a server action (`setActiveSiteAction` is gone). + `SiteScopeProvider.choose(value, {navigating?})` refreshes the router after a write unless the caller navigates; + `record` (a site page's visit, the migration) refreshes too. Why: a cookie set in a server action is answered before + the router applies the action's re-render; a `router.push` in that gap discards the action and its replayed refresh + can commit the push as a history REPLACE (Next 16 `HistoryUpdater`: a push whose URL is already the location is a + replace). +- **A server action that revalidates delays its own answer** until the router applies the revalidated tree, which + under in-flight prefetches can wait for the next AutoRefresh pulse (~5 s). Settings' save (R6.3) and the drive + health timing's save (`saveHealthTimingsAction`, D1) no longer revalidate and refresh after an ok answer; the lane + pause/resume actions (`LaneActionButton`) still revalidate. +- **`CopyDifferences.mtimeOnly`** (`common/controller/relocateDir.ts`): `classifyDrift` puts a directory whose only + difference is its mtime there, not in `changed`; `describeDifferences` names it apart. diff --git a/plans/release-29.md b/plans/release-29.md @@ -445,6 +445,155 @@ Found and left: leaves a `proposed` entry on a ruled claim, which nothing shows (the inbox and the tab list unruled claims only) and a rerun skips. +### G1, as shipped (2026-10-15, lane C, `r29/gen-debts`) + +Draft everything's deck, as ruled: an option, off by default. Built as the plan's Shape row, with these as built: +- **The step** is `deck` in `CHAIN_STEPS` (`umtool/lib/report/chain.mjs`), mode `draft-all`, `option: "deck"`, placed + after `draft-teaser` and before `draft-flips`, no `draft` (no model, no `--model` on its argv). A step with an + `option` is in a chain only when that option is on: `chainStepsOf(mode, {deck})`, and `chainStart` / `chainSteps` / + `planChain` take `deck`. Without it the draft-all chain is exactly release 28's list (its labels count the same); + `deck` with the video chain is refused. It is `optional`: a refusal is recorded failed and the chain goes on (flips + and threads are then skipped by `draftPrecheck`, as before). +- **What it writes** is `deckChrome()` (`chain-draft.mjs`, the one constructor: `{engine: "hyperframes", layout: + "deck", deck: {}}`, a fresh object), which the On-screen section's switch now calls too (it had the literal). There + was no constructor in `deck.mjs` to reuse (its :137-157 is `validateChrome`). It is written by + `addDeckChrome(dir, chrome)` (`lib/report/manifest.mjs`): under the manifest lock, a cut whose `render.chrome` is + set (anything but null/absent) is left untouched (`{added: false}`, nothing written); else `validateChrome`, an + `auto-before-deck` snapshot in `revisions/`, then the writer. The step's line is "deck added: …" or "deck already + there: …" (`deckStepDetail`). +- **Where it is asked for:** umtool's chain route takes `deck` in the POST body (refused without `draftAll`) and + `&deck=1` on the GET; `chainViewOf(…, {deck})` lists the step when asked or when the iteration recorded a + `chain:deck` step; `ChainPanel` takes `deck`; `MediaDrafts` has the **with the deck** checkbox + (`data-draft-everything-deck`) beside **Draft everything**, the run keeping the value it was started with; + `umtool chain <article> <n> --draft-all --deck` (`--deck` alone is refused). +- **Found:** the minimal deck (its defaults) does not fit a small frame: on the e2e's 640×360 cuts `validateChrome` + refuses it ("footageScale 0.82 needs 294px but a 190px deck leaves 170"). The step is then recorded failed, as built; + the e2e's deck cut is full HD. + +| Commit | What | +| --- | --- | +| `ca779c9d` | umtool: the `deck` step, `deckChrome`, `addDeckChrome`, the route/view/panel/checkbox and `--deck`; `chain.test.mjs` (+1), `chain-draft.test.mjs` (+1); common `deckOption.test.ts` (3: flips and threads drafted on a converted cut given the deck, over the fake ollama, through umtool's own writer) | +| `b3e05faf` | (G2's commit, which carried the e2e of both) umtool e2e: `media-surfaces.spec.ts` "Draft everything with the deck" on msurf i3: the deck step done, the flips drafted (the stub's canned flips on a cut with a deck), the threads skipped, the snapshot, then the chain cancelled | +| `4979ee0e` | umtool e2e: msurf i3 is a full-HD cut (the minimal deck's defaults need the room) | + +### G2, as shipped (2026-10-15, lane C, `r29/gen-debts`) + +The social promotion text, text only. Built as the plan's Shape row, with these as built: +- **The counts are one module**, `common/lib/report/social.mjs` (+ `.d.mts`, exported; no node imports, so umtool's + page reads it): `SOCIAL_LIMITS` (X 280, Bluesky 300, a thread of at most 4, a URL 23), `xLength` (twitter-text's v3 + weighting: every `http(s)://` or `www.` URL 23, an emoji grapheme 2, a code point in 0–4351, 8192–8205, 8208–8223, + 8242–8247 1, any other 2), `blueskyLength` (NFC graphemes, `Intl.Segmenter`), `withLink` (the post, a blank line, + the link), `validateSocialPost`, `socialLinkOf`. +- **The fields:** `publish.x` and `publish.bluesky` `{post, thread?}` in `drafted.mjs` (`DRAFTED_MANIFEST_FIELDS`, + `FIELD_TASKS` → `social`, `isEmptyField`, the marks' placement check). `validatePublish` takes `PUBLISH_KEYS` + (`youtube, x, bluesky, videoUrl`): each post within its platform's count, a thread of at most 4, and + `publish.videoUrl` an http(s) URL. **`publish.videoUrl` is new**: the video's public URL, the operator's to set once + it is up; nothing drafts it. The stored first post INCLUDES its link (so the field is the post as published, and + the lint counts what is pasted). +- **The task** (`tasks/social.ts`, `SOCIAL_SPEC` on `runMediaTask`): one unit per platform, the YouTube task's + evidence (`evidenceOf`, now exported). The link is code's, resolved once per run: `publish.videoUrl`, else the + article's homepage page (`PROJECT_URL` + `/articles/<id>/`) when the registry has it published and `audience` + public, else none — said once in the log, not a check (a check's soft problem would re-ask a model that cannot fix + it). The prompt names the first post's budget (the limit minus the link's room: 255 on X); code counts the post + WITH its link, refuses links, timestamps, hashtags, @mentions and emoji, and grounds every post with + `checkLine(…, {quotes: true})` (names and numbers, Q1's third person, quotation marks only around a cited quote's + words). The repair keeps the first post's sentences that pass and fit, and drops failing thread posts (to 4); never + a rewrite. `toField` appends the link. +- **Wired** as a media step: `MEDIA_STEP_TASKS`, `GENERATION_TASKS`, narrate's route in every preset (a release-28 + settings file keeps its preset, `social` takes the preset's route), `reportDraft.ts`'s media case, `runTask`, the + MCP's lists and `MEDIA_REVIEW`, `/gen`'s phrasings, `archilyzer gen`'s usage; SETTINGS.md, settings.json.example and + COMMANDS.md regenerated. +- **Files:** `umtool/report-to-video/social.mjs` (`composeSocialText`: the first post, then each thread post under a + `— k/n —` line; `socialTexts`, `socialTextName`), exported `umtool-report-to-video/social`. build-video's + `writeSocialText` runs at the top of `writeYoutubeText` (every chapter mux, every variant: the posts are the cut's) + and removes a platform's file when its post is gone. Draft everything's `draft-social` (after `draft-youtube`) writes + the two files itself, no build needed, also when the draft is skipped. +- **umtool:** `SocialPostSection.tsx` on the Media tab after the YouTube section (each platform's posts, their counted + lengths in Meter — no verdict colour, "over the limit" in words — the file's age, "drafted by", **Copy**); `social` + in `MEDIA_SECTIONS`, `PROJECT_DRAFT_TASKS` and its draft row; `writeDraftedField` takes `publish.x` / + `publish.bluesky` ("Use this"); the drafts review labels them. +- Test kit: `draft/runs/social.json` (the X post's first answer refused — first person, a link, a hashtag — and + re-asked; the Bluesky post kept at once; no link: the kit's article is not public). + +| Commit | What | +| --- | --- | +| `b3e05faf` | common, umtool, mcp: `social.mjs`, the fields and `validatePublish`, `tasks/social.ts`, the wiring, `report-to-video/social.mjs`, build-video's writer, `draft-social`, `SocialPostSection`, the kit's run, docs; tests: common `social.test.ts` (7), `drafted.test.ts` (+1), `generationSettings.test.ts` (one test widened); umtool `social.test.mjs` (2), `chain-draft.test.mjs` (+1), `drafted-writer.test.mjs` (+1), `chain.test.mjs`/`create.test.mjs` lists; mcp `generation.test.ts` lists | +| `b3e05faf` (cont.) | umtool e2e: `media-draft.spec.ts` "social" (the real task over the kit's run on mdraft i4, the Media tab's posts and counts); `media-surfaces.spec.ts` the draft-all chain's 16 steps with `out/x.txt` and `out/bluesky.txt`; the stub's canned social, `social` run for real on mdraft | +| `4979ee0e` | umtool e2e: eight draft sections; the Bluesky post's count read on its first post | + +### D1, as shipped (2026-10-15, lane C, `r29/gen-debts`) + +- **relocateDir:** `CopyDifferences` gains `mtimeOnly`; `classifyDrift` puts a `.d..t` line (`DIR_MTIME_ONLY`) there, + not in `changed`; `describeDifferences` appends ", and N directories differ only in mtime (…)"; a reconcile whose + only drift is that says "the destination copy's content already matches the source; N directories differ only in + mtime (…), which the mirror pass settles". The verify's own `.d..t` rule is unchanged. +- **fetchPosts.test:** the fake's paged mode is stepped by files (`FAKE_GATES`: a page's cursor waits for + `cursor-<p>`, the next page for `page-<p+1>`), so the drain lands between page 1's records and its cursor whatever + the load; the resume run is cancelled once the fake's argv is in its log, not after 200 ms. +- **queue-lock.test:** every fixed hold a test's assertion depended on is a gate (`gateCmd`) opened once the waiter + has printed its banner (or, for the pass-through cases, once the nested run has finished while the lock is still + held — no stopwatch): the banner, `QUEUE_LOCK_HELD`, `E2E_QUEUE=0`, the SIGKILL (until `holder.json`, not 500 ms), + two heavy contenders, an e2e run behind a heavy one, two builds, the undeclared job, the nested build, named suites, + the SIGTERM waiter, `--scale-by`; the FIFO test's first hold too. +- **`generate`'s answer** (`renderIterationSummary`): for a media draft the `Video project:` line comes second, under + the header; any other task's stays under the iteration's files. +- **The editor flakes were product races, fixed in the app as R6.3 fixed Settings' save** (aaba3723): + - `site-scope.spec` (Back on `about:blank`): the active-site cookie was set in a server action, which Next answers + before its router applies the re-render the action carries; the picker's `router.push` in that gap discards the + pending action, which is replayed as a refresh after the push, and React committing the two together writes the + push's history entry as a REPLACE (Next 16's `HistoryUpdater`). The cookie is now written by **`POST + /api/active-site`** (same-origin JSON; `setActiveSiteAction` and `lib/activeSiteActions.ts` are gone), and the + provider refreshes after a write unless the caller navigates (`choose(value, {navigating})`). The same runs also + showed two other site-scope reds, both fixed: a re-scope waiting seconds on the action's re-render under load + (gone with the action), and the spec's `hydrated` (React's props on the select) coming before the provider's + BroadcastChannel subscription — it now waits on the picker's `data-hydrated`, stamped by a re-render after every + first-commit effect. + - `storage-locations.spec:723` (the timing's "Saved." late): `saveHealthTimingsAction` no longer revalidates + `/storage`; `HealthTimingForm` refreshes after an ok answer. The same spec's `:661` (any-age eviction) asserted a + transient "still disabled" right after Preview, which a preview answering at once on the small fixture raced (2 of + 5 under load): a MutationObserver in the page now records whether the button was armed before the answer. + - `publish-lane.spec:78`: the spec waits on the lane's held state (`publishStatus`), then reloads, before reading + the pause/resume button (the shared `LaneActionButton` and its lane actions are unchanged). + +| Commit | What | +| --- | --- | +| `315e8335` | common, mcp, scripts: relocateDir's `mtimeOnly` (`relocateDir.test.ts` +1, one case rewritten); `fetchPosts.test.ts`; `queue-lock.test.mjs`; `renderIterationSummary` (`generation.test.ts` +1) | +| `742da22c` | editor: `POST /api/active-site`, the provider and the picker; the timing action and form; `site-scope.spec.ts`'s `hydrated`; `publish-lane.spec.ts` | +| `d30248dc` | merge of `r29/integration` (`cfdeb856`: V1, E1, E2), clean | +| `800a26fc` | editor e2e: `storage-locations.spec.ts`'s any-age eviction watched in the page | +| (this commit) | these records, FACTS "Release 29 lane C", CHANGELOG | + +### Lane C gates (2026-10-15, `r29/gen-debts`) + +Counts at the branch's start (`3217bdfb`) → before the merge → after the merge of `r29/integration` (`d30248dc`): +- tsc (all packages): clean before every commit. +- common: 4193/4193 → 4205/4205 (+12: `deckOption.test.ts` 3, `social.test.ts` 7, `drafted.test.ts` +1, + `relocateDir.test.ts` +1) → 4235: 4234 pass, 1 failed — `ttsServer.test.ts` "a start that times out…", run beside + an editor e2e; 6/6 alone. +- mcp 370 → 371/371 (+1). editor unit 304 → 304 → 308/308 (the merge's). umtool unit 33/33. +- `test:scripts`: 1013 (1008 pass, 2 failed — `queue-lock.test.mjs` "an e2e run takes the heavy slot too" and "two + builds never overlap", the fixed holds — 3 skipped) → 1019 (1016 + 3 skipped, 0 failed) → 1020 (1017 + 3 skipped, + 0 failed). +- Flakes, 5 runs each, `fetchPosts.test.ts` and `queue-lock.test.mjs` run two at once: 8/8 and 37/37 every run. +- `docs env|files|cli --check`, `settings example --check`: clean (COMMANDS.md, SETTINGS.md regenerated in + `b3e05faf`; clean again after the merge). +- umtool e2e, two specs per run, foreground: `media-draft.spec.ts` + `media-surfaces.spec.ts` 4/7 (the deck refused on + a 640×360 cut, a Bluesky count's locator, seven sections → eight), then 7/7 (1.5 min), and 7/7 after the merge + (1.4 min). +- Editor e2e, one spec per run with `--repeat-each=5`, foreground (each run's prebuild a capped `next build` through + the heavy slot): `site-scope.spec.ts` 64/65 (the other-tab broadcast), 64/65 (a re-scope over 5 s), then with the + route 65/65 (2.0 min); after the merge `publish-lane.spec.ts` 10/10 (58.5 s); `storage-locations.spec.ts` 43/45 + (`:661` twice) then 45/45 (2.2 min). +- umtool capped build, the corpus linked, through the heavy slot (5 GB): ok, 49 s wall; the link removed. + +Found and left: +- The minimal deck refuses a small frame (G1, above). Draft everything on such a cut records the deck step failed. +- A social post's link is resolved when it is drafted: a `publish.videoUrl` set later is in the posts only after a + forced re-draft or an edit (the field shows its link, so the operator sees which). +- `LaneActionButton`'s lane actions still revalidate (`/jobs`, `/workers`, the lane's page), so their buttons can + re-render late under load as the timing's did; the publish-lane spec now waits on the lane's state instead. Not + changed here: the button is shared by every lane. + ## Not in this release Auto-posting to X/Bluesky/YouTube (text only); any umtool restructuring; the "en track → 0 cues" bug (closed in r20). diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -145,7 +145,9 @@ test("serves waiters in arrival order (FIFO)", async () => { // Each arrival waits until the one before it is in line: the first holds // (its holder.json is written), the next two have printed their banner and // had a moment to block in flock. A fixed stagger raced a loaded machine. - const first = startLock(["--", ...markerCmd(log, "1", 600)], env); + // The first holds until both are in line (release 29 D1: a gate, not 600 ms). + const gate = path.join(dir, "gate-1"); + const first = startLock(["--", ...gateCmd(log, "1", gate)], env); await until(() => fs.existsSync(`${lock}.holder.json`)); const runs = [first.done]; for (const id of ["2", "3"]) { @@ -154,6 +156,7 @@ test("serves waiters in arrival order (FIFO)", async () => { await delay(150); runs.push(r.done); } + openGate(gate); await Promise.all(runs); assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2S3E3"); @@ -164,9 +167,14 @@ test("prints a banner naming the holder while waiting", async () => { const lock = path.join(dir, "q.lock"); const env = { E2E_QUEUE_LOCK_FILE: lock }; - const first = runLock(["--", process.execPath, "-e", "setTimeout(()=>{},600)"], env); + // The first holds until the second has said it waits (a gate, not 600 ms). + const gate = path.join(dir, "gate"); + const first = runLock(["--", ...gateCmd(path.join(dir, "first.log"), "1", gate)], env); await until(() => fs.existsSync(`${lock}.holder.json`)); - const second = await runLock(["--", process.execPath, "-e", "0"], env); + const waiting = startLock(["--", process.execPath, "-e", "0"], env); + await waiting.waitFor(/waiting for the e2e queue/); + openGate(gate); + const second = await waiting.done; await first; assert.equal(second.code, 0); @@ -180,21 +188,23 @@ test("QUEUE_LOCK_HELD passes straight through without deadlocking", async () => const lock = path.join(dir, "q.lock"); const env = { E2E_QUEUE_LOCK_FILE: lock }; - // Hold the lock for a good while, then prove a nested invocation (the shape - // of root `pnpm e2e` -> `pnpm --filter editor run e2e`) does not wait for it. - const held = runLock(["--", process.execPath, "-e", "setTimeout(()=>{},1500)"], env); - await delay(300); + // Hold the lock until the nested run is over, then prove a nested + // invocation (the shape of root `pnpm e2e` -> `pnpm --filter editor run + // e2e`) does not wait for it: it finishes while the lock is still held — a + // gate, not a 1500 ms hold and a 1000 ms stopwatch (release 29 D1). + const gate = path.join(dir, "gate"); + const held = runLock(["--", ...gateCmd(path.join(dir, "held.log"), "h", gate)], env); + await until(() => fs.existsSync(`${lock}.holder.json`)); - const t0 = Date.now(); const nested = await runLock(["--", process.execPath, "-e", "0"], { ...env, QUEUE_LOCK_HELD: "e2e", }); - const elapsed = Date.now() - t0; assert.equal(nested.code, 0); - assert.ok(elapsed < 1000, `nested run waited ${elapsed}ms — it deadlocked on its parent's lock`); + assert.ok(fs.existsSync(`${lock}.holder.json`), "the nested run finished while its parent's lock was held"); assert.doesNotMatch(nested.stderr, /waiting for the e2e queue/); + openGate(gate); await held; }); @@ -203,13 +213,15 @@ test("E2E_QUEUE=0 bypasses the queue entirely", async () => { const lock = path.join(dir, "q.lock"); const env = { E2E_QUEUE_LOCK_FILE: lock }; - const held = runLock(["--", process.execPath, "-e", "setTimeout(()=>{},1500)"], env); - await delay(300); + const gate = path.join(dir, "gate"); + const held = runLock(["--", ...gateCmd(path.join(dir, "held.log"), "h", gate)], env); + await until(() => fs.existsSync(`${lock}.holder.json`)); - const t0 = Date.now(); const bypass = await runLock(["--", process.execPath, "-e", "0"], { ...env, E2E_QUEUE: "0" }); assert.equal(bypass.code, 0); - assert.ok(Date.now() - t0 < 1000, "E2E_QUEUE=0 still waited for the lock"); + assert.ok(fs.existsSync(`${lock}.holder.json`), "E2E_QUEUE=0 still waited for the lock"); + assert.doesNotMatch(bypass.stderr, /waiting for the e2e queue/); + openGate(gate); await held; }); @@ -223,7 +235,7 @@ test("a SIGKILLed run releases the lock immediately", async () => { [SCRIPT, "--", process.execPath, "-e", "setTimeout(()=>{},30000)"], { env, stdio: "ignore" }, ); - await delay(500); // let it acquire + await until(() => fs.existsSync(`${lock}.holder.json`)); // it has acquired victim.kill("SIGKILL"); await new Promise((r) => victim.on("exit", r)); @@ -413,9 +425,13 @@ test("two heavy contenders run one at a time; the second names what it waits beh const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir); - const first = startLock(["--heavy", "--", ...markerCmd(log, "1", 600)], env); + const gate = path.join(dir, "gate"); + const first = startLock(["--heavy", "--", ...gateCmd(log, "1", gate)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`)); - const second = await runLock(["--heavy", "--", ...markerCmd(log, "2", 50)], env); + const waiting = startLock(["--heavy", "--", ...markerCmd(log, "2", 50)], env); + await waiting.waitFor(/waiting for the heavy slot/); + openGate(gate); + const second = await waiting.done; assert.equal((await first.done).code, 0); assert.equal(second.code, 0); assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); @@ -427,9 +443,13 @@ test("an e2e run takes the heavy slot too: it waits for a heavy job, then runs", const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); - const build = startLock(["--heavy", "--", ...markerCmd(log, "b", 600)], env); + const gate = path.join(dir, "gate"); + const build = startLock(["--heavy", "--", ...gateCmd(log, "b", gate)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`)); - const e2e = await runLock(["--", ...markerCmd(log, "e", 50)], env); + const waiting = startLock(["--", ...markerCmd(log, "e", 50)], env); + await waiting.waitFor(/waiting for the heavy slot/); + openGate(gate); + const e2e = await waiting.done; await build.done; assert.equal(e2e.code, 0); assert.equal(fs.readFileSync(log, "utf8"), "SbEbSeEe"); @@ -682,9 +702,13 @@ test("two builds never overlap, whatever the memory; the second waits for the bu const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir); - const first = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 600)], env); + const gate = path.join(dir, "gate"); + const first = startLock(["--heavy", "--build", "--estimate", "100", "--", ...gateCmd(log, "1", gate)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); - const second = await runLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "2", 50)], env); + const waiting = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "2", 50)], env); + await waiting.waitFor(/waiting for the build slot/); + openGate(gate); + const second = await waiting.done; assert.equal((await first.done).code, 0); assert.equal(second.code, 0, second.stderr); assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); @@ -695,11 +719,18 @@ test("an undeclared job runs alone: it waits for the weighted ones, and none sta const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir); - const weighted = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "w", 600)], env); + const gateW = path.join(dir, "gate-w"); + const gateX = path.join(dir, "gate-x"); + const weighted = startLock(["--heavy", "--estimate", "100", "--", ...gateCmd(log, "w", gateW)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.jobs`) && fs.readdirSync(`${env.HEAVY_LOCK_FILE}.jobs`).length > 0); - const alone = startLock(["--heavy", "--", ...markerCmd(log, "x", 600)], env); + const alone = startLock(["--heavy", "--", ...gateCmd(log, "x", gateX)], env); await alone.waitFor(/waiting for the heavy slot — held by .*pid \d+, 100 MB/); + openGate(gateW); + // `alone` has started (its S is in the log) before `later` asks: none starts beside it. + await until(() => fs.readFileSync(log, "utf8").includes("Sx")); const later = startLock(["--heavy", "--estimate", "100", "--", ...markerCmd(log, "l", 50)], env); + await later.waitFor(/waiting for the heavy slot/); + openGate(gateX); for (const r of await Promise.all([weighted.done, alone.done, later.done])) assert.equal(r.code, 0, r.stderr); assert.equal(fs.readFileSync(log, "utf8"), "SwEwSxExSlEl"); }); @@ -708,10 +739,14 @@ test("a build nested in an admitted run waits for the build slot (one build at a const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir); - const outer = startLock(["--heavy", "--build", "--estimate", "100", "--", ...markerCmd(log, "1", 700)], env); + const gate = path.join(dir, "gate"); + const outer = startLock(["--heavy", "--build", "--estimate", "100", "--", ...gateCmd(log, "1", gate)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.build.holder.json`)); // The shape of an e2e config's rebuild inside a running suite: HEAVY_HELD set. - const nested = await runLock(["--heavy", "--build", "--", ...markerCmd(log, "2", 50)], { ...env, HEAVY_HELD: "1" }); + const waiting = startLock(["--heavy", "--build", "--", ...markerCmd(log, "2", 50)], { ...env, HEAVY_HELD: "1" }); + await waiting.waitFor(/waiting for the build slot/); + openGate(gate); + const nested = await waiting.done; assert.equal(nested.code, 0, nested.stderr); await outer.done; assert.equal(fs.readFileSync(log, "utf8"), "S1E1S2E2"); @@ -732,15 +767,18 @@ test("named suites run side by side; the same suite never runs twice", async () const dir = tmpDir(); const log = path.join(dir, "order.log"); const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock") }); - const suite = (name, id, ms) => - startLock(["--name", name, "--estimate", "100", "--", ...markerCmd(log, id, ms)], env); - const a = suite("e2e-editor", "a", 900); + // a and b hold until the second editor run has said it waits: their overlap + // and its wait are the gate's, not a 900 ms hold's (release 29 D1). + const gate = path.join(dir, "gate-ab"); + const held = (name, id) => startLock(["--name", name, "--estimate", "100", "--", ...gateCmd(log, id, gate)], env); + const a = held("e2e-editor", "a"); await until(() => fs.existsSync(path.join(dir, "q.lock.e2e-editor.holder.json"))); - const b = suite("e2e-umtool", "b", 900); + const b = held("e2e-umtool", "b"); const order = () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8") : ""); - await until(() => order().includes("Sb") || order().includes("Ea")); - const again = suite("e2e-editor", "c", 50); + await until(() => order().includes("Sb")); + const again = startLock(["--name", "e2e-editor", "--estimate", "100", "--", ...markerCmd(log, "c", 50)], env); await again.waitFor(/waiting for the e2e queue — held by .*pid \d+/); + openGate(gate); for (const r of await Promise.all([a.done, b.done, again.done])) assert.equal(r.code, 0, r.stderr); const ran = order(); assert.ok(overlapped(ran), `editor and umtool did not overlap: ${ran}`); @@ -784,7 +822,8 @@ test("--prebuild ensures the suite's build before its admission, and the config test("a waiter stopped by SIGTERM leaves no holder file behind", async () => { const dir = tmpDir(); const env = heavyEnv(dir); - const first = startLock(["--heavy", "--", process.execPath, "-e", "setTimeout(()=>{},1500)"], env); + const gate = path.join(dir, "gate"); + const first = startLock(["--heavy", "--", ...gateCmd(path.join(dir, "first.log"), "1", gate)], env); await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`)); const waiter = startLock(["--heavy", "--", "true"], env); await waiter.waitFor(/waiting for the heavy slot/); @@ -793,6 +832,7 @@ test("a waiter stopped by SIGTERM leaves no holder file behind", async () => { const res = await waiter.done; assert.equal(res.code, 128 + os.constants.signals.SIGTERM); assert.equal(fs.existsSync(`${env.HEAVY_LOCK_FILE}.admit.holder.json`), false); + openGate(gate); assert.equal((await first.done).code, 0); }); @@ -805,11 +845,13 @@ test("--scale-by: an estimate per worker, times the editor suite's E2E_WORKERS", const dir = tmpDir(); const env = heavyEnv(dir, { E2E_QUEUE_LOCK_FILE: path.join(dir, "q.lock"), E2E_WORKERS: "3" }); const jobs = path.join(dir, "heavy.lock.jobs"); - const cmd = [process.execPath, "-e", "setTimeout(()=>{},400)"]; - const run = startLock(["--name", "e2e-x", "--estimate", "1500", "--scale-by", "E2E_WORKERS", "--", ...cmd], env); + // Held until its ticket is read (a gate, not 400 ms). + const gate = path.join(dir, "gate"); + const run = startLock(["--name", "e2e-x", "--estimate", "1500", "--scale-by", "E2E_WORKERS", "--", ...gateCmd(path.join(dir, "x.log"), "x", gate)], env); await until(() => fs.existsSync(jobs) && fs.readdirSync(jobs).some((n) => n.endsWith(".json"))); const ticket = JSON.parse(fs.readFileSync(path.join(jobs, fs.readdirSync(jobs).find((n) => n.endsWith(".json"))), "utf8")); assert.equal(ticket.estimateMb, 4500); + openGate(gate); assert.equal((await run.done).code, 0); }); diff --git a/settings.json.example b/settings.json.example @@ -254,6 +254,7 @@ "flips": "local", "threads": "local", "youtube": "local", + "social": "local", "verdicts": "local" }, "models": { diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts @@ -12,13 +12,15 @@ 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>[&mode=draft-all] -> { chain } the steps, where it resumes, its job -// POST { article, n, from?, draftAll?, model? } -> { ok, job } started +// GET ?article=<id>&n=<n>[&mode=draft-all][&deck=1] -> { chain } the steps, where it resumes, its job +// POST { article, n, from?, draftAll?, model?, deck? } -> { ok, job } started // POST { 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. +// `deck` (release 29 G1, Draft everything's option, off by default) adds the +// deck step before the flips: the minimal on-screen deck on a cut with none. function parse(article: unknown, n: unknown): { article: string; n: number } | string { const a = String(article ?? ""); const k = Number(n); @@ -27,11 +29,11 @@ function parse(article: unknown, n: unknown): { article: string; n: number } | s return { article: a, n: k }; } -async function chainOf(article: string, n: number, mode: ChainMode = "video") { +async function chainOf(article: string, n: number, mode: ChainMode = "video", deck = false) { const its = await readArticleIterations(article); const it = its.iterations.find((r) => r.n === n); if (!it) return null; - return chainViewOf(article, it, mode); + return chainViewOf(article, it, mode, { deck }); } const modeOf = (v: unknown): ChainMode => (v === "draft-all" || v === true ? "draft-all" : "video"); @@ -41,7 +43,7 @@ export async function GET(request: Request) { 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, modeOf(url.searchParams.get("mode"))); + const chain = await chainOf(p.article, p.n, modeOf(url.searchParams.get("mode")), url.searchParams.get("deck") === "1"); if (!chain) return Response.json({ error: `no iteration i${p.n}` }, { status: 404 }); return Response.json({ chain }, { headers: { "cache-control": "no-store" } }); } catch (err) { @@ -50,7 +52,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; draftAll?: unknown; model?: unknown }; + const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown; deck?: unknown }; if (body.cancel !== undefined) { const id = String(body.cancel); if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 }); @@ -69,10 +71,12 @@ export async function POST(request: Request) { 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 } : {}) }); + const deck = body.deck === true; + if (deck && mode !== "draft-all") return Response.json({ error: "the deck is Draft everything's option (draftAll)" }, { status: 400 }); + const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(deck ? { deck } : {}), ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) }); 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) }); + return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode, deck) }); } catch (err) { return Response.json({ error: (err as Error).message }, { status: 400 }); } diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -26,10 +26,11 @@ // 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]] +// [--draft-all [--model M] [--deck]] // an iteration's pipeline: current, windows, prepare, posts, manifest, // voices, video, podcast, attach, dedupe (resumes at the first step not done); -// --draft-all is Draft everything: the drafts between manifest and the fast build +// --draft-all is Draft everything: the drafts between manifest and the fast build; +// --deck adds the on-screen deck to a cut with none before the flips // 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] @@ -683,11 +684,12 @@ 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] [--draft-all [--model M]]", + " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]", ` 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", + " each draft a report-draft job on --model (else its route); a draft that fails does not stop it;", + " --deck adds a step before the flips: the minimal on-screen deck on a cut with none", " 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", @@ -970,11 +972,13 @@ async function cmdChain() { const article = positional[0]; const n = Number(positional[1]); if (!article || !Number.isInteger(n) || n < 1) { - die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M]]"); + die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]"); } 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"); + const deck = has("--deck"); + if (deck && !draftAll) die("--deck is Draft everything's option (--draft-all): the deck the flips and threads draw on"); let plan; try { plan = planChain({ @@ -985,13 +989,13 @@ 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") } : {}) } : {}), + ...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}), ...(deck ? { deck: true } : {}) } : {}), }); } catch (err) { die(err.message); } const { start, steps } = plan; - const again = `umtool chain ${article} ${n}${draftAll ? " --draft-all" : ""}`; + const again = `umtool chain ${article} ${n}${draftAll ? ` --draft-all${deck ? " --deck" : ""}` : ""}`; if (json && has("--dry")) return out({ article, n, start, steps }); if (steps.length === 0) { console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`); diff --git a/umtool/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx @@ -18,6 +18,7 @@ export default function ChainPanel({ label, mode = "video", model, + deck = false, autoStart = false, }: { article: string; @@ -25,6 +26,8 @@ export default function ChainPanel({ label: string; mode?: ChainMode; model?: string; + /** Draft everything with its deck step (release 29 G1). */ + deck?: boolean; autoStart?: boolean; }) { const draftAll = mode === "draft-all"; @@ -35,7 +38,7 @@ export default function ChainPanel({ const [sending, setSending] = useState(false); const load = useCallback(async () => { - const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? "&mode=draft-all" : ""}`, { cache: "no-store" }); + const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? `&mode=draft-all${deck ? "&deck=1" : ""}` : ""}`, { cache: "no-store" }); const b = await r.json(); if (!r.ok) { setError(b.error ?? `HTTP ${r.status}`); @@ -43,7 +46,7 @@ export default function ChainPanel({ } setChain(b.chain); return b.chain as ChainView; - }, [article, n, draftAll]); + }, [article, n, draftAll, deck]); const running = chain?.job?.state === "running"; useEffect(() => { @@ -61,7 +64,7 @@ export default function ChainPanel({ try { const r = await fetch("/api/articles/chain", { method: "POST", - body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}) } : {}) }), + body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}), ...(deck ? { deck: true } : {}) } : {}) }), }); const b = await r.json(); if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); @@ -72,7 +75,7 @@ export default function ChainPanel({ } finally { setSending(false); } - }, [article, n, from, draftAll, model, load]); + }, [article, n, from, draftAll, model, deck, load]); useEffect(() => { if (!autoStart || started.current) return; @@ -109,7 +112,8 @@ export default function ChainPanel({ > {draftAll && ( <p className="text-[11.5px] text-muted"> - {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 + {model ? <span className="font-mono">{model}</span> : "each task's route"} + {deck ? " · with the deck" : ""} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build </p> )} {chain && ( diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx @@ -56,6 +56,7 @@ export const MEDIA_SECTIONS: { task: string; label: string }[] = [ { task: "threads", label: "Threads" }, { task: "narrate", label: "Narration" }, { task: "youtube", label: "YouTube" }, + { task: "social", label: "Social" }, ]; const sectionOf = (address: string) => address.split("/")[0]; @@ -438,6 +439,11 @@ export default function MediaDrafts({ const [only, setOnly] = useState<string | null>(null); const [allModel, setAllModel] = useState(""); const [allRun, setAllRun] = useState(0); + // Draft everything's deck option (release 29 G1, off by default): ticked, + // the chain adds the minimal deck to a cut with none before the flips. The + // run keeps the value it was started with. + const [allDeck, setAllDeck] = useState(false); + const [runDeck, setRunDeck] = useState(false); const allModels = modelsFor(policy, "onscreen"); useEffect(() => { if (!allModel && allModels.route) setAllModel(allModels.route); @@ -521,12 +527,19 @@ export default function MediaDrafts({ </option> ))} </select> + <label className="flex items-center gap-1 text-[12px] text-muted" title="Adds the on-screen deck to a cut with none, so the flips and threads are drafted too"> + <input type="checkbox" data-draft-everything-deck="" checked={allDeck} onChange={(e) => setAllDeck(e.target.checked)} disabled={!policy} /> + with the deck + </label> <button type="button" data-draft-everything="" className={buttonVariants({ variant: "outline", size: "md" })} disabled={!policy} - onClick={() => setAllRun((k) => k + 1)} + onClick={() => { + setRunDeck(allDeck); + setAllRun((k) => k + 1); + }} > Draft everything </button> @@ -551,7 +564,7 @@ export default function MediaDrafts({ </p> ) )} - {link.ok && allRun > 0 && <ChainPanel key={allRun} article={link.article} n={link.n} label={`i${link.n}`} mode="draft-all" model={allModel} autoStart />} + {link.ok && allRun > 0 && <ChainPanel key={allRun} article={link.article} n={link.n} label={`i${link.n}`} mode="draft-all" model={allModel} deck={runDeck} autoStart />} <div className="flex flex-wrap gap-1.5" role="group" aria-label="Sections"> <button type="button" data-media-chip="all" aria-pressed={only === null} onClick={() => setOnly(null)} className={chipClass(only === null)}> All <span className="font-mono text-[11px] text-meter">{total}</span> diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -11,6 +11,7 @@ import { badgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { backdropTransform, footageAt } from "@/lib/report/footage-move.mjs"; import { VERDICTS } from "umtool-report-to-video/factcheck"; +import { deckChrome } from "@/lib/report/chain-draft.mjs"; // --------------------------------------------------------------------------- // ON-SCREEN: the persistent panel under the footage of a report cut. @@ -1050,7 +1051,7 @@ export default function OnscreenSection({ return; } setSwitching(on); - const ok = await putChrome(on ? { engine: "hyperframes", layout: "deck", deck: {} } : null); + const ok = await putChrome(on ? deckChrome() : null); if (!ok) { setSwitching(null); return; diff --git a/umtool/components/projects/SocialPostSection.tsx b/umtool/components/projects/SocialPostSection.tsx @@ -0,0 +1,68 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import CopyButton from "@/components/CopyButton"; +import { Panel } from "@/components/ui/panel"; +import { fmtAgo } from "@/lib/format"; +import { SOCIAL_LIMITS, SOCIAL_NAMES, socialLength, type SocialPlatform } from "yt-dlp-transcript-common/lib/report/social.mjs"; +import { SOCIAL_PLATFORMS, composeSocialText, socialPosts, socialTextName } from "umtool-report-to-video/social"; + +// The promotion posts (release 29 G2): `publish.x` and `publish.bluesky`, the +// first post (its link under it, added by code) and the thread under it, each +// with its length as its platform counts it (X: a link is 23; Bluesky: +// graphemes). Copy takes what out/<platform>.txt holds -- the same text, +// composed from the manifest. TEXT ONLY: nothing here posts. Nothing when +// the cut has neither post. + +type Props = { dir: string; manifest: Record<string, unknown> }; +type Value = { post?: string; thread?: string[] }; + +export default async function SocialPostSection({ dir, manifest }: Props) { + const publish = (manifest.publish ?? {}) as Partial<Record<SocialPlatform, Value>>; + const drafted = (manifest.drafted ?? {}) as Record<string, { model?: string } | undefined>; + const platforms = (SOCIAL_PLATFORMS as readonly SocialPlatform[]).filter((p) => socialPosts(publish[p]).length > 0); + if (!platforms.length) return null; + const written = Object.fromEntries( + await Promise.all(platforms.map(async (p) => [p, await stat(path.join(dir, "out", socialTextName(p))).then((s) => s.mtimeMs, () => null)] as const)), + ) as Record<SocialPlatform, number | null>; + return ( + <Panel title="social posts" aria-label="Social posts" aside={<span className="text-muted">text only — copy it, nothing is posted</span>}> + <div className="grid gap-3 md:grid-cols-2"> + {platforms.map((p) => { + const posts = socialPosts(publish[p]); + const text = composeSocialText(publish[p]) ?? ""; + const by = drafted[`publish.${p}`]; + return ( + <section key={p} data-social={p} aria-label={`${SOCIAL_NAMES[p]} post`} className="min-w-0 space-y-1.5"> + <div className="flex flex-wrap items-baseline gap-2"> + <h3 className="text-[12.5px] font-medium text-text">{SOCIAL_NAMES[p]}</h3> + <span className="font-mono text-[11px] text-muted" data-social-status=""> + {written[p] !== null ? `out/${socialTextName(p)}, written ${fmtAgo(written[p]!)}` : "not written to out/ yet"} + {by ? ` · drafted by ${by.model ?? "a model"}` : ""} + </span> + <span className="ml-auto"> + <CopyButton text={text} label="Copy" title={`copy the ${SOCIAL_NAMES[p]} post${posts.length > 1 ? " and its thread" : ""}`} /> + </span> + </div> + <ol className="m-0 list-none space-y-1.5 p-0"> + {posts.map((t, i) => { + const n = socialLength(p, t); + const over = n > SOCIAL_LIMITS[p]; + return ( + <li key={i} data-social-post={i} className="rounded-[3px] border border-seam-2 bg-ground px-2.5 py-1.5"> + <pre className="m-0 whitespace-pre-wrap break-words font-mono text-[11.5px] text-text">{t}</pre> + <div className="mt-1 text-right font-mono text-[10.5px] text-meter" data-social-count={n} data-social-over={over ? "" : undefined}> + {posts.length > 1 ? `${i + 1}/${posts.length} · ` : ""} + {n}/{SOCIAL_LIMITS[p]} {p === "bluesky" ? "graphemes" : "as X counts"} + {over ? " — over the limit" : ""} + </div> + </li> + ); + })} + </ol> + </section> + ); + })} + </div> + </Panel> + ); +} diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx @@ -6,6 +6,7 @@ import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/project import MediaDrafts, { type FieldProvenance } from "../MediaDrafts"; import OnscreenSection from "../OnscreenSection"; import YoutubeSection from "../YoutubeSection"; +import SocialPostSection from "../SocialPostSection"; import type { DraftsView } from "../drafts"; import type { ReportTabProps } from "./shared"; @@ -13,7 +14,7 @@ import type { ReportTabProps } from "./shared"; // says over its footage -- every drafted field with its provenance and // review, each section's "Draft with <model>", Draft everything and Approve // all (components/projects/MediaDrafts.tsx); then the on-screen panel whole -// (moved out of Build) and the upload's text. Release 28's review page, +// (moved out of Build), the upload's text and the promotion posts. Release 28's review page, // Draft panel and the Iterations tab's media drafts are this now; the // narration's words are edited and played on its bench (…/narration), the // fields walked one at a time on the review bench (…/review). @@ -52,6 +53,9 @@ export default async function MediaTab({ project, detail }: ReportTabProps) { {/* --- the upload's text (out/youtube.txt, or its preview) --------- */} <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> + + {/* --- the promotion posts (publish.x, publish.bluesky; text only) - */} + <SocialPostSection dir={project.dir} manifest={m as Record<string, unknown>} /> </> ); } diff --git a/umtool/docs/authoring.md b/umtool/docs/authoring.md @@ -139,7 +139,7 @@ pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n> `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 + YouTube, the social posts) each draft fields of the iteration's cut, marked as drafts: the piece's **Media** tab (**Draft with <model>** per section, **Draft everything**), or `pnpm ops report-draft` with `iteration`. A field you wrote or edited is never replaced; the draft waits in `<task>-draft.json` @@ -147,9 +147,11 @@ pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n> 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 + the podcast, then drafts the YouTube text and writes `out/youtube.txt`, then + the posts for X and Bluesky (`out/x.txt`, `out/bluesky.txt`; text only). A failed draft does not stop it; flips and threads need the deck, and one - panel only. + panel only — **with the deck** (`--deck`) adds the minimal deck to a cut + with none before the flips. - **Review every draft before a final build:** the Media tab, or the review bench `/projects/<project>/review`: **Approve draft**, or **Reject** with a note. A fast build warns; `--preset final` refuses an unapproved or rejected draft (`--drafts-unreviewed` overrides diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -423,7 +423,7 @@ function continuation(article, rn, force, given) { // 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"]); +const MEDIA_RUN = new Set(["cut", "onscreen", "teaser", "social"]); function startMediaDraft(body, id) { const { task, article } = body; const n = body.iteration; @@ -473,11 +473,15 @@ function startMediaDraft(body, id) { // 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 +// flips no deck to draw on failed +// with a deck (Draft everything's deck option, release 29 G1): +// one THEN/NOW pair over its two clips done +// threads no deck to draw on failed // narrate a line on each card that has none done // youtube a title and a summary done +// social an X and a Bluesky post (release 29 G2) done const CANNED_ARTICLES = new Set(["msurf"]); -const MEDIA_TASKS = new Set(["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]); +const MEDIA_TASKS = new Set(["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube", "social"]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); function cannedUnits(task, m, body) { @@ -499,7 +503,12 @@ function cannedUnits(task, m, body) { })); 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 "flips": { + const clips = tl.filter((e) => e.type === "clip"); + if (!isObj(m.render?.chrome) || clips.length < 2) return { refused: "the cut has no on-screen deck (render.chrome) to draw the flips on" }; + const side = (e, when) => ({ entry: e.id, when, words: e.quote ?? e.id }); + return [{ id: "flips", target: { field: "render.chrome.flips" }, value: { pairs: [{ id: "county", topic: "The county vote", then: side(clips[0], "Mar 2024"), now: side(clips[1], "Apr 2024") }] } }]; + } case "threads": return { refused: `the cut has no on-screen deck (render.chrome) to draw the ${task} on` }; case "narrate": @@ -510,6 +519,11 @@ function cannedUnits(task, m, body) { })); 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." } }]; + case "social": + return [ + { id: "x", target: { field: "publish.x" }, value: { post: "The county vote, as the channel told it.", thread: ["The channel said it twice."] } }, + { id: "bluesky", target: { field: "publish.bluesky" }, value: { post: "The county vote, as the channel told it." } }, + ]; } return []; } @@ -518,6 +532,8 @@ 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; + if (t.field === "publish.x" || t.field === "publish.bluesky") return m.publish?.[t.field.slice("publish.".length)]; + if (t.field === "render.chrome.flips") return m.render?.chrome?.flips; return undefined; } diff --git a/umtool/e2e/fixtures/media-draft-fixture.mjs b/umtool/e2e/fixtures/media-draft-fixture.mjs @@ -4,10 +4,11 @@ // 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 +// articles/mdraft/iterations/{1,2,3,4} sweep, qwen3:8b, done; the kit's report +// gen-projects/mdraft/i{1,2,3,4}/ 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 +// i4 the social task's (release 29 G2) // // 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/ @@ -19,7 +20,7 @@ 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 }; +export const MEDIA_DRAFT_ITERATIONS = { cut: 1, onscreen: 2, teaser: 3, social: 4 }; const put = (file, value) => { mkdirSync(path.dirname(file), { recursive: true }); diff --git a/umtool/e2e/fixtures/media-surfaces-fixture.mjs b/umtool/e2e/fixtures/media-surfaces-fixture.mjs @@ -10,6 +10,8 @@ // (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 +// gen-projects/msurf/i3/ Draft everything with the deck (release 29 +// G1): the deck step, then the flips drafted // // The editor stub drafts this article's media CANNED (editor-stub.mjs // cannedDraft): every media task, its field written through applyDraft with its @@ -43,7 +45,7 @@ export function makeMediaSurfacesFixture({ dest, articles, manifest, cachedWindo 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]) { + for (const n of [1, 2, 3]) { 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"), { @@ -73,6 +75,9 @@ export function makeMediaSurfacesFixture({ dest, articles, manifest, cachedWindo { 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 }; + // i3's cut is full HD: the minimal deck (its defaults) needs the room a + // full frame has, and its chain is cancelled before any build. + if (n === 3) m.render = { ...(m.render ?? {}), width: 1920, height: 1080 }; // 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); diff --git a/umtool/e2e/media-draft.spec.ts b/umtool/e2e/media-draft.spec.ts @@ -86,3 +86,27 @@ test("teaser: a cut with none gets one after its last clip, its lines drafted an 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 }); }); + +test("social (release 29 G2): a post for X and one for Bluesky with their threads, counted by code; no link for an article not public; shown on the Media tab with Copy", async ({ page }) => { + test.setTimeout(120_000); + await draft(page, "social", 4); + const m = manifestOf(4); + expect(m.publish.x).toEqual({ + post: 'Synth Kitchen\'s baker says "I would never sell the bakery to a chain" and that she paid for the new mixer herself.', + thread: ["In a later stream she says she did not enter the contest this year.", "She will not talk about the lease."], + }); + expect(m.publish.bluesky.post).toBe("What the baker of Synth Kitchen says about the bakery: she would not sell it to a chain, and she paid for the new mixer herself."); + expect(m.drafted["publish.x"]).toMatchObject({ task: "social", model: "qwen3:8b", iteration: 4, attempt: 2 }); + expect(m.drafted["publish.bluesky"]).toMatchObject({ task: "social", attempt: 1 }); + const d = draftFileOf(4, "social"); + expect(d.units.x.attempts[0].hard.join(" | ")).toMatch(/the narrator is third person/); + // The Media tab shows each platform's posts with their counted lengths, and Copy. + await page.goto(urls.section(`gen-projects/${ARTICLE}/i4`, "drafts")); + const panel = page.getByRole("region", { name: "Social posts" }); + await expect(panel.getByRole("region", { name: "X post" }).locator("[data-social-post]")).toHaveCount(3); + await expect(panel.getByRole("region", { name: "X post" }).locator("[data-social-count]").first()).toHaveText(`1/3 · ${m.publish.x.post.length}/280 as X counts`); + await expect(panel.getByRole("region", { name: "Bluesky post" }).locator("[data-social-count]").first()).toHaveText(`1/2 · ${m.publish.bluesky.post.length}/300 graphemes`); + await expect(panel.getByRole("region", { name: "X post" }).getByRole("button", { name: "Copy" })).toBeVisible(); + // Its draft row on the Media tab, in Draft everything's order (the last). + await expect(page.locator("[data-media-chip='social']")).toBeVisible(); +}); diff --git a/umtool/e2e/media-surfaces.spec.ts b/umtool/e2e/media-surfaces.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WARM_TIMEOUT, warm } from "./warm"; @@ -42,8 +42,8 @@ test("Draft with <model> per section: the job followed, the badge, the last run, await page.goto(urls.section(PROJECT, "drafts")); const panel = page.getByRole("region", { name: "Media drafts" }); 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); + // Eight sections (release 29 G2: the social posts); flips and threads say why they cannot draft on this cut. + await expect(panel.locator("[data-draft-task]")).toHaveCount(8); 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. @@ -110,9 +110,9 @@ test("Draft everything: every draft in order on the model chosen, a refused one const before = asked().length; await page.getByRole("button", { name: "Draft everything" }).click(); const chain = page.getByRole("region", { name: "i2 Draft everything" }); - await expect(chain.locator("[data-chain-step]")).toHaveCount(15); + await expect(chain.locator("[data-chain-step]")).toHaveCount(16); 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(step("draft-social")).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"], @@ -127,6 +127,7 @@ test("Draft everything: every draft in order on the model chosen, a refused one ["video", "done"], ["podcast", "done"], ["draft-youtube", "done"], + ["draft-social", "done"], ] as const) { await expect(step(name), name).toHaveAttribute("data-step-status", status); } @@ -134,7 +135,7 @@ test("Draft everything: every draft in order on the model chosen, a refused one // 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.map((r) => r.task)).toEqual(["cut", "onscreen", "teaser", "narrate", "youtube", "social"]); 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" }); @@ -146,4 +147,40 @@ test("Draft everything: every draft in order on the model chosen, a refused one 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"); + // The social posts (release 29 G2), as files to copy. + expect(m.publish.x.post).toBe("The county vote, as the channel told it."); + expect(readFileSync(path.join(out, "x.txt"), "utf8")).toBe("The county vote, as the channel told it.\n\n— 2/2 —\nThe channel said it twice.\n"); + expect(readFileSync(path.join(out, "bluesky.txt"), "utf8")).toBe("The county vote, as the channel told it.\n"); + // Off by default: no deck step, and the cut still has no deck. + await expect(chain.locator("[data-chain-step='deck']")).toHaveCount(0); + expect(m.render.chrome).toBeUndefined(); +}); + +test("Draft everything with the deck (release 29 G1): the deck step adds the minimal deck, the flips are drafted on it, the threads then skipped", async ({ page }) => { + test.setTimeout(240_000); + await page.goto(urls.articleHref({ site: "articles", id: ARTICLE }, { tab: "iterations" })); + await page.locator("[data-iteration='3'] [data-media-link]").click(); + await expect(page.getByRole("region", { name: "Media drafts" })).toHaveAttribute("data-draft-panel", `${ARTICLE}/i3`); + expect(manifestOf(3).render.chrome).toBeUndefined(); + await page.getByRole("combobox", { name: "Draft everything model" }).selectOption("qwen3:8b"); + await page.getByRole("checkbox", { name: "with the deck" }).check(); + const before = asked().length; + await page.getByRole("button", { name: "Draft everything" }).click(); + const chain = page.getByRole("region", { name: "i3 Draft everything" }); + await expect(chain.locator("[data-chain-step]")).toHaveCount(17); + const step = (name: string) => chain.locator(`[data-chain-step='${name}']`); + await expect(step("draft-threads")).toHaveAttribute("data-step-status", "skipped", { timeout: 180_000 }); + // Done with what this case is about: the build is the other test's. + await chain.getByRole("button", { name: "Cancel the chain" }).click(); + await expect(step("deck")).toHaveAttribute("data-step-status", "done"); + await expect(step("deck")).toContainText("deck added"); + await expect(step("draft-flips")).toHaveAttribute("data-step-status", "done"); + await expect(step("draft-threads")).toContainText("the cut has flips"); + const m = manifestOf(3); + expect(m.render.chrome).toMatchObject({ engine: "hyperframes", layout: "deck", deck: {} }); + expect(m.render.chrome.flips.pairs[0].id).toBe("county"); + expect(m.drafted["render.chrome.flips"]).toMatchObject({ task: "flips", model: "qwen3:8b", iteration: 3 }); + // The cut before the deck is in revisions/. + expect(readdirSync(path.join(projectDir(3), "revisions")).some((f) => f.includes("auto-before-deck"))).toBe(true); + expect(asked().slice(before).map((r) => r.task).slice(0, 4)).toEqual(["cut", "onscreen", "teaser", "flips"]); }); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -362,6 +362,8 @@ function projectIdOfDir(dir: string | null): string | null { export type ChainMode = "video" | "draft-all"; export type ChainView = { mode: ChainMode; + /** Draft everything with its deck step (release 29 G1). */ + deck: boolean; 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; @@ -488,19 +490,25 @@ export function projectsRootOf(gen: GenerationSettings): string { return gen.projectsRoot ? expandHome(gen.projectsRoot) : DEFAULT_PROJECTS_ROOT; } -export function chainViewOf(article: string, it: IterationRow, mode: ChainMode = "video"): ChainView { +/** + * An iteration's chain as umtool shows it. `deck` (Draft everything's option, + * release 29 G1) lists the deck step; so does an iteration that recorded one. + */ +export function chainViewOf(article: string, it: IterationRow, mode: ChainMode = "video", { deck = false }: { deck?: boolean } = {}): ChainView { const done = new Set(doneSteps({ steps: it.steps })); 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 }[]; + const withDeck = mode === "draft-all" && (deck || byTask.has("chain:deck")); + const defs = chainStepsOf(mode, { deck: withDeck }) as { name: string; label: string; optional?: boolean }[]; return { mode, + deck: withDeck, 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[]; mode: string }) => string | null)({ done: [...done], mode }), + resumeAt: (chainStart as (o: { done: string[]; mode: string; deck: boolean }) => string | null)({ done: [...done], mode, deck: withDeck }), job: job ? { id: job.id, diff --git a/umtool/lib/articles/projectDraft.ts b/umtool/lib/articles/projectDraft.ts @@ -14,7 +14,7 @@ import { sitesPaths } from "./sites"; // 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 const PROJECT_DRAFT_TASKS = ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube", "social"] as const; export type ProjectDraftTask = (typeof PROJECT_DRAFT_TASKS)[number]; export type ProjectIteration = @@ -226,5 +226,14 @@ export function draftRowsOf(manifest: Record<string, unknown>): DraftRowView[] { entries: null, blocked: null, }, + { + task: "social", + label: "social posts", + writes: "a post for X (280, a link 23) and for Bluesky (300 graphemes), each with up to 4 more under it; the link added by code; text only, never posted", + state: `the X post is ${ownerWords(ownerOf(manifest, { field: "publish.x" }))}, the Bluesky post ${ownerWords(ownerOf(manifest, { field: "publish.bluesky" }))}`, + address: null, + entries: null, + blocked: null, + }, ]; } diff --git a/umtool/lib/create/create.test.mjs b/umtool/lib/create/create.test.mjs @@ -5,8 +5,8 @@ import { policyChip, routeGroups, routeSummary } from "./policy.mjs"; import { estimateOf, estimateText, spendHistory } from "./estimate.mjs"; import { chainable, defaultChainIteration } from "./iterations.mjs"; -const TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; -const media = (r) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }); +const TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"]; +const media = (r) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }); const BALANCED = { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...media("local") }; test("the balanced preset in one line: grouped by route, drafts as one word", () => { @@ -19,7 +19,7 @@ test("one route for everything says so; agreeing revisions are one word; split d assert.equal(routeSummary(api, TASKS), "everything on the API"); assert.equal(routeSummary(Object.fromEntries(TASKS.map((t) => [t, "local"])), TASKS), "everything local"); const custom = { ...api, sweep: "code", narrate: "local" }; - assert.equal(routeSummary(custom, TASKS), "Claude Code: sweeps · API: revisions, research, cut drafts, on-screen drafts, teaser drafts, flips drafts, threads drafts, YouTube drafts · local: narration"); + assert.equal(routeSummary(custom, TASKS), "Claude Code: sweeps · API: revisions, research, cut drafts, on-screen drafts, teaser drafts, flips drafts, threads drafts, YouTube drafts, social post drafts · local: narration"); }); test("the chip names the preset, or why there is none", () => { diff --git a/umtool/lib/create/policy.mjs b/umtool/lib/create/policy.mjs @@ -12,7 +12,7 @@ export const ROUTE_WORD = { code: "Claude Code", api: "API", local: "local" }; /** The media drafts (release 28) and narration: one word, "drafts", when they agree. */ -const DRAFT_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]; +const DRAFT_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"]; /** One task's word when it is said alone. */ const TASK_WORD = { @@ -27,6 +27,7 @@ const TASK_WORD = { flips: "flips drafts", threads: "threads drafts", youtube: "YouTube drafts", + social: "social post drafts", }; /** diff --git a/umtool/lib/report/chain-draft.mjs b/umtool/lib/report/chain-draft.mjs @@ -5,6 +5,22 @@ import { flipsOn, threadsOn } from "yt-dlp-transcript-common/lib/report/panels.mjs"; +/** + * The minimal on-screen deck: every deck setting its default (deck.mjs + * DECK_DEFAULTS). What the On-screen section's switch turns on and what + * Draft everything's deck step (release 29 G1) adds to a cut with none -- + * one constructor, a fresh object each call. + * + * @returns {{ engine: "hyperframes", layout: "deck", deck: Record<string, never> }} + */ +export function deckChrome() { + return { engine: "hyperframes", layout: "deck", deck: {} }; +} + +/** A deck step's line: what it did. */ +export const deckStepDetail = (added) => + added ? "deck added: render.chrome with every setting its default (a snapshot of the cut before it is in revisions/)" : "deck already there: the cut's render.chrome is kept as it is"; + /** 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`); diff --git a/umtool/lib/report/chain-draft.test.mjs b/umtool/lib/report/chain-draft.test.mjs @@ -12,12 +12,12 @@ 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 { mkdirSync, mkdtempSync, readFileSync, readdirSync, 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"; +import { deckChrome, deckStepDetail, draftOutcome, draftPrecheck, draftFileOf } from "./chain-draft.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const KIT = path.join(HERE, "..", "..", "..", "common", "testing", "draft"); @@ -67,6 +67,7 @@ const plan = { 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" }, + social: { end: "done", summary: "2 social posts drafted" }, flips: { end: "slow" }, }; const requests = []; @@ -204,6 +205,20 @@ test("the YouTube draft with no build yet: done, and the next build writes out/y assert.equal(recorded("draft-youtube").detail, "1 title and description drafted; the next build writes out/youtube.txt"); }); +test("the social draft (release 29 G2): done, and its posts written to out/x.txt and out/bluesky.txt — no build needed", async () => { + const file = path.join(PROJECT, "video.manifest.json"); + const link = "https://archilyzer.example/articles/synth-basic/"; + put(file, { ...baseManifest, publish: { x: { post: `The post.\n\n${link}`, thread: ["Two."] }, bluesky: { post: `The post.\n\n${link}` } } }); + const r = await (await step("draft-social")).done; + assert.equal(r.code, 0, r.out); + assert.deepEqual(requests.at(-1), { task: "social", article: "synth-basic", iteration: 1 }); + assert.equal(recorded("draft-social").status, "done"); + assert.equal(recorded("draft-social").detail, "2 social posts drafted; out/x.txt and out/bluesky.txt written"); + assert.equal(readFileSync(path.join(PROJECT, "out", "x.txt"), "utf8"), `The post.\n\n${link}\n\n— 2/2 —\nTwo.\n`); + assert.equal(readFileSync(path.join(PROJECT, "out", "bluesky.txt"), "utf8"), `The post.\n\n${link}\n`); + put(file, baseManifest); +}); + 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"); @@ -218,7 +233,31 @@ test("a cancel of the chain cancels the editor's job, and the step is recorded c assert.equal(recorded("draft-flips").status, "cancelled"); }); +test("the deck step (release 29 G1): the minimal deck on a cut with none, a snapshot first; a cut with one is left as it is", async () => { + const file = path.join(PROJECT, "video.manifest.json"); + put(file, baseManifest); + assert.match(draftPrecheck("flips", json(file)), /no on-screen deck/); + const asked = requests.length; + const r = await (await step("deck")).done; + assert.equal(r.code, 0, r.out); + assert.equal(requests.length, asked, "no model, no editor"); + assert.equal(recorded("deck").status, "done"); + assert.equal(recorded("deck").detail, deckStepDetail(true)); + const m = json(file); + assert.deepEqual(m.render.chrome, deckChrome()); + assert.deepEqual({ ...m, render: { ...m.render, chrome: undefined } }, { ...baseManifest, render: { ...baseManifest.render, chrome: undefined } }, "nothing else changed"); + assert.ok(readdirSync(path.join(PROJECT, "revisions")).some((f) => f.includes("auto-before-deck"))); + assert.equal(draftPrecheck("flips", m), null); + const before = readFileSync(file, "utf8"); + const again = await (await step("deck")).done; + assert.equal(again.code, 0, again.out); + assert.equal(recorded("deck").detail, "deck already there: the cut's render.chrome is kept as it is"); + assert.equal(readFileSync(file, "utf8"), before); + put(file, baseManifest); +}); + test("draftPrecheck and draftOutcome, pure", () => { + assert.notEqual(deckChrome(), deckChrome(), "a fresh object each call"); assert.equal(draftPrecheck("cut", {}), null); assert.match(draftPrecheck("threads", { render: {} }), /no on-screen deck/); assert.equal(draftPrecheck("threads", { render: { chrome: {} } }), null); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -21,6 +21,10 @@ // 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. +// +// The deck step (`deck`, release 29 G1, Draft everything's option) asks no +// model: it adds the minimal on-screen deck through umtool's manifest writer +// (manifest.mjs addDeckChrome: a snapshot first) when the cut has none. import { spawn } from "node:child_process"; import { copyFile, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; @@ -46,7 +50,9 @@ import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; -import { draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; +import { deckChrome, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; +import { addDeckChrome } from "./manifest.mjs"; +import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; @@ -365,6 +371,15 @@ async function youtubeText(ctx) { return code === 0 ? "; out/youtube.txt written" : `; out/youtube.txt not written (build-video --chapters-only ended ${code})`; } +// The deck option (release 29 G1): the minimal deck on a cut with none, so +// flips and threads have a panel to draw on; a cut with a deck is untouched. +STEPS.deck = async (ctx) => { + const file = path.join(ctx.project, "video.manifest.json"); + if (!(await exists(file))) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); + const r = await addDeckChrome(ctx.project, deckChrome()); + return deckStepDetail(r.added); +}; + for (const name of ["cut", "onscreen", "teaser", "flips", "threads", "narrate"]) { STEPS[`draft-${name}`] = (ctx) => draftStep(ctx, name); } @@ -373,6 +388,33 @@ STEPS["draft-youtube"] = async (ctx) => { return `${said}${await youtubeText(ctx)}`; }; +// After the social draft (release 29 G2), its posts as files to copy: +// out/x.txt and out/bluesky.txt (report-to-video/social.mjs; the build writes +// them too). They need no build: the posts are the manifest's. +async function writeSocialFiles(ctx) { + const manifest = await readJsonOr(path.join(ctx.project, "video.manifest.json")); + const out = path.join(ctx.project, "out"); + await mkdir(out, { recursive: true }); + const written = []; + for (const { name, text } of socialTexts(manifest)) { + if (text === null) continue; + await writeFile(path.join(out, name), text, "utf8"); + written.push(`out/${name}`); + } + return written.length ? `${written.join(" and ")} written` : "no post to write"; +} +STEPS["draft-social"] = async (ctx) => { + let said; + try { + said = await draftStep(ctx, "social"); + } catch (err) { + // Nothing to draft (both posts written already): their files still are. + if (err instanceof StepSkipped) throw new StepSkipped(`${err.message}; ${await writeSocialFiles(ctx)}`); + throw err; + } + return `${said}; ${await writeSocialFiles(ctx)}`; +}; + async function writeJson(file, value) { const tmp = `${file}.tmp-${process.pid}`; await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs @@ -27,18 +27,28 @@ // 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 +// draft-youtube → draft-social // // 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 +// out/youtube.txt is written; the social posts (release 29 G2) after it, +// written to out/x.txt and out/bluesky.txt. 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. // +// THE DECK OPTION (release 29 G1, off by default): Draft everything with +// `deck` has one more step, `deck`, before draft-flips — no model: it writes +// the minimal on-screen deck (`render.chrome`, ./chain-draft.mjs deckChrome) +// through umtool's manifest writer (an `auto-before-deck` snapshot first), +// ONLY when the cut has no `render.chrome`, so flips and threads have a deck +// to draw on; a cut with one is left as it is. Without the option the chain +// is exactly the one above (a step with `option` is in a chain only when its +// option is on). +// // 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 @@ -71,6 +81,7 @@ export const CHAIN_STEPS = [ { 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: "deck", label: "add the on-screen deck when the cut has none", timeoutMs: 5 * 60_000, modes: DRAFT_ONLY, optional: true, option: "deck" }, { 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" }, @@ -78,6 +89,7 @@ export const CHAIN_STEPS = [ { 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: "draft-social", label: "draft the posts for X and Bluesky", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "social" }, { 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 }, ]; @@ -85,10 +97,19 @@ export const CHAIN_STEPS = [ /** 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") { +/** The chains' options: `deck` (Draft everything's deck step, release 29 G1). Each is off by default. */ +export const CHAIN_OPTIONS = ["deck"]; + +/** + * A chain's steps, in order. A step with an `option` is in it only when that + * option is on (`{ deck: true }`); with none on, the chain is as it always was. + * + * @param {string} [mode] + * @param {{ deck?: boolean }} [options] + */ +export function chainStepsOf(mode = "video", options = {}) { if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`); - return CHAIN_STEPS.filter((s) => s.modes.includes(mode)); + return CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true)); } /** Every step's name, either chain's (what the executor runs). */ @@ -150,8 +171,8 @@ export function chainProject(projectsRoot, article, n) { * has not recorded finished (`done`: the step names recorded finished, * doneSteps), else nothing (the whole chain is done: null). */ -export function chainStart({ from = null, done = [], mode = "video" } = {}) { - const names = chainStepsOf(mode).map((s) => s.name); +export function chainStart({ from = null, done = [], mode = "video", deck = false } = {}) { + const names = chainStepsOf(mode, { deck }).map((s) => s.name); if (from !== null && from !== undefined) { if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`); return from; @@ -193,16 +214,18 @@ export function readIterationRecord(articlesDir, article, n) { * (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). + * `final` says, and `model` rides on the draft steps (else each task's route); + * `deck` adds its deck step (G1). * - * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string }} o + * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean }} o * @returns {import("../trim").Step[]} */ export function chainSteps(o) { const projectsRoot = o.projectsRoot ?? configuredProjectsRoot(); chainProject(projectsRoot, o.article, o.n); const mode = o.mode ?? "video"; - const defs = chainStepsOf(mode); + if (o.deck === true && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); + const defs = chainStepsOf(mode, { deck: o.deck === true }); const start = o.start === undefined ? defs[0].name : o.start; if (start === null) return []; const at = defs.findIndex((s) => s.name === start); @@ -233,25 +256,28 @@ export function chainSteps(o) { * iteration not done, or an unknown `from`. `steps` is empty when every step * is done. * - * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string }} o + * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean }} 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 mode = o.mode ?? "video"; - const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode }); + const deck = o.deck === true; + if (deck && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); + const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck }); const steps = chainSteps({ article: o.article, n: o.n, start, mode, + ...(deck ? { deck } : {}), ...(o.model ? { model: o.model } : {}), ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}), ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}), final: o.final === true, }); - return { record, start, steps, mode }; + return { record, start, steps, mode, deck }; } 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 @@ -22,6 +22,7 @@ import { chainSteps, chainWindows, chainStepsOf, + CHAIN_OPTIONS, DRAFT_STEP_TASKS, doneSteps, originFromSweep, @@ -53,6 +54,35 @@ test("the steps, in order, each one process of the executor under tsx, from the assert.equal(chainProject("/p", "a", 2), path.join("/p", "a", "i2")); }); +test("the deck option (release 29 G1): a step before the flips, off by default — without it the chain is as it was", () => { + assert.deepEqual(CHAIN_OPTIONS, ["deck"]); + const plain = chainStepsOf("draft-all").map((s) => s.name); + assert.ok(!plain.includes("deck")); + const withDeck = chainStepsOf("draft-all", { deck: true }).map((s) => s.name); + assert.deepEqual(withDeck.filter((n) => n !== "deck"), plain); + assert.equal(withDeck.indexOf("deck"), withDeck.indexOf("draft-flips") - 1); + assert.equal(withDeck.indexOf("deck"), withDeck.indexOf("draft-teaser") + 1); + // Not the video chain's; an option the chain is not asked for adds nothing. + assert.deepEqual(chainStepsOf("video", { deck: true }).map((s) => s.name), CHAIN_STEP_NAMES); + assert.deepEqual(chainStepsOf("draft-all", { deck: false }).map((s) => s.name), plain); + // The step asks no model: no --model on it, and the labels count it. + const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", deck: true }); + const deck = steps.find((s) => s.argv[7] === "deck"); + assert.ok(deck && !deck.argv.includes("--model")); + assert.equal(steps.length, withDeck.length); + assert.match(deck.label, new RegExp(`^${withDeck.indexOf("deck") + 1}/${withDeck.length} add the on-screen deck`)); + assert.deepEqual( + chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all" }).map((s) => s.argv[7]), + plain, + ); + assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", deck: true }), /the deck is Draft everything's option/); + // Resume: a chain that ran to the threads without the deck starts again at the deck with it. + const ran = ["current", "windows", "prepare", "posts", "manifest", "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads"]; + assert.equal(chainStart({ done: ran, mode: "draft-all", deck: true }), "deck"); + assert.equal(chainStart({ done: ran, mode: "draft-all" }), "draft-narrate"); + assert.ok(doneSteps({ steps: [{ task: "chain:deck", status: "failed" }] }).includes("deck"), "optional: a failed deck step is passed"); +}); + test("resume: the first step not recorded done; --from names one; all done is nothing", () => { const it = { steps: [ @@ -75,16 +105,16 @@ test("Draft everything: the drafts between the manifest and the fast build, YouT 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", + "voices", "video", "podcast", "draft-youtube", "draft-social", ]); 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.deepEqual(DRAFT_STEP_TASKS, ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube", "social"]); 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"); + assert.equal(steps.length, 16); + assert.equal(steps[5].label, "6/16 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-"); @@ -174,10 +204,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus 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.deepEqual(all.steps.map((s) => s.argv[7]).slice(-2), ["draft-youtube", "draft-social"]); assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5")); assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr))); assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr))); + // --deck (release 29 G1): the deck step before the flips; Draft everything's only. + const deck = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--deck", "--projects-root", path.join(ROOT, "projects"))); + assert.deepEqual(deck.steps.map((s) => s.argv[7]).slice(6, 8), ["deck", "draft-flips"]); + assert.throws(() => run("art", "2", "--dry", "--deck"), (e) => /--deck is Draft everything's option/.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 @@ -125,3 +125,21 @@ test("writeDraftedField: a threads alternative's clips set each clip's thread wi ); assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before); }); + +test("writeDraftedField: Use this on a social post (release 29 G2) writes it as the operator's, within its platform's count", async (t) => { + const m = drafted(); + m.publish.x = { post: "The drafted post." }; + m.drafted["publish.x"] = P("social"); + const p = await project(t, m); + await writeDraftedField(p.dir, { field: "publish.x", value: { post: "My post.\n\nhttps://archilyzer.example/articles/a/", thread: ["Two."] } }); + const after = await p.read(); + assert.deepEqual(after.publish.x, { post: "My post.\n\nhttps://archilyzer.example/articles/a/", thread: ["Two."] }); + assert.equal(after.drafted["publish.x"], undefined, "the operator's now"); + assert.deepEqual(after.publish.youtube, { title: "T", description: "D" }, "the other publish keys kept"); + await writeDraftedField(p.dir, { field: "publish.bluesky", value: { post: "A Bluesky post." } }); + assert.equal((await p.read()).publish.bluesky.post, "A Bluesky post."); + await assert.rejects( + writeDraftedField(p.dir, { field: "publish.bluesky", value: { post: "x".repeat(301) } }), + (e) => e instanceof StructureRefused && /publish\.bluesky\.post is 301 graphemes \(at most 300\)/.test(e.message), + ); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -629,6 +629,33 @@ export async function updateChrome(dir, chrome, { token = null } = {}) { }); } +/** + * Put `chrome` (the minimal deck) on a cut that has NO `render.chrome`, and + * leave a cut that has one as it is (release 29 G1: Draft everything's deck + * step). A structural change -- the cut gains a panel -- so the file as it + * still is goes to revisions/ first (`auto-before-deck`), as every structural + * write does; then validateChrome, then the write. `{ added: false }` writes + * nothing. + * + * @param {string} dir + * @param {Record<string, unknown>} chrome + * @returns {Promise<{ added: boolean, token: string | null, snapshot?: unknown }>} + */ +export async function addDeckChrome(dir, chrome) { + return withManifestLock(async () => { + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const render = manifest.render ?? {}; + if (render.chrome !== undefined && render.chrome !== null) return { added: false, token: await manifestToken(dir) }; + const { chrome: _none, ...rest } = render; + const errors = validateChrome(chrome, rest); + if (errors.length) throw new ChromeRefused(errors); + manifest.render = { ...render, chrome }; + const snapshot = await autoSnapshot(dir, "deck"); + const token = await writeManifestAtomic(dir, manifest); + return { added: true, token, snapshot }; + }); +} + /** validateChrome's sentences, thrown whole so a route can return each one. */ export class ChromeRefused extends Error { /** @param {string[]} errors */ @@ -1117,6 +1144,8 @@ export async function updateNarration(dir, id, text, { token = null, at = null } * — and the entries are checked as the build checks * them (validateThreadEntries) * publish.youtube `{ title, description }` (validatePublish) + * publish.x, .bluesky `{ post, thread? }` (validatePublish: each post + * within its platform's count) * * The cut's order ("timeline") is not taken this way: an order replaces every * entry, and is the cut task's to apply. @@ -1149,11 +1178,12 @@ export async function writeDraftedField(dir, { entry = null, field, value }, { t } return { entry, field, value: es[0][field] ?? null }; } - if (field === "publish.youtube") { - m.publish = { ...(m.publish && typeof m.publish === "object" ? m.publish : {}), youtube: copy() }; + if (field === "publish.youtube" || field === "publish.x" || field === "publish.bluesky") { + const key = field.slice("publish.".length); + m.publish = { ...(m.publish && typeof m.publish === "object" ? m.publish : {}), [key]: copy() }; const errors = validatePublish(m); if (errors.length) throw new StructureRefused(errors); - return { entry: null, field, value: m.publish.youtube }; + return { entry: null, field, value: m.publish[key] }; } const render = m.render ?? {}; if (!render.chrome || typeof render.chrome !== "object") { diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -708,6 +708,27 @@ 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). +### `publish.x`, `publish.bluesky` — the promotion posts (`out/x.txt`, `out/bluesky.txt`) + +```jsonc +"publish": { "x": { "post": "…\n\nhttps://…", // the first post, its link under it + "thread": ["…", "…"] }, // optional: up to 4 more posts under it + "bluesky": { "post": "…" }, + "videoUrl": "https://…" } // optional: the video's public URL (the posts' link) +``` + +Text only: nothing posts it. Each post is within its platform's count +(`common/lib/report/social.mjs`, the build's lint refuses one past it): X 280, +every URL weighed as 23 and an emoji as 2; Bluesky 300 graphemes. The `social` +task drafts both (grounded, third person, quotes only word for word; no links, +hashtags, @mentions or emoji of its own) and appends the link in code: the +`videoUrl`, else the article's page on the homepage when it is public there. +Every build that writes `out/youtube.txt` also writes `out/x.txt` and +`out/bluesky.txt` (`social.mjs`: the first post, then each thread post under a +`— k/n —` line), and removes one whose post is gone; Draft everything's social +step writes them without a build. The Media tab's **Social posts** shows each +post with its counted length and **Copy**. + ### The `image` entry type A still: the receipts a clip cannot say out loud — a post, a thread, a DM, a @@ -1246,10 +1267,11 @@ 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": {…} }` +"render.chrome.flips": {…}, "render.chrome.threads": {…}, "publish.youtube": {…}, +"publish.x": {…}, "publish.bluesky": {…} }` (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 +top-level key; the promotion posts, release 29). 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. diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -145,6 +145,7 @@ 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"; +import { socialTexts } from "./social.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). @@ -3999,6 +4000,25 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, } /** + * `out/x.txt` and `out/bluesky.txt` (social.mjs, release 29 G2): the cut's + * `publish.x` / `publish.bluesky` posts, for the operator to copy -- written + * wherever out/youtube.txt is (writeYoutubeText calls this first), whatever + * the variant (the posts are the cut's, not a variant's). A platform with no + * post has no file: an old one goes. + */ +export async function writeSocialText(manifest, outRoot) { + for (const { platform, name, text } of socialTexts(manifest)) { + const file = path.join(outRoot, name); + if (text === null) { + await rm(file, { force: true }); + continue; + } + await writeFile(file, text, "utf8"); + EMIT("social", { file: name, platform }); + } +} + +/** * `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 @@ -4009,6 +4029,7 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, * @param {string | null} [why] why there are no chapters (`--no-chapters`) */ async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why = null) { + await writeSocialText(manifest, outRoot); 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"}` }; diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs @@ -181,6 +181,7 @@ export function judgedText(field, value) { 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 === "publish.x" || field === "publish.bluesky") return [str(value?.post), ...(Array.isArray(value?.thread) ? value.thread.map(str) : [])].join(" / "); if (field === "timeline" && Array.isArray(value)) return value.map((e) => e?.id).join(", "); return JSON.stringify(value).slice(0, 500); } @@ -194,6 +195,8 @@ export const FIELD_LABELS = Object.freeze({ "render.chrome.flips": "flips", "render.chrome.threads": "threads", "publish.youtube": "YouTube title and description", + "publish.x": "X post", + "publish.bluesky": "Bluesky post", }); /** diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -39,6 +39,7 @@ "./render-cards": "./render-cards.mjs", "./resolve-windows": "./resolve-windows.mjs", "./shoot-page": "./shoot-page.mjs", + "./social": "./social.mjs", "./sources": "./sources.mjs", "./verify-build": "./verify-build.mjs", "./youtube": "./youtube.mjs" diff --git a/umtool/report-to-video/social.mjs b/umtool/report-to-video/social.mjs @@ -0,0 +1,60 @@ +// THE SOCIAL TEXT (release 29 G2): what a cut's promotion posts say, as files +// the operator copies from -- `out/x.txt` and `out/bluesky.txt`, composed by +// CODE from `publish.x` / `publish.bluesky` `{ post, thread? }` (drafted by +// the social task, its link already under the first post, or written by +// hand). TEXT ONLY: nothing here, or anywhere, posts it. +// +// <the first post, its link under it> +// +// — 2/3 — +// <a thread post> +// +// — 3/3 — +// <a thread post> +// +// The `— k/n —` lines are not part of any post: they say where one ends. +// How a post is counted is common's (lib/report/social.mjs); the lengths are +// the manifest's to keep within (validatePublish), so this composes what is +// there and says nothing about it. +// +// PURE: no fs. build-video.mjs writes the files (wherever it writes +// out/youtube.txt), and so does the chain's social draft. + +import { SOCIAL_PLATFORMS } from "yt-dlp-transcript-common/lib/report/social.mjs"; + +export { SOCIAL_PLATFORMS }; + +const text = (s) => (typeof s === "string" ? s.trim() : ""); + +/** A platform's posts in order: the first, then the thread's. Empty when there is no first post. */ +export function socialPosts(value) { + const post = text(value?.post); + if (!post) return []; + return [post, ...(Array.isArray(value?.thread) ? value.thread.map(text).filter(Boolean) : [])]; +} + +/** + * The file's text for one platform's `{ post, thread? }`, or null when it has + * no first post. + * + * @param {{ post?: string, thread?: string[] } | null | undefined} value + * @returns {string | null} + */ +export function composeSocialText(value) { + const posts = socialPosts(value); + if (!posts.length) return null; + if (posts.length === 1) return `${posts[0]}\n`; + return `${posts.map((p, i) => (i === 0 ? p : `— ${i + 1}/${posts.length} —\n${p}`)).join("\n\n")}\n`; +} + +/** The file a platform's text is written to, in the project's `out/`. */ +export const socialTextName = (platform) => `${platform}.txt`; + +/** + * Every platform's file for a manifest: `[{ platform, name, text }]`, `text` + * null when the manifest has no post for it (an old file is then removed by + * the writer, so out/ never shows a post the manifest no longer has). + */ +export function socialTexts(manifest) { + return SOCIAL_PLATFORMS.map((platform) => ({ platform, name: socialTextName(platform), text: composeSocialText(manifest?.publish?.[platform]) })); +} diff --git a/umtool/report-to-video/social.test.mjs b/umtool/report-to-video/social.test.mjs @@ -0,0 +1,47 @@ +// The social text (release 29 G2): out/x.txt and out/bluesky.txt composed by +// code from `publish.x` / `publish.bluesky` — the first post, then each +// thread post under a `— k/n —` line — and build-video's writer, which writes +// each platform's file and removes one whose post is gone. +// +// Run with: node --test umtool/report-to-video/social.test.mjs + +import assert from "node:assert/strict"; +import test, { after } from "node:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { composeSocialText, socialPosts, socialTextName, socialTexts } from "./social.mjs"; +import { writeSocialText } from "./build-video.mjs"; + +const ROOT = mkdtempSync(path.join(os.tmpdir(), "social-text-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const LINK = "https://archilyzer.example/articles/synth-basic/"; + +test("one post is the file; a thread is numbered under it, each post whole", () => { + assert.equal(composeSocialText({ post: `The post.\n\n${LINK}` }), `The post.\n\n${LINK}\n`); + assert.equal( + composeSocialText({ post: `The post.\n\n${LINK}`, thread: ["Two.", " ", "Three."] }), + `The post.\n\n${LINK}\n\n— 2/3 —\nTwo.\n\n— 3/3 —\nThree.\n`, + ); + assert.equal(composeSocialText({ post: " " }), null); + assert.equal(composeSocialText(undefined), null); + assert.deepEqual(socialPosts({ post: "a", thread: ["b", ""] }), ["a", "b"]); + assert.equal(socialTextName("x"), "x.txt"); + assert.deepEqual( + socialTexts({ publish: { bluesky: { post: "b" } } }).map((t) => [t.name, t.text]), + [ + ["x.txt", null], + ["bluesky.txt", "b\n"], + ], + ); +}); + +test("build-video writes each platform's file, and removes one whose post is gone", async () => { + writeFileSync(path.join(ROOT, "x.txt"), "an old post\n"); + await writeSocialText({ publish: { bluesky: { post: `The post.\n\n${LINK}`, thread: ["Two."] } } }, ROOT); + assert.equal(readFileSync(path.join(ROOT, "bluesky.txt"), "utf8"), `The post.\n\n${LINK}\n\n— 2/2 —\nTwo.\n`); + assert.equal(existsSync(path.join(ROOT, "x.txt")), false, "the manifest has no X post now"); + await writeSocialText({}, ROOT); + assert.equal(existsSync(path.join(ROOT, "bluesky.txt")), false); +});