Archilyzer · Source

archilyzer

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

commit 02fa0dd2fc95448f2bfb6de2b1166d91386f78e5
parent fe30313e52b41eb06b30eaf1feb39c3c60b83651
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 07:32:02 -0400

common, umtool, mcp: the social promotion text — drafted fields publish.x and publish.bluesky ({post, thread?}, text only, never posted; publish.videoUrl the operator's) counted by code in common/lib/report/social.mjs (X 280 with every URL 23 and an emoji 2, Bluesky 300 graphemes, a thread of at most 4) and checked by validatePublish; the `social` task on the media scaffold (one unit per platform; grounded, third person, quotes only verbatim, no links, hashtags, @mentions or emoji; the link appended in code — the video's URL, else a public article's page on the homepage); `social` in GENERATION_TASKS/MEDIA_STEP_TASKS with narrate's route; Draft everything's draft-social after draft-youtube; report-to-video/social.mjs → out/x.txt, out/bluesky.txt wherever out/youtube.txt is written; umtool's Social posts section (counted lengths, Copy) and its draft row; the kit's runs/social.json; docs, SETTINGS.md, COMMANDS.md

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 | 4+++-
Mcommon/bin/archilyzer.ts | 4++--
Mcommon/bin/gen.ts | 2+-
Mcommon/controller/reportDraft.ts | 9+++++----
Mcommon/lib/generationSettings.test.ts | 9++++++++-
Mcommon/lib/generationSettings.ts | 7++++---
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/app/api/ops/report-draft/route.ts | 2+-
Mmcp/src/generation.test.ts | 3++-
Mmcp/src/generation.ts | 13+++++++------
Mmcp/src/instructions.ts | 6+++++-
Msettings.json.example | 3++-
Mumtool/components/projects/MediaDrafts.tsx | 1+
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 | 4+++-
Mumtool/e2e/media-draft.spec.ts | 24++++++++++++++++++++++++
Mumtool/e2e/media-surfaces.spec.ts | 45+++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/articles/projectDraft.ts | 11++++++++++-
Mumtool/lib/create/create.test.mjs | 6+++---
Mumtool/lib/create/policy.mjs | 3++-
Mumtool/lib/report/chain-draft.test.mjs | 15+++++++++++++++
Mumtool/lib/report/chain-run.mjs | 28++++++++++++++++++++++++++++
Mumtool/lib/report/chain.mjs | 6++++--
Mumtool/lib/report/chain.test.mjs | 14+++++++++-----
Mumtool/lib/report/drafted-writer.test.mjs | 18++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 9++++++---
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+++++++++++++++++++++++++++++++++++++++++++++++
50 files changed, 1105 insertions(+), 74 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 @@ -200,6 +200,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 @@ -208,9 +209,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. | #### `generation.models` @@ -1088,7 +1089,8 @@ Default: "teaser": "local", "flips": "local", "threads": "local", - "youtube": "local" + "youtube": "local", + "social": "local" }, "models": { "api": "claude-sonnet-5-5", 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/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 @@ -350,7 +350,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; } @@ -709,7 +709,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,11 +14,11 @@ 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); -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] as const; +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social"] 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"]; @@ -27,7 +27,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") }, @@ -178,6 +178,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.", }; export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { 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"; @@ -101,6 +104,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/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/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -141,6 +141,7 @@ test("generation_policy sets a preset as its routes, and one route alone", async flips: "api", threads: "api", youtube: "api", + social: "api", }, }, }, @@ -301,7 +302,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); 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 } }; } @@ -581,7 +581,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 +597,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 +617,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 +634,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 +650,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/settings.json.example b/settings.json.example @@ -253,7 +253,8 @@ "teaser": "local", "flips": "local", "threads": "local", - "youtube": "local" + "youtube": "local", + "social": "local" }, "models": { "api": "claude-sonnet-5-5", 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]; 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 @@ -420,7 +420,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; @@ -470,11 +470,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) { @@ -496,7 +500,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": @@ -507,6 +516,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 []; } @@ -515,6 +529,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"), { 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]")).toHaveText(`${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"; @@ -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/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.test.mjs b/umtool/lib/report/chain-draft.test.mjs @@ -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"); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -52,6 +52,7 @@ 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 { 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"; @@ -387,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,12 +27,13 @@ // 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. @@ -88,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 }, ]; diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs @@ -105,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-"); @@ -204,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 @@ -1144,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. @@ -1176,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); +});