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): add the archive importer and the engagement analysis of the account timeline

nirholas357368d26eba
diff --git a/docs/x-archive/trythreews-engagement.md b/docs/x-archive/trythreews-engagement.md
new file mode 100644
index 000000000..761747e7e
--- /dev/null
+++ b/docs/x-archive/trythreews-engagement.md
@@ -0,0 +1,237 @@
+# @trythreews: what actually lands on X
+
+Generated by `npm run x:archive:analyze` from the post archive in [data/x-archive/](../../data/x-archive/). Do not hand-edit: rerun the script after the next scrape.
+
+- **Source:** archive files (data/x-archive/trythreews-2026-08-14.json)
+- **Generated:** 2026-08-14T06:08:05.394Z
+- **Corpus:** 214 posts written by @trythreews, 2026-04-29 to 2026-08-12. 145 reposts and quotes of other accounts are archived but excluded from every number below: they carry the original author's engagement, not ours.
+- **Engagements** here means likes + reposts + replies. Views measure delivery, engagements measure whether anyone cared.
+- **View counts are rounded by X itself** past 999 ("6.3K"), so every rate below carries about two significant figures. Exact counts under 1,000 are exact.
+
+## Headline
+
+| Metric | Value |
+|---|---:|
+| Posts analyzed | 214 |
+| Total likes | 3,451 |
+| Total reposts | 899 |
+| Total replies | 1,141 |
+| Total views (approx) | 1,380,518 |
+| Median engagements per post | 12 |
+| Mean engagements per post | 25.7 |
+| p75 / p90 / p99 | 29 / 62 / 266 |
+| Best post | 359 |
+| Median engagement rate | 1.37% of views (214 posts with a view count) |
+| Share of engagement from the top 10% of posts | 49.2% |
+
+## The read-off
+
+- **Names $THREE** carries: 6 posts at a median 44 engagements (3.67x the corpus median) against 11 for the 208 without it.
+- **Has an image** carries: 41 posts at a median 25 engagements (2.08x the corpus median) against 10 for the 173 without it.
+- **Mentions an account** carries: 45 posts at a median 22 engagements (1.83x the corpus median) against 10 for the 169 without it.
+- **Is a reply** costs: 17 posts at a median 5 (0.42x) against 12 without.
+- **Text only** costs: 149 posts at a median 10 (0.83x) against 16 without.
+- Best-performing subject: **Industry commentary** (6 posts, median 46, 3.79x). Weakest: **Other** (143 posts, median 10, 0.83x).
+- Best length band: **100-179 chars** (24 posts, 1.88x). Worst: **1-99 chars** (0.75x).
+- Strongest posting hour: **01:00 UTC** (5 posts, 3.50x). Weakest: **06:00 UTC** (0.38x).
+- Concentration: the top 10% of posts earn **49.2%** of all engagement. Median post: 12 engagements; p90: 62; best: 359.
+
+## Top 15 posts by engagement
+
+| Date | Post | Likes | RT | Replies | Eng. | Signals |
+|---|---|---:|---:|---:|---:|---|
+| 2026-08-07 | [Today: The first in-world meetup of the http:// Three.ws User Group hosted by @IBM Open h…](https://x.com/trythreews/status/2085684765286637618) | 228 | 90 | 41 | 359 | video, @1, token, avatar |
+| 2026-05-13 | [We just reverse engineered the @pumpfun agent payments SDK Your AI doesn't just execute t…](https://x.com/trythreews/status/2054675701132132736) | 0 | 201 | 92 | 293 | video, @1, avatar, agent, payments |
+| 2026-08-12 | [three․ws is now verified on @fomo What that means in practice: search THREE in the fomo a…](https://x.com/trythreews/status/2087646652056432688) | 187 | 63 | 16 | 266 | image, @1, token, partner |
+| 2026-06-04 | [MCP Servers are live on the official @AnthropicAI MCP Registry https:// registry.modelcon…](https://x.com/trythreews/status/2062326562775531744) | 202 | 27 | 12 | 241 | text, @1, reply, agent |
+| 2026-06-22 | [Important links from the video ▸ Try the modal live (real 402 → sign → settle) https:// t…](https://x.com/trythreews/status/2068961439465796028) | 139 | 49 | 9 | 197 | card, @1, agent, payments |
+| 2026-06-25 | [More co-marketing with IBM coming](https://x.com/trythreews/status/2069961582759829808) | 114 | 43 | 11 | 168 | text, other |
+| 2026-07-08 | [For the developers: Did you know we have 70+ packages on npm? three-ws/tour https:// npmj…](https://x.com/trythreews/status/2074761553346478138) | 82 | 27 | 2 | 111 | image, @2, avatar, agent, payments, shipping |
+| 2026-07-08 | [http:// three.ws/tour http:// three.ws/walk https:// three.ws/tour-builder http:// three.…](https://x.com/trythreews/status/2074759891357745160) | 69 | 19 | 4 | 92 | text, other |
+| 2026-07-28 | [Thank you @solana @OpenAI and all of our partners, community members, and developers that…](https://x.com/trythreews/status/2082234618842079558) | 73 | 13 | 4 | 90 | text, @2, partner |
+| 2026-07-16 | [](https://x.com/trythreews/status/2077891066762756376) | 72 | 18 | n/a | 90 | card, other |
+| 2026-06-16 | [with on-chain reputation, know you are transacting with good ai just as you would any ser…](https://x.com/trythreews/status/2066782180492390665) | 76 | 11 | 1 | 88 | text, other |
+| 2026-06-22 | [Give your agents access to money We just shipped a drop-in payment modal for any x402 pai…](https://x.com/trythreews/status/2068951336918638699) | 0 | 0 | 84 | 84 | video, agent, payments, shipping, commentary |
+| 2026-06-06 | [Can't wait](https://x.com/trythreews/status/2063249039316140141) | 71 | 6 | 2 | 79 | text, other |
+| 2026-07-05 | [hello @elonmusk](https://x.com/trythreews/status/2073812694600384788) | 58 | 8 | 5 | 71 | text, @1, other |
+| 2026-07-28 | [http:// three.ws has been named an OpenAI Partner. As part of the OpenAI Partner Network,…](https://x.com/trythreews/status/2082227422850941395) | 0 | 0 | 70 | 70 | image, partner |
+
+## Highest engagement rate (500+ views)
+
+Rate normalizes for reach, so this is the list of posts that converted the attention they got rather than the posts that simply got shown to more people.
+
+| Date | Post | Views | Eng. | Rate | Signals |
+|---|---|---:|---:|---:|---|
+| 2026-06-18 | [the amazon for ai agents](https://x.com/trythreews/status/2067564518268629236) | 733 | 67 | 9.14% | text, agent |
+| 2026-07-30 | [Everyone will know soon. Thanks, 0ya!](https://x.com/trythreews/status/2082934921983873310) | 668 | 55 | 8.23% | text, commentary |
+| 2026-07-16 | [A product shipped by @trythreews that literally everyone with a phone can try and use. We…](https://x.com/trythreews/status/2077791709321433472) | 746 | 57 | 7.64% | text, @1, shipping, commentary |
+| 2026-07-30 | [There is clear potential at the intersection of 3D and DeFi for creating more immersive a…](https://x.com/trythreews/status/2082634676972470585) | 965 | 61 | 6.32% | text, avatar |
+| 2026-07-31 | [Web2 Web3 Only possible on @Pumpfun](https://x.com/trythreews/status/2083240241683722572) | 1.1K | 67 | 6.09% | text, @1, other |
+| 2026-07-07 | [$three > $BTC](https://x.com/trythreews/status/2074501642897285513) | 667 | 34 | 5.10% | text, token |
+| 2026-06-21 | [You are locked in! Still improving the feature, but thanks for sharing.](https://x.com/trythreews/status/2068626384457699548) | 533 | 27 | 5.07% | text, other |
+| 2026-07-16 | [Thank you for the support.](https://x.com/trythreews/status/2077793694498124023) | 514 | 26 | 5.06% | text, other |
+| 2026-06-09 | [Stay tuned to see the full video in action.](https://x.com/trythreews/status/2064268495278485766) | 686 | 34 | 4.96% | text, other |
+| 2026-08-07 | [Read more about this event in the thread posted by @nichxbt on our @IBM user group https:…](https://x.com/trythreews/status/2085686157204197574) | 1.4K | 68 | 4.86% | text, @2, other |
+
+## Most replies (conversation starters)
+
+| Date | Post | Likes | RT | Replies | Eng. | Signals |
+|---|---|---:|---:|---:|---:|---|
+| 2026-05-13 | [We just reverse engineered the @pumpfun agent payments SDK Your AI doesn't just execute t…](https://x.com/trythreews/status/2054675701132132736) | 0 | 201 | 92 | 293 | video, @1, avatar, agent, payments |
+| 2026-06-22 | [Give your agents access to money We just shipped a drop-in payment modal for any x402 pai…](https://x.com/trythreews/status/2068951336918638699) | 0 | 0 | 84 | 84 | video, agent, payments, shipping, commentary |
+| 2026-07-28 | [http:// three.ws has been named an OpenAI Partner. As part of the OpenAI Partner Network,…](https://x.com/trythreews/status/2082227422850941395) | 0 | 0 | 70 | 70 | image, partner |
+| 2026-07-31 | [We’ve been featured in @VogueMagazine Photo Vogue! http:// three.ws is now officially rec…](https://x.com/trythreews/status/2083234861184397693) | 0 | 0 | 48 | 48 | image, @1, agent |
+| 2026-07-18 | [IBM just gave three․ws its own corner of IBM․com An official community on IBM's platform,…](https://x.com/trythreews/status/2078321037868167313) | 0 | 0 | 46 | 46 | image, @1, other |
+| 2026-07-06 | [We just shipped 3,000+ animations for 3D AI Agents. http:// three.ws is now officially th…](https://x.com/trythreews/status/2073943451499131112) | 0 | 0 | 42 | 42 | video, avatar, agent, shipping |
+| 2026-08-07 | [Today: The first in-world meetup of the http:// Three.ws User Group hosted by @IBM Open h…](https://x.com/trythreews/status/2085684765286637618) | 228 | 90 | 41 | 359 | video, @1, token, avatar |
+| 2026-06-09 | [333 of the first 3D avatars ever created on three․ws are now on-chain, forever. Each one …](https://x.com/trythreews/status/2064242904428925036) | 0 | 0 | 41 | 41 | image, @2, avatar, agent, payments, partner |
+| 2026-08-04 | [@GoogleCloud three․ws We are excited to announce we are joining forces with Google Cloud!…](https://x.com/trythreews/status/2084704775665566007) | 0 | 0 | 36 | 36 | video, @1, avatar |
+| 2026-06-18 | [](https://x.com/trythreews/status/2067553231967031646) | 0 | 0 | 33 | 33 | text, other |
+
+## What correlates with engagement
+
+Lift is the group's median engagements divided by the corpus median. Rows are only shown where both sides have enough posts to compare.
+
+| Signal | With | Median (with) | Lift | Without | Median (without) | Lift |
+|---|---:|---:|---:|---:|---:|---:|
+| Names $THREE | 6 | 44 | 3.67x | 208 | 11 | 0.92x |
+| Has an image | 41 | 25 | 2.08x | 173 | 10 | 0.83x |
+| Mentions an account | 45 | 22 | 1.83x | 169 | 10 | 0.83x |
+| Has a video | 17 | 21 | 1.75x | 197 | 11 | 0.92x |
+| Multi-paragraph | 74 | 21 | 1.71x | 140 | 9 | 0.75x |
+| Contains a link | 36 | 17 | 1.38x | 178 | 11 | 0.88x |
+| Text only | 149 | 10 | 0.83x | 65 | 16 | 1.33x |
+| Has a link card | 24 | 9 | 0.71x | 190 | 12 | 1.00x |
+| Asks a question | 10 | 7 | 0.58x | 204 | 12 | 1.00x |
+| Is a reply | 17 | 5 | 0.42x | 197 | 12 | 1.00x |
+
+### By length
+
+| Length | Posts | Median | Mean | Best | Lift |
+|---|---:|---:|---:|---:|---:|
+| 1-99 chars | 138 | 9 | 15.9 | 168 | 0.75x |
+| 100-179 chars | 24 | 23 | 42.4 | 241 | 1.88x |
+| 180-279 chars | 48 | 16 | 41.7 | 359 | 1.29x |
+| 280-499 chars | 4 | 71 | 70.5 | 111 | 5.88x |
+| 500+ chars | 0 | n/a | n/a | n/a | n/a |
+
+### By subject
+
+A post can carry more than one subject, so the counts sum past the corpus size.
+
+| Subject | Posts | Median | Mean | Best | Lift |
+|---|---:|---:|---:|---:|---:|
+| Industry commentary | 6 | 46 | 43.3 | 84 | 3.79x |
+| Token / $THREE | 8 | 32 | 98.9 | 359 | 2.63x |
+| Shipped / changelog | 9 | 30 | 38.1 | 111 | 2.50x |
+| Partner / ecosystem | 15 | 29 | 46.5 | 266 | 2.42x |
+| Agents | 43 | 18 | 40.2 | 293 | 1.50x |
+| Avatars / 3D | 30 | 17 | 42.1 | 359 | 1.42x |
+| Payments / x402 | 21 | 12 | 45.6 | 293 | 1.00x |
+| Build log / behind the scenes | 4 | 11 | 11.0 | 16 | 0.88x |
+| Other | 143 | 10 | 16.6 | 168 | 0.83x |
+
+## Timing (UTC)
+
+| Hour | Posts | Median | Lift |
+|---:|---:|---:|---:|
+| 00:00 | 9 | 10 | 0.83x |
+| 01:00 | 5 | 42 | 3.50x |
+| 02:00 | 6 | 6 | 0.50x |
+| 03:00 | 2 | 24 | 2.00x |
+| 04:00 | 9 | 7 | 0.58x |
+| 05:00 | 4 | 19 | 1.54x |
+| 06:00 | 22 | 5 | 0.38x |
+| 07:00 | 21 | 15 | 1.25x |
+| 08:00 | 9 | 22 | 1.83x |
+| 09:00 | 6 | 13 | 1.08x |
+| 10:00 | 4 | 17 | 1.42x |
+| 11:00 | 25 | 17 | 1.42x |
+| 12:00 | 7 | 6 | 0.50x |
+| 13:00 | 5 | 16 | 1.33x |
+| 14:00 | 8 | 13 | 1.08x |
+| 15:00 | 3 | 20 | 1.67x |
+| 16:00 | 8 | 33 | 2.71x |
+| 17:00 | 3 | 40 | 3.33x |
+| 18:00 | 8 | 16 | 1.33x |
+| 19:00 | 12 | 12 | 0.96x |
+| 20:00 | 5 | 9 | 0.75x |
+| 21:00 | 13 | 8 | 0.67x |
+| 22:00 | 9 | 29 | 2.42x |
+| 23:00 | 11 | 16 | 1.33x |
+
+| Weekday | Posts | Median | Lift |
+|---|---:|---:|---:|
+| Sun | 23 | 10 | 0.83x |
+| Mon | 24 | 13 | 1.08x |
+| Tue | 37 | 9 | 0.75x |
+| Wed | 26 | 12 | 0.96x |
+| Thu | 45 | 14 | 1.17x |
+| Fri | 35 | 11 | 0.92x |
+| Sat | 24 | 13 | 1.08x |
+
+## Cadence by month
+
+| Month | Posts | Median | Mean | Best |
+|---|---:|---:|---:|---:|
+| 2026-04 | 10 | 7 | 7.7 | 14 |
+| 2026-05 | 29 | 10 | 20.8 | 293 |
+| 2026-06 | 85 | 10 | 22.5 | 241 |
+| 2026-07 | 70 | 16 | 26.6 | 111 |
+| 2026-08 | 20 | 18 | 51.9 | 359 |
+
+## Accounts we mention (2+ posts)
+
+| Account | Posts mentioning | Mean engagements |
+|---|---:|---:|
+| @fomo | 2 | 160.0 |
+| @ibm | 7 | 82.3 |
+| @pumpfun | 6 | 71.2 |
+| @anthropicai | 5 | 63.2 |
+| @three | 2 | 61.0 |
+| @solana | 2 | 50.0 |
+| @nichxbt | 2 | 36.0 |
+| @trythreews | 2 | 30.5 |
+| @metaplex | 2 | 28.0 |
+| @coincomms | 2 | 21.0 |
+| @coinmarketcap | 3 | 11.7 |
+| @spotify | 2 | 6.0 |
+
+## Accounts we repost or quote
+
+Excluded from every measurement above, kept because who the account amplifies is its own marketing record.
+
+| Account | Posts amplified |
+|---|---:|
+| @nichxbt | 26 |
+| @reale | 7 |
+| @eplus | 6 |
+| @swarminged | 6 |
+| @metasthetic | 6 |
+| @speraxusd | 5 |
+| @potatocheapgam1 | 4 |
+| @benjamin51511 | 3 |
+| @humanbeing1099 | 3 |
+| @illworkforelove | 2 |
+| @x402u | 2 |
+| @kgomotso86764 | 2 |
+| @cryptowarrior_e | 2 |
+| @imchizx | 2 |
+| @dava66666 | 2 |
+
+## Lowest 10 posts
+
+The floor is as instructive as the ceiling: these are the shapes to stop repeating.
+
+| Date | Post | Likes | RT | Replies | Eng. | Signals |
+|---|---|---:|---:|---:|---:|---|
+| 2026-08-04 | ["Google vetted http:// three.ws, and http:// three.ws passed."](https://x.com/trythreews/status/2084720030051405828) | 0 | 0 | n/a | 0 | card, other |
+| 2026-07-25 | [](https://x.com/trythreews/status/2081033827636711670) | 0 | n/a | n/a | 0 | card, other |
+| 2026-07-11 | [We are thrilled to announce http:// three.ws has been accepted into the NVIDIA Developer …](https://x.com/trythreews/status/2075835958889685499) | 0 | 0 | n/a | 0 | image, @1, avatar |
+| 2026-07-10 | [banger](https://x.com/trythreews/status/2075729204147298776) | 0 | n/a | n/a | 0 | text, reply, other |
+| 2026-06-25 | [](https://x.com/trythreews/status/2070014575924363514) | 0 | 0 | n/a | 0 | text, other |
+| 2026-06-16 | [](https://x.com/trythreews/status/2066795399055331684) | 0 | n/a | n/a | 0 | text, other |
+| 2026-06-16 | [](https://x.com/trythreews/status/2066781488289574950) | 0 | n/a | n/a | 0 | text, other |
+| 2026-06-16 | [](https://x.com/trythreews/status/2066781386732978422) | 0 | n/a | n/a | 0 | text, other |
+| 2026-05-22 | [](https://x.com/trythreews/status/2057781368780927471) | 0 | n/a | n/a | 0 | text, reply, other |
+| 2026-05-11 | [](https://x.com/trythreews/status/2053700891186983198) | 0 | n/a | n/a | 0 | text, other |
diff --git a/scripts/x-archive-analyze.mjs b/scripts/x-archive-analyze.mjs
new file mode 100644
index 000000000..dfebc9814
--- /dev/null
+++ b/scripts/x-archive-analyze.mjs
@@ -0,0 +1,378 @@
+#!/usr/bin/env node
+/**
+ * Engagement analysis over the X post archive.
+ *
+ * Usage:
+ * node scripts/x-archive-analyze.mjs # DB if reachable, else the archive files
+ * node scripts/x-archive-analyze.mjs --source files # force the checked-in archive
+ * node scripts/x-archive-analyze.mjs --source db # force Postgres (fails loudly if unreachable)
+ * node scripts/x-archive-analyze.mjs --handle trythreews # one account (default: every account found)
+ * node scripts/x-archive-analyze.mjs --stdout # print the report instead of writing files
+ *
+ * Writes docs/x-archive/<handle>-engagement.md (the readable report) and
+ * data/x-archive/reports/<handle>-engagement.json (the same numbers as data).
+ */
+
+import { readFileSync } from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+import {
+ ARCHIVE_DIR,
+ analyze,
+ engagementRate,
+ engagements,
+ listArchiveFiles,
+ mergeScrapes,
+ readScrapeFile,
+ topicsOf,
+} from './x-archive-lib.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '..');
+const DOC_DIR = path.resolve(REPO_ROOT, 'docs', 'x-archive');
+const REPORT_DIR = path.resolve(REPO_ROOT, ARCHIVE_DIR, 'reports');
+
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ } catch {
+ // Absent env files are normal outside a configured checkout.
+ }
+}
+
+const args = process.argv.slice(2);
+const flag = (name) => args.includes(`--${name}`);
+const value = (name) => {
+ const i = args.indexOf(`--${name}`);
+ return i >= 0 ? args[i + 1] : null;
+};
+
+const SOURCE = value('source') || 'auto';
+const ONLY_HANDLE = value('handle');
+const TO_STDOUT = flag('stdout');
+
+async function loadFromFiles() {
+ const files = await listArchiveFiles(path.resolve(REPO_ROOT, ARCHIVE_DIR));
+ if (!files.length) throw new Error(`no scrape files in ${ARCHIVE_DIR}`);
+ const byHandle = new Map();
+ for (const file of files) {
+ const scrape = await readScrapeFile(file);
+ if (!byHandle.has(scrape.handle)) byHandle.set(scrape.handle, []);
+ byHandle.get(scrape.handle).push(scrape);
+ }
+ const out = new Map();
+ for (const [handle, scrapes] of byHandle) {
+ out.set(handle, { posts: mergeScrapes(scrapes).posts, sources: scrapes.map((s) => path.relative(REPO_ROOT, s.sourceFile)) });
+ }
+ return { origin: 'archive files', accounts: out };
+}
+
+async function loadFromDb() {
+ const { neon } = await import('@neondatabase/serverless');
+ const sql = neon(process.env.DATABASE_URL);
+ const rows = await sql`
+ select tweet_id, handle, author_handle, url, text, posted_at,
+ is_retweet, is_reply, is_pinned, has_image, has_video, has_card,
+ hashtags, mentions, urls,
+ likes, retweets, replies, views, views_label, views_exact, measured_at
+ from x_account_posts
+ order by posted_at desc
+ `;
+ const imports = await sql`select handle, source_file, scraped_at from x_account_imports order by scraped_at`;
+ const accounts = new Map();
+ for (const r of rows) {
+ const post = {
+ tweetId: r.tweet_id,
+ handle: r.handle,
+ authorHandle: r.author_handle,
+ isOwn: r.author_handle === r.handle,
+ url: r.url,
+ text: r.text,
+ postedAt: new Date(r.posted_at).toISOString(),
+ isRetweet: r.is_retweet,
+ isReply: r.is_reply,
+ isPinned: r.is_pinned,
+ hasImage: r.has_image,
+ hasVideo: r.has_video,
+ hasCard: r.has_card,
+ hashtags: r.hashtags || [],
+ mentions: r.mentions || [],
+ urls: r.urls || [],
+ likes: r.likes,
+ retweets: r.retweets,
+ replies: r.replies,
+ views: r.views,
+ viewsLabel: r.views_label,
+ viewsExact: r.views_exact,
+ measuredAt: r.measured_at ? new Date(r.measured_at).toISOString() : null,
+ };
+ if (!accounts.has(r.handle)) {
+ accounts.set(r.handle, {
+ posts: [],
+ sources: imports.filter((i) => i.handle === r.handle).map((i) => i.source_file),
+ });
+ }
+ accounts.get(r.handle).posts.push(post);
+ }
+ if (!accounts.size) throw new Error('x_account_posts is empty. Run `npm run x:archive:import` first.');
+ return { origin: 'database', accounts };
+}
+
+async function load() {
+ if (SOURCE === 'files') return loadFromFiles();
+ if (SOURCE === 'db') {
+ if (!process.env.DATABASE_URL) throw new Error('--source db needs DATABASE_URL');
+ return loadFromDb();
+ }
+ if (process.env.DATABASE_URL) {
+ try {
+ return await loadFromDb();
+ } catch (err) {
+ console.warn(`database unavailable (${err.message}); falling back to the archive files.`);
+ }
+ }
+ return loadFromFiles();
+}
+
+// ---------------------------------------------------------------------------
+// Rendering
+// ---------------------------------------------------------------------------
+
+const num = (n, digits = 0) => (n === null || n === undefined ? 'n/a' : Number(n).toLocaleString('en-US', { maximumFractionDigits: digits, minimumFractionDigits: digits }));
+const pct = (n, digits = 1) => (n === null || n === undefined ? 'n/a' : `${Number(n).toFixed(digits)}%`);
+const lift = (n) => (n === null || n === undefined ? 'n/a' : `${n.toFixed(2)}x`);
+const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
+
+function excerpt(post, len = 90) {
+ const oneLine = post.text.replace(/\s+/g, ' ').trim();
+ return oneLine.length > len ? `${oneLine.slice(0, len - 1)}…` : oneLine;
+}
+
+function tagsOf(post) {
+ const tags = [];
+ if (post.hasVideo) tags.push('video');
+ else if (post.hasImage) tags.push('image');
+ else if (post.hasCard) tags.push('card');
+ else tags.push('text');
+ if (post.mentions.length) tags.push(`@${post.mentions.length}`);
+ if (post.isReply) tags.push('reply');
+ tags.push(...topicsOf(post));
+ return tags.join(', ');
+}
+
+function postTable(posts, { rate = false } = {}) {
+ const head = rate
+ ? '| Date | Post | Views | Eng. | Rate | Signals |\n|---|---|---:|---:|---:|---|'
+ : '| Date | Post | Likes | RT | Replies | Eng. | Signals |\n|---|---|---:|---:|---:|---:|---|';
+ const rows = posts.map((p) => {
+ const date = p.postedAt.slice(0, 10);
+ const link = `[${excerpt(p).replace(/\|/g, '\\|')}](${p.url})`;
+ return rate
+ ? `| ${date} | ${link} | ${p.viewsLabel || num(p.views)} | ${num(engagements(p))} | ${pct(engagementRate(p), 2)} | ${tagsOf(p)} |`
+ : `| ${date} | ${link} | ${num(p.likes)} | ${num(p.retweets)} | ${num(p.replies)} | ${num(engagements(p))} | ${tagsOf(p)} |`;
+ });
+ return `${head}\n${rows.join('\n')}`;
+}
+
+// Turn the measured lifts into plain sentences. Everything here is derived from
+// the numbers above it, so the read-off cannot drift from the data.
+function readOff(report) {
+ const lines = [];
+ const strong = report.formats
+ .filter((f) => f.significant && f.with.lift !== null && f.without.lift !== null)
+ .map((f) => ({ ...f, delta: f.with.lift - f.without.lift }))
+ .sort((a, b) => b.delta - a.delta);
+
+ for (const f of strong.slice(0, 3)) {
+ if (f.delta <= 0.15) continue;
+ lines.push(
+ `**${f.label}** carries: ${f.with.count} posts at a median ${num(f.with.medianEngagements)} engagements (${lift(f.with.lift)} the corpus median) against ${num(f.without.medianEngagements)} for the ${f.without.count} without it.`,
+ );
+ }
+ for (const f of strong.slice(-2).reverse()) {
+ if (f.delta >= -0.15) continue;
+ lines.push(
+ `**${f.label}** costs: ${f.with.count} posts at a median ${num(f.with.medianEngagements)} (${lift(f.with.lift)}) against ${num(f.without.medianEngagements)} without.`,
+ );
+ }
+
+ const topics = report.topics.filter((t) => t.count >= 5);
+ if (topics.length) {
+ const best = topics[0];
+ const worst = topics[topics.length - 1];
+ lines.push(
+ `Best-performing subject: **${best.label}** (${best.count} posts, median ${num(best.medianEngagements)}, ${lift(best.lift)}). Weakest: **${worst.label}** (${worst.count} posts, median ${num(worst.medianEngagements)}, ${lift(worst.lift)}).`,
+ );
+ }
+
+ const lengths = report.lengths.filter((l) => l.count >= 5).sort((a, b) => (b.lift || 0) - (a.lift || 0));
+ if (lengths.length) {
+ lines.push(`Best length band: **${lengths[0].label}** (${lengths[0].count} posts, ${lift(lengths[0].lift)}). Worst: **${lengths[lengths.length - 1].label}** (${lift(lengths[lengths.length - 1].lift)}).`);
+ }
+
+ const hours = report.timing.byHourUtc.filter((h) => h.count >= 5).sort((a, b) => (b.lift || 0) - (a.lift || 0));
+ if (hours.length) {
+ lines.push(`Strongest posting hour: **${String(hours[0].hour).padStart(2, '0')}:00 UTC** (${hours[0].count} posts, ${lift(hours[0].lift)}). Weakest: **${String(hours[hours.length - 1].hour).padStart(2, '0')}:00 UTC** (${lift(hours[hours.length - 1].lift)}).`);
+ }
+
+ if (report.distribution.topDecileShare !== null) {
+ lines.push(
+ `Concentration: the top 10% of posts earn **${pct(report.distribution.topDecileShare * 100)}** of all engagement. Median post: ${num(report.distribution.medianEngagements)} engagements; p90: ${num(report.distribution.p90)}; best: ${num(report.distribution.max)}.`,
+ );
+ }
+
+ return lines.map((l) => `- ${l}`).join('\n');
+}
+
+function renderMarkdown(report, meta) {
+ const g = report.generatedFrom;
+ const d = report.distribution;
+
+ return `# @${report.handle}: what actually lands on X
+
+Generated by \`npm run x:archive:analyze\` from the post archive in [data/x-archive/](../../data/x-archive/). Do not hand-edit: rerun the script after the next scrape.
+
+- **Source:** ${meta.origin} (${meta.sources.join(', ') || 'n/a'})
+- **Generated:** ${meta.generatedAt}
+- **Corpus:** ${num(g.analyzed)} posts written by @${report.handle}, ${g.firstPostAt?.slice(0, 10)} to ${g.lastPostAt?.slice(0, 10)}. ${num(g.retweetsExcluded)} reposts and quotes of other accounts are archived but excluded from every number below: they carry the original author's engagement, not ours.
+- **Engagements** here means likes + reposts + replies. Views measure delivery, engagements measure whether anyone cared.
+- **View counts are rounded by X itself** past 999 ("6.3K"), so every rate below carries about two significant figures. Exact counts under 1,000 are exact.
+
+## Headline
+
+| Metric | Value |
+|---|---:|
+| Posts analyzed | ${num(g.analyzed)} |
+| Total likes | ${num(report.totals.likes)} |
+| Total reposts | ${num(report.totals.retweets)} |
+| Total replies | ${num(report.totals.replies)} |
+| Total views (approx) | ${num(report.totals.views)} |
+| Median engagements per post | ${num(d.medianEngagements)} |
+| Mean engagements per post | ${num(d.meanEngagements, 1)} |
+| p75 / p90 / p99 | ${num(d.p75)} / ${num(d.p90)} / ${num(d.p99)} |
+| Best post | ${num(d.max)} |
+| Median engagement rate | ${pct(d.medianRatePct, 2)} of views (${num(d.ratedPosts)} posts with a view count) |
+| Share of engagement from the top 10% of posts | ${d.topDecileShare === null ? "n/a" : pct(d.topDecileShare * 100)} |
+
+## The read-off
+
+${readOff(report)}
+
+## Top 15 posts by engagement
+
+${postTable(report.top.byEngagements)}
+
+## Highest engagement rate (500+ views)
+
+Rate normalizes for reach, so this is the list of posts that converted the attention they got rather than the posts that simply got shown to more people.
+
+${postTable(report.top.byRate, { rate: true })}
+
+## Most replies (conversation starters)
+
+${postTable(report.top.byReplies)}
+
+## What correlates with engagement
+
+Lift is the group's median engagements divided by the corpus median. Rows are only shown where both sides have enough posts to compare.
+
+| Signal | With | Median (with) | Lift | Without | Median (without) | Lift |
+|---|---:|---:|---:|---:|---:|---:|
+${report.formats
+ .filter((f) => f.significant)
+ .sort((a, b) => (b.with.lift || 0) - (a.with.lift || 0))
+ .map((f) => `| ${f.label} | ${num(f.with.count)} | ${num(f.with.medianEngagements)} | ${lift(f.with.lift)} | ${num(f.without.count)} | ${num(f.without.medianEngagements)} | ${lift(f.without.lift)} |`)
+ .join('\n')}
+
+### By length
+
+| Length | Posts | Median | Mean | Best | Lift |
+|---|---:|---:|---:|---:|---:|
+${report.lengths.map((l) => `| ${l.label} | ${num(l.count)} | ${num(l.medianEngagements)} | ${num(l.meanEngagements, 1)} | ${num(l.bestEngagements)} | ${lift(l.lift)} |`).join('\n')}
+
+### By subject
+
+A post can carry more than one subject, so the counts sum past the corpus size.
+
+| Subject | Posts | Median | Mean | Best | Lift |
+|---|---:|---:|---:|---:|---:|
+${report.topics.map((t) => `| ${t.label} | ${num(t.count)} | ${num(t.medianEngagements)} | ${num(t.meanEngagements, 1)} | ${num(t.bestEngagements)} | ${lift(t.lift)} |`).join('\n')}
+
+## Timing (UTC)
+
+| Hour | Posts | Median | Lift |
+|---:|---:|---:|---:|
+${report.timing.byHourUtc.map((h) => `| ${String(h.hour).padStart(2, '0')}:00 | ${num(h.count)} | ${num(h.medianEngagements)} | ${lift(h.lift)} |`).join('\n')}
+
+| Weekday | Posts | Median | Lift |
+|---|---:|---:|---:|
+${report.timing.byWeekdayUtc.map((w) => `| ${WEEKDAYS[w.weekday]} | ${num(w.count)} | ${num(w.medianEngagements)} | ${lift(w.lift)} |`).join('\n')}
+
+## Cadence by month
+
+| Month | Posts | Median | Mean | Best |
+|---|---:|---:|---:|---:|
+${report.cadence.map((c) => `| ${c.month} | ${num(c.count)} | ${num(c.medianEngagements)} | ${num(c.meanEngagements, 1)} | ${num(c.bestEngagements)} |`).join('\n')}
+
+## Accounts we mention (2+ posts)
+
+| Account | Posts mentioning | Mean engagements |
+|---|---:|---:|
+${report.mentions.map((m) => `| ${m.handle} | ${num(m.posts)} | ${num(m.meanEngagements, 1)} |`).join('\n')}
+
+## Accounts we repost or quote
+
+Excluded from every measurement above, kept because who the account amplifies is its own marketing record.
+
+| Account | Posts amplified |
+|---|---:|
+${report.amplified.byAuthor.map((a) => `| @${a.author} | ${num(a.count)} |`).join('\n')}
+
+## Lowest 10 posts
+
+The floor is as instructive as the ceiling: these are the shapes to stop repeating.
+
+${postTable(report.top.worst)}
+`;
+}
+
+async function main() {
+ const { origin, accounts } = await load();
+ const generatedAt = new Date().toISOString();
+
+ for (const [handle, { posts, sources }] of accounts) {
+ if (ONLY_HANDLE && handle !== ONLY_HANDLE.replace(/^@/, '')) continue;
+ const report = analyze(posts, { handle });
+ const markdown = renderMarkdown(report, { origin, sources, generatedAt });
+
+ if (TO_STDOUT) {
+ console.log(markdown);
+ continue;
+ }
+
+ await mkdir(DOC_DIR, { recursive: true });
+ await mkdir(REPORT_DIR, { recursive: true });
+ const mdPath = path.join(DOC_DIR, `${handle}-engagement.md`);
+ const jsonPath = path.join(REPORT_DIR, `${handle}-engagement.json`);
+ await writeFile(mdPath, markdown);
+ await writeFile(jsonPath, `${JSON.stringify({ generatedAt, origin, sources, report }, null, 2)}\n`);
+ console.log(`@${handle}: ${report.generatedFrom.analyzed} posts analyzed from ${origin}`);
+ console.log(` ${path.relative(REPO_ROOT, mdPath)}`);
+ console.log(` ${path.relative(REPO_ROOT, jsonPath)}`);
+ }
+}
+
+main().catch((err) => {
+ console.error(err.message || err);
+ process.exitCode = 1;
+});
diff --git a/scripts/x-archive-import.mjs b/scripts/x-archive-import.mjs
new file mode 100644
index 000000000..d7befc3ea
--- /dev/null
+++ b/scripts/x-archive-import.mjs
@@ -0,0 +1,213 @@
+#!/usr/bin/env node
+/**
+ * Ingest X profile scrapes from data/x-archive/ into Postgres.
+ *
+ * Usage:
+ * node scripts/x-archive-import.mjs # every archive file not yet ingested
+ * node scripts/x-archive-import.mjs --file <path.json> # one file (also accepts a path outside the archive)
+ * node scripts/x-archive-import.mjs --dry-run # parse + report, touch nothing
+ * node scripts/x-archive-import.mjs --force # re-ingest a file already recorded
+ *
+ * Idempotency: each file is hashed and recorded in x_account_imports. Running
+ * the importer twice over the same archive is a no-op, so this is safe to wire
+ * into a cron or run by hand after every scrape.
+ *
+ * Auth: reads DATABASE_URL from .env.local, then .env, then the environment.
+ */
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+import { Pool, neonConfig } from '@neondatabase/serverless';
+import ws from 'ws';
+import { ARCHIVE_DIR, listArchiveFiles, readScrapeFile } from './x-archive-lib.mjs';
+
+neonConfig.webSocketConstructor = ws;
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '..');
+
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim();
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[m[1]] = val;
+ }
+ } catch {
+ // A missing env file is normal: production supplies these on the service.
+ }
+}
+
+const args = process.argv.slice(2);
+const flag = (name) => args.includes(`--${name}`);
+const value = (name) => {
+ const i = args.indexOf(`--${name}`);
+ return i >= 0 ? args[i + 1] : null;
+};
+
+const DRY_RUN = flag('dry-run');
+const FORCE = flag('force');
+
+function rel(file) {
+ return path.relative(REPO_ROOT, path.resolve(file));
+}
+
+async function collectFiles() {
+ const one = value('file');
+ if (one) return [path.resolve(REPO_ROOT, one)];
+ const files = await listArchiveFiles(path.resolve(REPO_ROOT, ARCHIVE_DIR));
+ if (!files.length) {
+ throw new Error(`no scrape files in ${ARCHIVE_DIR}. Drop a profile scrape there or pass --file.`);
+ }
+ return files;
+}
+
+async function importScrape(client, scrape) {
+ const sourceFile = rel(scrape.sourceFile);
+
+ const existing = await client.query(
+ 'select id, imported_at from x_account_imports where handle = $1 and source_sha256 = $2',
+ [scrape.handle, scrape.sha256],
+ );
+ if (existing.rowCount && !FORCE) {
+ return { skipped: true, reason: `already imported ${existing.rows[0].imported_at.toISOString()}` };
+ }
+
+ await client.query('begin');
+ try {
+ const imp = await client.query(
+ `insert into x_account_imports (handle, source_file, source_sha256, scraped_at, tweet_count)
+ values ($1, $2, $3, $4, $5)
+ on conflict (handle, source_sha256) do update set
+ source_file = excluded.source_file,
+ tweet_count = excluded.tweet_count,
+ imported_at = now()
+ returning id`,
+ [scrape.handle, sourceFile, scrape.sha256, scrape.scrapedAt, scrape.posts.length],
+ );
+ const importId = imp.rows[0].id;
+
+ let inserted = 0;
+ let updated = 0;
+ for (const p of scrape.posts) {
+ const res = await client.query(
+ `insert into x_account_posts (
+ tweet_id, handle, author_handle, url, text, posted_at,
+ is_retweet, is_reply, is_pinned, has_image, has_video, has_card,
+ hashtags, mentions, urls,
+ likes, retweets, replies, views, views_label, views_exact, measured_at
+ ) values (
+ $1, $2, $3, $4, $5, $6,
+ $7, $8, $9, $10, $11, $12,
+ $13, $14, $15,
+ $16, $17, $18, $19, $20, $21, $22
+ )
+ on conflict (tweet_id) do update set
+ url = excluded.url,
+ text = excluded.text,
+ is_pinned = excluded.is_pinned,
+ hashtags = excluded.hashtags,
+ mentions = excluded.mentions,
+ urls = excluded.urls,
+ likes = excluded.likes,
+ retweets = excluded.retweets,
+ replies = excluded.replies,
+ views = excluded.views,
+ views_label = excluded.views_label,
+ views_exact = excluded.views_exact,
+ measured_at = excluded.measured_at,
+ updated_at = now()
+ -- Only accept a scrape that is newer than the one already on the
+ -- row. Re-importing an older archive after a newer one must not
+ -- roll the counters backwards.
+ where x_account_posts.measured_at is null
+ or excluded.measured_at >= x_account_posts.measured_at
+ returning (xmax = 0) as is_insert`,
+ [
+ p.tweetId, p.handle, p.authorHandle, p.url, p.text, p.postedAt,
+ p.isRetweet, p.isReply, p.isPinned, p.hasImage, p.hasVideo, p.hasCard,
+ p.hashtags, p.mentions, p.urls,
+ p.likes, p.retweets, p.replies, p.views, p.viewsLabel, p.viewsExact, p.measuredAt,
+ ],
+ );
+ if (res.rowCount) {
+ if (res.rows[0].is_insert) inserted++;
+ else updated++;
+ }
+
+ await client.query(
+ `insert into x_account_post_snapshots (tweet_id, import_id, captured_at, likes, retweets, replies, views, views_label)
+ values ($1, $2, $3, $4, $5, $6, $7, $8)
+ on conflict (tweet_id, captured_at) do nothing`,
+ [p.tweetId, importId, p.measuredAt, p.likes, p.retweets, p.replies, p.views, p.viewsLabel],
+ );
+ }
+
+ await client.query('update x_account_imports set inserted_count = $2, updated_count = $3 where id = $1', [
+ importId,
+ inserted,
+ updated,
+ ]);
+ await client.query('commit');
+ return { skipped: false, inserted, updated, total: scrape.posts.length };
+ } catch (err) {
+ await client.query('rollback');
+ throw err;
+ }
+}
+
+async function main() {
+ const files = await collectFiles();
+ const scrapes = [];
+ for (const file of files) {
+ const scrape = await readScrapeFile(file);
+ scrapes.push(scrape);
+ console.log(`${rel(file)}: @${scrape.handle}, ${scrape.posts.length} posts, scraped ${scrape.scrapedAt}`);
+ }
+
+ if (DRY_RUN) {
+ const total = scrapes.reduce((n, s) => n + s.posts.length, 0);
+ console.log(`\nDry run: ${scrapes.length} file(s), ${total} posts parsed. Nothing written.`);
+ return;
+ }
+
+ if (!process.env.DATABASE_URL) {
+ console.error('\nDATABASE_URL is not set. Add it to .env.local or export it in your shell.');
+ console.error('The archive files themselves are the durable copy; run again once the database is reachable.');
+ process.exitCode = 3;
+ return;
+ }
+
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
+ const client = await pool.connect();
+ try {
+ const check = await client.query(
+ "select to_regclass('public.x_account_posts') is not null as ready",
+ );
+ if (!check.rows[0].ready) {
+ console.error('\nx_account_posts does not exist. Run `npm run db:status`, then `npm run db:migrate`.');
+ process.exitCode = 4;
+ return;
+ }
+
+ for (const scrape of scrapes) {
+ const result = await importScrape(client, scrape);
+ if (result.skipped) console.log(` skip ${rel(scrape.sourceFile)}: ${result.reason} (use --force to re-ingest)`);
+ else console.log(` ok ${rel(scrape.sourceFile)}: ${result.inserted} new, ${result.updated} refreshed, ${result.total} seen`);
+ }
+ } finally {
+ client.release();
+ await pool.end();
+ }
+}
+
+main().catch((err) => {
+ console.error(err.message || err);
+ process.exitCode = 1;
+});