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(x-content): add post formats and the avatar-embed-moves story, and move the X card renderer into shared script helpers
nirholas9a295c599a49
diff --git a/api/_lib/x-content/editor.js b/api/_lib/x-content/editor.jsindex 45b2dcb32..761484272 100644--- a/api/_lib/x-content/editor.js+++ b/api/_lib/x-content/editor.js@@ -111,7 +111,14 @@ async function imageParts(item, root) {continue;}const buffer = await sharp(resolve(root, row.path), { animated: false }).resize({ width: 1600, withoutEnlargement: true }).jpeg({ quality: 85 }).toBuffer();- parts.push({ type: 'text', text: `${row.role}: ${row.path}. Alt text: ${JSON.stringify(row.alt || '')}` });+ // Say where a head came from, so the editor judges a GIF by more than its+ // first frame and knows key art is drawn, not captured.+ const origin = [+ type.kind === 'gif' ? `a looping GIF${row.derived ? ` cut from ${row.derived.from ?? 0} s to ${row.derived.to ?? '?'} s of the reel` : ''}; this is its first frame` : null,+ row.derived && type.kind !== 'gif' ? `a ${row.derived.as} built from a frame of the reel` : null,+ row.generated ? `AI-generated by ${row.generated.model}${row.generated.source ? ' from a real frame of the product' : ''} (prompt: ${JSON.stringify(row.generated.prompt || '')})` : null,+ ].filter(Boolean);+ parts.push({ type: 'text', text: `${row.role}: ${row.path}${origin.length ? `, ${origin.join('; ')}` : ''}. Alt text: ${JSON.stringify(row.alt || '')}` });parts.push({ type: 'image', data: buffer.toString('base64'), mime: 'image/jpeg' });}return parts;diff --git a/api/_lib/x-content/editorial.js b/api/_lib/x-content/editorial.jsindex 8235e2af3..a4e4803c9 100644--- a/api/_lib/x-content/editorial.js+++ b/api/_lib/x-content/editorial.js@@ -166,6 +166,8 @@ export function claimProblems(item, { articleText = '' } = {}) {return problems;}+export const GIF_MIN_WIDTH = 600;+// Media most likely to embarrass: soft upscales, crops that cut the subject,// alt text that says nothing, and a frame older than the product it shows.export async function mediaQualityProblems(post, root, { maxFrameAgeDays = 21, now = Date.now() } = {}) {@@ -183,7 +185,10 @@ export async function mediaQualityProblems(post, root, { maxFrameAgeDays = 21, nconst meta = await sharp(resolve(root, media.path), { animated: type.kind === 'gif' }).metadata();const width = meta.width;const height = meta.pageHeight || meta.height;- if (width < 1200) problems.push({ rule: 'media', severity: 'blocking', message: `${media.path} is ${width}px wide; X renders it soft below 1200px` });+ // X plays a GIF as a video, at most 1280 wide, so it is held to the+ // width a clip reads at instead of the still-image bar.+ const minWidth = type.kind === 'gif' ? GIF_MIN_WIDTH : 1200;+ if (width < minWidth) problems.push({ rule: 'media', severity: 'blocking', message: `${media.path} is ${width}px wide; X renders it soft below ${minWidth}px` });const ratio = width / height;if (list.length === 1 && (ratio > 2 || ratio < 0.75)) {problems.push({ rule: 'media', severity: 'major', message: `${media.path} is ${ratio.toFixed(2)}:1; X crops a single image outside 3:4 to 2:1 in the timeline` });diff --git a/api/_lib/x-content/formats.js b/api/_lib/x-content/formats.jsnew file mode 100644index 000000000..d56785fe3--- /dev/null+++ b/api/_lib/x-content/formats.js@@ -0,0 +1,148 @@+// What a post looks like in the feed, and the heads that can lead it.+//+// A reader scrolling the timeline sees the head post's media before a word of+// it: a clip, a looping GIF, a still, or nothing. Running the same one every+// slot reads as a bot, however good each post is. The account's own outcomes+// say stills lead (photo heads out-earned video heads on likes and bookmarks),+// and the community asks for the black cards by name, so the queue rotates the+// format the same way it rotates lane and pattern (priority.js).+//+// A proof reel stays the evidence for every post that carries a scenario. What+// changes is where it sits: an item can declare a `head` other than the reel,+// and the reel then moves to a reply, so the thread opens on a card, a GIF cut+// from the reel, or a piece of AI key art, and the clip that proves it is one+// tap down. The head is rebuilt from the reel every time the reel is filmed+// (scripts/lib/x-heads.mjs), and it records the reel it was cut from, so a+// head can never outlive the evidence it was made from.+//+// "head": { "as": "card", "headline": "One idea\nin two lines", "body": "...", "at": 6.5 }+// "head": { "as": "gif", "from": 2, "to": 8, "width": 640 }+// "head": { "as": "art", "headline": "...", "prompt": "what the key art shows", "at": 4 }+//+// This module is pure: it runs in the production image, which renders nothing.++import { existsSync } from 'node:fs';+import { resolve } from 'node:path';+import { describeItem } from './outcomes.js';+import { languageProblems } from './editorial.js';+import { loadProof } from './reel.js';+import { mediaType } from './media.js';++export const FORMATS = ['video', 'gif', 'photo', 'text', 'article'];+export const HEAD_KINDS = ['reel', 'card', 'gif', 'art'];++export const HEAD_LIMITS = {+ headline: 90,+ body: 200,+ prompt: 1200,+ gifSeconds: [1, 10],+ gifWidth: [320, 1080],+};++// The format of an item as the feed shows it.+export function formatOf(item) {+ if (!item) return null;+ if (item.kind === 'article') return 'article';+ const media = describeItem(item).media;+ return media === 'none' ? 'text' : media;+}++// Ledger rows written before the format was recorded take it from the queue+// item they published, so rotation is right from the first tick after deploy.+export function withFormats(published, items) {+ const byId = new Map((items || []).map((item) => [item.id, item]));+ return (published || []).map((row) => (row.format || !byId.has(row.id) ? row : { ...row, format: formatOf(byId.get(row.id)) }));+}++// Approved stock by feed format, for `plan` and the low-variety warning.+export function formatMix(items) {+ const mix = Object.fromEntries(FORMATS.map((format) => [format, 0]));+ for (const item of items) {+ const format = formatOf(item);+ if (format in mix) mix[format]++;+ }+ return mix;+}++// Where the reel goes when the head is something else: the first reply unless+// the item says otherwise.+export function reelPostIndex(item) {+ const head = item?.head;+ if (!head || head.as === 'reel') return 0;+ return Number.isInteger(head.reelIn) ? head.reelIn : 1;+}++const numbersIn = (text) => String(text || '').match(/\d[\d,.]*\d|\d/g) || [];++// Problems with the declared head. A head built from a reel must name the+// bytes of the reel on record, so a re-filmed item cannot keep an old head.+export function headProblems(item, root) {+ const problems = headSpecProblems(item);+ const head = item.head;+ if (problems.length || !head || head.as === 'reel') return problems;+ return [...problems, ...headMediaProblems(item, root)];+}++// The head as written, before anything is built from it.+export function headSpecProblems(item) {+ const head = item.head;+ if (head === undefined) return [];+ const problems = [];+ if (!head || !HEAD_KINDS.includes(head.as)) return [`head.as must be one of ${HEAD_KINDS.join(', ')}`];+ if (item.kind !== 'post') return ['a head is only for post items; an article leads with its cover'];+ if (head.as === 'reel') return [];+ if (!item.scenario) problems.push(`a ${head.as} head is built from the item's proof reel, and the item carries no scenario`);++ const reelIndex = reelPostIndex(item);+ if (!(reelIndex >= 1 && reelIndex < (item.posts?.length || 0))) {+ problems.push(`head.as ${head.as} moves the reel to post ${reelIndex + 1}, so the item needs a reply there to carry it`);+ }+ if (['card', 'art'].includes(head.as)) {+ const headline = String(head.headline || '').trim();+ if (!headline) problems.push(`a ${head.as} head needs a headline`);+ if (headline.length > HEAD_LIMITS.headline) problems.push(`head.headline is ${headline.length} characters; keep it under ${HEAD_LIMITS.headline} so it reads in a phone timeline`);+ if (head.body && String(head.body).length > HEAD_LIMITS.body) problems.push(`head.body is ${String(head.body).length} characters; keep it under ${HEAD_LIMITS.body}`);+ // Card type is copy the reader sees, so it meets the same bar as the post,+ // and a number on it must be one the post states (and the review checks).+ for (const text of [head.headline, head.body].filter(Boolean)) {+ for (const finding of languageProblems(text)) if (finding.severity === 'blocking') problems.push(`head ${finding.rule}: ${finding.message}`);+ }+ const copy = (item.posts || []).map((post) => post.text).join('\n');+ for (const number of [...numbersIn(head.headline), ...numbersIn(head.body)]) {+ if (!copy.includes(number)) problems.push(`head states ${number}, which no post in the item says; the review only checks numbers the posts state`);+ }+ }+ if (head.as === 'art' && !String(head.prompt || '').trim()) problems.push('an art head needs a prompt that says what the key art shows');+ if (head.as === 'art' && String(head.prompt || '').length > HEAD_LIMITS.prompt) problems.push(`head.prompt is over ${HEAD_LIMITS.prompt} characters`);+ if (head.as === 'gif') {+ const [minSeconds, maxSeconds] = HEAD_LIMITS.gifSeconds;+ if (head.from !== undefined || head.to !== undefined) {+ const span = Number(head.to) - Number(head.from);+ if (!(Number(head.from) >= 0 && span >= minSeconds && span <= maxSeconds)) problems.push(`head.from and head.to must mark ${minSeconds} to ${maxSeconds} seconds of the reel`);+ }+ if (head.width !== undefined && !(head.width >= HEAD_LIMITS.gifWidth[0] && head.width <= HEAD_LIMITS.gifWidth[1])) {+ problems.push(`head.width must be ${HEAD_LIMITS.gifWidth[0]} to ${HEAD_LIMITS.gifWidth[1]} pixels`);+ }+ }++ return problems;+}++// The head on the post has to be one built for this head, from this reel.+function headMediaProblems(item, root) {+ const head = item.head;+ const problems = [];+ const media = item.posts?.[0]?.media?.[0];+ const expected = head.as === 'gif' ? 'gif' : 'image';+ if (!media?.derived) problems.push(`the head post does not carry a ${head.as} built from the reel; run \`npm run x:content -- remix ${item.id}\``);+ else {+ if (mediaType(media.path)?.kind !== expected) problems.push(`the head post carries ${media.path}, not a ${head.as}`);+ if (media.derived.as !== head.as) problems.push(`the head post carries a ${media.derived.as}, but head.as is ${head.as}; run remix again`);+ if (!existsSync(resolve(root, media.path))) problems.push(`${media.path} is missing`);+ const proof = item.scenario ? loadProof(root, item.id) : null;+ if (proof?.video?.sha256 && media.derived.reel !== proof.video.sha256) {+ problems.push(`the head was cut from an older reel; run \`npm run x:content -- remix ${item.id}\` so it shows what the latest run filmed`);+ }+ }+ return problems;+}diff --git a/api/_lib/x-content/media.js b/api/_lib/x-content/media.jsindex a6d3ecb31..91c31be96 100644--- a/api/_lib/x-content/media.js+++ b/api/_lib/x-content/media.js@@ -39,6 +39,45 @@ export const VIDEO_LIMITS = {export const MAX_ALT_TEXT = 1000;+// X's animated GIF limits, beyond the 15 MB in MEDIA_TYPES.+export const GIF_LIMITS = { maxWidth: 1280, maxHeight: 1080, maxFrames: 350, maxPixels: 300_000_000 };++// Width, height and frame count straight from the GIF block structure, so the+// limits are checked without decoding a pixel (and without sharp, which this+// synchronous check cannot await). Returns null for a file that is not a GIF.+export function gifInfo(buffer) {+ if (buffer.length < 13 || buffer.toString('latin1', 0, 3) !== 'GIF') return null;+ const width = buffer.readUInt16LE(6);+ const height = buffer.readUInt16LE(8);+ const flags = buffer[10];+ let offset = 13 + (flags & 0x80 ? 3 * 2 ** ((flags & 0x07) + 1) : 0);+ let frames = 0;+ const skipSubBlocks = () => {+ while (offset < buffer.length && buffer[offset] !== 0) offset += buffer[offset] + 1;+ offset++;+ };+ while (offset < buffer.length) {+ const block = buffer[offset];+ if (block === 0x3b) break;+ if (block === 0x21) {+ offset += 2;+ skipSubBlocks();+ } else if (block === 0x2c) {+ frames++;+ const local = buffer[offset + 9];+ offset += 10 + (local & 0x80 ? 3 * 2 ** ((local & 0x07) + 1) : 0);+ offset++;+ skipSubBlocks();+ } else {+ return { width, height, frames, truncated: true };+ }+ }+ return { width, height, frames };+}++// Media an image model drew is labelled as such where the reader meets it.+export const GENERATED_LABEL = /\bAI[- ]generated\b/i;+export const CATEGORY = { image: 'tweet_image', gif: 'tweet_gif', video: 'tweet_video' };export function mediaType(path) {@@ -65,6 +104,19 @@ export function mediaProblems(media, root) {const alt = String(media.alt || '').trim();if (!alt) problems.push(`${path}: needs alt text`);if (alt.length > MAX_ALT_TEXT) problems.push(`${path}: alt text is ${alt.length} characters; X allows ${MAX_ALT_TEXT}`);+ if (media.generated && !GENERATED_LABEL.test(alt)) problems.push(`${path}: an image model drew this, so its alt text must say "AI-generated"`);+ if (media.generated && !media.generated.model) problems.push(`${path}: generated media must record the model that drew it`);+ if (type.kind === 'gif') {+ const gif = gifInfo(readFileSync(absolute));+ const G = GIF_LIMITS;+ if (!gif) problems.push(`${path}: is not a GIF file`);+ else {+ if (gif.truncated) problems.push(`${path}: the GIF is malformed`);+ if (gif.width > G.maxWidth || gif.height > G.maxHeight) problems.push(`${path}: ${gif.width}x${gif.height} is over X's ${G.maxWidth}x${G.maxHeight} GIF limit`);+ if (gif.frames > G.maxFrames) problems.push(`${path}: ${gif.frames} frames is over X's ${G.maxFrames} frame GIF limit`);+ if (gif.width * gif.height * gif.frames > G.maxPixels) problems.push(`${path}: ${gif.width}x${gif.height} over ${gif.frames} frames is over X's ${G.maxPixels / 1e6} million pixel GIF limit`);+ }+ }return problems;}diff --git a/api/_lib/x-content/priority.js b/api/_lib/x-content/priority.jsindex 71c0430f1..3a5268a6a 100644--- a/api/_lib/x-content/priority.js+++ b/api/_lib/x-content/priority.js@@ -30,6 +30,10 @@// review the AI editor's average score above or below 4// variety a penalty when the post would repeat the last lane or pattern// more times in a row than the queue allows+// format a penalty when the post would repeat the last feed format+// (video, GIF, still, text, article; formats.js) more times in a+// row than `maximumSameFormatInARow` allows, so a run of clips is+// broken by a card or a GIF whenever the stock holds one//// Small samples are shrunk toward no effect: the archive measured "names// $THREE" at 13.3x over only four posts, and one lucky post should not decide@@ -40,6 +44,7 @@ import { resolve } from 'node:path';import { FORMAT_DIMENSIONS, LENGTH_BUCKETS, TOPICS } from '../../../scripts/x-archive-lib.mjs';import { weightedLength } from './quality.js';import { LEARNED_MIN_SAMPLE, learnedScore } from './outcomes.js';+import { formatOf } from './formats.js';const DAY = 24 * 60 * 60_000;// Prior strength for shrinkage: a signal measured on n posts keeps n / (n + K)@@ -206,6 +211,8 @@ export function scoreItem(item, { lifts, published = [], quality = {}, review =if (trailingRun(sorted, 'lane', item.lane) >= maxLane || trailingRun(sorted, 'pattern', item.pattern) >= maxPattern) {parts.variety = -25;}+ const maxFormat = Number(quality.maximumSameFormatInARow ?? Infinity);+ if (trailingRun(sorted, 'format', formatOf(item)) >= maxFormat) parts.format = -25;const score = Math.round(Object.values(parts).reduce((sum, value) => sum + value, 0) * 10) / 10;return {diff --git a/api/_lib/x-content/publisher.js b/api/_lib/x-content/publisher.jsindex 553b64076..b1242cdd5 100644--- a/api/_lib/x-content/publisher.js+++ b/api/_lib/x-content/publisher.js@@ -13,6 +13,7 @@import { loadArticle } from './queue.js';import { readMedia } from './media.js';import { attachArticleMedia } from './articles.js';+import { formatOf } from './formats.js';// X expires an uploaded media id after 24 hours; re-upload past this age.const MEDIA_ID_TTL_MS = 23 * 60 * 60 * 1000;@@ -128,6 +129,7 @@ export async function publishItem({ item, client, root, state, store, account =kind: item.kind,lane: item.lane,pattern: item.pattern,+ format: formatOf(item),publishedAt: new Date(now).toISOString(),text: item.kind === 'article' ? item.article.title : item.posts[0].text,postIds: progress.postIds,diff --git a/api/_lib/x-content/queue.js b/api/_lib/x-content/queue.jsindex 81db52921..8e7ed6347 100644--- a/api/_lib/x-content/queue.js+++ b/api/_lib/x-content/queue.js@@ -13,6 +13,7 @@ import { MARKDOWN_ENTITY_BUDGET, markdownToContentState } from './articles.js';import { claimProblems, languageProblems } from './editorial.js';import { approvalProblems } from './review.js';import { proofProblems, scenarioProblems } from './reel.js';+import { headProblems } from './formats.js';export const QUEUE_PATH = 'data/x-content/queue.json';export const STATUSES = ['draft', 'review', 'approved', 'paused', 'posted'];@@ -219,6 +220,8 @@ export function validateItem(item, root, { quality = qualityAt(root), now = Dateif (!(item.probes || []).some((probe) => probe.type === 'scenario')) problems.push('scenario: declare { "type": "scenario" } in probes so every review runs it again');if (['review', 'approved'].includes(item.status)) problems.push(...proofProblems(item, root, now).map((problem) => `proof: ${problem}`));}+ // A card, GIF, or key art in front of the reel has to be built from it.+ problems.push(...headProblems(item, root).map((problem) => `head: ${problem}`));// Approval is only real while a passing review covers these exact bytes.if (item.status === 'approved') problems.push(...approvalProblems(item, root, now).map((problem) => `review: ${problem}`));diff --git a/api/_lib/x-content/reel.js b/api/_lib/x-content/reel.jsindex 8633083cb..d41ee8fb4 100644--- a/api/_lib/x-content/reel.js+++ b/api/_lib/x-content/reel.js@@ -210,7 +210,7 @@ export function proofProblems(item, root, now = Date.now()) {const age = (now - Date.parse(proof.ranAt)) / 86_400_000;if (age > PROOF_MAX_AGE_DAYS) problems.push(`the reel was filmed ${Math.floor(age)} days ago; the product moves, so film it again`);const reel = (item.posts || []).flatMap((post) => post.media || []).find((media) => media.path === proof.video?.path);- if (!reel) problems.push(`the head post does not carry the reel ${proof.video?.path || ''}`);+ if (!reel) problems.push(`no post carries the reel ${proof.video?.path || ''}`);else {const file = resolve(root, reel.path);if (existsSync(file) && sha256File(file) !== proof.video.sha256) problems.push(`${reel.path} is not the file the proof filmed`);diff --git a/api/_lib/x-content/runner.js b/api/_lib/x-content/runner.jsindex 7ac7588e7..825831e8f 100644--- a/api/_lib/x-content/runner.js+++ b/api/_lib/x-content/runner.js@@ -233,6 +233,9 @@ export async function runTick({const reviews = new Map(publishable.map((item) => [item.id, loadReview(root, item.id)]));const context = {items: publishable,+ // Every item the ledger may name, publishable or not, so a ledger row+ // from before formats were recorded still says what it looked like.+ allItems: queue.items || [],state,now,cadence: queue.cadence,diff --git a/api/_lib/x-content/schedule.js b/api/_lib/x-content/schedule.jsindex 56c201cef..1f368c549 100644--- a/api/_lib/x-content/schedule.js+++ b/api/_lib/x-content/schedule.js@@ -13,6 +13,7 @@import { createHash, createHmac } from 'node:crypto';import { rankItems } from './priority.js';+import { withFormats } from './formats.js';const MINUTE = 60_000;const DAY = 24 * 60 * MINUTE;@@ -178,6 +179,7 @@ export const tierOf = (item) => (TIERS.includes(Number(item.tier)) ? Number(item// tick already tried and could not send, so the slot falls to the next best.export function pickDue({items,+ allItems = items,state,now = Date.now(),cadence: rawCadence = {},@@ -191,7 +193,7 @@ export function pickDue({quota = false,}) {const cadence = { ...DEFAULT_CADENCE, ...rawCadence };- const published = [...(state?.published || [])].sort((a, b) => a.publishedAt.localeCompare(b.publishedAt));+ const published = withFormats(state?.published, allItems).sort((a, b) => a.publishedAt.localeCompare(b.publishedAt));const publishedIds = new Set(published.map((row) => row.id));const inflight = state?.inflight || {};diff --git a/data/x-content/proofs/avatar-embed-moves.json b/data/x-content/proofs/avatar-embed-moves.jsonnew file mode 100644index 000000000..180b92d8d--- /dev/null+++ b/data/x-content/proofs/avatar-embed-moves.json@@ -0,0 +1,127 @@+{+ "id": "avatar-embed-moves",+ "scenarioHash": "09b9afa48ef1d91d4d06b47b454d1c2373b8e062fe079b614bf7ac115aa0110b",+ "ranAt": "2026-10-10T05:43:04.520Z",+ "target": {+ "commit": "5af439bc0",+ "revision": "three-ws-api-00487-7mt"+ },+ "passed": false,+ "steps": [+ {+ "index": 1,+ "kind": "goto",+ "target": "https://three.ws/embed/avatar?model=/avatars/michelle.glb&bg=dark",+ "detail": "loaded https://three.ws/embed/avatar?model=/avatars/michelle.glb&bg=dark",+ "ok": true,+ "ms": 20925,+ "frames": 0+ },+ {+ "index": 2,+ "kind": "expect",+ "target": "Animations",+ "detail": "appeared after 0.7 s",+ "ok": true,+ "ms": 703,+ "frames": 0+ },+ {+ "index": 3,+ "kind": "hold",+ "target": "1600",+ "detail": "1600 ms",+ "ok": true,+ "ms": 13808,+ "frames": 0+ },+ {+ "index": 4,+ "kind": "press",+ "target": "1",+ "detail": "pressed 1",+ "ok": true,+ "ms": 1486,+ "frames": 0+ },+ {+ "index": 5,+ "kind": "hold",+ "target": "1400",+ "detail": "1400 ms",+ "ok": true,+ "ms": 11227,+ "frames": 0+ },+ {+ "index": 6,+ "kind": "press",+ "target": "2",+ "detail": "pressed 2",+ "ok": true,+ "ms": 1795,+ "frames": 0+ },+ {+ "index": 7,+ "kind": "hold",+ "target": "1000",+ "detail": "1000 ms",+ "ok": true,+ "ms": 8578,+ "frames": 0+ },+ {+ "index": 8,+ "kind": "press",+ "target": "3",+ "detail": "pressed 3",+ "ok": true,+ "ms": 1581,+ "frames": 0+ },+ {+ "index": 9,+ "kind": "hold",+ "target": "1400",+ "detail": "1400 ms",+ "ok": true,+ "ms": 11252,+ "frames": 0+ },+ {+ "index": 10,+ "kind": "click",+ "target": "Animations",+ "detail": "clicked",+ "ok": true,+ "ms": 6143,+ "frames": 0+ },+ {+ "index": 11,+ "kind": "hold",+ "target": "600",+ "detail": "600 ms",+ "ok": true,+ "ms": 4854,+ "frames": 0+ },+ {+ "index": 12,+ "kind": "click",+ "target": "Boxer Dance",+ "ok": false,+ "detail": "no request to /animations/clips/av-boxer-dance.json answered within 60 s",+ "ms": 64098,+ "frames": 0+ }+ ],+ "facts": {},+ "saw": [+ "Animations"+ ],+ "responses": [],+ "cuts": [],+ "video": null+}diff --git a/data/x-content/queue.json b/data/x-content/queue.jsonindex b04ff4a1b..ed76c55c4 100644--- a/data/x-content/queue.json+++ b/data/x-content/queue.json@@ -32,6 +32,7 @@"queueSimilarityLimit": 0.34,"maximumSameLaneInARow": 2,"maximumSamePatternInARow": 1,+ "maximumSameFormatInARow": 1,"glossary": ["Hunyuan","Tripo",@@ -4620,7 +4621,7 @@},{"id": "docs-world",- "status": "review",+ "status": "draft","kind": "post","tier": 2,"lane": "community",@@ -4740,6 +4741,23 @@"posts": [{"text": "This is the documentation, rebuilt as a place. More than 300 pages, and you read them by walking up to them.\n\nEvery docs section is a pavilion on a ring, 16 in all. Search a page from wherever you stand and a trail of arrows leads to the pavilion that holds it. Enter reads it there and then: the real page opens inside the scene, as text you can select and zoom.\n\nthree.ws/docs/world",+ "media": [+ {+ "path": "public/x-media/docs-world/loop.gif",+ "alt": "Looping clip filmed live on three.ws/docs/world. On screen: The three.ws docs, built as a place / Every docs section is a pavilion on a ring.",+ "derived": {+ "as": "gif",+ "reel": "d59be7703de098a2dbaa92292e8b6577ca1103b4466c688bdd85d04c77d90834",+ "from": 1.2,+ "to": 7.2,+ "width": 800,+ "fps": 15+ }+ }+ ]+ },+ {+ "text": "Same files as the classic docs, so the two can never drift apart. Walk with the arrow keys or the touch joystick, and pass any rigged GLB with ?avatar= to make it your body in the world.","media": [{"path": "public/x-media/docs-world/reel.mp4",@@ -4754,9 +4772,6 @@"reel": true}]- },- {- "text": "Same files as the classic docs, so the two can never drift apart. Walk with the arrow keys or the touch joystick, and pass any rigged GLB with ?avatar= to make it your body in the world."}],"claims": [@@ -4899,7 +4914,10 @@]}],- "mentions": {}+ "mentions": {},+ "head": {+ "as": "gif"+ }},{"id": "drive-copilot",@@ -15042,7 +15060,7 @@},{"id": "photo-to-3d",- "status": "approved",+ "status": "draft","kind": "post","tier": 2,"lane": "community",@@ -15117,6 +15135,20 @@"posts": [{"text": "One photo of a garden gnome went in, and a textured 3D model came out, viewable in the browser with the garden cut away: three.ws/image-to-3d\n\nIt is free, with no sign-up and no API key. The free engines run on NVIDIA-hosted generation and our own self-hosted GPU workers, so the machine you upload from needs no GPU of its own. When the model lands, orbit it and download the GLB.",+ "media": [+ {+ "path": "public/x-media/photo-to-3d/card.png",+ "alt": "three.ws card on a black background with the headline \"One photo in. A 3D model out.\" Free, with no sign-up and no API key. Orbit it, then download the GLB. Beside it, a frame of three.ws/image-to-3d from the reel filmed live on the product.",+ "derived": {+ "as": "card",+ "reel": "66aa5624fa5bce982bf99c37c65483f99841b51c9a18ded1e4f49b0261efe0c2",+ "at": 14.5+ }+ }+ ]+ },+ {+ "text": "One photo leaves the back of the object to the model to guess. Photo mode takes up to 6 views of the same object and reconstructs them together, so a second or third angle replaces the guess with what the camera saw.\n\nThe reel uses a single public domain photo, and the wait for the model is cut and labelled on screen.","media": [{"path": "public/x-media/photo-to-3d/reel.mp4",@@ -15132,9 +15164,6 @@}]},- {- "text": "One photo leaves the back of the object to the model to guess. Photo mode takes up to 6 views of the same object and reconstructs them together, so a second or third angle replaces the guess with what the camera saw.\n\nThe reel uses a single public domain photo, and the wait for the model is cut and labelled on screen."- },{"text": "The result is a GLB you keep. From the same screen you can view it in AR in your own room, split it into selectable parts, or rebuild it to a polygon budget and export an engine-ready GLB and FBX.\n\nAgents get it too: the same pipeline is available to agents over MCP, so a bot can turn a photo into a model without opening the page."}@@ -15276,7 +15305,12 @@}],"mentions": {},- "approvedBy": "policy"+ "approvedBy": "policy",+ "head": {+ "as": "card",+ "headline": "One photo in.\nA 3D model out.",+ "body": "Free, with no sign-up and no API key. Orbit it, then download the GLB."+ }}]}diff --git a/data/x-content/stories/avatar-embed-moves.json b/data/x-content/stories/avatar-embed-moves.jsonnew file mode 100644index 000000000..2e72acd65--- /dev/null+++ b/data/x-content/stories/avatar-embed-moves.json@@ -0,0 +1,52 @@+{+ "id": "avatar-embed-moves",+ "status": "draft",+ "kind": "post",+ "tier": 2,+ "lane": "community",+ "pattern": "clip",+ "notBefore": "2026-10-11T00:00:00Z",+ "covers": ["/embed/avatar"],+ "scenario": {+ "format": "square",+ "steps": [+ { "goto": "https://three.ws/embed/avatar?model=/avatars/michelle.glb&bg=dark", "settle": 9000 },+ { "expect": "Animations", "within": 45000 },+ { "hold": 1600, "caption": "A three.ws avatar, live in an embed" },+ { "press": "1", "caption": "The number keys change her face" },+ { "hold": 1400 },+ { "press": "2" },+ { "hold": 1000 },+ { "press": "3" },+ { "hold": 1400 },+ { "click": "Animations", "caption": "One click plays a move" },+ { "hold": 600 },+ { "click": "Boxer Dance", "caption": "Retargeted onto her rig in the browser" },+ { "hold": 3200 },+ { "click": "Superhero Jump" },+ { "hold": 2400 },+ { "click": "Back Flip" },+ { "hold": 3000 }+ ]+ },+ "probes": [{ "type": "scenario" }],+ "posts": [+ {+ "text": "This three.ws avatar takes requests. The number keys change her face, from a smile to a wink to surprise, and one click plays a move: a boxer dance, a superhero jump, a back flip.\n\nEvery clip is retargeted onto her own skeleton live in the browser, so the same library plays on any humanoid avatar you bring."+ },+ {+ "text": "The embed is a real control surface for your site. Your page can make the avatar speak with lip sync, set any of the 52 ARKit face shapes, turn her head toward something, or hand her the webcam for live mocap.\n\nDrop one into your own page: three.ws/docs/embedding"+ }+ ],+ "claims": [+ { "says": "from a smile to a wink to surprise", "evidence": [{ "type": "file", "path": "src/avatar-embed.js", "contains": "label: 'wink'" }] },+ { "says": "a boxer dance, a superhero jump, a back flip", "evidence": [{ "type": "file", "path": "public/animations/manifest.json", "matches": "\"label\":\\s*\"Boxer Dance\"" }, { "type": "file", "path": "public/animations/manifest.json", "matches": "\"label\":\\s*\"Back Flip\"" }] },+ { "says": "Every clip is retargeted onto her own skeleton live in the browser", "evidence": [{ "type": "file", "path": "src/animation-retarget.js", "contains": "Runtime animation retargeting" }] },+ { "says": "the same library plays on any humanoid avatar you bring", "evidence": [{ "type": "file", "path": "src/glb-canonicalize.js", "contains": "letting the\n// pre-baked Mixamo animation library play on any rig variant" }] },+ { "says": "speak with lip sync", "evidence": [{ "type": "file", "path": "src/avatar-embed.js", "contains": "drive audio-based lipsync onto the avatar's mouth morphs" }] },+ { "says": "set any of the 52 ARKit face shapes", "evidence": [{ "type": "file", "path": "src/avatar-embed.js", "contains": "Apply weight (0..1) to any ARKit-52 canonical morph by name" }] },+ { "says": "turn her head toward something", "evidence": [{ "type": "file", "path": "src/avatar-embed.js", "contains": "v1.avatar.lookAt" }] },+ { "says": "hand her the webcam for live mocap", "evidence": [{ "type": "file", "path": "src/avatar-embed.js", "contains": "Toggle webcam mocap" }] }+ ],+ "mentions": {}+}diff --git a/public/x-media/docs-world/loop.gif b/public/x-media/docs-world/loop.gifnew file mode 100644index 000000000..412cf08c8Binary files /dev/null and b/public/x-media/docs-world/loop.gif differdiff --git a/public/x-media/photo-to-3d/card.png b/public/x-media/photo-to-3d/card.pngnew file mode 100644index 000000000..68ee1c796Binary files /dev/null and b/public/x-media/photo-to-3d/card.png differdiff --git a/scripts/lib/x-card.mjs b/scripts/lib/x-card.mjsnew file mode 100644index 000000000..8471c652f--- /dev/null+++ b/scripts/lib/x-card.mjs@@ -0,0 +1,179 @@+// The black three.ws card: one 1600x900 frame in the visual system the+// community keeps asking for. Black ground, soft blue and violet glow, the+// three.ws lockup, a Space Grotesk headline, and the product shown inside a+// frame instead of as a raw screenshot.+//+// Used by scripts/make-x-post-card.mjs (a hand-written spec) and by the X+// content heads (scripts/lib/x-heads.mjs), which build a card around a frame of+// a proof reel or around AI key art.+//+// Frames:+// browser the shot in a tilted browser window (a landscape page capture)+// phone the shot in a phone (a mobile capture)+// panel the shot in a rounded panel, any aspect (a square reel frame)+// art the shot full-bleed behind the type, faded into the black so the+// headline sits on it; `inset` adds a real product frame in a corner+// and `credit` labels the art for what it is++import sharp from 'sharp';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++export const CARD_WIDTH = 1600;+export const CARD_HEIGHT = 900;++const OVERLAYS = ['#tws-corner-stack', '.twx-i18n-fab', '.walk-companion', '.walk-c2w-fx', '.walk-trail-layer', '#market-sidebar-toggle'];+const GL_ARGS = ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'];++const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);++export function brandAssets(root) {+ const fontFaces = [+ ['Space Grotesk', '300 700', 'space-grotesk-latin.woff2'],+ ['Inter', '300 800', 'inter-latin.woff2'],+ ]+ .map(([family, weight, file]) => `@font-face{font-family:'${family}';font-style:normal;font-weight:${weight};src:url(data:font/woff2;base64,${readFileSync(join(root, 'public/fonts', file)).toString('base64')}) format('woff2');}`)+ .join('\n');+ const markUri = `data:image/png;base64,${readFileSync(join(root, 'public/pwa-512x512.png')).toString('base64')}`;+ return { fontFaces, markUri };+}++// A capture whose every channel averages under this is a blank page.+export async function isBlank(buffer) {+ const means = (await sharp(buffer).stats()).channels.slice(0, 3).map((channel) => channel.mean);+ return means.every((mean) => mean < 6);+}++// Image bytes as a data URI the card can embed. A 2x capture of a WebGL page is+// tens of megabytes as PNG, enough to make the card's own screenshot fail, and+// no frame on the card is wider than 1600, so that is the ceiling.+export async function imageUri(buffer, { width = CARD_WIDTH, quality = 90 } = {}) {+ const fitted = await sharp(buffer).resize({ width, withoutEnlargement: true }).jpeg({ quality }).toBuffer();+ return `data:image/jpeg;base64,${fitted.toString('base64')}`;+}++// A live page captured the way the card frames it.+export async function capturePage(url, { frame = 'browser', hide = [], scrollBy = 0, settleMs = 9000 } = {}) {+ const { chromium } = await import('playwright');+ const browser = await chromium.launch({ args: GL_ARGS });+ try {+ const page = await browser.newPage({ viewport: frame === 'phone' ? { width: 412, height: 892 } : { width: 1280, height: 800 }, deviceScaleFactor: 2, colorScheme: 'dark' });+ try {+ await page.goto(url, { waitUntil: 'networkidle', timeout: 90_000 });+ } catch {+ // An open socket never idles; the settle below covers it.+ }+ await page.addStyleTag({ content: `${[...OVERLAYS, ...hide].join(',')}{display:none!important}` });+ if (scrollBy) await page.evaluate((y) => window.scrollBy({ top: y, behavior: 'instant' }), scrollBy);+ await page.waitForTimeout(settleMs);+ return await page.screenshot({ type: 'png' });+ } finally {+ await browser.close();+ }+}++function codeHtml(lines) {+ return (lines || [])+ .map((line) => `<div>${esc(line).replace(/(<\/?)([a-z0-9-]+)/gi, '$1<b>$2</b>').replace(/([a-z-]+)=("|")/gi, '<i>$1</i>=$2')}</div>`)+ .join('');+}++function frameHtml(spec, shotUri) {+ if (spec.frame === 'phone') return `<div class="phone"><img src="${shotUri}" alt=""></div>`;+ if (spec.frame === 'panel') return `<div class="panel"><img src="${shotUri}" alt=""></div>`;+ if (spec.frame === 'art') {+ return [+ `<div class="art" style="background-image:url('${shotUri}')"></div><div class="art-fade"></div>`,+ spec.insetUri ? `<figure class="inset"><img src="${spec.insetUri}" alt=""><figcaption>${esc(spec.insetLabel || 'Filmed live on three.ws')}</figcaption></figure>` : '',+ spec.credit ? `<div class="credit">${esc(spec.credit)}</div>` : '',+ ].join('');+ }+ return `<div class="browser"><div class="bar"><u></u><u></u><u></u><span>${esc(spec.label || 'three.ws')}</span></div><img src="${shotUri}" alt=""></div>`;+}++// The card as HTML. `shotUri` is a data URI (imageUri) or null for type alone.+export function cardHtml(spec, shotUri, brand) {+ const W = CARD_WIDTH;+ const H = CARD_HEIGHT;+ const art = spec.frame === 'art';+ const copyWidth = spec.frame === 'phone' ? 760 : spec.frame === 'panel' ? 700 : art ? 820 : 650;+ const copyTop = art ? 'auto' : `${spec.code ? 196 : 232}px`;+ const headline = esc(spec.headline || '').replace(/\n/g, '<br>');+ const code = codeHtml(spec.code);+ return `<!doctype html><meta charset="utf-8"><style>+${brand.fontFaces}+*{margin:0;padding:0;box-sizing:border-box}+body{width:${W}px;height:${H}px;background:#000;color:#fff;overflow:hidden;position:relative;font-family:'Inter',sans-serif;-webkit-font-smoothing:antialiased}+.glow{position:absolute;inset:0;background:+ radial-gradient(34% 40% at 22% 28%, rgba(78,120,255,.22), transparent 70%),+ radial-gradient(30% 36% at 80% 24%, rgba(56,180,255,.14), transparent 72%),+ radial-gradient(34% 40% at 30% 84%, rgba(140,84,255,.16), transparent 70%),+ radial-gradient(30% 36% at 84% 80%, rgba(104,96,255,.14), transparent 72%)}+.beam{position:absolute;left:4%;right:4%;top:40%;height:220px;transform:rotate(-5deg);filter:blur(60px);+ background:linear-gradient(90deg, transparent, rgba(150,200,255,.09) 22%, rgba(190,220,255,.14) 50%, rgba(150,200,255,.09) 78%, transparent)}+.lockup{position:absolute;left:72px;top:60px;display:flex;align-items:center;gap:16px;z-index:3}+.lockup img{width:64px;height:64px;border-radius:17px}+.lockup span{font-family:'Space Grotesk',sans-serif;font-weight:600;font-size:42px;letter-spacing:-.045em}+.copy{position:absolute;left:72px;top:${copyTop};${art ? 'bottom:96px;' : ''}width:${copyWidth}px;z-index:3}+h1{font-family:'Space Grotesk',sans-serif;font-weight:600;letter-spacing:-.04em;line-height:1.02;font-size:${spec.headlineSize || (art ? 84 : 74)}px;${art ? 'text-shadow:0 4px 40px rgba(0,0,0,.85);' : ''}}+.copy p{margin-top:26px;font-size:27px;line-height:1.45;color:${art ? '#c4d0e8' : '#a7b6d3'};${art ? 'text-shadow:0 2px 24px rgba(0,0,0,.9);' : ''}}+.code{margin-top:34px;padding:22px 24px;border-radius:16px;background:rgba(12,16,32,.78);box-shadow:0 0 0 1px rgba(255,255,255,.10) inset;+ font:500 16px/1.75 ui-monospace,'SF Mono',Menlo,Consolas,monospace;color:#c9d6f2;white-space:nowrap;overflow:hidden}+.code b{color:#7fb2ff;font-weight:600}.code i{color:#b79bff;font-style:normal}+.foot{position:absolute;left:72px;bottom:58px;font-size:21px;color:#8fa3c6;letter-spacing:.01em;z-index:3}+.browser{position:absolute;left:760px;top:150px;width:780px;border-radius:18px;overflow:hidden;+ background:#12131f;box-shadow:0 50px 100px rgba(0,0,0,.9), 0 12px 30px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.12) inset;+ transform:perspective(2200px) rotateY(-7deg) rotateX(2deg)}+.bar{height:44px;display:flex;align-items:center;gap:8px;padding:0 16px;background:linear-gradient(#262a40,#1a1d2e)}+.bar u{width:11px;height:11px;border-radius:50%;background:#4a5070;display:block}+.bar span{margin-left:14px;flex:1;height:24px;border-radius:12px;background:rgba(255,255,255,.07);font-size:13px;line-height:24px;padding:0 12px;color:#93a2c4}+.browser img{display:block;width:100%}+.phone{position:absolute;left:1180px;top:470px;width:360px;transform:translate(-50%,-50%) perspective(1800px) rotateY(-8deg) rotateX(3deg);+ border-radius:34px;padding:8px;background:linear-gradient(135deg,#4a5070 0%,#2a2e44 26%,#12131f 62%,#31364f 100%);+ box-shadow:0 50px 100px rgba(0,0,0,.92), 0 12px 30px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.10) inset}+.phone img{display:block;width:100%;border-radius:27px;background:#000}+.panel{position:absolute;right:72px;top:90px;bottom:90px;width:720px;display:flex;align-items:center;justify-content:center}+.panel img{display:block;max-width:100%;max-height:100%;border-radius:22px;background:#05060c;+ box-shadow:0 50px 100px rgba(0,0,0,.9), 0 0 0 1px rgba(255,255,255,.12), 0 0 80px rgba(96,120,255,.22)}+.art{position:absolute;inset:0;background-size:cover;background-position:${spec.artPosition || 'center right'}}+.art-fade{position:absolute;inset:0;background:+ linear-gradient(90deg, rgba(0,0,0,.92) 0%, rgba(0,0,0,.72) 34%, rgba(0,0,0,.18) 62%, transparent 78%),+ linear-gradient(0deg, rgba(0,0,0,.75) 0%, transparent 34%),+ linear-gradient(180deg, rgba(0,0,0,.55) 0%, transparent 22%)}+.inset{position:absolute;right:56px;bottom:56px;width:380px;z-index:3}+.inset img{display:block;width:100%;border-radius:16px;box-shadow:0 30px 70px rgba(0,0,0,.9), 0 0 0 1px rgba(255,255,255,.18)}+.inset figcaption{margin-top:10px;font-size:15px;color:#c4d0e8;text-align:right;letter-spacing:.02em;text-shadow:0 2px 12px rgba(0,0,0,.9)}+.credit{position:absolute;right:56px;top:66px;font-size:14px;color:rgba(220,228,255,.62);letter-spacing:.06em;text-transform:uppercase;z-index:3}+</style>+${art ? '' : '<div class="glow"></div><div class="beam"></div>'}+${shotUri ? frameHtml(spec, shotUri) : ''}+<div class="lockup"><img src="${brand.markUri}" alt=""><span>three.ws</span></div>+<div class="copy"><h1>${headline}</h1>${spec.body ? `<p>${esc(spec.body)}</p>` : ''}${code ? `<div class="code">${code}</div>` : ''}</div>+${spec.foot ? `<div class="foot">${esc(spec.foot)}</div>` : ''}`;+}++// Renders the card in a browser that never touched WebGL: capturing a WebGL+// page can wedge the software GPU process, after which every screenshot in+// that browser fails. Returns PNG bytes.+export async function renderCard(spec, { root, shot = null } = {}) {+ if (shot && (await isBlank(shot))) throw new Error(`the frame for ${spec.out || 'the card'} is effectively blank`);+ const shotUri = shot ? await imageUri(shot) : null;+ const { chromium } = await import('playwright');+ const browser = await chromium.launch();+ try {+ const page = await browser.newPage({ viewport: { width: CARD_WIDTH, height: CARD_HEIGHT }, deviceScaleFactor: 1 });+ await page.setContent(cardHtml(spec, shotUri, brandAssets(root)), { waitUntil: 'load' });+ await page.evaluate(() => document.fonts.ready);+ return await page.screenshot({ type: 'png' });+ } finally {+ await browser.close();+ }+}++// PNG when it fits X's 5 MB image limit with room to spare, JPEG otherwise (a+// full-bleed photographic card compresses badly as PNG).+export async function encodeCard(png, { maxBytes = 4.5 * 1024 * 1024 } = {}) {+ const lossless = await sharp(png).png({ compressionLevel: 9 }).toBuffer();+ if (lossless.length <= maxBytes) return { buffer: lossless, ext: '.png' };+ return { buffer: await sharp(png).jpeg({ quality: 92, mozjpeg: true }).toBuffer(), ext: '.jpg' };+}diff --git a/scripts/lib/x-heads.mjs b/scripts/lib/x-heads.mjsnew file mode 100644index 000000000..7f1fffa42--- /dev/null+++ b/scripts/lib/x-heads.mjs@@ -0,0 +1,406 @@+// Builds the head an item declares (api/_lib/x-content/formats.js) from its+// proof reel: a black card around a frame of the reel, a looping GIF cut from+// the reel's busiest stretch, or AI key art grounded on a frame of the reel.+//+// Every head records the sha256 of the reel it was cut from (`derived.reel`),+// and the queue refuses a head whose reel has since been re-filmed, so a post+// can never lead with a picture of a product state that no longer passes.+//+// Authoring only: ffmpeg, a browser, and an image model. Production ships the+// files this writes and never renders anything.++import { execFile, spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { promisify } from 'node:util';+import sharp from 'sharp';++import { FORMATS, ffmpegPath, loadProof } from '../../api/_lib/x-content/reel.js';+import { GIF_LIMITS, MEDIA_TYPES, gifInfo, parseFfmpegProbe } from '../../api/_lib/x-content/media.js';+import { GIF_MIN_WIDTH } from '../../api/_lib/x-content/editorial.js';+import { HEAD_LIMITS, reelPostIndex } from '../../api/_lib/x-content/formats.js';+import { encodeCard, renderCard } from './x-card.mjs';++const execFileAsync = promisify(execFile);+const MB = 1024 * 1024;++export const headDir = (id) => `public/x-media/${id}`;++// ── Reel geometry ───────────────────────────────────────────────────────────++function probeReel(root, path) {+ const probe = parseFfmpegProbe(spawnSync(ffmpegPath(root), ['-hide_banner', '-i', resolve(root, path)], { encoding: 'utf8' }).stderr || '');+ if (!probe) throw new Error(`could not read the reel ${path}`);+ return probe;+}++// Height in output pixels of the caption bar under the page, so a still can+// show the product alone.+function barPixels(item, probe) {+ const format = FORMATS[item.scenario?.format || 'landscape'] || FORMATS.landscape;+ return Math.round((format.bar / format.height) * probe.height);+}++// Where the reel was filmed, as a reader would type it.+export function pageLabel(item) {+ try {+ const url = new URL(item.scenario.steps[0].goto);+ return `${url.host}${url.pathname === '/' ? '' : url.pathname}`;+ } catch {+ return 'three.ws';+ }+}++// One frame of the reel at `atSec`, as PNG bytes. `cropBottom` pixels of+// caption bar are dropped.+export function reelFrame({ root, path, atSec, cropBottom = 0 }) {+ const dir = mkdtempSync(join(tmpdir(), 'x-head-frame-'));+ try {+ const out = join(dir, 'frame.png');+ const filters = cropBottom > 0 ? ['-vf', `crop=iw:ih-${cropBottom}:0:0`] : [];+ const cut = spawnSync(ffmpegPath(root), ['-y', '-hide_banner', '-loglevel', 'error', '-ss', atSec.toFixed(2), '-i', resolve(root, path), '-frames:v', '1', ...filters, out], { encoding: 'utf8' });+ if (cut.status !== 0) throw new Error(`ffmpeg could not cut a frame at ${atSec} s: ${String(cut.stderr).trim().split('\n').pop()}`);+ return readFileSync(out);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++// Per-sample motion across the reel: the mean absolute change between+// consecutive 96px grey thumbnails, sampled `rate` times a second.+export function motionProfile({ root, path, rate = 6 }) {+ const size = 96;+ const run = spawnSync(+ ffmpegPath(root),+ ['-hide_banner', '-loglevel', 'error', '-i', resolve(root, path), '-vf', `fps=${rate},scale=${size}:${size},format=gray`, '-f', 'rawvideo', '-'],+ { maxBuffer: 256 * MB },+ );+ if (run.status !== 0) throw new Error(`ffmpeg could not sample the reel: ${String(run.stderr).trim().split('\n').pop()}`);+ const frame = size * size;+ const frames = Math.floor(run.stdout.length / frame);+ const motion = [0];+ for (let index = 1; index < frames; index++) {+ let total = 0;+ const a = (index - 1) * frame;+ const b = index * frame;+ for (let pixel = 0; pixel < frame; pixel++) total += Math.abs(run.stdout[a + pixel] - run.stdout[b + pixel]);+ motion.push(total / frame);+ }+ return { rate, motion };+}++// The busiest `seconds`-long stretch of the reel, skipping the page load.+export function busiestWindow({ motion, rate }, { seconds, durationSec, skipSec = 1 }) {+ const span = Math.max(1, Math.round(seconds * rate));+ const first = Math.min(Math.round(skipSec * rate), Math.max(0, motion.length - span));+ let best = { start: first, total: -1 };+ let total = 0;+ for (let index = first; index < motion.length; index++) {+ total += motion[index];+ if (index - first >= span) total -= motion[index - span];+ if (index - first >= span - 1 && total > best.total) best = { start: index - span + 1, total };+ }+ const from = Math.max(0, Math.min(best.start / rate, durationSec - seconds));+ return { from: round1(from), to: round1(Math.min(durationSec, from + seconds)) };+}++// The calmest `seconds`-long stretch in the back half of the reel: where a run+// holds on its result, after the confetti, toasts and camera moves of getting+// there have settled. Ties go to the later stretch, closer to the payoff.+export function settledWindow({ motion, rate }, { seconds = 1, durationSec, fromShare = 0.45, tailSec = 0.4 }) {+ const span = Math.max(1, Math.round(seconds * rate));+ const first = Math.round(durationSec * fromShare * rate);+ const last = Math.min(motion.length, Math.floor((durationSec - tailSec) * rate)) - span;+ if (last < first) return null;+ let best = null;+ for (let start = first; start <= last; start++) {+ let total = 0;+ for (let index = start; index < start + span; index++) total += motion[index];+ if (!best || total <= best.total) best = { start, total };+ }+ return { from: round1(best.start / rate), to: round1((best.start + span) / rate) };+}++// The still a card shows: the middle of the reel's settled result, unless that+// frame is far plainer than the rest of the run (a result that faded out), in+// which case the most detailed of the later frames.+async function bestStill({ root, path, probe, cropBottom }) {+ const window = settledWindow(motionProfile({ root, path }), { durationSec: probe.durationSec });+ const settledAt = window ? round1((window.from + window.to) / 2) : null;+ const candidates = [0.5, 0.62, 0.74, 0.86].map((share) => round1(probe.durationSec * share));+ let detailed = null;+ let settled = null;+ for (const atSec of [settledAt, ...candidates].filter((at) => at !== null)) {+ const buffer = reelFrame({ root, path, atSec, cropBottom });+ const { entropy } = await sharp(buffer).stats();+ const frame = { atSec, buffer, entropy };+ if (atSec === settledAt && !settled) settled = frame;+ if (!detailed || entropy > detailed.entropy) detailed = frame;+ }+ return settled && settled.entropy >= detailed.entropy * 0.85 ? settled : detailed;+}++const round1 = (value) => Math.round(value * 10) / 10;++// Captions on screen between `from` and `to`, in the order a viewer reads them.+// A caption stays up until a later step replaces it (`""` clears it), and one+// that is on screen for less than half a second of the window is not counted.+export function captionsBetween(item, proof, { from, to, fps, minSeconds = 0.5 }) {+ const seen = new Map();+ let current = '';+ let frame = 0;+ (proof.steps || []).forEach((step, index) => {+ const caption = item.scenario?.steps?.[index]?.caption;+ if (caption !== undefined) current = caption;+ const start = frame / fps;+ frame += Number(step.frames) || 0;+ const overlap = Math.min(frame / fps, to) - Math.max(start, from);+ if (current && overlap > 0) seen.set(current, (seen.get(current) || 0) + overlap);+ });+ return [...seen].filter(([, seconds]) => seconds >= minSeconds).map(([caption]) => caption);+}++function derived(head, proof, extra = {}) {+ return { as: head.as, reel: proof.video.sha256, ...extra };+}++// ── Card ────────────────────────────────────────────────────────────────────++async function buildCard(item, { root, proof, probe }) {+ const head = item.head;+ const cropBottom = barPixels(item, probe);+ const still = head.at !== undefined+ ? { atSec: Number(head.at), buffer: reelFrame({ root, path: proof.video.path, atSec: Number(head.at), cropBottom }) }+ : await bestStill({ root, path: proof.video.path, probe, cropBottom });+ const meta = await sharp(still.buffer).metadata();+ const label = pageLabel(item);+ const frame = meta.width / meta.height > 1.25 ? 'browser' : 'panel';+ const png = await renderCard({ headline: head.headline, body: head.body, frame, label, foot: head.foot }, { root, shot: still.buffer });+ const { buffer, ext } = await encodeCard(png);+ const path = `${headDir(item.id)}/card${ext}`;+ writeHead(root, path, buffer);+ const alt = head.alt || `three.ws card on a black background with the headline "${oneLine(head.headline)}"${/[.!?]$/.test(oneLine(head.headline)) ? '' : '.'}${head.body ? ` ${sentence(head.body)}` : ''} Beside it, a frame of ${label} from the reel filmed live on the product.`;+ return { path, alt, derived: derived(head, proof, { at: still.atSec }) };+}++// ── GIF ─────────────────────────────────────────────────────────────────────++// Tried in order until the GIF fits under the size ceiling. Every rung stays at+// or above the width a clip reads at on X (editorial.js GIF_MIN_WIDTH).+const GIF_LADDER = [+ { width: 800, fps: 15 },+ { width: 720, fps: 15 },+ { width: 720, fps: 12 },+ { width: 640, fps: 12 },+ { width: GIF_MIN_WIDTH, fps: 10 },+];+// Under X's 15 MB with room for a slow phone connection to start it promptly.+export const GIF_TARGET_BYTES = 12 * MB;++function encodeGif({ root, path, from, to, width, fps, out }) {+ const filters = `fps=${fps},scale=${width}:-2:flags=lanczos,split[a][b];[a]palettegen=max_colors=256:stats_mode=diff[p];[b][p]paletteuse=dither=sierra2_4a:diff_mode=rectangle`;+ const run = spawnSync(+ ffmpegPath(root),+ ['-y', '-hide_banner', '-loglevel', 'error', '-ss', from.toFixed(2), '-t', (to - from).toFixed(2), '-i', resolve(root, path), '-filter_complex', filters, '-loop', '0', out],+ { encoding: 'utf8' },+ );+ if (run.status !== 0) throw new Error(`ffmpeg could not encode the GIF: ${String(run.stderr).trim().split('\n').pop()}`);+ return statSync(out).size;+}++async function buildGif(item, { root, proof, probe }) {+ const head = item.head;+ const [, maxSeconds] = HEAD_LIMITS.gifSeconds;+ const window = head.from !== undefined+ ? { from: Number(head.from), to: Number(head.to) }+ : busiestWindow(motionProfile({ root, path: proof.video.path }), { seconds: Math.min(6, maxSeconds, probe.durationSec), durationSec: probe.durationSec });+ const path = `${headDir(item.id)}/loop.gif`;+ const out = resolve(root, path);+ mkdirSync(dirname(out), { recursive: true });+ const ladder = head.width ? [{ width: head.width, fps: 15 }, ...GIF_LADDER.filter((rung) => rung.width < head.width)] : GIF_LADDER;+ let fitted = null;+ for (const rung of ladder) {+ const width = Math.min(rung.width, probe.width, GIF_LIMITS.maxWidth);+ const bytes = encodeGif({ root, path: proof.video.path, from: window.from, to: window.to, width, fps: rung.fps, out });+ const info = gifInfo(readFileSync(out));+ const withinX = info && info.height <= GIF_LIMITS.maxHeight && info.frames <= GIF_LIMITS.maxFrames && info.width * info.height * info.frames <= GIF_LIMITS.maxPixels;+ if (bytes <= GIF_TARGET_BYTES && withinX) {+ fitted = { ...rung, width, bytes, frames: info.frames };+ break;+ }+ }+ if (!fitted) throw new Error(`${path}: no rung of the GIF ladder fit under ${GIF_TARGET_BYTES / MB} MB; set head.from and head.to to a shorter stretch`);+ const captions = captionsBetween(item, proof, { ...window, fps: proof.video.fps || 30 });+ const alt = head.alt || `Looping clip filmed live on ${pageLabel(item)}${captions.length ? `. On screen: ${captions.map(oneLine).join(' / ')}` : ''}.`;+ return { path, alt, derived: derived(head, proof, { from: window.from, to: window.to, width: fitted.width, fps: fitted.fps }) };+}++// ── AI key art ──────────────────────────────────────────────────────────────++// The art is the image model's; the type, the lockup, and the product frame are+// ours. The model is asked never to draw text, so nothing it invents can read as+// a claim, and the real frame stays visible beside or inside it.+const ART_STYLE = 'Cinematic key art for a technology launch. Deep pure black background, soft blue and violet rim light, faint volumetric haze, glossy reflective black floor, high detail, shallow depth of field. Leave the left third dark and empty for a headline. No text, no letters, no logos, no watermark, no user interface.';++const VERTEX_PROJECT = process.env.GOOGLE_CLOUD_PROJECT || 'aerial-vehicle-466722-p5';+// Best first. Gemini 3 Pro Image is served only from the global endpoint.+export const ART_MODELS = [+ { lane: 'vertex', model: 'gemini-3-pro-image-preview', location: 'global' },+ { lane: 'vertex', model: 'gemini-2.5-flash-image', location: 'us-central1' },+ { lane: 'nim', model: 'black-forest-labs/flux.1-dev' },+];++async function gcloudToken() {+ const { stdout } = await execFileAsync('gcloud', ['auth', 'print-access-token']);+ return stdout.trim();+}++async function vertexArt({ model, location }, prompt, source) {+ const host = location === 'global' ? 'https://aiplatform.googleapis.com' : `https://${location}-aiplatform.googleapis.com`;+ const endpoint = `${host}/v1/projects/${VERTEX_PROJECT}/locations/${location}/publishers/google/models/${model}:generateContent`;+ const body = {+ contents: [{ role: 'user', parts: [{ text: prompt }, { inlineData: { mimeType: 'image/png', data: source.toString('base64') } }] }],+ generationConfig: { responseModalities: ['IMAGE'], imageConfig: { aspectRatio: '16:9', imageSize: '2K' } },+ };+ const response = await fetch(endpoint, {+ method: 'POST',+ headers: { authorization: `Bearer ${await gcloudToken()}`, 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(180_000),+ });+ const data = await response.json().catch(() => ({}));+ if (!response.ok) throw new Error(`vertex ${model} ${response.status}: ${String(data?.error?.message || '').slice(0, 160)}`);+ const part = (data?.candidates?.[0]?.content?.parts || []).find((row) => row?.inlineData?.data);+ if (!part) throw new Error(`vertex ${model} returned no image (${data?.candidates?.[0]?.finishReason || 'no candidate'})`);+ return Buffer.from(part.inlineData.data, 'base64');+}++// FLUX.1-dev on NVIDIA NIM, the platform's free image lane. It cannot take an+// image, so its art is a backdrop and the real frame is inset on the card. Its+// content filter answers some harmless prompts with a black frame, so a few+// seeds are tried before the lane gives up.+async function nimArt(prompt) {+ const key = process.env.NVIDIA_API_KEY;+ if (!key) throw new Error('nim flux: NVIDIA_API_KEY is not set');+ let last = 'no attempt';+ for (const seed of [3, 11, 29, 47]) {+ const response = await fetch('https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-dev', {+ method: 'POST',+ headers: { authorization: `Bearer ${key}`, accept: 'application/json', 'content-type': 'application/json' },+ body: JSON.stringify({ prompt, mode: 'base', width: 1344, height: 768, seed, steps: 40, cfg_scale: 3.5 }),+ signal: AbortSignal.timeout(120_000),+ });+ const data = await response.json().catch(() => ({}));+ const artifact = data?.artifacts?.[0];+ if (response.ok && artifact?.finishReason === 'SUCCESS' && artifact.base64) return Buffer.from(artifact.base64, 'base64');+ last = response.ok ? `withheld (${artifact?.finishReason || 'empty'})` : `${response.status}`;+ }+ throw new Error(`nim flux: ${last} on every seed`);+}++// Draws the key art. Returns { buffer, model, grounded, failures }.+export async function drawArt(prompt, source, { models = ART_MODELS, log = () => {} } = {}) {+ const failures = [];+ for (const choice of models) {+ try {+ if (choice.lane === 'vertex') {+ const buffer = await vertexArt(choice, `Turn this real product screenshot into ${ART_STYLE} Keep the subject of the screenshot recognisable and central. ${prompt}`, source);+ return { buffer, model: `vertex-ai/${choice.model}`, grounded: true, failures };+ }+ const buffer = await nimArt(`${prompt}. ${ART_STYLE}`);+ return { buffer, model: `nvidia-nim/${choice.model}`, grounded: false, failures };+ } catch (err) {+ failures.push(`${choice.model}: ${err.message}`);+ log(` art lane ${choice.model} failed: ${err.message}`);+ }+ }+ throw new Error(`no image model drew the key art: ${failures.join('; ')}`);+}++async function buildArt(item, { root, proof, probe, log }) {+ const head = item.head;+ const cropBottom = barPixels(item, probe);+ const still = head.at !== undefined+ ? { atSec: Number(head.at), buffer: reelFrame({ root, path: proof.video.path, atSec: Number(head.at), cropBottom }) }+ : await bestStill({ root, path: proof.video.path, probe, cropBottom });+ const art = await drawArt(head.prompt, still.buffer, { log });+ const label = pageLabel(item);+ const png = await renderCard(+ {+ headline: head.headline,+ body: head.body,+ frame: 'art',+ credit: 'AI-generated key art',+ // Art the model drew without seeing the product carries the real frame.+ insetUri: art.grounded ? null : `data:image/jpeg;base64,${(await sharp(still.buffer).resize({ width: 800, withoutEnlargement: true }).jpeg({ quality: 90 }).toBuffer()).toString('base64')}`,+ insetLabel: `Filmed live on ${label}`,+ },+ { root, shot: art.buffer },+ );+ const { buffer, ext } = await encodeCard(png);+ const path = `${headDir(item.id)}/art${ext}`;+ writeHead(root, path, buffer);+ const alt = head.alt+ ? ensureGeneratedLabel(head.alt)+ : `AI-generated key art ${art.grounded ? `made from a frame of ${label}` : `with a frame of ${label} filmed live in the corner`}, under the headline "${oneLine(head.headline)}".`;+ return {+ path,+ alt,+ derived: derived(head, proof, { at: still.atSec }),+ generated: { model: art.model, prompt: head.prompt, source: art.grounded ? `${proof.video.path}@${still.atSec}s` : null },+ };+}++// Card body as one sentence of alt text, ending in exactly one stop.+const sentence = (text) => {+ const line = oneLine(text);+ return /[.!?]$/.test(line) ? line : `${line}.`;+};++const ensureGeneratedLabel = (alt) => (/\bAI[- ]generated\b/i.test(alt) ? alt : `AI-generated: ${alt}`);+const oneLine = (text) => String(text || '').replace(/\s*\n\s*/g, ' ').trim();++function writeHead(root, path, buffer) {+ const out = resolve(root, path);+ mkdirSync(dirname(out), { recursive: true });+ writeFileSync(out, buffer);+ const limit = MEDIA_TYPES[path.slice(path.lastIndexOf('.'))].maxBytes;+ if (buffer.length > limit) throw new Error(`${path} is ${(buffer.length / MB).toFixed(1)} MB, over X's ${limit / MB} MB limit`);+}++// ── Placement ───────────────────────────────────────────────────────────────++const BUILDERS = { card: buildCard, gif: buildGif, art: buildArt };++// Puts the reel where the head says it goes and builds the head in front of+// it. `reel` is the media entry proveItem returned. Mutates the item.+export async function placeHead(item, reel, { root, log = () => {} } = {}) {+ const head = item.head;+ const reelIndex = reelPostIndex(item);+ if (!head || head.as === 'reel' || reelIndex === 0) {+ item.posts[0].media = [reel];+ return { head: null };+ }+ if (!item.posts[reelIndex]) throw new Error(`head.as ${head.as} moves the reel to post ${reelIndex + 1}, which the item does not have; add a reply to carry it`);+ // The reply carries the reel alone: X allows a video no company on its post.+ item.posts[reelIndex].media = [reel];+ const proof = loadProof(root, item.id);+ if (!proof?.video?.sha256) throw new Error('no filmed proof on record to build the head from');+ const probe = probeReel(root, proof.video.path);+ const media = await BUILDERS[head.as](item, { root, proof, probe, log });+ item.posts[0].media = [media];+ return { head: media };+}++// Rebuilds the head of an item that is already filmed, without filming again.+export async function rebuildHead(item, { root, log = () => {} } = {}) {+ const proof = loadProof(root, item.id);+ if (!proof?.video?.path) throw new Error(`${item.id} has no filmed proof; run \`npm run x:content -- prove ${item.id}\` first`);+ const reel = (item.posts || []).flatMap((post) => post.media || []).find((media) => media.path === proof.video.path);+ if (!reel) throw new Error(`no post of ${item.id} carries its reel ${proof.video.path}; film it again`);+ // Every other post that carried the reel gives it up first.+ for (const post of item.posts) post.media = (post.media || []).filter((media) => media.path !== proof.video.path);+ for (const post of item.posts) if (!post.media.length) delete post.media;+ return placeHead(item, reel, { root, log });+}diff --git a/scripts/make-x-post-card.mjs b/scripts/make-x-post-card.mjsindex 93890cbcd..3eaf6d0bf 100644--- a/scripts/make-x-post-card.mjs+++ b/scripts/make-x-post-card.mjs@@ -2,7 +2,8 @@// Render one branded 1600x900 card for an X post, in the same visual system as the// Android launch cards (scripts/make-x-thread-cards.mjs): black ground, soft blue and// violet glow, the three.ws lockup, a Space Grotesk headline, and the product shown-// inside a device frame instead of as a raw screenshot.+// inside a device frame instead of as a raw screenshot. The renderer itself lives in+// scripts/lib/x-card.mjs, shared with the X content heads (`x:content -- remix`).//// Raw screenshots read as noise in a timeline. The posts that moved the most $THREE// volume all carried either a video or a clean card that says one thing in large type,@@ -12,7 +13,7 @@//// Spec: { "out": "public/x-media/<id>/card.png", "headline": "Line one\nLine two",// "body": "One or two plain sentences.", "code": ["<line>", "<line>"],-// "frame": "browser" | "phone", "shot": "path/to.png" | "https://three.ws/page",+// "frame": "browser" | "phone" | "panel", "shot": "path/to.png" | "https://three.ws/page",// "label": "yoursite.com", "scrollBy": 400, "settleMs": 12000,// "hide": [".sticky-toolbar"] }// `hide` lists extra selectors to drop from a live capture, e.g. a sticky bar that@@ -22,105 +23,22 @@// never ship showing nothing.import sharp from 'sharp';-import { chromium } from 'playwright';import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';import { fileURLToPath } from 'node:url';import path from 'node:path';+import { CARD_HEIGHT, CARD_WIDTH, capturePage, renderCard } from './lib/x-card.mjs';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const args = process.argv.slice(2);const specPath = args[args.indexOf('--spec') + 1];if (!specPath || !existsSync(specPath)) throw new Error('pass --spec <file.json>');const spec = JSON.parse(readFileSync(specPath, 'utf8'));-const W = 1600;-const H = 900;-const FONT_FACES = [- ['Space Grotesk', '300 700', 'space-grotesk-latin.woff2'],- ['Inter', '300 800', 'inter-latin.woff2'],-].map(([family, weight, file]) => `@font-face{font-family:'${family}';font-style:normal;font-weight:${weight};src:url(data:font/woff2;base64,${readFileSync(path.join(ROOT, 'public/fonts', file)).toString('base64')}) format('woff2');}`).join('\n');-const MARK_URI = `data:image/png;base64,${readFileSync(path.join(ROOT, 'public/pwa-512x512.png')).toString('base64')}`;-const OVERLAYS = ['#tws-corner-stack', '.twx-i18n-fab', '.walk-companion', '.walk-c2w-fx', '.walk-trail-layer', '#market-sidebar-toggle'];-const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));--const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });--async function shotUri() {- let buf;- if (/^https?:/.test(spec.shot)) {- const page = await browser.newPage({ viewport: spec.frame === 'phone' ? { width: 412, height: 892 } : { width: 1280, height: 800 }, deviceScaleFactor: 2, colorScheme: 'dark' });- try { await page.goto(spec.shot, { waitUntil: 'networkidle', timeout: 90000 }); } catch { /* an open socket never idles; the settle below covers it */ }- await page.addStyleTag({ content: `${[...OVERLAYS, ...(spec.hide || [])].join(',')}{display:none!important}` });- if (spec.scrollBy) await page.evaluate((y) => window.scrollBy({ top: y, behavior: 'instant' }), spec.scrollBy);- await page.waitForTimeout(spec.settleMs ?? 9000);- buf = await page.screenshot({ type: 'png' });- await page.close();- } else {- buf = readFileSync(path.resolve(ROOT, spec.shot));- }- const means = (await sharp(buf).stats()).channels.slice(0, 3).map((c) => c.mean);- if (means.every((m) => m < 6)) throw new Error(`[x-card] the capture for ${spec.out} is effectively blank`);- // A 2x capture of a WebGL-heavy page is tens of megabytes as PNG, enough to make the- // card's own screenshot fail. The frame is under 800px wide, so 1600 is already 2x.- const fitted = await sharp(buf).resize({ width: 1600, withoutEnlargement: true }).jpeg({ quality: 90 }).toBuffer();- return `data:image/jpeg;base64,${fitted.toString('base64')}`;-}--const shot = await shotUri();-// Capturing a WebGL-heavy page can wedge the software GPU process, after which every-// further screenshot in that browser fails. The card is plain HTML, so it renders in a-// fresh instance that never touched WebGL.-await browser.close();-const cardBrowser = await chromium.launch();-const headline = esc(spec.headline).replace(/\n/g, '<br>');-const code = (spec.code || []).map((line) => `<div>${esc(line).replace(/(<\/?)([a-z0-9-]+)/gi, '$1<b>$2</b>').replace(/([a-z-]+)=("|")/gi, '<i>$1</i>=$2')}</div>`).join('');-const phoneFrame = spec.frame === 'phone';--const html = `<!doctype html><meta charset="utf-8"><style>-${FONT_FACES}-*{margin:0;padding:0;box-sizing:border-box}-body{width:${W}px;height:${H}px;background:#000;color:#fff;overflow:hidden;position:relative;font-family:'Inter',sans-serif;-webkit-font-smoothing:antialiased}-.glow{position:absolute;inset:0;background:- radial-gradient(34% 40% at 22% 28%, rgba(78,120,255,.22), transparent 70%),- radial-gradient(30% 36% at 80% 24%, rgba(56,180,255,.14), transparent 72%),- radial-gradient(34% 40% at 30% 84%, rgba(140,84,255,.16), transparent 70%),- radial-gradient(30% 36% at 84% 80%, rgba(104,96,255,.14), transparent 72%)}-.beam{position:absolute;left:4%;right:4%;top:40%;height:220px;transform:rotate(-5deg);filter:blur(60px);- background:linear-gradient(90deg, transparent, rgba(150,200,255,.09) 22%, rgba(190,220,255,.14) 50%, rgba(150,200,255,.09) 78%, transparent)}-.lockup{position:absolute;left:72px;top:60px;display:flex;align-items:center;gap:16px}-.lockup img{width:64px;height:64px;border-radius:17px}-.lockup span{font-family:'Space Grotesk',sans-serif;font-weight:600;font-size:42px;letter-spacing:-.045em}-.copy{position:absolute;left:72px;top:${spec.code ? 196 : 232}px;width:${phoneFrame ? 760 : 650}px}-h1{font-family:'Space Grotesk',sans-serif;font-weight:600;letter-spacing:-.04em;line-height:1.02;font-size:${spec.headlineSize || 74}px}-.copy p{margin-top:26px;font-size:27px;line-height:1.45;color:#a7b6d3}-.code{margin-top:34px;padding:22px 24px;border-radius:16px;background:rgba(12,16,32,.78);box-shadow:0 0 0 1px rgba(255,255,255,.10) inset;- font:500 16px/1.75 ui-monospace,'SF Mono',Menlo,Consolas,monospace;color:#c9d6f2;white-space:nowrap;overflow:hidden}-.code b{color:#7fb2ff;font-weight:600}.code i{color:#b79bff;font-style:normal}-.foot{position:absolute;left:72px;bottom:58px;font-size:21px;color:#8fa3c6;letter-spacing:.01em}-.browser{position:absolute;left:760px;top:150px;width:780px;border-radius:18px;overflow:hidden;- background:#12131f;box-shadow:0 50px 100px rgba(0,0,0,.9), 0 12px 30px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.12) inset;- transform:perspective(2200px) rotateY(-7deg) rotateX(2deg)}-.bar{height:44px;display:flex;align-items:center;gap:8px;padding:0 16px;background:linear-gradient(#262a40,#1a1d2e)}-.bar u{width:11px;height:11px;border-radius:50%;background:#4a5070;display:block}-.bar span{margin-left:14px;flex:1;height:24px;border-radius:12px;background:rgba(255,255,255,.07);font-size:13px;line-height:24px;padding:0 12px;color:#93a2c4}-.browser img{display:block;width:100%}-.phone{position:absolute;left:1180px;top:470px;width:360px;transform:translate(-50%,-50%) perspective(1800px) rotateY(-8deg) rotateX(3deg);- border-radius:34px;padding:8px;background:linear-gradient(135deg,#4a5070 0%,#2a2e44 26%,#12131f 62%,#31364f 100%);- box-shadow:0 50px 100px rgba(0,0,0,.92), 0 12px 30px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.10) inset}-.phone img{display:block;width:100%;border-radius:27px;background:#000}-</style>-<div class="glow"></div><div class="beam"></div>-<div class="lockup"><img src="${MARK_URI}" alt=""><span>three.ws</span></div>-<div class="copy"><h1>${headline}</h1>${spec.body ? `<p>${esc(spec.body)}</p>` : ''}${code ? `<div class="code">${code}</div>` : ''}</div>-${spec.foot ? `<div class="foot">${esc(spec.foot)}</div>` : ''}-${phoneFrame ? `<div class="phone"><img src="${shot}" alt=""></div>` : `<div class="browser"><div class="bar"><u></u><u></u><u></u><span>${esc(spec.label || 'yoursite.com')}</span></div><img src="${shot}" alt=""></div>`}`;--const page = await cardBrowser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });-await page.setContent(html, { waitUntil: 'load' });-await page.waitForTimeout(400);+const shot = /^https?:/.test(spec.shot)+ ? await capturePage(spec.shot, { frame: spec.frame, hide: spec.hide || [], scrollBy: spec.scrollBy, settleMs: spec.settleMs ?? 9000 })+ : readFileSync(path.resolve(ROOT, spec.shot));+const png = await renderCard(spec, { root: ROOT, shot });const out = path.resolve(ROOT, spec.out);mkdirSync(path.dirname(out), { recursive: true });-const png = await page.screenshot({ type: 'png' });-await cardBrowser.close();writeFileSync(out, await sharp(png).png({ compressionLevel: 9 }).toBuffer());-console.log(`[x-card] wrote ${spec.out} (${W}x${H})`);+console.log(`[x-card] wrote ${spec.out} (${CARD_WIDTH}x${CARD_HEIGHT})`);diff --git a/scripts/x-content.mjs b/scripts/x-content.mjsindex cdf2c220e..2e50281bc 100644--- a/scripts/x-content.mjs+++ b/scripts/x-content.mjs@@ -17,6 +17,10 @@// film, review, and release by policy where the queue allows it// npm run x:content -- advance --ship and publish what is approved as bundles, so it goes out// without waiting for a deploy (needs X_CONTENT_BUNDLE_SECRET)+// npm run x:content -- remix <slug> --as card|gif|art|reel [--headline "..."] [--body "..."] [--at 6]+// [--from 2 --to 8] [--width 720] [--prompt "..."]+// lead a filmed post with a black card, a GIF cut from+// the reel, or AI key art; the reel moves to the first reply// npm run x:content -- pause <slug> take a post back before it goes out// 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@@ -45,6 +49,8 @@ import { FORMATS, proofPath, proofProblems, proveItem, scoutPage } from '../api/import { approvalPolicy, policyBlockers, releaseDigest, vetoUntil } from '../api/_lib/x-content/approval.js';import { learnLifts, outcomesStore } from '../api/_lib/x-content/outcomes.js';import { browserProblem } from '../api/_lib/x-content/verify.js';+import { FORMATS as FEED_FORMATS, HEAD_KINDS as HEAD_AS, formatMix, formatOf, headSpecProblems, withFormats } from '../api/_lib/x-content/formats.js';+import { placeHead, rebuildHead } from './lib/x-heads.mjs';const root = resolve(fileURLToPath(new URL('..', import.meta.url)));const DAY = 24 * 60 * 60_000;@@ -60,7 +66,7 @@ loadEnvFile(resolve(root, '.env.local'));loadEnvFile(resolve(root, '.env'));const args = process.argv.slice(2);-const VALUE_FLAGS = new Set(['--id', '--as', '--lane', '--pattern', '--out', '--captions', '--item', '--now', '--status', '--speed', '--format', '--shot', '--file']);+const VALUE_FLAGS = new Set(['--id', '--as', '--lane', '--pattern', '--out', '--captions', '--item', '--now', '--status', '--speed', '--format', '--shot', '--file', '--headline', '--body', '--at', '--from', '--to', '--width', '--prompt', '--alt']);const positional = args.filter((arg, index) => !arg.startsWith('--') && !VALUE_FLAGS.has(args[index - 1]));const has = (flag) => args.includes(`--${flag}`);const option = (name, fallback = null) => {@@ -130,6 +136,12 @@ async function plan() {console.log('\nStock (approved, ready, not held), one slot per tier per day:');for (const row of inventory(queue.items.filter((item) => !problems[item.id].length), state, root, now, cadence)) console.log(` ${stockLabel(row)}${row.low ? ' LOW' : ''}`);+ // The feed format each approved post would lead with, and the last few sent.+ const approved = queue.items.filter((item) => item.status === 'approved' && !published.has(item.id));+ const mix = formatMix(approved);+ console.log(` by format: ${FEED_FORMATS.map((format) => `${format} ${mix[format]}`).join(', ')}`);+ const recent = withFormats(state.published, queue.items).slice(-6).map((row) => row.format || '?');+ if (recent.length) console.log(` last sent: ${recent.join(' > ')} (at most ${queue.quality?.maximumSameFormatInARow ?? 'any'} of one format in a row)`);// Items a kind slot owns are ranked for that slot, not for their tier.const reserved = reservedKinds(cadence);@@ -141,7 +153,7 @@ async function plan() {const waiting = queue.items.filter((item) => group.match(item) && !published.has(item.id));if (!waiting.length) continue;console.log(`\n${group.label} by priority:`);- const ranked = rankItems(waiting, { lifts, published: state.published || [], quality: queue.quality, reviews, now });+ const ranked = rankItems(waiting, { lifts, published: withFormats(state.published, queue.items), quality: queue.quality, reviews, now });for (const row of ranked) {const item = row.item;const flags = [@@ -151,7 +163,7 @@ async function plan() {Date.parse(item.notBefore) > now ? `embargoed until ${item.notBefore}` : null,].filter(Boolean);const parts = Object.entries(row.parts).map(([key, value]) => `${key} ${value > 0 ? '+' : ''}${value}`).join(', ');- console.log(` ${String(row.score).padStart(6)} ${item.id.padEnd(26)} ${flags.length ? `[${flags.join('; ')}]` : 'ready'}`);+ console.log(` ${String(row.score).padStart(6)} ${item.id.padEnd(26)} ${String(formatOf(item)).padEnd(7)} ${flags.length ? `[${flags.join('; ')}]` : 'ready'}`);const outlook = row.volumeChance == null? `predicted ${row.predictedLift}x the account median`: `${Math.round(row.volumeChance * 100)}% chance of a volume response${row.volumeSignals.length ? `: ${row.volumeSignals.join(', ')}` : ''}`;@@ -165,7 +177,7 @@ async function plan() {}const publishable = queue.items.filter((item) => !problems[item.id].length);- const next = pickDue({ items: publishable, state, now, cadence: queue.cadence, quality: queue.quality, seed, lifts, reviews, exclude: holds });+ const next = pickDue({ items: publishable, allItems: queue.items, state, now, cadence: queue.cadence, quality: queue.quality, seed, lifts, reviews, exclude: holds });console.log(`\nnow: ${next.item ? `${next.item.id} would fill slot ${next.slot.key} (${next.slot.kind ? `${next.slot.kind}, T${next.tier}` : `T${next.tier}`}${next.filledDown ? `, filling a T${next.slot.tier} slot` : ''}, score ${next.score})` : next.reason}`);}@@ -435,18 +447,22 @@ function printProof(id, proof) {if (proof.video) console.log(` reel: ${proof.video.path} ${proof.video.durationSec} s, ${proof.video.width}x${proof.video.height}, ${proof.video.frames} frames, ${Math.round(proof.video.motion * 100)}% changing`);}-// Films one item. Returns the proof; the reel is put on the item's head post.+// Films one item. Returns the proof. The reel leads the post unless the item+// declares another head, which is then rebuilt from this reel (x-heads.mjs)+// and the reel moves to the reply the head names.async function film(item, { filming = true } = {}) {const failureShot = resolve(root, `node_modules/.cache/x-content/${item.id}-failure.png`);mkdirSync(dirname(failureShot), { recursive: true });const { proof, media } = await proveItem(item, { root, film: filming, failureShot });printProof(item.id, proof);if (!proof.passed) console.log(` the page as it was when the step failed: ${relative(root, failureShot)}`);- // The reel replaces whatever led the post. Anything else the head carried+ // The reel replaces whatever carried it before. Anything else on its post// goes with it, because X allows a video no company on its post.if (media) {- item.posts[0].media = [media];- console.log(` recorded in ${proofPath(item.id)}`);+ for (const post of item.posts) post.media = (post.media || []).filter((row) => row.path !== media.path);+ const { head } = await placeHead(item, media, { root, log: console.log });+ for (const post of item.posts) if (!post.media?.length) delete post.media;+ console.log(` recorded in ${proofPath(item.id)}${head ? `; head rebuilt as ${relative(root, resolve(root, head.path))}` : ''}`);}return proof;}@@ -516,6 +532,46 @@ async function adopt() {if (refused) process.exit(1);}+// Changes what leads a filmed post, without filming it again. The head is built+// from the reel on record, the reel moves to the reply the head names, and the+// item goes back to draft, because a review only covers the bytes it saw:+// `advance` reviews it again and releases it by policy.+async function remix() {+ const id = positional[1];+ const usage = `Usage: remix <slug> [--as ${HEAD_AS.join('|')}] [--headline "Line one\\nLine two"] [--body "..."] [--at 6] [--from 2 --to 8] [--width 720] [--prompt "..."] [--alt "..."]\n Without --as, rebuilds the head the item already declares.`;+ if (!id) fail(usage);+ const queue = loadQueue(root);+ const item = queue.items.find((row) => row.id === id);+ if (!item) fail(`${id} is not in the queue`);+ const as = option('as') ?? item.head?.as;+ if (!HEAD_AS.includes(as)) fail(usage);+ await requireBrowser();+ if (item.status === 'posted') fail(`${id} has already gone out`);+ if (!item.scenario) fail(`${id} carries no scenario, so it has no reel to build a head from`);++ const previous = item.head?.as === as ? item.head : {};+ const text = (name) => option(name)?.replace(/\\n/g, '\n');+ const number = (name) => (option(name) == null ? undefined : Number(option(name)));+ const head = { ...previous, as };+ for (const [key, value] of Object.entries({ headline: text('headline'), body: text('body'), prompt: text('prompt'), alt: text('alt'), at: number('at'), from: number('from'), to: number('to'), width: number('width') })) {+ if (value !== undefined) head[key] = value;+ }+ if (as === 'reel') delete item.head;+ else item.head = head;+ const before = headSpecProblems(item);+ if (before.length) fail(`${id}: ${before.join('; ')}`);++ const { head: media } = await rebuildHead(item, { root, log: console.log });+ const wasStatus = item.status;+ if (['review', 'approved', 'paused'].includes(item.status)) item.status = 'draft';+ saveQueue(queue);+ const problems = validateItem({ ...item, status: 'review' }, root, { quality: queue.quality || {} });+ console.log(`ok ${id}: ${media ? `leads with ${media.path}${media.generated ? ` (AI-generated by ${media.generated.model})` : ''}` : 'leads with its reel again'}; ${wasStatus === item.status ? item.status : `${wasStatus} -> ${item.status}`}`);+ if (media?.alt) console.log(` alt: ${media.alt}`);+ for (const problem of problems) console.log(` fix: ${problem}`);+ console.log(` next: npm run x:content -- advance ${id}`);+}+async function pause() {const id = positional[1];const queue = loadQueue(root);@@ -702,6 +758,6 @@ async function approve() {if (blocked) process.exit(1);}-const commands = { check, plan, run, review, approve, scout, prove, adopt, advance, pause, import: importSource, 'prepare-video': prepareVideo };+const commands = { check, plan, run, review, approve, scout, prove, adopt, advance, remix, pause, import: importSource, 'prepare-video': prepareVideo };if (!commands[command]) fail(`Unknown command ${command}. Commands: ${Object.keys(commands).join(', ')}`);await commands[command]();diff --git a/tests/x-content-reel.test.js b/tests/x-content-reel.test.jsindex e7826a386..38ca7ac02 100644--- a/tests/x-content-reel.test.js+++ b/tests/x-content-reel.test.js@@ -191,9 +191,9 @@ describe('proof', () => {expect(proofProblems(item(), sandbox(old), NOW).join('\n')).toMatch(/filmed 16 days ago/);});- it('requires the head post to carry the reel that was filmed', () => {+ it('requires a post to carry the reel that was filmed', () => {const swapped = item({ posts: [{ text: item().posts[0].text, media: [{ path: 'public/x-media/galaxy-search/other.mp4', probe: PROBE }] }] });- expect(proofProblems(swapped, sandbox(), NOW).join('\n')).toMatch(/does not carry the reel/);+ expect(proofProblems(swapped, sandbox(), NOW).join('\n')).toMatch(/no post carries the reel/);});it('notices a reel that was replaced after the run', () => {