Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(memory): put X seeding behind the same consent grant as the GitHub lane

nirholas33dfc2e50987
diff --git a/api/_lib/migrations/20260811140000_x_memory_consent.sql b/api/_lib/migrations/20260811140000_x_memory_consent.sql
new file mode 100644
index 000000000..40ea3f6a8
--- /dev/null
+++ b/api/_lib/migrations/20260811140000_x_memory_consent.sql
@@ -0,0 +1,54 @@
+-- Consent-gated X memory seeding.
+--
+-- Connecting X and seeding an agent used to be the same decision: any user with
+-- a live 'x' social_connection could push their posts into an agent's long-term
+-- memory with one button, and disconnecting left those memories behind forever.
+-- This table makes the seed its own explicit, versioned, revocable grant.
+--
+-- Every memory row a seed writes carries its consent id in
+-- context->>'consent_id', so revoking deletes exactly what the grant produced.
+-- The disclosure the owner actually read is stored verbatim on the row: when
+-- the wording changes, X_SEED_SCOPE_VERSION moves and the stored version stops
+-- authorizing new seeds until the owner agrees to the new text.
+
+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's numeric account id, captured at grant time. A reconnect to a different
+ -- X account cannot silently reuse a grant made for the first one.
+ x_user_id text not null,
+ username text not null,
+ scope_version text not null,
+ -- The exact disclosure text shown when consent was granted.
+ disclosure jsonb not null default '{}'::jsonb,
+ -- The OAuth scopes X actually granted the connection at that moment.
+ 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
+);
+
+-- An agent's memory is seeded from at most one live X identity. Pointing it at
+-- another account means revoking the first grant, which deletes its rows.
+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;
+
+-- Revocation deletes by consent id, so keep that lookup off a sequential scan.
+create index if not exists agent_memories_x_seed_consent
+ on agent_memories ((context ->> 'consent_id'))
+ where context ->> 'source' = 'x_seed';
+
+-- social_connections.scopes is NOT NULL with no default, but the X OAuth
+-- callback (unlike the GitHub one) never supplied it, so every X connect
+-- attempt died on a not-null violation before a row was ever written. The
+-- callback now records the granted scope string; this default keeps any other
+-- writer from hitting the same wall.
+alter table social_connections alter column scopes set default '';
diff --git a/api/_lib/x-memory-seed.js b/api/_lib/x-memory-seed.js
new file mode 100644
index 000000000..eed4dcf75
--- /dev/null
+++ b/api/_lib/x-memory-seed.js
@@ -0,0 +1,400 @@
+/**
+ * X memory seeding: the consent disclosure and the seeding transform.
+ * ------------------------------------------------------------------
+ * Everything in this module is pure. The network calls (OAuth token refresh,
+ * the X reads, the LLM distillation) live in the handler; what gets *stored*
+ * is decided here so it can be pinned by tests and so the consent screen and
+ * the writer read the same declaration instead of drifting apart.
+ *
+ * The contract the consent screen makes is enforced here, not just described:
+ *
+ * - only the fields listed in `reads` are ever sent to the distiller,
+ * - raw posts never become a memory (a near-verbatim fact is dropped),
+ * - links are stripped out of stored text,
+ * - every stored row carries its provenance and the scope version the
+ * owner agreed to, so revocation can find and delete exactly these rows.
+ */
+
+// Bump when the disclosure below changes in a way an owner would want to
+// re-read. A consent recorded against an older version stops authorizing new
+// seeds: the handler asks for consent again at the new version.
+export const X_SEED_SCOPE_VERSION = '2026-08-11.1';
+
+/** Tag every seeded memory carries. Revocation deletes exactly this tag. */
+export const X_SEED_TAG = 'x_seed';
+
+export const X_SEED_LIMITS = {
+ /** Most recent original posts read per seed. */
+ maxPosts: 100,
+ /** Posts shorter than this after link stripping carry no signal. */
+ minPostChars: 20,
+ /** Facts stored per seed. */
+ maxFacts: 15,
+ /** Characters per stored fact. */
+ maxFactChars: 280,
+ /** Top-ranked facts promoted to the always-in-context working tier. */
+ workingTierFacts: 5,
+};
+
+/**
+ * Exactly what the seeder reads and stores. This object is served verbatim to
+ * the consent screen, so every line here is a promise the code below keeps.
+ */
+export const X_SEED_DISCLOSURE = Object.freeze({
+ version: X_SEED_SCOPE_VERSION,
+ provider: 'x',
+ title: 'Seed this agent from your X account',
+ summary:
+ 'Your most recent public posts are read once, distilled into short facts about ' +
+ 'what you talk about and how you talk, and stored as memories on this agent. ' +
+ 'Your posts themselves are never stored.',
+ reads: Object.freeze([
+ 'Your X profile: display name, handle, bio, follower and following counts.',
+ `Up to ${X_SEED_LIMITS.maxPosts} of your most recent original public posts (text and post date).`,
+ ]),
+ skips: Object.freeze([
+ 'Reposts and replies are excluded from the read.',
+ 'Direct messages, drafts, protected accounts you follow, likes, bookmarks, and your follower list are never read.',
+ ]),
+ stores: Object.freeze([
+ `Up to ${X_SEED_LIMITS.maxFacts} short distilled facts (max ${X_SEED_LIMITS.maxFactChars} characters each) about your recurring topics, opinions, projects, and tone.`,
+ 'Your X handle, so the agent can attribute what it learned.',
+ 'The date of the seed and the version of this disclosure you agreed to.',
+ ]),
+ never: Object.freeze([
+ 'The text of your posts. A distilled fact that copies a post is discarded before it is written.',
+ 'Links from your posts. URLs are stripped out of stored text.',
+ 'Any X credential. Your access token stays encrypted in the connection record and is never copied into a memory.',
+ ]),
+ retention: Object.freeze(
+ 'Seeded memories live on the agent until you re-seed (which replaces them) or ' +
+ 'revoke consent (which deletes them).',
+ ),
+ revocation: Object.freeze(
+ 'Revoking consent, or disconnecting X, deletes every memory this seeding created. ' +
+ 'Nothing distilled from your account survives.',
+ ),
+});
+
+// ── Text normalisation ────────────────────────────────────────────────────────
+
+const URL_RE = /https?:\/\/\S+/g;
+
+export function stripLinks(text) {
+ return String(text ?? '')
+ .replace(URL_RE, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+function normalizeForCompare(text) {
+ return stripLinks(text)
+ .toLowerCase()
+ .replace(/[^a-z0-9\s]/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+// ── Read side: which posts feed the distiller ────────────────────────────────
+
+/**
+ * Narrow a raw X timeline payload to the posts the disclosure allows: original
+ * public posts, link-stripped, long enough to carry signal, de-duplicated, and
+ * capped. Only `text` and `created_at` survive; any other field X returned is
+ * dropped here so it can never reach the distiller.
+ *
+ * @param {Array<object>} rawPosts entries from GET /2/users/:id/tweets
+ * @returns {Array<{text: string, created_at: string|null}>}
+ */
+export function selectSeedPosts(rawPosts, { limit = X_SEED_LIMITS.maxPosts } = {}) {
+ if (!Array.isArray(rawPosts)) return [];
+ const seen = new Set();
+ const out = [];
+ for (const post of rawPosts) {
+ if (!post || typeof post !== 'object') continue;
+ // The read already excludes retweets and replies; re-check so a payload
+ // shape change cannot quietly widen what gets distilled.
+ const refs = Array.isArray(post.referenced_tweets) ? post.referenced_tweets : [];
+ if (refs.some((r) => r?.type === 'retweeted' || r?.type === 'replied_to')) continue;
+ if (post.in_reply_to_user_id) continue;
+ const text = stripLinks(post.text);
+ if (text.length < X_SEED_LIMITS.minPostChars) continue;
+ if (/^rt @/i.test(text)) continue;
+ const key = normalizeForCompare(text);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push({ text, created_at: post.created_at ?? null });
+ if (out.length >= limit) break;
+ }
+ return out;
+}
+
+/**
+ * The profile fields the disclosure allows, and nothing else. Everything the
+ * distiller sees about the account passes through here first.
+ */
+export function selectSeedProfile(rawProfile) {
+ const p = rawProfile && typeof rawProfile === 'object' ? rawProfile : {};
+ return {
+ username: typeof p.username === 'string' ? p.username : '',
+ name: typeof p.name === 'string' ? p.name : '',
+ description: stripLinks(p.description).slice(0, 500),
+ followers: Number(p.public_metrics?.followers_count) || 0,
+ following: Number(p.public_metrics?.following_count) || 0,
+ };
+}
+
+// ── Topic extraction (deterministic) ─────────────────────────────────────────
+
+const STOPWORDS = new Set([
+ 'the', 'and', 'for', 'that', 'this', 'with', 'you', 'your', 'are', 'was', 'were', 'but',
+ 'not', 'have', 'has', 'had', 'from', 'they', 'them', 'their', 'what', 'when', 'where',
+ 'which', 'who', 'will', 'would', 'could', 'should', 'about', 'there', 'here', 'been',
+ 'just', 'like', 'more', 'most', 'some', 'such', 'than', 'then', 'they', 'into', 'over',
+ 'only', 'also', 'very', 'much', 'many', 'even', 'still', 'really', 'get', 'got', 'going',
+ 'make', 'made', 'use', 'using', 'used', 'new', 'now', 'today', 'time', 'day', 'week',
+ 'year', 'people', 'thing', 'things', 'way', 'good', 'great', 'best', 'better', 'its',
+ 'his', 'her', 'she', 'him', 'our', 'out', 'off', 'all', 'any', 'can', 'one', 'two',
+ 'how', 'why', 'via', 'amp', 'rt', 'dont', 'doesnt', 'cant', 'wont', 'ive', 'im',
+]);
+
+/**
+ * The topics an account posts about, by frequency. Hashtags count double
+ * because an author chose them deliberately. Used both for provenance tags and
+ * for the deterministic facts that keep a seed useful when the distiller is
+ * unavailable.
+ *
+ * @returns {Array<{topic: string, count: number}>}
+ */
+export function deriveTopics(posts, { limit = 8 } = {}) {
+ const counts = new Map();
+ const bump = (token, weight) => counts.set(token, (counts.get(token) || 0) + weight);
+ for (const post of Array.isArray(posts) ? posts : []) {
+ const text = typeof post === 'string' ? post : post?.text;
+ if (!text) continue;
+ for (const tag of String(text).match(/#[A-Za-z][A-Za-z0-9_]{1,30}/g) || []) {
+ bump(tag.slice(1).toLowerCase(), 2);
+ }
+ const words = normalizeForCompare(text).split(' ');
+ for (const word of words) {
+ if (word.length < 4 || word.length > 30) continue;
+ if (STOPWORDS.has(word)) continue;
+ if (/^\d+$/.test(word)) continue;
+ bump(word, 1);
+ }
+ }
+ return [...counts.entries()]
+ .filter(([, count]) => count > 1)
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .slice(0, limit)
+ .map(([topic, count]) => ({ topic, count }));
+}
+
+// ── Distiller output parsing ─────────────────────────────────────────────────
+
+/**
+ * Read a fact list out of whatever the model returned. Models answer this
+ * prompt with a bare JSON array, a fenced one, or a numbered list depending on
+ * which provider in the chain served it, so all three parse. An unparseable
+ * answer yields an empty list and the caller falls back to derived facts
+ * rather than storing nothing.
+ *
+ * @returns {string[]}
+ */
+export function parseFactList(raw) {
+ const text = String(raw ?? '').trim();
+ if (!text) return [];
+
+ const unfenced = text
+ .replace(/^```(?:json)?\s*/i, '')
+ .replace(/\s*```$/i, '')
+ .trim();
+
+ const jsonCandidates = [unfenced];
+ const arrayMatch = unfenced.match(/\[[\s\S]*\]/);
+ if (arrayMatch) jsonCandidates.push(arrayMatch[0]);
+
+ for (const candidate of jsonCandidates) {
+ try {
+ const parsed = JSON.parse(candidate);
+ if (Array.isArray(parsed)) {
+ const strings = parsed.filter((f) => typeof f === 'string');
+ if (strings.length) return strings;
+ }
+ } catch {
+ // Fall through to the line reader below.
+ }
+ }
+
+ return unfenced
+ .split('\n')
+ .map((line) => line.replace(/^\s*(?:[-*•]|\d+[.)])\s*/, '').trim())
+ .filter((line) => line.length > 0 && !/^[[\]{}]+$/.test(line));
+}
+
+/**
+ * Enforce the "stores" and "never" halves of the disclosure on the distiller's
+ * output: strip links and wrapping punctuation, cap length and count, drop
+ * duplicates, and drop any fact that is really just a copy of a post.
+ *
+ * @param {string[]} facts raw strings from the distiller
+ * @param {{sourcePosts?: Array<{text: string}>}} opts
+ */
+export function sanitizeFacts(facts, { sourcePosts = [] } = {}) {
+ const sources = (Array.isArray(sourcePosts) ? sourcePosts : [])
+ .map((p) => normalizeForCompare(typeof p === 'string' ? p : p?.text))
+ .filter((s) => s.length >= X_SEED_LIMITS.minPostChars);
+
+ const seen = new Set();
+ const out = [];
+ for (const candidate of Array.isArray(facts) ? facts : []) {
+ if (typeof candidate !== 'string') continue;
+ let fact = stripLinks(candidate)
+ .replace(/^["'`\s]+|["'`\s]+$/g, '')
+ .replace(/^[-*•]\s*/, '')
+ .trim();
+ if (fact.length < 8) continue;
+ if (fact.length > X_SEED_LIMITS.maxFactChars) {
+ fact = `${fact.slice(0, X_SEED_LIMITS.maxFactChars - 1).trimEnd()}…`;
+ }
+ const key = normalizeForCompare(fact);
+ if (!key || seen.has(key)) continue;
+ if (isVerbatimPost(key, sources)) continue;
+ seen.add(key);
+ out.push(fact);
+ if (out.length >= X_SEED_LIMITS.maxFacts) break;
+ }
+ return out;
+}
+
+/**
+ * True when a candidate fact is the text of a post rather than a statement
+ * about the author. Containment in either direction catches both the model
+ * echoing a post back and the model quoting one with a short preamble.
+ */
+function isVerbatimPost(normalizedFact, normalizedSources) {
+ if (normalizedFact.length < X_SEED_LIMITS.minPostChars) return false;
+ return normalizedSources.some(
+ (source) => source.includes(normalizedFact) || normalizedFact.includes(source),
+ );
+}
+
+/**
+ * Facts derived without a model, from the profile and the topic histogram.
+ * These are what a seed stores when the LLM chain is unavailable or answers
+ * with something unparseable: a smaller, blander seed beats a silent zero.
+ */
+export function deriveFallbackFacts(profile, posts, topics) {
+ const p = profile || {};
+ const handle = p.username ? `@${p.username}` : 'this account';
+ const facts = [];
+ if (p.name && p.username) facts.push(`${p.name} posts on X as ${handle}.`);
+ if (p.description) facts.push(`${handle} describes themselves as: ${p.description}`);
+ const named = (topics || []).slice(0, 6).map((t) => t.topic);
+ if (named.length >= 2) {
+ facts.push(`${handle} posts most often about ${named.slice(0, -1).join(', ')} and ${named.at(-1)}.`);
+ } else if (named.length === 1) {
+ facts.push(`${handle} posts most often about ${named[0]}.`);
+ }
+ const count = Array.isArray(posts) ? posts.length : 0;
+ if (count > 0) {
+ const avg = Math.round(posts.reduce((n, t) => n + (t.text?.length || 0), 0) / count);
+ facts.push(
+ `${handle} writes ${avg < 90 ? 'short, punchy' : avg < 180 ? 'medium-length' : 'long-form'} posts, averaging about ${avg} characters.`,
+ );
+ }
+ return facts;
+}
+
+// ── Write side: the memory rows ──────────────────────────────────────────────
+
+/**
+ * Turn the accepted facts into the exact rows written to `agent_memories`.
+ *
+ * Salience decays down the ranked list, and the top few are promoted to the
+ * `working` tier so they are always in the agent's context rather than only
+ * surfacing when a message happens to match them. That promotion is what makes
+ * a seed observable in the very next reply.
+ *
+ * @param {object} opts
+ * @param {string[]} opts.facts sanitized facts, most important first
+ * @param {object} opts.profile output of selectSeedProfile
+ * @param {Array<{topic:string}>} [opts.topics] provenance tags
+ * @param {string} [opts.source] 'model' or 'derived'
+ * @param {string} [opts.seededAt] ISO timestamp recorded in provenance
+ * @returns {Array<{type:string, content:string, tags:string[], context:object, salience:number, tier:string}>}
+ */
+export function buildSeedMemories({
+ facts,
+ profile,
+ topics = [],
+ source = 'model',
+ seededAt = null,
+ scopeVersion = X_SEED_SCOPE_VERSION,
+}) {
+ const list = Array.isArray(facts) ? facts.slice(0, X_SEED_LIMITS.maxFacts) : [];
+ const username = profile?.username || '';
+ const topicTags = topics
+ .slice(0, 3)
+ .map((t) => t.topic)
+ .filter((t) => /^[a-z0-9_]{3,30}$/.test(t));
+
+ return list.map((content, index) => ({
+ type: 'reference',
+ content,
+ tags: ['x', X_SEED_TAG, ...topicTags],
+ context: {
+ source: 'x_seed',
+ username,
+ rank: index + 1,
+ distilled_by: source,
+ scope_version: scopeVersion,
+ ...(seededAt ? { seeded_at: seededAt } : {}),
+ },
+ salience: Number((0.8 - index * 0.02).toFixed(2)),
+ tier: index < X_SEED_LIMITS.workingTierFacts ? 'working' : 'recall',
+ }));
+}
+
+/**
+ * The whole transform in one call: raw X payloads in, memory rows out. The
+ * handler supplies `distil` (the LLM call) so this stays pure and testable;
+ * a distiller that throws or returns nothing usable degrades to derived facts
+ * instead of failing the seed.
+ *
+ * @param {object} opts
+ * @param {object} opts.rawProfile GET /2/users/me payload `data`
+ * @param {Array<object>} opts.rawPosts GET /2/users/:id/tweets payload `data`
+ * @param {(profile: object, posts: object[]) => Promise<string>} opts.distil
+ * @param {string} [opts.seededAt]
+ */
+export async function seedFromX({ rawProfile, rawPosts, distil, seededAt = null }) {
+ const profile = selectSeedProfile(rawProfile);
+ const posts = selectSeedPosts(rawPosts);
+ const topics = deriveTopics(posts);
+
+ let facts = [];
+ let source = 'model';
+ if (posts.length || profile.description) {
+ try {
+ facts = sanitizeFacts(parseFactList(await distil(profile, posts)), {
+ sourcePosts: posts,
+ });
+ } catch (err) {
+ console.warn('[x-seed] distillation failed, falling back to derived facts', err?.message);
+ facts = [];
+ }
+ }
+ if (!facts.length) {
+ source = 'derived';
+ facts = sanitizeFacts(deriveFallbackFacts(profile, posts, topics), { sourcePosts: posts });
+ }
+
+ return {
+ profile,
+ postsRead: posts.length,
+ topics,
+ source,
+ memories: buildSeedMemories({ facts, profile, topics, source, seededAt }),
+ };
+}
diff --git a/api/_lib/x-seed-consent.js b/api/_lib/x-seed-consent.js
new file mode 100644
index 000000000..8bc483970
--- /dev/null
+++ b/api/_lib/x-seed-consent.js
@@ -0,0 +1,87 @@
+/**
+ * Revocation for X memory seeding.
+ * --------------------------------
+ * Three surfaces can end an X seeding grant, and all three have to mean the
+ * same thing: the grant stops, and every memory it produced is gone.
+ *
+ * - the owner revokes on one agent (DELETE /api/agents/:id/memory/seed/x)
+ * - the owner disconnects X (DELETE /api/x/status)
+ * - the owner reconnects a DIFFERENT X account (the OAuth callback)
+ *
+ * The delete matches on the `x_seed` tag rather than on the consent id, so
+ * memories written before consents were recorded are purged too. Nothing
+ * distilled from an X account outlives the permission to use it.
+ */
+
+import { sql } from './db.js';
+import { X_SEED_TAG } from './x-memory-seed.js';
+
+/**
+ * Delete every seeded memory on one agent.
+ * @returns {Promise<number>} rows deleted
+ */
+export async function deleteSeededMemories(agentId) {
+ const rows = await sql`
+ DELETE FROM agent_memories
+ WHERE agent_id = ${agentId} AND tags && ARRAY[${X_SEED_TAG}]::text[]
+ RETURNING id
+ `;
+ await sql`
+ UPDATE agent_identities
+ SET x_username = NULL, x_seeded_at = NULL
+ WHERE id = ${agentId}
+ `;
+ return rows.length;
+}
+
+/**
+ * Revoke one agent's live grant (if any) and delete what it produced.
+ * Idempotent: an agent with no grant still gets its seeded rows purged.
+ *
+ * @returns {Promise<{deleted: number, consents: number}>}
+ */
+export async function revokeAgentSeedConsent(agentId, reason) {
+ const consents = await sql`
+ UPDATE x_memory_consents
+ SET revoked_at = now(), revoked_reason = ${reason}
+ WHERE agent_id = ${agentId} AND revoked_at IS NULL
+ RETURNING id
+ `;
+ return { consents: consents.length, deleted: await deleteSeededMemories(agentId) };
+}
+
+/**
+ * Revoke every live grant a user holds and delete the seeded memories across
+ * all of their agents. Used when the X connection itself goes away, so a
+ * disconnect can never leave distilled posts behind on an agent the owner
+ * forgot about.
+ *
+ * @returns {Promise<{deleted: number, consents: number, agents: number}>}
+ */
+export async function revokeAllSeedConsentsForUser(userId, reason) {
+ const consents = await sql`
+ UPDATE x_memory_consents
+ SET revoked_at = now(), revoked_reason = ${reason}
+ WHERE user_id = ${userId} AND revoked_at IS NULL
+ RETURNING agent_id
+ `;
+
+ const deleted = await sql`
+ DELETE FROM agent_memories
+ WHERE tags && ARRAY[${X_SEED_TAG}]::text[]
+ AND agent_id IN (SELECT id FROM agent_identities WHERE user_id = ${userId})
+ RETURNING agent_id
+ `;
+
+ await sql`
+ UPDATE agent_identities
+ SET x_username = NULL, x_seeded_at = NULL
+ WHERE user_id = ${userId} AND (x_username IS NOT NULL OR x_seeded_at IS NOT NULL)
+ `;
+
+ return {
+ consents: consents.length,
+ deleted: deleted.length,
+ agents: new Set(deleted.map((r) => r.agent_id)).size,
+ };
+}
diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.js
index a35a8e4f7..f67fe7117 100644
--- a/api/agents/[id]/memory-seed-x.js
+++ b/api/agents/[id]/memory-seed-x.js
@@ -1,16 +1,36 @@
-// POST /api/agents/:id/memory/seed/x — fetch X tweets, distil to facts, seed agent memory.
-// GET /api/agents/:id/memory/seed/x — return connection status and last seed info.
+// Consent-gated X memory seeding.
//
-// Auth: session user must own the agent AND have an active 'x' social_connection.
-// Rate limit: 1 seed per agent per 6 hours.
+// GET /api/agents/:id/memory/seed/x — connection state, the consent grant,
+// and the disclosure the owner must
+// agree to before anything is read.
+// POST /api/agents/:id/memory/seed/x — grant consent (first call) and seed.
+// DELETE /api/agents/:id/memory/seed/x — revoke consent and delete every
+// memory the grant produced.
+//
+// Auth: session user must own the agent AND have a live 'x' social_connection.
+// A connection is permission to read X on the user's behalf; it is NOT
+// permission to write their posts into an agent's long-term memory. That second
+// decision is this endpoint's consent grant: explicit, versioned against the
+// disclosure text (api/_lib/x-memory-seed.js), and revocable with deletion.
+//
+// Rate limit: 1 seed per agent per 6 hours, consumed only once the request is
+// authorized and consented, so a rejected call never burns the owner's window.
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { limits } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
import { llmComplete } from '../../_lib/llm.js';
import { isUuid } from '../../_lib/validate.js';
+import {
+ X_SEED_DISCLOSURE,
+ X_SEED_LIMITS,
+ X_SEED_SCOPE_VERSION,
+ seedFromX,
+} from '../../_lib/x-memory-seed.js';
+import { revokeAgentSeedConsent } from '../../_lib/x-seed-consent.js';
import { decryptToken, encryptToken } from '../../auth/x/[action].js';
// ── Token refresh ─────────────────────────────────────────────────────────────
@@ -61,155 +81,278 @@ async function getAccessToken(conn) {
return decryptToken(conn.access_token);
}
-// ── Distil tweets → facts via Claude ─────────────────────────────────────────
+// ── Distillation ─────────────────────────────────────────────────────────────
-async function distilFacts(profile, tweets) {
- const tweetLines = tweets.map((t) => t.text).join('\n');
-
- const { text: raw } = await llmComplete({
+// Only the fields selectSeedProfile / selectSeedPosts kept ever reach the model.
+async function distilFacts(profile, posts, userId) {
+ const { text } = await llmComplete({
maxTokens: 1024,
+ track: { userId, feature: 'x_memory_seed' },
system:
- 'You distill tweets into concise memory facts for an AI agent. ' +
- 'Focus on: recurring topics, strong opinions, projects, communication style, humor. ' +
- 'Output ONLY a JSON array of up to 15 single-sentence strings, no other text.',
+ 'You distill an author\'s public posts into concise memory facts for an AI agent that ' +
+ 'speaks on their behalf. Focus on recurring topics, strong opinions, ongoing projects, ' +
+ 'and communication style. Write statements ABOUT the author, never quote or paraphrase a ' +
+ 'single post. ' +
+ `Output ONLY a JSON array of up to ${X_SEED_LIMITS.maxFacts} single-sentence strings.`,
user:
- `Profile: @${profile.username} | ${profile.description || ''} | ` +
- `${profile.public_metrics?.followers_count ?? 0} followers\n\n` +
- `Recent tweets (newest first):\n${tweetLines}`,
+ `Profile: @${profile.username} | ${profile.name} | ${profile.description} | ` +
+ `${profile.followers} followers\n\n` +
+ `Recent original posts (newest first):\n${posts.map((p) => p.text).join('\n')}`,
});
-
- try {
- const stripped = raw
- .replace(/^```(?:json)?\s*/i, '')
- .replace(/\s*```$/i, '')
- .trim();
- const facts = JSON.parse(stripped);
- return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
- } catch {
- return [];
- }
+ return text;
}
-// ── GET — status ──────────────────────────────────────────────────────────────
-
-async function handleGet(req, res, agentId) {
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+// ── Shared lookups ───────────────────────────────────────────────────────────
+async function loadAgent(agentId, userId) {
const [agent] = await sql`
SELECT id, user_id, x_username, x_seeded_at FROM agent_identities
WHERE id = ${agentId} AND deleted_at IS NULL
`;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (!agent) return { error: ['not_found', 404, 'agent not found'] };
+ if (agent.user_id !== userId) return { error: ['forbidden', 403, 'not your agent'] };
+ return { agent };
+}
+async function loadConnection(userId) {
const [conn] = await sql`
- SELECT id, username FROM social_connections
- WHERE user_id = ${user.id} AND provider = 'x'
+ SELECT id, provider_uid, username, scopes, access_token, refresh_token, expires_at
+ FROM social_connections
+ WHERE user_id = ${userId} AND provider = 'x'
AND (disconnected_at IS NULL OR disconnected_at > now())
LIMIT 1
`;
+ return conn ?? null;
+}
+
+async function loadConsent(agentId) {
+ const [consent] = await sql`
+ SELECT id, x_user_id, username, scope_version, granted_scopes, granted_at,
+ last_seeded_at, memories_seeded, posts_read
+ FROM x_memory_consents
+ WHERE agent_id = ${agentId} AND revoked_at IS NULL
+ LIMIT 1
+ `;
+ return consent ?? null;
+}
+// A grant stops authorizing new seeds when the disclosure text has moved on, or
+// when the live connection now points at a different X account than the one the
+// owner consented to. Both cases send the owner back to the consent screen.
+function consentState(consent, conn) {
+ if (!consent) return { granted: false, reason: 'none' };
+ if (consent.scope_version !== X_SEED_SCOPE_VERSION) {
+ return { granted: false, reason: 'scope_version_changed', consent };
+ }
+ if (conn && conn.provider_uid && consent.x_user_id !== conn.provider_uid) {
+ return { granted: false, reason: 'account_changed', consent };
+ }
+ return { granted: true, reason: 'active', consent };
+}
+
+function consentPayload(state) {
+ const c = state.consent;
+ return {
+ granted: state.granted,
+ reason: state.reason,
+ scope_version: c?.scope_version ?? null,
+ granted_at: c?.granted_at ?? null,
+ granted_scopes: c?.granted_scopes ?? null,
+ username: c?.username ?? null,
+ last_seeded_at: c?.last_seeded_at ?? null,
+ memories_seeded: c?.memories_seeded ?? 0,
+ posts_read: c?.posts_read ?? 0,
+ };
+}
+
+async function countSeededMemories(agentId) {
const [{ count }] = await sql`
SELECT count(*)::int AS count FROM agent_memories
- WHERE agent_id = ${agentId} AND tags && ARRAY['x']::text[]
+ WHERE agent_id = ${agentId} AND tags && ARRAY['x_seed']::text[]
`;
+ return count;
+}
+
+// ── GET — status + disclosure ────────────────────────────────────────────────
+
+async function handleGet(req, res, agentId) {
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const { agent, error: agentErr } = await loadAgent(agentId, user.id);
+ if (agentErr) return error(res, agentErr[1], agentErr[0], agentErr[2]);
+
+ const conn = await loadConnection(user.id);
+ const state = consentState(await loadConsent(agentId), conn);
return json(res, 200, {
connected: !!conn,
+ configured: !!(env.X_OAUTH_CLIENT_ID && env.X_OAUTH_CLIENT_SECRET),
username: conn?.username ?? agent.x_username ?? null,
+ connection_scopes: conn?.scopes ?? null,
seeded_at: agent.x_seeded_at ?? null,
- fact_count: count,
+ fact_count: await countSeededMemories(agentId),
+ scope_version: X_SEED_SCOPE_VERSION,
+ disclosure: X_SEED_DISCLOSURE,
+ consent: consentPayload(state),
});
}
-// ── POST — seed ───────────────────────────────────────────────────────────────
+// ── POST — grant consent, then seed ──────────────────────────────────────────
async function handlePost(req, res, agentId) {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
- const [agent] = await sql`
- SELECT id, user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ const { error: agentErr } = await loadAgent(agentId, user.id);
+ if (agentErr) return error(res, agentErr[1], agentErr[0], agentErr[2]);
- // Consume the per-agent seed budget only AFTER ownership is proven —
- // otherwise any signed-in user could burn another agent's 6-hour window.
+ const conn = await loadConnection(user.id);
+ if (!conn) return error(res, 400, 'not_connected', 'connect your X account first');
+
+ const body = await readJson(req).catch(() => ({}));
+ const existing = await loadConsent(agentId);
+ let state = consentState(existing, conn);
+
+ // No live grant: this request must carry the owner's acceptance of the
+ // current disclosure. Nothing is read from X before that check passes.
+ if (!state.granted) {
+ const accepted = body?.consent?.accepted === true;
+ const version = body?.consent?.scope_version;
+ if (!accepted || version !== X_SEED_SCOPE_VERSION) {
+ return error(res, 403, 'consent_required', 'explicit consent is required before seeding', {
+ scope_version: X_SEED_SCOPE_VERSION,
+ disclosure: X_SEED_DISCLOSURE,
+ consent: consentPayload(state),
+ });
+ }
+ // A stale grant (disclosure moved, or the connection now points at a
+ // different X account) is retired, deleting its memories, before the new
+ // one is recorded. Two live grants for one agent can never coexist.
+ if (existing) await revokeAgentSeedConsent(agentId, 're_consented');
+ const [row] = await sql`
+ INSERT INTO x_memory_consents
+ (user_id, agent_id, x_user_id, username, scope_version, disclosure, granted_scopes)
+ VALUES (
+ ${user.id}, ${agentId}, ${conn.provider_uid}, ${conn.username},
+ ${X_SEED_SCOPE_VERSION}, ${JSON.stringify(X_SEED_DISCLOSURE)}::jsonb, ${conn.scopes ?? null}
+ )
+ RETURNING id, x_user_id, username, scope_version, granted_scopes, granted_at,
+ last_seeded_at, memories_seeded, posts_read
+ `;
+ state = consentState(row, conn);
+ }
+
+ const consent = state.consent;
+
+ // Budget is consumed only now: authorized, connected, and consented.
const rl = await limits.xSeed(agentId);
if (!rl.success) return rateLimited(res, rl, 'agent can only be re-seeded every 6 hours');
- const [conn] = await sql`
- SELECT id, username, access_token, refresh_token, expires_at FROM social_connections
- WHERE user_id = ${user.id} AND provider = 'x'
- AND (disconnected_at IS NULL OR disconnected_at > now())
- LIMIT 1
- `;
- if (!conn) return error(res, 400, 'not_connected', 'connect your X account first');
-
const accessToken = await getAccessToken(conn);
- // Fetch profile
const profileRes = await fetch(
'https://api.twitter.com/2/users/me?user.fields=name,username,description,public_metrics',
{ headers: { authorization: `Bearer ${accessToken}` } },
);
- if (!profileRes.ok) {
- throw Object.assign(new Error('X profile fetch failed'), { status: 502 });
+ if (!profileRes.ok) throw Object.assign(new Error('X profile fetch failed'), { status: 502 });
+ const { data: rawProfile } = await profileRes.json();
+ if (!rawProfile?.id) throw Object.assign(new Error('X profile unreadable'), { status: 502 });
+
+ // The account that consented must be the account being read.
+ if (rawProfile.id !== consent.x_user_id) {
+ return error(res, 409, 'account_mismatch', 'consent was granted for a different X account', {
+ consent: consentPayload(consentState(consent, conn)),
+ });
}
- const { data: profile } = await profileRes.json();
- // Fetch up to 100 recent original tweets
- const tweetsRes = await fetch(
- `https://api.twitter.com/2/users/${profile.id}/tweets?max_results=100&exclude=retweets,replies&tweet.fields=text,created_at`,
+ const postsRes = await fetch(
+ `https://api.twitter.com/2/users/${rawProfile.id}/tweets?max_results=${X_SEED_LIMITS.maxPosts}` +
+ '&exclude=retweets,replies&tweet.fields=text,created_at',
{ headers: { authorization: `Bearer ${accessToken}` } },
);
- if (!tweetsRes.ok) {
- throw Object.assign(new Error('X tweets fetch failed'), { status: 502 });
- }
- const tweetsJson = await tweetsRes.json();
- const tweets = tweetsJson.data ?? [];
+ if (!postsRes.ok) throw Object.assign(new Error('X posts fetch failed'), { status: 502 });
+ const postsJson = await postsRes.json();
- const facts = await distilFacts(profile, tweets);
+ const seededAt = new Date().toISOString();
+ const result = await seedFromX({
+ rawProfile,
+ rawPosts: postsJson.data ?? [],
+ distil: (profile, posts) => distilFacts(profile, posts, user.id),
+ seededAt,
+ });
- // Delete old x-tagged memories for this agent, then insert fresh ones
+ // Re-seeding replaces: the previous batch goes before the new one lands, so
+ // the agent never carries two generations of facts about the same account.
await sql`
DELETE FROM agent_memories
- WHERE agent_id = ${agentId} AND tags && ARRAY['x']::text[]
+ WHERE agent_id = ${agentId} AND tags && ARRAY['x_seed']::text[]
`;
- if (facts.length > 0) {
- const rows = facts.map((fact) => ({
- agent_id: agentId,
- type: 'reference',
- content: fact,
- tags: ['x', 'x_seed'],
- context: JSON.stringify({ source: 'x_seed', username: profile.username }),
- salience: 0.7,
- }));
- for (const row of rows) {
- await sql`
- INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)
- VALUES (${row.agent_id}, ${row.type}, ${row.content}, ${row.tags}, ${row.context}::jsonb, ${row.salience})
- `;
- }
+ for (const mem of result.memories) {
+ await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, tier)
+ VALUES (
+ ${agentId}, ${mem.type}, ${mem.content}, ${mem.tags},
+ ${JSON.stringify({ ...mem.context, consent_id: consent.id })}::jsonb,
+ ${mem.salience}, ${mem.tier}
+ )
+ `;
}
- // Update agent_identities with x_username and x_seeded_at
await sql`
UPDATE agent_identities
- SET x_username = ${profile.username}, x_seeded_at = now()
+ SET x_username = ${result.profile.username}, x_seeded_at = ${seededAt}
WHERE id = ${agentId}
`;
+ await sql`
+ UPDATE x_memory_consents
+ SET last_seeded_at = ${seededAt},
+ memories_seeded = ${result.memories.length},
+ posts_read = ${result.postsRead}
+ WHERE id = ${consent.id}
+ `;
+
+ return json(res, 200, {
+ username: result.profile.username,
+ seeded: result.memories.length,
+ posts_read: result.postsRead,
+ distilled_by: result.source,
+ topics: result.topics.map((t) => t.topic),
+ facts: result.memories.map((m) => m.content),
+ in_context: result.memories.filter((m) => m.tier === 'working').length,
+ consent: consentPayload(consentState({ ...consent, last_seeded_at: seededAt }, conn)),
+ });
+}
+
+// ── DELETE — revoke consent and delete what it produced ──────────────────────
- return json(res, 200, { username: profile.username, seeded: facts.length, facts });
+async function handleDelete(req, res, agentId) {
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const { error: agentErr } = await loadAgent(agentId, user.id);
+ if (agentErr) return error(res, agentErr[1], agentErr[0], agentErr[2]);
+
+ // Idempotent, and it purges seeded rows even when no grant row survives:
+ // memories written before consents were recorded still have to go.
+ const { deleted, consents } = await revokeAgentSeedConsent(agentId, 'owner_revoked');
+
+ return json(res, 200, {
+ revoked: true,
+ deleted,
+ consents_revoked: consents,
+ remaining: await countSeededMemories(agentId),
+ consent: consentPayload({ granted: false, reason: 'revoked' }),
+ });
}
// ── dispatch ──────────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
const agentId = req.query?.id;
if (!agentId) return error(res, 400, 'validation_error', 'agent id required');
@@ -220,5 +363,6 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') return handleGet(req, res, agentId);
if (req.method === 'POST') return handlePost(req, res, agentId);
- return method(req, res, ['GET', 'POST']);
+ if (req.method === 'DELETE') return handleDelete(req, res, agentId);
+ return method(req, res, ['GET', 'POST', 'DELETE']);
});
diff --git a/api/agents/_id/memory-seed-farcaster.js b/api/agents/_id/memory-seed-farcaster.js
deleted file mode 100644
index 271b98201..000000000
--- a/api/agents/_id/memory-seed-farcaster.js
+++ /dev/null
@@ -1,211 +0,0 @@
-// GET /api/agents/:id/memory/seed/farcaster — current link status
-// POST /api/agents/:id/memory/seed/farcaster — link Farcaster account & seed memories
-
-import { z } from 'zod';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { env } from '../../_lib/env.js';
-import { llmComplete } from '../../_lib/llm.js';
-
-const bodySchema = z
- .object({
- fid: z.number().int().positive().optional(),
- fname: z.string().trim().min(1).max(64).optional(),
- })
- .refine((d) => d.fid != null || d.fname != null, { message: 'fid or fname required' });
-
-const NEYNAR_BASE = 'https://api.neynar.com/v2/farcaster';
-const SEED_COOLDOWN_MS = 6 * 60 * 60 * 1000;
-
-const NEYNAR_TIMEOUT_MS = 15_000;
-
-async function neynarGet(path, apiKey) {
- const resp = await fetch(`${NEYNAR_BASE}${path}`, {
- headers: { api_key: apiKey },
- signal: AbortSignal.timeout(NEYNAR_TIMEOUT_MS),
- });
- if (!resp.ok) {
- const err = new Error(`Neynar ${resp.status}`);
- err.httpStatus = resp.status;
- throw err;
- }
- return resp.json();
-}
-
-async function distillFacts(profile, casts) {
- const castTexts = casts
- .slice(0, 50)
- .map((c) => c.text || '')
- .filter(Boolean)
- .join('\n');
-
- const displayName = profile.display_name || profile.username || '';
- const bio = profile.profile?.bio?.text || '';
- const followers = profile.follower_count ?? 0;
- const userLine = `Display name: ${displayName}, Bio: ${bio || '(none)'}, Followers: ${followers}`;
-
- const { text: raw } = await llmComplete({
- maxTokens: 1024,
- system:
- 'You distill Farcaster casts into concise memory facts for an AI agent. ' +
- 'Focus on: recurring topics, opinions, projects, communication style, community ties. ' +
- 'Output ONLY a JSON array of up to 15 single-sentence strings, no other text.',
- user: `Profile: ${userLine}\n\nRecent casts (newest first):\n${castTexts}`,
- });
-
- try {
- const stripped = raw
- .replace(/^```(?:json)?\s*/i, '')
- .replace(/\s*```$/i, '')
- .trim();
- const facts = JSON.parse(stripped);
- return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
- } catch {
- return [];
- }
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'POST'])) return;
-
- if (!env.NEYNAR_API_KEY)
- return error(res, 501, 'not_configured', 'Farcaster integration not configured');
-
- const url = new URL(req.url, 'http://x');
- const parts = url.pathname.split('/').filter(Boolean);
- const agentId = parts[2];
-
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- const userId = session?.id ?? bearer?.userId;
- if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
-
- const [agent] = await sql`
- SELECT id, farcaster_fid, farcaster_fname, farcaster_seeded_at
- FROM agent_identities
- WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
-
- if (req.method === 'GET') {
- const [countRow] = await sql`
- SELECT COUNT(*)::int AS fact_count
- FROM agent_memories
- WHERE agent_id = ${agentId}
- AND context->>'source' = 'farcaster_seed'
- AND (expires_at IS NULL OR expires_at > now())
- `;
- return json(res, 200, {
- fid: agent.farcaster_fid ?? null,
- fname: agent.farcaster_fname ?? null,
- seeded_at: agent.farcaster_seeded_at ?? null,
- fact_count: countRow?.fact_count ?? 0,
- });
- }
-
- // POST
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl);
-
- if (agent.farcaster_seeded_at) {
- const elapsed = Date.now() - new Date(agent.farcaster_seeded_at).getTime();
- if (elapsed < SEED_COOLDOWN_MS) {
- // Plain 429: this is a per-agent cooldown, not the IP limiter above —
- // reusing rateLimited(res, rl) here would emit RateLimit-* headers from
- // a limiter result that actually succeeded, misleading clients.
- const retryAfter = Math.max(1, Math.ceil((SEED_COOLDOWN_MS - elapsed) / 1000));
- res.setHeader('retry-after', String(retryAfter));
- return error(
- res,
- 429,
- 'cooldown_active',
- 'farcaster seed cooldown: try again in 6 hours',
- {
- retry_after: retryAfter,
- },
- );
- }
- }
-
- const body = parse(bodySchema, await readJson(req));
-
- let fid = body.fid ?? null;
- let fname = body.fname ?? null;
-
- // Resolve fname → fid
- if (!fid && fname) {
- let userData;
- try {
- userData = await neynarGet(
- `/user/by_username?username=${encodeURIComponent(fname)}`,
- env.NEYNAR_API_KEY,
- );
- } catch (e) {
- if (e.httpStatus === 404)
- return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');
- throw e;
- }
- fid = userData?.user?.fid;
- if (!fid) return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');
- }
-
- // Fetch casts and profile in parallel. A Neynar outage is an upstream failure,
- // not an internal one: neynarGet tags its error with `httpStatus`, which wrap()
- // does not read (it reads `status`), so an uncaught throw here surfaced as a
- // bare 500 plus an ops alert for somebody else's downtime.
- let castsData;
- let profileData;
- try {
- [castsData, profileData] = await Promise.all([
- neynarGet(`/feed/user/casts?fid=${fid}&limit=50&include_replies=false`, env.NEYNAR_API_KEY),
- neynarGet(`/user?fid=${fid}`, env.NEYNAR_API_KEY),
- ]);
- } catch (e) {
- if (e.httpStatus === 404)
- return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');
- console.error('[memory-seed-farcaster] Neynar fetch failed', e?.message);
- return error(res, 502, 'upstream_error', 'Farcaster data is unavailable right now');
- }
-
- const casts = castsData?.casts ?? [];
- const profile = profileData?.users?.[0] ?? profileData?.user ?? {};
-
- if (!fname && profile.username) fname = profile.username;
-
- const facts = casts.length > 0 ? await distillFacts(profile, casts) : [];
-
- // Delete existing farcaster_seed memories (idempotent re-seed)
- await sql`
- DELETE FROM agent_memories
- WHERE agent_id = ${agentId} AND context->>'source' = 'farcaster_seed'
- `;
-
- // Insert new memories
- for (const fact of facts) {
- await sql`
- INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience)
- VALUES (
- gen_random_uuid(),
- ${agentId},
- 'user',
- ${fact},
- ARRAY['farcaster'],
- ${JSON.stringify({ source: 'farcaster_seed', fid })}::jsonb,
- 0.7
- )
- `;
- }
-
- // Update agent with validated farcaster identity
- await sql`
- UPDATE agent_identities
- SET farcaster_fid = ${fid}, farcaster_fname = ${fname}, farcaster_seeded_at = now()
- WHERE id = ${agentId}
- `;
-
- return json(res, 200, { fid, fname, seeded: facts.length, facts });
-});
diff --git a/api/auth/x/[action].js b/api/auth/x/[action].js
index 76a913d8c..876893608 100644
--- a/api/auth/x/[action].js
+++ b/api/auth/x/[action].js
@@ -19,6 +19,7 @@ import {
import { cors, method, wrap, error, redirect, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
+import { revokeAllSeedConsentsForUser } from '../../_lib/x-seed-consent.js';
// ── Signed-cookie PKCE state ─────────────────────────────────────────────────
@@ -209,6 +210,11 @@ async function handleCallback(req, res) {
const tokens = await tokenRes.json().catch(() => ({}));
const { access_token, refresh_token, expires_in } = tokens;
+ // X echoes the scopes it actually granted, which can be narrower than what we
+ // asked for if the user unticked a permission. Record them: social_connections
+ // .scopes is NOT NULL, and the memory-seeding consent screen shows the owner
+ // what this connection is allowed to do.
+ const grantedScopes = typeof tokens.scope === 'string' ? tokens.scope : '';
if (!access_token) {
console.error('[x-oauth] token response carried no access_token');
return redirect(res, errorRedirect);
@@ -237,12 +243,24 @@ async function handleCallback(req, res) {
const encAccess = encryptToken(access_token);
const encRefresh = refresh_token ? encryptToken(refresh_token) : null;
+ // Reconnecting a DIFFERENT X account retires every memory-seeding grant made
+ // for the previous one and deletes the memories it produced. Consent was
+ // given for that account's posts, and it does not transfer to this one.
+ const [prior] = await sql`
+ SELECT provider_uid FROM social_connections
+ WHERE user_id = ${userId} AND provider = 'x'
+ LIMIT 1
+ `;
+ if (prior?.provider_uid && prior.provider_uid !== profile.id) {
+ await revokeAllSeedConsentsForUser(userId, 'x_account_changed');
+ }
+
// Upsert by (user_id, provider) — uses the existing unique constraint
await sql`
INSERT INTO social_connections
- (user_id, provider, provider_uid, username, access_token, refresh_token, expires_at, raw_data)
+ (user_id, provider, provider_uid, username, access_token, refresh_token, expires_at, raw_data, scopes)
VALUES
- (${userId}, 'x', ${profile.id}, ${profile.username}, ${encAccess}, ${encRefresh}, ${expiresAt}, ${JSON.stringify(profile)})
+ (${userId}, 'x', ${profile.id}, ${profile.username}, ${encAccess}, ${encRefresh}, ${expiresAt}, ${JSON.stringify(profile)}, ${grantedScopes})
ON CONFLICT (user_id, provider) DO UPDATE SET
provider_uid = EXCLUDED.provider_uid,
username = EXCLUDED.username,
@@ -250,6 +268,7 @@ async function handleCallback(req, res) {
refresh_token = EXCLUDED.refresh_token,
expires_at = EXCLUDED.expires_at,
raw_data = EXCLUDED.raw_data,
+ scopes = EXCLUDED.scopes,
disconnected_at = NULL,
updated_at = now()
`;