Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(memory): make Farcaster seeding keyless-capable and record a revocable consent grant
nirholascb2551e0b875
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 9c63ea315..3d7847793 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -1514,12 +1514,19 @@ export const env = {return opt('RIDER_HELIUS_WEBHOOK_SECRET');},- // Neynar API key — used by POST /api/agents/:id/memory/seed/farcaster.- // When unset, the endpoint returns 501 not_configured.+ // Neynar API key — the preferred (indexed) rung of the Farcaster read chain+ // in api/_lib/farcaster-client.js. Optional: without it the chain falls back+ // to the keyless public hub below, so Farcaster memory seeding still works.get NEYNAR_API_KEY() {return opt('NEYNAR_API_KEY');},+ // Public Farcaster hub HTTP endpoint — the keyless rung of that same chain.+ // Any hub that speaks the standard /v1 HTTP API works.+ get FARCASTER_HUB_URL() {+ return opt('FARCASTER_HUB_URL');+ },+// OpenAI API key — used by TTS proxy (/api/tts/speak) and chat endpoints.// Never sent to the browser.get OPENAI_API_KEY() {diff --git a/api/_lib/farcaster-client.js b/api/_lib/farcaster-client.jsnew file mode 100644index 000000000..169fa7aeb--- /dev/null+++ b/api/_lib/farcaster-client.js@@ -0,0 +1,180 @@+// Read-only Farcaster reader with a two-rung failover chain.+//+// 1. Neynar (@neynar/nodejs-sdk, MIT) when NEYNAR_API_KEY is configured.+// Indexed data: follower counts and per-cast reaction counts, which is what+// makes engagement ranking possible.+// 2. A public Farcaster hub over its documented HTTP API, keyless. Default+// https://hub.pinata.cloud, override with FARCASTER_HUB_URL. Serves the raw+// protocol messages, so it has no reaction counts but needs no vendor key+// and never goes dark because a billing plan lapsed.+//+// Every call here is a public read. No signer is requested, nothing is written+// back to Farcaster, and no private endpoint is touched: the wallet proof in+// api/agents/_id/memory-seed-farcaster.js is what establishes that the caller+// owns the fid, not an access token.++import { NeynarAPIClient, Configuration } from '@neynar/nodejs-sdk';+import { env } from './env.js';+import {+ normalizeHubCasts,+ normalizeHubUserData,+ normalizeNeynarCasts,+ normalizeNeynarUser,+ normalizeVerifications,+} from './farcaster-seed.js';++const HUB_TIMEOUT_MS = 15_000;+const HUB_PAGE_SIZE = 100;++export class FarcasterError extends Error {+ constructor(message, { status = 502, code = 'farcaster_upstream' } = {}) {+ super(message);+ this.name = 'FarcasterError';+ this.status = status;+ this.code = code;+ }+}++let _neynar = null;+function neynar() {+ if (!env.NEYNAR_API_KEY) return null;+ if (!_neynar) _neynar = new NeynarAPIClient(new Configuration({ apiKey: env.NEYNAR_API_KEY }));+ return _neynar;+}++export function hubUrl() {+ return (env.FARCASTER_HUB_URL || 'https://hub.pinata.cloud').replace(/\/+$/, '');+}++async function hubGet(path) {+ let resp;+ try {+ resp = await fetch(`${hubUrl()}${path}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(HUB_TIMEOUT_MS),+ });+ } catch (err) {+ throw new FarcasterError(`Farcaster hub unreachable: ${err?.message || err}`);+ }+ if (resp.status === 404) throw new FarcasterError('Farcaster user not found', { status: 404, code: 'farcaster_user_not_found' });+ if (!resp.ok) throw new FarcasterError(`Farcaster hub ${resp.status}`);+ return resp.json();+}++/** Page through a hub message endpoint until `limit` messages or the pages run out. */+async function hubMessages(path, limit) {+ const messages = [];+ let pageToken = '';+ while (messages.length < limit) {+ const sep = path.includes('?') ? '&' : '?';+ const page = await hubGet(+ `${path}${sep}pageSize=${HUB_PAGE_SIZE}${pageToken ? `&pageToken=${encodeURIComponent(pageToken)}` : ''}`,+ );+ const batch = page?.messages || [];+ messages.push(...batch);+ pageToken = page?.nextPageToken || '';+ if (!pageToken || batch.length === 0) break;+ }+ return messages.slice(0, limit);+}++// ── Resolve a user ──────────────────────────────────────────────────────────++/**+ * Resolve `{ fid }` or `{ fname }` to a profile. Returns the lane that answered+ * so callers can report which data source the seed came from.+ */+export async function resolveFarcasterUser({ fid = null, fname = null }) {+ if (!fid && !fname) throw new FarcasterError('fid or fname required', { status: 400, code: 'validation_error' });++ const client = neynar();+ if (client) {+ try {+ const user = fid+ ? (await client.fetchBulkUsers({ fids: [Number(fid)] }))?.users?.[0]+ : (await client.lookupUserByUsername({ username: String(fname).replace(/^@/, '') }))?.user;+ if (user?.fid) return { ...normalizeNeynarUser(user), lane: 'neynar' };+ } catch (err) {+ if (err?.response?.status === 404) {+ throw new FarcasterError('Farcaster user not found', { status: 404, code: 'farcaster_user_not_found' });+ }+ console.warn('[farcaster-client] neynar user lookup failed, falling back to hub', err?.message || err);+ }+ }++ let resolvedFid = fid ? Number(fid) : null;+ if (!resolvedFid) {+ const proof = await hubGet(`/v1/userNameProofByName?name=${encodeURIComponent(String(fname).replace(/^@/, ''))}`);+ resolvedFid = Number(proof?.fid);+ if (!Number.isInteger(resolvedFid) || resolvedFid <= 0) {+ throw new FarcasterError('Farcaster user not found', { status: 404, code: 'farcaster_user_not_found' });+ }+ }++ const data = await hubGet(`/v1/userDataByFid?fid=${resolvedFid}`);+ const messages = data?.messages || [];+ if (messages.length === 0 && !fid) {+ throw new FarcasterError('Farcaster user not found', { status: 404, code: 'farcaster_user_not_found' });+ }+ const profile = normalizeHubUserData(messages);+ return {+ fid: resolvedFid,+ fname: profile.fname || (fname ? String(fname).replace(/^@/, '') : null),+ displayName: profile.displayName,+ bio: profile.bio,+ pfpUrl: profile.pfpUrl,+ url: profile.url,+ followerCount: null,+ followingCount: null,+ lane: 'hub',+ };+}++// ── Verified addresses ──────────────────────────────────────────────────────++/**+ * The wallets this fid has publicly proved control of, by protocol. This is the+ * allowlist for the consent signature: only an address in here can grant a seed+ * for this fid, which is what stops one user from seeding another user's casts.+ */+export async function fetchVerifiedAddresses(fid) {+ const client = neynar();+ if (client) {+ try {+ const user = (await client.fetchBulkUsers({ fids: [Number(fid)] }))?.users?.[0];+ const verified = user?.verified_addresses;+ if (verified) {+ return {+ solana: [...new Set(verified.sol_addresses || [])],+ ethereum: [...new Set((verified.eth_addresses || []).map((a) => String(a).toLowerCase()))],+ lane: 'neynar',+ };+ }+ } catch (err) {+ console.warn('[farcaster-client] neynar verifications failed, falling back to hub', err?.message || err);+ }+ }++ const messages = await hubMessages(`/v1/verificationsByFid?fid=${Number(fid)}`, HUB_PAGE_SIZE);+ return { ...normalizeVerifications(messages), lane: 'hub' };+}++// ── Casts ───────────────────────────────────────────────────────────────────++/** Recent casts for a fid, newest first, normalized across both lanes. */+export async function fetchRecentCasts(fid, limit = 100) {+ const bounded = Math.min(Math.max(1, Number(limit) || 100), 200);+ const client = neynar();+ if (client) {+ try {+ const resp = await client.fetchCastsForUser({ fid: Number(fid), limit: bounded, includeReplies: false });+ const casts = normalizeNeynarCasts(resp?.casts || []);+ if (casts.length > 0) return { casts, lane: 'neynar' };+ } catch (err) {+ console.warn('[farcaster-client] neynar casts failed, falling back to hub', err?.message || err);+ }+ }++ const messages = await hubMessages(`/v1/castsByFid?fid=${Number(fid)}&reverse=true`, bounded);+ return { casts: normalizeHubCasts(messages), lane: 'hub' };+}diff --git a/api/_lib/farcaster-seed.js b/api/_lib/farcaster-seed.jsnew file mode 100644index 000000000..9bbef009c--- /dev/null+++ b/api/_lib/farcaster-seed.js@@ -0,0 +1,395 @@+// Pure transforms for consent-gated Farcaster memory seeding.+//+// Everything here is deterministic and network-free so the seeding pipeline can+// be tested without a hub, an indexer, or a database:+// * the consent message a user signs with their wallet (build + parse),+// * normalisation of the two upstream shapes (hub protobuf-JSON, Neynar),+// * selection of which casts are worth remembering,+// * the memory rows written to agent_memories.+//+// The network lane lives in ./farcaster-client.js; the HTTP surface lives in+// api/agents/_id/memory-seed-farcaster.js.++// Farcaster message timestamps are seconds since 2021-01-01T00:00:00Z.+export const FARCASTER_EPOCH_MS = 1_609_459_200_000;++// Read-only, least privilege: we never ask for a Farcaster signer, never write+// a cast, and never touch anything that is not already public on the protocol.+export const CONSENT_SCOPE = 'farcaster:profile.read farcaster:casts.read';++export const CONSENT_TTL_MS = 10 * 60 * 1000;++export const MEMORY_SOURCE = 'farcaster_seed';++export const PROOF_CHAINS = ['solana', 'ethereum'];++const CONSENT_HEADER = 'three.ws memory seeding consent';++const CONSENT_BODY =+ 'I authorize three.ws to read my public Farcaster profile and casts and store them as ' ++ 'memory for the agent below. Revoking this grant deletes every memory seeded from it.';++// ── Consent message ─────────────────────────────────────────────────────────++/**+ * Build the exact text the user signs in their wallet. Deterministic: the+ * server rebuilds it from the challenge it stored and compares byte for byte,+ * so a tampered field (different agent, different fid) never verifies.+ */+export function buildConsentMessage({+ domain,+ agentId,+ fid,+ fname,+ address,+ chain,+ nonce,+ issuedAt,+ expiresAt,+ castLimit,+}) {+ if (!domain) throw new Error('domain required');+ if (!agentId) throw new Error('agentId required');+ if (!Number.isInteger(fid) || fid <= 0) throw new Error('fid required');+ if (!address) throw new Error('address required');+ if (!PROOF_CHAINS.includes(chain)) throw new Error(`unsupported chain: ${chain}`);+ if (!nonce) throw new Error('nonce required');++ return [+ `${domain} ${CONSENT_HEADER}`,+ '',+ CONSENT_BODY,+ '',+ `Agent: ${agentId}`,+ `Farcaster FID: ${fid}`,+ `Farcaster Name: ${fname || '(none)'}`,+ `Wallet: ${address}`,+ `Chain: ${chain}`,+ `Scope: ${CONSENT_SCOPE}`,+ `Casts: up to ${castLimit}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expiresAt}`,+ ].join('\n');+}++/** Parse a consent message back into fields. Returns null when malformed. */+export function parseConsentMessage(message) {+ if (typeof message !== 'string') return null;+ const lines = message.split('\n');+ const header = new RegExp(`^(\\S+) ${CONSENT_HEADER}$`).exec(lines[0] || '');+ if (!header) return null;++ const out = { domain: header[1] };+ const keys = {+ Agent: 'agentId',+ 'Farcaster FID': 'fid',+ 'Farcaster Name': 'fname',+ Wallet: 'address',+ Chain: 'chain',+ Scope: 'scope',+ Casts: 'castLimit',+ Nonce: 'nonce',+ 'Issued At': 'issuedAt',+ 'Expiration Time': 'expiresAt',+ };+ for (const line of lines.slice(1)) {+ const kv = /^([A-Za-z ]+):\s*(.*)$/.exec(line);+ if (!kv) continue;+ const field = keys[kv[1].trim()];+ if (field) out[field] = kv[2].trim();+ }++ if (!out.agentId || !out.fid || !out.address || !out.nonce) return null;+ out.fid = Number(out.fid);+ if (!Number.isInteger(out.fid) || out.fid <= 0) return null;+ if (out.fname === '(none)') out.fname = null;+ const castLimit = /(\d+)/.exec(out.castLimit || '');+ out.castLimit = castLimit ? Number(castLimit[1]) : null;+ return out;+}++// ── Address matching ────────────────────────────────────────────────────────++/**+ * Solana addresses are base58 and case significant; EVM addresses are hex and+ * are compared case-insensitively so a checksummed wallet still matches the+ * lowercase form the protocol stores.+ */+export function normalizeAddress(address, chain) {+ const raw = String(address ?? '').trim();+ if (!raw) return '';+ return chain === 'ethereum' ? raw.toLowerCase() : raw;+}++export function addressMatches(candidate, verified, chain) {+ const needle = normalizeAddress(candidate, chain);+ if (!needle) return false;+ return (verified || []).some((v) => normalizeAddress(v, chain) === needle);+}++// ── Upstream normalisation: hub protobuf-JSON ───────────────────────────────++const USER_DATA_FIELDS = {+ USER_DATA_TYPE_PFP: 'pfpUrl',+ USER_DATA_TYPE_DISPLAY: 'displayName',+ USER_DATA_TYPE_BIO: 'bio',+ USER_DATA_TYPE_URL: 'url',+ USER_DATA_TYPE_USERNAME: 'fname',+};++/** Fold a hub `/v1/userDataByFid` message list into a flat profile. */+export function normalizeHubUserData(messages) {+ const profile = { fname: null, displayName: null, bio: null, pfpUrl: null, url: null };+ for (const msg of messages || []) {+ const body = msg?.data?.userDataBody;+ const field = USER_DATA_FIELDS[body?.type];+ if (field && typeof body.value === 'string' && body.value) profile[field] = body.value;+ }+ return profile;+}++/**+ * Fold a hub `/v1/verificationsByFid` message list into the addresses the fid+ * has publicly proved control of, split by protocol. These are the only+ * wallets allowed to grant consent for this fid.+ */+export function normalizeVerifications(messages) {+ const out = { solana: [], ethereum: [] };+ for (const msg of messages || []) {+ const body = msg?.data?.verificationAddAddressBody;+ const address = body?.address;+ if (!address) continue;+ const chain = body.protocol === 'PROTOCOL_SOLANA' ? 'solana' : 'ethereum';+ const normalized = normalizeAddress(address, chain);+ if (normalized && !out[chain].includes(normalized)) out[chain].push(normalized);+ }+ return out;+}++/** Fold a hub `/v1/castsByFid` message list into normalized casts. */+export function normalizeHubCasts(messages) {+ const casts = [];+ for (const msg of messages || []) {+ const data = msg?.data;+ if (data?.type !== 'MESSAGE_TYPE_CAST_ADD') continue;+ const body = data.castAddBody;+ if (!body) continue;+ casts.push({+ hash: msg.hash || null,+ text: typeof body.text === 'string' ? body.text : '',+ timestamp: farcasterTimeToMs(data.timestamp),+ isReply: Boolean(body.parentCastId || body.parentUrl),+ engagement: null,+ });+ }+ return casts;+}++export function farcasterTimeToMs(seconds) {+ const n = Number(seconds);+ if (!Number.isFinite(n)) return null;+ return FARCASTER_EPOCH_MS + n * 1000;+}++// ── Upstream normalisation: Neynar ──────────────────────────────────────────++/** Fold Neynar's indexed cast objects into the same shape as the hub lane. */+export function normalizeNeynarCasts(casts) {+ const out = [];+ for (const cast of casts || []) {+ const likes = cast?.reactions?.likes_count ?? 0;+ const recasts = cast?.reactions?.recasts_count ?? 0;+ const replies = cast?.replies?.count ?? 0;+ const ts = cast?.timestamp ? Date.parse(cast.timestamp) : NaN;+ out.push({+ hash: cast?.hash || null,+ text: typeof cast?.text === 'string' ? cast.text : '',+ timestamp: Number.isFinite(ts) ? ts : null,+ isReply: Boolean(cast?.parent_hash || cast?.parent_url),+ engagement: likes + recasts * 2 + replies * 3,+ });+ }+ return out;+}++export function normalizeNeynarUser(user) {+ if (!user) return null;+ return {+ fid: user.fid ?? null,+ fname: user.username || null,+ displayName: user.display_name || null,+ bio: user.profile?.bio?.text || null,+ pfpUrl: user.pfp_url || null,+ url: null,+ followerCount: user.follower_count ?? null,+ followingCount: user.following_count ?? null,+ };+}++// ── Cast selection ──────────────────────────────────────────────────────────++const URL_RE = /https?:\/\/\S+/g;+const MENTION_RE = /(^|\s)@[\w.-]+/g;++/** Text left once links and mentions are stripped: what actually carries meaning. */+export function substantiveText(text) {+ return String(text ?? '')+ .replace(URL_RE, ' ')+ .replace(MENTION_RE, ' ')+ .replace(/\s+/g, ' ')+ .trim();+}++/**+ * Pick the casts worth remembering: drop link-only and near-empty posts,+ * de-duplicate reposted text, then rank by engagement when the lane reports it+ * (Neynar) and by recency when it does not (a hub serves raw messages with no+ * reaction counts).+ */+export function selectSeedCasts(casts, { limit = 40, minChars = 16, includeReplies = false } = {}) {+ const seen = new Set();+ const kept = [];+ for (const cast of casts || []) {+ if (!includeReplies && cast.isReply) continue;+ const body = substantiveText(cast.text);+ if (body.length < minChars) continue;+ const key = body.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ kept.push({ ...cast, body });+ }++ const ranked = kept.some((c) => typeof c.engagement === 'number')+ ? kept.sort(+ (a, b) => (b.engagement ?? 0) - (a.engagement ?? 0) || (b.timestamp ?? 0) - (a.timestamp ?? 0),+ )+ : kept.sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0));++ return ranked.slice(0, Math.max(0, limit));+}++// ── Memory rows ─────────────────────────────────────────────────────────────++const MAX_CONTENT_CHARS = 10_000;+const DEFAULT_CAST_MEMORIES = 12;++function isoDay(ms) {+ return Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null;+}++/**+ * Turn a verified profile, its selected casts, and any LLM-distilled facts into+ * agent_memories rows. Every row carries the consent id so revocation can+ * delete exactly what this grant wrote and nothing else.+ *+ * The profile and cast rows are derived without an LLM, so a seed still+ * produces real memory when the distillation lane is unavailable.+ */+export function buildSeedMemories({+ fid,+ fname = null,+ profile = {},+ casts = [],+ facts = [],+ consentId,+ castMemoryLimit = DEFAULT_CAST_MEMORIES,+}) {+ if (!Number.isInteger(fid) || fid <= 0) throw new Error('fid required');+ if (!consentId) throw new Error('consentId required');++ const handle = fname || profile.fname || String(fid);+ const base = { source: MEMORY_SOURCE, fid, consent_id: consentId, fname: handle };+ const rows = [];++ const identity = [+ profile.displayName ? `Display name: ${profile.displayName}` : null,+ `Farcaster: @${handle} (FID ${fid})`,+ profile.bio ? `Bio: ${profile.bio}` : null,+ Number.isFinite(profile.followerCount) ? `Followers: ${profile.followerCount}` : null,+ ]+ .filter(Boolean)+ .join('. ');++ rows.push({+ type: 'user',+ content: clip(`The user's Farcaster identity. ${identity}`),+ tags: ['farcaster', 'profile'],+ context: { ...base, kind: 'profile' },+ salience: 0.8,+ });++ for (const fact of facts) {+ const content = typeof fact === 'string' ? fact.trim() : '';+ if (!content) continue;+ rows.push({+ type: 'user',+ content: clip(content),+ tags: ['farcaster', 'fact'],+ context: { ...base, kind: 'fact' },+ salience: 0.7,+ });+ }++ const topCasts = casts.slice(0, Math.max(0, castMemoryLimit));+ topCasts.forEach((cast, index) => {+ const body = cast.body || substantiveText(cast.text);+ if (!body) return;+ const day = isoDay(cast.timestamp);+ const dated = day ? ` on ${day}` : '';+ // Rank decay keeps the loudest casts above the tail without ever pushing a+ // raw post into the working core, which is reserved for distilled facts.+ const salience = Math.max(0.4, 0.62 - index * 0.015);+ rows.push({+ type: 'reference',+ content: clip(`The user cast${dated} on Farcaster: "${body}"`),+ tags: ['farcaster', 'cast'],+ context: { ...base, kind: 'cast', cast_hash: cast.hash ?? null, cast_at: cast.timestamp ?? null },+ salience: Number(salience.toFixed(3)),+ });+ });++ return rows;+}++function clip(text) {+ return text.length > MAX_CONTENT_CHARS ? `${text.slice(0, MAX_CONTENT_CHARS - 1)}…` : text;+}++/** Prompt input for the distillation lane: newest-first cast text, bounded. */+export function distillationInput({ profile = {}, casts = [], maxCasts = 50 }) {+ const lines = casts+ .slice(0, maxCasts)+ .map((c) => c.body || substantiveText(c.text))+ .filter(Boolean);+ const header = [+ profile.displayName ? `Display name: ${profile.displayName}` : null,+ profile.fname ? `Handle: @${profile.fname}` : null,+ profile.bio ? `Bio: ${profile.bio}` : null,+ Number.isFinite(profile.followerCount) ? `Followers: ${profile.followerCount}` : null,+ ]+ .filter(Boolean)+ .join(', ');+ return { header: header || '(no profile data)', casts: lines };+}++/** Parse the distillation model's reply into a bounded list of fact strings. */+export function parseDistilledFacts(raw, { max = 15 } = {}) {+ if (typeof raw !== 'string') return [];+ const stripped = raw+ .replace(/^```(?:json)?\s*/i, '')+ .replace(/\s*```\s*$/i, '')+ .trim();+ let parsed;+ try {+ parsed = JSON.parse(stripped);+ } catch {+ return [];+ }+ if (!Array.isArray(parsed)) return [];+ return parsed+ .filter((f) => typeof f === 'string')+ .map((f) => f.trim())+ .filter(Boolean)+ .slice(0, max);+}diff --git a/api/_lib/migrations/20260811130000_farcaster_memory_consent.sql b/api/_lib/migrations/20260811130000_farcaster_memory_consent.sqlnew file mode 100644index 000000000..645ecc0e8--- /dev/null+++ b/api/_lib/migrations/20260811130000_farcaster_memory_consent.sql@@ -0,0 +1,67 @@+-- Consent-gated Farcaster memory seeding.+--+-- Seeding used to accept any handle: a signed-in user could type someone else's+-- Farcaster name and pull that person's casts into an agent's long-term memory.+-- These two tables make the flow consent-first and revocable.+--+-- farcaster_seed_challenges holds the one-time nonce and the exact text the+-- wallet is asked to sign. The message is stored server-side so verification+-- compares against what WE issued, never against a client-supplied copy.+--+-- farcaster_memory_consents is the durable grant. Every memory row written by a+-- seed carries its consent id in context->>'consent_id', so revocation deletes+-- exactly what the grant produced and nothing else.++create table if not exists farcaster_seed_challenges (+ nonce text primary key,+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ fid integer not null,+ fname text,+ -- Canonical signable text. Byte-for-byte comparison at verify time.+ message text not null,+ cast_limit int not null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null,+ consumed_at timestamptz+);++create index if not exists farcaster_seed_challenges_agent+ on farcaster_seed_challenges (agent_id) where consumed_at is null;+create index if not exists farcaster_seed_challenges_expiry+ on farcaster_seed_challenges (expires_at);++create table if not exists farcaster_memory_consents (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ fid integer not null,+ fname text,+ scope text not null,+ -- The wallet that proved control of the fid. It must appear in the fid's+ -- public Farcaster verifications, which is what binds grant to identity.+ proof_chain text not null check (proof_chain in ('solana', 'ethereum')),+ proof_address text not null,+ proof_signature text not null,+ proof_message text not null,+ source_lane text,+ granted_at timestamptz not null default now(),+ revoked_at timestamptz,+ last_seeded_at timestamptz,+ memories_seeded int not null default 0,+ casts_ingested int not null default 0+);++-- An agent's memory is seeded from at most one live Farcaster identity. Pointing+-- it at a different fid means revoking the first grant, which deletes its rows.+create unique index if not exists farcaster_memory_consents_active_agent+ on farcaster_memory_consents (agent_id) where revoked_at is null;+create index if not exists farcaster_memory_consents_user+ on farcaster_memory_consents (user_id);+create index if not exists farcaster_memory_consents_fid+ on farcaster_memory_consents (fid) where revoked_at is null;++-- Revocation deletes by consent id, so keep that lookup off a sequential scan.+create index if not exists agent_memories_farcaster_consent+ on agent_memories ((context ->> 'consent_id'))+ where context ->> 'source' = 'farcaster_seed';diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 3f0f9765b..c9f15ce2b 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -2285,3 +2285,88 @@ create table if not exists user_badges ();create unique index if not exists user_badges_uniq on user_badges (user_id, code);create index if not exists user_badges_user on user_badges (user_id, unlocked_at desc);++-- ── Farcaster memory seeding consent ────────────────────────────────────────+-- Mirrors api/_lib/migrations/20260811130000_farcaster_memory_consent.sql. The+-- challenge table holds the one-time nonce plus the exact text the wallet signs+-- (stored server-side so verification never trusts a client copy); the consent+-- table is the durable, revocable grant. Every seeded memory row carries its+-- consent id in context->>'consent_id' so a revoke deletes exactly that grant.+create table if not exists farcaster_seed_challenges (+ nonce text primary key,+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ fid integer not null,+ fname text,+ message text not null,+ cast_limit int not null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null,+ consumed_at timestamptz+);+create index if not exists farcaster_seed_challenges_agent+ on farcaster_seed_challenges (agent_id) where consumed_at is null;+create index if not exists farcaster_seed_challenges_expiry+ on farcaster_seed_challenges (expires_at);++create table if not exists farcaster_memory_consents (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ fid integer not null,+ fname text,+ scope text not null,+ proof_chain text not null check (proof_chain in ('solana', 'ethereum')),+ proof_address text not null,+ proof_signature text not null,+ proof_message text not null,+ source_lane text,+ granted_at timestamptz not null default now(),+ revoked_at timestamptz,+ last_seeded_at timestamptz,+ memories_seeded int not null default 0,+ casts_ingested int not null default 0+);+create unique index if not exists farcaster_memory_consents_active_agent+ on farcaster_memory_consents (agent_id) where revoked_at is null;+create index if not exists farcaster_memory_consents_user+ on farcaster_memory_consents (user_id);+create index if not exists farcaster_memory_consents_fid+ on farcaster_memory_consents (fid) where revoked_at is null;+create index if not exists agent_memories_farcaster_consent+ on agent_memories ((context ->> 'consent_id'))+ where context ->> 'source' = 'farcaster_seed';++-- ── x_memory_consents ─────────────────────────────────────────────────────────+-- Consent-gated X memory seeding. See+-- api/_lib/migrations/20260811140000_x_memory_consent.sql for the rationale and+-- api/_lib/x-memory-seed.js for the disclosure this grant is recorded against.+create table if not exists x_memory_consents (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ x_user_id text not null,+ username text not null,+ scope_version text not null,+ disclosure jsonb not null default '{}'::jsonb,+ granted_scopes text,+ granted_at timestamptz not null default now(),+ revoked_at timestamptz,+ revoked_reason text,+ last_seeded_at timestamptz,+ memories_seeded int not null default 0,+ posts_read int not null default 0+);+create unique index if not exists x_memory_consents_active_agent+ on x_memory_consents (agent_id) where revoked_at is null;+create index if not exists x_memory_consents_user+ on x_memory_consents (user_id);+create index if not exists x_memory_consents_x_user+ on x_memory_consents (x_user_id) where revoked_at is null;+create index if not exists agent_memories_x_seed_consent+ on agent_memories ((context ->> 'consent_id'))+ where context ->> 'source' = 'x_seed';++-- The X OAuth callback never supplied social_connections.scopes, which is NOT+-- NULL with no default, so every X connect died before writing a row.+alter table social_connections alter column scopes set default '';