Skip to content

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.

feat(x-content): write posts as filmed stories and release them by policy

nirholas01a6af658294
diff --git a/STRUCTURE.md b/STRUCTURE.md
index cb9e4a853..0fc1151e9 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -312,7 +312,7 @@ bottom.
| Internationalization (i18n) | Runtime [src/i18n.js](src/i18n.js) `→ /i18n.js`; catalogs [public/locales/](public/locales) (`en` + 84 locales, `manifest.json`, `localized-pages.json`); pipeline [scripts/i18n-annotate.mjs](scripts/i18n-annotate.mjs) · [i18n-extract.mjs](scripts/i18n-extract.mjs) · [i18n-translate.mjs](scripts/i18n-translate.mjs) (Vertex Gemini, glossary-locked) · [i18n-backfill.mjs](scripts/i18n-backfill.mjs) (re-translates copy that was baked to English during a backend outage); hreflang in [api/sitemap/[type].js](api/sitemap/%5Btype%5D.js) | Live (85 languages) | LobeHub-model client-side copy swap. `npm run i18n:annotate` auto-injects `data-i18n*` into static HTML (byte-surgical), `i18n:extract` builds `en.json`, `i18n:translate` fans it out to every locale via Vertex with brand/protocol terms masked. `i18n:backfill` finds keys whose value is still byte-identical to English (the silent failure mode: a baked fallback is present, so every later run skips it) and re-translates them. Runtime auto-detects locale, mounts a floating `<lang-switcher>`, and injects hreflang. Doc: [docs/i18n.md](docs/i18n.md). Tests: [tests/i18n.test.js](tests/i18n.test.js), [tests/i18n-annotate.test.js](tests/i18n-annotate.test.js), [tests/i18n-backfill.test.js](tests/i18n-backfill.test.js). |
| Shared utilities (import instead of hand-rolling) | Frontend [src/shared/markdown.js](src/shared/markdown.js) · [src/shared/toast.js](src/shared/toast.js) · [src/shared/fuzzy.js](src/shared/fuzzy.js) · `timeAgo`/`toEpochMs` in [src/shared/coin-format.js](src/shared/coin-format.js); backend [api/_lib/resilience.js](api/_lib/resilience.js) · [api/_lib/mem-cache.js](api/_lib/mem-cache.js) · [api/_lib/pool.js](api/_lib/pool.js) · [api/_lib/csv.js](api/_lib/csv.js); ops [scripts/check-cron-drift.mjs](scripts/check-cron-drift.mjs) | Live · doc [docs/shared-utilities.md](docs/shared-utilities.md) | Thin layers over vetted packages, each replacing a family of hand-rolled copies that had drifted. `markdown.js` = `marked` + `DOMPurify`, the single sanitized path for model/user text reaching `innerHTML` (the concierge SDK carries its own copy at [concierge-sdk/src/markdown.js](concierge-sdk/src/markdown.js) because it ships as an independent bundle). `toast.js` = one aria-live region with a real queue. `fuzzy.js` = `@leeoniya/ufuzzy` ranking + typo tolerance + match ranges for both command palettes. `resilience.js` = `cockatiel` circuit breakers **and** jittered retry (`withRetry`, `parseRetryAfter`, `isRetryableError`). `mem-cache.js` = `lru-cache` with true recency eviction and single-flight `cached()`. `pool.js` = `p-limit` bounded concurrency. `csv.js` = RFC 4180 quoting **plus** spreadsheet formula-injection neutralization. `check-cron-drift.mjs` = `cron-parser` validation of every cron declared in vercel.json against live Cloud Scheduler, sharing its job-id derivation with [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs) so the two can never disagree. Tests: [tests/shared-markdown.test.js](tests/shared-markdown.test.js), [tests/fuzzy.test.js](tests/fuzzy.test.js), [tests/csv.test.js](tests/csv.test.js), [tests/resilience-shared.test.js](tests/resilience-shared.test.js) |
| Announcement factory (internal) | Calendar [scripts/announce-plan.mjs](scripts/announce-plan.mjs) `npm run announce:plan`, factory [scripts/announce-kit.mjs](scripts/announce-kit.mjs) `npm run announce:kit`, engine [api/_lib/announce/](api/_lib/announce), ranker [scripts/announce-rank.mjs](scripts/announce-rank.mjs), gate [scripts/check-announce.mjs](scripts/check-announce.mjs), packs [docs/announcements/](docs/announcements/README.md), deferrals [data/announce-deferred.json](data/announce-deferred.json) | Internal, owner-gated · doc [docs/announcement-factory.md](docs/announcement-factory.md) | Works the backlog of shipped surfaces nobody has posted about (322 of 429) into the X content queue, a batch at a time. The calendar is derived from the publisher's own cadence and rotation rules, so it can never promise a slot the scheduler would refuse, and a surface whose frame would carry live third-party market data is flagged for owner approval instead of being quietly packed. Each pack starts as an evidence brief (the rendered live page, the changelog, the docs, the README) whose every fact is already a check the verifier can run; the model chain drafts from that brief and nothing else, and the draft is held against the voice lint, the claims ledger, the evidence list and the account's own archive, then rewritten until it passes. A surface with no route (packages, workers, services) gets a title card typeset from its real README in the site's own fonts, because a post with no image measured 0.875x. Output is a pack plus a queue item at status `draft`: approval and publishing stay exactly where they were. Tests: [tests/announce-factory.test.js](tests/announce-factory.test.js) |
-| X content pipeline (internal) | Queue [data/x-content/queue.json](data/x-content/queue.json), engine [api/_lib/x-content/](api/_lib/x-content), cron [api/cron/x-content.js](api/cron/x-content.js), CLI [scripts/x-content.mjs](scripts/x-content.mjs), media `public/x-media/` | Internal, owner-gated · doc [docs/x-content-pipeline.md](docs/x-content-pipeline.md) | The reviewed @trythreews publishing queue: posts and threads with native images, GIFs, and captioned video, blog or external pages imported as native posts or full X Articles (via the X Articles API), a copy lint against automated-feed tells, jittered cadence with lane rotation, and a database ledger that resumes a half-sent thread instead of reposting. Previews only until `X_CONTENT_AUTO_PUBLISH=true`. Tests: [tests/x-content.test.js](tests/x-content.test.js) |
+| X content pipeline (internal) | Queue [data/x-content/queue.json](data/x-content/queue.json), engine [api/_lib/x-content/](api/_lib/x-content), cron [api/cron/x-content.js](api/cron/x-content.js), CLI [scripts/x-content.mjs](scripts/x-content.mjs), media `public/x-media/` | Internal · docs [docs/x-content-pipeline.md](docs/x-content-pipeline.md), [docs/x-story-authoring.md](docs/x-story-authoring.md) | The reviewed @trythreews publishing queue: posts and threads with native images, GIFs, and captioned video, blog or external pages imported as native posts or full X Articles (via the X Articles API), a copy lint against automated-feed tells, jittered cadence with lane rotation, and a database ledger that resumes a half-sent thread instead of reposting. A post's video is a proof reel ([reel.js](api/_lib/x-content/reel.js)): a filmed, passing end-to-end run of its own scenario against production, so a feature that does not work cannot be announced. The queue learns from its own measured results ([outcomes.js](api/_lib/x-content/outcomes.js)), releases filmed posts by policy with a veto window ([approval.js](api/_lib/x-content/approval.js)), and can ship an approved post without a deploy as a signed bundle ([overlay.js](api/_lib/x-content/overlay.js)). Previews only until `X_CONTENT_AUTO_PUBLISH=true`. Tests: [tests/x-content.test.js](tests/x-content.test.js), [x-content-reel](tests/x-content-reel.test.js), [x-content-approval](tests/x-content-approval.test.js), [x-content-outcomes](tests/x-content-outcomes.test.js), [x-content-overlay](tests/x-content-overlay.test.js) |
| X post archive + engagement analysis (internal) | Snapshots [data/x-archive/](data/x-archive), schema [api/_lib/migrations/20260814120000_x_account_archive.sql](api/_lib/migrations/20260814120000_x_account_archive.sql), normalization + analysis [scripts/x-archive-lib.mjs](scripts/x-archive-lib.mjs), commands [scripts/x-archive-import.mjs](scripts/x-archive-import.mjs) · [scripts/x-archive-refresh.mjs](scripts/x-archive-refresh.mjs) · [scripts/x-archive-analyze.mjs](scripts/x-archive-analyze.mjs), report [docs/x-archive/](docs/x-archive) | Internal · doc [docs/x-archive.md](docs/x-archive.md) | Every post our own X accounts published, kept as raw snapshot files and indexed into `x_account_posts` / `x_account_post_snapshots` so engagement is a measured time series rather than a memory. `npm run x:archive:analyze` regenerates a report ranking posts by engagement and by engagement *rate*, and scores every measurable signal (media, mentions, length, subject, hour) as lift against the corpus median. Two scraper defects are handled rather than inherited: a profile scrape returns reposts of other accounts with `isRetweet: false` (authorship is read from the permalink instead), and X renders like counts lazily so real posts arrive at "0 likes" (those are archived, named, and excluded from the medians until `npm run x:archive:refresh` replaces them with exact X API counters). Distinct from `x_posts`, which is what platform users publish through [api/x/post.js](api/x/post.js). Tests: [tests/x-archive.test.js](tests/x-archive.test.js) |
| Interactive 3D history timeline | [pages/timeline.html](pages/timeline.html) `→ /timeline`, [src/timeline.js](src/timeline.js), data [data/timeline.json](data/timeline.json) | Live | three.ws's public history (launches, partnerships, listings, press, product ships) as an explorable 3D scene: 60+ milestones as glowing markers along a curved path, 360° free-orbit or a marker-to-marker Walk mode with a guide beacon (reuses the shared `AnimationManager` + default rig from [src/walk.js](src/walk.js)'s pattern), a synced bottom scrubber, category filters, and a detail panel linking to the original source where one exists (IBM Community, NVIDIA Developer Forums, Yahoo Finance, Phemex, CoinGecko, HackerNoon). Real accessible HTML-list fallback for no-WebGL or fetch-failure. |
| Upstream resilience toolkit | [scripts/resilience/](scripts/resilience) + [scripts/audit-upstreams.mjs](scripts/audit-upstreams.mjs) `→ npm run audit:upstreams`, baseline [data/upstream-baseline.json](data/upstream-baseline.json), generated map [docs/resilience.md](docs/resilience.md) | Live | Answers the question a fallback alone cannot: when a third-party service is down, what is each endpoint ALLOWED to say? An AST pass grades every outbound call site on five protections (deadline, retry, failover, last-good, breaker) and ratchets against a committed baseline, so a new unbounded call fails the build while the existing tail is paid down at its own pace. On top of it, endpoints declare a degradation contract (`may-serve-stale`, `must-refuse`, `must-not-serve-stale`) that [tests/upstream-degradation.test.js](tests/upstream-degradation.test.js) proves by replacing fetch with a dead upstream and judging the real response. Built after four fallbacks that each passed review turned out to serve remembered data on paths where staleness costs money or grants access. Complements [scripts/check-fetch-timeouts.mjs](scripts/check-fetch-timeouts.mjs), which enforces the deadline floor. Docs: [scripts/resilience/README.md](scripts/resilience/README.md) |
diff --git a/api/_lib/announce/ledger.js b/api/_lib/announce/ledger.js
index 6b3457d80..e9449fdf5 100644
--- a/api/_lib/announce/ledger.js
+++ b/api/_lib/announce/ledger.js
@@ -51,9 +51,13 @@ export function cryptoPaths(root) {
return paths;
}
-// Ids that are already spoken for: queued, or carrying a pack.
+// Ids that are already spoken for: queued, covered by a queued story, or
+// carrying a pack. A story is about what a person can do, which is often
+// several surfaces at once (a page, the package behind it, the worker behind
+// that), and its `covers` names each one so the backlog stops offering them.
export function takenIds(root, queue) {
const taken = new Set((queue.items || []).map((item) => item.id));
+ for (const item of queue.items || []) for (const key of item.covers || []) taken.add(slugFor(key));
const dir = resolve(root, 'docs/announcements');
if (existsSync(dir)) {
for (const file of readdirSync(dir)) {
diff --git a/api/_lib/x-content/approval.js b/api/_lib/x-content/approval.js
new file mode 100644
index 000000000..564514e4a
--- /dev/null
+++ b/api/_lib/x-content/approval.js
@@ -0,0 +1,72 @@
+// Who may release a reviewed post: the owner, or the queue's own policy.
+//
+// Approval used to be one decision made by hand for every post, which is what
+// kept a backlog of 300 shipped surfaces at three posts a week. The policy
+// hands the owner's attention back to the posts that need it. A post is
+// released without the owner only when every one of these holds:
+//
+// the queue says so `approval.mode` is "auto" (anything else is the owner)
+// the tier is listed flagship posts carry a partner's name or $THREE, so
+// tier 1 stays with the owner unless the queue lists it
+// it was filmed the post carries a scenario, and the reel on it is the
+// one a passing run of that scenario filmed. A post that
+// was never proven against the product is never released
+// by policy
+// it tags no one a tag puts a partner's name next to ours; a person
+// decides that
+// the review passed on the editor's own verdict, not on an override
+//
+// A release by policy is never immediate. The post is embargoed for
+// `vetoHours`, and the release is written to the ops alerts, so there is always
+// a window in which `npm run x:content -- pause <id>` takes it back.
+
+import { proofProblems } from './reel.js';
+import { tierOf } from './schedule.js';
+import { mentionsIn } from './editorial.js';
+
+const HOUR = 3_600_000;
+export const DEFAULT_APPROVAL = { mode: 'owner', tiers: [2, 3], vetoHours: 24 };
+export const MIN_VETO_HOURS = 1;
+
+export function approvalPolicy(queue) {
+ const raw = queue?.approval || {};
+ const tiers = Array.isArray(raw.tiers) ? raw.tiers.map(Number).filter((tier) => [1, 2, 3].includes(tier)) : DEFAULT_APPROVAL.tiers;
+ const veto = Number(raw.vetoHours);
+ return {
+ mode: raw.mode === 'auto' ? 'auto' : 'owner',
+ tiers,
+ vetoHours: Number.isFinite(veto) && veto >= MIN_VETO_HOURS ? veto : DEFAULT_APPROVAL.vetoHours,
+ };
+}
+
+// Why this post must wait for the owner, or [] when the policy may release it.
+export function policyBlockers(item, record, policy, root, now = Date.now()) {
+ if (policy.mode !== 'auto') return ['the queue leaves approval to the owner'];
+ const reasons = [];
+ if (!policy.tiers.includes(tierOf(item))) reasons.push(`tier ${tierOf(item)} posts are approved by the owner`);
+ if (!item.scenario) reasons.push('it was never filmed against the product');
+ else reasons.push(...proofProblems(item, root, now).map((problem) => `proof: ${problem}`));
+ const tagged = mentionsIn((item.posts || []).map((post) => post.text).join('\n'));
+ if (tagged.length) reasons.push(`it tags ${tagged.join(', ')}`);
+ if (!record?.passed) reasons.push('its review did not pass');
+ else if (record.editor?.verdict !== 'publish') reasons.push(`the editor's verdict was ${record.editor?.verdict || 'never given'}`);
+ return reasons;
+}
+
+// The embargo a policy release carries: the later of the one the post already
+// had and the end of the veto window.
+export function vetoUntil(item, policy, now = Date.now()) {
+ const existing = Date.parse(item.notBefore);
+ const window = now + policy.vetoHours * HOUR;
+ return new Date(Math.max(Number.isFinite(existing) ? existing : 0, window)).toISOString();
+}
+
+// What the ops alert says about a batch the policy released.
+export function releaseDigest(released) {
+ const first = released.map((row) => row.notBefore).sort()[0];
+ const lines = released.map((row) => `${row.id} (T${row.tier}, from ${row.notBefore.slice(0, 16)}Z): ${row.head.replace(/\s+/g, ' ').slice(0, 120)}`);
+ return {
+ title: `x-content: ${released.length} post(s) approved by policy`,
+ detail: `Nothing goes out before ${first.slice(0, 16)}Z. To take one back: npm run x:content -- pause <id>\n${lines.join('\n')}`,
+ };
+}
diff --git a/api/_lib/x-content/queue.js b/api/_lib/x-content/queue.js
index 5fe396db8..5039f614f 100644
--- a/api/_lib/x-content/queue.js
+++ b/api/_lib/x-content/queue.js
@@ -145,6 +145,10 @@ export function validateItem(item, root, { quality = qualityAt(root) } = {}) {
if (!/^[0-9]{5,25}$/.test(String(item.quotes))) problems.push('quotes must be a post id (digits only), not a URL');
}
if (item.priority !== undefined && !(Number(item.priority) >= -50 && Number(item.priority) <= 50)) problems.push('priority is an owner boost from -50 to 50');
+ // The backlog surfaces a story speaks for, by their ledger keys.
+ if (item.covers !== undefined && !(Array.isArray(item.covers) && item.covers.every((key) => typeof key === 'string' && /^(\/|@|workers\/|services\/|[a-z0-9])/.test(key)))) {
+ problems.push('covers must list backlog keys such as "/galaxy", "@three-ws/scene-mcp" or "workers/rig"');
+ }
for (const probe of item.probes || []) {
if (!['api', 'browser', 'command', 'scenario'].includes(probe.type)) problems.push(`probe type ${probe.type} must be api, browser, command, or scenario`);
if (probe.type === 'scenario' && !item.scenario) problems.push('a scenario probe needs the item to carry a `scenario`');
diff --git a/data/x-content/queue.json b/data/x-content/queue.json
index c1988e913..c88ae50de 100644
--- a/data/x-content/queue.json
+++ b/data/x-content/queue.json
@@ -57,7 +57,16 @@
"reprojection",
"GPU",
"retopo"
- ]
+ ],
+ "maximumLength": 1000
+ },
+ "approval": {
+ "mode": "auto",
+ "tiers": [
+ 2,
+ 3
+ ],
+ "vetoHours": 24
},
"items": [
{
diff --git a/docs/announce-voice.md b/docs/announce-voice.md
index 7126ed886..221db7d9d 100644
--- a/docs/announce-voice.md
+++ b/docs/announce-voice.md
@@ -1,75 +1,87 @@
# The announcement voice
-**Status:** the contract every announcement pack in [`docs/announcements/`](./announcements/) is written and
-checked against. **Last measured against the archive:** 2026-09-04.
+**Status:** the contract every post in the queue is written and reviewed against, and the file
+the AI editor is handed with each one. **Last measured against the live account:** 2026-09-29.
-three.ws has shipped 430 surfaces and posted about roughly 50 of them. The backlog is inventory,
-not a roadmap, and working it down means writing a lot of announcements. The failure mode that
-threatens is not running out of features. It is that 300 posts written quickly all start to sound
-like the same machine wrote them, and an audience that smells a template stops reading the ones
-that matter.
+three.ws has shipped more than 400 surfaces and posted about roughly 60 of them. The backlog is
+inventory, not a roadmap, and working it down means writing a lot of announcements. The failure
+mode that threatens is not running out of features. It is that 300 posts written quickly all start
+to sound like the same machine wrote them, and an audience that smells a template stops reading the
+ones that matter.
-So this file is the anti-template. Everything in it is derived from two sources on disk, and it
-names them so a claim here can be re-checked rather than believed:
+## Where the numbers come from
-- [`data/x-archive/trythreews-2026-08-14.json`](../data/x-archive/trythreews-2026-08-14.json), 359
- scraped posts, 214 of them ours.
-- [`data/x-archive/analysis/trythreews-engagement.json`](../data/x-archive/analysis/trythreews-engagement.json),
- the engagement report over the 158 of those with usable metrics.
+The X API, read for the account's own head posts, by the learning loop in
+[`api/_lib/x-content/outcomes.js`](../api/_lib/x-content/outcomes.js). Run
+`npm run x:outcomes -- --refresh` and it prints the table these rules were taken from, measured
+again today, so a claim here can be re-checked rather than believed. The queue ranks with the same
+table on every tick.
----
+An earlier version of this file was derived from a scrape
+([`data/x-archive/trythreews-2026-08-14.json`](../data/x-archive/trythreews-2026-08-14.json)).
+That scrape was taken before X had loaded the like counts of the account's largest posts, so 56 of
+214 posts were dropped as having no likes, the three strongest posts among them. Two of the rules it
+produced were the wrong way round, and both are corrected below.
## What the numbers actually say
-Median engagement lift by signal, from the engagement report. "Lift" is the signal's median against
-the account's overall median of 12.
+Median likes of head posts published from 2026-08-10 to 2026-09-28 (53 posts; replies inside a
+thread are not counted as posts):
-| Signal | Lift | Sample | What it means for a draft |
+| Signal | Median likes | Posts | What it means for a draft |
|---|---|---|---|
-| $THREE / token topic | **13.3x** | 4 | The token is not a side note. When a feature genuinely touches it, lead with that. |
-| Mentions an account | **4.5x** | 21 | Tag the partner a feature really runs on. Never tag one it does not. |
-| 100-179 characters | **3.0x** | 17 | The best band reachable in a single post. This is the default. |
-| 180-279 characters | 1.67x | 17 | Fine when the mechanism genuinely needs the room. |
-| Has an image | **2.3x** | 14 | Non-negotiable. See below. |
-| Contains a link | 1.5x | 18 | The link is how anyone gets to the thing. Always include it. |
-| **1-99 characters** | **0.83x** | **121** | The account's single biggest problem. |
-| **Text only** | **0.875x** | **132** | The second biggest. |
-| Has a video | 0.71x | 6 | An uploaded video underperformed a still. Prefer an animated WebP or a real screenshot. |
-
-Read the last three rows together: **121 of 158 measured posts were one-liners and 132 carried no
-media at all.** They are the bulk of the account's output and they are the bottom of its
-performance. Nothing in this document matters more than not writing another one.
+| Video | **149** | 14 | The strongest format, and the one people save: 11 bookmarks a post against 4 for a photo. Film the feature. |
+| Photo | 101 | 25 | A still is the fallback when a feature has nothing that moves. |
+| No media | 80 | 14 | The floor. |
+| Over 280 characters | **140** | 21 | Say the whole thing. The account is on X Premium, and its long posts do about twice the rest. |
+| 180 to 280 characters | 76 | 16 | |
+| 100 to 179 characters | 75 | 7 | The band the old contract aimed every post at. It measures no better than the one above it. |
+| Under 100 characters | 55 | 9 | A one-liner is missing the mechanism. |
+| Tags one account | **134** | 17 | Tag the partner a feature really runs on. Never tag one it does not. |
+| Tags no one | 75 | 25 | |
+| A thread | 133 | 34 | The head states the point; the replies carry the detail and the link. |
+| A single post | 80 | 19 | |
+| Media and no link in the head | 173 | 9 | A link in the head measured about a third less reach (9,574 impressions against 6,035). Nine posts is a small sample, so the queue alternates and keeps measuring. |
+| Media and a three.ws link in the head | 121 | 29 | |
+
+These overlap: a partner announcement is usually long, filmed, and tagged. Read them as direction,
+not as multipliers to stack.
+
+One comparison matters more than the rest. In September the posts this pipeline wrote had a median
+of 63 likes and 2,851 impressions, and the posts written by hand had 112 and 5,386. The pipeline's
+posts were short, still, and linked in the head. That gap is what this contract exists to close.
## The five rules
-1. **Every post ships an image.** Not a stock graphic: a frame of the real product, captured by
- `npm run announce:media` from the live route. A pack with no media is not finished and the
- gate fails it.
-2. **100 characters is the floor and 179 is the target ceiling.** Under 100 a draft is missing the
- mechanism: say how the thing works, not that it exists. Above 179 the measured lift halves.
- The hard wall is 280 weighted characters, which `scripts/post-tweet.mjs` enforces and which a
- URL costs 23 of no matter its real length. The archive's 280-499 band (4.75x over 3 posts) is
- real but not reachable in a single post; that shape is a thread or the Telegram register.
- Check every draft with `node scripts/post-tweet.mjs --file <pack>.post.txt --dry-run`, which
- prints the weighted count and refuses anything over the wall.
-3. **One claim, and it has to be checkable.** Every number in a post comes from the captured
- frame or a linked page. If the media says 86% win rate, the post may say 86% win rate. If
- nothing on screen supports a number, it does not go in.
-4. **Tag only what is true.** `@solana` when it settles on Solana. `@AnthropicAI` when it is an
- MCP server. `@IBM` when it runs on watsonx. A tag we cannot defend costs more than the 4.5x
- is worth.
-5. **Link the surface.** One link, to the page the post is about.
-
-## How this account already sounds
-
-Measured across the 214 posts we have written, not asserted:
-
-- **0 hashtags.** Never add one.
-- **0 emoji.** Never add one.
-- **2 em-dashes**, and the house style bans the character outright. Use a period, a comma, a
- colon, or parentheses.
-- **1 post out of 214 opened with "Introducing".** That is the existing voice and it is a good
- one. Keep it.
+1. **Film the feature.** A post's media is a reel of the feature being used, made by
+ `npm run x:content -- prove <id>` from the scenario the post carries. The reel is a passing
+ end-to-end run against production, so it cannot show anything the product did not do. A feature
+ with nothing to film gets a frame of the real product from `npm run announce:media`. Nothing
+ ships with a stock graphic, and nothing ships with no media.
+2. **Write until the reader could use it.** 100 characters is the floor: under it a draft says
+ that a thing exists and not how it works. There is no target ceiling. The wall is the queue's
+ `quality.maximumLength`. The first 280 characters are all a reader sees before "Show more", so
+ the strongest true statement goes first and the post has to stand on those 280 alone.
+3. **Every claim is checkable, and checked against the product.** Every number and every absolute
+ (first, only, every, never) sits inside a claim with evidence. The strongest evidence is the
+ run itself: a number the scenario read off the screen, a text it waited for, or an answer it got
+ from the server. If the run did not see it, the post does not say it.
+4. **Tag only what is true.** `@solana` when it settles on Solana. `@IBM` when it runs on
+ watsonx. A tag we cannot defend costs more than it is worth, and a post that tags anyone is
+ approved by a person, never by policy.
+5. **Link the surface, once.** One link, to the page the post is about. It may sit in the head or
+ in the first reply; the queue measures both.
+
+## House choices
+
+These are decisions, not measurements, and the gate enforces each one:
+
+- **No hashtags.**
+- **No emoji.** The account's hand-written posts do use them, and the data cannot separate their
+ effect from the partner news they usually sit in. The queue leaves them out so that a run of
+ scheduled posts never reads as decorated.
+- **No em-dashes or en-dashes.** Use a period, a comma, a colon, or parentheses.
+- **No launch-deck openers.** "Introducing" opened one post in 214.
## Banned openings
@@ -97,14 +109,14 @@ Open with the mechanism or the number. The strongest posts in the archive do exa
state a specific, surprising, checkable fact in the first line and let the reader decide it is
impressive.
-Three patterns that fit the measured bands:
+Three patterns for the opening, which is the part a reader sees before "Show more":
-**The number lead** (100-179 chars). Open on a figure the screenshot proves.
+**The number lead.** Open on a figure the run read off the screen.
> Seven autonomous agents have scored 832,142 pump.fun launches on three.ws. 86% win rate on the
> top one. Every trade on the floor is live: three.ws/activity
-**The mechanism lead** (100-179 chars). Open on how it works, because the how is the interesting part.
+**The mechanism lead.** Open on how it works, because the how is the interesting part.
> A sentence or a selfie becomes a rigged 3D agent holding its own custodial @solana wallet, a
> persona, and a voice. It walks and emotes on arrival: three.ws/genesis
@@ -135,7 +147,7 @@ nothing it does not. See [`genesis.md`](./announcements/genesis.md) for the work
pack carries:
- **The claim**, and the evidence for it, with a link to where it can be checked.
-- **The post**, inside the length band, in this voice.
+- **The post**, in this voice.
- **The media**, by shot id from [`data/announce-media.json`](../data/announce-media.json), with
its alt text. Alt text is a requirement, not a courtesy: a post whose whole payload is an image
is unreadable to a screen reader without it.
@@ -146,6 +158,6 @@ pack carries:
## What this file does not decide
-Posting. Publishing to an external channel is an owner-gated action under the operating rules,
-every time, and nothing in this pipeline posts anything. A finished pack is a finished pack: the
-owner runs the one command.
+Who releases a post. That is the queue's `approval` setting, described in
+[the pipeline doc](./x-content-pipeline.md#who-approves-a-post): the owner, or the policy for posts
+that were filmed, tag no one, and passed review on the editor's own verdict.
diff --git a/docs/start-here.md b/docs/start-here.md
index 864dac8f2..d79ea0801 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -233,6 +233,7 @@ Deeper references that don't fit a track above but answer real questions:
- [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
+- [Writing a story for the X queue](./x-story-authoring.md): how to write a post whose video is a filmed, passing run of the feature it announces
- [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)
- [Memory seed connectors](./api-reference.md#memory-seed-connectors-api): the public read-only lane behind the seeding demo. Turn a GitHub, X, or Farcaster handle into a footprint payload, then synthesize a memory seed from any subset of them
diff --git a/docs/x-content-pipeline.md b/docs/x-content-pipeline.md
index 3e59ad0e3..f4e424aca 100644
--- a/docs/x-content-pipeline.md
+++ b/docs/x-content-pipeline.md
@@ -3,9 +3,14 @@
How @trythreews publishes posts, threads, native video, blog shares, and full X
Articles on a human cadence, from one reviewed queue.
-This is internal marketing infrastructure. Nothing reaches X without two owner
-decisions: an item's `status` set to `approved`, and auto-publishing switched on
-for the Cloud Run service (or the owner running one publish by hand).
+This is internal marketing infrastructure. Nothing reaches X unless auto-publishing
+is switched on for the Cloud Run service (or the owner runs one publish by hand),
+and nothing reaches X that did not pass the editorial bar. Who releases a post
+that passed is the queue's `approval` setting: the owner, or a policy that only
+ever releases posts filmed against the live product
+([Who approves a post](#who-approves-a-post)).
+
+To write a post, start with [Writing a story](./x-story-authoring.md).
---
@@ -21,6 +26,8 @@ pipeline, enforced before anything is sent:
| Tell | What the pipeline does |
|---|---|
| Link cards and text-only posts | The head post must carry a native image, GIF, or video (`"textOnly": true` opts out on purpose). Media is uploaded to X, not linked. |
+| A clip of a feature that does not work | A post's reel is a filmed run of its own scenario against production. If a step fails there is no reel, and a review runs the scenario again ([Proof reels](#proof-reels)). |
+| Rules nobody re-measured | The queue reads its own results back through the X API and ranks with what they show ([What the queue learns](#what-the-queue-learns)). |
| Missing alt text | Every image and GIF needs alt text, sent to X as media metadata. |
| Silent autoplay | `prepare-video` burns captions into the clip, because most of the feed watches muted. |
| Hype copy | [api/_lib/x-content/quality.js](../api/_lib/x-content/quality.js) rejects launch openers ("Introducing", "We're excited"), hype vocabulary, hashtags, emoji, stacked exclamation marks, all-caps shouting, and en or em dashes. |
@@ -51,6 +58,14 @@ 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/reel.js](../api/_lib/x-content/reel.js) | Proof reels: the scenario runner, the frame-stepped camera, the encoder, and the proof record. |
+| `data/x-content/stories/<id>.json` | Stories being written, one to a file, before `adopt` moves them into the queue. |
+| `data/x-content/proofs/<id>.json` | What the filmed run did: each step, what it read, what the server answered, and the hash of the reel. |
+| `public/x-media/<id>/reel.mp4` | The reel. |
+| [api/_lib/x-content/outcomes.js](../api/_lib/x-content/outcomes.js) | The learning loop: measured results of the account's head posts, and the lifts learned from them. `app_settings` row `x_content_outcomes`. |
+| [api/_lib/x-content/approval.js](../api/_lib/x-content/approval.js) | The approval policy. |
+| [api/_lib/x-content/overlay.js](../api/_lib/x-content/overlay.js) | Signed bundles in object storage, laid over the image's files so a post can ship without a deploy. |
+| [scripts/x-outcomes.mjs](../scripts/x-outcomes.mjs), [scripts/x-bundle.mjs](../scripts/x-bundle.mjs) | `npm run x:outcomes` and `npm run x:bundle`. |
| [api/_lib/x-content/llm.js](../api/_lib/x-content/llm.js) | The model chain (Vertex, Groq gpt-oss-120b, 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. |
@@ -96,7 +111,9 @@ 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`. 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.
+- `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. `npm run x:content -- advance` does the whole line: it films, reviews, and releases what the policy allows.
+- `scenario` is the run that is filmed: see [Proof reels](#proof-reels) and [Writing a story](./x-story-authoring.md). An item with a scenario declares `{ "type": "scenario" }` in `probes`.
+- `covers` lists the backlog surfaces the story speaks for, by ledger key (`/galaxy`, `@three-ws/scene-mcp`, `workers/rig`), so the announcement plan stops offering them.
- `tier`: 1 (flagship: partner news, $THREE utility, major launches), 2 (features with proof), or 3 (proof of work: short demos, stats, build notes). Each tier owns one slot a day.
- `priority` is an optional owner boost from -50 to 50 on top of the computed score. `expiresAt` marks time-sensitive news: it rises as its window closes and is dropped once it passes. `notBefore` is an embargo: the post is not ready before it.
- `lane` and `pattern` are free-form labels; the score penalizes repeating the last ones.
@@ -106,7 +123,7 @@ X Articles require the posting account to be on X Premium.
- `textFrom` is optional. When set, `check` fails if the inline text differs from that announcement-pack file, so the copy that was reviewed is the copy that ships.
- An `article` item carries `"article": { "title", "body", "cover": { "path" } }`, and its optional `posts` quote the published Article.
-Cadence lives at the top of the file: `slots` (each `{ tier, at }` in UTC), `windowMinutes` (how far a slot's opening may be jittered), `minimumMinutesApart`, `dailyCap`, and `quietHoursUtc` (a `["HH:MM", "HH:MM"]` pair, which may wrap midnight). `quality` sets the similarity limits and the maximum same-lane and same-pattern runs.
+Cadence lives at the top of the file: `slots` (each `{ tier, at }` in UTC), `windowMinutes` (how far a slot's opening may be jittered), `minimumMinutesApart`, `dailyCap`, and `quietHoursUtc` (a `["HH:MM", "HH:MM"]` pair, which may wrap midnight). `quality` sets the similarity limits, the maximum same-lane and same-pattern runs, and `maximumLength`: the longest a post may be, in weighted characters. @trythreews is on X Premium, so the queue sets it above the standard 280; a value under 280 is ignored. `approval` is the policy described below.
**What the cap counts:** `dailyCap` limits scheduled posts in the last 24 hours, and a scheduled post is one the scheduler placed in a slot. A post an operator sends by hand (`run --id`) carries no slot and does not count toward it, because counting those let four owner-requested posts on one afternoon hold every slot shut the following morning. Hand-sent posts do still count toward `minimumMinutesApart`, which measures from the last post of any kind, so the schedule never fires minutes after a manual post. To fill an open slot by hand and keep the schedule's bookkeeping right, run a scheduler tick (`npm run x:content -- run`, no `--id`): it takes the same lock as the cron, picks the post the cron would, and records the slot so the cron sees it as used.
@@ -120,7 +137,8 @@ Cadence lives at the top of the file: `slots` (each `{ tier, at }` in UTC), `win
| Part | What it measures |
|---|---|
-| `engagement` | Predicted lift from how @trythreews posts with the same signals actually performed (format, length, topic), using the same classifiers as the engagement report. Small samples are shrunk toward no effect, and overlapping signals are not stacked. |
+| `learned` | What the account's own head posts of the last 90 days measured for a post of this shape (media, length, thread, tags, where the link sits), read through the X API. Present once 20 posts have matured. See [What the queue learns](#what-the-queue-learns). |
+| `engagement` | The fallback when nothing has been learned yet: predicted lift from the archive report. |
| `timely` | Up to +20 as an `expiresAt` window closes. |
| `boost` | The owner's `priority`. |
| `waiting` | +1 per day ready, capped at +10, so nothing starves. |
@@ -133,6 +151,115 @@ Cadence lives at the top of the file: `slots` (each `{ tier, at }` in UTC), `win
**Stock:** every run counts approved, ready posts per tier (one per day). When any tier has fewer than 3 days left, it raises one alert a day through the platform's ops alerts: always recorded in `ops_alerts`, and pushed to Telegram when `TELEGRAM_ALERTS_CHAT_ID` is set on the service. Running low never makes the queue post something unreviewed; it only posts less.
+## Proof reels
+
+Every post the owner has taken down had passed the fact check, because a fact check proves a page
+says something and not that the feature does it. A scenario closes that gap. It is a list of steps
+run against production, and the run is the probe, the video, the captions, and the evidence at
+once: if a step fails there is no reel and no post.
+
+```bash
+npm run x:content -- scout https://three.ws/galaxy --format square # what the page offers a scenario
+npm run x:content -- prove galaxy-search # run it, film it, record the proof
+npm run x:content -- prove galaxy-search --no-film # run it without filming
+```
+
+How it is filmed, and why:
+
+- **The page clock is stepped, not recorded.** A headless browser renders WebGL in software at one
+ to three frames a second, and a recorder pads that to 25 by repeating frames. The runner takes
+ over the page clock, advances it one frame, takes a picture, and repeats, so every frame of the
+ reel is a distinct frame at exactly 1/30 s of page time. Galaxy measured 1.3 distinct frames a
+ second recorded in real time and 30 stepped.
+- **The page is composited on the CPU.** The browser runs with `--disable-gpu-compositing` and
+ `--disable-gpu-rasterization`. Without them the page itself goes through the same software
+ Vulkan device as the 3D scene, and one frame measured 3.5 to 15 seconds. With them a frame is
+ about 110 to 250 ms and WebGL is unaffected. A 9 second reel films in under two minutes.
+- **Waiting is cut and labelled.** Anything that waits on the network runs on the real clock and
+ is not filmed; the reel shows how long was cut.
+- **Nothing covers the product.** Captions, the cut badge, and a stamp with the production commit
+ and the date sit in a bar under the page. Only the pointer is drawn on the page.
+- **The proof is bound to the post.** `data/x-content/proofs/<id>.json` records the hash of the
+ scenario and of the reel. Change a step, or swap the file, and the item no longer validates. A
+ proof expires after 14 days.
+- **Reviews run it again.** The `scenario` probe runs the steps unfilmed and compares every fact
+ it reads with what the reel shows. A count that has moved is a stale reel: film it again.
+
+A scenario needs a browser and ffmpeg, so reels are made where posts are reviewed. Production
+only checks the record.
+
+## What the queue learns
+
+The rules this pipeline started with came from a scrape taken before X had loaded the like counts
+of the account's largest posts. It reported that video loses to a still and that 100 to 179
+characters is the best length. The X API says the opposite on both.
+
+So the queue measures itself. After each tick's publish attempt it reads the account's head posts
+of the last 90 days (at most once every 6 hours), describes each one by its shape, and learns what
+each attribute is worth: recency weighted, shrunk toward nothing for small samples, and counted
+only once a post is 48 hours old. Replies are left out of the outcome on purpose, because on this
+account they are mostly `$three @grok` farming. Hand-written posts teach it as much as its own.
+
+```bash
+npm run x:outcomes # the learned table, and the best and worst posts of the window
+npm run x:outcomes -- --refresh # read X again first
+npm run x:outcomes -- --compare # the pipeline's posts against the hand-written ones
+```
+
+## Who approves a post
+
+`approval` in the queue file:
+
+```json
+"approval": { "mode": "auto", "tiers": [2, 3], "vetoHours": 24 }
+```
+
+`mode` is `owner` (every post waits for `approve`) or `auto`. Under `auto` a post is released
+without the owner only when all of these hold; anything else waits for the owner, and `advance`
+says which one stopped it:
+
+| Condition | Why |
+|---|---|
+| Its tier is listed | Tier 1 carries a partner's name or $THREE, so it stays with the owner unless the queue lists it. |
+| It was filmed, and the proof covers it | A post never proven against the product is never released by policy. |
+| It tags no one | A tag puts a partner's name next to ours. A person decides that. |
+| The review passed on the editor's own verdict | An `editorOverride` is a person's judgment, so it needs a person. |
+
+A release by policy is embargoed for `vetoHours` and written to the ops alerts (and pushed to
+Telegram when `TELEGRAM_ALERTS_CHAT_ID` is set), so there is always a window to take it back:
+
+```bash
+npm run x:content -- pause <slug>
+```
+
+## Publishing without a deploy
+
+The queue, the review records and the media are files baked into the image, so by default a post
+approved today goes out after the next production deploy. Bundles remove that wait:
+
+```bash
+npm run x:bundle -- publish --approved # ship every approved, unpublished post
+npm run x:bundle -- list # what production will see
+npm run x:bundle -- verify # signature and every file hash
+npm run x:bundle -- pull # build the same directory production builds, to inspect
+npm run x:bundle -- remove <slug>
+```
+
+A bundle is the item, its review record, its proof, and its media, stored in object storage by
+content hash, with an index signed by `X_CONTENT_BUNDLE_SECRET`. At the start of a tick the cron
+builds a directory with the image's files and the bundles' files in the same layout and runs the
+unchanged engine against it, so every rule on this page still applies. A posted item is never
+replaced. If the signature does not verify, a file does not match its hash, or storage is down, the
+tick uses the image queue and says so in its response.
+
+It is off until both are set on the service:
+
+```bash
+gcloud run services update three-ws-api --region us-central1 \
+ --update-secrets X_CONTENT_BUNDLE_SECRET=x-content-bundle-secret:latest \
+ --update-env-vars X_CONTENT_REMOTE_QUEUE=true
+```
+
## Workflow
```bash
@@ -183,6 +310,7 @@ Evidence types:
| `module` | A repo module's `export` has `length` entries, or equals `equals` |
| `github-issue` | `repo#number` has the given `state` and `label` |
| `github-issues` | `repo` has at least `min` issues with the given `state` and `label` |
+| `proof` | The item's filmed run read the `fact` off the screen (`equals`, `contains`), waited for the text in `saw`, or got an answer from the path in `responded` |
Feature probes, in `probes`, run as part of every review, and the `api` ones run again seconds before a post goes out:
@@ -191,9 +319,12 @@ Feature probes, in `probes`, run as part of every review, and the `api` ones run
| `api` | A URL answers 2xx (or `expect.status`), and optionally contains `expect.contains` or has a JSON value at `expect.json.path` (`equals`, `exists`, `min`) | review and pre-flight |
| `browser` | Driving the live page in a real browser (`goto`, `click`, `expect` steps) reaches the expected result | review |
| `command` | A repo test that exercises the exact behavior the post claims exits 0 (`argv`) | review |
+| `scenario` | The item's scenario passes against the live product, and every fact it reads is the fact the reel shows | review |
The live product is the source of truth. When a screenshot disagrees with the live page, the screenshot is stale: recapture it and use the live number. The editor is instructed the same way, and its verdict cannot pass an item it raised a blocking issue on or scored below 4 anywhere. Where a human disagrees with a `revise` verdict that has no blocking issue, `"editorOverride": { "reason": "..." }` on the item records the decision; nothing overrides a failed fact check or blocking lint.
+For a reel the editor is given four frames from it, its captions, and the record of the run, since it cannot watch video. It is calibrated against the account's best posts as the X API measured them.
+
The editor tries Claude on Vertex AI first, then gpt-oss-120b on Groq (skipped when the request carries an image, so a review that must see its media routes to a multimodal rung), then Claude through OpenRouter, then OpenAI, then Kimi K3 on NVIDIA NIM, falling through on any provider or billing error; each record names the model that reviewed it. The CLI reads missing credentials from the Cloud Run service and uses the signed-in `gh` session for GitHub checks.
This bar caught real errors in the first three queued posts. The Rig Doctor post said the tool knew 11 rig conventions while the live page and code said 15, called a merged fix "an open first issue" when no such issue was open, and shipped a screenshot from before the change. The AWS post was 94 characters and stated no mechanism, and an AI rewrite of it upgraded "an AWS Partner" to "a verified AWS Partner", which no evidence supports.
@@ -223,4 +354,6 @@ Queue edits reach production with the next deploy, because the cron reads the qu
## Tests
+[tests/x-content-reel.test.js](../tests/x-content-reel.test.js) covers scenario validation, the proof binding, proof as evidence, post length, and what the editor is given for a reel. [tests/x-content-approval.test.js](../tests/x-content-approval.test.js) covers the approval policy and story coverage. [tests/x-content-outcomes.test.js](../tests/x-content-outcomes.test.js) covers the learning loop, and [tests/x-content-overlay.test.js](../tests/x-content-overlay.test.js) the bundles.
+
[tests/x-content.test.js](../tests/x-content.test.js) covers the tiered slots, fill-down, priority scoring, holds and the fall-through that publishes the next post when one fails, stock counting, quote-tweet ids and their publish wiring, hand-sent posts counting toward spacing but not the cap, the video speed-up filter chain and its caption ordering, the voice and editorial lint, the claims ledger, media quality, review records binding approval to exact content, the editor verdict rules, the media rules, the Markdown to Article offsets, the scheduler's spacing, cap, embargo, and resume rules, and the publisher's thread chaining, crash resume, and Article draft, publish, and quote sequence.
diff --git a/docs/x-story-authoring.md b/docs/x-story-authoring.md
new file mode 100644
index 000000000..f7a26f451
--- /dev/null
+++ b/docs/x-story-authoring.md
@@ -0,0 +1,235 @@
+# Writing a story for the X queue
+
+A story is one post about one thing three.ws does, with a reel of that thing being done. This is
+the guide for writing one: what goes in the file, how to film it, and what makes the difference
+between a post people save and a post people scroll past.
+
+Read [the voice contract](./announce-voice.md) first. It is short, and the AI editor holds every
+post to it. For how the queue schedules, reviews and publishes, see
+[the pipeline doc](./x-content-pipeline.md).
+
+---
+
+## The idea
+
+A post used to be written from what a page said about itself, and checked against the same page.
+That proves the copy matches the page. It does not prove the feature works, and every post that has
+been taken down was taken down for that gap.
+
+So a story starts from using the feature. You write a **scenario**: the steps a person would take,
+and what they would see when it worked. The pipeline runs those steps against production, and the
+run is, at once:
+
+| | |
+|---|---|
+| **the probe** | every step has to pass, or there is no reel and no post |
+| **the video** | the run is filmed, so the media cannot show anything the product did not do |
+| **the captions** | each step can carry the sentence that explains it |
+| **the evidence** | what the run read off the screen, waited for, or got from the server is what your claims cite |
+
+If the feature does not hold up when you use it, that is the finding. Do not write the post. Note
+what failed and move on to a surface that works.
+
+## One story, not one surface
+
+The backlog lists more than 300 surfaces. It does not hold 300 stories. Seven `@three-ws/*-mcp`
+packages announced one by one are seven posts of the same shape, and most packages have no users
+to announce them to. Write about what a person can now do, and let the packages, workers and
+services that make it possible be the detail inside that story. `covers` records which surfaces a
+story speaks for, so the backlog stops offering them.
+
+## The file
+
+Stories live one to a file in `data/x-content/stories/<id>.json` until they are finished, so
+several can be written at once. The file is a queue item:
+
+```json
+{
+ "id": "galaxy-search",
+ "status": "draft",
+ "kind": "post",
+ "tier": 2,
+ "lane": "labs",
+ "pattern": "walkthrough",
+ "notBefore": "2026-09-30T00:00:00Z",
+ "covers": ["/galaxy"],
+ "scenario": {
+ "format": "square",
+ "steps": [
+ { "goto": "https://three.ws/galaxy", "settle": 6000, "caption": "Every published agent, placed by what it does" },
+ { "hold": 2200 },
+ { "read": "agents", "match": "([\\d,]+)\\s*agents" },
+ { "type": "trading bots", "into": "Search by meaning", "caption": "Describe what you want in plain words" },
+ { "click": "Search", "awaits": "/api/galaxy" },
+ { "expect": "Closest to", "caption": "The map flies to the closest matches" },
+ { "hold": 4000 }
+ ]
+ },
+ "probes": [{ "type": "scenario" }],
+ "posts": [
+ { "text": "The head post. The reel is attached to it by `prove`." },
+ { "text": "A reply with the detail and the link: three.ws/galaxy" }
+ ],
+ "claims": [
+ { "says": "600 agents", "evidence": [{ "type": "proof", "fact": "agents", "equals": "600" }] }
+ ],
+ "mentions": {}
+}
+```
+
+| Field | What to put in it |
+|---|---|
+| `id` | A lowercase slug. It names the reel, the proof and the review record. |
+| `tier` | 1 for a flagship ($THREE utility, or a partner the feature runs on), 2 for a feature, 3 for developer proof of work (a package, a CLI, a worker). |
+| `lane` | Who it is for: `community`, `developer`, `token`, `labs`. The queue will not run the same lane three times in a row. |
+| `pattern` | The shape of the opening: `mechanism`, `number`, `walkthrough`, `correction`, `clip`. The queue will not run the same pattern twice in a row. |
+| `notBefore` | The earliest it may go out. Use tomorrow's date. |
+| `covers` | The backlog surfaces this story speaks for, as their keys (`/galaxy`, `@three-ws/scene-mcp`, `workers/rig`). |
+| `probes` | Always includes `{ "type": "scenario" }`, so every review runs the scenario again. Add an `api` probe when the feature has an endpoint: it is the only kind that runs again seconds before the post goes out. |
+
+## Writing the scenario
+
+Look before you write. `scout` opens the page the way the camera will and lists what is there:
+
+```bash
+npm run x:content -- scout https://three.ws/galaxy --format square --shot /tmp/galaxy.png
+```
+
+It prints the controls you can click by their text, the fields you can type into, and the lines of
+the page that carry a number. Open the screenshot as well: the list cannot tell you that a panel
+covers the thing you meant to film.
+
+### Steps
+
+| Step | What it does | Filmed |
+|---|---|---|
+| `{ "goto": "https://...", "settle": 6000 }` | Loads the page and waits `settle` ms for it to finish arriving. Always the first step. | no |
+| `{ "hold": 2000 }` | Films 2 seconds of the page as it is. | yes |
+| `{ "click": "Search" }` | Moves the pointer to the control with that text and clicks it. `{ "click": { "selector": "#go" } }` when the control has no text. | yes |
+| `{ "hover": "Preview" }` | Moves the pointer onto a control. | yes |
+| `{ "type": "trading bots", "into": "Search by meaning" }` | Clicks the field whose placeholder or label matches `into`, then types. | yes |
+| `{ "press": "Enter" }` | Presses a key. | yes |
+| `{ "drag": [[0.3, 0.5], [0.7, 0.5]], "ms": 1500 }` | Drags across the viewport, as fractions of its width and height. This is how you orbit a 3D scene. | yes |
+| `{ "scroll": 500, "ms": 1000 }` | Scrolls by pixels, or to a text: `{ "scroll": "Pricing" }`. | yes |
+| `{ "expect": "Closest to", "within": 45000 }` | Waits until the text is on screen. Add `"film": true` to film the wait. | no |
+| `{ "read": "agents", "match": "([\\d,]+)\\s*agents" }` | Reads a fact off the page. The first group of the pattern is the fact. | no |
+| `{ "wait": 3000 }` | Waits in real time. | no |
+| `{ "caption": "..." }` | Changes the caption and does nothing else. | no |
+
+Any step can carry `"caption"`, up to 90 characters. The caption stays until another replaces it;
+`""` clears it. An action (`click`, `type`, `press`) can carry `"awaits": "/api/path"`: the request
+the action has to cause. The run fails if no such request answers, or if it answers with an error.
+
+### What makes a scenario prove something
+
+- **Expect what only success shows.** "600 agents" is on the galaxy page before anyone searches,
+ so waiting for it proves nothing. "Closest to" appears only when a search came back.
+- **Prefer `awaits` when success is visual.** A camera flying across a map adds no text. The
+ request that made it fly is the proof.
+- **Click by the exact text.** "Search" is matched exactly before it is matched loosely, because
+ "Search" once landed on a "Clear search" button and the reel filmed the query being wiped.
+- **Read every number you intend to say.** A number in your copy is only allowed if a claim covers
+ it, and the strongest claim is `{ "type": "proof", "fact": "agents", "equals": "600" }`.
+
+### What makes a reel worth watching
+
+- **Show the result, and hold on it.** The last hold is the longest. A reel that ends the moment
+ the result appears has filmed the wait and skipped the point.
+- **8 to 20 seconds.** Under 8 there was no time to read a caption. Over 20 the feature should
+ have been two stories.
+- **`square` for anything a phone user would do, `landscape` for a wide scene or a dashboard.** The
+ page is laid out at a small logical width on purpose, so its controls come out large in the
+ frame.
+- **Captions say what the viewer cannot see:** what is happening and why it is hard. "Click
+ Search" is a wasted caption. "Describe what you want in plain words" is not.
+- **Waiting is not filmed.** Anything that waits on the network is cut, and the reel shows a badge
+ saying how long was cut. Do not try to hide a slow feature. Say how long it takes.
+- **Nothing is drawn over the product.** Captions, the cut badge and the stamp sit in a bar under
+ the page. The stamp says which production commit was filmed and when.
+- **Hide only what is not the subject.** Floating site chrome is hidden for you. `"hide":
+ ["selector"]` on the scenario hides more. Never hide part of the feature to make it look better.
+
+## Filming it
+
+```bash
+npm run x:content -- prove --file data/x-content/stories/galaxy-search.json
+```
+
+It runs the scenario against production, films it, writes the reel to
+`public/x-media/<id>/reel.mp4` and the proof to `data/x-content/proofs/<id>.json`, and puts the reel
+on the head post. It prints each step, what the run read, and what the server answered. When a step
+fails it saves a picture of the page as it was at that moment and prints where.
+
+Then watch the reel. `prove` cannot tell you that the interesting part happened off screen. Pull a
+few frames and look at them:
+
+```bash
+node_modules/ffmpeg-static/ffmpeg -ss 6 -i public/x-media/galaxy-search/reel.mp4 -frames:v 1 /tmp/frame.jpg
+```
+
+`--no-film` runs the steps without filming, which is the fast way to get a scenario passing before
+you spend time on the film.
+
+## Writing the post
+
+The reel shows that it works. The post says why anyone should care.
+
+- **The first 280 characters are the post.** That is what a reader sees before "Show more". Open
+ with the strongest true statement and make those 280 stand on their own.
+- **Say it as news, in plain words.** "Your three.ws avatar speaks sign language now" is the
+ strongest opening on the account that tags no one. It names what is new, who it is for, and
+ nothing else.
+- **Then the mechanism.** How it works is the interesting part, and it is the part a competitor
+ cannot copy from a screenshot.
+- **Go long when there is more to say.** Posts over 280 characters measure about twice the likes
+ of shorter ones on this account. Long is not padded: every sentence carries a fact.
+- **A thread for the detail.** The head makes the point. One or two replies carry the numbers,
+ the limits, and what to do next.
+- **One link, to the surface.** Put it in the head or in the first reply. The queue measures both
+ placements, so alternate: if the last story you wrote linked in the head, link this one in the
+ reply.
+- **No hashtags, no emoji, no dashes, no launch-deck openers, no hype words.** The
+ [contract](./announce-voice.md) lists them, and the gate refuses them.
+- **Nothing about price.** Say what $THREE does. Never what it will be worth.
+
+## Claims
+
+Every number, ordinal and absolute in your copy (first, only, every, never, fastest, instant, zero)
+has to sit inside a claim, every claim has to quote your copy word for word, and every claim needs
+evidence:
+
+| Evidence | Passes when |
+|---|---|
+| `{ "type": "proof", "fact": "agents", "equals": "600" }` | the run read that fact off the screen (`contains` also works) |
+| `{ "type": "proof", "saw": "Closest to" }` | the run waited for that text and saw it |
+| `{ "type": "proof", "responded": "/api/galaxy" }` | an action in the run awaited that request and it answered without an error |
+| `{ "type": "page", "url": "https://three.ws/x", "contains": "..." }` | the live page contains the text |
+| `{ "type": "file", "path": "src/x.js", "contains": "..." }` | a file in the repo contains the text |
+| `{ "type": "module", "path": "src/x.js", "export": "LIST", "length": 15 }` | an export has that many entries |
+
+A count that can change (agents, entries, downloads) will change. When it does, the next review
+fails and says the reel is stale, and the fix is to film it again. Prefer facts that hold: a price
+set by a tier, a limit in the code, what a tool does.
+
+## What not to write
+
+- **Anything that names a crypto project other than $THREE.** That includes a token, a launchpad,
+ an exchange, or a protocol, in the copy, the captions, or visible in the frame. Those stories
+ need the owner's approval before they are committed. Solana is the chain $THREE lives on and may
+ be named. If the page you are filming shows third-party market data, stop and pick another.
+- **A feature that did not pass its scenario.** Not with a weaker scenario, and not with the
+ failing step removed.
+- **A post about a page.** `/login`, `/pricing`, `/sitemap` are not stories.
+- **A surface that was already announced.** `data/x-content/queue.json` lists what has gone out.
+- **A promise.** No dates, no "coming soon", nothing the run did not show.
+
+## When it is finished
+
+```bash
+npm run x:content -- adopt galaxy-search # the story joins the queue as a draft
+npm run x:content -- advance galaxy-search # film if needed, review, and release if the policy allows
+```
+
+`advance` takes the story as far as it can go and stops at the first thing that needs a person,
+saying what that is. `npm run x:content -- advance` with no name does it for every draft and every
+item under review.
diff --git a/scripts/audit-docs.mjs b/scripts/audit-docs.mjs
index cc27d9863..af83b773b 100644
--- a/scripts/audit-docs.mjs
+++ b/scripts/audit-docs.mjs
@@ -378,6 +378,7 @@ const UNPUBLISHED_DOCS = new Map([
['trading-hub', 'in-flight: landed mid-session, register with its /trading page'],
['x402-solana-july-roundup-response', 'internal: ready-to-paste X reply draft; posting is owner-gated'],
['x-content-pipeline', 'internal: owner-gated @trythreews publishing queue runbook'],
+ ['x-story-authoring', 'internal: how a post for the @trythreews queue is written and filmed, like x-content-pipeline'],
['x-archive', 'internal: marketing analytics over our own X timeline, not a reader-facing product doc'],
['x-accounts', 'internal: which X handle is live and what the unposted drafts do about it; account operations, not a reader-facing product doc'],
['x-account-appeal', 'internal: the founder account suspension appeal packet; account operations, not a reader-facing product doc'],
diff --git a/scripts/x-content.mjs b/scripts/x-content.mjs
index 719b3413b..2bb5b4a90 100644
--- a/scripts/x-content.mjs
+++ b/scripts/x-content.mjs
@@ -11,6 +11,11 @@
// npm run x:content -- scout <url> [--format square] what a page offers a scenario: controls, fields, numbers
// npm run x:content -- prove <slug> [--no-film] run the item's scenario against the live product and film it
// npm run x:content -- prove --status draft film every item in a status that carries a scenario
+// npm run x:content -- prove --file data/x-content/stories/<slug>.json film a story that is not in the queue yet
+// npm run x:content -- adopt [<slug>...] move finished stories from data/x-content/stories/ into the queue
+// npm run x:content -- advance [<slug>] [--dry-run] take every draft and review item as far as it can go:
+// film, review, and release by policy where the queue allows it
+// 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
// npm run x:content -- approve <slug> owner gate: release a reviewed item
@@ -20,12 +25,12 @@
// publish ledger; X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are
// needed only to publish.
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, extname, relative, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
-import { QUEUE_PATH, loadQueue, validateQueue } from '../api/_lib/x-content/queue.js';
+import { QUEUE_PATH, loadQueue, validateItem, validateQueue } from '../api/_lib/x-content/queue.js';
import { DEFAULT_CADENCE, TIERS, currentSlot, pickDue, slotOpenings, tierOf } from '../api/_lib/x-content/schedule.js';
import { loadLifts, rankItems } from '../api/_lib/x-content/priority.js';
import { activeHolds, inventory } from '../api/_lib/x-content/runner.js';
@@ -34,7 +39,8 @@ import { dbStore, memoryStore } from '../api/_lib/x-content/state.js';
import { MAX_SPEED, VIDEO_LIMITS, mediaType, parseFfmpegProbe, videoFilterChain } from '../api/_lib/x-content/media.js';
import { weightedLength } from '../api/_lib/x-content/quality.js';
import { approvalProblems, loadReview, reviewItem } from '../api/_lib/x-content/review.js';
-import { FORMATS, proofPath, proveItem, scoutPage } from '../api/_lib/x-content/reel.js';
+import { FORMATS, proofPath, proofProblems, proveItem, scoutPage } from '../api/_lib/x-content/reel.js';
+import { approvalPolicy, policyBlockers, releaseDigest, vetoUntil } from '../api/_lib/x-content/approval.js';
import { learnLifts, outcomesStore } from '../api/_lib/x-content/outcomes.js';
const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
@@ -51,7 +57,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']);
+const VALUE_FLAGS = new Set(['--id', '--as', '--lane', '--pattern', '--out', '--captions', '--item', '--now', '--status', '--speed', '--format', '--shot', '--file']);
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) => {
@@ -412,32 +418,171 @@ 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.
+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
+ // 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)}`);
+ }
+ return proof;
+}
+
+const saveJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, '\t')}\n`);
+const saveQueue = (queue) => saveJson(resolve(root, QUEUE_PATH), queue);
+
+// Stories are queue items that live one to a file until they are finished, so
+// several can be written and filmed at once without every author rewriting
+// the same queue file.
+const STORY_DIR = 'data/x-content/stories';
+
async function prove() {
+ const filming = !has('no-film');
+ const file = option('file');
+ if (file) {
+ const path = resolve(root, file);
+ if (!existsSync(path)) fail(`${file} does not exist`);
+ const item = JSON.parse(readFileSync(path, 'utf8'));
+ if (!item.scenario) fail(`${file} carries no scenario`);
+ const proof = await film(item, { filming });
+ if (filming && proof.passed) saveJson(path, item);
+ if (!proof.passed) process.exit(1);
+ return;
+ }
const queue = loadQueue(root);
const status = option('status');
const id = positional[1];
const items = queue.items.filter((item) => item.scenario && (id ? item.id === id : status ? item.status === status : false));
- if (!items.length) fail(id ? `${id} is not in the queue, or carries no scenario` : 'Usage: prove <slug> | prove --status draft [--no-film]');
- const film = !has('no-film');
+ if (!items.length) fail(id ? `${id} is not in the queue, or carries no scenario` : 'Usage: prove <slug> | prove --status draft | prove --file <story.json> [--no-film]');
let failed = 0;
for (const item of items) {
- 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, failureShot });
- printProof(item.id, proof);
- if (!proof.passed) {
- failed++;
- console.log(` the page as it was when the step failed: ${relative(root, failureShot)}`);
+ const proof = await film(item, { filming });
+ if (!proof.passed) failed++;
+ else if (filming) saveQueue(queue);
+ }
+ if (failed) process.exit(1);
+}
+
+async function adopt() {
+ const dir = resolve(root, STORY_DIR);
+ const wanted = positional.slice(1);
+ const files = existsSync(dir) ? readdirSync(dir).filter((name) => name.endsWith('.json') && (!wanted.length || wanted.includes(name.replace(/\.json$/, '')))) : [];
+ if (!files.length) fail(`no stories to adopt in ${STORY_DIR}${wanted.length ? ` named ${wanted.join(', ')}` : ''}`);
+ const queue = loadQueue(root);
+ let refused = 0;
+ for (const name of files) {
+ const path = resolve(dir, name);
+ const story = JSON.parse(readFileSync(path, 'utf8'));
+ const existing = queue.items.findIndex((item) => item.id === story.id);
+ if (existing >= 0 && ['approved', 'posted'].includes(queue.items[existing].status)) {
+ refused++;
+ console.log(`skip ${story.id}: the queue already holds it as ${queue.items[existing].status}`);
continue;
}
- if (!media) continue;
- // The reel replaces whatever led the post. Anything else the head carried
- // goes with it, because X allows a video no company on its post.
- item.posts[0].media = [media];
- console.log(` recorded in ${proofPath(item.id)}`);
+ // A story arrives as a draft whatever it called itself: review and
+ // approval are steps the queue takes, not claims a file makes.
+ const item = { ...story, status: 'draft' };
+ const problems = validateItem(item, root, { quality: queue.quality || {} });
+ if (existing >= 0) queue.items[existing] = item;
+ else queue.items.push(item);
+ rmSync(path);
+ console.log(`ok ${story.id}: in the queue as a draft${problems.length ? `, with ${problems.length} problem(s) to fix: ${problems[0]}` : ''}`);
+ }
+ saveQueue(queue);
+ if (refused) process.exit(1);
+}
+
+async function pause() {
+ const id = positional[1];
+ const queue = loadQueue(root);
+ const item = queue.items.find((row) => row.id === id);
+ if (!item) fail('Usage: pause <slug>');
+ if (item.status === 'posted') fail(`${id} has already gone out`);
+ item.status = 'paused';
+ saveQueue(queue);
+ console.log(`ok ${id}: paused. It will not go out until it is approved again.`);
+}
+
+// One command for the whole line. Each item is taken as far as it can go and
+// stops at the first thing that needs a person, with the reason.
+async function advance() {
+ const queue = loadQueue(root);
+ const id = positional[1];
+ const dryRun = has('dry-run');
+ const policy = approvalPolicy(queue);
+ const quality = queue.quality || {};
+ const items = queue.items.filter((item) => (id ? item.id === id : ['draft', 'review'].includes(item.status)));
+ if (!items.length) fail(id ? `${id} is not in the queue` : 'nothing to advance: no draft or review items');
+ console.log(`approval: ${policy.mode === 'auto' ? `by policy for tier ${policy.tiers.join(', ')}, embargoed ${policy.vetoHours} h` : 'by the owner'}`);
+ if (!dryRun) hydrateReviewEnv();
+
+ const rows = [];
+ const released = [];
+ for (const item of items) {
+ const row = { id: item.id, from: item.status, reached: item.status, stopped: null };
+ rows.push(row);
+ try {
+ if (item.scenario && proofProblems(item, root).length) {
+ if (dryRun) {
+ row.stopped = 'would film its scenario';
+ continue;
+ }
+ const proof = await film(item);
+ if (!proof.passed) {
+ const failed = proof.steps.find((step) => !step.ok);
+ row.stopped = `the feature did not pass its scenario at step ${failed.index} (${failed.kind} ${failed.target}): ${failed.detail}`;
+ continue;
+ }
+ saveQueue(queue);
+ }
+ const problems = validateItem({ ...item, status: 'review' }, root, { quality });
+ if (problems.length) {
+ row.stopped = problems[0];
+ continue;
+ }
+ if (dryRun) {
+ row.stopped = 'would review it';
+ continue;
+ }
+ item.status = 'review';
+ row.reached = 'review';
+ saveQueue(queue);
+ const record = await reviewItem(item, { root, glossary: quality.glossary || [], quality });
+ printReview(record);
+ if (!record.passed) {
+ row.stopped = record.blockers[0];
+ continue;
+ }
+ const blockers = policyBlockers(item, record, policy, root);
+ if (blockers.length) {
+ row.stopped = `passed review; waits for the owner because ${blockers[0]}`;
+ continue;
+ }
+ item.status = 'approved';
+ item.notBefore = vetoUntil(item, policy);
+ item.approvedBy = 'policy';
+ row.reached = 'approved';
+ saveQueue(queue);
+ released.push({ id: item.id, tier: tierOf(item), notBefore: item.notBefore, head: item.posts?.[0]?.text || item.article?.title || '' });
+ } catch (err) {
+ row.stopped = String(err.message || err).split('\n')[0];
+ }
+ }
+
+ console.log('\nitem from reached stopped at');
+ for (const row of rows) console.log(`${row.id.padEnd(28)} ${row.from.padEnd(8)} ${row.reached.padEnd(9)} ${row.stopped || ''}`);
+ if (released.length) {
+ const digest = releaseDigest(released);
+ console.log(`\n${digest.title}\n${digest.detail}`);
+ const { sendOpsAlert } = await import('../api/_lib/alerts.js');
+ await sendOpsAlert(digest.title, digest.detail, { severity: 'info' }).catch((err) => console.log(`(the ops alert was not recorded: ${err.message})`));
}
- if (film) writeFileSync(resolve(root, QUEUE_PATH), `${JSON.stringify(queue, null, '\t')}\n`);
- if (failed) process.exit(1);
}
// --- review ----------------------------------------------------------------
@@ -531,6 +676,6 @@ async function approve() {
if (blocked) process.exit(1);
}
-const commands = { check, plan, run, review, approve, scout, prove, import: importSource, 'prepare-video': prepareVideo };
+const commands = { check, plan, run, review, approve, scout, prove, adopt, advance, 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-approval.test.js b/tests/x-content-approval.test.js
new file mode 100644
index 000000000..6598f4867
--- /dev/null
+++ b/tests/x-content-approval.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest';
+import { createHash } from 'node:crypto';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { DEFAULT_APPROVAL, approvalPolicy, policyBlockers, releaseDigest, vetoUntil } from '../api/_lib/x-content/approval.js';
+import { proofPath, reelPath, scenarioHash } from '../api/_lib/x-content/reel.js';
+import { validateItem } from '../api/_lib/x-content/queue.js';
+import { takenIds } from '../api/_lib/announce/ledger.js';
+import { slugFor } from '../api/_lib/announce/plan.js';
+
+const HOUR = 3_600_000;
+const NOW = Date.parse('2026-09-29T12:00:00Z');
+const REEL = Buffer.from('a filmed reel');
+const SCENARIO = { steps: [{ goto: 'https://three.ws/wardrobe' }, { click: 'Forge it', awaits: '/api/wardrobe' }, { hold: 3000 }] };
+const PROBE = { durationSec: 9, width: 1080, height: 1080, fps: 30, videoCodec: 'h264', pixFmt: 'yuv420p' };
+const AUTO = { mode: 'auto', tiers: [2, 3], vetoHours: 24 };
+const PASSED = { passed: true, editor: { verdict: 'publish' } };
+
+function item(overrides = {}) {
+ return {
+ id: 'wardrobe',
+ status: 'review',
+ kind: 'post',
+ tier: 2,
+ lane: 'community',
+ pattern: 'walkthrough',
+ notBefore: '2026-09-29T00:00:00Z',
+ scenario: SCENARIO,
+ probes: [{ type: 'scenario' }],
+ posts: [{ text: 'Describe a jacket in a sentence and the wardrobe makes it, fitted to your avatar, ready to wear. three.ws/wardrobe', media: [{ path: reelPath('wardrobe'), probe: PROBE, reel: true }] }],
+ claims: [],
+ mentions: {},
+ ...overrides,
+ };
+}
+
+function sandbox({ passed = true } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'x-approval-'));
+ mkdirSync(join(dir, 'public/x-media/wardrobe'), { recursive: true });
+ mkdirSync(join(dir, 'data/x-content/proofs'), { recursive: true });
+ writeFileSync(join(dir, reelPath('wardrobe')), REEL);
+ writeFileSync(join(dir, 'data/x-content/queue.json'), JSON.stringify({ quality: {}, items: [] }));
+ const proof = {
+ id: 'wardrobe',
+ scenarioHash: scenarioHash(SCENARIO),
+ ranAt: new Date(NOW - HOUR).toISOString(),
+ passed,
+ steps: passed ? [] : [{ index: 2, kind: 'click', target: 'Forge it', ok: false, detail: 'POST /api/wardrobe answered HTTP 503' }],
+ facts: {},
+ saw: [],
+ responses: [],
+ cuts: [],
+ video: passed ? { path: reelPath('wardrobe'), sha256: createHash('sha256').update(REEL).digest('hex'), frames: 270, motion: 0.9, ...PROBE } : null,
+ };
+ writeFileSync(join(dir, proofPath('wardrobe')), JSON.stringify(proof));
+ return dir;
+}
+
+describe('approval policy', () => {
+ it('leaves approval with the owner unless the queue says otherwise', () => {
+ expect(approvalPolicy({})).toEqual(DEFAULT_APPROVAL);
+ expect(approvalPolicy({ approval: { mode: 'automatic' } }).mode).toBe('owner');
+ expect(approvalPolicy({ approval: { mode: 'auto', tiers: [1, 2, 9, 'x'], vetoHours: 6 } })).toEqual({ mode: 'auto', tiers: [1, 2], vetoHours: 6 });
+ });
+
+ it('never shortens the veto window to nothing', () => {
+ expect(approvalPolicy({ approval: { mode: 'auto', vetoHours: 0 } }).vetoHours).toBe(DEFAULT_APPROVAL.vetoHours);
+ expect(approvalPolicy({ approval: { mode: 'auto', vetoHours: 'soon' } }).vetoHours).toBe(DEFAULT_APPROVAL.vetoHours);
+ });
+
+ it('releases a filmed post that tags no one and passed on the editor verdict', () => {
+ expect(policyBlockers(item(), PASSED, AUTO, sandbox(), NOW)).toEqual([]);
+ });
+
+ it('keeps every post with the owner when the mode is owner', () => {
+ expect(policyBlockers(item(), PASSED, DEFAULT_APPROVAL, sandbox(), NOW)).toEqual(['the queue leaves approval to the owner']);
+ });
+
+ it('keeps flagship posts with the owner unless tier 1 is listed', () => {
+ expect(policyBlockers(item({ tier: 1 }), PASSED, AUTO, sandbox(), NOW)).toEqual(['tier 1 posts are approved by the owner']);
+ expect(policyBlockers(item({ tier: 1 }), PASSED, { ...AUTO, tiers: [1, 2, 3] }, sandbox(), NOW)).toEqual([]);
+ });
+
+ it('never releases a post that was not filmed', () => {
+ expect(policyBlockers(item({ scenario: undefined }), PASSED, AUTO, sandbox(), NOW)).toEqual(['it was never filmed against the product']);
+ });
+
+ it('never releases a post whose feature failed its scenario', () => {
+ expect(policyBlockers(item(), PASSED, AUTO, sandbox({ passed: false }), NOW).join('\n')).toMatch(/proof: the last run failed at step 2/);
+ });
+
+ it('leaves a tag to a person', () => {
+ const tagged = item({ posts: [{ ...item().posts[0], text: 'Garments are generated on @nvidia hardware and fitted to your avatar. three.ws/wardrobe' }] });
+ expect(policyBlockers(tagged, PASSED, AUTO, sandbox(), NOW)).toEqual(['it tags @nvidia']);
+ });
+
+ it('does not count an override as a pass', () => {
+ expect(policyBlockers(item(), { passed: true, editor: { verdict: 'revise' } }, AUTO, sandbox(), NOW)).toEqual(["the editor's verdict was revise"]);
+ expect(policyBlockers(item(), { passed: false, editor: { verdict: 'revise' } }, AUTO, sandbox(), NOW)).toEqual(['its review did not pass']);
+ expect(policyBlockers(item(), null, AUTO, sandbox(), NOW)).toEqual(['its review did not pass']);
+ });
+
+ it('embargoes a release for the veto window, or longer if the post already waited for more', () => {
+ expect(vetoUntil(item(), AUTO, NOW)).toBe('2026-09-30T12:00:00.000Z');
+ expect(vetoUntil(item({ notBefore: '2026-10-05T09:00:00Z' }), AUTO, NOW)).toBe('2026-10-05T09:00:00.000Z');
+ });
+
+ it('tells the owner what was released, when, and how to take it back', () => {
+ const digest = releaseDigest([
+ { id: 'wardrobe', tier: 2, notBefore: '2026-09-30T12:00:00.000Z', head: 'Describe a jacket\nin a sentence' },
+ { id: 'tty', tier: 3, notBefore: '2026-09-30T09:00:00.000Z', head: 'curl three.ws/tty' },
+ ]);
+ expect(digest.title).toBe('x-content: 2 post(s) approved by policy');
+ expect(digest.detail).toMatch(/Nothing goes out before 2026-09-30T09:00Z/);
+ expect(digest.detail).toMatch(/npm run x:content -- pause <id>/);
+ expect(digest.detail).toMatch(/wardrobe \(T2, from 2026-09-30T12:00Z\): Describe a jacket in a sentence/);
+ });
+});
+
+describe('a story covers backlog surfaces', () => {
+ it('takes every surface it names off the backlog', () => {
+ const queue = { items: [item({ covers: ['/wardrobe', '@three-ws/scene-mcp', 'workers/garment-forge'] })] };
+ const taken = takenIds(mkdtempSync(join(tmpdir(), 'x-covers-')), queue);
+ for (const key of ['/wardrobe', '@three-ws/scene-mcp', 'workers/garment-forge']) expect(taken.has(slugFor(key))).toBe(true);
+ expect(taken.has('wardrobe')).toBe(true);
+ expect(taken.has(slugFor('/galaxy'))).toBe(false);
+ });
+
+ it('refuses a covers list that is not a list of keys', () => {
+ expect(validateItem(item({ covers: ['/wardrobe', 'workers/garment-forge'] }), sandbox())).toEqual([]);
+ expect(validateItem(item({ covers: '/wardrobe' }), sandbox()).join('\n')).toMatch(/covers must list backlog keys/);
+ expect(validateItem(item({ covers: [42] }), sandbox()).join('\n')).toMatch(/covers must list backlog keys/);
+ });
+});