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
fix(x): return real drafts from the X panel and match the post tables to the code
nirholasfc3789fe8bcd
diff --git a/api/_lib/migrations/20260814060000_x_social_publish_state.sql b/api/_lib/migrations/20260814060000_x_social_publish_state.sqlnew file mode 100644index 000000000..7c87e0505--- /dev/null+++ b/api/_lib/migrations/20260814060000_x_social_publish_state.sql@@ -0,0 +1,87 @@+-- Reconcile x_scheduled_posts and x_pending_reviews with the columns the app+-- actually reads and writes.+--+-- Two generations of these tables exist in the tree. The original pair+-- (2026-05-13-x-scheduled-posts.sql, 2026-05-13-x-pro-features.sql) matches the+-- code: /api/cron/run-x-scheduled-posts and /api/x/schedule read posted_at,+-- tweet_id, error and attempts, and /api/x/reviews reads status, resolved_at and+-- thread_parts. The later marketplace rollforward+-- (2026-05-25-marketplace-and-social-tables.sql,+-- 2026-05-25-marketplace-social-rollforward.sql) and api/_lib/schema.sql declare a+-- DIFFERENT pair (published_at; reviewed_at/approved), and every one of those+-- statements is CREATE TABLE IF NOT EXISTS, so whichever file a given database ran+-- first silently decides its shape. A database provisioned from schema.sql gets+-- the second shape, and then the publisher cron fails on every tick with+-- `column "attempts" does not exist` while /api/x/schedule 500s on GET and POST.+--+-- This makes the shape deterministic from either starting point. Every statement+-- is a no-op on a database that already carries the first shape.++alter table x_scheduled_posts add column if not exists posted_at timestamptz;+alter table x_scheduled_posts add column if not exists tweet_id text;+alter table x_scheduled_posts add column if not exists error text;+alter table x_scheduled_posts add column if not exists attempts int not null default 0;+alter table x_scheduled_posts add column if not exists thread_parts jsonb;+alter table x_scheduled_posts add column if not exists reply_to_tweet_id text;++-- Rows a schema.sql-shaped database already published were only ever marked in+-- published_at. Carry them over, or the cron would treat every one of them as+-- still due and re-post it.+do $$+begin+ if exists (+ select 1 from information_schema.columns+ where table_schema = 'public' and table_name = 'x_scheduled_posts'+ and column_name = 'published_at'+ ) then+ update x_scheduled_posts+ set posted_at = published_at+ where posted_at is null and published_at is not null;+ end if;+end+$$;++create index if not exists x_scheduled_due_idx+ on x_scheduled_posts (scheduled_at)+ where posted_at is null and error is null;++alter table x_pending_reviews add column if not exists thread_parts jsonb;+alter table x_pending_reviews add column if not exists resolved_at timestamptz;+alter table x_pending_reviews add column if not exists status text not null default 'pending';++-- The original table constrained status inline, which Postgres auto-named+-- x_pending_reviews_status_check. Add it only where it is missing, so this does+-- not fail on a database that already has it.+do $$+begin+ if not exists (+ select 1 from pg_constraint where conname = 'x_pending_reviews_status_check'+ ) then+ alter table x_pending_reviews+ add constraint x_pending_reviews_status_check+ check (status in ('pending', 'approved', 'rejected'));+ end if;+end+$$;++-- Same carry-over for the review queue: a schema.sql-shaped database recorded the+-- decision in approved/reviewed_at, which /api/x/reviews cannot see, so an already+-- resolved draft would sit in the pending list forever.+do $$+begin+ if exists (+ select 1 from information_schema.columns+ where table_schema = 'public' and table_name = 'x_pending_reviews'+ and column_name = 'approved'+ ) then+ update x_pending_reviews+ set status = case when approved then 'approved' else 'rejected' end,+ resolved_at = coalesce(resolved_at, reviewed_at)+ where approved is not null and status = 'pending';+ end if;+end+$$;++create index if not exists x_pending_reviews_user_pending_idx+ on x_pending_reviews (user_id, created_at desc)+ where status = 'pending';diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 587093091..5ba16c6e0 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -2104,17 +2104,29 @@ CREATE TABLE IF NOT EXISTS x_triggers (CREATE INDEX IF NOT EXISTS x_triggers_user_enabled ON x_triggers(user_id) WHERE enabled;CREATE INDEX IF NOT EXISTS x_triggers_agent_enabled ON x_triggers(agent_id) WHERE enabled;+-- Shape matches what /api/cron/run-x-scheduled-posts and /api/x/schedule read and+-- write (posted_at, tweet_id, error, attempts), not the vestigial published_at+-- column this file used to declare. See+-- api/_lib/migrations/20260814060000_x_social_publish_state.sql for why the two+-- generations diverged and how an already-provisioned database is reconciled.CREATE TABLE IF NOT EXISTS x_scheduled_posts (- id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,- user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,- text text NOT NULL,- scheduled_at timestamptz NOT NULL,- published_at timestamptz,- created_at timestamptz NOT NULL DEFAULT now()+ id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id text,+ text text NOT NULL,+ thread_parts jsonb,+ reply_to_tweet_id text,+ scheduled_at timestamptz NOT NULL,+ posted_at timestamptz,+ tweet_id text,+ error text,+ attempts int NOT NULL DEFAULT 0,+ created_at timestamptz NOT NULL DEFAULT now());-CREATE INDEX IF NOT EXISTS x_scheduled_posts_pending- ON x_scheduled_posts(scheduled_at) WHERE published_at IS NULL;+CREATE INDEX IF NOT EXISTS x_scheduled_due_idx+ ON x_scheduled_posts(scheduled_at) WHERE posted_at IS NULL AND error IS NULL;+CREATE INDEX IF NOT EXISTS x_scheduled_user_idx+ ON x_scheduled_posts(user_id, scheduled_at DESC);-- ── walk metrics / events / achievements ────────────────────────────────────-- See api/_lib/migrations/20260621140000_walk_metrics.sql for the full rationale.@@ -2225,18 +2237,24 @@ create unique index if not exists walk_control_commands_dedupon walk_control_commands (session_id, kind, dedup_key)where dedup_key is not null;+-- Shape matches what /api/x/reviews reads and writes (status + resolved_at), not+-- the vestigial approved/reviewed_at pair this file used to declare. See+-- api/_lib/migrations/20260814060000_x_social_publish_state.sql for why the two+-- generations diverged and how an already-provisioned database is reconciled.CREATE TABLE IF NOT EXISTS x_pending_reviews (id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,trigger_id uuid REFERENCES x_triggers(id) ON DELETE SET NULL,- agent_id uuid REFERENCES agent_identities(id) ON DELETE SET NULL,+ agent_id text,text text NOT NULL,- reviewed_at timestamptz,- approved boolean,+ thread_parts jsonb,+ status text NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'approved', 'rejected')),+ resolved_at timestamptz,created_at timestamptz NOT NULL DEFAULT now());-CREATE INDEX IF NOT EXISTS x_pending_reviews_user_pending- ON x_pending_reviews(user_id) WHERE reviewed_at IS NULL;+CREATE INDEX IF NOT EXISTS x_pending_reviews_user_pending_idx+ ON x_pending_reviews(user_id, created_at DESC) WHERE status = 'pending';-- ── club_tips — backfill amount_atomics ──────────────────────────────────────ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS amount_atomics numeric;diff --git a/api/x/analytics.js b/api/x/analytics.jsindex 4fc4e61c9..4fe470087 100644--- a/api/x/analytics.js+++ b/api/x/analytics.js@@ -1,9 +1,10 @@-// GET /api/x/analytics — recent posts with engagement metrics+// GET /api/x/analytics: recent posts with engagement metrics// Optional: ?agent_id=<id> to filterimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, json } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -14,6 +15,9 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agent_id');+ // agent_id is a uuid column on the deployed schema, so a junk value reaches+ // Postgres as a cast error and 500s a caller mistake. Reject it here.+ if (agentId !== null && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');const rows = agentId? await sql`@@ -27,14 +31,17 @@ export default wrap(async (req, res) => {order by created_at desc limit 50`;- // Roll up totals.+ // Roll up totals. X returns counts as numbers but the column is jsonb, so a+ // value that round-tripped as a string would silently turn `+=` into string+ // concatenation and render "00012" in the dashboard. Coerce every term.+ const count = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);const totals = rows.reduce((acc, r) => {const m = r.metrics || {};- acc.likes += m.like_count || 0;- acc.retweets += m.retweet_count || 0;- acc.replies += m.reply_count || 0;- acc.quotes += m.quote_count || 0;- acc.impressions += m.impression_count || 0;+ acc.likes += count(m.like_count);+ acc.retweets += count(m.retweet_count);+ acc.replies += count(m.reply_count);+ acc.quotes += count(m.quote_count);+ acc.impressions += count(m.impression_count);acc.posts++;return acc;}, { posts: 0, likes: 0, retweets: 0, replies: 0, quotes: 0, impressions: 0 });diff --git a/api/x/draft.js b/api/x/draft.jsindex 23dc675ef..5412ea552 100644--- a/api/x/draft.js+++ b/api/x/draft.js@@ -1,13 +1,87 @@-// POST /api/x/draft — generate a tweet draft using Claude based on the agent's-// profile (name + description). Returns a single 280-char proposal that the-// user can edit before posting.+// POST /api/x/draft+// Body: { agent_id?, prompt?, tone?, thread?, count? }+// Generates tweet drafts in the agent's voice with the platform LLM chain and+// returns { drafts: [{ text, length } | { thread_parts, length }] }, the shape+// the dashboard X panel renders. `count` asks for that many DIFFERENT options+// (each generated from its own angle), not that many paraphrases of one.import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';-import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';+import { cors, method, wrap, error, readJson, json, rateLimited } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';+import { MAX_TWEET_LEN } from '../_lib/x-post.js';-const MAX_TWEET_LEN = 280;+const MAX_DRAFTS = 3;+const MAX_PROMPT_LEN = 500;+const MAX_THREAD_PARTS = 5;++// Mirrors the tone select in the dashboard X panel (src/dashboard/dashboard.js).+const TONE_GUIDE = {+ neutral: 'Plain and confident. No hype words, no exclamation marks.',+ hype: 'High energy and punchy. Short sentences. Specific excitement, never generic hype.',+ sarcastic: 'Dry wit, understated, self-aware. Never mean.',+ technical: 'Precise and concrete. Name the mechanism, not the vibe.',+ deadpan: 'Flat delivery, no exclamation marks. Humor comes from understatement.',+};++// One angle per requested draft, so "Draft x3" returns three genuinely different+// openings instead of three rewrites of the same sentence.+const ANGLES = [+ 'Open with a concrete detail only this agent would know.',+ 'Open with a question that makes a scrolling reader stop.',+ 'Open with a claim, then back it with one specific fact.',+];++function buildSystem({ tone, thread }) {+ const lines = [+ 'You write tweets for AI agents on three.ws.',+ 'Rules:',+ `- Each tweet is under ${MAX_TWEET_LEN} characters. This is a hard limit.`,+ "- Write in the agent's voice: first person, matching its description.",+ '- At most one hashtag. No hashtag spam.',+ '- Plain text only. No surrounding quotes, no markdown, no emoji spam.',+ '- Never use an em-dash or an en-dash.',+ `- Tone: ${TONE_GUIDE[tone]}`,+ ];+ if (thread) {+ lines.push(+ '- Write a thread of 2 to 4 tweets. Separate each tweet with a line containing only three hyphens.',+ 'Output ONLY the thread, nothing else.',+ );+ } else {+ lines.push('Output ONLY the tweet text, nothing else.');+ }+ return lines.join('\n');+}++// Strip the wrapping quotes an LLM sometimes adds, then hard-cap at the tweet+// limit so a long completion can never produce a draft X would reject.+function normalizeTweet(raw) {+ let text = String(raw || '').trim();+ if (text.length > 1 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();+ if (text.length > MAX_TWEET_LEN) text = `${text.slice(0, MAX_TWEET_LEN - 1).trimEnd()}…`;+ return text;+}++function toDraft(raw, thread) {+ if (!thread) {+ const text = normalizeTweet(raw);+ return text ? { text, length: text.length } : null;+ }+ const parts = String(raw || '')+ .split(/^[ \t]*-{3,}[ \t]*$/m)+ .map(normalizeTweet)+ .filter(Boolean)+ .slice(0, MAX_THREAD_PARTS);+ if (!parts.length) return null;+ // A single-part "thread" is just a tweet; return it in the shape the client+ // renders for one so it doesn't show a one-item thread picker.+ if (parts.length === 1) return { text: parts[0], length: parts[0].length };+ return { thread_parts: parts, length: parts.reduce((n, p) => n + p.length, 0) };+}export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;@@ -16,44 +90,101 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ // Drafting spends real LLM budget on the platform's keys, so it is gated like+ // the rest of the authenticated write surface: CSRF stops another origin from+ // burning a signed-in user's budget, and the bucket stops a single session+ // from turning the endpoint into a free LLM relay.+ if (!(await requireCsrf(req, res, user.id))) return;++ const rl = await limits.xDraftIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const body = await readJson(req);const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;+ if (agentId && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');+const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ if (prompt.length > MAX_PROMPT_LEN) {+ return error(res, 400, 'validation_error', `prompt must be ${MAX_PROMPT_LEN} characters or fewer`);+ }+ const requestedTone = typeof body?.tone === 'string' ? body.tone : '';+ if (requestedTone && !TONE_GUIDE[requestedTone]) {+ return error(res, 400, 'validation_error', `tone must be one of: ${Object.keys(TONE_GUIDE).join(', ')}`);+ }+ const thread = body?.thread === true;++ const rawCount = body?.count === undefined ? 1 : Number(body.count);+ if (!Number.isInteger(rawCount) || rawCount < 1 || rawCount > MAX_DRAFTS) {+ return error(res, 400, 'validation_error', `count must be an integer between 1 and ${MAX_DRAFTS}`);+ }++ // Persona context. The dashboard sends `avatar.agent_id || avatar.id`, so the+ // id can address either table; resolve both, scoped to the caller, so nobody+ // can pull another owner's private agent description into a prompt.let agentContext = '';+ let storedTone = '';if (agentId) {- const rows = await sql`select id, name, description from avatars where id = ${agentId} limit 1`;- const a = rows[0];- if (a) agentContext = `Agent name: ${a.name || 'Unnamed'}\nAgent description: ${a.description || '(none)'}`;- }-- const system = `You write tweets for AI agents on three.ws. Tweets must be:-- Under ${MAX_TWEET_LEN} characters (hard limit).-- In the agent's voice (first person, matching the description).-- No hashtag spam. At most 1 hashtag.-- No leading/trailing quotes. Plain text only.-- Avoid em-dashes.-Output ONLY the tweet text, nothing else.`;-- const userPrompt = [- agentContext,- prompt ? `What to post about: ${prompt}` : 'Write something engaging about being an autonomous AI agent.',- ].filter(Boolean).join('\n\n');-- let result;- try {- result = await llmComplete({ system, user: userPrompt, maxTokens: 200 });- } catch (err) {- if (err instanceof LlmUnavailableError) {- return error(res, 503, 'llm_unavailable', 'draft generation is not available right now');+ const [identity] = await sql`+ select name, description from agent_identities+ where id = ${agentId} and user_id = ${user.id} and deleted_at is null+ limit 1+ `;+ const [avatar] = identity+ ? []+ : await sql`select name, description, tone from avatars where id = ${agentId} and user_id = ${user.id} limit 1`;+ const a = identity || avatar;+ if (a) {+ agentContext = `Agent name: ${a.name || 'Unnamed'}\nAgent description: ${a.description || '(none)'}`;+ if (typeof a.tone === 'string' && TONE_GUIDE[a.tone]) storedTone = a.tone;}- console.error('[x-draft] LLM failed', err.status || '', err.message);- return error(res, 502, 'llm_failed', 'draft generation failed');}+ // Explicit tone wins; otherwise fall back to the agent's saved tone.+ const tone = requestedTone || storedTone || 'neutral';++ const system = buildSystem({ tone, thread });+ const topic = prompt+ ? `What to post about: ${prompt}`+ : 'Write something engaging about being an autonomous AI agent.';++ const settled = await Promise.allSettled(+ Array.from({ length: rawCount }, (_, i) =>+ llmComplete({+ system,+ user: [agentContext, topic, `Angle: ${ANGLES[i % ANGLES.length]}`].filter(Boolean).join('\n\n'),+ maxTokens: thread ? 600 : 200,+ track: { userId: user.id, agentId, tool: 'x/draft' },+ }),+ ),+ );- let text = result.text;- if (text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();- if (text.length > MAX_TWEET_LEN) text = text.slice(0, MAX_TWEET_LEN - 1) + '…';+ const drafts = [];+ const seen = new Set();+ let unavailable = false;+ let lastError = null;+ for (const outcome of settled) {+ if (outcome.status === 'rejected') {+ if (outcome.reason instanceof LlmUnavailableError) unavailable = true;+ else lastError = outcome.reason;+ continue;+ }+ const draft = toDraft(outcome.value?.text, thread);+ if (!draft) continue;+ // Different angles occasionally converge on the same line; show it once.+ const key = draft.thread_parts ? draft.thread_parts.join('\u0000') : draft.text;+ if (seen.has(key)) continue;+ seen.add(key);+ drafts.push(draft);+ }++ if (!drafts.length) {+ if (unavailable) return error(res, 503, 'llm_unavailable', 'draft generation is not available right now');+ if (lastError) {+ console.error('[x-draft] LLM failed', lastError.status || '', lastError.message);+ return error(res, 502, 'llm_failed', 'draft generation failed');+ }+ return error(res, 502, 'llm_empty', 'the model returned no usable draft, try again');+ }- return json(res, 200, { text, length: text.length });+ return json(res, 200, { drafts, tone, thread });});diff --git a/api/x/post.js b/api/x/post.jsindex 04b19a942..67582d7de 100644--- a/api/x/post.js+++ b/api/x/post.js@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');- // Publishing to the user's connected X account is a sensitive state change —+ // Publishing to the user's connected X account is a sensitive state change,// gate it behind CSRF like the rest of the write surface (marketplace, etc.),// and rate-limit so a leaked session can't spam the account.if (!(await requireCsrf(req, res, user.id))) return;diff --git a/api/x/reviews.js b/api/x/reviews.jsindex 1ecde6757..dde32d1db 100644--- a/api/x/reviews.js+++ b/api/x/reviews.js@@ -1,12 +1,13 @@-// GET /api/x/reviews — list pending review drafts-// PATCH /api/x/reviews?id=<uuid> — approve (publishes) or edit + approve+// GET /api/x/reviews: list pending review drafts+// PATCH /api/x/reviews?id=<uuid>: approve (publishes) or edit + approve// body: { action: 'approve'|'reject', text?, thread_parts? }-// DELETE /api/x/reviews?id=<uuid> — reject without publishing+// DELETE /api/x/reviews?id=<uuid>: reject without publishingimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';import { publishTweet, XPostError } from '../_lib/x-post.js';export default wrap(async (req, res) => {@@ -27,40 +28,62 @@ export default wrap(async (req, res) => {return json(res, 200, { reviews: rows });}- // PATCH (approve/edit/reject) and DELETE (reject) are state-changing — gate+ // PATCH (approve/edit/reject) and DELETE (reject) are state-changing, so gate// them behind CSRF before touching the review.if (!(await requireCsrf(req, res, user.id))) return;const url = new URL(req.url, 'http://x');const id = url.searchParams.get('id');if (!id) return error(res, 400, 'validation_error', 'id required');+ // `id` addresses a uuid primary key; a junk value would reach Postgres as a+ // cast error and turn a caller mistake into a 500.+ if (!isUuid(id)) return error(res, 400, 'validation_error', 'id must be a uuid');- const rows = await sql`- select * from x_pending_reviews- where id = ${id} and user_id = ${user.id} and status = 'pending'- limit 1- `;- const review = rows[0];- if (!review) return error(res, 404, 'not_found', 'review not found or already resolved');-- if (req.method === 'DELETE') {- await sql`update x_pending_reviews set status = 'rejected', resolved_at = now() where id = ${id}`;+ // Reject: one conditional write, so a second request on the same review is a+ // clean 404 rather than a silent no-op reported as success.+ const reject = async () => {+ const done = await sql`+ update x_pending_reviews set status = 'rejected', resolved_at = now()+ where id = ${id} and user_id = ${user.id} and status = 'pending'+ returning id+ `;+ if (!done.length) return error(res, 404, 'not_found', 'review not found or already resolved');return json(res, 200, { rejected: id });- }+ };++ if (req.method === 'DELETE') return reject();- // PATCH — approve (possibly with edits)+ // PATCH: approve (possibly with edits) or reject.const body = await readJson(req);- const action = body?.action || 'approve';- if (action === 'reject') {- await sql`update x_pending_reviews set status = 'rejected', resolved_at = now() where id = ${id}`;- return json(res, 200, { rejected: id });- }+ const action = body?.action ?? 'approve';+ if (action === 'reject') return reject();if (action !== 'approve') return error(res, 400, 'validation_error', 'action must be approve or reject');- const text = typeof body?.text === 'string' ? body.text : review.text;- const threadParts = Array.isArray(body?.thread_parts) ? body.thread_parts : (Array.isArray(review.thread_parts) ? review.thread_parts : null);+ if (body?.text !== undefined && typeof body.text !== 'string') {+ return error(res, 400, 'validation_error', 'text must be a string');+ }+ if (body?.thread_parts !== undefined) {+ if (!Array.isArray(body.thread_parts) || body.thread_parts.some((p) => typeof p !== 'string')) {+ return error(res, 400, 'validation_error', 'thread_parts must be an array of strings');+ }+ }const appendLink = body?.append_link === true;+ // Claim the review in the same statement that checks it is still pending. A+ // select-then-publish-then-update let two concurrent approvals of one review+ // both reach X; only the tweet-text dedup window stopped a real double post.+ const [review] = await sql`+ update x_pending_reviews set status = 'approved', resolved_at = now()+ where id = ${id} and user_id = ${user.id} and status = 'pending'+ returning id, agent_id, text, thread_parts+ `;+ if (!review) return error(res, 404, 'not_found', 'review not found or already resolved');++ const text = typeof body?.text === 'string' ? body.text : review.text;+ const threadParts = Array.isArray(body?.thread_parts)+ ? body.thread_parts+ : (Array.isArray(review.thread_parts) ? review.thread_parts : null);+try {const result = await publishTweet({userId: user.id,@@ -69,10 +92,15 @@ export default wrap(async (req, res) => {threadParts,appendLink,});- await sql`update x_pending_reviews set status = 'approved', resolved_at = now() where id = ${id}`;return json(res, 200, { approved: id, ...result });} catch (err) {+ // Nothing was published, so hand the review back to the queue instead of+ // leaving it marked approved with no tweet behind it.+ await sql`+ update x_pending_reviews set status = 'pending', resolved_at = null where id = ${id}+ `.catch((e) => console.error('[x-reviews] could not release review', id, e.message));if (err instanceof XPostError) return error(res, err.status, err.code, err.message, err.extra);+ console.error('[x-reviews] publish failed', err);return error(res, 500, 'internal_error', err.message || 'publish failed');}});diff --git a/api/x/schedule.js b/api/x/schedule.jsindex cd064c153..425d71380 100644--- a/api/x/schedule.js+++ b/api/x/schedule.js@@ -1,13 +1,21 @@-// GET /api/x/schedule — list pending + recent scheduled posts-// POST /api/x/schedule — schedule a new post { text, scheduled_at, agent_id? }-// DELETE /api/x/schedule?id=<uuid> — cancel a pending scheduled post+// GET /api/x/schedule: list pending + recent scheduled posts+// POST /api/x/schedule: schedule a new post { text, scheduled_at, agent_id? }+// DELETE /api/x/schedule?id=<uuid>: cancel a pending scheduled postimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';import { MAX_TWEET_LEN } from '../_lib/x-post.js';+// Ceiling on the queue one account can hold. The publish cron scans pending rows+// every minute, so an unbounded queue is both a load problem and a way to park+// far more posts than the monthly quota could ever drain.+const MAX_PENDING_POSTS = 100;+// A schedule further out than this is a mistake, not a plan.+const MAX_SCHEDULE_AHEAD_MS = 365 * 24 * 60 * 60 * 1000;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;@@ -31,6 +39,9 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const id = url.searchParams.get('id');if (!id) return error(res, 400, 'validation_error', 'id required');+ // `id` addresses a uuid primary key; a junk value would reach Postgres as a+ // cast error and turn a caller mistake into a 500.+ if (!isUuid(id)) return error(res, 400, 'validation_error', 'id must be a uuid');const result = await sql`delete from x_scheduled_postswhere id = ${id} and user_id = ${user.id} and posted_at is null@@ -46,12 +57,16 @@ export default wrap(async (req, res) => {const text = typeof body?.text === 'string' ? body.text.trim() : '';const scheduledAt = typeof body?.scheduled_at === 'string' ? body.scheduled_at : '';const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;+ if (agentId && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');if (!text) return error(res, 400, 'validation_error', 'text required');if (text.length > MAX_TWEET_LEN) return error(res, 400, 'validation_error', `text exceeds ${MAX_TWEET_LEN} chars`);const when = new Date(scheduledAt);if (!scheduledAt || isNaN(when.getTime())) return error(res, 400, 'validation_error', 'scheduled_at must be a valid ISO timestamp');if (when.getTime() < Date.now() - 60_000) return error(res, 400, 'validation_error', 'scheduled_at must be in the future');+ if (when.getTime() > Date.now() + MAX_SCHEDULE_AHEAD_MS) {+ return error(res, 400, 'validation_error', 'scheduled_at must be within a year from now');+ }// Require a connected X account before accepting a schedule.const conn = await sql`@@ -61,6 +76,14 @@ export default wrap(async (req, res) => {`;if (!conn.length) return error(res, 400, 'not_connected', 'connect X account first');+ const [{ count }] = await sql`+ select count(*)::int as count from x_scheduled_posts+ where user_id = ${user.id} and posted_at is null+ `;+ if (count >= MAX_PENDING_POSTS) {+ return error(res, 409, 'limit_reached', `you already have ${MAX_PENDING_POSTS} posts queued, cancel one first`);+ }+const rows = await sql`insert into x_scheduled_posts (user_id, agent_id, text, scheduled_at)values (${user.id}, ${agentId}, ${text}, ${when.toISOString()})diff --git a/api/x/status.js b/api/x/status.jsindex 44ac957c5..56d56a1cd 100644--- a/api/x/status.js+++ b/api/x/status.js@@ -1,5 +1,5 @@-// GET /api/x/status — connection + quota + tier-// DELETE /api/x/status — disconnect+// GET /api/x/status: connection + quota + tier+// DELETE /api/x/status: disconnectimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';diff --git a/api/x/triggers.js b/api/x/triggers.jsindex ce98d0242..fd9795155 100644--- a/api/x/triggers.js+++ b/api/x/triggers.js@@ -1,27 +1,32 @@-// GET /api/x/triggers — list triggers for current user-// POST /api/x/triggers — create { kind, config, agent_id?, enabled? }-// PATCH /api/x/triggers?id=<uuid> — update { config?, enabled? }-// DELETE /api/x/triggers?id=<uuid> — delete+// GET /api/x/triggers: list triggers for current user+// POST /api/x/triggers: create { kind, config, agent_id?, enabled? }+// PATCH /api/x/triggers?id=<uuid>: update { config?, enabled? }+// DELETE /api/x/triggers?id=<uuid>: deleteimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';const VALID_KINDS = new Set(['daily_persona', 'weekly_digest', 'price_milestone', 'payment_received']);+// Ceiling per account. The run-x-triggers cron evaluates every enabled row on+// every tick, so an unbounded list is a self-inflicted load problem; 50 is far+// more rules than any real posting schedule needs.+const MAX_TRIGGERS_PER_USER = 50;function validateConfig(kind, config) {- if (typeof config !== 'object' || config === null) throw new Error('config must be an object');+ if (typeof config !== 'object' || config === null || Array.isArray(config)) throw new Error('config must be an object');if (kind === 'daily_persona') {const h = Number(config.hour_utc);- if (!Number.isInteger(h) || h < 0 || h > 23) throw new Error('hour_utc must be integer 0–23');+ if (!Number.isInteger(h) || h < 0 || h > 23) throw new Error('hour_utc must be an integer from 0 to 23');if (config.topic && typeof config.topic !== 'string') throw new Error('topic must be a string');}if (kind === 'weekly_digest') {const d = Number(config.day_of_week);const h = Number(config.hour_utc);- if (!Number.isInteger(d) || d < 0 || d > 6) throw new Error('day_of_week must be integer 0 (Sun)–6 (Sat)');- if (!Number.isInteger(h) || h < 0 || h > 23) throw new Error('hour_utc must be integer 0–23');+ if (!Number.isInteger(d) || d < 0 || d > 6) throw new Error('day_of_week must be an integer from 0 (Sun) to 6 (Sat)');+ if (!Number.isInteger(h) || h < 0 || h > 23) throw new Error('hour_utc must be an integer from 0 to 23');}if (kind === 'price_milestone') {if (!Array.isArray(config.thresholds_usd) || !config.thresholds_usd.length) throw new Error('thresholds_usd must be non-empty array of numbers');@@ -42,6 +47,9 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const id = url.searchParams.get('id');+ // `id` addresses a uuid primary key, so a junk value would reach Postgres as a+ // cast error and turn a caller mistake into a 500.+ if (id !== null && !isUuid(id)) return error(res, 400, 'validation_error', 'id must be a uuid');if (req.method === 'GET') {const rows = await sql`@@ -61,8 +69,15 @@ export default wrap(async (req, res) => {const config = body?.config ?? {};try { validateConfig(kind, config); } catch (err) { return error(res, 400, 'validation_error', err.message); }const agentId = typeof body?.agent_id === 'string' ? body.agent_id : null;+ if (agentId && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');const enabled = body?.enabled !== false;const autoPublish = body?.auto_publish !== false;++ const [{ count }] = await sql`select count(*)::int as count from x_triggers where user_id = ${user.id}`;+ if (count >= MAX_TRIGGERS_PER_USER) {+ return error(res, 409, 'limit_reached', `you already have ${MAX_TRIGGERS_PER_USER} triggers, delete one first`);+ }+const rows = await sql`insert into x_triggers (user_id, agent_id, kind, config, enabled, auto_publish)values (${user.id}, ${agentId}, ${kind}, ${JSON.stringify(config)}::jsonb, ${enabled}, ${autoPublish})@@ -95,6 +110,9 @@ export default wrap(async (req, res) => {where id = ${id} and user_id = ${user.id}returning id, agent_id, kind, config, enabled, auto_publish, last_fired_at, created_at, updated_at`;+ // The row can be deleted between the ownership read and the update; report+ // that honestly instead of returning a trigger-shaped hole.+ if (!rows.length) return error(res, 404, 'not_found', 'trigger not found');return json(res, 200, { trigger: rows[0] });}diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.jsindex bdfce2c2c..6d57a15d2 100644--- a/api/x402/pay-by-name.js+++ b/api/x402/pay-by-name.js@@ -126,7 +126,15 @@ async function handlePaidNameResolve(req, res, body) {});}+ // Resolve BEFORE settling. A name that resolves to nothing has no value to+ // sell, so the payment is left unspent and the buyer can retry or pay a+ // different endpoint. Settling first would have charged $0.001 for an+ // { address: null } answer, which is exactly what the pipeline stages take+ // care never to do.const resolved = await resolveName(name);+ if (!resolved?.address) {+ return error(res, 404, 'not_found', `could not resolve "${name}" (payment was not taken)`);+ }let settleResult;try {@@ -150,9 +158,9 @@ async function handlePaidNameResolve(req, res, body) {return json(res, 200, {data: {name,- address: resolved?.address ?? null,- verified: isOnCurveAddress(resolved?.address),- source: resolved?.source ?? null,+ address: resolved.address,+ verified: isOnCurveAddress(resolved.address),+ source: resolved.source ?? null,},});}diff --git a/api/x402/permit2-paid-demo.js b/api/x402/permit2-paid-demo.jsindex 4772e34eb..09e0ae131 100644--- a/api/x402/permit2-paid-demo.js+++ b/api/x402/permit2-paid-demo.js@@ -193,43 +193,14 @@ export default wrap(async (req, res) => {serviceName: 'three.ws Permit2 Demo',tags: ['x402', 'permit2', 'eip2612', 'gasless', 'demo'],});- let requirements;- try {- requirements = buildRequirements(resourceUrl);- } catch (err) {- if (err instanceof X402Error && err.status === 402) {- return send402(res, {- resourceUrl,- accepts: [],- description: ROUTE_DESCRIPTION,- bazaar: ROUTE_BAZAAR,- error: err.message,- serviceName: service.serviceName,- tags: service.tags,- iconUrl: service.iconUrl,- });- }- return error(- res,- err.status || 500,- err.code || 'misconfigured',- err.message || 'permit2-paid-demo misconfigured',- );- }- const challenge = {- resourceUrl,- accepts: requirements,- description: ROUTE_DESCRIPTION,- bazaar: ROUTE_BAZAAR,- serviceName: service.serviceName,- tags: service.tags,- iconUrl: service.iconUrl,- };-- // USE-23: bypass payment for internal / subscription / OAuth callers.- // The Permit2 demo skips its payload-shape check on bypass — the bypass- // caller never signed a payment, so there's nothing to validate.+ // USE-23: bypass payment for internal / subscription / OAuth callers. This+ // runs BEFORE buildRequirements on purpose. A bypass caller never signs a+ // payment, so the CDP credentials that Permit2 settlement needs are+ // irrelevant to them; building requirements first made the whole bypass+ // branch unreachable on any deployment without CDP creds (it 402'd instead).+ // The Permit2 payload-shape check below is skipped for the same reason:+ // there is no payload to validate.const acResult = await accessControl(req, routeConfig);if (acResult?.abort) {if (acResult.headers) {@@ -250,9 +221,9 @@ export default wrap(async (req, res) => {supportsEip2612: true,bypass: acResult.reason,payer: null,- network: requirements[0]?.network || null,- asset: requirements[0]?.asset || null,- amountAtomics: requirements[0]?.amount || null,+ network: NETWORK_BASE_MAINNET,+ asset: env.X402_ASSET_ADDRESS_BASE || null,+ amountAtomics: PRICE_ATOMICS,transaction: null,explorer: null,settledAt: null,@@ -268,6 +239,40 @@ export default wrap(async (req, res) => {return;}+ let requirements;+ try {+ requirements = buildRequirements(resourceUrl);+ } catch (err) {+ if (err instanceof X402Error && err.status === 402) {+ return send402(res, {+ resourceUrl,+ accepts: [],+ description: ROUTE_DESCRIPTION,+ bazaar: ROUTE_BAZAAR,+ error: err.message,+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ });+ }+ return error(+ res,+ err.status || 500,+ err.code || 'misconfigured',+ err.message || 'permit2-paid-demo misconfigured',+ );+ }++ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: ROUTE_DESCRIPTION,+ bazaar: ROUTE_BAZAAR,+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };+const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];if (!paymentHeader) return send402(res, challenge);diff --git a/api/x402/pump-agent-audit.js b/api/x402/pump-agent-audit.jsindex b77c9a5eb..aca8b2dd3 100644--- a/api/x402/pump-agent-audit.js+++ b/api/x402/pump-agent-audit.js@@ -340,11 +340,18 @@ async function markAgentTokens(launches) {}}-async function loadRecentLaunches({ limit, sort }) {- const n = Math.min(25, Math.max(1, Number(limit) || 10));- const raw = await recentPumpLaunches({ network: 'mainnet', limit: n });- const launches = await markAgentTokens(raw);+// Build the LIST-mode response from the raw (newest-first) feed. Exported for+// tests: the newest_* fields must keep describing the NEWEST launch even under+// sort=liquidity, so `newest` is read off the feed BEFORE the re-rank. Reading+// index 0 of the already-sorted array reported the highest-liquidity launch as+// the newest one, which only looked right whenever the two happened to coincide.+export function summarizeLaunches(feed, sort) {+ const newest = feed.reduce(+ (best, l) => (best == null || (l?.created_at ?? -Infinity) > (best.created_at ?? -Infinity) ? l : best),+ null,+ );+ const launches = feed.slice();// sort='liquidity' re-ranks by initial bonding-curve SOL reserves, highest first.if (sort === 'liquidity') {launches.sort((a, b) => (b.liquidity_sol ?? 0) - (a.liquidity_sol ?? 0));@@ -353,7 +360,6 @@ async function loadRecentLaunches({ limit, sort }) {const liq = launches.map((l) => l.liquidity_sol).filter((v) => v != null && v > 0);const avgLiq = liq.length ? liq.reduce((a, b) => a + b, 0) / liq.length : null;const maxLiq = liq.length ? Math.max(...liq) : null;- const newest = launches[sort === 'liquidity' ? 0 : 0]; // feed is newest-first from sourcereturn {network: 'mainnet',@@ -365,6 +371,16 @@ async function loadRecentLaunches({ limit, sort }) {avg_initial_liquidity_sol: avgLiq != null ? Math.round(avgLiq * 1e4) / 1e4 : null,max_initial_liquidity_sol: maxLiq != null ? Math.round(maxLiq * 1e4) / 1e4 : null,launches,+ };+}++async function loadRecentLaunches({ limit, sort }) {+ const n = Math.min(25, Math.max(1, Number(limit) || 10));+ const raw = await recentPumpLaunches({ network: 'mainnet', limit: n });+ const feed = await markAgentTokens(raw);++ return {+ ...summarizeLaunches(feed, sort),queried_at: new Date().toISOString(),};}@@ -546,9 +562,8 @@ async function detectWhaleActivity(limit) {// Read + parse the JSON body off the raw request stream (same idiom as the// other POST x402 endpoints — req.body is not pre-parsed in this runtime).async function readJsonBody(req) {- const chunks = [await readBody(req, 1_000_000)];- if (!chunks.length) return {};- return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+ const raw = await readBody(req, 1_000_000);+ return JSON.parse(Buffer.from(raw).toString('utf8') || '{}');}const WHALE_DESCRIPTION =diff --git a/data/changelog.json b/data/changelog.jsonindex 198c3b200..94f78f971 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-14",+ "title": "Paying to resolve a name that does not exist no longer costs anything",+ "summary": "The paid name-resolution call on /api/x402/pay-by-name sells one thing: the on-chain address behind a @username, a .sol name, or a raw wallet. When the name resolved to nothing it still took the $0.001 toll and handed back an empty answer. It now returns a plain 404 and leaves the payment unspent, so a buyer only ever pays for an address they actually received. Two smaller corrections shipped alongside: the pump launch feed's headline fields (newest mint, name and symbol) kept describing the newest launch when the list is ranked by liquidity instead of by age, rather than whichever coin happened to sit at the top; and internal and subscription callers can once again reach the Permit2 gas-sponsoring demo on deployments that have no card-facilitator credentials, since those callers never sign a payment in the first place.",+ "tags": [+ "fix"+ ],+ "link": "/docs/x402-endpoints"+ },{"date": "2026-08-14","title": "Agent share cards keep their portrait, and a sealed-drop card always paints a real theme",diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex 89e157655..afc63459e 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -222,7 +222,7 @@ datapoints at **$0.0005** USDC each by default, overridable per family with| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 (≤3) · $2.50–$10 (4–5, inventory-only) | **Vanity Grinder** — get a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Checks the pre-ground warehouse first for **instant delivery** (`source: "inventory"`); falls back to a live grind (`source: "ground"`) up to 3 chars. Keypair or importable BIP-39 mnemonic; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). || [`/api/x402/vanity-verifiable`](vanity.md#tier-2--provably-fair-grinder) | $0.02–$0.40 | **Provably-fair grinder** — same grind with a signed commit–reveal receipt proving the key was ground fresh and never kept. Spec: [PROTOCOL-vanity.md](PROTOCOL-vanity.md). || [`/api/x402/vanity-premium`](vanity.md#tier-3--premium-inventory) | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. |-| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. |+| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. A name that resolves to nothing returns `404 not_found` and the payment is left unsettled, so an unresolvable name is free. || `/api/x402/did` | $0.001 | Decentralized identifier resolution. || `/api/x402/three-buy` | $0.001 | Micro-buy service: one settled toll payment triggers one small, real on-chain USDC to $THREE buy funded by the micro-buy wallet (driven by the `three-buy-loop` cron). || `/api/x402/billboard` | $0.05 | Post to the on-platform billboard. |diff --git a/prompts/swarm-100/api-x402-07.md b/prompts/swarm-100/api-x402-07.mddeleted file mode 100644index c78997716..000000000--- a/prompts/swarm-100/api-x402-07.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/x402 batch 07 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/x402/onchain-identity-verify.js-- api/x402/pay-by-name.js-- api/x402/permit2-paid-demo.js-- api/x402/pipeline-gameready.js-- api/x402/pipeline-rembg.js-- api/x402/pipeline-remesh.js-- api/x402/pipeline-rig.js-- api/x402/pipeline-stylize.js-- api/x402/pipeline.js-- api/x402/pump-agent-audit.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-x402-07.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex aafa66125..d154eb1e0 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -1082,7 +1082,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {async function generateDrafts(count) {try {- const r = await fetch('/api/x/draft', {+ const r = await apiFetch('/api/x/draft', {method: 'POST',credentials: 'include',headers: { 'content-type': 'application/json' },diff --git a/tests/api-x-endpoints.test.js b/tests/api-x-endpoints.test.jsnew file mode 100644index 000000000..5b3feb07c--- /dev/null+++ b/tests/api-x-endpoints.test.js@@ -0,0 +1,411 @@+// Endpoint tests for the /api/x/* surface (analytics, draft, post, reviews,+// schedule, status, triggers). Each handler runs for real against a fake req/res+// with the DB, auth, CSRF, rate limiter, LLM chain, and X publish helper mocked,+// so http.js (cors/method/wrap/json/error) genuinely produces the status codes+// and envelopes the dashboard X panel renders against.+//+// Every case here is either the main path or a failure path that used to reach+// Postgres with an uncastable value and 500 on a caller mistake.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Tagged-template `sql` that returns whatever the test queued, in order.+const queue = [];+const sqlCalls = [];+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ sqlCalls.push(String(strings?.raw ? strings.join('?') : strings));+ return queue.length ? queue.shift() : [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++let session = null;+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++let csrfOk = true;+vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => csrfOk),+}));++let rateOk = true;+vi.mock('../api/_lib/rate-limit.js', () => {+ const allow = async () => ({ success: rateOk, limit: 20, remaining: rateOk ? 19 : 0, reset: 1 });+ return {+ limits: { authIp: allow, xDraftIp: allow },+ clientIp: () => '127.0.0.1',+ };+});++// Error classes the handlers branch on with `instanceof`. They are declared+// through vi.hoisted because the module factories below reference them at+// factory-evaluation time, which runs before ordinary top-level declarations.+const { XPostError, LlmUnavailableError } = vi.hoisted(() => {+ class XPostError extends Error {+ constructor(code, message, status = 400, extra = {}) {+ super(message);+ this.code = code;+ this.status = status;+ this.extra = extra;+ }+ }+ class LlmUnavailableError extends Error {+ constructor() {+ super('no provider');+ this.code = 'llm_unavailable';+ this.status = 503;+ }+ }+ return { XPostError, LlmUnavailableError };+});++const publishTweet = vi.fn();+const getUserTier = vi.fn(async () => ({ tier: 'free', quota: 5, min_interval_min: 30 }));+vi.mock('../api/_lib/x-post.js', () => ({+ MAX_TWEET_LEN: 280,+ XPostError,+ publishTweet: (...a) => publishTweet(...a),+ getUserTier: (...a) => getUserTier(...a),+}));++const llmComplete = vi.fn();+vi.mock('../api/_lib/llm.js', () => ({+ llmComplete: (...a) => llmComplete(...a),+ LlmUnavailableError,+}));++const revokeAllSeedConsentsForUser = vi.fn(async () => ({ consents: 2, deleted: 7, agents: 1 }));+vi.mock('../api/_lib/x-seed-consent.js', () => ({+ revokeAllSeedConsentsForUser: (...a) => revokeAllSeedConsentsForUser(...a),+}));++import analytics from '../api/x/analytics.js';+import draft from '../api/x/draft.js';+import post from '../api/x/post.js';+import reviews from '../api/x/reviews.js';+import schedule from '../api/x/schedule.js';+import status from '../api/x/status.js';+import triggers from '../api/x/triggers.js';++const UUID = '11111111-2222-4333-8444-555555555555';+const AGENT = '99999999-8888-4777-8666-555555555555';++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload ?? null; },+ get json() { return this.body ? JSON.parse(this.body) : null; },+ };+}++function mockReq({ method = 'GET', url = '/', body, headers = {} } = {}) {+ const req = { method, url, headers: { ...headers }, socket: {} };+ if (body !== undefined) {+ req.body = body;+ req.headers['content-type'] = 'application/json';+ }+ return req;+}++async function call(handler, reqInit) {+ const res = mockRes();+ await handler(mockReq(reqInit), res);+ return res;+}++beforeEach(() => {+ queue.length = 0;+ sqlCalls.length = 0;+ session = { id: 'user-1', email: '[email protected]' };+ csrfOk = true;+ rateOk = true;+ vi.clearAllMocks();+ getUserTier.mockResolvedValue({ tier: 'free', quota: 5, min_interval_min: 30 });+ revokeAllSeedConsentsForUser.mockResolvedValue({ consents: 2, deleted: 7, agents: 1 });+});++describe('GET /api/x/analytics', () => {+ it('rolls up engagement totals across the caller posts', async () => {+ queue.push([+ { id: 'p1', tweet_id: '1', text: 'a', agent_id: AGENT, metrics: { like_count: 3, retweet_count: 1, impression_count: 100 } },+ // jsonb can hand back a count as a string; totals must stay numeric.+ { id: 'p2', tweet_id: '2', text: 'b', agent_id: AGENT, metrics: { like_count: '4', reply_count: 2, impression_count: '50' } },+ ]);+ const res = await call(analytics, { url: '/api/x/analytics' });+ expect(res.statusCode).toBe(200);+ expect(res.json.totals).toEqual({ posts: 2, likes: 7, retweets: 1, replies: 2, quotes: 0, impressions: 150 });+ expect(res.json.posts).toHaveLength(2);+ });++ it('rejects a non-uuid agent_id instead of letting the cast 500', async () => {+ const res = await call(analytics, { url: '/api/x/analytics?agent_id=not-a-uuid' });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('validation_error');+ expect(sqlCalls).toHaveLength(0);+ });++ it('requires a session', async () => {+ session = null;+ const res = await call(analytics, { url: '/api/x/analytics' });+ expect(res.statusCode).toBe(401);+ });+});++describe('POST /api/x/draft', () => {+ it('returns one draft per requested count in the shape the dashboard renders', async () => {+ queue.push([{ name: 'Nova', description: 'a scout agent' }]); // agent_identities hit+ llmComplete+ .mockResolvedValueOnce({ text: '"first idea"' })+ .mockResolvedValueOnce({ text: 'second idea' })+ .mockResolvedValueOnce({ text: 'third idea' });++ const res = await call(draft, {+ method: 'POST',+ url: '/api/x/draft',+ body: { agent_id: AGENT, prompt: 'ship day', tone: 'hype', count: 3 },+ });++ expect(res.statusCode).toBe(200);+ expect(res.json.drafts).toEqual([+ { text: 'first idea', length: 10 },+ { text: 'second idea', length: 11 },+ { text: 'third idea', length: 10 },+ ]);+ expect(res.json.tone).toBe('hype');+ expect(llmComplete).toHaveBeenCalledTimes(3);+ // Persona context and the per-user LLM spend cap are both wired.+ expect(llmComplete.mock.calls[0][0].user).toContain('Agent name: Nova');+ expect(llmComplete.mock.calls[0][0].track).toMatchObject({ userId: 'user-1' });+ });++ it('splits a thread completion into thread_parts', async () => {+ queue.push([]); // no agent_identities row+ queue.push([]); // no avatars row+ llmComplete.mockResolvedValueOnce({ text: 'part one\n---\npart two\n---\npart three' });+ const res = await call(draft, { method: 'POST', url: '/api/x/draft', body: { thread: true } });+ expect(res.statusCode).toBe(200);+ expect(res.json.drafts[0].thread_parts).toEqual(['part one', 'part two', 'part three']);+ });++ it('caps a long completion at the tweet limit', async () => {+ llmComplete.mockResolvedValueOnce({ text: 'x'.repeat(400) });+ const res = await call(draft, { method: 'POST', url: '/api/x/draft', body: {} });+ expect(res.json.drafts[0].text).toHaveLength(280);+ });++ it('reports 503 when no LLM provider is available', async () => {+ llmComplete.mockRejectedValue(new LlmUnavailableError());+ const res = await call(draft, { method: 'POST', url: '/api/x/draft', body: {} });+ expect(res.statusCode).toBe(503);+ expect(res.json.error).toBe('llm_unavailable');+ });++ it('rejects an out-of-range count before spending a completion', async () => {+ const res = await call(draft, { method: 'POST', url: '/api/x/draft', body: { count: 9 } });+ expect(res.statusCode).toBe(400);+ expect(llmComplete).not.toHaveBeenCalled();+ });++ it('rejects an unknown tone', async () => {+ const res = await call(draft, { method: 'POST', url: '/api/x/draft', body: { tone: 'shakespearean' } });+ expect(res.statusCode).toBe(400);+ });++ it('is gated by CSRF and the draft rate limit', async () => {+ csrfOk = false;+ expect((await call(draft, { method: 'POST', url: '/api/x/draft', body: {} })).body).toBeNull();+ expect(llmComplete).not.toHaveBeenCalled();+ csrfOk = true;+ rateOk = false;+ const limited = await call(draft, { method: 'POST', url: '/api/x/draft', body: {} });+ expect(limited.statusCode).toBe(429);+ expect(llmComplete).not.toHaveBeenCalled();+ });+});++describe('POST /api/x/post', () => {+ it('publishes and returns the tweet envelope', async () => {+ publishTweet.mockResolvedValue({ tweet_id: '5', url: 'https://x.com/a/status/5', posts_used: 1, quota: 5, tier: 'free' });+ const res = await call(post, { method: 'POST', url: '/api/x/post', body: { text: 'hello', agent_id: AGENT } });+ expect(res.statusCode).toBe(200);+ expect(res.json.tweet_id).toBe('5');+ expect(publishTweet).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user-1', text: 'hello' }));+ });++ it('maps an XPostError to its own status and code', async () => {+ publishTweet.mockRejectedValue(new XPostError('quota_exceeded', 'free tier limit reached', 402, { quota: 5 }));+ const res = await call(post, { method: 'POST', url: '/api/x/post', body: { text: 'hello' } });+ expect(res.statusCode).toBe(402);+ expect(res.json).toMatchObject({ error: 'quota_exceeded', quota: 5 });+ });+});++describe('/api/x/reviews', () => {+ it('claims the review before publishing so a concurrent approve cannot double post', async () => {+ queue.push([{ id: UUID, agent_id: AGENT, text: 'queued draft', thread_parts: null }]);+ publishTweet.mockResolvedValue({ tweet_id: '9', url: 'https://x.com/a/status/9' });+ const res = await call(reviews, { method: 'PATCH', url: `/api/x/reviews?id=${UUID}`, body: { action: 'approve' } });+ expect(res.statusCode).toBe(200);+ expect(res.json).toMatchObject({ approved: UUID, tweet_id: '9' });+ // The claim is a conditional UPDATE, not a SELECT.+ expect(sqlCalls[0]).toMatch(/update x_pending_reviews/);+ expect(sqlCalls[0]).toMatch(/status = 'pending'/);+ });++ it('releases the claim back to pending when publishing fails', async () => {+ queue.push([{ id: UUID, agent_id: AGENT, text: 'queued draft', thread_parts: null }]);+ publishTweet.mockRejectedValue(new XPostError('rate_limited', 'wait 3 more min', 429));+ const res = await call(reviews, { method: 'PATCH', url: `/api/x/reviews?id=${UUID}`, body: { action: 'approve' } });+ expect(res.statusCode).toBe(429);+ expect(sqlCalls[1]).toMatch(/status = 'pending'/);+ });++ it('404s an approve on a review that is already resolved', async () => {+ queue.push([]);+ const res = await call(reviews, { method: 'PATCH', url: `/api/x/reviews?id=${UUID}`, body: { action: 'approve' } });+ expect(res.statusCode).toBe(404);+ expect(publishTweet).not.toHaveBeenCalled();+ });++ it('rejects a non-uuid id instead of letting the cast 500', async () => {+ const res = await call(reviews, { method: 'DELETE', url: '/api/x/reviews?id=nope' });+ expect(res.statusCode).toBe(400);+ expect(sqlCalls).toHaveLength(0);+ });++ it('rejects a thread_parts override that is not an array of strings', async () => {+ const res = await call(reviews, {+ method: 'PATCH',+ url: `/api/x/reviews?id=${UUID}`,+ body: { action: 'approve', thread_parts: [1, 2] },+ });+ expect(res.statusCode).toBe(400);+ expect(sqlCalls).toHaveLength(0);+ });+});++describe('/api/x/schedule', () => {+ const future = () => new Date(Date.now() + 3_600_000).toISOString();++ it('queues a post for a connected account', async () => {+ queue.push([{ '?column?': 1 }]); // social_connections check+ queue.push([{ count: 3 }]); // pending count+ queue.push([{ id: UUID, scheduled_at: future() }]);+ const res = await call(schedule, { method: 'POST', url: '/api/x/schedule', body: { text: 'later', scheduled_at: future(), agent_id: AGENT } });+ expect(res.statusCode).toBe(201);+ expect(res.json.id).toBe(UUID);+ });++ it('refuses to queue past the per-account ceiling', async () => {+ queue.push([{ '?column?': 1 }]);+ queue.push([{ count: 100 }]);+ const res = await call(schedule, { method: 'POST', url: '/api/x/schedule', body: { text: 'later', scheduled_at: future() } });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('limit_reached');+ });++ it('rejects a schedule more than a year out', async () => {+ const res = await call(schedule, {+ method: 'POST',+ url: '/api/x/schedule',+ body: { text: 'later', scheduled_at: new Date(Date.now() + 400 * 86_400_000).toISOString() },+ });+ expect(res.statusCode).toBe(400);+ });++ it('rejects a non-uuid cancel id instead of letting the cast 500', async () => {+ const res = await call(schedule, { method: 'DELETE', url: '/api/x/schedule?id=nope' });+ expect(res.statusCode).toBe(400);+ expect(sqlCalls).toHaveLength(0);+ });+});++describe('/api/x/status', () => {+ it('reports connection, tier, and quota', async () => {+ getUserTier.mockResolvedValue({ tier: 'pro', quota: 100, min_interval_min: 5 });+ queue.push([{+ username: 'threews',+ posts_this_month: 4,+ month_resets_at: new Date(Date.now() + 86_400_000).toISOString(),+ connected_at: '2026-01-01T00:00:00.000Z',+ last_posted_at: null,+ }]);+ const res = await call(status, { url: '/api/x/status' });+ expect(res.statusCode).toBe(200);+ expect(res.json).toMatchObject({ connected: true, username: 'threews', tier: 'pro', quota: 100, posts_used: 4 });+ });++ it('reports a disconnected account without inventing a username', async () => {+ queue.push([]);+ const res = await call(status, { url: '/api/x/status' });+ expect(res.json).toEqual({ connected: false, tier: 'free', quota: 5 });+ });++ it('revokes seed consents on disconnect', async () => {+ const res = await call(status, { method: 'DELETE', url: '/api/x/status' });+ expect(res.statusCode).toBe(200);+ expect(res.json).toMatchObject({ disconnected: true, seed_consents_revoked: 2, seeded_memories_deleted: 7 });+ expect(revokeAllSeedConsentsForUser).toHaveBeenCalledWith('user-1', 'x_disconnected');+ });+});++describe('/api/x/triggers', () => {+ it('creates a trigger', async () => {+ queue.push([{ count: 2 }]);+ queue.push([{ id: UUID, kind: 'daily_persona', config: { hour_utc: 9 }, enabled: true, auto_publish: true }]);+ const res = await call(triggers, {+ method: 'POST',+ url: '/api/x/triggers',+ body: { kind: 'daily_persona', config: { hour_utc: 9 }, agent_id: AGENT },+ });+ expect(res.statusCode).toBe(201);+ expect(res.json.trigger.id).toBe(UUID);+ });++ it('rejects an out-of-range hour without a banned dash in the message', async () => {+ const res = await call(triggers, {+ method: 'POST',+ url: '/api/x/triggers',+ body: { kind: 'daily_persona', config: { hour_utc: 99 } },+ });+ expect(res.statusCode).toBe(400);+ expect(res.json.error_description).toBe('hour_utc must be an integer from 0 to 23');+ // Escapes, not literals: the dash characters themselves are banned in this repo.+ expect(res.json.error_description).not.toMatch(/[\u2013\u2014]/);+ });++ it('refuses to create past the per-account ceiling', async () => {+ queue.push([{ count: 50 }]);+ const res = await call(triggers, {+ method: 'POST',+ url: '/api/x/triggers',+ body: { kind: 'weekly_digest', config: { day_of_week: 1, hour_utc: 9 } },+ });+ expect(res.statusCode).toBe(409);+ });++ it('rejects a non-uuid id instead of letting the cast 500', async () => {+ const res = await call(triggers, { method: 'DELETE', url: '/api/x/triggers?id=nope' });+ expect(res.statusCode).toBe(400);+ expect(sqlCalls).toHaveLength(0);+ });++ it('404s a patch on a trigger that vanished mid-request', async () => {+ queue.push([{ kind: 'daily_persona', config: { hour_utc: 9 } }]); // ownership read+ queue.push([]); // update matched nothing+ const res = await call(triggers, { method: 'PATCH', url: `/api/x/triggers?id=${UUID}`, body: { enabled: false } });+ expect(res.statusCode).toBe(404);+ });+});diff --git a/tests/api/x402-pay-by-name-paid-resolve.test.js b/tests/api/x402-pay-by-name-paid-resolve.test.jsnew file mode 100644index 000000000..35b4c51f5--- /dev/null+++ b/tests/api/x402-pay-by-name-paid-resolve.test.js@@ -0,0 +1,184 @@+/**+ * /api/x402/pay-by-name: the PAID name-resolution lane (POST {"name":…} with+ * no payer_wallet / amount_usdc / mode).+ *+ * The point of this suite is the settlement ORDER. The endpoint sells one+ * thing: an on-chain address for a name. When the name resolves to nothing+ * there is no good to deliver, so the buyer's payment must be left unspent+ * (same rule the pipeline stages follow: never charge for a stage that+ * produced no output). Payment verify/settle are stubbed at the module+ * boundary; SNS and the DB are stubbed so the suite stays offline.+ */++import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_SOLANA: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ X402_FEE_PAYER_SOLANA: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ THREEWS_SOL_PARENT_DOMAIN: 'threews.sol',+ });+});++const verifyPaymentMock = vi.fn(async () => ({+ payer: 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk',+ requirement: { network: 'solana:mainnet', amount: '1000' },+}));+const settlePaymentMock = vi.fn(async () => ({ transaction: 'sig-1' }));+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ verifyPayment: (...a) => verifyPaymentMock(...a),+ settlePayment: (...a) => settlePaymentMock(...a),+ encodePaymentResponseHeader: () => 'stub-payment-response',+ };+});++const sqlMock = vi.fn(async () => []);+vi.mock('../../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const snsResolveMock = vi.fn();+vi.mock('@bonfida/spl-name-service', () => ({ resolve: (...a) => snsResolveMock(...a) }));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: () => null,+}));++vi.mock('../../api/_lib/agent-pumpfun.js', () => ({+ solanaConnection: () => ({}),+ loadAgentForSigning: vi.fn(async () => ({ error: { status: 404, code: 'not_found', msg: 'nope' } })),+}));++const logPaymentEventMock = vi.fn();+vi.mock('../../api/_lib/x402/audit-log.js', () => ({ logPaymentEvent: (...a) => logPaymentEventMock(...a) }));++const { default: handler } = await import('../../api/x402/pay-by-name.js');++// An on-curve wallet, so `verified` comes back true on the happy path.+const WALLET = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';++function makeReq(body, headers = {}) {+ const req = {+ url: '/api/x402/pay-by-name',+ method: 'POST',+ headers: { host: 'three.ws', 'content-type': 'application/json', ...headers },+ query: {},+ };+ const buf = Buffer.from(JSON.stringify(body));+ let read = false;+ req.on = (event, cb) => {+ if (event === 'data' && !read) {+ cb(buf);+ read = true;+ } else if (event === 'end') queueMicrotask(cb);+ return req;+ };+ req.headers['content-length'] = String(buf.length);+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ },+ };+}++async function post(body, headers) {+ const res = makeRes();+ await handler(makeReq(body, headers), res);+ let parsed = null;+ try {+ parsed = JSON.parse(res._body);+ } catch {}+ return { res, body: parsed };+}++beforeEach(() => {+ verifyPaymentMock.mockClear();+ settlePaymentMock.mockClear();+ logPaymentEventMock.mockClear();+ sqlMock.mockReset().mockResolvedValue([]);+ snsResolveMock.mockReset();+});++describe('POST /api/x402/pay-by-name (paid resolution)', () => {+ it('challenges an unpaid call with a 402 carrying a Solana accept', async () => {+ const { res, body } = await post({ name: 'x402-audit-probe.sol' });+ expect(res.statusCode).toBe(402);+ expect(body.accepts).toHaveLength(1);+ expect(body.accepts[0].amount).toBe('1000');+ expect(settlePaymentMock).not.toHaveBeenCalled();+ });++ it('rejects a missing name before touching the payment path', async () => {+ const { res, body } = await post({ name: ' ' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(verifyPaymentMock).not.toHaveBeenCalled();+ });++ it('settles and returns the address when the name resolves', async () => {+ snsResolveMock.mockResolvedValue({ toBase58: () => WALLET });+ const { res, body } = await post({ name: 'x402-audit-probe.sol' }, { 'x-payment': 'proof' });+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({+ name: 'x402-audit-probe.sol',+ address: WALLET,+ verified: true,+ source: 'sns',+ });+ expect(settlePaymentMock).toHaveBeenCalledTimes(1);+ expect(res.getHeader('x-payment-response')).toBe('stub-payment-response');+ });++ it('does NOT settle when the name resolves to nothing', async () => {+ snsResolveMock.mockRejectedValue(new Error('domain not found'));+ const { res, body } = await post({ name: 'definitely-not-registered.sol' }, { 'x-payment': 'proof' });+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('not_found');+ expect(body.error_description).toContain('payment was not taken');+ expect(verifyPaymentMock).toHaveBeenCalledTimes(1);+ expect(settlePaymentMock).not.toHaveBeenCalled();+ expect(logPaymentEventMock).not.toHaveBeenCalled();+ });++ it('re-challenges with a 402 when the payment does not verify', async () => {+ verifyPaymentMock.mockRejectedValueOnce(new Error('bad signature'));+ const { res, body } = await post({ name: 'x402-audit-probe.sol' }, { 'x-payment': 'garbage' });+ expect(res.statusCode).toBe(402);+ expect(body.error).toBe('bad signature');+ expect(settlePaymentMock).not.toHaveBeenCalled();+ });++ it('surfaces a settle failure as a 502 rather than a silent success', async () => {+ snsResolveMock.mockResolvedValue({ toBase58: () => WALLET });+ settlePaymentMock.mockRejectedValueOnce(new Error('facilitator down'));+ const { res, body } = await post({ name: 'x402-audit-probe.sol' }, { 'x-payment': 'proof' });+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('settle_failed');+ });+});diff --git a/tests/api/x402-permit2-paid-demo.test.js b/tests/api/x402-permit2-paid-demo.test.jsnew file mode 100644index 000000000..31b0e13c7--- /dev/null+++ b/tests/api/x402-permit2-paid-demo.test.js@@ -0,0 +1,168 @@+/**+ * /api/x402/permit2-paid-demo: the Permit2-forced paid demo.+ *+ * This route deliberately advertises ONE accept (exact + Permit2 on Base) so a+ * client cannot silently fall back to EIP-3009. Two behaviours are load-bearing+ * and covered here:+ *+ * 1. Permit2 settlement runs through CDP, so without CDP credentials the+ * route must emit a clean 402 with an empty `accepts` rather than let a+ * buyer waste an EIP-2612 signature on a path we cannot honor.+ * 2. A bypass caller (internal key / subscription / OAuth) never signs a+ * payment, so the CDP requirement is irrelevant to them. The bypass+ * response must be reachable on a deployment with no CDP credentials.+ *+ * Payment verify/settle are stubbed at the module boundary; nothing here+ * touches a facilitator or the chain.+ */++import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000402',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ });+ delete process.env.CDP_API_KEY_ID;+ delete process.env.CDP_API_KEY_SECRET;+});++const verifyPaymentMock = vi.fn();+const settlePaymentMock = vi.fn();+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ verifyPayment: (...a) => verifyPaymentMock(...a),+ settlePayment: (...a) => settlePaymentMock(...a),+ encodePaymentResponseHeader: () => 'stub-payment-response',+ };+});++// The bypass hook is what this suite drives; installAccessControl's own+// API-key/OAuth resolution has its own suite, so it is stubbed to a+// test-controlled verdict here.+const accessVerdict = { value: null };+vi.mock('../../api/_lib/x402/access-control.js', () => ({+ installAccessControl: () => async () => accessVerdict.value,+}));++const { default: handler } = await import('../../api/x402/permit2-paid-demo.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(body) {+ this._body = body;+ },+ };+}++async function get(headers = {}, method = 'GET') {+ const res = makeRes();+ await handler(+ { url: '/api/x402/permit2-paid-demo', method, headers: { host: 'three.ws', ...headers }, query: {} },+ res,+ );+ let parsed = null;+ try {+ parsed = JSON.parse(res._body);+ } catch {}+ return { res, body: parsed };+}++beforeEach(() => {+ accessVerdict.value = null;+ verifyPaymentMock.mockReset();+ settlePaymentMock.mockReset();+});++describe('GET /api/x402/permit2-paid-demo without CDP credentials', () => {+ it('emits a 402 with no accepts instead of an unpayable challenge', async () => {+ const { res, body } = await get();+ expect(res.statusCode).toBe(402);+ expect(body.accepts).toEqual([]);+ expect(body.error).toContain('CDP_API_KEY_ID');+ });++ it('still serves a bypass caller, who never signs a payment', async () => {+ accessVerdict.value = { grantAccess: true, reason: 'internal', callerId: 'internal' };+ const { res, body } = await get();+ expect(res.statusCode).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.bypass).toBe('internal');+ expect(body.method).toBe('permit2');+ expect(body.network).toBe('eip155:8453');+ expect(body.asset).toBe(process.env.X402_ASSET_ADDRESS_BASE);+ expect(body.amountAtomics).toBe('1000');+ expect(body.transaction).toBeNull();+ expect(res.getHeader('x-payment-bypass')).toBe('internal');+ expect(verifyPaymentMock).not.toHaveBeenCalled();+ expect(settlePaymentMock).not.toHaveBeenCalled();+ });++ it('rejects an aborted access-control verdict with its own status', async () => {+ accessVerdict.value = { abort: true, status: 429, code: 'rate_limited', reason: 'quota exhausted' };+ const { res, body } = await get();+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});++describe('GET /api/x402/permit2-paid-demo with CDP credentials', () => {+ beforeEach(() => {+ process.env.CDP_API_KEY_ID = 'test-cdp-id';+ process.env.CDP_API_KEY_SECRET = 'test-cdp-secret';+ });++ it('advertises exactly one Permit2 accept and no EIP-3009 sibling', async () => {+ const { res, body } = await get();+ expect(res.statusCode).toBe(402);+ expect(body.accepts).toHaveLength(1);+ expect(body.accepts[0].network).toBe('eip155:8453');+ expect(body.accepts[0].extra.assetTransferMethod).toBe('permit2');+ expect(body.accepts[0].extra.supportsEip2612).toBe(true);+ });++ it('refuses a verified payment whose payload is not a Permit2 authorization', async () => {+ verifyPaymentMock.mockResolvedValue({ paymentPayload: { payload: { authorization: {} } } });+ const { res, body } = await get({ 'x-payment': 'eip3009-proof' });+ expect(res.statusCode).toBe(402);+ expect(body.error).toContain('permit2Authorization');+ expect(settlePaymentMock).not.toHaveBeenCalled();+ });++ it('settles a Permit2 payload and returns the tx hash plus a Basescan link', async () => {+ const txHash = '0x9c0a7e5ad5c9c0bb6f04f6ad9c52f4f44bb6c5d9c0a7e5ad5c9c0bb6f04f6ad9';+ verifyPaymentMock.mockResolvedValue({+ paymentPayload: { payload: { permit2Authorization: { nonce: '1' } } },+ payer: '0x0000000000000000000000000000000000000abc',+ requirement: {+ network: 'eip155:8453',+ asset: process.env.X402_ASSET_ADDRESS_BASE,+ amount: '1000',+ },+ });+ settlePaymentMock.mockResolvedValue({ transaction: txHash });+ const { res, body } = await get({ 'x-payment': 'permit2-proof' });+ expect(res.statusCode).toBe(200);+ expect(body.transaction).toBe(txHash);+ expect(body.explorer).toBe(`https://basescan.org/tx/${txHash}`);+ expect(body.proxy).toBe('0x402085c248EeA27D92E8b30b2C58ed07f9E20001');+ expect(res.getHeader('x-payment-response')).toBe('stub-payment-response');+ });++ it('answers a wrong-method call with 405', async () => {+ const { res, body } = await get({}, 'POST');+ expect(res.statusCode).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ });+});diff --git a/tests/api/x402-pump-agent-audit-list.test.js b/tests/api/x402-pump-agent-audit-list.test.jsnew file mode 100644index 000000000..c570ab16c--- /dev/null+++ b/tests/api/x402-pump-agent-audit-list.test.js@@ -0,0 +1,77 @@+/**+ * /api/x402/pump-agent-audit: LIST-mode summary shape.+ *+ * The list response carries both an ordering (`launches`, re-ranked when+ * sort=liquidity) and a headline (`newest_mint` / `newest_name` /+ * `newest_symbol`). Those are two different questions, and the summary used to+ * answer the second by reading index 0 of the already-liquidity-sorted array,+ * so under sort=liquidity it reported the deepest-liquidity launch as the+ * newest one. It only ever looked correct when the two happened to be the same+ * coin, which is exactly what a live spot-check sees most of the time.+ *+ * Mints below are synthetic; nothing here touches pump.fun or the DB.+ */++import { describe, it, expect } from 'vitest';++import { summarizeLaunches } from '../../api/x402/pump-agent-audit.js';++// Newest-first, the order the live feed hands back. The newest launch has the+// SHALLOWEST liquidity on purpose, so a summary that reads the sorted array+// cannot accidentally be right.+const FEED = [+ { mint: 'THREEsynthetic1111111111111111111111111newA', name: 'Alpha', symbol: 'ALPHA', created_at: 3_000, liquidity_sol: 1.5 },+ { mint: 'THREEsynthetic1111111111111111111111111midB', name: 'Bravo', symbol: 'BRAVO', created_at: 2_000, liquidity_sol: 30 },+ { mint: 'THREEsynthetic1111111111111111111111111oldC', name: 'Charlie', symbol: 'CHARLIE', created_at: 1_000, liquidity_sol: 12 },+];++describe('summarizeLaunches', () => {+ it('reports the newest launch and preserves feed order under sort=newest', () => {+ const out = summarizeLaunches(FEED, 'newest');+ expect(out.sort).toBe('newest');+ expect(out.count).toBe(3);+ expect(out.newest_mint).toBe(FEED[0].mint);+ expect(out.newest_name).toBe('Alpha');+ expect(out.newest_symbol).toBe('ALPHA');+ expect(out.launches.map((l) => l.name)).toEqual(['Alpha', 'Bravo', 'Charlie']);+ });++ it('still reports the NEWEST launch when the list is re-ranked by liquidity', () => {+ const out = summarizeLaunches(FEED, 'liquidity');+ expect(out.launches.map((l) => l.name)).toEqual(['Bravo', 'Charlie', 'Alpha']);+ // The headline describes the newest coin, not the deepest-liquidity one.+ expect(out.newest_mint).toBe(FEED[0].mint);+ expect(out.newest_name).toBe('Alpha');+ expect(out.newest_symbol).toBe('ALPHA');+ });++ it('does not mutate the caller feed while re-ranking', () => {+ const before = FEED.map((l) => l.name);+ summarizeLaunches(FEED, 'liquidity');+ expect(FEED.map((l) => l.name)).toEqual(before);+ });++ it('computes average and peak initial liquidity over positive reserves only', () => {+ const out = summarizeLaunches(+ [...FEED, { mint: 'THREEsynthetic11111111111111111111111zeroD', name: 'Delta', symbol: 'DELTA', created_at: 500, liquidity_sol: 0 }],+ 'newest',+ );+ expect(out.max_initial_liquidity_sol).toBe(30);+ expect(out.avg_initial_liquidity_sol).toBe(14.5);+ });++ it('degrades to nulls on an empty feed instead of NaN or undefined', () => {+ const out = summarizeLaunches([], 'newest');+ expect(out.count).toBe(0);+ expect(out.newest_mint).toBeNull();+ expect(out.newest_name).toBeNull();+ expect(out.newest_symbol).toBeNull();+ expect(out.avg_initial_liquidity_sol).toBeNull();+ expect(out.max_initial_liquidity_sol).toBeNull();+ expect(out.launches).toEqual([]);+ });++ it('defaults the reported sort to newest when none is supplied', () => {+ expect(summarizeLaunches(FEED, undefined).sort).toBe('newest');+ });+});