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): learn what works from the account's own measured posts
nirholas1e8f96399784
diff --git a/api/_lib/x-content/outcomes.js b/api/_lib/x-content/outcomes.jsnew file mode 100644index 000000000..92cd1d602--- /dev/null+++ b/api/_lib/x-content/outcomes.js@@ -0,0 +1,414 @@+// What actually happened to the posts @trythreews sent, read back through the X+// API, and what that says about the next one. This closes the loop the queue was+// missing: priority.js used to rank on a scraped archive that had lost the like+// counts of the account's biggest posts, so it believed a video does worse than+// a still when the live numbers say the opposite.+//+// Three steps, each usable on its own:+//+// collectOutcomes pages the account's own timeline and keeps one compact row+// per head post: its public metrics and the attributes a+// draft can be checked for before it is sent+// learnLifts for every attribute value, how much better or worse posts+// with it did than posts without it, weighted toward recent+// posts and shrunk toward no effect on small samples+// learnedScore describes a queued item in the same vocabulary and turns+// the lifts that apply to it into ranking points+//+// Rows hold numbers and attributes only, never the copy, so the stored record+// stays small enough to load on every tick.+//+// Everything is pure except the store and collectOutcomes.++import { urlsIn, weightedLength } from './quality.js';++export const OUTCOMES_KEY = 'x_content_outcomes';++const HOUR = 60 * 60_000;+const DAY = 24 * HOUR;++// How far back the timeline is read, and the most posts one refresh will page+// through (replies included, because they are how a thread is recognised).+export const OUTCOMES_WINDOW_DAYS = 90;+export const OUTCOMES_LIMIT = 800;+// A stored record older than this is read again on the next publishing tick.+export const OUTCOMES_REFRESH_HOURS = 6;+// X answers 503 on a timeline page often enough that one failed page should not+// cost the whole read. The wait grows with each try.+export const READ_ATTEMPTS = 3;+export const READ_RETRY_MS = 2000;+// Likes keep arriving for about two days; a younger post would be measured low.+export const MIN_AGE_HOURS = 48;+// A post this old counts half as much as one sent today, so the lifts follow+// the audience the account has now.+export const HALF_LIFE_DAYS = 45;+// Prior strength for shrinkage: a value seen on n posts keeps n / (n + K) of+// its measured difference.+export const SHRINK_K = 8;+// Below this many posts a value is reported but moves no score.+export const MIN_VALUE_COUNT = 3;+// The ranking ignores the learned lifts until this many posts have matured.+export const LEARNED_MIN_SAMPLE = 20;+export const CALIBRATION_TEXT_CHARS = 400;+export const LEARNED_POINTS_PER_UNIT = 10;+export const LEARNED_POINTS_LIMIT = 15;++// Weighted length (quality.js) at which a post leaves each bucket. `long` is a+// post over the standard limit, which X only allows on a Premium account.+export const LENGTH_BANDS = [+ { key: 'short', below: 100 },+ { key: 'band', below: 180 },+ { key: 'standard', below: 281 },+ { key: 'long', below: Infinity },+];++export const TIMELINE_FIELDS = {+ 'tweet.fields': ['public_metrics', 'created_at', 'referenced_tweets', 'attachments', 'entities', 'note_tweet', 'conversation_id', 'in_reply_to_user_id', 'article'],+ expansions: ['attachments.media_keys'],+ 'media.fields': ['type'],+};++const emptyOutcomes = () => ({ fetchedAt: null, posts: [] });++export function outcomesStore() {+ const db = () => import('../db.js').then((module) => module.sql);+ return {+ label: 'database',+ async load() {+ const sql = await db();+ const [row] = await sql`SELECT value FROM app_settings WHERE key = ${OUTCOMES_KEY}`;+ return { ...emptyOutcomes(), ...(row?.value || {}) };+ },+ async save(outcomes) {+ const sql = await db();+ await sql`+ INSERT INTO app_settings (key, value) VALUES (${OUTCOMES_KEY}, ${JSON.stringify(outcomes)}::jsonb)+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()+ `;+ },+ };+}++// For a machine without DATABASE_URL: starts empty, keeps nothing past the run.+export function memoryOutcomesStore(initial = emptyOutcomes()) {+ let outcomes = structuredClone(initial);+ return {+ label: 'memory (no DATABASE_URL, so nothing learned is kept)',+ async load() {+ return structuredClone(outcomes);+ },+ async save(next) {+ outcomes = structuredClone(next);+ },+ };+}++// ── Describing a post ───────────────────────────────────────────────────────++const X_HOSTS = /(^|\.)(x\.com|twitter\.com|t\.co)$/i;++function hostOf(url) {+ try {+ return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).hostname;+ } catch {+ return '';+ }+}++// X appends its own link for attached media and for a quoted post. Neither is a+// link the author wrote, and neither takes the reader anywhere off the post.+const isOwnLink = (url) => X_HOSTS.test(hostOf(url));++const lengthBand = (length) => LENGTH_BANDS.find((band) => length < band.below).key;++const mentionsIn = (text) => (String(text).match(/(?<![\w@])@\w{1,15}/g) || []).length;++const hasCashtag = (text) => /\$THREE\b/i.test(String(text));++const MEDIA_RANK = ['video', 'gif', 'photo'];+const API_MEDIA_KIND = { video: 'video', animated_gif: 'gif', photo: 'photo' };++// One kind per post: X allows a video or a GIF alone, so the moving kind wins+// the rare time a row carries both.+const mediaKind = (kinds) => MEDIA_RANK.find((kind) => kinds.includes(kind)) || 'none';++function pathMediaKind(path) {+ if (/\.(mp4|mov)$/i.test(path || '')) return 'video';+ if (/\.gif$/i.test(path || '')) return 'gif';+ if (/\.(png|jpe?g|webp)$/i.test(path || '')) return 'photo';+ return null;+}++// The API escapes these three in post text; the reader never sees them.+const unescapeText = (text) => String(text).replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');++// A head post starts its own conversation: not a reply, and not a repost.+//+// The reference list alone is not proof. On 2026-09-29 X answered a timeline+// read with ten replies in a row whose `referenced_tweets` were missing (it+// returned 503 a minute later), and all ten were learned from as if they were+// short, bare head posts. A head is therefore also required to carry its own id+// as its conversation, so a post X did not fully describe is left out.+export function isHeadPost(tweet) {+ if ((tweet.referenced_tweets || []).some((ref) => ref.type === 'replied_to' || ref.type === 'retweeted')) return false;+ if (tweet.in_reply_to_user_id) return false;+ return String(tweet.conversation_id || '') === String(tweet.id);+}++// The lead post id of a ledger row, read from the URL the publisher recorded+// (for an Article that is the Article's own post, which `postIds` does not hold).+export function leadPostId(row) {+ return String(row?.url || '').match(/\/status\/(\d+)/)?.[1] || row?.postIds?.[0] || null;+}++export function describePost(tweet, { mediaByKey = new Map(), threadSizes = new Map(), pipelineById = new Map() } = {}) {+ const metrics = tweet.public_metrics || {};+ // A post over 280 characters arrives truncated in `text`, whole in `note_tweet`.+ // An Article's own post arrives as nothing but X's link to the Article, while+ // the feed shows its title over its cover, so that is what gets described.+ const raw = tweet.article?.title || tweet.note_tweet?.text || tweet.text || '';+ const links = [...(tweet.entities?.urls || []), ...(tweet.note_tweet?.entities?.urls || [])];+ const resolved = links.length ? links : urlsIn(raw).map((url) => ({ url, expanded_url: url }));+ const own = resolved.filter((row) => row.media_key || isOwnLink(row.expanded_url || row.url));+ const written = resolved.filter((row) => !own.includes(row));+ // X's own links are not part of what the author typed, so they are taken out+ // before the copy is measured.+ const text = unescapeText(own.reduce((copy, row) => copy.split(row.url).join(''), raw)).trim();++ const kinds = (tweet.attachments?.media_keys || []).map((key) => API_MEDIA_KIND[mediaByKey.get(key)?.type]).filter(Boolean);+ if (tweet.article?.cover_media) kinds.push('photo');+ const published = pipelineById.get(String(tweet.id));+ const row = {+ id: String(tweet.id),+ at: tweet.created_at,+ impressions: Number(metrics.impression_count || 0),+ likes: Number(metrics.like_count || 0),+ // The count X shows under a post: plain reposts plus quotes.+ reposts: Number(metrics.retweet_count || 0) + Number(metrics.quote_count || 0),+ replies: Number(metrics.reply_count || 0),+ bookmarks: Number(metrics.bookmark_count || 0),+ media: mediaKind(kinds),+ length: lengthBand(weightedLength(text)),+ link: written.length ? 'head' : 'none',+ thread: (threadSizes.get(String(tweet.conversation_id || tweet.id)) || 0) > 0,+ mentions: mentionsIn(text),+ cashtag: hasCashtag(text),+ source: published ? 'pipeline' : 'hand',+ // The opening of the post, so the editor can be calibrated against what+ // the account's best posts actually said (bestPosts).+ text: text.slice(0, CALIBRATION_TEXT_CHARS),+ };+ if (published) {+ row.lane = published.lane;+ row.pattern = published.pattern;+ }+ return row;+}++// A queued item in the same vocabulary, from what is known before it is sent.+// An Article is described as its own post, title over cover, because that post+// is the one the ledger records and the one that gets measured. The posts that+// follow an Article quote it; they do not reply to it, so it is never a thread.+export function describeItem(item) {+ const isArticle = item.kind === 'article';+ const head = item.posts?.[0] || {};+ const text = String(isArticle ? item.article?.title || '' : head.text || '').trim();+ const kinds = isArticle ? [] : (head.media || []).map((row) => pathMediaKind(row.path)).filter(Boolean);+ if (isArticle && item.article?.cover) kinds.push('photo');+ return {+ media: mediaKind(kinds),+ length: lengthBand(weightedLength(text)),+ // A link that sits in a reply is not in front of the reader of the head.+ link: urlsIn(text).some((url) => !isOwnLink(url)) ? 'head' : 'none',+ thread: !isArticle && (item.posts?.length || 0) > 1,+ mentions: mentionsIn(text),+ cashtag: hasCashtag(text),+ source: 'pipeline',+ lane: item.lane,+ pattern: item.pattern,+ };+}++// The attribute values a row carries, as the keys the lifts are stored under.+export function attributeKeys(row) {+ const keys = [+ `media:${row.media}`,+ `length:${row.length}`,+ `link:${row.link}`,+ `thread:${Boolean(row.thread)}`,+ `mentions:${row.mentions >= 2 ? '2+' : row.mentions || 0}`,+ `cashtag:${Boolean(row.cashtag)}`,+ ];+ if (row.source === 'pipeline') {+ if (row.lane) keys.push(`lane:${row.lane}`);+ if (row.pattern) keys.push(`pattern:${row.pattern}`);+ }+ return keys;+}++// ── Collecting ──────────────────────────────────────────────────────────────++async function readTimeline({ client, now, days, limit }) {+ const { data: me } = await client.me();+ const timeline = await client.userTimeline(me.id, {+ max_results: 100,+ exclude: ['retweets'],+ // X documents whole seconds for this parameter.+ start_time: new Date(now - days * DAY).toISOString().replace(/\.\d{3}Z$/, 'Z'),+ ...TIMELINE_FIELDS,+ });++ const tweets = [];+ for await (const tweet of timeline) {+ tweets.push(tweet);+ if (tweets.length >= limit) break;+ }+ // Read after paging: the paginator adds each page's media as it fetches it.+ return { me, tweets, media: timeline.includes?.media || [] };+}++// X having a bad minute, as opposed to X refusing us (401, 403, 429), which no+// second try would change.+const isTransient = (err) => Number(err?.code ?? err?.status) >= 500;++const wait = (ms) => new Promise((done) => setTimeout(done, ms));++export async function collectOutcomes({+ client,+ ledger = null,+ now = Date.now(),+ days = OUTCOMES_WINDOW_DAYS,+ limit = OUTCOMES_LIMIT,+ attempts = READ_ATTEMPTS,+ retryDelayMs = READ_RETRY_MS,+}) {+ // A read that fails part way is started again from the top: half a timeline+ // would measure the recent posts against nothing.+ let read = null;+ for (let attempt = 1; !read; attempt++) {+ try {+ read = await readTimeline({ client, now, days, limit });+ } catch (err) {+ if (attempt >= attempts || !isTransient(err)) throw err;+ await wait(retryDelayMs * attempt);+ }+ }+ const { me, tweets } = read;+ const mediaByKey = new Map(read.media.map((row) => [row.media_key, row]));++ const heads = tweets.filter(isHeadPost);+ const headIds = new Set(heads.map((tweet) => String(tweet.id)));+ // A thread is the account answering itself under its own head. An answer to+ // somebody else in the same conversation is a reply, not a second part.+ const threadSizes = new Map();+ for (const tweet of tweets) {+ const conversation = String(tweet.conversation_id || '');+ const toSelf = String(tweet.in_reply_to_user_id || '') === String(me.id);+ if (isHeadPost(tweet) || !headIds.has(conversation) || !toSelf) continue;+ threadSizes.set(conversation, (threadSizes.get(conversation) || 0) + 1);+ }++ // Matched on the lead post. The other ids are kept too: for a thread they are+ // replies and never become rows, but the post that quotes an Article is a head+ // of its own, and it is the queue's post as much as the Article is.+ const pipelineById = new Map();+ for (const row of ledger?.published || []) {+ for (const id of [leadPostId(row), ...(row.postIds || [])]) if (id) pipelineById.set(String(id), row);+ }++ return {+ fetchedAt: new Date(now).toISOString(),+ posts: heads.map((tweet) => describePost(tweet, { mediaByKey, threadSizes, pipelineById })),+ };+}++export function outcomesAreStale(outcomes, now = Date.now(), hours = OUTCOMES_REFRESH_HOURS) {+ const fetched = Date.parse(outcomes?.fetchedAt || '');+ return !Number.isFinite(fetched) || now - fetched > hours * HOUR;+}++// ── Learning ────────────────────────────────────────────────────────────────++// One number per post. Logs, because a post with 400 likes is not 100 times the+// post with 4. Replies are left out on purpose: on this account they are mostly+// "$three @grok" farming spam, so they measure nothing about the post.+// The account's strongest matured head posts by outcome, newest regime first:+// what "good" has meant on this account lately, in its own words.+export function bestPosts(rows, { now = Date.now(), count = 6 } = {}) {+ return (rows || [])+ .filter((row) => row.text && isMature(row, now))+ .sort((a, b) => outcomeOf(b) - outcomeOf(a))+ .slice(0, count)+ .map((row) => ({ text: row.text.replace(/\s+/g, ' ').trim(), likes: row.likes, reposts: row.reposts, bookmarks: row.bookmarks, views: row.impressions, media: row.media, posted: row.at.slice(0, 10) }));+}++export function outcomeOf(row) {+ return Math.log1p(row.likes || 0) + 0.5 * Math.log1p(row.bookmarks || 0) + 0.25 * Math.log1p(row.reposts || 0);+}++export const isMature = (row, now = Date.now(), minAgeHours = MIN_AGE_HOURS) => now - Date.parse(row.at) >= minAgeHours * HOUR;++// Adding zero turns a rounded -0 into 0, so a report never prints "-0".+const round = (value, places = 4) => Math.round(value * 10 ** places) / 10 ** places + 0;++export function learnLifts(rows, { now = Date.now(), minAgeHours = MIN_AGE_HOURS, halfLifeDays = HALF_LIFE_DAYS, shrinkK = SHRINK_K } = {}) {+ const matured = (rows || []).filter((row) => isMature(row, now, minAgeHours));+ let weight = 0;+ let sum = 0;+ const groups = new Map();+ for (const row of matured) {+ const w = 0.5 ** ((now - Date.parse(row.at)) / DAY / halfLifeDays);+ const outcome = outcomeOf(row);+ weight += w;+ sum += w * outcome;+ for (const key of attributeKeys(row)) {+ const group = groups.get(key) || { weight: 0, sum: 0, n: 0 };+ group.weight += w;+ group.sum += w * outcome;+ group.n += 1;+ groups.set(key, group);+ }+ }++ const lifts = {};+ for (const key of [...groups.keys()].sort()) {+ const group = groups.get(key);+ const rest = weight - group.weight;+ // A value every post carries has nothing to be compared against.+ const delta = group.weight > 0 && rest > 1e-12 ? group.sum / group.weight - (sum - group.sum) / rest : 0;+ const shrunk = group.n < MIN_VALUE_COUNT ? 0 : delta * (group.n / (group.n + shrinkK));+ lifts[key] = { delta: round(delta), n: group.n, shrunk: round(shrunk) };+ }+ return {+ learnedAt: new Date(now).toISOString(),+ sample: matured.length,+ baseline: round(weight > 0 ? sum / weight : 0),+ lifts,+ };+}++// ── Scoring a queued item ───────────────────────────────────────────────────++// The attributes overlap (a partner post is usually long and carries video), so+// adding them up would count one good post several times. The estimate is the+// strongest reason for the post, the strongest reason against it, and the+// average of whatever else was measured.+export function learnedScore(item, learned) {+ const found = attributeKeys(describeItem(item))+ .filter((key) => learned?.lifts?.[key])+ .map((key) => ({ key, shrunk: learned.lifts[key].shrunk, n: learned.lifts[key].n }));+ // A value seen on too few posts says nothing either way. Averaging its zero in+ // would pull every other signal toward no effect.+ const measured = found.filter((row) => row.n >= MIN_VALUE_COUNT).map((row) => row.shrunk);+ const best = Math.max(0, ...measured);+ const worst = Math.min(0, ...measured);+ const rest = [...measured];+ if (best > 0) rest.splice(rest.indexOf(best), 1);+ if (worst < 0) rest.splice(rest.indexOf(worst), 1);+ const mean = rest.length ? rest.reduce((a, b) => a + b, 0) / rest.length : 0;+ const points = LEARNED_POINTS_PER_UNIT * (best + worst + mean);+ return {+ points: round(Math.max(-LEARNED_POINTS_LIMIT, Math.min(LEARNED_POINTS_LIMIT, points)), 1),+ found: found.map(({ key, shrunk }) => ({ key, shrunk })),+ };+}diff --git a/api/_lib/x-content/priority.js b/api/_lib/x-content/priority.jsindex f46a04a90..f40a6cd66 100644--- a/api/_lib/x-content/priority.js+++ b/api/_lib/x-content/priority.js@@ -10,10 +10,19 @@// data/x-content/volume-model.json. Pool volume is what pays the// platform, so it outranks attention: it replaces the engagement// part whenever the model file is present-// engagement the fallback when there is no volume model: predicted lift from-// how @trythreews posts with the same signals actually performed+// learned how posts shaped like this one did on the live account, read+// back through the X API (outcomes.js): likes, bookmarks, and+// reposts of posts with the same media, length, link, thread,+// mentions, cashtag, lane, and pattern, against posts without.+// Added beside volume once LEARNED_MIN_SAMPLE posts have matured,+// and held between -15 and +15 so it informs the order without+// overruling the owner's boost+// engagement the fallback when there is neither a volume model nor a learned+// sample: predicted lift from the scraped archive// (data/x-archive/analysis), using the same format, length, and-// topic classifiers that produced the report+// topic classifiers that produced the report. The scrape lost the+// like counts of the account's biggest posts, so it is never used+// once the measured outcomes are there// timely a post with `expiresAt` rises as its window closes, and is// dropped once it has passed (stale news is worse than none)// boost the owner's explicit `priority` on the item, -50 to +50@@ -30,6 +39,7 @@ import { existsSync, readFileSync } from 'node:fs';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';const DAY = 24 * 60 * 60_000;// Prior strength for shrinkage: a signal measured on n posts keeps n / (n + K)@@ -82,6 +92,8 @@ export function volumeScore(item, model) {return { chance: 1 / (1 + Math.exp(-z)), found };}+// Synchronous and file based. The learned lifts come from the database, so the+// caller attaches them afterwards as `lifts.learned` (see runTick).export function loadLifts(root) {const path = resolve(root, ENGAGEMENT_REPORT);// The volume model rides along on the lifts map so every caller that already@@ -161,10 +173,12 @@ export function scoreItem(item, { lifts, published = [], quality = {}, review =const signals = engagementSignals(item, lifts);const predicted = Math.exp(combinedLog(signals));const volume = volumeScore(item, lifts?.volumeModel);+ const learned = lifts?.learned?.sample >= LEARNED_MIN_SAMPLE ? learnedScore(item, lifts.learned) : null;// Same scale as the engagement part it replaces: 10 points per doubling against// the average post, so the other parts keep their relative weight.if (volume) parts.volume = Math.round(10 * Math.log2(volume.chance / lifts.volumeModel.baseRate) * 10) / 10;- else parts.engagement = Math.round(10 * Math.log2(predicted) * 10) / 10;+ else if (!learned) parts.engagement = Math.round(10 * Math.log2(predicted) * 10) / 10;+ if (learned) parts.learned = learned.points;if (item.expiresAt) {const left = Date.parse(item.expiresAt) - now;@@ -192,7 +206,15 @@ export function scoreItem(item, { lifts, published = [], quality = {}, review =}const score = Math.round(Object.values(parts).reduce((sum, value) => sum + value, 0) * 10) / 10;- return { score, parts, signals, predictedLift: Math.round(predicted * 100) / 100, volumeChance: volume ? Math.round(volume.chance * 1000) / 1000 : null, volumeSignals: volume?.found || [] };+ return {+ score,+ parts,+ signals,+ predictedLift: Math.round(predicted * 100) / 100,+ volumeChance: volume ? Math.round(volume.chance * 1000) / 1000 : null,+ volumeSignals: volume?.found || [],+ learnedSignals: learned?.found || [],+ };}// Every ready candidate, best first. Ties go to the item that has been readydiff --git a/api/_lib/x-content/runner.js b/api/_lib/x-content/runner.jsindex 07c4178ab..78bf4b63d 100644--- a/api/_lib/x-content/runner.js+++ b/api/_lib/x-content/runner.js@@ -8,6 +8,10 @@// post in the same tick. Only failures that are not the post's fault (X is// down, rate-limited, or rejecting our credentials) stop the tick, because// every post would fail the same way; the next tick retries.+//+// A tick also keeps the learning loop turning (outcomes.js): it ranks with what+// the account's earlier posts measured, and once the publish attempt is over it+// reads the timeline again if the stored record has gone stale.import { loadQueue, validateQueue } from './queue.js';import { TIERS, pickDue, tierOf } from './schedule.js';@@ -15,6 +19,7 @@ import { loadLifts } from './priority.js';import { loadReview, contentHash } from './review.js';import { previewClient, publishItem, xClientFromEnv } from './publisher.js';import { itemTexts, linkChecks, probeChecks } from './verify.js';+import { collectOutcomes, learnLifts, outcomesAreStale, outcomesStore } from './outcomes.js';const HOUR = 60 * 60_000;// Tries per tick before giving up the slot: enough to skip a few broken posts,@@ -95,12 +100,55 @@ async function alertLowInventory(state, store, stock, now) {return summary;}+// ── Outcomes ────────────────────────────────────────────────────────────────+// Ranking reads whatever was last stored and never waits on X. A record that+// cannot be read is the same as none: the tick ranks without the learned part.+async function loadOutcomes(outcomes) {+ if (!outcomes) return null;+ try {+ return await outcomes.load();+ } catch (err) {+ console.warn('[x-content] outcomes load failed', err?.message || err);+ return null;+ }+}++// Runs after the publish attempt, so a slow timeline read cannot delay a post,+// and swallows its own failure, so it cannot turn a sent post into a failed tick.+async function refreshOutcomes({ outcomes, stored, collect, client, ledger, now }) {+ const sample = (rows) => learnLifts(rows, { now }).sample;+ if (!outcomes || !outcomesAreStale(stored, now)) return { refreshed: false, sample: sample(stored?.posts) };+ try {+ const fresh = await collect({ client, ledger, now });+ await outcomes.save(fresh);+ return { refreshed: true, sample: sample(fresh.posts) };+ } catch (err) {+ console.warn('[x-content] outcomes refresh failed', err?.message || err);+ return { refreshed: false, sample: sample(stored?.posts) };+ }+}+// `client` and `checks` default to the real X client and the real pre-flight;-// tests pass their own to drive the hold-and-fall-through path.-export async function runTick({ root, store, now = Date.now(), dryRun = true, requestedId = null, env = process.env, client: injectedClient = null, checks = preflight }) {+// tests pass their own to drive the hold-and-fall-through path. `outcomes` and+// `collect` default to the stored record and the real timeline read.+export async function runTick({+ root,+ store,+ now = Date.now(),+ dryRun = true,+ requestedId = null,+ env = process.env,+ client: injectedClient = null,+ checks = preflight,+ outcomes = env.DATABASE_URL ? outcomesStore() : null,+ collect = collectOutcomes,+}) {const queue = loadQueue(root);const state = await store.load();const { problems } = validateQueue(queue, root, { state });+ const stored = await loadOutcomes(outcomes);+ const learned = stored ? learnLifts(stored.posts, { now }) : null;+ const lifts = loadLifts(root);const blocked = (queue.items || []).filter((item) => item.status === 'approved' && problems[item.id]?.length)@@ -119,23 +167,38 @@ export async function runTick({ root, store, now = Date.now(), dryRun = true, reanyStatus: dryRun,// The queue is public; the minute a slot opens is not. See schedule.js.seed: env.X_CONTENT_SCHEDULE_SEED || null,- lifts: loadLifts(root),+ lifts: learned ? Object.assign(lifts || new Map(), { learned }) : lifts,reviews,};+ const unrefreshed = { refreshed: false, sample: learned?.sample || 0 };if (dryRun) {const decision = pickDue({ ...context, exclude: activeHolds(state, publishable, root, now) });- if (!decision.item) return { published: null, reason: decision.reason, blocked };+ if (!decision.item) return { published: null, reason: decision.reason, blocked, outcomes: unrefreshed };const client = previewClient();// Preview against a scratch copy: the real ledger must not change.const scratch = structuredClone(state);await publishItem({ item: decision.item, client, root, state: scratch, store: { save: async () => {} }, account: queue.account });- return { preview: { id: decision.item.id, kind: decision.item.kind, score: decision.score, parts: decision.parts, ranking: decision.ranking, calls: client.calls }, blocked };+ return { preview: { id: decision.item.id, kind: decision.item.kind, score: decision.score, parts: decision.parts, ranking: decision.ranking, calls: client.calls }, blocked, outcomes: unrefreshed };}const client = injectedClient || (await xClientFromEnv(env));- if (!client) return { published: null, skipped: 'not_configured', reason: 'X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are required', blocked };+ if (!client) return { published: null, skipped: 'not_configured', reason: 'X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET are required', blocked, outcomes: unrefreshed };++ // The tail runs whether the slot was filled, left empty, or the publish threw,+ // and adds `outcomes` to the result without touching the rest of it. A named+ // run is an operator sending one post by hand; it reads nothing back.+ let result;+ let report = unrefreshed;+ try {+ result = await fillSlot({ queue, state, store, root, now, requestedId, client, checks, context, publishable, blocked });+ } finally {+ if (!requestedId) report = await refreshOutcomes({ outcomes, stored, collect, client, ledger: state, now });+ }+ return { ...result, outcomes: report };+}+async function fillSlot({ queue, state, store, root, now, requestedId, client, checks, context, publishable, blocked }) {const stock = inventory(publishable, state, root, now);const lowStock = requestedId ? null : await alertLowInventory(state, store, stock, now).catch(() => null);diff --git a/package.json b/package.jsonindex 383813fae..6da77b93a 100644--- a/package.json+++ b/package.json@@ -210,6 +210,8 @@"x:content": "node scripts/x-content.mjs","x:content:check": "node scripts/x-content.mjs check","x:content:plan": "node scripts/x-content.mjs plan",+ "x:outcomes": "node scripts/x-outcomes.mjs",+ "x:bundle": "node scripts/x-bundle.mjs","changelog:push": "node scripts/changelog-telegram.mjs","changelog:push:x": "node scripts/changelog-x.mjs","tweet": "node scripts/post-tweet.mjs",diff --git a/scripts/x-outcomes.mjs b/scripts/x-outcomes.mjsnew file mode 100644index 000000000..0530a7d6b--- /dev/null+++ b/scripts/x-outcomes.mjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+// What the @trythreews posts actually did, and what the content queue has+// learned from it. The same engine runs inside every publishing tick of+// /api/cron/x-content (api/_lib/x-content/outcomes.js); this is the operator's+// view of it.+//+// node scripts/x-outcomes.mjs the learned table, then the best and worst posts+// node scripts/x-outcomes.mjs --refresh read the timeline from X first, and save it+// node scripts/x-outcomes.mjs --json the learned object as JSON+// node scripts/x-outcomes.mjs --compare pipeline posts against hand-sent ones, last 30 days+//+// Read only: it never posts. Env: reads .env.local then .env. DATABASE_URL gives+// it the stored outcomes and the publish ledger; X_API_KEY, X_API_SECRET,+// X_ACCESS_TOKEN, X_ACCESS_SECRET are needed only for --refresh, and are taken+// from the Cloud Run service when they are not in the local env files.++import { existsSync, readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++import { MIN_AGE_HOURS, attributeKeys, collectOutcomes, isMature, learnLifts, memoryOutcomesStore, outcomeOf, outcomesStore } from '../api/_lib/x-content/outcomes.js';+import { xClientFromEnv } from '../api/_lib/x-content/publisher.js';+import { dbStore, memoryStore } from '../api/_lib/x-content/state.js';++const root = resolve(fileURLToPath(new URL('..', import.meta.url)));+const DAY = 24 * 60 * 60_000;+const COMPARE_DAYS = 30;+const BEST = 10;+const WORST = 5;++function loadEnvFile(path) {+ if (!existsSync(path)) return;+ for (const line of readFileSync(path, 'utf8').split('\n')) {+ const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);+ if (match && !process.env[match[1]]) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');+ }+}+loadEnvFile(resolve(root, '.env.local'));+loadEnvFile(resolve(root, '.env'));++const args = process.argv.slice(2);+const has = (flag) => args.includes(`--${flag}`);++function fail(message) {+ console.error(message);+ process.exit(1);+}++// The four credentials of the @trythreews user context, taken from the Cloud+// Run service when they are not in the local env files.+const X_ENV = ['X_API_KEY', 'X_API_SECRET', 'X_ACCESS_TOKEN', 'X_ACCESS_SECRET'];++function hydrateXEnv() {+ if (!process.env.GOOGLE_CLOUD_PROJECT) process.env.GOOGLE_CLOUD_PROJECT = 'aerial-vehicle-466722-p5';+ for (const name of X_ENV.filter((key) => !process.env[key])) {+ const read = spawnSync(process.execPath, [resolve(root, 'scripts/read-service-env.mjs'), `^${name}$`, '--raw'], { cwd: root, encoding: 'utf8' });+ const value = read.status === 0 ? read.stdout.trim() : '';+ if (value) process.env[name] = value;+ }+}++const store = () => (process.env.DATABASE_URL ? outcomesStore() : memoryOutcomesStore());+const ledgerStore = () => (process.env.DATABASE_URL ? dbStore() : memoryStore());++async function refresh(outcomes) {+ hydrateXEnv();+ const client = await xClientFromEnv(process.env);+ if (!client) fail(`Reading the timeline needs ${X_ENV.join(', ')}.`);+ const ledger = await ledgerStore().load();+ let fresh;+ try {+ fresh = await collectOutcomes({ client, ledger });+ } catch (err) {+ // Nothing is saved from a read that stopped half way, so the stored record+ // is still the last complete one.+ fail(`X did not answer the timeline read (${err?.data?.title || err?.message || err}). The stored outcomes are unchanged; run it again in a minute.`);+ }+ await outcomes.save(fresh);+ return fresh;+}++// Rounded before the sign is chosen, so a lift of -0.004 prints as 0.00.+function signed(value, places = 2) {+ const rounded = Math.round(value * 10 ** places) / 10 ** places + 0;+ return `${rounded > 0 ? '+' : ''}${rounded.toFixed(places)}`;+}++const postUrl = (row) => `https://x.com/i/status/${row.id}`;++function describeRow(row) {+ const metrics = `${String(row.likes).padStart(5)} likes ${String(row.bookmarks).padStart(4)} saved ${String(row.reposts).padStart(4)} reposts ${String(row.impressions).padStart(7)} views`;+ return ` ${outcomeOf(row).toFixed(2).padStart(5)} ${row.at.slice(0, 10)} ${metrics} ${postUrl(row)}\n ${row.source} ${attributeKeys(row).join(' ')}`;+}++function printLearned(outcomes, learned, now) {+ console.log(`outcomes: ${outcomes.posts.length} head post(s), read ${outcomes.fetchedAt || 'never'}`);+ console.log(`sample: ${learned.sample} post(s) at least ${MIN_AGE_HOURS} hours old`);+ console.log(`baseline: ${learned.baseline.toFixed(2)} (log1p(likes) + 0.5 log1p(bookmarks) + 0.25 log1p(reposts), recency weighted)`);+ if (!learned.sample) {+ console.log('\nNothing has been measured yet. Run with --refresh to read the timeline from X.');+ return;+ }++ console.log('\nLift of each attribute value, against the posts without it:');+ console.log(` ${'value'.padEnd(26)} ${'shrunk'.padStart(7)} ${'raw'.padStart(7)} ${'n'.padStart(5)}`);+ const table = Object.entries(learned.lifts).sort(([a, left], [b, right]) => right.shrunk - left.shrunk || right.delta - left.delta || a.localeCompare(b));+ for (const [key, row] of table) {+ console.log(` ${key.padEnd(26)} ${signed(row.shrunk).padStart(7)} ${signed(row.delta).padStart(7)} ${String(row.n).padStart(5)}`);+ }++ const ranked = outcomes.posts.filter((row) => isMature(row, now)).sort((a, b) => outcomeOf(b) - outcomeOf(a));+ console.log(`\nBest ${Math.min(BEST, ranked.length)} of the window:`);+ for (const row of ranked.slice(0, BEST)) console.log(describeRow(row));+ const worst = ranked.slice(BEST).slice(-WORST);+ if (worst.length) {+ console.log(`\nWorst ${worst.length} of the window:`);+ for (const row of worst.reverse()) console.log(describeRow(row));+ }+}++function median(values) {+ if (!values.length) return null;+ const sorted = [...values].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;+}++function printCompare(outcomes, now) {+ const recent = outcomes.posts.filter((row) => now - Date.parse(row.at) <= COMPARE_DAYS * DAY);+ console.log(`Head posts of the last ${COMPARE_DAYS} days, read ${outcomes.fetchedAt || 'never'}. Medians:\n`);+ console.log(` ${'source'.padEnd(10)} ${'posts'.padStart(6)} ${'likes'.padStart(8)} ${'impressions'.padStart(12)} ${'bookmarks'.padStart(10)}`);+ for (const source of ['pipeline', 'hand']) {+ const rows = recent.filter((row) => row.source === source);+ const cell = (field) => (rows.length ? String(median(rows.map((row) => row[field]))) : 'none');+ console.log(` ${source.padEnd(10)} ${String(rows.length).padStart(6)} ${cell('likes').padStart(8)} ${cell('impressions').padStart(12)} ${cell('bookmarks').padStart(10)}`);+ }+ const young = recent.filter((row) => !isMature(row, now)).length;+ if (young) console.log(`\n${young} of these are under ${MIN_AGE_HOURS} hours old, so their counts are still rising.`);+ if (!recent.length) console.log('\nNothing has been measured yet. Run with --refresh to read the timeline from X.');+}++const outcomes = store();+const now = Date.now();+const record = has('refresh') ? await refresh(outcomes) : await outcomes.load();+const learned = learnLifts(record.posts, { now });++if (has('json')) console.log(JSON.stringify(learned, null, '\t'));+else if (has('compare')) printCompare(record, now);+else printLearned(record, learned, now);diff --git a/tests/x-content-outcomes.test.js b/tests/x-content-outcomes.test.jsnew file mode 100644index 000000000..5ce446382--- /dev/null+++ b/tests/x-content-outcomes.test.js@@ -0,0 +1,617 @@+import { describe, it, expect, vi } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import {+ HALF_LIFE_DAYS,+ LEARNED_MIN_SAMPLE,+ LEARNED_POINTS_LIMIT,+ MIN_AGE_HOURS,+ OUTCOMES_REFRESH_HOURS,+ SHRINK_K,+ attributeKeys,+ collectOutcomes,+ describeItem,+ describePost,+ isHeadPost,+ learnLifts,+ learnedScore,+ memoryOutcomesStore,+ outcomeOf,+ outcomesAreStale,+} from '../api/_lib/x-content/outcomes.js';+import { loadLifts, scoreItem } from '../api/_lib/x-content/priority.js';+import { runTick } from '../api/_lib/x-content/runner.js';+import { memoryStore } from '../api/_lib/x-content/state.js';+import { previewClient } from '../api/_lib/x-content/publisher.js';+import { contentHash, reviewPath } from '../api/_lib/x-content/review.js';++const root = process.cwd();+const HOUR = 3_600_000;+const DAY = 24 * HOUR;+const NOW = Date.parse('2026-09-17T16:50:00Z');++const metrics = (likes = 0, over = {}) => ({ like_count: likes, retweet_count: 0, quote_count: 0, reply_count: 0, bookmark_count: 0, impression_count: 0, ...over });+const tweet = (id, text, over = {}) => ({ id, text, created_at: '2026-09-01T12:00:00.000Z', conversation_id: id, public_metrics: metrics(), ...over });+const daysAgo = (days) => new Date(NOW - days * DAY).toISOString();+const row = (over = {}) => ({ id: '1', at: daysAgo(10), impressions: 0, likes: 0, reposts: 0, replies: 0, bookmarks: 0, media: 'none', length: 'band', link: 'none', thread: false, mentions: 0, cashtag: false, source: 'hand', ...over });++describe('describePost', () => {+ it('reads the whole copy of a long post from note_tweet', () => {+ const full = `${'A long build note about the rig pipeline. '.repeat(8)}https://t.co/full`;+ const post = tweet('10', `${full.slice(0, 270)}...`, {+ note_tweet: { text: full, entities: { urls: [{ url: 'https://t.co/full', expanded_url: 'https://three.ws/rig-doctor' }] } },+ });+ const described = describePost(post);+ expect(described.length).toBe('long');+ expect(described.link).toBe('head');+ });++ it('sorts a post into the length bucket its weighted length falls in', () => {+ const linked = (words) => tweet('11', `${'x'.repeat(words)} https://t.co/a`, { entities: { urls: [{ url: 'https://t.co/a', expanded_url: 'https://github.com/nirholas/three.ws' }] } });+ // Every URL weighs 23, whatever its real length.+ expect(describePost(linked(75)).length).toBe('short');+ expect(describePost(linked(76)).length).toBe('band');+ expect(describePost(linked(155)).length).toBe('band');+ expect(describePost(linked(156)).length).toBe('standard');+ expect(describePost(linked(256)).length).toBe('standard');+ expect(describePost(linked(257)).length).toBe('long');+ expect(describePost(tweet('12', 'Tom & Jerry')).length).toBe('short');+ });++ it('names the media kind, and lets a video outrank a still', () => {+ const mediaByKey = new Map([+ ['7_1', { media_key: '7_1', type: 'video' }],+ ['3_1', { media_key: '3_1', type: 'photo' }],+ ['16_1', { media_key: '16_1', type: 'animated_gif' }],+ ]);+ const kind = (keys) => describePost(tweet('20', 'A clip', { attachments: { media_keys: keys } }), { mediaByKey }).media;+ expect(kind(['7_1'])).toBe('video');+ expect(kind(['3_1'])).toBe('photo');+ expect(kind(['16_1'])).toBe('gif');+ expect(kind(['3_1', '7_1'])).toBe('video');+ expect(describePost(tweet('21', 'Words only')).media).toBe('none');+ });++ it('does not count the link X adds for media or for a quoted post', () => {+ const copy = 'x'.repeat(95);+ const media = tweet('30', `${copy} https://t.co/media`, {+ attachments: { media_keys: ['7_1'] },+ entities: { urls: [{ url: 'https://t.co/media', expanded_url: 'https://x.com/trythreews/status/30/video/1', media_key: '7_1' }] },+ });+ const described = describePost(media, { mediaByKey: new Map([['7_1', { type: 'video' }]]) });+ expect(described.link).toBe('none');+ // 95 characters of copy: the media link is not part of what was written.+ expect(described.length).toBe('short');++ const quote = tweet('31', 'The detail the first post left out https://t.co/quote', {+ referenced_tweets: [{ type: 'quoted', id: '9' }],+ entities: { urls: [{ url: 'https://t.co/quote', expanded_url: 'https://twitter.com/trythreews/status/9' }] },+ });+ expect(isHeadPost(quote)).toBe(true);+ expect(describePost(quote).link).toBe('none');+ });++ it('describes an Article by its title and cover, not by the bare link X returns for it', () => {+ const article = tweet('35', 'https://t.co/art', {+ entities: { urls: [{ url: 'https://t.co/art', expanded_url: 'https://x.com/i/article/2101755492414656512' }] },+ article: { title: 'Hold, do not spend: how $THREE gates the expensive lanes', cover_media: '3_35' },+ });+ expect(describePost(article)).toMatchObject({ media: 'photo', length: 'short', link: 'none', cashtag: true, mentions: 0 });+ });++ it('counts a three.ws link and an outside link the same way', () => {+ const linked = (expanded) => describePost(tweet('40', 'Read it https://t.co/a', { entities: { urls: [{ url: 'https://t.co/a', expanded_url: expanded }] } })).link;+ expect(linked('https://three.ws/genesis')).toBe('head');+ expect(linked('https://builder.aws.com/content/x')).toBe('head');+ });++ it('marks a head that the account answered itself as a thread', () => {+ const head = tweet('50', 'Part one');+ expect(describePost(head, { threadSizes: new Map([['50', 2]]) }).thread).toBe(true);+ expect(describePost(head, { threadSizes: new Map([['51', 2]]) }).thread).toBe(false);+ });++ it('counts mentions, spots the cashtag, and carries the metrics over', () => {+ const described = describePost(+ tweet('60', 'Now on @awscloud with @nvidia: the $three layer, mail [email protected]', {+ public_metrics: metrics(40, { retweet_count: 5, quote_count: 2, reply_count: 9, bookmark_count: 11, impression_count: 9000 }),+ }),+ );+ expect(described).toMatchObject({ id: '60', at: '2026-09-01T12:00:00.000Z', mentions: 2, cashtag: true, likes: 40, reposts: 7, replies: 9, bookmarks: 11, impressions: 9000 });+ expect(describePost(tweet('61', 'It costs $3 and $THREEFOLD is not us')).cashtag).toBe(false);+ });++ it('takes lane and pattern from the publish ledger, and only from there', () => {+ const pipelineById = new Map([['70', { id: 'genesis', lane: 'creation', pattern: 'proof' }]]);+ expect(describePost(tweet('70', 'Sent by the queue'), { pipelineById })).toMatchObject({ source: 'pipeline', lane: 'creation', pattern: 'proof' });+ const hand = describePost(tweet('71', 'Sent by hand'), { pipelineById });+ expect(hand.source).toBe('hand');+ expect(hand).not.toHaveProperty('lane');+ expect(hand).not.toHaveProperty('pattern');+ expect(attributeKeys(hand).some((key) => key.startsWith('lane:'))).toBe(false);+ });+});++describe('collectOutcomes', () => {+ // Two pages, served the way the twitter-api-v2 paginator serves them: the+ // second page and its media only exist once the iterator has asked for them.+ function timelineClient(pages) {+ const calls = [];+ return {+ calls,+ async me() {+ return { data: { id: '42', username: 'trythreews' } };+ },+ async userTimeline(id, options) {+ calls.push({ id, options });+ const media = [...pages[0].media];+ return {+ includes: { get media() { return media; } },+ async *[Symbol.asyncIterator]() {+ yield* pages[0].tweets;+ for (const page of pages.slice(1)) {+ calls.push({ page: 'next' });+ media.push(...page.media);+ yield* page.tweets;+ }+ },+ };+ },+ };+ }++ const reply = (id, conversation, to) => tweet(id, 'and another thing', { conversation_id: conversation, in_reply_to_user_id: to, referenced_tweets: [{ type: 'replied_to', id: conversation }] });+ const pages = [+ {+ media: [{ media_key: '7_1', type: 'video' }],+ tweets: [+ tweet('105', 'A clip of the rig', { attachments: { media_keys: ['7_1'] }, public_metrics: metrics(30) }),+ reply('104', '103', '42'),+ tweet('103', 'A thread starts here', { public_metrics: metrics(12) }),+ reply('102', '999', '7'),+ ],+ },+ {+ media: [{ media_key: '3_9', type: 'photo' }],+ tweets: [+ reply('101', '100', '7'),+ tweet('100', 'A still from the studio', { attachments: { media_keys: ['3_9'] }, public_metrics: metrics(4) }),+ tweet('99', 'RT @someone: hello', { referenced_tweets: [{ type: 'retweeted', id: '5' }] }),+ ],+ },+ ];+ const ledger = { published: [{ id: 'studio-still', lane: 'creation', pattern: 'proof', postIds: ['100'], url: 'https://x.com/trythreews/status/100' }] };++ it('credits the queue with an Article and with the post that quotes it', async () => {+ const quoting = tweet('201', 'The long version is up', { referenced_tweets: [{ type: 'quoted', id: '200' }] });+ const article = tweet('200', 'https://t.co/art', { article: { title: 'How rigs get named', cover_media: '3_200' } });+ const client = timelineClient([{ media: [], tweets: [quoting, article] }]);+ const sent = { published: [{ id: 'rig-names', kind: 'article', lane: 'article', pattern: 'longform', postIds: ['201'], articlePostId: '200', url: 'https://x.com/trythreews/status/200' }] };+ const outcomes = await collectOutcomes({ client, ledger: sent, now: NOW });+ expect(outcomes.posts.map((post) => [post.id, post.source, post.lane])).toEqual([['201', 'pipeline', 'article'], ['200', 'pipeline', 'article']]);+ });++ it('pages the whole timeline and keeps one row per head post', async () => {+ const client = timelineClient(pages);+ const outcomes = await collectOutcomes({ client, ledger, now: NOW });++ expect(client.calls.filter((call) => call.page === 'next')).toHaveLength(1);+ const [{ id, options }] = client.calls;+ expect(id).toBe('42');+ expect(options).toMatchObject({ max_results: 100, exclude: ['retweets'], start_time: '2026-06-19T16:50:00Z', expansions: ['attachments.media_keys'], 'media.fields': ['type'] });+ expect(options['tweet.fields']).toEqual(expect.arrayContaining(['public_metrics', 'created_at', 'referenced_tweets', 'attachments', 'entities', 'note_tweet', 'conversation_id']));++ expect(outcomes.fetchedAt).toBe(new Date(NOW).toISOString());+ expect(outcomes.posts.map((post) => post.id)).toEqual(['105', '103', '100']);+ expect(outcomes.posts.map((post) => post.media)).toEqual(['video', 'none', 'photo']);+ // 103 was answered by the account itself; 100 only by the account answering+ // somebody else, which is a reply and not a second part.+ expect(outcomes.posts.map((post) => post.thread)).toEqual([false, true, false]);+ expect(outcomes.posts[2]).toMatchObject({ source: 'pipeline', lane: 'creation', pattern: 'proof', likes: 4 });+ expect(outcomes.posts[0].source).toBe('hand');+ });++ it('leaves out a reply that X returned without its reference', async () => {+ // A degraded read: the reply arrives with no `referenced_tweets`. Its+ // conversation still belongs to another post, so it is not a head.+ const bare = tweet('104', '@someone so exciting', { conversation_id: '103' });+ const unplaced = tweet('98', 'No conversation at all', { conversation_id: undefined });+ const answered = tweet('97', '@someone agreed', { in_reply_to_user_id: '7' });+ const client = timelineClient([{ media: [], tweets: [bare, tweet('103', 'A real head'), unplaced, answered] }]);+ const outcomes = await collectOutcomes({ client, ledger, now: NOW });+ expect(outcomes.posts.map((post) => post.id)).toEqual(['103']);+ // Nothing says the account wrote 104 to itself, so it is not a second part.+ expect(outcomes.posts[0].thread).toBe(false);+ expect([bare, unplaced, answered].map(isHeadPost)).toEqual([false, false, false]);+ });++ it('starts the read again when X fails part way, and gives up on a refusal', async () => {+ const flaky = timelineClient(pages);+ const timeline = flaky.userTimeline;+ let reads = 0;+ flaky.userTimeline = async (id, options) => {+ const paged = await timeline(id, options);+ if (++reads > 1) return paged;+ return {+ includes: paged.includes,+ async *[Symbol.asyncIterator]() {+ yield* pages[0].tweets;+ throw Object.assign(new Error('Service Unavailable'), { code: 503 });+ },+ };+ };+ const outcomes = await collectOutcomes({ client: flaky, ledger, now: NOW, retryDelayMs: 0 });+ expect(reads).toBe(2);+ expect(outcomes.posts.map((post) => post.id)).toEqual(['105', '103', '100']);++ const down = timelineClient(pages);+ down.userTimeline = vi.fn(async () => {+ throw Object.assign(new Error('Service Unavailable'), { code: 503 });+ });+ await expect(collectOutcomes({ client: down, now: NOW, attempts: 3, retryDelayMs: 0 })).rejects.toThrow('Service Unavailable');+ expect(down.userTimeline).toHaveBeenCalledTimes(3);++ const refused = timelineClient(pages);+ refused.userTimeline = vi.fn(async () => {+ throw Object.assign(new Error('Too Many Requests'), { code: 429 });+ });+ await expect(collectOutcomes({ client: refused, now: NOW, retryDelayMs: 0 })).rejects.toThrow('Too Many Requests');+ expect(refused.userTimeline).toHaveBeenCalledTimes(1);+ });++ it('stops reading at the limit', async () => {+ const client = timelineClient(pages);+ const outcomes = await collectOutcomes({ client, ledger, now: NOW, limit: 3 });+ expect(outcomes.posts.map((post) => post.id)).toEqual(['105', '103']);+ expect(client.calls.filter((call) => call.page === 'next')).toHaveLength(0);+ });++ it('calls a record stale once it is older than the refresh interval, or missing', () => {+ expect(outcomesAreStale({ fetchedAt: null, posts: [] }, NOW)).toBe(true);+ expect(outcomesAreStale(null, NOW)).toBe(true);+ expect(outcomesAreStale({ fetchedAt: new Date(NOW - (OUTCOMES_REFRESH_HOURS + 1) * HOUR).toISOString() }, NOW)).toBe(true);+ expect(outcomesAreStale({ fetchedAt: new Date(NOW - (OUTCOMES_REFRESH_HOURS - 1) * HOUR).toISOString() }, NOW)).toBe(false);+ });+});++describe('learnLifts', () => {+ it('scores a post on likes, bookmarks, and reposts, and ignores replies', () => {+ const base = row({ likes: 20, bookmarks: 6, reposts: 3 });+ expect(outcomeOf(base)).toBeCloseTo(Math.log1p(20) + 0.5 * Math.log1p(6) + 0.25 * Math.log1p(3), 10);+ expect(outcomeOf({ ...base, replies: 500 })).toBe(outcomeOf(base));+ });++ it('leaves out posts too young for their counts to have settled', () => {+ const rows = [+ row({ id: 'a', at: new Date(NOW - (MIN_AGE_HOURS - 1) * HOUR).toISOString(), likes: 900 }),+ row({ id: 'b', at: new Date(NOW - MIN_AGE_HOURS * HOUR).toISOString(), likes: 5 }),+ row({ id: 'c', at: daysAgo(9), likes: 5 }),+ ];+ const learned = learnLifts(rows, { now: NOW });+ expect(learned.sample).toBe(2);+ expect(learned.baseline).toBeCloseTo(Math.log1p(5), 4);+ expect(learned.learnedAt).toBe(new Date(NOW).toISOString());+ expect(learnLifts(rows, { now: NOW, minAgeHours: 1 }).sample).toBe(3);+ });++ it('weights a recent post above an old one', () => {+ // One half-life apart: the old video counts half as much as the new one.+ const rows = [+ row({ id: 'new', at: daysAgo(HALF_LIFE_DAYS), media: 'video', likes: 100 }),+ row({ id: 'old', at: daysAgo(2 * HALF_LIFE_DAYS), media: 'video', likes: 0 }),+ row({ id: 'p1', at: daysAgo(HALF_LIFE_DAYS), media: 'photo', likes: 0 }),+ row({ id: 'p2', at: daysAgo(HALF_LIFE_DAYS), media: 'photo', likes: 0 }),+ ];+ const learned = learnLifts(rows, { now: NOW });+ const video = (0.5 * Math.log1p(100) + 0.25 * 0) / 0.75;+ expect(learned.lifts['media:video'].delta).toBeCloseTo(video, 4);+ expect(learned.lifts['media:photo'].delta).toBeCloseTo(-video, 4);+ expect(learned.baseline).toBeCloseTo((0.5 * Math.log1p(100)) / 1.75, 4);+ // An unweighted mean would have put the video lift at half the top post.+ expect(learned.lifts['media:video'].delta).toBeGreaterThan(Math.log1p(100) / 2);+ });++ it('shrinks a difference by how few posts it was measured on', () => {+ const rows = [+ ...[1, 2, 3, 4].map((n) => row({ id: `v${n}`, media: 'video', likes: 50 })),+ ...[1, 2, 3, 4, 5, 6].map((n) => row({ id: `p${n}`, media: 'photo', likes: 10 })),+ ];+ const learned = learnLifts(rows, { now: NOW });+ const delta = Math.log1p(50) - Math.log1p(10);+ expect(learned.lifts['media:video']).toEqual({ delta: expect.closeTo(delta, 4), n: 4, shrunk: expect.closeTo(delta * (4 / (4 + SHRINK_K)), 4) });+ expect(learned.lifts['media:photo']).toEqual({ delta: expect.closeTo(-delta, 4), n: 6, shrunk: expect.closeTo(-delta * (6 / (6 + SHRINK_K)), 4) });+ expect(learnLifts(rows, { now: NOW, shrinkK: 0 }).lifts['media:video'].shrunk).toBeCloseTo(delta, 4);+ // Every post shares these values, so there is nothing to compare against.+ expect(learned.lifts['cashtag:false']).toEqual({ delta: 0, n: 10, shrunk: 0 });+ });++ it('reports a value seen on fewer than three posts without letting it move a score', () => {+ const rows = [+ ...[1, 2].map((n) => row({ id: `g${n}`, media: 'gif', likes: 400 })),+ ...[1, 2, 3].map((n) => row({ id: `v${n}`, media: 'video', likes: 400 })),+ ...[1, 2, 3, 4, 5].map((n) => row({ id: `p${n}`, media: 'photo', likes: 2 })),+ ];+ const learned = learnLifts(rows, { now: NOW });+ expect(learned.lifts['media:gif'].n).toBe(2);+ expect(learned.lifts['media:gif'].delta).toBeGreaterThan(1);+ expect(learned.lifts['media:gif'].shrunk).toBe(0);+ expect(learned.lifts['media:video'].shrunk).toBeGreaterThan(0);+ });++ it('groups mentions, and measures lane and pattern on pipeline posts only', () => {+ const rows = [+ row({ id: 'a', mentions: 0 }),+ row({ id: 'b', mentions: 1 }),+ row({ id: 'c', mentions: 2 }),+ row({ id: 'd', mentions: 5, source: 'pipeline', lane: 'creation', pattern: 'proof' }),+ row({ id: 'e', lane: 'creation', pattern: 'proof' }),+ ];+ const { lifts } = learnLifts(rows, { now: NOW });+ expect(lifts['mentions:0'].n).toBe(2);+ expect(lifts['mentions:1'].n).toBe(1);+ expect(lifts['mentions:2+'].n).toBe(2);+ expect(lifts['lane:creation'].n).toBe(1);+ expect(lifts['pattern:proof'].n).toBe(1);+ });+});++describe('learnedScore', () => {+ const item = (over = {}) => ({+ id: 'x', kind: 'post', lane: 'creation', pattern: 'proof',+ posts: [{ text: 'Genesis turns a sentence into a rigged 3D agent on @solana with $THREE perks, and it walks on arrival: three.ws/genesis', media: [{ path: 'public/x-media/t/clip.mp4' }] }, { text: 'More in the docs.' }],+ ...over,+ });+ const lift = (shrunk, n = 10) => ({ delta: shrunk * 2, n, shrunk });+ const learned = (lifts) => ({ learnedAt: new Date(NOW).toISOString(), sample: 40, baseline: 2, lifts });++ it('describes a queued item in the vocabulary of the measured posts', () => {+ expect(describeItem(item())).toEqual({ media: 'video', length: 'band', link: 'head', thread: true, mentions: 1, cashtag: true, source: 'pipeline', lane: 'creation', pattern: 'proof' });+ const quiet = item({ posts: [{ text: 'A short note.', media: [{ path: 'public/x-media/t/a.png' }] }] });+ expect(describeItem(quiet)).toMatchObject({ media: 'photo', length: 'short', link: 'none', thread: false, mentions: 0, cashtag: false });+ expect(describeItem(item({ posts: [{ text: 'Looping', media: [{ path: 'public/x-media/t/loop.gif' }] }] })).media).toBe('gif');+ });++ it('describes a queued Article the way its own post will be measured', () => {+ const article = item({+ kind: 'article', lane: 'article', pattern: 'longform',+ article: { title: 'Hold, do not spend: how $THREE gates the expensive lanes', body: 'data/x-content/articles/hold.md', cover: { path: 'public/x-media/t/a.png' } },+ posts: [{ text: 'The long version, with the 402 you get when you do not hold, on @solana: three.ws/three' }, { text: 'And a second quote.' }],+ });+ expect(describeItem(article)).toEqual({ media: 'photo', length: 'short', link: 'none', thread: false, mentions: 0, cashtag: true, source: 'pipeline', lane: 'article', pattern: 'longform' });+ });++ it('treats a link that sits in a reply as no link on the head', () => {+ const replyLink = item({ posts: [{ text: 'The head says what shipped and leaves the address for the reply below.' }, { text: 'three.ws/genesis' }] });+ expect(describeItem(replyLink).link).toBe('none');+ expect(describeItem(replyLink).thread).toBe(true);+ });++ it('adds the best and the worst signal to the mean of the rest, without stacking them', () => {+ const scored = learnedScore(item(), learned({+ 'media:video': lift(0.6),+ 'length:band': lift(0.2),+ 'link:head': lift(-0.4),+ 'thread:true': lift(0.1),+ 'mentions:1': lift(-0.1),+ 'cashtag:true': lift(0.3),+ 'media:photo': lift(-0.9),+ }));+ expect(scored.found.map((entry) => entry.key)).toEqual(['media:video', 'length:band', 'link:head', 'thread:true', 'mentions:1', 'cashtag:true']);+ expect(scored.found[0]).toEqual({ key: 'media:video', shrunk: 0.6 });+ // 0.6 for, 0.4 against, and the rest average (0.2 + 0.1 - 0.1 + 0.3) / 4.+ expect(scored.points).toBe(Math.round(10 * (0.6 - 0.4 + 0.125) * 10) / 10);+ expect(scored.points).toBeLessThan(10 * (0.6 + 0.2 + 0.1 + 0.3));+ });++ it('uses the single signal it has, and scores nothing when it has none', () => {+ expect(learnedScore(item(), learned({ 'media:video': lift(0.5) })).points).toBe(5);+ expect(learnedScore(item(), learned({ 'link:head': lift(-0.5) })).points).toBe(-5);+ expect(learnedScore(item(), learned({ 'media:video': lift(0.5), 'cashtag:true': lift(0.2) })).points).toBe(7);+ expect(learnedScore(item(), learned({}))).toEqual({ points: 0, found: [] });+ expect(learnedScore(item(), null)).toEqual({ points: 0, found: [] });+ });++ it('lists a thinly measured value without letting it dilute the others', () => {+ const scored = learnedScore(item(), learned({+ 'media:video': lift(0.6),+ 'cashtag:true': lift(0.2),+ 'lane:creation': { delta: 1.4, n: 1, shrunk: 0 },+ 'pattern:proof': { delta: -0.8, n: 2, shrunk: 0 },+ }));+ expect(scored.found.map((entry) => entry.key)).toEqual(['media:video', 'cashtag:true', 'lane:creation', 'pattern:proof']);+ expect(scored.points).toBe(8);+ });++ it('clamps the points on both sides', () => {+ expect(learnedScore(item(), learned({ 'media:video': lift(4), 'cashtag:true': lift(3) })).points).toBe(LEARNED_POINTS_LIMIT);+ expect(learnedScore(item(), learned({ 'media:video': lift(-4), 'cashtag:true': lift(-3) })).points).toBe(-LEARNED_POINTS_LIMIT);+ });+});++describe('scoreItem with learned lifts', () => {+ const now = Date.parse('2026-09-17T00:00:00Z');+ const post = { id: 'x', kind: 'post', lane: 'l', pattern: 'p', notBefore: '2026-09-17T00:00:00Z', posts: [{ text: 'The $THREE layer, on @awscloud: three.ws/x', media: [{ path: 'public/x.webp' }] }] };+ const learned = (sample) => ({ learnedAt: new Date(now).toISOString(), sample, baseline: 2, lifts: { 'media:photo': { delta: 0.5, n: 30, shrunk: 0.4 }, 'cashtag:true': { delta: -0.3, n: 12, shrunk: -0.2 } } });+ const attach = (extra) => Object.assign(new Map(loadLifts(root)), { volumeModel: null, ...extra });++ it('adds the learned part and drops the archive estimate once the sample is large enough', () => {+ const scored = scoreItem(post, { lifts: attach({ learned: learned(LEARNED_MIN_SAMPLE) }), now });+ expect(scored.parts.learned).toBe(2);+ expect(scored.parts.engagement).toBeUndefined();+ expect(scored.score).toBe(2);+ expect(scored.learnedSignals).toEqual([{ key: 'media:photo', shrunk: 0.4 }, { key: 'cashtag:true', shrunk: -0.2 }]);+ });++ it('keeps the volume part in front, with the learned part beside it', () => {+ const lifts = Object.assign(loadLifts(root), { learned: learned(60) });+ const scored = scoreItem(post, { lifts, now });+ const alone = scoreItem(post, { lifts: loadLifts(root), now });+ expect(scored.parts.volume).toBe(alone.parts.volume);+ expect(scored.parts.learned).toBe(2);+ expect(scored.parts.engagement).toBeUndefined();+ expect(scored.score).toBeCloseTo(alone.score + 2, 5);+ });++ it('ranks the old way while the sample is too small, or missing', () => {+ const before = scoreItem(post, { lifts: attach({}), now });+ expect(before.parts.engagement).toBeGreaterThan(0);+ expect(before.learnedSignals).toEqual([]);++ const thin = scoreItem(post, { lifts: attach({ learned: learned(LEARNED_MIN_SAMPLE - 1) }), now });+ expect(thin.parts).toEqual(before.parts);+ expect(thin.parts.learned).toBeUndefined();+ expect(thin.score).toBe(before.score);++ const withModel = scoreItem(post, { lifts: Object.assign(loadLifts(root), { learned: learned(3) }), now });+ expect(withModel.parts).toEqual(scoreItem(post, { lifts: loadLifts(root), now }).parts);+ expect(scoreItem(post, { lifts: null, now }).parts.learned).toBeUndefined();+ });+});++describe('runTick and the outcomes loop', () => {+ const cadence = { windowMinutes: 45, minimumMinutesApart: 240, dailyCap: 3, slots: [{ tier: 3, at: '08:00' }, { tier: 1, at: '16:00' }, { tier: 2, at: '22:00' }] };+ const texts = {+ rigged: 'Rig Doctor names the skeleton convention of a humanoid GLB in the browser and lists the joints that stay frozen: three.ws/rig-doctor',+ priced: 'Materialize measures the true solid volume of a repaired mesh and prices a physical print from that measurement: three.ws/materialize',+ };++ function sandbox() {+ const dir = mkdtempSync(join(tmpdir(), 'x-outcomes-'));+ mkdirSync(join(dir, 'data/x-content/reviews'), { recursive: true });+ const items = Object.entries(texts).map(([id, text], index) => ({+ id, status: 'approved', kind: 'post', tier: 1, lane: id, pattern: id, priority: 20 - index * 20,+ notBefore: '2026-09-17T00:00:00Z', textOnly: true, posts: [{ text }],+ }));+ for (const item of items) {+ writeFileSync(join(dir, reviewPath(item.id)), JSON.stringify({ id: item.id, contentHash: contentHash(item, dir), reviewedAt: '2026-09-17T00:00:00Z', passed: true, blockers: [] }));+ }+ writeFileSync(join(dir, 'data/x-content/queue.json'), JSON.stringify({ account: 'trythreews', cadence, items }));+ return dir;+ }++ // Posts of the queue's own length did well; short ones did not.+ const measured = [+ ...Array.from({ length: 12 }, (_, n) => row({ id: `b${n}`, at: daysAgo(5 + n), length: 'band', likes: 80 })),+ ...Array.from({ length: 12 }, (_, n) => row({ id: `s${n}`, at: daysAgo(5 + n), length: 'short', likes: 3 })),+ ];+ const stale = () => memoryOutcomesStore({ fetchedAt: new Date(NOW - (OUTCOMES_REFRESH_HOURS + 1) * HOUR).toISOString(), posts: measured });+ const recorder = () => {+ const events = [];+ const client = previewClient();+ const send = client.tweet;+ client.tweet = async (payload) => {+ events.push('tweet');+ return send(payload);+ };+ return { events, client };+ };+ const noChecks = async () => [];++ it('ranks with the learned lifts, and reads nothing from X on a dry run', async () => {+ const outcomes = stale();+ const collect = vi.fn();+ const result = await runTick({ root: sandbox(), store: memoryStore(), dryRun: true, now: NOW, env: {}, outcomes, collect });+ expect(result.preview.id).toBe('rigged');+ expect(result.preview.parts.learned).toBeGreaterThan(0);+ expect(result.preview.parts.engagement).toBeUndefined();+ expect(result.preview.parts.learned).toBe(learnedScore({ lane: 'rigged', pattern: 'rigged', posts: [{ text: texts.rigged }] }, learnLifts(measured, { now: NOW })).points);+ expect(result.outcomes).toEqual({ refreshed: false, sample: 24 });+ expect(collect).not.toHaveBeenCalled();+ expect((await outcomes.load()).posts).toHaveLength(24);+ });++ it('ranks the old way when there is no outcomes store', async () => {+ const result = await runTick({ root: sandbox(), store: memoryStore(), dryRun: true, now: NOW, env: {} });+ expect(result.preview.parts.learned).toBeUndefined();+ expect(result.preview.parts.engagement).toBe(0);+ expect(result.outcomes).toEqual({ refreshed: false, sample: 0 });+ });++ it('refreshes stale outcomes once the post is out', async () => {+ const outcomes = stale();+ const { events, client } = recorder();+ const fresh = { fetchedAt: new Date(NOW).toISOString(), posts: [...measured, row({ id: 'n1', at: daysAgo(3) })] };+ const collect = vi.fn(async ({ ledger }) => {+ events.push(`collect after ${ledger.published.map((entry) => entry.id).join(',')}`);+ return fresh;+ });+ const result = await runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: NOW, env: {}, client, checks: noChecks, outcomes, collect });++ expect(result.published.id).toBe('rigged');+ expect(result.published.slot).toBe('2026-09-17#1');+ expect(events).toEqual(['tweet', 'collect after rigged']);+ expect(collect).toHaveBeenCalledTimes(1);+ expect(collect.mock.calls[0][0]).toMatchObject({ client, now: NOW });+ expect(result.outcomes).toEqual({ refreshed: true, sample: 25 });+ expect(await outcomes.load()).toEqual(fresh);+ });++ it('refreshes on a tick that had nothing to send, and leaves fresh outcomes alone', async () => {+ const quiet = Date.parse('2026-09-17T13:00:00Z');+ const outcomes = memoryOutcomesStore({ fetchedAt: null, posts: [] });+ const collect = vi.fn(async ({ now }) => ({ fetchedAt: new Date(now).toISOString(), posts: measured }));+ const first = await runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: quiet, env: {}, client: previewClient(), checks: noChecks, outcomes, collect });+ expect(first.published).toBeNull();+ expect(first.reason).toMatch(/no slot is open/);+ expect(first.outcomes.refreshed).toBe(true);++ const second = await runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: quiet + HOUR, env: {}, client: previewClient(), checks: noChecks, outcomes, collect });+ expect(second.outcomes.refreshed).toBe(false);+ expect(collect).toHaveBeenCalledTimes(1);+ });++ it('still reports the post as sent when the refresh throws', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const outcomes = stale();+ const store = memoryStore();+ const collect = vi.fn(async () => {+ throw new Error('Too Many Requests');+ });+ const result = await runTick({ root: sandbox(), store, dryRun: false, now: NOW, env: {}, client: previewClient(), checks: noChecks, outcomes, collect });++ expect(result.published.id).toBe('rigged');+ expect(result.outcomes).toEqual({ refreshed: false, sample: 24 });+ expect((await store.load()).published.map((entry) => entry.id)).toEqual(['rigged']);+ expect(warn).toHaveBeenCalledWith('[x-content] outcomes refresh failed', 'Too Many Requests');+ expect((await outcomes.load()).posts).toHaveLength(24);+ } finally {+ warn.mockRestore();+ }+ });++ it('ranks without the learned part when the stored outcomes cannot be read', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const broken = { load: async () => { throw new Error('connection refused'); }, save: vi.fn() };+ const result = await runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: NOW, env: {}, client: previewClient(), checks: noChecks, outcomes: broken, collect: async () => ({ fetchedAt: new Date(NOW).toISOString(), posts: measured }) });+ expect(result.published.id).toBe('rigged');+ expect(warn).toHaveBeenCalledWith('[x-content] outcomes load failed', 'connection refused');+ expect(broken.save).toHaveBeenCalledTimes(1);+ } finally {+ warn.mockRestore();+ }+ });++ it('does not refresh for a post an operator sends by name', async () => {+ const collect = vi.fn();+ const result = await runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: NOW, env: {}, requestedId: 'priced', client: previewClient(), checks: noChecks, outcomes: stale(), collect });+ expect(result.published.id).toBe('priced');+ expect(result.outcomes).toEqual({ refreshed: false, sample: 24 });+ expect(collect).not.toHaveBeenCalled();+ });++ it('lets an account-wide failure through unchanged, after the refresh has run', async () => {+ const outcomes = stale();+ const down = previewClient();+ down.tweet = async () => {+ throw Object.assign(new Error('Service Unavailable'), { code: 503 });+ };+ const collect = vi.fn(async ({ now }) => ({ fetchedAt: new Date(now).toISOString(), posts: measured.slice(0, 5) }));+ await expect(runTick({ root: sandbox(), store: memoryStore(), dryRun: false, now: NOW, env: {}, client: down, checks: noChecks, outcomes, collect })).rejects.toThrow('Service Unavailable');+ expect(collect).toHaveBeenCalledTimes(1);+ expect((await outcomes.load()).posts).toHaveLength(5);+ });+});