Skip to content

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

feat(x): record every mention decision in x_mention_events with race-safe dedupe

nirholasab198d4ff8d9
diff --git a/api/_lib/migrations/20261008170000_x_mention_events.sql b/api/_lib/migrations/20261008170000_x_mention_events.sql
new file mode 100644
index 000000000..399dae25f
--- /dev/null
+++ b/api/_lib/migrations/20261008170000_x_mention_events.sql
@@ -0,0 +1,44 @@
+-- Migration: record every decision the X mention bot makes.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261008170000_x_mention_events.sql
+-- Idempotent.
+--
+-- One row per mention of one of our X accounts (@trythreews, or an agent's own
+-- connected account): what the bot saw, which intent the pure parser gave it,
+-- what the bot decided, and what it replied or, in dry-run mode, would have
+-- replied. The tweet id is the primary key, so a mention read twice by two
+-- overlapping polls is recorded once and handled once. The same rows feed the
+-- per-author rate limits, the dry-run review console, the per-agent settings
+-- preview and the mention-bot health check.
+--
+-- decision is null while a mention is received but not yet decided. Polling
+-- cursors live in app_settings under x_mentions_cursor:<kind>:<ref>, not here.
+
+create table if not exists x_mention_events (
+ tweet_id text primary key,
+ account_kind text not null check (account_kind in ('company', 'agent')),
+ account_ref text not null,
+ author_id text not null,
+ author_username text,
+ conversation_id text,
+ mention_text text,
+ mention_created_at timestamptz,
+ intent text not null check (intent in ('make', 'image3d', 'avatar', 'help', 'launch', 'chat', 'ignore')),
+ args jsonb not null default '{}'::jsonb,
+ decision text check (decision in ('reply', 'skip', 'rate_limited', 'unsafe', 'budget', 'error', 'pending', 'paused')),
+ reason text,
+ reply_text text,
+ reply_media_url text,
+ reply_link text,
+ reply_tweet_id text,
+ dry_run boolean not null default true,
+ creation_id text,
+ error text,
+ created_at timestamptz not null default now(),
+ decided_at timestamptz,
+ replied_at timestamptz,
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists x_mention_events_author_time_idx on x_mention_events (author_id, created_at desc);
+create index if not exists x_mention_events_account_time_idx on x_mention_events (account_kind, account_ref, created_at desc);
+create index if not exists x_mention_events_decision_time_idx on x_mention_events (decision, created_at desc);
diff --git a/api/_lib/x-mention-store.js b/api/_lib/x-mention-store.js
new file mode 100644
index 000000000..cf17040af
--- /dev/null
+++ b/api/_lib/x-mention-store.js
@@ -0,0 +1,193 @@
+// @ts-check
+// The audit trail and dedupe ledger of the X mention bot.
+//
+// Every mention the reader (x-mentions.js) returns is recorded here once,
+// with the intent the pure parser (x-mention-intents.js) gave it, before
+// anything else happens. The tweet id is the primary key, so two overlapping
+// polls that both see a mention race on one INSERT ... ON CONFLICT DO
+// NOTHING and exactly one of them wins the right to handle it. The decision,
+// the reply (or, in dry-run mode, the reply it would have posted) and any
+// error are written back onto the same row. The table is
+// x_mention_events (migration 20261008170000_x_mention_events.sql).
+//
+// Polling cursors are one app_settings row per account,
+// `x_mentions_cursor:<kind>:<ref>` (e.g. x_mentions_cursor:company:trythreews,
+// x_mentions_cursor:agent:<agent id>), and only ever move forward.
+
+import { sql } from './db.js';
+
+export const DECISIONS = Object.freeze(['reply', 'skip', 'rate_limited', 'unsafe', 'budget', 'error', 'pending', 'paused']);
+export const ACCOUNT_KINDS = Object.freeze(['company', 'agent']);
+export const MENTION_TEXT_MAX = 4000;
+const TEXT_MAX = 2000;
+const SNOWFLAKE_RE = /^\d{1,25}$/;
+
+export class MentionStoreError extends Error {
+ /** @param {string} message @param {string} code */
+ constructor(message, code) {
+ super(message);
+ this.name = 'MentionStoreError';
+ this.code = code;
+ }
+}
+
+function capText(v, max = TEXT_MAX) {
+ if (v == null) return null;
+ const s = String(v);
+ return s.length > max ? s.slice(0, max) : s;
+}
+
+function accountOf(account) {
+ const kind = account?.kind;
+ const ref = account?.ref != null ? String(account.ref) : '';
+ if (!ACCOUNT_KINDS.includes(kind) || !ref) throw new MentionStoreError('account must be { kind: company|agent, ref }', 'bad_account');
+ return { kind, ref };
+}
+
+/** The app_settings key holding one account's mention cursor. */
+export function cursorKey(account) {
+ const { kind, ref } = accountOf(account);
+ return `x_mentions_cursor:${kind}:${ref}`;
+}
+
+/** The newest mention id already read for an account, or null before the first poll. */
+export async function getCursor(account) {
+ const [row] = await sql`select value from app_settings where key = ${cursorKey(account)}`;
+ const id = row?.value?.since_id;
+ return id ? String(id) : null;
+}
+
+/**
+ * Move an account's cursor forward to `sinceId`. A cursor never moves back:
+ * when two polls finish out of order, the older one's write is a no-op.
+ * @returns {Promise<boolean>} true when the cursor moved
+ */
+export async function advanceCursor(account, sinceId) {
+ const id = String(sinceId ?? '');
+ if (!SNOWFLAKE_RE.test(id)) throw new MentionStoreError(`not an X post id: ${id.slice(0, 40)}`, 'bad_cursor');
+ const value = JSON.stringify({ since_id: id });
+ const rows = await sql`
+ insert into app_settings (key, value) values (${cursorKey(account)}, ${value}::jsonb)
+ on conflict (key) do update
+ set value = excluded.value, updated_at = now()
+ where coalesce((app_settings.value->>'since_id')::numeric, 0) < (excluded.value->>'since_id')::numeric
+ returning key
+ `;
+ return rows.length > 0;
+}
+
+/**
+ * Record a mention once. The first caller for a tweet id gets
+ * `inserted: true` and owns its handling; every later caller gets false.
+ *
+ * @param {{ mention: any, parsed: { intent: string, args?: object, reason?: string }, dryRun?: boolean, decision?: string|null, reason?: string|null }} input
+ * @returns {Promise<{ inserted: boolean, tweetId: string }>}
+ */
+export async function recordMention({ mention, parsed, dryRun = true, decision = null, reason = null }) {
+ const tweetId = String(mention?.id ?? '');
+ if (!SNOWFLAKE_RE.test(tweetId)) throw new MentionStoreError('mention has no X post id', 'bad_mention');
+ const authorId = mention?.userId || mention?.author?.id;
+ if (!authorId) throw new MentionStoreError('mention has no author id', 'bad_mention');
+ const { kind, ref } = accountOf(mention?.account);
+ if (!parsed?.intent) throw new MentionStoreError('mention was not parsed', 'bad_intent');
+ if (decision != null && !DECISIONS.includes(decision)) throw new MentionStoreError(`unknown decision: ${decision}`, 'bad_decision');
+ const createdAt = mention.createdAt && Number.isFinite(Date.parse(mention.createdAt)) ? mention.createdAt : null;
+ const rows = await sql`
+ insert into x_mention_events (
+ tweet_id, account_kind, account_ref, author_id, author_username, conversation_id,
+ mention_text, mention_created_at, intent, args, decision, reason, dry_run, decided_at
+ ) values (
+ ${tweetId}, ${kind}, ${ref}, ${String(authorId)}, ${mention.username || mention.author?.username || null},
+ ${mention.conversationId || mention.chatId || null}, ${capText(mention.text, MENTION_TEXT_MAX)}, ${createdAt},
+ ${parsed.intent}, ${JSON.stringify(parsed.args || {})}::jsonb, ${decision},
+ ${capText(reason ?? parsed.reason ?? null)}, ${dryRun !== false}, ${decision ? new Date().toISOString() : null}
+ )
+ on conflict (tweet_id) do nothing
+ returning tweet_id
+ `;
+ return { inserted: rows.length > 0, tweetId };
+}
+
+/**
+ * Write a decision and its reply back onto a recorded mention. Fields left
+ * undefined keep their value. A reply_tweet_id, once set, is never replaced:
+ * one mention gets one reply.
+ *
+ * @param {string} tweetId
+ * @param {{ decision?: string, reason?: string, replyText?: string, replyMediaUrl?: string, replyLink?: string, replyTweetId?: string, creationId?: string, error?: string, dryRun?: boolean }} fields
+ * @returns {Promise<object|null>} the updated row, or null when no such mention
+ */
+export async function updateDecision(tweetId, fields = {}) {
+ const id = String(tweetId ?? '');
+ if (!SNOWFLAKE_RE.test(id)) throw new MentionStoreError('not an X post id', 'bad_mention');
+ const d = fields.decision ?? null;
+ if (d != null && !DECISIONS.includes(d)) throw new MentionStoreError(`unknown decision: ${d}`, 'bad_decision');
+ const replyTweetId = fields.replyTweetId != null ? String(fields.replyTweetId) : null;
+ const rows = await sql`
+ update x_mention_events set
+ decision = coalesce(${d}, decision),
+ reason = coalesce(${capText(fields.reason)}, reason),
+ reply_text = coalesce(${capText(fields.replyText)}, reply_text),
+ reply_media_url = coalesce(${capText(fields.replyMediaUrl)}, reply_media_url),
+ reply_link = coalesce(${capText(fields.replyLink)}, reply_link),
+ reply_tweet_id = coalesce(reply_tweet_id, ${replyTweetId}),
+ replied_at = case when reply_tweet_id is null and ${replyTweetId}::text is not null then now() else replied_at end,
+ creation_id = coalesce(${fields.creationId != null ? String(fields.creationId) : null}, creation_id),
+ error = coalesce(${capText(fields.error)}, error),
+ dry_run = coalesce(${typeof fields.dryRun === 'boolean' ? fields.dryRun : null}::boolean, dry_run),
+ decided_at = case when ${d}::text is not null then now() else decided_at end,
+ updated_at = now()
+ where tweet_id = ${id}
+ returning *
+ `;
+ return rows[0] || null;
+}
+
+/** One recorded mention, or null. */
+export async function getMentionEvent(tweetId) {
+ const [row] = await sql`select * from x_mention_events where tweet_id = ${String(tweetId)}`;
+ return row || null;
+}
+
+/**
+ * How many mentions from one author were recorded in the trailing window,
+ * optionally limited to some decisions (e.g. ['reply'] for a reply cap) and
+ * to one of our accounts.
+ *
+ * @param {string} authorId
+ * @param {{ windowSeconds?: number, decisions?: string[]|null, account?: { kind: string, ref: string }|null }} [opts]
+ */
+export async function countByAuthor(authorId, { windowSeconds = 3600, decisions = null, account = null } = {}) {
+ const secs = Math.max(1, Math.round(Number(windowSeconds) || 3600));
+ const list = decisions && decisions.length ? decisions.filter((x) => DECISIONS.includes(x)) : null;
+ const acct = account ? accountOf(account) : null;
+ const [row] = await sql`
+ select count(*)::int as n from x_mention_events
+ where author_id = ${String(authorId)}
+ and created_at > now() - make_interval(secs => ${secs})
+ and (${list ? list.join(',') : null}::text is null or decision = any(string_to_array(${list ? list.join(',') : null}::text, ',')))
+ and (${acct?.kind ?? null}::text is null or (account_kind = ${acct?.kind ?? null} and account_ref = ${acct?.ref ?? null}))
+ `;
+ return row?.n ?? 0;
+}
+
+/**
+ * The most recent recorded mentions of one account, newest first, optionally
+ * only one decision (the dry-run console lists `reply` rows with dry_run).
+ *
+ * @param {{ kind: string, ref: string }} account
+ * @param {{ limit?: number, decision?: string|null, dryRun?: boolean|null }} [opts]
+ */
+export async function recentDecisions(account, { limit = 50, decision = null, dryRun = null } = {}) {
+ const { kind, ref } = accountOf(account);
+ if (decision != null && !DECISIONS.includes(decision)) throw new MentionStoreError(`unknown decision: ${decision}`, 'bad_decision');
+ const n = Math.max(1, Math.min(500, Math.round(Number(limit) || 50)));
+ return sql`
+ select * from x_mention_events
+ where account_kind = ${kind} and account_ref = ${ref}
+ and (${decision}::text is null or decision = ${decision})
+ and (${dryRun}::boolean is null or dry_run = ${dryRun})
+ order by created_at desc, tweet_id desc
+ limit ${n}
+ `;
+}
diff --git a/tests/x-mention-store.test.js b/tests/x-mention-store.test.js
new file mode 100644
index 000000000..54aa81aff
--- /dev/null
+++ b/tests/x-mention-store.test.js
@@ -0,0 +1,236 @@
+// x-mention-store.js against the REAL x_mention_events migration, in an
+// in-process Postgres (PGlite), the same way the payment-intent suite tests
+// its constraints. The schema comes from the migration file itself, so a
+// column or CHECK the store relies on cannot drift from what production gets.
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { PGlite } from '@electric-sql/pglite';
+
+const dbState = { pg: null };
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = async (strings, ...values) => {
+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');
+ const out = await dbState.pg.query(text, values);
+ return out.rows;
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+const store = await import('../api/_lib/x-mention-store.js');
+const { normalizeMentions } = await import('../api/_lib/x-mentions.js');
+const { parseMentionIntent } = await import('../api/_lib/x-mention-intents.js');
+
+const MIG = new URL('../api/_lib/migrations/', import.meta.url);
+const MIGRATION = readFileSync(new URL('20261008170000_x_mention_events.sql', MIG), 'utf8');
+// app_settings exactly as its migration creates it.
+const APP_SETTINGS = (() => {
+ const src = readFileSync(new URL('20260922210000_free_tier_models.sql', MIG), 'utf8');
+ const start = src.indexOf('CREATE TABLE IF NOT EXISTS app_settings');
+ return src.slice(start, src.indexOf(');', start) + 2);
+})();
+
+const COMPANY = { kind: 'company', ref: 'trythreews', userId: '1700000000000000001', handle: 'trythreews' };
+const page = JSON.parse(readFileSync(join(process.cwd(), 'tests', 'fixtures', 'x-mentions', 'timeline-page.fixture.json'), 'utf8'));
+const MENTIONS = normalizeMentions(page, COMPANY);
+const byId = (id) => MENTIONS.find((m) => m.id === id);
+const record = (m, extra = {}) => store.recordMention({ mention: m, parsed: parseMentionIntent(m), ...extra });
+
+beforeEach(async () => {
+ dbState.pg = new PGlite();
+ await dbState.pg.exec(APP_SETTINGS);
+ await dbState.pg.exec(MIGRATION);
+});
+
+describe('migration', () => {
+ it('is idempotent and creates the three time indexes', async () => {
+ await dbState.pg.exec(MIGRATION);
+ const { rows } = await dbState.pg.query(`select indexname from pg_indexes where tablename = 'x_mention_events' order by indexname`);
+ expect(rows.map((r) => r.indexname)).toEqual([
+ 'x_mention_events_account_time_idx',
+ 'x_mention_events_author_time_idx',
+ 'x_mention_events_decision_time_idx',
+ 'x_mention_events_pkey',
+ ]);
+ });
+
+ it('rejects an unknown intent, decision or account kind', async () => {
+ const ins = (kind, intent, decision) => dbState.pg.query(
+ `insert into x_mention_events (tweet_id, account_kind, account_ref, author_id, intent, decision) values ('1', $1, 'r', 'a', $2, $3)`,
+ [kind, intent, decision],
+ );
+ await expect(ins('company', 'transfer', null)).rejects.toThrow(/intent_check/);
+ await expect(ins('company', 'make', 'sent_funds')).rejects.toThrow(/decision_check/);
+ await expect(ins('person', 'make', null)).rejects.toThrow(/account_kind_check/);
+ });
+});
+
+describe('recordMention', () => {
+ it('stores what the bot saw and the parsed intent, dry run by default', async () => {
+ const m = byId('1800000000000000101');
+ expect(await record(m)).toEqual({ inserted: true, tweetId: '1800000000000000101' });
+ const row = await store.getMentionEvent('1800000000000000101');
+ expect(row).toMatchObject({
+ account_kind: 'company',
+ account_ref: 'trythreews',
+ author_id: '1700000000000000020',
+ author_username: 'fixture_dee',
+ conversation_id: '1800000000000000101',
+ mention_text: '@trythreews turn my cat into 3d https://t.co/fixtureImg1',
+ intent: 'image3d',
+ decision: null,
+ reason: 'command:image3d',
+ dry_run: true,
+ reply_tweet_id: null,
+ });
+ expect(row.args.mediaUrl).toBe('https://pbs.twimg.com/media/FixtureCatPhoto.jpg');
+ expect(new Date(row.mention_created_at).toISOString()).toBe('2026-10-08T02:50:00.000Z');
+ });
+
+ it('dedupes: a second record of the same tweet is a no-op', async () => {
+ const m = byId('1800000000000000104');
+ expect((await record(m)).inserted).toBe(true);
+ expect((await record(m, { dryRun: false })).inserted).toBe(false);
+ const { rows } = await dbState.pg.query('select count(*)::int as n, bool_and(dry_run) as dry from x_mention_events');
+ expect(rows[0]).toEqual({ n: 1, dry: true });
+ });
+
+ it('the dedupe race: two concurrent inserts, exactly one wins', async () => {
+ const m = byId('1800000000000000102');
+ const results = await Promise.all([record(m), record(m), record(m)]);
+ expect(results.filter((r) => r.inserted)).toHaveLength(1);
+ const { rows } = await dbState.pg.query(`select count(*)::int as n from x_mention_events where tweet_id = '1800000000000000102'`);
+ expect(rows[0].n).toBe(1);
+ });
+
+ it('can record an immediate decision, e.g. skipping our own post', async () => {
+ const own = byId('1800000000000000107');
+ await record(own, { decision: 'skip' });
+ const row = await store.getMentionEvent(own.id);
+ expect(row).toMatchObject({ intent: 'ignore', decision: 'skip', reason: 'own_post' });
+ expect(row.decided_at).not.toBeNull();
+ });
+
+ it('refuses a mention without an id, author, account or parse', async () => {
+ const m = byId('1800000000000000101');
+ await expect(store.recordMention({ mention: { ...m, id: 'abc' }, parsed: { intent: 'make' } })).rejects.toMatchObject({ code: 'bad_mention' });
+ await expect(store.recordMention({ mention: { ...m, userId: null, author: null }, parsed: { intent: 'make' } })).rejects.toMatchObject({ code: 'bad_mention' });
+ await expect(store.recordMention({ mention: { ...m, account: { kind: 'x', ref: 'y' } }, parsed: { intent: 'make' } })).rejects.toMatchObject({ code: 'bad_account' });
+ await expect(store.recordMention({ mention: m, parsed: null })).rejects.toMatchObject({ code: 'bad_intent' });
+ await expect(record(m, { decision: 'sent' })).rejects.toMatchObject({ code: 'bad_decision' });
+ });
+
+ it('caps a very long post', async () => {
+ const m = { ...byId('1800000000000000104'), id: '1800000000000000999', text: 'x'.repeat(30_000) };
+ await record(m);
+ const row = await store.getMentionEvent('1800000000000000999');
+ expect(row.mention_text).toHaveLength(store.MENTION_TEXT_MAX);
+ });
+});
+
+describe('updateDecision', () => {
+ it('writes the decision and the would-be reply, keeping untouched fields', async () => {
+ const m = byId('1800000000000000104');
+ await record(m);
+ const row = await store.updateDecision(m.id, {
+ decision: 'reply',
+ reason: 'made',
+ replyText: 'Here is your lighthouse.',
+ replyMediaUrl: 'https://three.ws/api/render/glb?glbUrl=fixture',
+ replyLink: 'https://three.ws/forge',
+ creationId: 'creation-fixture-1',
+ });
+ expect(row).toMatchObject({ decision: 'reply', reason: 'made', reply_text: 'Here is your lighthouse.', creation_id: 'creation-fixture-1', intent: 'make', dry_run: true, reply_tweet_id: null });
+ expect(row.decided_at).not.toBeNull();
+ const again = await store.updateDecision(m.id, { error: 'render slow' });
+ expect(again).toMatchObject({ decision: 'reply', reply_text: 'Here is your lighthouse.', error: 'render slow' });
+ });
+
+ it('sets a reply tweet id once and never replaces it', async () => {
+ const m = byId('1800000000000000101');
+ await record(m);
+ const first = await store.updateDecision(m.id, { decision: 'reply', replyTweetId: '1800000000000001001', dryRun: false });
+ expect(first).toMatchObject({ reply_tweet_id: '1800000000000001001', dry_run: false });
+ expect(first.replied_at).not.toBeNull();
+ const second = await store.updateDecision(m.id, { replyTweetId: '1800000000000001002' });
+ expect(second.reply_tweet_id).toBe('1800000000000001001');
+ expect(new Date(second.replied_at).getTime()).toBe(new Date(first.replied_at).getTime());
+ });
+
+ it('returns null for an unknown mention and refuses an unknown decision', async () => {
+ expect(await store.updateDecision('1800000000000009999', { decision: 'skip' })).toBeNull();
+ await expect(store.updateDecision('1800000000000000101', { decision: 'launched' })).rejects.toMatchObject({ code: 'bad_decision' });
+ });
+});
+
+describe('counts and recent decisions', () => {
+ beforeEach(async () => {
+ for (const m of MENTIONS) await record(m);
+ // Two more from the same author (fixture_dee), one replied, one rate limited.
+ const dee = byId('1800000000000000101');
+ await record({ ...dee, id: '1800000000000000110' });
+ await record({ ...dee, id: '1800000000000000111' });
+ await store.updateDecision('1800000000000000101', { decision: 'reply' });
+ await store.updateDecision('1800000000000000110', { decision: 'reply' });
+ await store.updateDecision('1800000000000000111', { decision: 'rate_limited' });
+ await store.updateDecision('1800000000000000107', { decision: 'skip' });
+ });
+
+ it('counts one author in a window, by decision and by account', async () => {
+ expect(await store.countByAuthor('1700000000000000020')).toBe(3);
+ expect(await store.countByAuthor('1700000000000000020', { decisions: ['reply'] })).toBe(2);
+ expect(await store.countByAuthor('1700000000000000020', { decisions: ['reply', 'rate_limited'] })).toBe(3);
+ expect(await store.countByAuthor('1700000000000000020', { account: { kind: 'agent', ref: 'agent-x' } })).toBe(0);
+ expect(await store.countByAuthor('1700000000000000020', { account: { kind: 'company', ref: 'trythreews' } })).toBe(3);
+ expect(await store.countByAuthor('1700000000000000099')).toBe(0);
+ });
+
+ it('the window excludes older rows', async () => {
+ await dbState.pg.query(`update x_mention_events set created_at = now() - interval '2 hours' where tweet_id = '1800000000000000110'`);
+ expect(await store.countByAuthor('1700000000000000020', { windowSeconds: 3600 })).toBe(2);
+ expect(await store.countByAuthor('1700000000000000020', { windowSeconds: 3 * 3600 })).toBe(3);
+ });
+
+ it('lists recent decisions per account, newest first, filtered', async () => {
+ const all = await store.recentDecisions({ kind: 'company', ref: 'trythreews' });
+ expect(all).toHaveLength(MENTIONS.length + 2);
+ const replies = await store.recentDecisions({ kind: 'company', ref: 'trythreews' }, { decision: 'reply', dryRun: true });
+ expect(replies.map((r) => r.tweet_id).sort()).toEqual(['1800000000000000101', '1800000000000000110']);
+ expect(await store.recentDecisions({ kind: 'agent', ref: 'agent-x' })).toEqual([]);
+ expect(await store.recentDecisions({ kind: 'company', ref: 'trythreews' }, { limit: 2 })).toHaveLength(2);
+ });
+});
+
+describe('cursor', () => {
+ const acct = { kind: 'company', ref: 'trythreews' };
+
+ it('uses the documented app_settings key', () => {
+ expect(store.cursorKey(acct)).toBe('x_mentions_cursor:company:trythreews');
+ expect(store.cursorKey({ kind: 'agent', ref: 'agent-1' })).toBe('x_mentions_cursor:agent:agent-1');
+ expect(() => store.cursorKey({ kind: 'company', ref: '' })).toThrow(/account/);
+ });
+
+ it('starts empty, advances, and never moves back', async () => {
+ expect(await store.getCursor(acct)).toBeNull();
+ expect(await store.advanceCursor(acct, '1800000000000000104')).toBe(true);
+ expect(await store.getCursor(acct)).toBe('1800000000000000104');
+ expect(await store.advanceCursor(acct, '1800000000000000102')).toBe(false);
+ expect(await store.getCursor(acct)).toBe('1800000000000000104');
+ expect(await store.advanceCursor(acct, '1800000000000000107')).toBe(true);
+ expect(await store.getCursor(acct)).toBe('1800000000000000107');
+ });
+
+ it('compares ids beyond 2^53 exactly', async () => {
+ await store.advanceCursor(acct, '9007199254740993');
+ expect(await store.advanceCursor(acct, '9007199254740992')).toBe(false);
+ expect(await store.advanceCursor(acct, '9007199254740994')).toBe(true);
+ });
+
+ it('keeps accounts apart and refuses a non-id cursor', async () => {
+ await store.advanceCursor(acct, '1800000000000000107');
+ expect(await store.getCursor({ kind: 'agent', ref: 'agent-1' })).toBeNull();
+ await expect(store.advanceCursor(acct, '1; drop table app_settings')).rejects.toMatchObject({ code: 'bad_cursor' });
+ });
+});