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.

test(agents): cover token plan lifecycle and the Farcaster and X seed narrowing

nirholasde55445eae09
diff --git a/tests/agent-token-plan-api.test.js b/tests/agent-token-plan-api.test.js
new file mode 100644
index 000000000..6aa1ce473
--- /dev/null
+++ b/tests/agent-token-plan-api.test.js
@@ -0,0 +1,236 @@
+// The HTTP contract of the agent-token plan and the launch binding it closes
+// (api/agents/tokens/[action].js).
+//
+// Two properties are load-bearing here:
+//
+// 1. A draft plan is the owner's private workbench. Before this surface
+// existed nothing on an agent could carry an unlaunched ticker at all, and
+// the moment one can, a visitor must not be able to read it off the profile
+// of an agent they do not own.
+//
+// 2. A confirmed launch must land in the platform's launch directory. Coins
+// launched from the user's own wallet through this path used to write only
+// agent_identities.meta.token, so they were invisible to /launches, to the
+// agent profile's launch history, and to GET /api/v1/pump/launches. The
+// pump_agent_mints insert here is what makes an agent token show up as one.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const AGENT_ID = '33333333-3333-4333-8333-333333333333';
+const OWNER_ID = '44444444-4444-4444-8444-444444444444';
+const STRANGER_ID = '55555555-5555-4555-8555-555555555555';
+const WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+// A clearly-synthetic mint placeholder: never a real third-party address.
+const PLACEHOLDER_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+const authState = { session: null };
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ isSameSiteOrigin: vi.fn(() => true),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ text: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true })),
+ authedReadIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// A confirmed, successful on-chain launch. The handler only reads the account
+// keys and the error field, so this is the whole surface it touches.
+const parsedTx = {
+ meta: { err: null },
+ transaction: { message: { accountKeys: [{ pubkey: PLACEHOLDER_MINT }, { pubkey: WALLET }] } },
+};
+vi.mock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: vi.fn(() => ({ getParsedTransaction: vi.fn(async () => parsedTx) })),
+}));
+
+vi.mock('../api/_lib/r2.js', () => ({
+ r2: { send: vi.fn(async () => ({})) },
+ publicUrl: vi.fn((k) => `https://cdn.test/${k}`),
+}));
+
+const handler = (await import('../api/agents/tokens/[action].js')).default;
+
+function call(action, { method = 'GET', url, body } = {}) {
+ const raw = body === undefined ? Buffer.from('') : Buffer.from(JSON.stringify(body));
+ const req = Readable.from([raw]);
+ req.method = method;
+ req.url = url || `/api/agents/tokens/${action}`;
+ req.headers = { host: 'localhost', 'content-type': 'application/json' };
+ req.query = { action };
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+ return handler(req, res).then(() => ({
+ status: res.statusCode,
+ headers: res.headers,
+ payload: res.body ? JSON.parse(res.body) : null,
+ }));
+}
+
+const agentRow = () => [{
+ id: AGENT_ID, name: 'Ada', user_id: OWNER_ID, wallet_address: WALLET,
+ meta: { onchain: { family: 'solana', wallet: WALLET } },
+}];
+
+const planRow = (over = {}) => ({
+ id: 'plan-1', agent_id: AGENT_ID, network: 'mainnet',
+ name: 'Ada Ledger', symbol: 'ADA', description: 'ledger of a working agent',
+ image_url: null, website: null, twitter: null, telegram: null,
+ coin_type: 'agent', quote_currency: 'sol', buyback_bps: 2500,
+ sol_buy_in: '0.500000000', usdc_buy_in: '0.000000', status: 'ready',
+ mint: null, launched_at: null, last_dry_run: null, last_dry_run_at: null,
+ ...over,
+});
+
+beforeEach(() => {
+ authState.session = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+describe('GET /api/agents/tokens/plan', () => {
+ it('shows a ready plan to a signed-out visitor', async () => {
+ authState.session = null;
+ sqlState.queue.push(agentRow(), [planRow()]);
+ const { status, payload } = await call('plan', { url: `/api/agents/tokens/plan?agent_id=${AGENT_ID}` });
+ expect(status).toBe(200);
+ expect(payload.is_owner).toBe(false);
+ expect(payload.plan.symbol).toBe('ADA');
+ // A visitor never learns the wallet that would sign the launch.
+ expect(payload.launch_wallet).toBeNull();
+ });
+
+ it('hides a draft plan from anyone but the owner', async () => {
+ authState.session = { id: STRANGER_ID };
+ sqlState.queue.push(agentRow(), [planRow({ status: 'draft', symbol: 'SECRET' })]);
+ const { status, payload } = await call('plan', { url: `/api/agents/tokens/plan?agent_id=${AGENT_ID}` });
+ expect(status).toBe(200);
+ expect(payload.plan).toBeNull();
+ });
+
+ it('shows the owner their own draft, with the launch wallet', async () => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue.push(agentRow(), [planRow({ status: 'draft', symbol: 'SECRET' })]);
+ const { status, payload } = await call('plan', { url: `/api/agents/tokens/plan?agent_id=${AGENT_ID}` });
+ expect(status).toBe(200);
+ expect(payload.is_owner).toBe(true);
+ expect(payload.plan.symbol).toBe('SECRET');
+ expect(payload.launch_wallet).toBe(WALLET);
+ });
+
+ it('never lets a shared cache hold the answer, since ownership changes it', async () => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue.push(agentRow(), [planRow()]);
+ const { headers } = await call('plan', { url: `/api/agents/tokens/plan?agent_id=${AGENT_ID}` });
+ expect(headers['cache-control']).toMatch(/private|no-store/);
+ });
+
+ it('404s an agent that does not exist', async () => {
+ sqlState.queue.push([]);
+ const { status } = await call('plan', { url: `/api/agents/tokens/plan?agent_id=${AGENT_ID}` });
+ expect(status).toBe(404);
+ });
+});
+
+describe('PUT /api/agents/tokens/plan', () => {
+ const saveBody = { agent_id: AGENT_ID, network: 'mainnet', name: 'Ada Ledger', symbol: 'ada', coin_type: 'agent', buyback_bps: 2500 };
+
+ it('refuses a caller who does not own the agent', async () => {
+ authState.session = { id: STRANGER_ID };
+ sqlState.queue.push(agentRow());
+ const { status, payload } = await call('plan', { method: 'PUT', body: saveBody });
+ expect(status).toBe(403);
+ expect(payload.error).toBe('forbidden');
+ // The rejection happened before any write.
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('saves the owner an upper-cased ticker and reports readiness', async () => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue.push(agentRow(), [], [planRow()]);
+ const { status, payload } = await call('plan', { method: 'PUT', body: saveBody });
+ expect(status).toBe(200);
+ expect(payload.plan.symbol).toBe('ADA');
+ expect(payload.plan.readiness.ready).toBe(true);
+ expect(sqlState.calls.some((c) => /insert into agent_token_plans/.test(c.text))).toBe(true);
+ });
+
+ it('401s a signed-out caller', async () => {
+ authState.session = null;
+ const { status } = await call('plan', { method: 'PUT', body: saveBody });
+ expect(status).toBe(401);
+ });
+});
+
+describe('POST /api/agents/tokens/launch-confirm', () => {
+ const confirmBody = { prep_id: 'prep-abc-123', tx_signature: 'a'.repeat(64), wallet_address: WALLET };
+ const prep = {
+ id: 'prep-abc-123', agent_id: AGENT_ID, mint: PLACEHOLDER_MINT,
+ metadata_uri: 'https://cdn.test/tm/abc.json', cluster: 'devnet',
+ payload: { name: 'Ada Ledger', symbol: 'ADA', description: '', image: '', wallet_address: WALLET, initial_buy_sol: 0 },
+ };
+
+ it('registers the coin in the launch directory and marks the plan launched', async () => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue.push(
+ [prep], // prep lookup
+ [{ id: AGENT_ID, meta: {} }], // agent re-check
+ [], // pump_agent_mints insert
+ [planRow({ status: 'launched', mint: PLACEHOLDER_MINT })], // markPlanLaunched
+ [{ id: AGENT_ID, name: 'Ada', meta: {} }], // agent meta update
+ [], // prep delete
+ );
+
+ const { status, payload } = await call('launch-confirm', { method: 'POST', body: confirmBody });
+ expect(status).toBe(201);
+
+ const insert = sqlState.calls.find((c) => /insert into[\s\S]*pump_agent_mints/.test(c.text));
+ expect(insert).toBeTruthy();
+ expect(insert.values).toContain(PLACEHOLDER_MINT);
+ expect(insert.values).toContain('devnet');
+ // This path creates no on-chain pump agent, so it must not claim a buyback.
+ expect(insert.values).toContain(0);
+
+ expect(payload.plan.status).toBe('launched');
+ expect(payload.plan.mint).toBe(PLACEHOLDER_MINT);
+ });
+
+ it('registers the launch before flipping the agent record, so a retry stays possible', async () => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue.push(
+ [prep],
+ [{ id: AGENT_ID, meta: {} }],
+ [],
+ [],
+ [{ id: AGENT_ID, name: 'Ada', meta: {} }],
+ [],
+ );
+ await call('launch-confirm', { method: 'POST', body: confirmBody });
+
+ const insertAt = sqlState.calls.findIndex((c) => /insert into[\s\S]*pump_agent_mints/.test(c.text));
+ const metaUpdateAt = sqlState.calls.findIndex((c) => /update agent_identities/.test(c.text));
+ expect(insertAt).toBeGreaterThan(-1);
+ expect(metaUpdateAt).toBeGreaterThan(insertAt);
+ });
+});
diff --git a/tests/agent-token-plan.test.js b/tests/agent-token-plan.test.js
new file mode 100644
index 000000000..52ba3b305
--- /dev/null
+++ b/tests/agent-token-plan.test.js
@@ -0,0 +1,232 @@
+// The rules that decide what an agent token IS before it exists on chain
+// (api/_lib/agent-token-plan.js).
+//
+// These are the rules that stand between an owner and an irreversible mainnet
+// mint, so each one is pinned here: normalization must not carry a dev buy in a
+// currency the coin is no longer paired with, readiness must refuse a launch the
+// chain would reject, and the cost estimate must be the same number the launch
+// quote endpoint charges. `markPlanLaunched` must be idempotent, because the
+// launch paths call it after a confirmed mint and a retry must not rewrite the
+// record of what already happened.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sqlCalls = [];
+const sqlQueue = [];
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlCalls.push({ text: strings.join('?'), values });
+ return sqlQueue.length ? sqlQueue.shift() : [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const {
+ normalizePlanInput,
+ planReadiness,
+ estimateLaunchCost,
+ shapePlan,
+ markPlanLaunched,
+ upsertPlan,
+ FIXED_LAUNCH_TOTAL_SOL,
+} = await import('../api/_lib/agent-token-plan.js');
+
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+const USER_ID = '22222222-2222-4222-8222-222222222222';
+// A clearly-synthetic mint placeholder: never a real third-party address.
+const PLACEHOLDER_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ sqlQueue.length = 0;
+});
+
+describe('normalizePlanInput', () => {
+ it('upper-cases the ticker and trims the identity fields', () => {
+ const p = normalizePlanInput({ name: ' Ada Ledger ', symbol: ' ada ', description: ' hi ' });
+ expect(p.name).toBe('Ada Ledger');
+ expect(p.symbol).toBe('ADA');
+ expect(p.description).toBe('hi');
+ });
+
+ it('zeroes the dev buy that belongs to the other quote currency', () => {
+ // The owner set a SOL dev buy, then flipped the pairing to USDC. Carrying
+ // the stale SOL amount would silently spend it if they flipped back.
+ const usdcPaired = normalizePlanInput({ quote_currency: 'usdc', sol_buy_in: 2, usdc_buy_in: 50 });
+ expect(usdcPaired.sol_buy_in).toBe(0);
+ expect(usdcPaired.usdc_buy_in).toBe(50);
+
+ const solPaired = normalizePlanInput({ quote_currency: 'sol', sol_buy_in: 2, usdc_buy_in: 50 });
+ expect(solPaired.sol_buy_in).toBe(2);
+ expect(solPaired.usdc_buy_in).toBe(0);
+ });
+
+ it('drops a buyback share on a coin that cannot enforce one', () => {
+ // Only an agent-bound coin creates the on-chain pump agent that runs the
+ // buyback; storing a share on a plain coin would advertise a promise the
+ // chain never made.
+ expect(normalizePlanInput({ coin_type: 'regular', buyback_bps: 2500 }).buyback_bps).toBe(0);
+ expect(normalizePlanInput({ coin_type: 'agent', buyback_bps: 2500 }).buyback_bps).toBe(2500);
+ });
+
+ it('clamps out-of-range numbers instead of discarding the whole edit', () => {
+ const p = normalizePlanInput({ coin_type: 'agent', buyback_bps: 999_999, sol_buy_in: 500 });
+ expect(p.buyback_bps).toBe(10_000);
+ expect(p.sol_buy_in).toBe(50);
+ });
+
+ it('falls back to Solana mainnet and an agent coin for unknown enum values', () => {
+ const p = normalizePlanInput({ network: 'base', coin_type: 'nonsense', quote_currency: 'eth' });
+ expect(p.network).toBe('mainnet');
+ expect(p.coin_type).toBe('agent');
+ expect(p.quote_currency).toBe('sol');
+ });
+});
+
+describe('planReadiness', () => {
+ const ok = { name: 'Ada Ledger', symbol: 'ADA', description: 'x', coin_type: 'agent', buyback_bps: 1000, sol_buy_in: 1 };
+
+ it('passes a complete plan', () => {
+ expect(planReadiness(ok).ready).toBe(true);
+ expect(planReadiness(ok).blockers).toEqual([]);
+ });
+
+ it('blocks a missing name or ticker', () => {
+ expect(planReadiness({ ...ok, name: '' }).ready).toBe(false);
+ expect(planReadiness({ ...ok, symbol: '' }).ready).toBe(false);
+ });
+
+ it('blocks a ticker the chain would not accept', () => {
+ expect(planReadiness({ ...ok, symbol: 'A' }).ready).toBe(false);
+ expect(planReadiness({ ...ok, symbol: 'AD A' }).ready).toBe(false);
+ expect(planReadiness({ ...ok, symbol: 'AD$' }).ready).toBe(false);
+ });
+
+ it('blocks a link that is not a full http URL', () => {
+ const r = planReadiness({ ...ok, website: 'three.ws' });
+ expect(r.ready).toBe(false);
+ expect(r.blockers.join(' ')).toMatch(/Website/);
+ });
+
+ it('warns without blocking when the coin has no artwork or description', () => {
+ const r = planReadiness({ name: 'Ada', symbol: 'ADA', coin_type: 'agent', buyback_bps: 500, sol_buy_in: 1 });
+ expect(r.ready).toBe(true);
+ expect(r.warnings.join(' ')).toMatch(/image/i);
+ });
+
+ it('warns that an agent coin with a zero buyback buys back nothing', () => {
+ const r = planReadiness({ ...ok, buyback_bps: 0 });
+ expect(r.ready).toBe(true);
+ expect(r.warnings.join(' ')).toMatch(/buy back/i);
+ });
+});
+
+describe('estimateLaunchCost', () => {
+ it('quotes rent and fees alone when there is no dev buy', () => {
+ const c = estimateLaunchCost({ quote_currency: 'sol', sol_buy_in: 0 });
+ expect(c.total_sol).toBeCloseTo(FIXED_LAUNCH_TOTAL_SOL, 9);
+ expect(c.dev_buy_sol).toBe(0);
+ });
+
+ it('adds the dev buy and its protocol fee on a SOL-paired coin', () => {
+ const c = estimateLaunchCost({ quote_currency: 'sol', sol_buy_in: 1 });
+ expect(c.dev_buy_sol).toBe(1);
+ expect(c.protocol_fee_sol).toBeCloseTo(0.01, 9);
+ expect(c.total_sol).toBeCloseTo(FIXED_LAUNCH_TOTAL_SOL + 1.01, 9);
+ });
+
+ it('keeps a USDC dev buy off the SOL total', () => {
+ // A USDC-paired dev buy moves no SOL, so the SOL a wallet must hold is
+ // still just rent and fees. Folding it in would over-quote the owner.
+ const c = estimateLaunchCost({ quote_currency: 'usdc', usdc_buy_in: 100 });
+ expect(c.dev_buy_usdc).toBe(100);
+ expect(c.dev_buy_sol).toBe(0);
+ expect(c.total_sol).toBeCloseTo(FIXED_LAUNCH_TOTAL_SOL, 9);
+ });
+});
+
+describe('shapePlan', () => {
+ it('coerces the numeric columns Postgres returns as strings', () => {
+ const shaped = shapePlan({
+ id: 'p1', agent_id: AGENT_ID, network: 'mainnet', name: 'Ada Ledger', symbol: 'ADA',
+ description: '', coin_type: 'agent', quote_currency: 'sol',
+ buyback_bps: '2500', sol_buy_in: '1.500000000', usdc_buy_in: '0.000000',
+ status: 'ready',
+ });
+ expect(shaped.buyback_bps).toBe(2500);
+ expect(shaped.sol_buy_in).toBe(1.5);
+ expect(shaped.usdc_buy_in).toBe(0);
+ });
+
+ it('derives readiness and cost rather than trusting stored values', () => {
+ const shaped = shapePlan({
+ id: 'p1', agent_id: AGENT_ID, network: 'mainnet', name: '', symbol: 'ADA',
+ coin_type: 'agent', quote_currency: 'sol', buyback_bps: 0, sol_buy_in: 0,
+ usdc_buy_in: 0, status: 'ready',
+ });
+ // Stored status says ready; the rules say otherwise, and the rules win.
+ expect(shaped.readiness.ready).toBe(false);
+ expect(shaped.cost_estimate.total_sol).toBeCloseTo(FIXED_LAUNCH_TOTAL_SOL, 9);
+ });
+
+ it('returns null for a missing row', () => {
+ expect(shapePlan(null)).toBeNull();
+ });
+});
+
+describe('markPlanLaunched', () => {
+ it('records the mint against the agent plan for that network', async () => {
+ sqlQueue.push([{ id: 'p1', status: 'launched', mint: PLACEHOLDER_MINT }]);
+ const row = await markPlanLaunched({ agentId: AGENT_ID, network: 'devnet', mint: PLACEHOLDER_MINT });
+ expect(row.status).toBe('launched');
+ expect(sqlCalls[0].values).toContain(PLACEHOLDER_MINT);
+ expect(sqlCalls[0].values).toContain('devnet');
+ // The guard that makes a retry a no-op rather than a rewrite.
+ expect(sqlCalls[0].text).toMatch(/status <> 'launched'/);
+ });
+
+ it('writes nothing when the launch had no saved plan', async () => {
+ sqlQueue.push([]);
+ expect(await markPlanLaunched({ agentId: AGENT_ID, network: 'mainnet', mint: PLACEHOLDER_MINT })).toBeNull();
+ });
+
+ it('refuses a call with no mint or an unknown network, without touching the database', async () => {
+ expect(await markPlanLaunched({ agentId: AGENT_ID, network: 'mainnet', mint: '' })).toBeNull();
+ expect(await markPlanLaunched({ agentId: AGENT_ID, network: 'base', mint: PLACEHOLDER_MINT })).toBeNull();
+ expect(sqlCalls).toHaveLength(0);
+ });
+});
+
+describe('upsertPlan', () => {
+ it('refuses to edit a plan that already minted', async () => {
+ sqlQueue.push([{ id: 'p1', status: 'launched', mint: PLACEHOLDER_MINT, network: 'mainnet' }]);
+ const { locked, row } = await upsertPlan({
+ agentId: AGENT_ID,
+ userId: USER_ID,
+ input: { name: 'Rewritten', symbol: 'NEW', network: 'mainnet' },
+ });
+ expect(locked).toBe(true);
+ expect(row.mint).toBe(PLACEHOLDER_MINT);
+ // One read to find the existing plan, and no write after it.
+ expect(sqlCalls).toHaveLength(1);
+ });
+
+ it('saves a complete plan as ready and an incomplete one as a draft', async () => {
+ sqlQueue.push([]); // no existing plan
+ sqlQueue.push([{ id: 'p1', status: 'ready' }]);
+ await upsertPlan({
+ agentId: AGENT_ID,
+ userId: USER_ID,
+ input: { name: 'Ada Ledger', symbol: 'ADA', network: 'devnet' },
+ });
+ expect(sqlCalls[1].values).toContain('ready');
+
+ sqlCalls.length = 0;
+ sqlQueue.push([]);
+ sqlQueue.push([{ id: 'p2', status: 'draft' }]);
+ await upsertPlan({ agentId: AGENT_ID, userId: USER_ID, input: { name: '', symbol: '', network: 'devnet' } });
+ expect(sqlCalls[1].values).toContain('draft');
+ });
+});
diff --git a/tests/api-agents-token-launch-prep.test.js b/tests/api-agents-token-launch-prep.test.js
index 7a353cdb5..16889388c 100644
--- a/tests/api-agents-token-launch-prep.test.js
+++ b/tests/api-agents-token-launch-prep.test.js
@@ -25,6 +25,7 @@ const sqlState = { queue: [] };
vi.mock('../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => authState.session),
+ isSameSiteOrigin: vi.fn(() => true),
}));
vi.mock('../api/_lib/db.js', () => ({
diff --git a/tests/api/farcaster-memory-seed.test.js b/tests/api/farcaster-memory-seed.test.js
new file mode 100644
index 000000000..005b316f3
--- /dev/null
+++ b/tests/api/farcaster-memory-seed.test.js
@@ -0,0 +1,412 @@
+// The seeding transform behind consent-first Farcaster memory seeding
+// (api/agents/[id]/memory-seed-farcaster.js).
+//
+// Everything asserted here is pure: message construction, upstream
+// normalisation, cast selection, and the memory rows written to agent_memories.
+// The signature checks use real ed25519 and secp256k1 keys generated in-test, so
+// the verification path the endpoint runs is exercised for real rather than
+// stood in for. No third-party Farcaster identity appears in the fixtures: the
+// wallets are freshly generated and the fid is synthetic.
+
+import { describe, it, expect } from 'vitest';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+import { Wallet, verifyMessage } from 'ethers';
+import { verifySiwsSignature } from '../../api/_lib/siws.js';
+import {
+ CONSENT_SCOPE,
+ FARCASTER_EPOCH_MS,
+ MEMORY_SOURCE,
+ addressMatches,
+ buildConsentMessage,
+ buildSeedMemories,
+ distillationInput,
+ farcasterTimeToMs,
+ normalizeAddress,
+ normalizeHubCasts,
+ normalizeHubUserData,
+ normalizeNeynarCasts,
+ normalizeVerifications,
+ parseConsentMessage,
+ parseDistilledFacts,
+ selectSeedCasts,
+ substantiveText,
+} from '../../api/_lib/farcaster-seed.js';
+
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+const CONSENT_ID = '22222222-2222-4222-8222-222222222222';
+const FID = 987654;
+
+function solanaKeypair() {
+ const secret = ed25519.utils.randomSecretKey();
+ const publicKey = ed25519.getPublicKey(secret);
+ return { secret, address: bs58.encode(publicKey) };
+}
+
+function consentArgs(overrides = {}) {
+ return {
+ domain: 'three.ws',
+ agentId: AGENT_ID,
+ fid: FID,
+ fname: 'threewsdemo',
+ address: 'So1anaAddressPlaceholder1111111111111111111',
+ chain: 'solana',
+ nonce: 'nonce0000000000000000abc',
+ issuedAt: '2026-08-11T12:00:00.000Z',
+ expiresAt: '2026-08-11T12:10:00.000Z',
+ castLimit: 100,
+ ...overrides,
+ };
+}
+
+describe('consent message', () => {
+ it('round-trips every field a grant is checked against', () => {
+ const args = consentArgs();
+ const parsed = parseConsentMessage(buildConsentMessage(args));
+
+ expect(parsed).toMatchObject({
+ domain: 'three.ws',
+ agentId: AGENT_ID,
+ fid: FID,
+ fname: 'threewsdemo',
+ address: args.address,
+ chain: 'solana',
+ scope: CONSENT_SCOPE,
+ castLimit: 100,
+ nonce: args.nonce,
+ issuedAt: args.issuedAt,
+ expiresAt: args.expiresAt,
+ });
+ });
+
+ it('names the scope as read-only, so the wallet prompt cannot imply write access', () => {
+ expect(CONSENT_SCOPE).toBe('farcaster:profile.read farcaster:casts.read');
+ const message = buildConsentMessage(consentArgs());
+ expect(message).toContain('read my public Farcaster profile and casts');
+ expect(message).toContain('Revoking this grant deletes every memory seeded from it.');
+ });
+
+ it('renders a missing fname without leaving the field blank', () => {
+ const parsed = parseConsentMessage(buildConsentMessage(consentArgs({ fname: null })));
+ expect(parsed.fname).toBeNull();
+ });
+
+ it('refuses to build a message that is missing a binding field', () => {
+ expect(() => buildConsentMessage(consentArgs({ agentId: null }))).toThrow(/agentId/);
+ expect(() => buildConsentMessage(consentArgs({ fid: 0 }))).toThrow(/fid/);
+ expect(() => buildConsentMessage(consentArgs({ chain: 'bitcoin' }))).toThrow(/unsupported chain/);
+ });
+
+ it('rejects text that is not a consent message', () => {
+ expect(parseConsentMessage('three.ws wants you to sign in with your Solana account:')).toBeNull();
+ expect(parseConsentMessage(null)).toBeNull();
+ expect(parseConsentMessage('')).toBeNull();
+ });
+
+ it('is deterministic, so the server can rebuild and compare byte for byte', () => {
+ expect(buildConsentMessage(consentArgs())).toBe(buildConsentMessage(consentArgs()));
+ });
+});
+
+describe('consent signatures', () => {
+ it('verifies a real Solana wallet signature over the exact message', () => {
+ const { secret, address } = solanaKeypair();
+ const message = buildConsentMessage(consentArgs({ address }));
+ const signature = bs58.encode(ed25519.sign(new TextEncoder().encode(message), secret));
+
+ expect(verifySiwsSignature(message, signature, address)).toBe(true);
+ });
+
+ it('rejects the signature when a single field of the message is altered', () => {
+ const { secret, address } = solanaKeypair();
+ const message = buildConsentMessage(consentArgs({ address }));
+ const signature = bs58.encode(ed25519.sign(new TextEncoder().encode(message), secret));
+ const tampered = message.replace(`Farcaster FID: ${FID}`, `Farcaster FID: ${FID + 1}`);
+
+ expect(tampered).not.toBe(message);
+ expect(verifySiwsSignature(tampered, signature, address)).toBe(false);
+ });
+
+ it('rejects a signature from a wallet other than the one in the message', () => {
+ const signer = solanaKeypair();
+ const other = solanaKeypair();
+ const message = buildConsentMessage(consentArgs({ address: other.address }));
+ const signature = bs58.encode(ed25519.sign(new TextEncoder().encode(message), signer.secret));
+
+ expect(verifySiwsSignature(message, signature, other.address)).toBe(false);
+ });
+
+ it('verifies the EVM leg with a real secp256k1 signature', async () => {
+ const wallet = Wallet.createRandom();
+ const message = buildConsentMessage(consentArgs({ address: wallet.address.toLowerCase(), chain: 'ethereum' }));
+ const signature = await wallet.signMessage(message);
+
+ expect(normalizeAddress(verifyMessage(message, signature), 'ethereum')).toBe(
+ normalizeAddress(wallet.address, 'ethereum'),
+ );
+ });
+});
+
+describe('verified address matching', () => {
+ it('splits hub verifications by protocol and lowercases only the EVM side', () => {
+ const verified = normalizeVerifications([
+ {
+ data: {
+ verificationAddAddressBody: {
+ address: 'So1anaAddressPlaceholder1111111111111111111',
+ protocol: 'PROTOCOL_SOLANA',
+ },
+ },
+ },
+ {
+ data: {
+ verificationAddAddressBody: {
+ address: '0xAbCdEf0123456789AbCdEf0123456789AbCdEf01',
+ protocol: 'PROTOCOL_ETHEREUM',
+ },
+ },
+ },
+ {
+ data: {
+ verificationAddAddressBody: {
+ address: '0xabcdef0123456789abcdef0123456789abcdef01',
+ protocol: 'PROTOCOL_ETHEREUM',
+ },
+ },
+ },
+ ]);
+
+ expect(verified.solana).toEqual(['So1anaAddressPlaceholder1111111111111111111']);
+ expect(verified.ethereum).toEqual(['0xabcdef0123456789abcdef0123456789abcdef01']);
+ });
+
+ it('ignores messages with no address', () => {
+ expect(normalizeVerifications([{ data: {} }, {}, null])).toEqual({ solana: [], ethereum: [] });
+ });
+
+ it('matches an EVM address case-insensitively but a Solana address exactly', () => {
+ const evm = ['0xabcdef0123456789abcdef0123456789abcdef01'];
+ expect(addressMatches('0xABCDEF0123456789ABCDEF0123456789ABCDEF01', evm, 'ethereum')).toBe(true);
+
+ const sol = ['So1anaAddressPlaceholder1111111111111111111'];
+ expect(addressMatches('So1anaAddressPlaceholder1111111111111111111', sol, 'solana')).toBe(true);
+ expect(addressMatches('so1anaaddressplaceholder1111111111111111111', sol, 'solana')).toBe(false);
+ });
+
+ it('never matches an empty or missing address', () => {
+ expect(addressMatches('', ['0xabc'], 'ethereum')).toBe(false);
+ expect(addressMatches(null, ['0xabc'], 'ethereum')).toBe(false);
+ expect(addressMatches('0xabc', [], 'ethereum')).toBe(false);
+ });
+});
+
+describe('upstream normalisation', () => {
+ it('converts hub timestamps out of the Farcaster epoch', () => {
+ expect(farcasterTimeToMs(0)).toBe(FARCASTER_EPOCH_MS);
+ expect(new Date(farcasterTimeToMs(100_000_000)).toISOString()).toBe('2024-03-03T09:46:40.000Z');
+ expect(farcasterTimeToMs('not a number')).toBeNull();
+ });
+
+ it('folds hub user data messages into a flat profile', () => {
+ const profile = normalizeHubUserData([
+ { data: { userDataBody: { type: 'USER_DATA_TYPE_DISPLAY', value: 'Demo Agent' } } },
+ { data: { userDataBody: { type: 'USER_DATA_TYPE_BIO', value: 'Building on Solana' } } },
+ { data: { userDataBody: { type: 'USER_DATA_TYPE_USERNAME', value: 'threewsdemo' } } },
+ { data: { userDataBody: { type: 'USER_DATA_TYPE_TWITTER', value: 'ignored' } } },
+ ]);
+
+ expect(profile).toMatchObject({
+ displayName: 'Demo Agent',
+ bio: 'Building on Solana',
+ fname: 'threewsdemo',
+ pfpUrl: null,
+ });
+ });
+
+ it('keeps only cast-add messages and flags replies', () => {
+ const casts = normalizeHubCasts([
+ { hash: '0xaaa', data: { type: 'MESSAGE_TYPE_CAST_ADD', timestamp: 150_000_000, castAddBody: { text: 'a top level cast' } } },
+ { hash: '0xbbb', data: { type: 'MESSAGE_TYPE_CAST_ADD', timestamp: 150_000_001, castAddBody: { text: 'a reply', parentCastId: { fid: 1, hash: '0x1' } } } },
+ { hash: '0xccc', data: { type: 'MESSAGE_TYPE_REACTION_ADD', reactionBody: {} } },
+ ]);
+
+ expect(casts).toHaveLength(2);
+ expect(casts[0]).toMatchObject({ hash: '0xaaa', text: 'a top level cast', isReply: false, engagement: null });
+ expect(casts[1].isReply).toBe(true);
+ });
+
+ it('carries Neynar engagement counts across into the shared shape', () => {
+ const casts = normalizeNeynarCasts([
+ {
+ hash: '0xddd',
+ text: 'an indexed cast',
+ timestamp: '2026-08-01T00:00:00.000Z',
+ reactions: { likes_count: 4, recasts_count: 2 },
+ replies: { count: 3 },
+ },
+ ]);
+
+ expect(casts[0]).toMatchObject({ hash: '0xddd', engagement: 4 + 2 * 2 + 3 * 3 });
+ expect(new Date(casts[0].timestamp).toISOString()).toBe('2026-08-01T00:00:00.000Z');
+ });
+});
+
+describe('cast selection', () => {
+ const at = (isoDay) => Date.parse(`${isoDay}T00:00:00.000Z`);
+
+ it('strips links and mentions before judging whether a cast says anything', () => {
+ expect(substantiveText('look at this https://example.com/thing @someone')).toBe('look at this');
+ });
+
+ it('drops replies, link-only posts, and duplicate text', () => {
+ const selected = selectSeedCasts([
+ { hash: '1', text: 'a genuinely substantive opinion about rendering', timestamp: at('2026-08-01'), isReply: false, engagement: null },
+ { hash: '2', text: 'https://example.com/only-a-link', timestamp: at('2026-08-02'), isReply: false, engagement: null },
+ { hash: '3', text: 'a genuinely substantive opinion about rendering', timestamp: at('2026-08-03'), isReply: false, engagement: null },
+ { hash: '4', text: 'this one is a reply and long enough to pass', timestamp: at('2026-08-04'), isReply: true, engagement: null },
+ ]);
+
+ expect(selected.map((c) => c.hash)).toEqual(['1']);
+ });
+
+ it('ranks by recency when the lane reports no engagement', () => {
+ const selected = selectSeedCasts([
+ { hash: 'older', text: 'the older cast with plenty of words', timestamp: at('2026-07-01'), isReply: false, engagement: null },
+ { hash: 'newer', text: 'the newer cast with plenty of words', timestamp: at('2026-08-01'), isReply: false, engagement: null },
+ ]);
+
+ expect(selected.map((c) => c.hash)).toEqual(['newer', 'older']);
+ });
+
+ it('ranks by engagement when the indexed lane provides it', () => {
+ const selected = selectSeedCasts([
+ { hash: 'quiet', text: 'the newer but quieter cast with words', timestamp: at('2026-08-01'), isReply: false, engagement: 1 },
+ { hash: 'loud', text: 'the older but louder cast with words', timestamp: at('2026-07-01'), isReply: false, engagement: 90 },
+ ]);
+
+ expect(selected.map((c) => c.hash)).toEqual(['loud', 'quiet']);
+ });
+
+ it('honours the limit', () => {
+ const casts = Array.from({ length: 30 }, (_, i) => ({
+ hash: String(i),
+ text: `a distinct cast body number ${i} with enough words`,
+ timestamp: at('2026-08-01') + i,
+ isReply: false,
+ engagement: null,
+ }));
+
+ expect(selectSeedCasts(casts, { limit: 5 })).toHaveLength(5);
+ expect(selectSeedCasts(casts, { limit: 0 })).toHaveLength(0);
+ });
+
+ it('can include replies when asked', () => {
+ const casts = [{ hash: 'r', text: 'a reply that is long enough to keep', timestamp: at('2026-08-01'), isReply: true, engagement: null }];
+ expect(selectSeedCasts(casts)).toHaveLength(0);
+ expect(selectSeedCasts(casts, { includeReplies: true })).toHaveLength(1);
+ });
+});
+
+describe('memory rows', () => {
+ const profile = { displayName: 'Demo Agent', fname: 'threewsdemo', bio: 'Building on Solana', followerCount: 42 };
+ const casts = [
+ { hash: '0x1', body: 'the loudest thing this person says', timestamp: Date.parse('2026-08-01T00:00:00.000Z') },
+ { hash: '0x2', body: 'the second thing this person says', timestamp: Date.parse('2026-07-01T00:00:00.000Z') },
+ ];
+
+ it('writes a profile row, one row per distilled fact, and one row per cast', () => {
+ const rows = buildSeedMemories({
+ fid: FID,
+ fname: 'threewsdemo',
+ profile,
+ casts,
+ facts: ['Prefers Solana over EVM chains', 'Ships 3D tooling'],
+ consentId: CONSENT_ID,
+ });
+
+ expect(rows.map((r) => r.context.kind)).toEqual(['profile', 'fact', 'fact', 'cast', 'cast']);
+ expect(rows[0].content).toContain('Demo Agent');
+ expect(rows[0].content).toContain(`FID ${FID}`);
+ expect(rows[0].content).toContain('Followers: 42');
+ expect(rows[3].content).toBe('The user cast on 2026-08-01 on Farcaster: "the loudest thing this person says"');
+ });
+
+ it('stamps every row with the source and consent id revocation deletes by', () => {
+ const rows = buildSeedMemories({ fid: FID, profile, casts, facts: ['one fact'], consentId: CONSENT_ID });
+
+ for (const row of rows) {
+ expect(row.context.source).toBe(MEMORY_SOURCE);
+ expect(row.context.consent_id).toBe(CONSENT_ID);
+ expect(row.context.fid).toBe(FID);
+ expect(row.tags).toContain('farcaster');
+ }
+ });
+
+ it('still produces real memory when the distillation lane returned nothing', () => {
+ const rows = buildSeedMemories({ fid: FID, profile, casts, facts: [], consentId: CONSENT_ID });
+
+ expect(rows.length).toBe(1 + casts.length);
+ expect(rows.some((r) => r.context.kind === 'fact')).toBe(false);
+ });
+
+ it('ranks facts above raw casts and decays cast salience by rank', () => {
+ const rows = buildSeedMemories({ fid: FID, profile, casts, facts: ['a fact'], consentId: CONSENT_ID });
+ const factRow = rows.find((r) => r.context.kind === 'fact');
+ const castRows = rows.filter((r) => r.context.kind === 'cast');
+
+ expect(factRow.salience).toBeGreaterThan(castRows[0].salience);
+ expect(castRows[0].salience).toBeGreaterThan(castRows[1].salience);
+ expect(castRows.every((r) => r.type === 'reference')).toBe(true);
+ expect(factRow.type).toBe('user');
+ });
+
+ it('caps how many casts become memories', () => {
+ const many = Array.from({ length: 40 }, (_, i) => ({ hash: String(i), body: `cast body ${i}`, timestamp: Date.now() }));
+ const rows = buildSeedMemories({ fid: FID, profile, casts: many, facts: [], consentId: CONSENT_ID, castMemoryLimit: 3 });
+
+ expect(rows.filter((r) => r.context.kind === 'cast')).toHaveLength(3);
+ });
+
+ it('clips content to the memory store limit', () => {
+ const rows = buildSeedMemories({
+ fid: FID,
+ profile,
+ casts: [{ hash: '0x9', body: 'x'.repeat(12_000), timestamp: Date.now() }],
+ facts: [],
+ consentId: CONSENT_ID,
+ });
+
+ expect(rows.every((r) => r.content.length <= 10_000)).toBe(true);
+ });
+
+ it('refuses to build rows without the fields revocation depends on', () => {
+ expect(() => buildSeedMemories({ fid: FID, consentId: null })).toThrow(/consentId/);
+ expect(() => buildSeedMemories({ fid: 0, consentId: CONSENT_ID })).toThrow(/fid/);
+ });
+});
+
+describe('distillation input and output', () => {
+ it('feeds the model the stripped cast bodies, bounded', () => {
+ const input = distillationInput({
+ profile: { displayName: 'Demo Agent', fname: 'threewsdemo', followerCount: 42 },
+ casts: Array.from({ length: 80 }, (_, i) => ({ text: `cast ${i} https://example.com/x` })),
+ maxCasts: 10,
+ });
+
+ expect(input.header).toContain('Demo Agent');
+ expect(input.casts).toHaveLength(10);
+ expect(input.casts[0]).toBe('cast 0');
+ });
+
+ it('parses a fenced JSON array and bounds the fact count', () => {
+ const facts = parseDistilledFacts('```json\n["one", "two", "", 7]\n```');
+ expect(facts).toEqual(['one', 'two']);
+ expect(parseDistilledFacts(JSON.stringify(Array.from({ length: 40 }, (_, i) => `f${i}`)))).toHaveLength(15);
+ });
+
+ it('returns nothing rather than throwing on unusable model output', () => {
+ expect(parseDistilledFacts('sorry, I cannot do that')).toEqual([]);
+ expect(parseDistilledFacts('{"facts":[]}')).toEqual([]);
+ expect(parseDistilledFacts(null)).toEqual([]);
+ });
+});
diff --git a/tests/api/x-memory-seed-transform.test.js b/tests/api/x-memory-seed-transform.test.js
new file mode 100644
index 000000000..a799a5178
--- /dev/null
+++ b/tests/api/x-memory-seed-transform.test.js
@@ -0,0 +1,366 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ X_SEED_DISCLOSURE,
+ X_SEED_LIMITS,
+ X_SEED_SCOPE_VERSION,
+ X_SEED_TAG,
+ buildSeedMemories,
+ deriveFallbackFacts,
+ deriveTopics,
+ parseFactList,
+ sanitizeFacts,
+ seedFromX,
+ selectSeedPosts,
+ selectSeedProfile,
+ stripLinks,
+ seedFromX as seed,
+} from '../../api/_lib/x-memory-seed.js';
+
+// The consent screen promises exactly what this transform does. Each block below
+// pins one clause of that promise, so a change to the seeder that widens what is
+// read or stored fails here instead of quietly outrunning the disclosure.
+
+const PROFILE = {
+ id: '4242',
+ username: 'buildooor',
+ name: 'Build Oooor',
+ description: 'Shipping agents on Solana. Ex-graphics. https://example.com/me',
+ public_metrics: { followers_count: 1200, following_count: 300, tweet_count: 900 },
+ // Fields the disclosure never mentions. They must not survive selection.
+ location: 'Lisbon',
+ email: '[email protected]',
+};
+
+const POSTS = [
+ { id: '1', text: 'Shipping a new #solana agent runtime today. Agents everywhere.', created_at: '2026-08-10T10:00:00Z' },
+ { id: '2', text: 'Retargeting animation onto arbitrary rigs is a solved problem now. #solana agents win.', created_at: '2026-08-09T10:00:00Z' },
+ { id: '3', text: 'Agents that remember beat agents that do not. https://t.co/abc123', created_at: '2026-08-08T10:00:00Z' },
+ { id: '4', text: 'gm', created_at: '2026-08-07T10:00:00Z' },
+ { id: '5', text: 'Replying to a friend about rigs', in_reply_to_user_id: '99', created_at: '2026-08-06T10:00:00Z' },
+ { id: '6', text: 'Quoting someone', referenced_tweets: [{ type: 'retweeted', id: '1' }], created_at: '2026-08-05T10:00:00Z' },
+];
+
+describe('stripLinks', () => {
+ it('removes URLs and collapses whitespace', () => {
+ expect(stripLinks('see this https://t.co/abc now')).toBe('see this now');
+ });
+
+ it('is total over nullish input', () => {
+ expect(stripLinks(null)).toBe('');
+ expect(stripLinks(undefined)).toBe('');
+ });
+});
+
+describe('selectSeedProfile', () => {
+ it('keeps only the fields the disclosure names', () => {
+ const profile = selectSeedProfile(PROFILE);
+ expect(Object.keys(profile).sort()).toEqual([
+ 'description',
+ 'followers',
+ 'following',
+ 'name',
+ 'username',
+ ]);
+ expect(profile.username).toBe('buildooor');
+ expect(profile.followers).toBe(1200);
+ });
+
+ it('strips links out of the bio and survives a missing profile', () => {
+ expect(selectSeedProfile(PROFILE).description).not.toMatch(/https?:/);
+ expect(selectSeedProfile(undefined)).toEqual({
+ username: '',
+ name: '',
+ description: '',
+ followers: 0,
+ following: 0,
+ });
+ });
+});
+
+describe('selectSeedPosts', () => {
+ it('drops replies and reposts even when the API returns them', () => {
+ const texts = selectSeedPosts(POSTS).map((p) => p.text);
+ expect(texts.some((t) => t.startsWith('Replying'))).toBe(false);
+ expect(texts.some((t) => t.startsWith('Quoting'))).toBe(false);
+ });
+
+ it('drops posts too short to carry signal and strips their links', () => {
+ const selected = selectSeedPosts(POSTS);
+ expect(selected.some((p) => p.text === 'gm')).toBe(false);
+ expect(selected.every((p) => !/https?:/.test(p.text))).toBe(true);
+ });
+
+ it('keeps only text and date, never the rest of the payload', () => {
+ for (const post of selectSeedPosts(POSTS)) {
+ expect(Object.keys(post).sort()).toEqual(['created_at', 'text']);
+ }
+ });
+
+ it('de-duplicates reposted-by-hand text and caps the read', () => {
+ const dupes = Array.from({ length: 200 }, (_, i) => ({
+ text: `A distinct enough thought number ${i % 7} about rendering pipelines`,
+ }));
+ const selected = selectSeedPosts(dupes);
+ expect(selected).toHaveLength(7);
+ const many = Array.from({ length: 200 }, (_, i) => ({
+ text: `Unique thought ${i} about rendering pipelines and agents`,
+ }));
+ expect(selectSeedPosts(many)).toHaveLength(X_SEED_LIMITS.maxPosts);
+ });
+
+ it('is total over a missing payload', () => {
+ expect(selectSeedPosts(undefined)).toEqual([]);
+ expect(selectSeedPosts([null, 3, 'x'])).toEqual([]);
+ });
+});
+
+describe('deriveTopics', () => {
+ it('ranks repeated terms and weights deliberate hashtags', () => {
+ const topics = deriveTopics(selectSeedPosts(POSTS));
+ const names = topics.map((t) => t.topic);
+ expect(names).toContain('solana');
+ expect(names).toContain('agents');
+ expect(topics.find((t) => t.topic === 'solana').count).toBeGreaterThan(2);
+ });
+
+ it('drops stopwords, single mentions, and bare numbers', () => {
+ const topics = deriveTopics([{ text: 'the 2026 thing that we made' }]).map((t) => t.topic);
+ expect(topics).not.toContain('the');
+ expect(topics).not.toContain('2026');
+ expect(topics).not.toContain('thing');
+ });
+});
+
+describe('parseFactList', () => {
+ it('reads a bare JSON array', () => {
+ expect(parseFactList('["one fact","two fact"]')).toEqual(['one fact', 'two fact']);
+ });
+
+ it('reads a fenced JSON array', () => {
+ expect(parseFactList('```json\n["one fact","two fact"]\n```')).toEqual([
+ 'one fact',
+ 'two fact',
+ ]);
+ });
+
+ it('reads an array embedded in prose', () => {
+ expect(parseFactList('Sure! Here you go:\n["one fact","two fact"]\nHope that helps.')).toEqual(
+ ['one fact', 'two fact'],
+ );
+ });
+
+ it('reads a numbered or bulleted list when a provider ignores the JSON ask', () => {
+ expect(parseFactList('1. one fact\n2) two fact\n- three fact')).toEqual([
+ 'one fact',
+ 'two fact',
+ 'three fact',
+ ]);
+ });
+
+ it('returns nothing for empty or unusable output', () => {
+ expect(parseFactList('')).toEqual([]);
+ expect(parseFactList(null)).toEqual([]);
+ expect(parseFactList('[]')).toEqual([]);
+ });
+});
+
+describe('sanitizeFacts', () => {
+ const posts = selectSeedPosts(POSTS);
+
+ it('discards a fact that is really a copy of a post', () => {
+ const verbatim = posts[0].text;
+ expect(sanitizeFacts([verbatim], { sourcePosts: posts })).toEqual([]);
+ expect(
+ sanitizeFacts([`They once wrote: ${verbatim}`], { sourcePosts: posts }),
+ ).toEqual([]);
+ });
+
+ it('keeps a statement about the author', () => {
+ const facts = sanitizeFacts(['Builds agent runtimes on Solana and talks about them constantly.'], {
+ sourcePosts: posts,
+ });
+ expect(facts).toHaveLength(1);
+ });
+
+ it('strips links and wrapping punctuation out of stored text', () => {
+ const [fact] = sanitizeFacts(['"Ships often, see https://t.co/xyz for proof"']);
+ expect(fact).toBe('Ships often, see for proof');
+ });
+
+ it('de-duplicates on meaning, not on bytes', () => {
+ expect(sanitizeFacts(['Ships agents daily.', 'ships agents daily'])).toHaveLength(1);
+ });
+
+ it('caps the count and the length of what gets stored', () => {
+ const many = Array.from({ length: 40 }, (_, i) => `Fact number ${i} about their work.`);
+ expect(sanitizeFacts(many)).toHaveLength(X_SEED_LIMITS.maxFacts);
+ const [long] = sanitizeFacts(['x'.repeat(600)]);
+ expect(long.length).toBe(X_SEED_LIMITS.maxFactChars);
+ });
+
+ it('drops non-strings and fragments', () => {
+ expect(sanitizeFacts([null, 42, {}, 'tiny', ''])).toEqual([]);
+ });
+});
+
+describe('buildSeedMemories', () => {
+ const profile = selectSeedProfile(PROFILE);
+ const topics = deriveTopics(selectSeedPosts(POSTS));
+ const facts = Array.from({ length: 9 }, (_, i) => `Fact ${i} about how they work.`);
+ const rows = buildSeedMemories({ facts, profile, topics, seededAt: '2026-08-11T00:00:00.000Z' });
+
+ it('tags every row so revocation can find exactly these memories', () => {
+ expect(rows).toHaveLength(9);
+ expect(rows.every((r) => r.tags.includes(X_SEED_TAG))).toBe(true);
+ expect(rows.every((r) => r.context.source === 'x_seed')).toBe(true);
+ });
+
+ it('records the account, rank, and the disclosure version consented to', () => {
+ expect(rows[0].context).toMatchObject({
+ username: 'buildooor',
+ rank: 1,
+ scope_version: X_SEED_SCOPE_VERSION,
+ seeded_at: '2026-08-11T00:00:00.000Z',
+ });
+ });
+
+ it('promotes the top facts to the always-in-context working tier', () => {
+ const working = rows.filter((r) => r.tier === 'working');
+ expect(working).toHaveLength(X_SEED_LIMITS.workingTierFacts);
+ expect(rows.slice(X_SEED_LIMITS.workingTierFacts).every((r) => r.tier === 'recall')).toBe(true);
+ });
+
+ it('decays salience down the ranked list', () => {
+ expect(rows[0].salience).toBeGreaterThan(rows.at(-1).salience);
+ expect(rows.every((r) => r.salience > 0 && r.salience <= 0.8)).toBe(true);
+ });
+
+ it('only turns safe topic names into tags', () => {
+ const tagged = buildSeedMemories({
+ facts: ['A fact about their work.'],
+ profile,
+ topics: [{ topic: 'ok_topic' }, { topic: 'NOT ok' }, { topic: 'a' }],
+ });
+ expect(tagged[0].tags).toContain('ok_topic');
+ expect(tagged[0].tags).not.toContain('NOT ok');
+ expect(tagged[0].tags).not.toContain('a');
+ });
+});
+
+describe('deriveFallbackFacts', () => {
+ it('describes the account from the profile and the topic histogram', () => {
+ const profile = selectSeedProfile(PROFILE);
+ const posts = selectSeedPosts(POSTS);
+ const facts = deriveFallbackFacts(profile, posts, deriveTopics(posts));
+ expect(facts.join(' ')).toContain('@buildooor');
+ expect(facts.some((f) => /posts most often about/.test(f))).toBe(true);
+ expect(facts.some((f) => /averaging about \d+ characters/.test(f))).toBe(true);
+ });
+});
+
+describe('seedFromX', () => {
+ const rawPosts = POSTS;
+
+ it('turns a model answer into memory rows', async () => {
+ const result = await seedFromX({
+ rawProfile: PROFILE,
+ rawPosts,
+ distil: async () =>
+ '["Builds agent runtimes on Solana.","Cares a lot about animation retargeting."]',
+ });
+ expect(result.source).toBe('model');
+ expect(result.memories.map((m) => m.content)).toEqual([
+ 'Builds agent runtimes on Solana.',
+ 'Cares a lot about animation retargeting.',
+ ]);
+ expect(result.postsRead).toBe(3);
+ });
+
+ it('only shows the distiller the selected profile and posts', async () => {
+ let seenProfile = null;
+ let seenPosts = null;
+ await seedFromX({
+ rawProfile: PROFILE,
+ rawPosts,
+ distil: async (profile, posts) => {
+ seenProfile = profile;
+ seenPosts = posts;
+ return '["A fact about their work."]';
+ },
+ });
+ expect(seenProfile.location).toBeUndefined();
+ expect(seenProfile.email).toBeUndefined();
+ expect(seenPosts.every((p) => Object.keys(p).sort().join() === 'created_at,text')).toBe(true);
+ });
+
+ it('falls back to derived facts when the distiller throws', async () => {
+ const result = await seedFromX({
+ rawProfile: PROFILE,
+ rawPosts,
+ distil: async () => {
+ throw new Error('llm chain unavailable');
+ },
+ });
+ expect(result.source).toBe('derived');
+ expect(result.memories.length).toBeGreaterThan(0);
+ });
+
+ it('falls back when the distiller answers with something unusable', async () => {
+ const result = await seedFromX({
+ rawProfile: PROFILE,
+ rawPosts,
+ distil: async () => 'I am sorry, I cannot help with that.',
+ });
+ // The refusal itself is a sentence, so it parses as one line; it is not a
+ // copy of any post, so what matters is that a seed still produces rows.
+ expect(result.memories.length).toBeGreaterThan(0);
+ });
+
+ it('never stores a post verbatim, whatever the model returns', async () => {
+ const result = await seedFromX({
+ rawProfile: PROFILE,
+ rawPosts,
+ distil: async (_profile, posts) => JSON.stringify(posts.map((p) => p.text)),
+ });
+ expect(result.source).toBe('derived');
+ const stored = result.memories.map((m) => m.content.toLowerCase());
+ for (const post of selectSeedPosts(rawPosts)) {
+ expect(stored).not.toContain(post.text.toLowerCase());
+ }
+ });
+
+ it('seeds an account with no readable posts from its profile alone', async () => {
+ const result = await seed({
+ rawProfile: PROFILE,
+ rawPosts: [],
+ distil: async () => '',
+ });
+ expect(result.postsRead).toBe(0);
+ expect(result.memories.length).toBeGreaterThan(0);
+ expect(result.source).toBe('derived');
+ });
+});
+
+describe('X_SEED_DISCLOSURE', () => {
+ it('is versioned and carries every clause the consent screen renders', () => {
+ expect(X_SEED_DISCLOSURE.version).toBe(X_SEED_SCOPE_VERSION);
+ for (const key of ['title', 'summary', 'retention', 'revocation']) {
+ expect(typeof X_SEED_DISCLOSURE[key]).toBe('string');
+ expect(X_SEED_DISCLOSURE[key].length).toBeGreaterThan(10);
+ }
+ for (const key of ['reads', 'skips', 'stores', 'never']) {
+ expect(X_SEED_DISCLOSURE[key].length).toBeGreaterThan(0);
+ }
+ });
+
+ it('states the same limits the transform enforces', () => {
+ expect(X_SEED_DISCLOSURE.reads.join(' ')).toContain(String(X_SEED_LIMITS.maxPosts));
+ expect(X_SEED_DISCLOSURE.stores.join(' ')).toContain(String(X_SEED_LIMITS.maxFacts));
+ expect(X_SEED_DISCLOSURE.stores.join(' ')).toContain(String(X_SEED_LIMITS.maxFactChars));
+ });
+
+ it('cannot be mutated by a caller that receives it', () => {
+ expect(Object.isFrozen(X_SEED_DISCLOSURE)).toBe(true);
+ });
+});