Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(announce): build the announcement factory that turns shipped surfaces into evidence-backed post packs
nirholas0a431cddb3de
diff --git a/.gitignore b/.gitignoreindex eadbd0b57..dacdf6a78 100644--- a/.gitignore+++ b/.gitignore@@ -647,3 +647,12 @@ HSO6cvibUAATRw9.jpg# Registry / extension build archives for the integrations (never committed)integrations/**/*.zip++# The announcement calendar, briefs and drafts (`npm run announce:plan`,+# `npm run announce:kit`). Generated from data/announcements.json, which is+# itself held out of the tree above, and carrying the same verbatim page and+# package descriptions: a handful name crypto projects other than $THREE, and+# lifting that gate is the owner's call. Nothing here is unique work: every file+# is regenerated by one command, and the finished packs (docs/announcements/)+# and queue items are committed as usual.+data/announce-plan/diff --git a/api/_lib/announce/brief.js b/api/_lib/announce/brief.jsnew file mode 100644index 000000000..66037e809--- /dev/null+++ b/api/_lib/announce/brief.js@@ -0,0 +1,228 @@+// The evidence brief: everything true about one surface, gathered before a word+// of copy is written.+//+// A post is only publishable here if every number and absolute in it sits in a+// claim backed by evidence that a machine can re-check (api/_lib/x-content/verify.js).+// Writing the copy first and hunting for evidence afterwards is what makes that+// expensive, so this module inverts it: collect the checkable facts first, then+// let the drafter write only from them.+//+// Five sources, in descending order of how much a reader can trust them:+//+// live page the rendered text of the route itself, harvested through the+// same Playwright reader the verifier uses. A sentence taken+// from here is evidence that passes by construction, because+// the check is "the live page contains this text".+// changelog data/changelog.json already holds plain-language summaries+// of user-visible changes, written for the community. When a+// surface has entries, they are the best raw material we own.+// docs docs/<slug>.md and anything under docs/ that names the route.+// package README and package.json for a package, worker, or service.+// archive the closest posts @trythreews already published, so the+// drafter is told what not to repeat rather than discovering+// it at the similarity gate.++import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { copySimilarity } from '../x-content/quality.js';+import { loadHistory } from '../x-content/queue.js';++const SITE = 'https://three.ws';+// The house style bans both dash glyphs everywhere, including quoted evidence,+// and a pack that embeds one fails `npm run check:announce`. A candidate that+// carries one is dropped rather than rewritten, because the verifier matches+// the string against the live page character for character.+const DASHED = new RegExp('[\\u2014\\u2013]');+const ENDPOINT_RE = /\b(GET|POST|PUT|PATCH|DELETE)\s+(\/api\/[A-Za-z0-9/:_.\-{}]+)/g;++const read = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : '');++// Prose paragraphs of a Markdown file, with the scaffolding (headings, tables,+// code, badges) removed. Those carry the mechanism; a table cell does not.+function paragraphs(markdown, limit = 4) {+ const blocks = markdown+ .replace(/```[\s\S]*?```/g, '')+ .split(/\n{2,}/)+ .map((block) => block.trim())+ .filter((block) => block && !block.startsWith('#') && !block.startsWith('|') && !block.startsWith('<') && !/^[-*]\s/.test(block))+ .map((block) => block.replace(/\s+/g, ' '));+ return blocks.slice(0, limit);+}++function headings(markdown, limit = 12) {+ return [...markdown.matchAll(/^#{2,3}\s+(.+)$/gm)].map((match) => match[1].trim()).slice(0, limit);+}++function endpointsIn(text) {+ return [...new Set([...text.matchAll(ENDPOINT_RE)].map((match) => `${match[1]} ${match[2]}`))].slice(0, 8);+}++// Docs that describe this surface: the file named after it, and any doc that+// names the route in its body.+function docsFor(root, slug, url) {+ const dir = join(root, 'docs');+ const found = [];+ const direct = join(dir, `${slug}.md`);+ if (existsSync(direct)) found.push({ path: `docs/${slug}.md`, body: read(direct) });+ const folder = join(dir, slug);+ if (existsSync(folder) && statSync(folder).isDirectory()) {+ for (const name of readdirSync(folder).filter((file) => file.endsWith('.md')).slice(0, 3)) {+ found.push({ path: `docs/${slug}/${name}`, body: read(join(folder, name)) });+ }+ }+ if (!found.length && url) {+ const needle = `](${url})`;+ for (const name of readdirSync(dir).filter((file) => file.endsWith('.md'))) {+ const body = read(join(dir, name));+ if (body.includes(needle)) {+ found.push({ path: `docs/${name}`, body });+ if (found.length >= 2) break;+ }+ }+ }+ return found.map((entry) => ({+ path: entry.path,+ headings: headings(entry.body),+ paragraphs: paragraphs(entry.body),+ endpoints: endpointsIn(entry.body),+ quotable: quotableLines(entry.body),+ }));+}++// Lines a `file` evidence check can quote. The verifier matches the raw bytes+// of the file, so a paragraph that was joined across newlines would never be+// found: only whole lines, exactly as they sit on disk, can be cited.+export function quotableLines(body, limit = 8) {+ const skip = /^(?:#|\||`{3}|<|!\[|\[!)/;+ const out = [];+ for (const raw of String(body || '').split('\n')) {+ // Blockquote and list markers are stripped, never the text after them:+ // what is left is still a contiguous substring of the file, which is+ // what the `file` evidence check matches against.+ const line = raw.trim().replace(/^(?:>\s?|[-*+]\s|\d+\.\s)+/, '').trim();+ if (!line || skip.test(line)) continue;+ for (const sentence of line.split(/(?<=[.!?])\s+/).map((part) => part.trim())) {+ if (sentence.length < 60 || sentence.length > 200) continue;+ if (!/[.!?]$/.test(sentence) || DASHED.test(sentence)) continue;+ // A line that wraps mid-sentence leaves a tail that reads as a+ // fragment. Evidence is quoted in the pack a human approves from, so+ // only a sentence that starts like one is worth offering.+ if (!/^[A-Z0-9`[$]/.test(sentence)) continue;+ if (/^https?:/.test(sentence)) continue;+ if (!out.includes(sentence)) out.push(sentence);+ if (out.length >= limit) return out;+ }+ }+ return out;+}++// Changelog entries about this surface: linked to it, or naming its title.+export function changelogFor(root, { url, title }) {+ const path = join(root, 'data/changelog.json');+ if (!existsSync(path)) return [];+ const { entries = [] } = JSON.parse(readFileSync(path, 'utf8'));+ const name = String(title || '').toLowerCase();+ return entries+ .filter((entry) => (url && entry.link === url) || (name.length > 5 && `${entry.title} ${entry.summary}`.toLowerCase().includes(name)))+ .sort((left, right) => right.date.localeCompare(left.date))+ .slice(0, 6)+ .map((entry) => ({ date: entry.date, title: entry.title, summary: entry.summary, tags: entry.tags }));+}++// Lines of the rendered page that could carry a claim: long enough to say+// something, short enough to quote, and not navigation furniture.+export function harvestFacts(pageText, limit = 24) {+ const junk = /^(?:home|docs|sign in|sign up|menu|skip to|cookie|©|all rights)/i;+ const lines = String(pageText || '')+ .split('\n')+ .map((line) => line.replace(/\s+/g, ' ').trim())+ .filter((line) => line.length >= 30 && line.length <= 220)+ .filter((line) => !junk.test(line))+ .filter((line) => /[a-z]/.test(line))+ .filter((line) => !DASHED.test(line))+ // A whole sentence, not a card label or a truncated gallery caption. The+ // verifier matches the string against the live page, so a fragment that+ // the page clips with an ellipsis would fail the check it was picked for.+ .filter((line) => /^[A-Z0-9$]/.test(line) && /[.!?]$/.test(line));+ const seen = new Set();+ const unique = lines.filter((line) => !seen.has(line.toLowerCase()) && seen.add(line.toLowerCase()));+ // A line with a number or a mechanism verb beats a line of marketing.+ const weight = (line) => (/\d/.test(line) ? 2 : 0) + (/\b(?:runs?|returns?|signs?|uploads?|renders?|retargets?|settles?|pays?|streams?|verif|generat|captur)/i.test(line) ? 1 : 0);+ return unique.sort((left, right) => weight(right) - weight(left)).slice(0, limit);+}++export function closestPriorPosts(root, text, limit = 3) {+ return loadHistory(root)+ .map((prior) => ({ text: prior.replace(/\s+/g, ' ').trim(), similarity: copySimilarity(text, prior) }))+ .sort((left, right) => right.similarity - left.similarity)+ .slice(0, limit);+}++export async function buildBrief(slot, { root, ledgerEntry = {}, pages = null, site = SITE }) {+ const url = slot.url ? `${site}${slot.url}` : null;+ const docs = docsFor(root, slot.id, slot.url);+ const dir = ledgerEntry.dir ? join(root, ledgerEntry.dir) : null;+ const readme = dir && existsSync(join(dir, 'README.md')) ? read(join(dir, 'README.md')) : '';++ let liveFacts = [];+ let liveStatus = null;+ if (url && pages) {+ const { status, text, raw } = await pages.text(url);+ liveStatus = status;+ liveFacts = harvestFacts(raw || text);+ }++ const readmePath = ledgerEntry.dir ? `${ledgerEntry.dir}/README.md` : null;+ const fileFacts = [+ ...docs.map((doc) => ({ path: doc.path, lines: doc.quotable })),+ ...(readme && readmePath ? [{ path: readmePath, lines: quotableLines(readme) }] : []),+ ].filter((row) => row.lines.length);++ const evidence = [+ ...liveFacts.slice(0, 12).map((fact) => ({ type: 'page', url, contains: fact })),+ ...fileFacts.flatMap((row) => row.lines.map((line) => ({ type: 'file', path: row.path, contains: line }))),+ ].filter((row) => row.contains && !DASHED.test(row.contains));++ return {+ id: slot.id,+ key: slot.key,+ url,+ route: slot.url,+ lane: slot.lane,+ pattern: slot.pattern,+ notBefore: slot.notBefore,+ surface: {+ kind: slot.kind,+ section: slot.section,+ title: ledgerEntry.title || slot.id,+ description: ledgerEntry.description || '',+ shipped: ledgerEntry.added || null,+ score: slot.score,+ signals: ledgerEntry.signals || {},+ },+ partner: slot.partner ? { handle: slot.partner, why: null } : null,+ docs,+ readme: readme ? { path: readmePath, paragraphs: paragraphs(readme), endpoints: endpointsIn(readme) } : null,+ changelog: changelogFor(root, { url: slot.url, title: ledgerEntry.title }),+ endpoints: [...new Set([...docs.flatMap((doc) => doc.endpoints), ...(readme ? endpointsIn(readme) : [])])].slice(0, 8),+ live: { status: liveStatus, facts: liveFacts },+ fileFacts,+ evidenceCandidates: evidence,+ avoid: closestPriorPosts(root, `${ledgerEntry.title || ''} ${ledgerEntry.description || ''}`),+ media: {+ shot: slot.shot,+ route: slot.url,+ motion: slot.motion,+ gate: slot.mediaGate,+ },+ };+}++export function briefPath(id) {+ return `data/announce-plan/briefs/${id}.json`;+}++export function loadBrief(root, id) {+ const path = resolve(root, briefPath(id));+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null;+}diff --git a/api/_lib/announce/card.js b/api/_lib/announce/card.jsnew file mode 100644index 000000000..c1d0a964f--- /dev/null+++ b/api/_lib/announce/card.js@@ -0,0 +1,157 @@+// Frames for the surfaces that have no route.+//+// A page can be photographed: `npm run announce:media` drives it in a real+// browser and the frame is the product. A package, a worker, or a service has+// no page, and 115 of the 316 planned announcements are one of those. The+// engagement archive is blunt about the alternative: a post with no media+// measured 0.875x against the account median, so "this one ships without an+// image" is not an option that leaves the post worth making.+//+// So the frame is built from what the thing actually is: its real name, its+// real one-line description, the command a developer really runs, and the tools+// or exports it really provides, all read out of its README and package.json.+// Nothing is invented, and nothing is styled to look like a screenshot of+// something that does not exist. It is a title card, and it says so by being+// obviously typeset rather than obviously photographed.+//+// The card is typeset in the product's own three fonts, fetched from the live+// origin and inlined: a page rendered from a string has no origin, so a linked+// stylesheet whose @font-face rules use root-relative URLs resolves to nothing+// and the card silently falls back to Helvetica.++import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';++// The house style bans both dash glyphs in every surface we author, and a card+// is authored copy that happens to be rendered as pixels.+const DASHES = new RegExp('\\s*[\\u2014\\u2013]\\s*', 'g');+const clean = (text) => String(text || '').replace(/\s+/g, ' ').replace(/<[^>]+>/g, '').replace(DASHES, ', ').trim();+const escape = (text) =>+ String(text || '').replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);++// The command a reader would actually run, preferred in the order a reader+// would meet it: the one-line agent install, then npx, then npm install.+export function commandFrom(readme) {+ const blocks = [...String(readme).matchAll(/```(?:bash|sh|shell)\n([\s\S]*?)```/g)].map((match) => match[1]);+ const lines = blocks.flatMap((block) => block.split('\n').map((line) => line.trim())).filter(Boolean);+ return (+ lines.find((line) => line.startsWith('claude mcp add')) ||+ lines.find((line) => line.startsWith('npx ')) ||+ lines.find((line) => line.startsWith('npm install')) ||+ lines.find((line) => line.startsWith('npm ')) ||+ null+ );+}++// Tool or export names, from the shapes a README in this repo actually uses: a+// tools table, backticked headings, or a bullet list of backticked names.+export function namesFrom(readme, limit = 8) {+ const body = String(readme);+ const names = [];+ const section = body.slice(Math.max(0, body.search(/^#{2,3}\s+(?:tools|api|exports|commands)\b/im)));+ // Only the first table of that section: the ones after it list parameters+ // and enum values, which are not the names a reader is being shown.+ const firstTable = section.match(/(?:^\|.*\n)+/m)?.[0] || '';+ for (const match of firstTable.matchAll(/^\|\s*`([a-z0-9_.:-]{3,40})`/gim)) names.push(match[1]);+ if (names.length < 3) for (const match of section.matchAll(/^#{3,4}\s+`([a-z0-9_.:-]{3,40})`/gim)) names.push(match[1]);+ if (names.length < 3) for (const match of section.matchAll(/^[-*]\s+`([a-z0-9_.:-]{3,40})`/gim)) names.push(match[1]);+ return [...new Set(names)].slice(0, limit);+}++// The site's own @font-face rules, with their root-relative sources rewritten+// to absolute ones so they load inside a document that has no base URL.+let fontCssPromise = null;+export function fetchFontCss(origin = 'https://three.ws') {+ if (!fontCssPromise) {+ fontCssPromise = fetch(`${origin}/fonts/fonts.css`, { signal: AbortSignal.timeout(20_000) })+ .then((response) => (response.ok ? response.text() : ''))+ .then((css) => css.replace(/url\(['"]?\/fonts\//g, `url('${origin}/fonts/`))+ .catch(() => '');+ }+ return fontCssPromise;+}++export function cardFacts(root, { dir, title, description }) {+ const readme = dir && existsSync(join(root, dir, 'README.md')) ? readFileSync(join(root, dir, 'README.md'), 'utf8') : '';+ const pkgPath = dir ? join(root, dir, 'package.json') : null;+ const pkg = pkgPath && existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')) : {};+ const subtitle =+ clean(pkg.description) ||+ clean(readme.match(/<p align="center"><strong>([\s\S]*?)<\/strong><\/p>/)?.[1]) ||+ clean(description);+ return {+ title: pkg.name || title,+ subtitle,+ command: commandFrom(readme),+ names: namesFrom(readme),+ footer: pkg.name?.startsWith('@') ? `npmjs.com/package/${pkg.name}` : dir,+ };+}++// 1600x900: the frame X renders uncropped for a single image, and the viewport+// the capture script calls `wide`.+export function cardHtml(facts, { origin = 'https://three.ws', fontCss = '' } = {}) {+ const chips = (facts.names || []).map((name) => `<span class="chip">${escape(name)}</span>`).join('');+ return `<!doctype html>+<html lang="en" data-theme="dark">+<head>+<meta charset="utf-8">+<style>+${fontCss}</style>+<style>+ html, body { margin: 0; height: 900px; width: 1600px; }+ body {+ background: radial-gradient(120% 90% at 78% 8%, rgba(255, 215, 0, 0.10), transparent 58%), #08080b;+ color: #f7f7f8;+ font-family: 'Inter', system-ui, sans-serif;+ display: flex;+ flex-direction: column;+ justify-content: center;+ padding: 96px 104px;+ box-sizing: border-box;+ }+ .eyebrow { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 22px; letter-spacing: 0.18em; text-transform: uppercase; color: rgba(255, 255, 255, 0.45); }+ h1 { font-family: 'Space Grotesk', 'Inter', system-ui, sans-serif; font-size: 74px; line-height: 1.04; margin: 26px 0 0; letter-spacing: -0.02em; }+ p.sub { font-size: 30px; line-height: 1.38; margin: 26px 0 0; color: rgba(255, 255, 255, 0.72); max-width: 1180px; }+ .cmd {+ margin-top: 44px;+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 27px;+ color: #f7f7f8;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 14px;+ padding: 24px 30px;+ display: flex;+ gap: 16px;+ align-items: baseline;+ max-width: 1290px;+ line-height: 1.35;+ overflow-wrap: anywhere;+ }+ .cmd.long { font-size: 23px; }+ .cmd b { color: rgba(255, 215, 0, 0.85); font-weight: 600; }+ .chips { margin-top: 40px; display: flex; flex-wrap: wrap; gap: 12px; max-width: 1300px; }+ .chip {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 21px;+ color: rgba(255, 255, 255, 0.78);+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.10);+ border-radius: 999px;+ padding: 10px 20px;+ }+ footer { position: absolute; left: 104px; bottom: 74px; display: flex; gap: 22px; align-items: center; font-size: 24px; color: rgba(255, 255, 255, 0.5); }+ footer .dot { width: 8px; height: 8px; border-radius: 50%; background: rgba(255, 215, 0, 0.8); }+</style>+</head>+<body>+ <div class="eyebrow">three.ws</div>+ <h1>${escape(facts.title)}</h1>+ ${facts.subtitle ? `<p class="sub">${escape(facts.subtitle)}</p>` : ''}+ ${facts.command ? `<div class="cmd${facts.command.length > 70 ? ' long' : ''}"><b>$</b><span>${escape(facts.command)}</span></div>` : ''}+ ${chips ? `<div class="chips">${chips}</div>` : ''}+ <footer><span class="dot"></span>${escape(facts.footer || 'three.ws')}</footer>+</body>+</html>`;+}diff --git a/api/_lib/announce/draft.js b/api/_lib/announce/draft.jsnew file mode 100644index 000000000..56099ad32--- /dev/null+++ b/api/_lib/announce/draft.js@@ -0,0 +1,205 @@+// The drafter: evidence brief in, one publishable post out.+//+// This is the step that used to be a person. It is not a template, and the+// difference matters: 300 posts from one template converge on one shape, an+// audience learns the shape, and the announcements that matter get skipped with+// the rest (docs/announce-voice.md measures why). So the model writes each post+// from that surface's own facts, and everything a template would have+// guaranteed is enforced afterwards instead, by the same checks that gate the+// queue:+//+// voice api/_lib/x-content/quality.js openers, hype, hashtags, length+// editorial api/_lib/x-content/editorial.js brand, compliance, claims, tags+// evidence the claims may only cite this brief's candidates, each of+// which was harvested from the live page or a repo file, so+// verification passes by construction rather than by luck+// repetition the account's own archive and the rest of the queue+//+// Failures are fed back to the model verbatim and it writes again, up to+// `attempts`. A draft that still fails is returned with its findings rather+// than written into the queue: this module never decides that something is good+// enough.++import { callModelChain } from '../x-content/llm.js';+import { copyProblems, copySimilarity, weightedLength } from '../x-content/quality.js';+import { claimProblems, languageProblems } from '../x-content/editorial.js';+import { loadHistory } from '../x-content/queue.js';++export const TARGET_BAND = [100, 179];++const PATTERN_GUIDE = {+ mechanism: 'Lead with how the thing actually works. The reader should finish the first sentence knowing what happens when they use it.',+ clip: 'The media is a motion loop of the product running. Write the sentence the loop cannot say: what is happening, and why it is hard.',+ number: 'Lead with the measured number and what it is a number of. The number must come from a claim with evidence.',+ correction: 'Lead with the assumption a reader would reasonably hold, then the fact that replaces it. Never invent the assumption: it has to be the obvious one.',+ walkthrough: 'Lead with the first move a user makes and what they get back. One concrete path, not a feature list.',+};++const LANE_GUIDE = {+ community: 'Written for people who use three.ws and hold $THREE. Plain language, no API names unless they are the point.',+ developer: 'Written for engineers who will read the code. Name the real endpoint, format, or package.',+ token: 'Written for people who follow the agent economy and $THREE. Say what the mechanism does with money. Never say what anything will be worth.',+ labs: 'Written for people who like seeing something unfinished done well. Be specific about what is experimental.',+};++export const SYSTEM = `You write posts for @trythreews, the X account of three.ws, a platform for 3D AI agents: avatars, a web component, agent wallets on Solana, and the $THREE token. You are given an evidence brief for one product surface that has shipped and has never been posted about. Write the post that announces it.++The brief is the only source of facts you have. Do not add anything that is not in it, do not guess at numbers, and do not describe behaviour it does not record.++Hard rules, each enforced by a machine after you answer:+- 100 to 179 weighted characters is the target band, 280 is the hard wall. A URL always counts as 23 characters however long it is.+- Exactly one link, to the surface itself, and it must appear in the head post.+- No hashtags, no emoji, no em-dashes or en-dashes, no stacked exclamation marks, no more than one all-caps word.+- No launch-deck openers (Introducing, We are excited, Say hello to, Meet the new, Big news, Today we are launching), no rhetorical question as the first sentence, no one-word-sentence drumbeat, no teaser that withholds the point, no thread counter.+- No hype or filler vocabulary: game-changer, revolutionary, seamless, powerful, robust, innovative, cutting-edge, world-class, leverage, empower, unleash, elevate, harness, journey, supercharge, delve, very, really, simply, literally, actually, basically, truly, incredibly, amazing, awesome, groundbreaking.+- No crypto slang (gm, wagmi, lfg, ser, frens, degens, based, cooking, ngl, tbh) and no engagement asks (check this out, follow us, link in bio, tag a friend, drop a).+- Nothing that reads as investment advice or a price promise. Say what the product does, never what a token will be worth.+- Names are written exactly: three.ws, $THREE, X (never Twitter), GitHub, JavaScript, TypeScript, OpenAI, NVIDIA, Solana, glTF, GLB, API, MCP, AI.+- Every number, ordinal, and absolute word (first, only, every, never, fastest, instant, unlimited, zero) in your copy must sit inside a claim you declare, and every claim must quote your own copy word for word and cite evidence from the brief's evidenceCandidates list, unchanged. Copy the candidate's fields exactly; do not invent a new one, do not edit its text. If you cannot support a number, write the post without it.+- @mentions only for an account the surface genuinely runs on, at most two, each with the reason recorded. The brief's partner field is a suggestion, not a licence: drop it if the brief does not show the surface really runs on them.+- Alt text describes what is in the image for someone who cannot see it, at least 60 characters, and does not repeat the post or open with "image of".++The same announcement also goes to the community Telegram channel, which has no character limit and a slightly longer register. Write that version too: two to four sentences, the same facts, no hashtags, no emoji, no dashes, and the same link.++Respond with a single JSON object and nothing else:+{"post":"...","thread":["optional reply","optional reply"],"telegram":"...","alt":"...","claims":[{"says":"exact words from your post","evidence":[{...one of the brief's evidenceCandidates, copied exactly...}]}],"mentions":{"@handle":"why the tag is true"},"why":"two sentences for the approver: what the post leads on and why that is the strongest true thing about this surface","headline":"a five to nine word title for the announcement pack"}`;++export function buildDraftRequest(brief, { voice = null, findings = [], previous = null } = {}) {+ const guidance = [+ `Pattern for this post: ${brief.pattern}. ${PATTERN_GUIDE[brief.pattern] || PATTERN_GUIDE.mechanism}`,+ `Lane: ${brief.lane}. ${LANE_GUIDE[brief.lane] || LANE_GUIDE.community}`,+ brief.media?.motion ? 'The attached media is an animated loop captured from the live route.' : 'The attached media is a still frame captured from the live route.',+ ].join('\n');++ const retry = previous+ ? [+ '## Your previous draft, and why it was rejected',+ JSON.stringify(previous, null, 2),+ findings.map((finding) => `- ${finding}`).join('\n'),+ 'Write it again. Fix every point. Keep what was already true.',+ ].join('\n\n')+ : null;++ const text = [+ `## Evidence brief\n${JSON.stringify(brief, null, 2)}`,+ `## How this one should read\n${guidance}`,+ voice ? `## House voice contract\n${voice}` : null,+ retry,+ 'Write the post now. Respond with the JSON object only.',+ ]+ .filter(Boolean)+ .join('\n\n');+ return { system: SYSTEM, parts: [{ type: 'text', text }] };+}++export function parseDraft(raw) {+ const text = String(raw || '');+ const start = text.indexOf('{');+ const end = text.lastIndexOf('}');+ if (start < 0 || end <= start) throw new Error('drafter returned no JSON object');+ const draft = JSON.parse(text.slice(start, end + 1));+ if (!String(draft.post || '').trim()) throw new Error('drafter returned an empty post');+ if (!String(draft.alt || '').trim()) throw new Error('drafter returned no alt text');+ draft.thread = Array.isArray(draft.thread) ? draft.thread.filter((row) => String(row || '').trim()) : [];+ draft.telegram = String(draft.telegram || '').trim();+ draft.claims = Array.isArray(draft.claims) ? draft.claims : [];+ draft.mentions = draft.mentions && typeof draft.mentions === 'object' ? draft.mentions : {};+ return draft;+}++// The queue item a draft becomes. Written here so the checks below judge exactly+// what would be published, not an approximation of it.+export function itemFor(brief, draft, { mediaPath, probe = null, status = 'draft' }) {+ const media = [{ path: mediaPath, alt: String(draft.alt || '').trim(), ...(probe ? { probe } : {}) }];+ return {+ id: brief.id,+ status,+ kind: 'post',+ lane: brief.lane,+ pattern: brief.pattern,+ notBefore: brief.notBefore,+ source: { path: `docs/announcements/${brief.id}.md`, url: brief.url || undefined },+ posts: [+ { text: String(draft.post || '').trim(), textFrom: `docs/announcements/${brief.id}.post.txt`, media },+ ...draft.thread.map((text) => ({ text: String(text).trim() })),+ ],+ claims: draft.claims,+ mentions: draft.mentions,+ };+}++const candidateKey = (evidence) => JSON.stringify([evidence.type, evidence.url || evidence.path || '', evidence.contains || evidence.matches || '']);++// Everything wrong with a draft, in the words the model will be shown. Offline:+// no network, so a retry costs one model call and nothing else.+export function draftFindings(brief, draft, { root = null, otherHeads = [] } = {}) {+ const findings = [];+ const head = String(draft.post || '').trim();+ const weight = weightedLength(head);++ for (const problem of copyProblems(head, { minimum: TARGET_BAND[0] })) findings.push(`head: ${problem}`);+ if (weight > TARGET_BAND[1] && weight <= 280) findings.push(`head is ${weight} weighted characters; the measured band is ${TARGET_BAND[0]} to ${TARGET_BAND[1]}, so tighten it unless the mechanism needs the room`);+ for (const reply of draft.thread) for (const problem of copyProblems(reply, { minimum: 40, requireUrl: false })) findings.push(`reply: ${problem}`);++ const texts = [head, ...draft.thread];+ for (const text of texts) {+ for (const finding of languageProblems(text)) if (finding.severity !== 'minor') findings.push(`${finding.rule}: ${finding.message}`);+ }+ for (const finding of claimProblems({ posts: texts.map((text) => ({ text })), claims: draft.claims, mentions: draft.mentions })) {+ if (finding.severity === 'blocking') findings.push(`${finding.rule}: ${finding.message}`);+ }++ // Evidence has to come from the brief, unedited. A model that paraphrases a+ // candidate produces a claim the verifier will fail on the live page.+ const allowed = new Set((brief.evidenceCandidates || []).map(candidateKey));+ for (const claim of draft.claims) {+ for (const evidence of claim.evidence || []) {+ if (!allowed.has(candidateKey(evidence))) {+ findings.push(`claims: evidence ${JSON.stringify(evidence).slice(0, 120)} is not one of the brief's evidenceCandidates; copy a candidate exactly or drop the claim`);+ }+ }+ }++ // Telegram carries the same facts in a longer register. It is not posted by+ // this pipeline, so only the rules that are about truth and house style apply.+ if (draft.telegram) {+ for (const finding of languageProblems(draft.telegram)) {+ if (finding.severity === 'blocking' && finding.rule !== 'links') findings.push(`telegram: ${finding.message}`);+ }+ if (!/three\.ws/.test(draft.telegram)) findings.push('telegram: the longer version must link the surface too');+ }++ const alt = String(draft.alt || '').trim();+ if (alt.length < 60) findings.push(`alt text is ${alt.length} characters; describe what the frame shows`);+ if (/^(?:an? )?(?:image|picture|photo|screenshot) of\b/i.test(alt)) findings.push('alt text opens with "image of"; screen readers already say it is an image');+ if (alt.toLowerCase() === head.toLowerCase()) findings.push('alt text repeats the post');++ if (brief.url && !head.includes(brief.url.replace(/^https?:\/\//, '')) && !head.includes(brief.url)) {+ findings.push(`head must link ${brief.url}, the surface this post is about`);+ }++ const rivals = [...otherHeads, ...(root ? loadHistory(root) : [])];+ for (const rival of rivals) {+ const score = copySimilarity(head, rival);+ if (score >= 0.34) {+ findings.push(`head reads like an existing post (similarity ${score.toFixed(2)}): "${rival.slice(0, 110)}". Lead on a different fact from the brief.`);+ break;+ }+ }+ return findings;+}++export async function draftPost(brief, { root, env = process.env, voice = null, attempts = 3, otherHeads = [] } = {}) {+ const tries = [];+ let previous = null;+ let findings = [];+ for (let attempt = 1; attempt <= attempts; attempt++) {+ const request = buildDraftRequest(brief, { voice, findings, previous });+ const { value, model, fallbacks } = await callModelChain(request, { env, parse: parseDraft });+ findings = draftFindings(brief, value, { root, otherHeads });+ tries.push({ attempt, model, fallbacks, findings, draft: value });+ if (!findings.length) return { draft: value, model, attempts: tries, ok: true };+ previous = value;+ }+ return { draft: tries[tries.length - 1].draft, model: tries[tries.length - 1].model, attempts: tries, ok: false, findings };+}diff --git a/api/_lib/announce/kit.js b/api/_lib/announce/kit.jsnew file mode 100644index 000000000..b5f768f58--- /dev/null+++ b/api/_lib/announce/kit.js@@ -0,0 +1,192 @@+// The pack renderer: one Markdown file per announcement, holding everything a+// person needs to approve it and everything a machine needs to publish it.+//+// The format follows the packs written by hand in docs/announcements/ and the+// campaign kits in marketing/growth/kits/, because those are what the gate+// (scripts/check-announce.mjs) and the reviewers already read: the media table+// is parsed for shot ids, the alt text has to be stated, and the post itself+// lives in a sibling .post.txt so the bytes that are checked are the bytes that+// ship.+//+// Everything in a rendered pack is either a fact from the brief, a decision+// from the plan, or the drafter's own reasoning. Nothing is invented here.++import { weightedLength } from '../x-content/quality.js';++const SITE = 'https://three.ws';++const SIGNALS = {+ reach: (value) => `sitemap priority ${(value / 20).toFixed(2)}, which is what we already decided this surface is worth`,+ visual: (value) => (value >= 25 ? 'a showcase surface, so its frame can be a motion loop' : 'renders something worth a frame'),+ token: () => 'touches $THREE or the agent economy, the topic band that measured highest in our own archive',+ partner: () => 'names a partner the surface genuinely runs on, so a tag is defensible',+ novelty: () => "on the coverage audit's hand-picked shortlist of strongest candidates",+ depth: () => 'documented in the tree, so there is enough to write a mechanism about and link proof for',+};++const LANE_AUDIENCE = {+ community: 'People who use three.ws and hold $THREE',+ developer: 'Engineers who will read the code',+ token: 'People who follow the agent economy and $THREE',+ labs: 'People who follow the experimental surfaces',+};++const KPI = {+ clip: 'loop completions and profile visits, then route sessions on the day',+ mechanism: 'route sessions and docs reads on the day of the post',+ number: 'replies that quote the number, and route sessions',+ correction: 'replies and quote posts, which is where a correction earns its reach',+ walkthrough: 'route sessions that reach the second step of the flow',+};++const utm = (url, source, medium, campaign, content) =>+ `${url}?utm_source=${source}&utm_medium=${medium}&utm_campaign=${campaign}&utm_content=${content}`;++function evidenceLabel(evidence) {+ if (evidence.type === 'page') return `live page shows "${evidence.contains}"`;+ if (evidence.type === 'file') return `\`${evidence.path}\` contains "${String(evidence.contains).slice(0, 90)}"`;+ if (evidence.type === 'module') return `\`${evidence.path}\` exports ${evidence.export}`;+ return JSON.stringify(evidence);+}++export function renderPostFile(draft) {+ return `${String(draft.post || '').trim()}\n`;+}++export function renderPack({ brief, draft, slot, ledgerEntry = {}, rank = null, total = null, model = null, verification = null }) {+ const id = brief.id;+ const url = brief.url || SITE;+ const campaign = `announce-${id}`;+ const weight = weightedLength(draft.post || '');+ const signals = Object.entries(ledgerEntry.signals || {}).filter(([, value]) => value > 0);+ const shotFile = `/announce/img/${slot.shot}.webp`;++ const lines = [];+ const push = (...rows) => lines.push(...rows);++ push(+ `# Announcement pack: ${draft.headline || ledgerEntry.title || id}`,+ '',+ `**Surface:** [\`${brief.key}\`](${url}) · **Stage:** drafted · **Slot:** ${slot.notBefore.slice(0, 16).replace('T', ' ')} UTC · **Announced externally:** never`,+ '',+ `${rank && total ? `Ranked ${rank} of ${total} never-announced surfaces by \`npm run announce:rank\`` : 'From the announcement backlog'}${ledgerEntry.score ? ` (score ${ledgerEntry.score})` : ''}. ${model && !/^hand/i.test(model) ? `Drafted on ${model} and packed by \`npm run announce:kit\`` : 'Drafted by hand and packed by `npm run announce:kit`'}, from the evidence brief in [\`data/announce-plan/briefs/${id}.json\`](../../data/announce-plan/briefs/${id}.json), against [the announcement voice](../announce-voice.md). Every fact below comes from that brief; nothing in this pack was written from memory.`,+ '',+ '---',+ '',+ '## At a glance',+ '',+ '| Field | Value |',+ '|---|---|',+ `| Pack id | \`${id}\` |`,+ `| Publish slot | ${slot.notBefore.slice(0, 16).replace('T', ' ')} UTC, jittered inside ${slot.windowMinutes} minutes by the scheduler |`,+ `| Lane and pattern | ${brief.lane} / ${brief.pattern} |`,+ `| Audience | ${LANE_AUDIENCE[brief.lane] || LANE_AUDIENCE.community} |`,+ '| Primary channel | X, @trythreews, through the reviewed content queue |',+ '| Secondary channels | Telegram (@three_ws), the surface\'s own docs page |',+ `| Proof | ${url} |`,+ `| Tracked links | Telegram \`${utm(url, 'telegram', 'community', campaign, 'announcement')}\`. The X post links the bare URL on purpose: X wraps every link in t.co and the queue's own ledger records the send, so a tagged link buys nothing and reads like marketing. |`,+ `| The single CTA | Open ${brief.route || url} and use it |`,+ `| Media | \`${slot.shot}\`, ${slot.motion ? 'motion loop' : 'still frame'}${slot.mediaGate ? `, ${slot.mediaGate} required before committing the frame` : ''} |`,+ `| KPI | ${KPI[brief.pattern] || KPI.mechanism} |`,+ '',+ '## Why this one, and why now',+ '',+ );++ if (signals.length) {+ push(+ 'The ranker scored it on signals measured against our own archive, not on taste:',+ '',+ ...signals.map(([name, value]) => `- **${name} (${value})**: ${(SIGNALS[name] || (() => 'a scored signal'))(value)}`),+ '',+ );+ }+ if (ledgerEntry.curatedWhy) push(`The coverage audit's note on it: ${ledgerEntry.curatedWhy}`, '');+ if (brief.surface.shipped) push(`It shipped on ${brief.surface.shipped} and has never been posted about.`, '');+ if (brief.changelog?.length) {+ push(+ `The changelog has ${brief.changelog.length} entr${brief.changelog.length === 1 ? 'y' : 'ies'} about it, the most recent from ${brief.changelog[0].date}: "${brief.changelog[0].title}".`,+ '',+ );+ }++ push('## The claim, and where it is checked', '', '> ' + String(draft.post || '').trim().replace(/\n/g, '\n> '), '');+ if (draft.claims?.length) {+ push('Every checkable part of that is declared as a claim in the queue item, and the verifier re-checks each one against the live surface before the post can be approved:', '', '| Claim | Checked against |', '|---|---|');+ for (const claim of draft.claims) {+ push(`| ${claim.says} | ${(claim.evidence || []).map(evidenceLabel).join('; ')} |`);+ }+ push('');+ } else {+ push('The copy states no number and no absolute, so it declares no claims. The link check and the live page are what back it.', '');+ }+ if (verification) {+ const failed = verification.checks.filter((check) => !check.ok);+ push(+ failed.length+ ? `Last verification run: ${failed.length} of ${verification.checks.length} checks failed (${failed.slice(0, 3).map((check) => `${check.target}: ${check.detail}`).join('; ')}).`+ : `Last verification run: all ${verification.checks.length} checks passed.`,+ '',+ );+ }+ if (Object.keys(draft.mentions || {}).length) {+ push('**Tags, and why each one is true:**', '', ...Object.entries(draft.mentions).map(([handle, why]) => `- \`${handle}\`: ${why}`), '');+ }++ push(+ '## Media',+ '',+ 'Captured from the live route by `npm run announce:media`, which drives the real page in a real Chromium and writes provenance (route, commit, time, sha256) beside the pixels in [`public/announce/media-manifest.json`](../../public/announce/media-manifest.json).',+ '',+ '| Shot | File | Notes |',+ '|---|---|---|',+ `| \`${slot.shot}\` | \`${shotFile}\` | ${slot.motion ? 'Motion loop of the live route' : 'Still frame of the live route'}${slot.mediaGate ? '. This surface renders live third-party market data, so the frame is held out of the tree until the owner approves it (set `thirdPartyMarketDataApproved` on the shot).' : '.'} |`,+ '',+ '**Alt text, required on the post:**',+ '',+ `> ${String(draft.alt || '').trim()}`,+ '',+ '## The post',+ '',+ `Pattern: ${brief.pattern}. **${weight} weighted characters**${weight >= 100 && weight <= 179 ? ', inside the 100 to 179 band that measured a 3.0x lift' : weight <= 280 ? ', inside the hard limit of 280' : ''}. Postable file: [\`${id}.post.txt\`](./${id}.post.txt), which is the byte-for-byte source the queue item points at.`,+ '',+ '```text',+ String(draft.post || '').trim(),+ '```',+ '',+ );++ if (draft.why) push('### Why it is written that way', '', draft.why, '');+ if (draft.thread?.length) {+ push('### Thread', '');+ draft.thread.forEach((reply, index) => {+ push(`${index + 2}/ (${weightedLength(reply)})`, '', '```text', String(reply).trim(), '```', '');+ });+ }+ if (draft.telegram) {+ push(+ '## Telegram (@three_ws)',+ '',+ 'The same facts in the channel\'s longer register. The changelog cron posts release notes there automatically; this is the announcement register, sent by hand or queued alongside the post.',+ '',+ '```text',+ String(draft.telegram).trim(),+ '```',+ '',+ );+ }++ push(+ '## Ship it',+ '',+ '```bash',+ `npm run announce:media -- --only ${slot.shot} # capture the frame from the live route`,+ `npm run x:content -- review ${id} # lint, live fact checks, AI editor`,+ `npm run x:content -- run --dry-run --id ${id} # exactly what would be sent to X`,+ '```',+ '',+ `The queue item is \`${id}\` in [\`data/x-content/queue.json\`](../../data/x-content/queue.json), at status \`draft\`. It becomes eligible to publish when a passing review record exists and the owner sets its status to \`approved\`; the Cloud Scheduler tick then sends it at its slot. Nothing here posts on its own.`,+ '',+ );+ return `${lines.join('\n')}\n`;+}diff --git a/api/_lib/announce/ledger.js b/api/_lib/announce/ledger.jsnew file mode 100644index 000000000..884c37870--- /dev/null+++ b/api/_lib/announce/ledger.js@@ -0,0 +1,104 @@+// Where the announcement machinery reads its state from, in one place, so the+// planner, the kit factory, and anything added later agree on what the backlog+// is and which slot a surface holds.+//+// Nothing here is generated on the fly that could be stale: the ledger is+// rebuilt by `npm run announce:rank -- --write`, and the plan, once written, is+// reused rather than recomputed, because a calendar that moves every time it is+// read is not a calendar.++import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { buildPlan, slugFor } from './plan.js';++export const LEDGER_PATH = 'data/announcements.json';+export const PLAN_DIR = 'data/announce-plan';+export const PLAN_PATH = `${PLAN_DIR}/plan.json`;++export class MissingLedgerError extends Error {+ constructor() {+ super('data/announcements.json is missing. Build it first:\n\n npm run announce:rank -- --probe --write\n');+ this.name = 'MissingLedgerError';+ }+}++export function loadLedger(root) {+ const path = resolve(root, LEDGER_PATH);+ if (!existsSync(path)) throw new MissingLedgerError();+ return JSON.parse(readFileSync(path, 'utf8'));+}++export function loadQueueFile(root) {+ return JSON.parse(readFileSync(resolve(root, 'data/x-content/queue.json'), 'utf8'));+}++// Surfaces under the `crypto` section render live third-party market data, so a+// frame of one carries the operating rules' coin gate.+export function cryptoPaths(root) {+ const pages = JSON.parse(readFileSync(resolve(root, 'data/pages.json'), 'utf8'));+ return new Set(pages.sections.filter((section) => section.id === 'crypto').flatMap((section) => section.pages.map((page) => page.path)));+}++// Ids that are already spoken for: queued, or carrying a pack.+export function takenIds(root, queue) {+ const taken = new Set((queue.items || []).map((item) => item.id));+ const dir = resolve(root, 'docs/announcements');+ if (existsSync(dir)) {+ for (const file of readdirSync(dir)) {+ if (file.endsWith('.md') && file !== 'README.md') taken.add(file.replace(/\.md$/, ''));+ }+ }+ return taken;+}++// Surfaces the owner or an earlier capture took off the table, with the reason.+// Committed, unlike the ledger, because the reason is knowledge the regenerated+// ledger cannot re-derive: `/genome` and `/portfolio` were both deferred after+// their frames showed an empty market and an empty input.+export function deferrals(root) {+ const path = resolve(root, 'data/announce-deferred.json');+ if (!existsSync(path)) return new Map();+ const { deferred = {} } = JSON.parse(readFileSync(path, 'utf8'));+ return new Map(Object.entries(deferred));+}++export function backlogOf(root, { ledger = null, queue = null } = {}) {+ const source = ledger || loadLedger(root);+ const taken = takenIds(root, queue || loadQueueFile(root));+ const deferred = deferrals(root);+ return (source.entries || [])+ .filter((entry) => entry.coverage === 'no')+ .filter((entry) => !entry.live || entry.live.ok)+ .filter((entry) => !taken.has(slugFor(entry.key)))+ .filter((entry) => !deferred.has(entry.key));+}++export function planFor(root, { start, ledger = null } = {}) {+ const queue = loadQueueFile(root);+ const entries = backlogOf(root, { ledger, queue });+ const plan = buildPlan(entries, { cadence: queue.cadence, quality: queue.quality, start, cryptoPaths: cryptoPaths(root) });+ plan.deferred = [...deferrals(root)].map(([key, why]) => ({ key, why }));+ return plan;+}++export function writePlan(root, plan, calendar) {+ const dir = resolve(root, PLAN_DIR);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'plan.json'), `${JSON.stringify(plan, null, '\t')}\n`);+ if (calendar) writeFileSync(join(dir, 'CALENDAR.md'), calendar);+}++// The written plan, so a batch drafted last week keeps its dates. Rebuilt only+// when there is none, or when the caller asks for a fresh start date.+export function loadOrBuildPlan(root, { start = null, refresh = false } = {}) {+ const path = resolve(root, PLAN_PATH);+ if (!refresh && !start && existsSync(path)) return JSON.parse(readFileSync(path, 'utf8'));+ const plan = planFor(root, { start: start || new Date(Date.now() + 86_400_000).toISOString().slice(0, 10) });+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${JSON.stringify(plan, null, '\t')}\n`);+ return plan;+}++export function ledgerEntryFor(ledger, key) {+ return (ledger.entries || []).find((entry) => entry.key === key) || {};+}diff --git a/api/_lib/announce/plan.js b/api/_lib/announce/plan.jsnew file mode 100644index 000000000..7dface833--- /dev/null+++ b/api/_lib/announce/plan.js@@ -0,0 +1,216 @@+// The announcement calendar: which unannounced surface goes out, in what order,+// on which day, in which lane and shape.+//+// scripts/announce-rank.mjs answers "what is worth announcing" and writes the+// ledger. This module answers the next question, which nobody had automated:+// given 300-plus never-announced surfaces and an account that can carry three+// posts a day without reading as a bot, what is the actual schedule?+//+// Everything here is pure so the schedule is reproducible: the same ledger and+// the same start date always produce the same calendar, which is what makes a+// plan reviewable rather than a fresh guess on every run.+//+// Three constraints shape it, and all three come from files that already exist+// rather than from taste:+//+// cadence data/x-content/queue.json: daily cap, minimum gap, quiet hours.+// Slot times are derived from those, never hardcoded.+// rotation the same queue's quality block: no more than N of the same+// lane in a row, no more than M of the same pattern. The+// scheduler in api/_lib/x-content/schedule.js enforces this at+// publish time by *skipping* an item, so a calendar that ignores+// it would stall itself.+// the coin gate a frame captured from a surface under the `crypto` section of+// data/pages.json bakes live third-party tickers into a+// committed file, which the operating rules gate on owner+// approval. Those surfaces are planned like any other and carry+// `mediaGate`, so a batch can be run without them.++const MINUTE = 60_000;++// Audience lane. Rotation only cares that neighbours differ, but the lane also+// decides who the pack is written for, so it is derived from where the surface+// lives rather than assigned round-robin.+export const LANES = ['community', 'developer', 'token', 'labs'];++// Post shape. Each surface gets a ranked list; the sequencer takes the first+// one that does not repeat its neighbour, which is how a 300-item run avoids+// converging on a single format.+export const PATTERNS = ['mechanism', 'clip', 'number', 'correction', 'walkthrough'];++const DEVELOPER_SECTIONS = new Set(['build', 'agent-tools', 'machine', 'package', 'worker', 'service']);+const TOKEN_RE = /\$THREE|\btoken\b|\bcoin\b|\bx402\b|\bwallet\b|\bUSDC\b|on-chain|onchain|\bmint\b|\btrading\b|\bpump\.fun\b/i;++export function laneFor(entry) {+ if (entry.section === 'crypto') return 'token';+ if (entry.section === 'labs') return 'labs';+ if (DEVELOPER_SECTIONS.has(entry.section)) return 'developer';+ if (TOKEN_RE.test(`${entry.title} ${entry.description}`) && entry.signals?.token) return 'token';+ return 'community';+}++// A surface that renders motion can carry a loop; one with a measured number in+// its own description can lead on the number. Everything can lead on mechanism,+// so it is always last and always available.+export function patternsFor(entry) {+ const text = `${entry.title} ${entry.description}`;+ const ranked = [];+ // A loop has to be a loop of something running, so only a surface with a+ // route can carry one. A package's frame is a typeset card, which is a+ // still by construction.+ const filmable = Boolean(entry.url);+ if (filmable && (entry.signals?.visual ?? 0) >= 25) ranked.push('clip');+ if (/\b\d[\d,.]*\s*(?:%|x\b|ms\b|seconds?|minutes?|hours?|k\b|m\b)|\b\d{2,}\b/.test(text)) ranked.push('number');+ if (/instead of|without|no longer|used to|rather than|misconception|assume/i.test(text)) ranked.push('correction');+ if (/\bhow to\b|guide|tutorial|step|studio|builder|editor/i.test(text)) ranked.push('walkthrough');+ if (filmable && (entry.signals?.visual ?? 0) > 0 && !ranked.includes('clip')) ranked.push('clip');+ // Any surface a visitor can act on can be written as a walkthrough, which is+ // what keeps a long run of pages from being 40 mechanism posts in a row.+ if (filmable && !ranked.includes('walkthrough')) ranked.push('walkthrough');+ ranked.push('mechanism');+ return [...new Set(ranked)];+}++// `/labor-market` -> `labor-market`, `@three-ws/walk-sdk` -> `walk-sdk`,+// `workers/rigger` -> `worker-rigger`. Stable, because it becomes the queue id,+// the pack filename, and the media shot id.+export function slugFor(key) {+ const raw = String(key || '');+ if (raw.startsWith('@')) return raw.split('/').pop().replace(/[^a-z0-9-]+/gi, '-').toLowerCase();+ if (raw.includes('/') && !raw.startsWith('/')) {+ const [base, name] = raw.split('/');+ return `${base.replace(/s$/, '')}-${name}`.replace(/[^a-z0-9-]+/gi, '-').toLowerCase();+ }+ return raw.replace(/^\//, '').replace(/[^a-z0-9-]+/gi, '-').toLowerCase() || 'home';+}++function minutesOf(value) {+ const [hour, minute] = String(value).split(':').map(Number);+ return hour * 60 + (minute || 0);+}++const inQuiet = (minutes, quiet) => {+ if (!Array.isArray(quiet) || quiet.length !== 2) return false;+ const [start, end] = quiet.map(minutesOf);+ const at = ((minutes % 1440) + 1440) % 1440;+ return start <= end ? at >= start && at < end : at >= start || at < end;+};++// The posting times of a day, derived from the cadence rather than chosen. A+// slot whose jitter window could land inside quiet hours is dropped, so the+// calendar never promises a slot the scheduler would refuse.+export function slotTimes(cadence = {}) {+ const quiet = cadence.quietHoursUtc || null;+ const cap = Math.max(1, Number(cadence.dailyCap ?? 3));+ const gap = Math.max(60, Number(cadence.minimumMinutesApart ?? 240));+ const window = Math.max(0, Number(cadence.windowMinutes ?? 90));+ const first = quiet ? minutesOf(quiet[1]) + 60 : 13 * 60;+ const spacing = Math.max(gap, 300);+ const times = [];+ for (let index = 0; index < cap; index++) {+ const at = first + index * spacing;+ if (at >= 1440) break;+ if (inQuiet(at, quiet) || inQuiet(at + window, quiet)) continue;+ times.push(`${String(Math.floor(at / 60)).padStart(2, '0')}:${String(at % 60).padStart(2, '0')}`);+ }+ return times.length ? times : ['13:00'];+}++function runLength(list, field, value) {+ let run = 0;+ for (let index = list.length - 1; index >= 0; index--) {+ if (list[index][field] !== value) break;+ run++;+ }+ return run;+}++// Greedy sequencer. Highest score first, but a candidate that would repeat the+// previous lane or pattern too many times yields to the next one that fits,+// and a candidate whose preferred pattern is blocked falls through its own+// ranked list before it gives up its slot.+export function sequence(entries, { maximumSameLaneInARow = 2, maximumSamePatternInARow = 1 } = {}) {+ const pool = entries.map((entry) => ({+ entry,+ lane: laneFor(entry),+ patterns: patternsFor(entry),+ }));+ const placed = [];+ while (pool.length) {+ let chosen = -1;+ let pattern = null;+ for (let index = 0; index < pool.length; index++) {+ const candidate = pool[index];+ if (runLength(placed, 'lane', candidate.lane) >= maximumSameLaneInARow) continue;+ pattern = candidate.patterns.find((option) => runLength(placed, 'pattern', option) < maximumSamePatternInARow) || null;+ if (pattern) {+ chosen = index;+ break;+ }+ }+ // Every remaining candidate repeats the neighbour. That happens whenever+ // the inventory is lopsided (167 of the 316 unannounced surfaces are+ // developer-lane packages, so a long developer run is unavoidable), and+ // the scheduler's own starvation rule releases such an item a day past+ // its slot. Shape still matters more than lane here, so the fallback+ // takes the best candidate that can at least change the post's shape.+ if (chosen < 0) {+ const lastPattern = placed[placed.length - 1]?.pattern;+ chosen = pool.findIndex((candidate) => candidate.patterns.some((option) => option !== lastPattern));+ if (chosen < 0) chosen = 0;+ pattern = pool[chosen].patterns.find((option) => option !== lastPattern) || pool[chosen].patterns[0];+ }+ const [candidate] = pool.splice(chosen, 1);+ placed.push({ entry: candidate.entry, lane: candidate.lane, pattern });+ }+ return placed;+}++export function buildPlan(entries, { cadence = {}, quality = {}, start, cryptoPaths = new Set(), perDay = null } = {}) {+ const times = slotTimes(cadence).slice(0, perDay || Infinity);+ const day0 = Date.parse(`${start}T00:00:00Z`);+ if (!Number.isFinite(day0)) throw new Error(`start must be a YYYY-MM-DD date, got ${start}`);++ const ordered = sequence(entries, quality);+ const slots = ordered.map((row, index) => {+ const day = Math.floor(index / times.length);+ const time = times[index % times.length];+ const notBefore = new Date(day0 + day * 1440 * MINUTE + minutesOf(time) * MINUTE).toISOString().replace('.000Z', 'Z');+ const slug = slugFor(row.entry.key);+ const gated = Boolean(row.entry.url && cryptoPaths.has(row.entry.url));+ return {+ position: index + 1,+ id: slug,+ key: row.entry.key,+ kind: row.entry.kind,+ section: row.entry.section,+ url: row.entry.url || null,+ lane: row.lane,+ pattern: row.pattern,+ notBefore,+ windowMinutes: Number(cadence.windowMinutes ?? 90),+ batch: Math.floor(day / 7) + 1,+ score: row.entry.score,+ partner: row.entry.partner || null,+ shot: `${slug}-hero`,+ motion: row.pattern === 'clip',+ mediaGate: gated ? 'owner-approval' : null,+ pack: `docs/announcements/${slug}.md`,+ };+ });++ return {+ generatedAt: new Date().toISOString(),+ start,+ times,+ perDay: times.length,+ days: Math.ceil(slots.length / times.length),+ totals: {+ slots: slots.length,+ gated: slots.filter((slot) => slot.mediaGate).length,+ byLane: Object.fromEntries(LANES.map((lane) => [lane, slots.filter((slot) => slot.lane === lane).length])),+ byPattern: Object.fromEntries(PATTERNS.map((pattern) => [pattern, slots.filter((slot) => slot.pattern === pattern).length])),+ },+ slots,+ };+}diff --git a/api/_lib/x-content/editor.js b/api/_lib/x-content/editor.jsindex 23cefda49..dadd59134 100644--- a/api/_lib/x-content/editor.js+++ b/api/_lib/x-content/editor.js@@ -13,16 +13,15 @@// account's best-performing posts. It returns a verdict, scores, specific// issues with fixes, and a rewrite. It never edits the queue: a human decides.//-// Transport chain, strongest first: Claude on Vertex AI (GCP credits), Claude-// through OpenRouter, OpenAI, then Kimi K3 on NVIDIA NIM (free, multimodal, and-// slow: a full review takes minutes). Each rung is skipped when its credentials-// are absent and falls through on any provider error, including billing.+// The transport chain it runs on (Vertex, OpenRouter, OpenAI, NVIDIA NIM) is+// shared with the drafter and lives in llm.js.import { existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import { mediaType } from './media.js';+import { EDITOR_MODEL, callModelChain } from './llm.js';-export const EDITOR_MODEL = 'claude-opus-5';+export { EDITOR_MODEL };const MAX_SOURCE_CHARS = 24_000;const MAX_ARTICLE_CHARS = 40_000;@@ -141,46 +140,7 @@ export function parseReview(raw) {return review;}-async function viaVertex({ system, parts }) {- const { vertexClaudeConfigured, vertexAnthropicMessages } = await import('../vertex-claude.js');- if (!vertexClaudeConfigured()) return null;- const content = parts.map((part) => (part.type === 'image' ? { type: 'image', source: { type: 'base64', media_type: part.mime, data: part.data } } : { type: 'text', text: part.text }));- const response = await vertexAnthropicMessages({ model: EDITOR_MODEL, max_tokens: 6000, system, messages: [{ role: 'user', content }] });- if (!response.ok) throw new Error(`Vertex ${response.status}: ${(await response.text()).slice(0, 200)}`);- const body = await response.json();- return { model: `vertex:${EDITOR_MODEL}`, text: body.content.filter((block) => block.type === 'text').map((block) => block.text).join('') };-}--async function viaChatCompletions({ system, parts }, { url, key, model, label, extraHeaders = {} }) {- if (!key) return null;- const content = parts.map((part) => (part.type === 'image' ? { type: 'image_url', image_url: { url: `data:${part.mime};base64,${part.data}` } } : { type: 'text', text: part.text }));- const response = await fetch(url, {- method: 'POST',- headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...extraHeaders },- body: JSON.stringify({ model, messages: [{ role: 'system', content: system }, { role: 'user', content }] }),- signal: AbortSignal.timeout(600_000),- });- if (!response.ok) throw new Error(`${label} ${response.status}: ${(await response.text()).slice(0, 200)}`);- const body = await response.json();- return { model: `${label}:${model}`, text: body.choices?.[0]?.message?.content || '' };-}-export async function reviewWithEditor(request, env = process.env) {- const rungs = [- () => viaVertex(request),- () => viaChatCompletions(request, { url: 'https://openrouter.ai/api/v1/chat/completions', key: env.OPENROUTER_API_KEY, model: `anthropic/${EDITOR_MODEL}`, label: 'openrouter', extraHeaders: { 'http-referer': 'https://three.ws', 'x-title': 'three.ws editorial review' } }),- () => viaChatCompletions(request, { url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-5.5-pro', label: 'openai' }),- () => viaChatCompletions(request, { url: 'https://integrate.api.nvidia.com/v1/chat/completions', key: env.NVIDIA_API_KEY, model: 'moonshotai/kimi-k3', label: 'nvidia' }),- ];- const failures = [];- for (const rung of rungs) {- try {- const result = await rung();- if (!result) continue;- return { ...parseReview(result.text), model: result.model, fallbacks: failures };- } catch (err) {- failures.push(err.message);- }- }- throw new Error(`no editor model was reachable:\n ${failures.join('\n ') || 'no credentials for Vertex, OpenRouter, or OpenAI'}`);+ const { value, model, fallbacks } = await callModelChain(request, { env, parse: parseReview });+ return { ...value, model, fallbacks };}diff --git a/api/_lib/x-content/llm.js b/api/_lib/x-content/llm.jsnew file mode 100644index 000000000..73da642a1--- /dev/null+++ b/api/_lib/x-content/llm.js@@ -0,0 +1,62 @@+// The model chain both editorial jobs run on: drafting a post from an evidence+// brief, and reviewing one before it ships.+//+// Order is cost and quality, strongest first: Claude on Vertex AI (Google+// credits, the standing approval in the operating rules), Claude through+// OpenRouter, OpenAI, then Kimi K3 on NVIDIA NIM (free, multimodal, slow). A+// rung with no credentials is skipped; a rung that errors, or that answers with+// something the caller cannot parse, falls through to the next one. Falling+// through on a parse failure is deliberate: a model that returns prose where+// JSON was asked for has failed the call, and the next rung usually will not.++export const EDITOR_MODEL = 'claude-opus-5';++async function viaVertex({ system, parts }) {+ const { vertexClaudeConfigured, vertexAnthropicMessages } = await import('../vertex-claude.js');+ if (!vertexClaudeConfigured()) return null;+ const content = parts.map((part) => (part.type === 'image' ? { type: 'image', source: { type: 'base64', media_type: part.mime, data: part.data } } : { type: 'text', text: part.text }));+ const response = await vertexAnthropicMessages({ model: EDITOR_MODEL, max_tokens: 6000, system, messages: [{ role: 'user', content }] });+ if (!response.ok) throw new Error(`Vertex ${response.status}: ${(await response.text()).slice(0, 200)}`);+ const body = await response.json();+ return { model: `vertex:${EDITOR_MODEL}`, text: body.content.filter((block) => block.type === 'text').map((block) => block.text).join('') };+}++async function viaChatCompletions({ system, parts }, { url, key, model, label, extraHeaders = {} }) {+ if (!key) return null;+ const content = parts.map((part) => (part.type === 'image' ? { type: 'image_url', image_url: { url: `data:${part.mime};base64,${part.data}` } } : { type: 'text', text: part.text }));+ const response = await fetch(url, {+ method: 'POST',+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...extraHeaders },+ body: JSON.stringify({ model, messages: [{ role: 'system', content: system }, { role: 'user', content }] }),+ signal: AbortSignal.timeout(600_000),+ });+ if (!response.ok) throw new Error(`${label} ${response.status}: ${(await response.text()).slice(0, 200)}`);+ const body = await response.json();+ return { model: `${label}:${model}`, text: body.choices?.[0]?.message?.content || '' };+}++export function modelRungs(request, env = process.env) {+ return [+ () => viaVertex(request),+ () => viaChatCompletions(request, { url: 'https://openrouter.ai/api/v1/chat/completions', key: env.OPENROUTER_API_KEY, model: `anthropic/${EDITOR_MODEL}`, label: 'openrouter', extraHeaders: { 'http-referer': 'https://three.ws', 'x-title': 'three.ws editorial review' } }),+ () => viaChatCompletions(request, { url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-5.5-pro', label: 'openai' }),+ () => viaChatCompletions(request, { url: 'https://integrate.api.nvidia.com/v1/chat/completions', key: env.NVIDIA_API_KEY, model: 'moonshotai/kimi-k3', label: 'nvidia' }),+ ];+}++// `parse` turns a rung's raw text into the caller's shape and may throw to+// reject that rung. The parsed value comes back with the model that produced it+// and the failures of every rung above it.+export async function callModelChain(request, { env = process.env, parse = (text) => text } = {}) {+ const failures = [];+ for (const rung of modelRungs(request, env)) {+ try {+ const result = await rung();+ if (!result) continue;+ return { value: parse(result.text), model: result.model, fallbacks: failures };+ } catch (err) {+ failures.push(err.message);+ }+ }+ throw new Error(`no model was reachable:\n ${failures.join('\n ') || 'no credentials for Vertex, OpenRouter, OpenAI, or NVIDIA'}`);+}diff --git a/api/_lib/x-content/review.js b/api/_lib/x-content/review.jsindex b2173280b..abc0a2bf1 100644--- a/api/_lib/x-content/review.js+++ b/api/_lib/x-content/review.js@@ -82,7 +82,19 @@ export async function reviewItem(item, { root, glossary = [], env = process.env,}}const verification = await verifyItem(item, { root, glossary, env });- const editor = skipEditor ? null : await reviewWithEditor(await buildReviewRequest(item, { root, verification, lint }), env);+ // An unreachable editor is a blocker, not a crash. The lint and the live+ // verification are the expensive half of a review and they are already done+ // by this point; throwing them away leaves the operator with no record of+ // the problems a model was never needed to find.+ let editorError = null;+ let editor = null;+ if (!skipEditor) {+ try {+ editor = await reviewWithEditor(await buildReviewRequest(item, { root, verification, lint }), env);+ } catch (err) {+ editorError = err.message;+ }+ }const blockers = [...lint.filter((row) => row.severity === 'blocking').map((row) => `${row.where}: ${row.message}`),@@ -93,7 +105,7 @@ export async function reviewItem(item, { root, glossary = [], env = process.env,const overridden = item.editorOverride?.reason && editor.verdict === 'revise' && !editor.issues.some((row) => row.severity === 'blocking');if (editor.verdict !== 'publish' && !overridden) blockers.push(`editor verdict is ${editor.verdict}`);} else {- blockers.push('the AI editor did not run');+ blockers.push(editorError ? `the AI editor did not run: ${editorError.split('\n')[0]}` : 'the AI editor did not run');}// The editor's rewrite is a draft like any other: lint it, and list every@@ -115,6 +127,7 @@ export async function reviewItem(item, { root, glossary = [], env = process.env,lint,verification,editor,+ editorError,};const path = resolve(root, reviewPath(item.id));mkdirSync(dirname(path), { recursive: true });diff --git a/api/_lib/x-content/verify.js b/api/_lib/x-content/verify.jsindex 6f2b60ddf..d7c316043 100644--- a/api/_lib/x-content/verify.js+++ b/api/_lib/x-content/verify.js@@ -60,7 +60,7 @@ export async function linkChecks(texts) {return checks;}-function createPageReader() {+export function createPageReader() {let browser = null;const cache = new Map();return {@@ -90,7 +90,9 @@ function createPageReader() {).catch(() => {});const text = await page.evaluate(() => document.body.innerText);- const result = { status, text: normalize(text) };+ // `text` is normalized for substring checks; `raw` keeps the line+ // breaks and casing the announcement brief harvests facts from.+ const result = { status, text: normalize(text), raw: text };cache.set(url, result);return result;} finally {diff --git a/docs/announcement-factory.md b/docs/announcement-factory.mdnew file mode 100644index 000000000..5898b5645--- /dev/null+++ b/docs/announcement-factory.md@@ -0,0 +1,188 @@+# The announcement factory++three.ws has shipped 429 surfaces and posted about roughly 50. The other 322 are not a roadmap,+they are inventory that already works and that nobody outside the repository has ever been told+about. This is the machinery that works that backlog down without a person writing each+announcement from scratch, and without the output reading like 300 posts from one template.++It sits between two things that already existed: the+[announcement ledger](./announcements/README.md), which scores what is worth announcing, and the+[X content pipeline](./x-content-pipeline.md), which publishes a reviewed queue on a human cadence.+The gap between them was the whole job: deciding when each surface goes out, gathering the facts+that make a post checkable, and writing the thing.++```+announce:rank -> announce:plan -> announce:kit -> announce:media -> x:content review -> approve -> cron posts+ what is when it goes brief, draft, the frame from lint, live facts, owner Cloud Scheduler,+ worth it out, in what pack, queue the live route the AI editor decides every 15 minutes+ shape+```++Nothing in this chain posts. Publishing still requires a passing editorial review and the owner+setting an item's status to `approved`.++---++## The calendar++```bash+npm run announce:rank -- --probe --write # rebuild the ledger and probe every route+npm run announce:plan # print the next 30 slots+npm run announce:plan -- --write # data/announce-plan/plan.json + CALENDAR.md+npm run announce:plan -- --batch 3 # one week's batch in full+```++[`scripts/announce-plan.mjs`](../scripts/announce-plan.mjs) turns the ranked backlog into dated+slots. Three things decide the schedule, and all three are read from files that already govern+publishing rather than chosen here:++| Decision | Where it comes from |+|---|---|+| How many posts a day, and at what times | The `cadence` block of [`data/x-content/queue.json`](../data/x-content/queue.json): daily cap, minimum gap, quiet hours. A slot whose jitter window could land inside quiet hours is dropped rather than promised. |+| What order, and which shape | The ledger's scores, then rotation: no more than `maximumSameLaneInARow` of one audience, no more than `maximumSamePatternInARow` of one post shape, from the same queue file. |+| Which ones need owner approval first | Any surface in the `crypto` section of [`data/pages.json`](../data/pages.json) renders live third-party market data, so a frame of it falls under the operating rules' coin gate. Those slots carry `mediaGate: "owner-approval"` and the factory skips them unless asked. |++The plan is a pure function of the ledger and the start date, so it is regenerated rather than+maintained. A surface already queued, already carrying a pack, or listed in+[`data/announce-deferred.json`](../data/announce-deferred.json) is dropped from it.++**Deferrals.** The ledger is rebuilt from the repository on every run, so it cannot remember a+judgement someone made by looking at a captured frame. `data/announce-deferred.json` is where that+judgement lives, with the reason, and it is committed for exactly that reason.++## Lanes and patterns++`lane` is the audience and comes from where the surface lives: `token` for the crypto section,+`labs` for the labs section, `developer` for build, agent tools, machine, packages, workers and+services, `community` for the rest.++`pattern` is the shape of the post, and each surface offers a ranked list so the sequencer can+change shape without changing which surface is next:++| Pattern | When it is offered | What the drafter is told |+|---|---|---|+| `clip` | The surface has a route and something moves on it | The media is a loop. Write what the loop cannot say. |+| `number` | Its own description carries a measured number | Lead with the number and what it counts. |+| `correction` | Its description contradicts an assumption a reader would hold | Lead with the assumption, then the fact that replaces it. |+| `walkthrough` | Any surface a visitor can act on | Lead with the first move and what comes back. |+| `mechanism` | Always available, and the default | Lead with how the thing works. |++A package, a worker, or a service is never offered `clip`: a loop has to be a loop of something+running, and those have no route.++## The factory++```bash+npm run announce:kit -- --count 3 # the next three planned slots+npm run announce:kit -- --batch 2 # a whole week+npm run announce:kit -- --id labor-market # one surface+npm run announce:kit -- --brief-only # gather facts, call no model+npm run announce:kit -- --capture # also shoot the frames+npm run announce:kit -- --include-gated # include owner-gated media+npm run announce:kit -- --dry-run # write nothing+```++[`scripts/announce-kit.mjs`](../scripts/announce-kit.mjs) runs five steps per slot.++**1. The brief** ([`api/_lib/announce/brief.js`](../api/_lib/announce/brief.js)) gathers every+checkable fact about the surface: the rendered text of the live route, the changelog entries that+mention it, its docs, and its README. It emits `evidenceCandidates`, each one a check the verifier+can already run (`page` contains this sentence, `file` contains this line). Two rules make those+candidates trustworthy rather than decorative: a page fact must be a whole sentence of the rendered+page, and a file fact must be a literal substring of the file on disk, because that is what+[`verify.js`](../api/_lib/x-content/verify.js) matches against. Sentences carrying a banned dash+glyph are dropped rather than rewritten, since the quote has to match character for character.++**2. The media recipe** goes into [`data/announce-media.json`](../data/announce-media.json), and+`npm run announce:media` shoots it from the live route with provenance written beside the pixels.+A surface with no route (115 of the 316 planned announcements are a package, a worker, or a+service) gets a title card instead: [`api/_lib/announce/card.js`](../api/_lib/announce/card.js)+typesets its real name, its real description, the command a developer really runs, and the tools it+really exposes, in the site's own fonts, and the same capture engine renders it. A post with no+image measured 0.875x against the account median, so "this one ships without an image" is not an+option.++**3. The draft** ([`api/_lib/announce/draft.js`](../api/_lib/announce/draft.js)) is written by the+model chain (Claude on Vertex AI, then OpenRouter, OpenAI, NVIDIA NIM) from the brief and nothing+else. It is then held against every gate the queue enforces: the voice lint, the editorial lint,+the claims ledger, the evidence list, and the account's own archive. Findings are handed back to+the model verbatim and it writes again, up to three attempts. A draft that still fails is written+to `data/announce-plan/drafts/<id>.rejected.json` instead of into the queue.++**Writing one by hand.** Drop a file at `data/announce-plan/drafts/<id>.json` in the same shape the+model returns (`post`, `thread`, `telegram`, `alt`, `claims`, `mentions`, `why`, `headline`) and the+factory prefers it, running it through exactly the same checks. `--redraft` ignores it.++**4. The pack** is `docs/announcements/<id>.md` plus `<id>.post.txt`, the format+`npm run check:announce` gates and a human approves from: the slot, the lane, the audience, the+tracked links, the claim table with its evidence, the media and its alt text, the post, the reason+it is written that way, and the longer Telegram register.++**5. The queue item** goes into [`data/x-content/queue.json`](../data/x-content/queue.json), with+`textFrom` pointing at the pack's `.post.txt`, so the bytes that were reviewed are the bytes that+ship. It lands at `review` when the queue validator finds nothing wrong with it and at `draft` when+something is still missing, which is almost always the frame: capture it, re-run the same command,+and it moves up. The status is the validator's verdict, not the factory's opinion.++## What the model is not allowed to do++| Rule | Enforced by |+|---|---|+| Invent a fact | The drafter sees only the brief, and every claim must cite one of its `evidenceCandidates`, copied exactly |+| Invent evidence | `draftFindings` rejects any evidence object that is not one of the candidates |+| State a number with nothing behind it | `claimProblems`: every number, ordinal and absolute must sit inside a declared claim |+| Tag an account the feature does not run on | Every `@mention` needs a recorded reason, and the reviewer confirms the account is real and public |+| Write hype, a hashtag, an emoji, a dash, a teaser, or a rhetorical opener | `copyProblems` and `languageProblems` |+| Repeat something @trythreews already posted | Similarity against the scraped archive and the rest of the queue |+| Describe an image that does not show what it says | The AI editor, which sees the frame and the alt text |++## Finishing a batch++```bash+npm run check:announce # media, alt text, length, voice, uniqueness, the coin gate+npm run x:content -- review --status review # lint, live fact checks, the AI editor, recorded per item+npm run x:content -- run --dry-run --id <id> # the exact calls that would go to X+npm run x:content -- approve --status review # the owner gate, for the whole batch+```++`approve` is the only step that is the owner's, and it is a gate rather than a switch: it moves an+item to `approved` only while a passing review record covers the exact bytes in the queue right+now, and prints why it is holding anything it refuses. After that the Cloud Scheduler tick+(`/api/cron/x-content`, every 15 minutes) sends each item at its slot, re-checks every link first,+and records what it sent.++So a week of announcements is four commands:++```bash+npm run announce:kit -- --batch 2 --capture+npm run check:announce+npm run x:content -- review --status review+npm run x:content -- approve --status review+```++## Credentials++The factory needs a model for the drafting step and the editorial review. It uses the shared chain+in [`api/_lib/x-content/llm.js`](../api/_lib/x-content/llm.js): Claude on Vertex AI first (the+standing Google Cloud approval), then `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `NVIDIA_API_KEY`.+On a workstation, `gcloud auth application-default login` is enough. Everything else (ranking,+planning, briefs, media capture, packing, the whole gate) runs with no model at all:+`npm run announce:kit -- --brief-only` is the offline half.++## Where things live++| Path | Role |+|---|---|+| [scripts/announce-plan.mjs](../scripts/announce-plan.mjs) | The calendar |+| [scripts/announce-kit.mjs](../scripts/announce-kit.mjs) | The factory |+| [api/_lib/announce/plan.js](../api/_lib/announce/plan.js) | Slot times, lanes, patterns, rotation |+| [api/_lib/announce/ledger.js](../api/_lib/announce/ledger.js) | Ledger, backlog, deferrals, plan persistence |+| [api/_lib/announce/brief.js](../api/_lib/announce/brief.js) | Evidence gathering |+| [api/_lib/announce/draft.js](../api/_lib/announce/draft.js) | Drafting and the rejection rules |+| [api/_lib/announce/card.js](../api/_lib/announce/card.js) | Title cards for surfaces with no route |+| [api/_lib/announce/kit.js](../api/_lib/announce/kit.js) | Pack rendering |+| [api/_lib/x-content/llm.js](../api/_lib/x-content/llm.js) | The model chain, shared with the editor |+| `data/announce-plan/` | Generated: the plan, the calendar, briefs, hand-written drafts |+| [data/announce-deferred.json](../data/announce-deferred.json) | Surfaces held back, with the reason |+| [docs/announcements/](./announcements/) | The packs themselves |+| [tests/announce-factory.test.js](../tests/announce-factory.test.js) | The rules above, as tests |diff --git a/docs/start-here.md b/docs/start-here.mdindex 2b189882e..396fa5fd0 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -225,6 +225,7 @@ Deeper references that don't fit a track above but answer real questions:- [The 3D viewer](./viewer.md): the rendering layer reference (model loading, cameras, animation, lighting)- [Avatar Artifact](./avatar-artifact.md): the standalone viewer page, its ?agent= and ?model= parameters, and the iframe you paste anywhere- [Farcaster memory seeding](./farcaster-memory-seeding.md): give an agent your Farcaster voice, proved with a wallet the account already verified, and revoke it in one click+- [The announcement factory](./announcement-factory.md): how the 322 shipped surfaces that have never been posted about get a dated slot, an evidence brief, a frame, a drafted post, and a pack, one command per batch- [X content pipeline](./x-content-pipeline.md): how @trythreews publishes native video, images, threads, blog shares, and full X Articles from one reviewed queue on a human cadence- [X memory seeding](./x-memory-seeding.md): seed an agent from your public X posts behind an explicit, versioned consent you can revoke (revocation deletes what the seed wrote)- [GitHub memory seeding](./github-memory-seeding.md): tick the profile, repositories, and READMEs your agent may read, and nothing outside that list is ever fetched or stored (disconnecting deletes every fact it wrote)diff --git a/docs/x-content-pipeline.md b/docs/x-content-pipeline.mdindex 5c543db19..08eab07b3 100644--- a/docs/x-content-pipeline.md+++ b/docs/x-content-pipeline.md@@ -48,6 +48,8 @@ X Articles require the posting account to be on X Premium.| `data/x-content/articles/<id>.md` | Article bodies, in Markdown. || `public/x-media/<id>/` | Media for queue items. Media must live under `public/` or `data/` so it ships inside the production image. || [api/_lib/x-content/](../api/_lib/x-content/) | The engine: voice and editorial lint, media rules, live fact verification, the AI editor, review records, Markdown to Article conversion, scheduler, publisher, ledger. |+| [api/_lib/x-content/llm.js](../api/_lib/x-content/llm.js) | The model chain (Vertex, OpenRouter, OpenAI, NVIDIA NIM) the editor and the announcement drafter share. |+| [api/_lib/announce/](../api/_lib/announce/) | The [announcement factory](./announcement-factory.md): it fills this queue from the backlog of shipped surfaces nobody has posted about. || `data/x-content/reviews/<id>.json` | The editorial review record for each item, bound to a hash of the exact content that was reviewed. || [api/cron/x-content.js](../api/cron/x-content.js) | The Cloud Scheduler tick, every 15 minutes. || [scripts/x-content.mjs](../scripts/x-content.mjs) | The operator CLI. |@@ -86,7 +88,7 @@ X Articles require the posting account to be on X Premium.}```-- `status`: `draft` (may be unfinished), `review` (must pass `check`), `approved` (eligible to publish), `paused`, `posted`.+- `status`: `draft` (may be unfinished), `review` (must pass `check`), `approved` (eligible to publish), `paused`, `posted`. Move an item to `approved` with `npm run x:content -- approve <slug>` (or `--status review` for a whole batch), which refuses anything a passing review record does not already cover.- `lane` and `pattern` are free-form labels; rotation compares them against what was published last.- `claims` is the fact ledger. Every number, ordinal, and absolute word (first, only, every, never, fastest) in the copy must sit inside some claim's `says`, every `says` must quote the copy, and every claim carries at least one piece of `evidence` (types below).- `mentions` maps each @handle in the copy to the reason the tag is true. A tag with no reason is blocked.diff --git a/package.json b/package.jsonindex 591f5dedd..9efef5274 100644--- a/package.json+++ b/package.json@@ -194,6 +194,8 @@"i18n:backfill": "node scripts/i18n-backfill.mjs","changelog:gaps": "node scripts/changelog-gaps.mjs","announce:rank": "node scripts/announce-rank.mjs",+ "announce:plan": "node scripts/announce-plan.mjs",+ "announce:kit": "node scripts/announce-kit.mjs","announce:media": "node scripts/capture-doc-media.mjs --spec data/announce-media.json --out public/announce/img --manifest public/announce/media-manifest.json","check:announce": "node scripts/check-announce.mjs","x:content": "node scripts/x-content.mjs",diff --git a/scripts/announce-kit.mjs b/scripts/announce-kit.mjsnew file mode 100644index 000000000..8289a9326--- /dev/null+++ b/scripts/announce-kit.mjs@@ -0,0 +1,305 @@+#!/usr/bin/env node+// announce-kit.mjs - the announcement factory: a planned slot in, a finished+// pack, media recipe, and queue item out.+//+// The backlog is 300-plus shipped surfaces that have never been posted about.+// Writing each announcement by hand takes an afternoon, which is why fewer than+// 50 of 430 surfaces were ever announced. This does the parts that are+// mechanical and refuses to fake the parts that are not:+//+// 1. brief every checkable fact about the surface, harvested from the live+// page, the changelog, its docs, and its README+// (api/_lib/announce/brief.js)+// 2. media a capture recipe for the frame, added to data/announce-media.json+// so `npm run announce:media` can shoot it from the live route+// 3. draft a post written from that brief by the model chain, then held+// against every gate the queue enforces (voice, editorial, claims,+// evidence, repetition) and rewritten until it passes+// (api/_lib/announce/draft.js)+// 4. pack docs/announcements/<id>.md and <id>.post.txt, the format+// `npm run check:announce` gates and a human approves from+// 5. queue the item in data/x-content/queue.json, at status `draft`+//+// What it never does: approve anything, capture a frame it was not asked to,+// or post. Publishing stays where it was, behind a passing editorial review and+// the owner's approval.+//+// npm run announce:kit -- --count 3 # the next three planned slots+// npm run announce:kit -- --batch 1 # a whole week's batch+// npm run announce:kit -- --id labor-market # one surface by id+// npm run announce:kit -- --brief-only # briefs and recipes, no model+// npm run announce:kit -- --capture # also shoot the frames+// npm run announce:kit -- --include-gated # include owner-gated media+// npm run announce:kit -- --dry-run # write nothing, print the plan+//+// A draft the model cannot be trusted to write (or that you want to write+// yourself) can be dropped at data/announce-plan/drafts/<id>.json in the same+// shape the model returns; this script prefers it and runs it through the same+// checks.++import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { briefPath, buildBrief } from '../api/_lib/announce/brief.js';+import { draftFindings, draftPost, itemFor } from '../api/_lib/announce/draft.js';+import { renderPack, renderPostFile } from '../api/_lib/announce/kit.js';+import { MissingLedgerError, ledgerEntryFor, loadLedger, loadOrBuildPlan } from '../api/_lib/announce/ledger.js';+import { slugFor } from '../api/_lib/announce/plan.js';+import { createPageReader } from '../api/_lib/x-content/verify.js';+import { validateItem } from '../api/_lib/x-content/queue.js';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');++function loadEnvFile(path) {+ if (!existsSync(path)) return;+ for (const line of readFileSync(path, 'utf8').split('\n')) {+ const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);+ if (match && !process.env[match[1]]) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');+ }+}+loadEnvFile(join(root, '.env.local'));+loadEnvFile(join(root, '.env'));++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(`--${name}`);+const option = (name, fallback = null) => {+ const index = argv.indexOf(`--${name}`);+ return index >= 0 && argv[index + 1] && !argv[index + 1].startsWith('--') ? argv[index + 1] : fallback;+};++const dryRun = flag('dry-run');+const briefOnly = flag('brief-only');+const includeGated = flag('include-gated');+const redraft = flag('redraft');+const live = !flag('no-live');++const QUEUE_FILE = join(root, 'data/x-content/queue.json');+const MEDIA_SPEC = join(root, 'data/announce-media.json');+const PACK_DIR = join(root, 'docs/announcements');+const DRAFT_DIR = join(root, 'data/announce-plan/drafts');++let ledger;+try {+ ledger = loadLedger(root);+} catch (error) {+ if (error instanceof MissingLedgerError) {+ console.error(error.message);+ process.exit(1);+ }+ throw error;+}++const plan = loadOrBuildPlan(root, { start: option('start'), refresh: flag('refresh') });+const wanted = (() => {+ const id = option('id');+ if (id) {+ const slot = plan.slots.find((row) => row.id === id);+ if (slot) return [slot];+ // A packed surface leaves the plan (the plan is what is left to do), so+ // re-running one after an edit rebuilds its slot from the queue item it+ // already has. Its date, lane and shape are whatever was committed.+ const queued = JSON.parse(readFileSync(QUEUE_FILE, 'utf8')).items.find((item) => item.id === id);+ const entry = (ledger.entries || []).find((row) => slugFor(row.key) === id);+ if (!queued || !entry) {+ console.error(`no planned slot or queue item with id ${id}. See: npm run announce:plan`);+ process.exit(1);+ }+ return [{+ position: 0,+ id,+ key: entry.key,+ kind: entry.kind,+ section: entry.section,+ url: entry.url || null,+ lane: queued.lane,+ pattern: queued.pattern,+ notBefore: queued.notBefore,+ windowMinutes: queued.windowMinutes || plan.slots[0]?.windowMinutes || 90,+ batch: 0,+ score: entry.score,+ partner: entry.partner || null,+ shot: `${id}-hero`,+ motion: queued.pattern === 'clip',+ mediaGate: null,+ pack: `docs/announcements/${id}.md`,+ }];+ }+ const batch = option('batch');+ const pool = batch ? plan.slots.filter((row) => row.batch === Number(batch)) : plan.slots;+ const eligible = includeGated ? pool : pool.filter((row) => !row.mediaGate);+ return batch ? eligible : eligible.slice(0, Number(option('count', 3)));+})();++if (!wanted.length) {+ console.error('nothing to do: every planned slot in range is either gated (use --include-gated) or already packed.');+ process.exit(1);+}++const voice = existsSync(join(root, 'docs/announce-voice.md')) ? readFileSync(join(root, 'docs/announce-voice.md'), 'utf8') : null;+const queue = JSON.parse(readFileSync(QUEUE_FILE, 'utf8'));+// Every other live head in the queue, so a new draft is held against them for+// repetition. An item's own previous head is excluded: re-running the factory+// over a pack that already exists must not reject it for matching itself.+const queuedHeads = new Map(+ (queue.items || []).filter((item) => item.status !== 'posted').map((item) => [item.id, item.posts?.[0]?.text || '']),+);+const headsExcept = (id) => [...queuedHeads.entries()].filter(([key, text]) => key !== id && text).map(([, text]) => text);++function upsertShot(slot, alt, entry) {+ const spec = JSON.parse(readFileSync(MEDIA_SPEC, 'utf8'));+ // A surface with a route is photographed. A package, worker, or service has+ // no route, so its frame is a title card typeset from its own README and+ // package.json by the same capture engine.+ const shot = slot.url+ ? {+ id: slot.shot,+ surface: slot.key,+ url: slot.url,+ alt,+ caption: `Captured from the live ${slot.url} route for the ${slot.id} announcement.`,+ ...(slot.motion ? { settle: 9000, motion: { seconds: 5, fps: 12 } } : {}),+ }+ : {+ id: slot.shot,+ surface: slot.key,+ viewport: 'wide',+ alt,+ caption: `Title card for ${slot.key}, typeset from its README and package.json.`,+ card: { dir: entry.dir || null, title: entry.title || slot.key, description: entry.description || '' },+ };+ const index = (spec.shots || []).findIndex((row) => row.id === slot.shot);+ if (index >= 0) spec.shots[index] = { ...spec.shots[index], ...shot };+ else spec.shots.push(shot);+ if (!dryRun) writeFileSync(MEDIA_SPEC, `${JSON.stringify(spec, null, '\t')}\n`);++ // The manifest records the alt text that was captured with the frame, and a+ // draft can change it after the capture. Keep the two in step rather than+ // leaving the docs renderer quoting an alt nobody reviewed.+ const manifestPath = join(root, 'public/announce/media-manifest.json');+ if (!dryRun && existsSync(manifestPath)) {+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));+ const shots = Array.isArray(manifest.shots) ? manifest.shots : Object.values(manifest.shots || {});+ const written = shots.find((row) => row.id === slot.shot);+ if (written && written.alt !== alt) {+ written.alt = alt;+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, '\t')}\n`);+ }+ }+ return shot;+}++function upsertItem(item) {+ const current = JSON.parse(readFileSync(QUEUE_FILE, 'utf8'));+ const index = (current.items || []).findIndex((row) => row.id === item.id);+ if (index >= 0) current.items[index] = item;+ else current.items.push(item);+ current.items.sort((left, right) => String(left.notBefore).localeCompare(String(right.notBefore)));+ if (!dryRun) writeFileSync(QUEUE_FILE, `${JSON.stringify(current, null, '\t')}\n`);+}++function capture(shotId) {+ const result = spawnSync(+ 'node',+ ['scripts/capture-doc-media.mjs', '--spec', 'data/announce-media.json', '--out', 'public/announce/img', '--manifest', 'public/announce/media-manifest.json', '--only', shotId],+ { cwd: root, stdio: 'inherit' },+ );+ return result.status === 0;+}++const pages = live ? createPageReader() : null;+const results = [];++try {+ for (const slot of wanted) {+ const entry = ledgerEntryFor(ledger, slot.key);+ const rank = (ledger.entries || []).filter((row) => row.coverage === 'no').findIndex((row) => row.key === slot.key) + 1;+ process.stderr.write(`\n${slot.id}: brief`);+ const brief = await buildBrief(slot, { root, ledgerEntry: entry, pages });+ if (!dryRun) {+ mkdirSync(dirname(join(root, briefPath(slot.id))), { recursive: true });+ writeFileSync(join(root, briefPath(slot.id)), `${JSON.stringify(brief, null, '\t')}\n`);+ }+ process.stderr.write(` (${brief.live.facts.length} live facts, ${brief.evidenceCandidates.length} evidence candidates, ${brief.changelog.length} changelog entries)`);++ if (briefOnly) {+ results.push({ id: slot.id, state: 'brief', detail: `${brief.evidenceCandidates.length} evidence candidates` });+ continue;+ }++ const handWritten = join(DRAFT_DIR, `${slot.id}.json`);+ let draft = null;+ let model = 'hand-written draft';+ let findings = [];+ if (!redraft && existsSync(handWritten)) {+ draft = JSON.parse(readFileSync(handWritten, 'utf8'));+ findings = draftFindings(brief, draft, { root, otherHeads: headsExcept(slot.id) });+ process.stderr.write(`\n${slot.id}: using ${handWritten.replace(`${root}/`, '')}`);+ } else {+ process.stderr.write(`\n${slot.id}: drafting`);+ try {+ const attempt = await draftPost(brief, { root, voice, otherHeads: headsExcept(slot.id) });+ draft = attempt.draft;+ model = attempt.model;+ findings = attempt.ok ? [] : attempt.findings;+ process.stderr.write(` (${attempt.attempts.length} attempt(s) on ${attempt.model})`);+ } catch (error) {+ results.push({ id: slot.id, state: 'no model', detail: error.message.split('\n')[0] });+ process.stderr.write(` failed: ${error.message.split('\n')[0]}`);+ continue;+ }+ }++ if (findings.length) {+ results.push({ id: slot.id, state: 'draft rejected', detail: findings[0] });+ if (!dryRun) {+ mkdirSync(DRAFT_DIR, { recursive: true });+ writeFileSync(join(DRAFT_DIR, `${slot.id}.rejected.json`), `${JSON.stringify({ draft, findings }, null, '\t')}\n`);+ }+ continue;+ }++ upsertShot(slot, String(draft.alt || '').trim(), entry);+ if (flag('capture') && !dryRun) {+ process.stderr.write(`\n${slot.id}: capturing ${slot.shot}`);+ if (!capture(slot.shot)) process.stderr.write(' (capture failed)');+ }++ const mediaPath = `public/announce/img/${slot.shot}.webp`;+ // `review` means finished and waiting for the editorial bar; `draft`+ // means something is still missing (almost always the frame, which is+ // captured separately). The queue validator decides which, not this+ // script's optimism.+ const candidate = itemFor(brief, draft, { mediaPath });+ const problems = validateItem(candidate, root);+ const item = { ...candidate, status: problems.length ? 'draft' : 'review' };+ const pack = renderPack({ brief, draft, slot, ledgerEntry: entry, rank: rank || null, total: (ledger.totals?.never ?? null), model });+ if (!dryRun) {+ mkdirSync(PACK_DIR, { recursive: true });+ writeFileSync(join(PACK_DIR, `${slot.id}.md`), pack);+ writeFileSync(join(PACK_DIR, `${slot.id}.post.txt`), renderPostFile(draft));+ upsertItem(item);+ }+ queuedHeads.set(slot.id, item.posts[0].text);+ results.push({+ id: slot.id,+ state: problems.length ? 'packed, item incomplete' : 'packed, awaiting review',+ detail: problems.length ? problems[0] : `${slot.notBefore.slice(0, 16).replace('T', ' ')} UTC, ${brief.lane}/${brief.pattern}`,+ });+ }+} finally {+ if (pages) await pages.close();+}++console.log('\n');+console.log(`${'pack'.padEnd(28)} ${'state'.padEnd(24)} detail`);+for (const row of results) console.log(`${row.id.padEnd(28)} ${row.state.padEnd(24)} ${row.detail}`);+const packed = results.filter((row) => row.state.startsWith('packed'));+if (packed.length) {+ console.log(`\nNext:\n npm run announce:media -- --only ${packed.map((row) => `${row.id}-hero`).join(',')}`);+ console.log(' npm run check:announce');+ console.log(' npm run x:content -- review --status review');+ console.log(' npm run x:content -- approve --status review # owner: releases the batch to its slots');+}+if (dryRun) console.log('\n(dry run: nothing was written)');diff --git a/scripts/announce-plan.mjs b/scripts/announce-plan.mjsnew file mode 100644index 000000000..1e3424b1d--- /dev/null+++ b/scripts/announce-plan.mjs@@ -0,0 +1,120 @@+#!/usr/bin/env node+// announce-plan.mjs - turn the ranked backlog into a dated posting calendar.+//+// The ledger (`npm run announce:rank -- --write`) says what is worth+// announcing. This says when each one goes out, in which lane, in which shape,+// and which ones need owner approval on their media before they can be+// committed. It is the piece that was missing between "322 surfaces have never+// been posted" and "the account posts three times a day without anyone writing+// a schedule".+//+// The calendar is derived, never invented: slot times come from the cadence in+// data/x-content/queue.json, rotation comes from that file's quality block, and+// the order comes from the ledger's scores. Re-running with the same start date+// produces the same plan, so a batch that is already drafted keeps its dates.+// Surfaces already queued, already packed, or listed in+// data/announce-deferred.json are dropped: the plan covers what is left.+//+// node scripts/announce-plan.mjs # the next 30 slots+// node scripts/announce-plan.mjs --batch 1 # one week's batch in full+// node scripts/announce-plan.mjs --write # plan.json + CALENDAR.md+// node scripts/announce-plan.mjs --start 2026-10-01 # anchor the calendar+// node scripts/announce-plan.mjs --json # machine-readable+//+// Wired as `npm run announce:plan`. It never drafts, never writes into the+// queue, and never posts.++import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { MissingLedgerError, PLAN_DIR, planFor, writePlan } from '../api/_lib/announce/ledger.js';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(name);+const option = (name, fallback = null) => {+ const index = argv.indexOf(name);+ return index >= 0 && argv[index + 1] && !argv[index + 1].startsWith('--') ? argv[index + 1] : fallback;+};++const start = option('--start', new Date(Date.now() + 86_400_000).toISOString().slice(0, 10));++let plan;+try {+ plan = planFor(root, { start });+} catch (error) {+ if (error instanceof MissingLedgerError) {+ console.error(error.message);+ process.exit(1);+ }+ throw error;+}++function calendarMarkdown() {+ const batches = Math.ceil(plan.days / 7);+ const lines = [+ '# The announcement calendar',+ '',+ `Generated by \`npm run announce:plan -- --write\` on ${plan.generatedAt.slice(0, 10)} from \`data/announcements.json\`. The same ledger and the same start date always produce this same calendar, so it can be regenerated rather than maintained.`,+ '',+ `**${plan.totals.slots} surfaces that have never been announced**, ${plan.perDay} a day at ${plan.times.join(', ')} UTC, starting ${plan.start}: ${plan.days} days of posting, ${batches} weekly batches. ${plan.totals.gated} of them capture media from a surface that renders live third-party market data, so those frames need owner approval before they can be committed.`,+ '',+ `Lane mix: ${Object.entries(plan.totals.byLane).map(([lane, count]) => `${lane} ${count}`).join(', ')}.`,+ `Pattern mix: ${Object.entries(plan.totals.byPattern).map(([pattern, count]) => `${pattern} ${count}`).join(', ')}.`,+ '',+ 'Slot times, lane rotation and pattern rotation all come from `data/x-content/queue.json`, which is the same file the publisher obeys, so nothing here can promise a slot the scheduler would refuse.',+ '',+ 'Each row becomes a full announcement pack with one command:',+ '',+ '```bash',+ 'npm run announce:kit -- --batch 1 # brief, draft, pack, media recipe, queue item',+ '```',+ '',+ ];+ if (plan.deferred?.length) {+ lines.push('## Deferred', '', '| Surface | Why |', '|---|---|');+ for (const row of plan.deferred) lines.push(`| \`${row.key}\` | ${row.why} |`);+ lines.push('');+ }+ let batch = 0;+ for (const slot of plan.slots) {+ if (slot.batch !== batch) {+ batch = slot.batch;+ const rows = plan.slots.filter((row) => row.batch === batch);+ lines.push('', `## Batch ${batch}: ${rows[0].notBefore.slice(0, 10)} to ${rows[rows.length - 1].notBefore.slice(0, 10)}`, '');+ lines.push('| Slot (UTC) | Surface | Lane | Pattern | Shot | Gate |');+ lines.push('|---|---|---|---|---|---|');+ }+ lines.push(+ `| ${slot.notBefore.slice(0, 16).replace('T', ' ')} | \`${slot.key}\` | ${slot.lane} | ${slot.pattern} | \`${slot.shot}\`${slot.motion ? ' (motion)' : ''} | ${slot.mediaGate || ''} |`,+ );+ }+ return `${lines.join('\n')}\n`;+}++if (flag('--write')) {+ writePlan(root, plan, calendarMarkdown());+ console.error(`wrote ${PLAN_DIR}/plan.json and ${PLAN_DIR}/CALENDAR.md`);+}++if (flag('--json')) {+ console.log(JSON.stringify(plan, null, 2));+ process.exit(0);+}++const only = option('--batch') ? Number(option('--batch')) : null;+const rows = only ? plan.slots.filter((slot) => slot.batch === only) : plan.slots.slice(0, Number(option('--top', 30)));++console.log(+ `${plan.totals.slots} unannounced surfaces, ${plan.perDay}/day at ${plan.times.join(', ')} UTC from ${plan.start}: ${plan.days} days, ${Math.ceil(plan.days / 7)} batches.`,+);+console.log(+ `lanes ${Object.entries(plan.totals.byLane).map(([lane, count]) => `${lane}:${count}`).join(' ')} patterns ${Object.entries(plan.totals.byPattern).map(([pattern, count]) => `${pattern}:${count}`).join(' ')} owner-gated media ${plan.totals.gated} deferred ${plan.deferred?.length || 0}\n`,+);+console.log(`${'when'.padEnd(17)} ${'surface'.padEnd(32)} ${'lane'.padEnd(10)} ${'pattern'.padEnd(11)} gate`);+for (const slot of rows) {+ console.log(+ `${slot.notBefore.slice(0, 16).replace('T', ' ').padEnd(17)} ${slot.key.padEnd(32)} ${slot.lane.padEnd(10)} ${slot.pattern.padEnd(11)} ${slot.mediaGate || ''}`,+ );+}+if (!only) console.log(`\n... ${Math.max(0, plan.totals.slots - rows.length)} more. Full calendar: npm run announce:plan -- --write`);diff --git a/scripts/audit-docs.mjs b/scripts/audit-docs.mjsindex cf10dfd5e..f43854ed7 100644--- a/scripts/audit-docs.mjs+++ b/scripts/audit-docs.mjs@@ -284,6 +284,7 @@ if (!explicitFiles.length) {const UNPUBLISHED_DOCS = new Map([['agora', 'internal: strategy framing, not a reader-facing product doc'],['announce-voice', 'internal: the voice contract announcement packs are written and gated against'],+ ['announcement-factory', 'internal: the marketing machinery that fills the X content queue, like x-content-pipeline'],['announcement-coverage', 'internal: X announcement coverage matrix for marketing planning'],['announcement-coverage-telegram', 'internal: paste-ready holders-channel post drafted from the coverage matrix'],['avatar-cli', 'internal: in-flight, register when the CLI ships'],diff --git a/scripts/capture-doc-media.mjs b/scripts/capture-doc-media.mjsindex 112a28966..029d51d1f 100644--- a/scripts/capture-doc-media.mjs+++ b/scripts/capture-doc-media.mjs@@ -151,7 +151,7 @@ function readSpec() {if (!shot.id) fail('every shot needs an id');if (seen.has(shot.id)) fail(`duplicate shot id: ${shot.id}`);seen.add(shot.id);- if (!shot.url) fail(`shot ${shot.id} has no url`);+ if (!shot.url && !shot.card) fail(`shot ${shot.id} has neither a url nor a card recipe`);if (!shot.alt) fail(`shot ${shot.id} has no alt text (a doc image without alt is a bug)`);if (!VIEWPORTS[shot.viewport || 'desktop']) {fail(`shot ${shot.id} has unknown viewport "${shot.viewport}"`);@@ -235,6 +235,20 @@ async function applyActions(page, actions = []) {/** Everything a page needs to look like a real, settled visit before we shoot. */async function preparePage(page, shot) {+ // A shot with no route is a title card for a surface that has no page: a+ // package, a worker, or a service. It is typeset from that thing's own+ // README and package.json (api/_lib/announce/card.js) and rendered in the+ // same browser, at the same viewport, through the same WebP writer, so it+ // carries the same provenance as a photographed route.+ if (shot.card) {+ const { cardFacts, cardHtml, fetchFontCss } = await import('../api/_lib/announce/card.js');+ const facts = cardFacts(ROOT_DIR, shot.card);+ const fontCss = await fetchFontCss(BASE);+ await page.setContent(cardHtml(facts, { origin: BASE, fontCss }), { waitUntil: 'domcontentloaded', timeout: 30000 });+ await page.evaluate(() => document.fonts?.ready).catch(() => {});+ await page.waitForTimeout(shot.settle ?? 1200);+ return;+ }const url = shot.url.startsWith('http') ? shot.url : BASE + shot.url;await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });await page.waitForLoadState('networkidle', { timeout: 45000 }).catch(() => {@@ -479,7 +493,7 @@ async function captureShot(browser, shot, commit) {src: `${PUBLIC_SRC}/${shot.id}.webp`,alt: shot.alt,caption: shot.caption || null,- route: shot.url,+ route: shot.url || `card:${shot.card?.dir || shot.id}`,viewport: shot.viewport || 'desktop',animated: Boolean(shot.motion),authenticated: Boolean(shot.auth),@@ -506,7 +520,7 @@ async function main() {if (flag('list')) {for (const shot of shots) {console.log(- `${shot.id.padEnd(30)} ${shot.motion ? 'motion' : 'still '} ${(shot.viewport || 'desktop').padEnd(8)} ${shot.url}`,+ `${shot.id.padEnd(30)} ${shot.motion ? 'motion' : 'still '} ${(shot.viewport || 'desktop').padEnd(8)} ${shot.url || `card:${shot.card?.dir || ''}`}`,);}console.log(`\n${shots.length} shot(s)`);diff --git a/scripts/x-content.mjs b/scripts/x-content.mjsindex 54532c3bf..d85068eff 100644--- a/scripts/x-content.mjs+++ b/scripts/x-content.mjs@@ -10,6 +10,8 @@// npm run x:content -- prepare-video <input> --out public/x-media/<id>/clip.mp4 [--captions file.srt] [--item slug]// npm run x:content -- review <slug> [--no-editor] the editorial bar: lint, live fact checks, AI editor// npm run x:content -- review --status review review every item awaiting review+// npm run x:content -- approve <slug> owner gate: release a reviewed item+// npm run x:content -- approve --status review release every item whose review passed//// Env: reads .env.local then .env. DATABASE_URL gives plan/run the shared// publish ledger; X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are@@ -26,7 +28,7 @@ import { runTick } from '../api/_lib/x-content/runner.js';import { dbStore, memoryStore } from '../api/_lib/x-content/state.js';import { VIDEO_LIMITS, mediaType, parseFfmpegProbe } from '../api/_lib/x-content/media.js';import { weightedLength } from '../api/_lib/x-content/quality.js';-import { reviewItem } from '../api/_lib/x-content/review.js';+import { approvalProblems, reviewItem } from '../api/_lib/x-content/review.js';const root = resolve(fileURLToPath(new URL('..', import.meta.url)));@@ -396,6 +398,32 @@ async function review() {if (failed) process.exit(1);}-const commands = { check, plan, run, review, import: importSource, 'prepare-video': prepareVideo };+// The owner's gate, as a command instead of a hand edit. It only ever moves an+// item to `approved`, and only while a passing review record covers the exact+// bytes that are in the queue right now, which is the same rule the publisher+// enforces at send time.+async function approve() {+ const queue = loadQueue(root);+ const status = option('status');+ const id = positional[1];+ const items = queue.items.filter((item) => (id ? item.id === id : status ? item.status === status : false));+ if (!items.length) fail('Usage: approve <slug> | approve --status review');++ let blocked = 0;+ for (const item of items) {+ const problems = approvalProblems({ ...item, status: 'approved' }, root);+ if (problems.length) {+ blocked++;+ console.log(`hold ${item.id}: ${problems.join('; ')}`);+ continue;+ }+ item.status = 'approved';+ console.log(`ok ${item.id}: approved for ${dueAt(item, queue.cadence) ? new Date(dueAt(item, queue.cadence)).toISOString() : item.notBefore}`);+ }+ writeFileSync(resolve(root, QUEUE_PATH), `${JSON.stringify(queue, null, '\t')}\n`);+ if (blocked) process.exit(1);+}++const commands = { check, plan, run, review, approve, import: importSource, 'prepare-video': prepareVideo };if (!commands[command]) fail(`Unknown command ${command}. Commands: ${Object.keys(commands).join(', ')}`);await commands[command]();diff --git a/tests/announce-factory.test.js b/tests/announce-factory.test.jsnew file mode 100644index 000000000..9599e1192--- /dev/null+++ b/tests/announce-factory.test.js@@ -0,0 +1,241 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';++import { buildPlan, laneFor, patternsFor, sequence, slotTimes, slugFor } from '../api/_lib/announce/plan.js';+import { harvestFacts, quotableLines } from '../api/_lib/announce/brief.js';+import { draftFindings, itemFor, parseDraft } from '../api/_lib/announce/draft.js';+import { cardFacts, cardHtml, commandFrom, namesFrom } from '../api/_lib/announce/card.js';+import { renderPack } from '../api/_lib/announce/kit.js';++const CADENCE = { windowMinutes: 90, minimumMinutesApart: 240, dailyCap: 3, quietHoursUtc: ['05:00', '12:00'] };+const QUALITY = { maximumSameLaneInARow: 2, maximumSamePatternInARow: 1 };++const entry = (key, extra = {}) => ({+ key,+ kind: 'page',+ section: 'build',+ title: key,+ description: 'A surface that does a thing.',+ url: key.startsWith('/') ? key : null,+ score: 50,+ signals: { visual: 0 },+ ...extra,+});++describe('plan', () => {+ it('derives slot times from the cadence and never schedules into quiet hours', () => {+ const times = slotTimes(CADENCE);+ expect(times).toEqual(['13:00', '18:00', '23:00']);+ for (const time of times) {+ const minutes = Number(time.slice(0, 2)) * 60;+ expect(minutes).toBeGreaterThanOrEqual(12 * 60);+ }+ });++ it('drops a slot whose jitter window would run into quiet hours', () => {+ expect(slotTimes({ ...CADENCE, quietHoursUtc: ['00:00', '12:00'], dailyCap: 3, minimumMinutesApart: 600 })).toEqual(['13:00']);+ });++ it('keeps ids stable across kinds', () => {+ expect(slugFor('/labor-market')).toBe('labor-market');+ expect(slugFor('@three-ws/walk-sdk')).toBe('walk-sdk');+ expect(slugFor('workers/rigger')).toBe('worker-rigger');+ });++ it('reads the lane off the surface, not off a rotation', () => {+ expect(laneFor(entry('/vaults', { section: 'crypto' }))).toBe('token');+ expect(laneFor(entry('@three-ws/x', { section: 'package' }))).toBe('developer');+ expect(laneFor(entry('/about', { section: 'main' }))).toBe('community');+ });++ it('only offers a motion pattern to a surface with a route', () => {+ expect(patternsFor(entry('/flow', { signals: { visual: 25 } }))).toContain('clip');+ expect(patternsFor(entry('@three-ws/flow', { url: null, signals: { visual: 25 } }))).not.toContain('clip');+ });++ it('never repeats a pattern back to back, and holds the lane run limit', () => {+ const entries = Array.from({ length: 12 }, (unused, index) => entry(`/page-${index}`, { signals: { visual: 25 } }));+ const placed = sequence(entries, QUALITY);+ expect(placed).toHaveLength(12);+ for (let index = 1; index < placed.length; index++) {+ expect(placed[index].pattern).not.toBe(placed[index - 1].pattern);+ }+ });++ it('dates every slot and flags media that needs owner approval', () => {+ const plan = buildPlan([entry('/vaults', { section: 'crypto' }), entry('/forge-max'), entry('/flow')], {+ cadence: CADENCE,+ quality: QUALITY,+ start: '2026-10-01',+ cryptoPaths: new Set(['/vaults']),+ });+ expect(plan.slots.map((slot) => slot.notBefore)).toEqual([+ '2026-10-01T13:00:00Z',+ '2026-10-01T18:00:00Z',+ '2026-10-01T23:00:00Z',+ ]);+ expect(plan.totals.gated).toBe(1);+ expect(plan.slots.find((slot) => slot.key === '/vaults').mediaGate).toBe('owner-approval');+ });+});++describe('brief', () => {+ it('keeps only whole sentences from a rendered page', () => {+ const facts = harvestFacts(+ [+ 'Home',+ 'a truncated gallery caption that stops mid',+ 'The analyzer repairs the mesh and prices the print from its measured volume.',+ ].join('\n'),+ );+ expect(facts).toEqual(['The analyzer repairs the mesh and prices the print from its measured volume.']);+ });++ it('quotes only text that is literally in the file it cites', () => {+ const body = [+ '# Heading',+ '',+ '> A Model Context Protocol server that turns the alerts surface into an agent-drivable control plane.',+ '',+ '- Rules are account-scoped, so a call reads and writes only your own rules and your own history.',+ ].join('\n');+ const lines = quotableLines(body);+ expect(lines.length).toBeGreaterThan(0);+ for (const line of lines) expect(body.includes(line)).toBe(true);+ });++ it('refuses a sentence carrying a banned dash glyph', () => {+ const dashed = `A sentence with an ${String.fromCharCode(8212)} em dash that is long enough to otherwise qualify here.`;+ expect(quotableLines(dashed)).toEqual([]);+ expect(harvestFacts(dashed)).toEqual([]);+ });+});++const BRIEF = {+ id: 'forge-max',+ key: '/forge-max',+ url: 'https://three.ws/forge-max',+ route: '/forge-max',+ lane: 'developer',+ pattern: 'number',+ notBefore: '2026-10-01T13:00:00Z',+ surface: { kind: 'page', section: 'build', title: 'Forge Max', description: 'The maximum-quality lane.' },+ evidenceCandidates: [{ type: 'page', url: 'https://three.ws/forge-max', contains: 'The highest-quality lane: 200k-poly geometry, 4K PBR textures.' }],+ media: { shot: 'forge-max-hero', motion: false },+};++const GOOD = {+ post: 'three.ws/forge-max opens the Forge with its top tier already pinned: 200k-poly geometry, 4K PBR textures, and the engine picked by what you asked for.',+ thread: [],+ alt: 'The three.ws Forge Max page with the High tier pinned in the quality row above the engine list, and the subtitle naming the geometry and texture budget.',+ claims: [{ says: '200k-poly geometry, 4K PBR textures', evidence: [BRIEF.evidenceCandidates[0]] }],+ mentions: {},+ telegram: '',+};++describe('draft', () => {+ it('passes a draft that cites the brief and stays in the band', () => {+ expect(draftFindings(BRIEF, GOOD)).toEqual([]);+ });++ it('rejects evidence the brief never offered', () => {+ const invented = { ...GOOD, claims: [{ says: '200k-poly geometry, 4K PBR textures', evidence: [{ type: 'page', url: 'https://three.ws/forge-max', contains: 'something nobody checked' }] }] };+ expect(draftFindings(BRIEF, invented).join(' ')).toMatch(/not one of the brief/);+ });++ it('rejects a number with no claim behind it', () => {+ const bare = { ...GOOD, claims: [] };+ expect(draftFindings(BRIEF, bare).join(' ')).toMatch(/unverified number/);+ });++ it('rejects hype, a missing link, and alt text that repeats the post', () => {+ const hype = { ...GOOD, post: 'Introducing a seamless way to unlock the power of 3D, it is truly game-changing for every single creator out there.', claims: [] };+ const findings = draftFindings(BRIEF, hype).join(' ');+ expect(findings).toMatch(/banned opening/);+ expect(findings).toMatch(/must link/);+ });++ it('flags a head that repeats something already posted', () => {+ expect(draftFindings(BRIEF, GOOD, { otherHeads: [GOOD.post] }).join(' ')).toMatch(/reads like an existing post/);+ });++ it('parses a model answer and refuses one with no post', () => {+ expect(parseDraft(`noise {"post":"x","alt":"y"} trailing`).post).toBe('x');+ expect(() => parseDraft('{"alt":"y"}')).toThrow(/empty post/);+ });++ it('builds a queue item that points at the reviewed pack bytes', () => {+ const item = itemFor(BRIEF, GOOD, { mediaPath: 'public/announce/img/forge-max-hero.webp' });+ expect(item.status).toBe('draft');+ expect(item.posts[0].textFrom).toBe('docs/announcements/forge-max.post.txt');+ expect(item.posts[0].media[0].alt).toBe(GOOD.alt);+ expect(item.notBefore).toBe(BRIEF.notBefore);+ });+});++describe('card', () => {+ it('reads the command and the tool names a README really documents', () => {+ const readme = [+ '## Install',+ '',+ '```bash',+ 'npx @three-ws/alerts-mcp',+ '```',+ '',+ '## Tools',+ '',+ '| Tool | What it does |',+ '|---|---|',+ '| `list_alert_rules` | lists |',+ '| `create_alert_rule` | creates |',+ '',+ '| Field | Values |',+ '|---|---|',+ '| `kind` | graduation |',+ ].join('\n');+ expect(commandFrom(readme)).toBe('npx @three-ws/alerts-mcp');+ expect(namesFrom(readme)).toEqual(['list_alert_rules', 'create_alert_rule']);+ });++ it('renders a card with no dash glyph and no unescaped markup', () => {+ const html = cardHtml({ title: '@three-ws/x', subtitle: 'A thing <script>alert(1)</script>', command: 'npx x', names: ['a_tool'], footer: 'npmjs.com/package/@three-ws/x' });+ expect(html).not.toMatch(new RegExp('[\\u2014\\u2013]'));+ expect(html).not.toContain('<script>');+ expect(html).toContain('a_tool');+ });++ it('normalizes a dash out of a real package description', () => {+ const facts = cardFacts(process.cwd(), { dir: 'packages/alerts-mcp' });+ expect(facts.title).toBe('@three-ws/alerts-mcp');+ expect(facts.subtitle).not.toMatch(new RegExp('[\\u2014\\u2013]'));+ });+});++describe('pack', () => {+ const slot = { id: 'forge-max', key: '/forge-max', shot: 'forge-max-hero', motion: false, mediaGate: null, notBefore: BRIEF.notBefore, windowMinutes: 90 };++ it('renders the media table the gate parses, and states the alt text', () => {+ const pack = renderPack({ brief: BRIEF, draft: GOOD, slot, ledgerEntry: { title: 'Forge Max', score: 75, signals: { reach: 18 } } });+ expect([...pack.matchAll(/^\| `([a-z0-9-]+)` \|/gm)].map((match) => match[1])).toEqual(['forge-max-hero']);+ expect(pack).toMatch(/Alt text, required on the post/);+ expect(pack).toMatch(/155 weighted characters/);+ expect(pack).not.toMatch(new RegExp('[\\u2014\\u2013]'));+ });++ it('says out loud when a frame needs owner approval', () => {+ const pack = renderPack({ brief: BRIEF, draft: GOOD, slot: { ...slot, mediaGate: 'owner-approval' } });+ expect(pack).toMatch(/owner approval|owner-approval/);+ });+});++describe('the committed packs this factory produced', () => {+ it('keeps the queue text identical to the reviewed pack bytes', () => {+ const queue = JSON.parse(readFileSync('data/x-content/queue.json', 'utf8'));+ for (const item of queue.items) {+ for (const post of item.posts || []) {+ if (!post.textFrom) continue;+ expect(readFileSync(post.textFrom, 'utf8').trim()).toBe(post.text.trim());+ }+ }+ });+});