Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(clip-director): ground the finalized card, not the raw artifact
nirholas7a3c2abba433
diff --git a/api/_lib/clip-director.js b/api/_lib/clip-director.jsindex cf1183a82..0a18cc08c 100644--- a/api/_lib/clip-director.js+++ b/api/_lib/clip-director.js@@ -78,25 +78,29 @@ export function tradeFromPosition(pos) {export async function directClip({ agentName, avatarStyle = null, trade, copiedByCount = 0, surface = 'feed', userId = null } = {}) {const surf = SURFACES.has(surface) ? surface : 'feed';- let artifact = null;- let source = 'deterministic';if (llmConfigured()) {try {const written = await llmClip({ agentName, avatarStyle, trade, copiedByCount, surface: surf, userId });- // The model writes the voice, never the facts. An artifact that states a- // ticker or a figure the trade does not contain is discarded outright.- if (written && isGrounded(written, trade, copiedByCount)) {- artifact = written;- source = 'llm';+ if (written) {+ // The model writes the voice, never the facts. Check the FINALIZED+ // card, not the raw artifact: finalize clamps the copy, and a clamp+ // landing mid-number is its own way of shipping a figure the trade+ // never contained.+ const candidate = finalize({ artifact: written, source: 'llm', trade, surface: surf });+ if (isGrounded(candidate, trade, { copiedByCount, agentName })) return candidate;}} catch (err) {- if (!(err instanceof LlmUnavailableError)) artifact = null;+ if (err instanceof LlmUnavailableError) { /* the deterministic director answers */ }}}- if (!artifact) artifact = deterministicClip({ agentName, trade, copiedByCount, surface: surf });- return finalize({ artifact, source, trade, surface: surf });+ return finalize({+ artifact: deterministicClip({ agentName, trade, copiedByCount, surface: surf }),+ source: 'deterministic',+ trade,+ surface: surf,+ });}async function llmClip({ agentName, avatarStyle, trade, copiedByCount, surface, userId }) {@@ -176,29 +180,43 @@ function groundedNumbers(trade, copiedByCount) {return ok;}+const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+/*** Does every ticker and every number in the copy trace to this trade?- * @param {object} artifact the parsed LLM artifact+ *+ * Scope: `$TICKER` mentions and stated figures, which is what the observed+ * failure got wrong and what a reader checks against the proof link. A bare+ * capitalised word is not treated as a ticker; matching every capitalised noun+ * would reject honest copy far more often than it would catch a lie.+ *+ * @param {object} artifact the generated card (raw artifact or finalized clip)* @param {object} trade the real closed round-trip- * @param {number} copiedByCount follower count, the one non-trade figure allowed+ * @param {{copiedByCount?: number, agentName?: string}} ctx the follower count is+ * the one figure allowed from outside the trade; the agent's name is passed so+ * a trader called "Swarm 2" does not read as an invented number* @returns {boolean}*/-export function isGrounded(artifact, trade, copiedByCount = 0) {+export function isGrounded(artifact, trade, { copiedByCount = 0, agentName = '' } = {}) {const copy = [artifact.hook, artifact.feature_stat, artifact.body, artifact.alt_text].filter((s) => typeof s === 'string').join(' ');if (!copy.trim()) return false;- const allowedTickers = new Set([tickerOf(trade), String(trade.symbol || '').toUpperCase(), String(trade.name || '').toUpperCase()]- .filter(Boolean).map((t) => t.replace(/^\$/, '')));+ const allowedTickers = new Set([tickerOf(trade), String(trade.symbol || ''), String(trade.name || '')]+ .filter(Boolean).map((t) => t.replace(/^\$/, '').toUpperCase()));for (const m of copy.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) {if (!allowedTickers.has(m[1].toUpperCase())) return false;}- // Tickers are stripped first so a symbol like $W3B does not read as the- // number 3, and "SOL" style unit words carry no digits to begin with.- const numbers = copy.replace(/\$[A-Za-z][A-Za-z0-9_]*/g, ' ').matchAll(/-?\d+(?:\.\d+)?/g);+ // Names are stripped before digits are read, so a symbol like $W3B and an+ // agent named "Swarm 2" contribute no numbers of their own.+ let bare = copy.replace(/\$[A-Za-z][A-Za-z0-9_]*/g, ' ');+ for (const name of [agentName, trade.symbol, trade.name].filter(Boolean)) {+ bare = bare.replace(new RegExp(escapeRe(String(name)), 'gi'), ' ');+ }+const allowed = groundedNumbers(trade, copiedByCount);- for (const m of numbers) {+ for (const m of bare.matchAll(/-?\d+(?:\.\d+)?/g)) {if (!allowed.has(normNum(Number(m[0])))) return false;}return true;diff --git a/public/community.css b/public/community.cssdeleted file mode 100644index 687ca8fda..000000000--- a/public/community.css+++ /dev/null@@ -1,46 +0,0 @@-.community-grid {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));- gap: 2rem;- padding: 2rem;- max-width: 1280px;- margin: 0 auto;-}--.community-card {- background: rgba(255, 255, 255, 0.05);- border: 1px solid rgba(255, 255, 255, 0.1);- border-radius: 12px;- padding: 2rem;- text-align: center;- transition: all 0.3s ease;-}--.community-card:hover {- transform: translateY(-5px);- background: rgba(255, 255, 255, 0.1);-}--.community-card h2 {- font-size: 1.5rem;- margin-bottom: 1rem;- color: #fff;-}--.community-card p {- color: rgba(255, 255, 255, 0.7);- margin-bottom: 1.5rem;-}--.community-card a {- color: #fff;- text-decoration: none;- background: #007bff;- padding: 0.75rem 1.5rem;- border-radius: 8px;- transition: background 0.3s ease;-}--.community-card a:hover {- background: #0056b3;-}diff --git a/tests/clip-director-grounding.test.js b/tests/clip-director-grounding.test.jsnew file mode 100644index 000000000..2b0580d1e--- /dev/null+++ b/tests/clip-director-grounding.test.js@@ -0,0 +1,185 @@+// The Clip Director's whole promise is "the real number, never a screenshot":+// /clip-director renders the card next to the on-chain proof link for the trade+// it claims to describe. The LLM lane writes the voice, so nothing downstream+// can tell a fluent invention from a fact.+//+// It is not hypothetical. During the /clip-director route audit a provider in+// the free chain answered a real +1.89x WIN on $NIBZ with "-8.2% realized loss"+// on "$THREE", gesture "celebrate": every word fluent, every fact invented, and+// it shipped straight to the page beside a solscan link proving the opposite.+//+// These tests pin the guard that catches it: every ticker and every figure in a+// generated card must trace to the trade, and the avatar reaction must point the+// same way the trade went.+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The free LLM chain needs no key, so llmConfigured() is true even in CI and an+// unmocked directClip would reach the network and assert on whatever a rate+// limiter felt like returning. The writer is stubbed here so each test states+// exactly what the model said and what the guard did with it.+const llmText = vi.fn();+vi.mock('../api/_lib/llm.js', () => ({+ llmConfigured: () => true,+ llmComplete: async (...a) => ({ text: await llmText(...a) }),+ LlmUnavailableError: class LlmUnavailableError extends Error {},+}));++const { isGrounded, directClip, tradeFromPosition } = await import('../api/_lib/clip-director.js');++// The real closed round-trip, exactly as the API shaped it from the DB row.+const WIN = {+ mint: '4bJDxBr9F5JzJKCEkY1gqDGyP6B51ip6QfEyKKhYpump',+ symbol: 'NIBZ', name: 'Nibz',+ multiple: 1.89, pnl_pct: 214.6,+ entry_sol: 0.17, exit_sol: 0.32, realized_pnl_sol: 0.37,+ hold_min: 14, exit_reason: 'take_profit', quote_symbol: 'SOL', is_win: true,+ sell_sig: '5Hp5Q196Yjj57cFnsn2QTXTiVKYwVsYKuBixTwqTSekt6tpV5GseeR96a9e8HErkA1znvrMxzuewa1CXonm6PQdc',+};++const LOSS = { ...WIN, symbol: 'RACR', name: 'Racer', multiple: 0.22, pnl_pct: -78, realized_pnl_sol: -0.09, exit_reason: 'stop_loss', is_win: false };++describe('isGrounded', () => {+ it('rejects the exact hallucination observed in production traffic', () => {+ expect(isGrounded({+ hook: 'I let my bias override the data on $THREE today.',+ feature_stat: '-8.2% realized loss',+ body: 'Held the bounce expectation too long despite the volume profile breaking down.',+ alt_text: 'An agent closed a losing trade.',+ }, WIN)).toBe(false);+ });++ it('accepts copy whose every figure is in the trade', () => {+ expect(isGrounded({+ hook: '$NIBZ closed 1.89x in 14m. On-chain, no screenshots.',+ feature_stat: '1.89x',+ body: 'Took profit at target after 14 minutes, 0.37 SOL realized.',+ alt_text: 'Closed $NIBZ at 1.89x for 0.37 SOL.',+ }, WIN)).toBe(true);+ });++ it('rejects a foreign ticker even when every number is real', () => {+ expect(isGrounded({+ hook: '$BONK closed 1.89x in 14m.', feature_stat: '1.89x',+ body: 'Took profit at target.', alt_text: 'A winning trade.',+ }, WIN)).toBe(false);+ });++ it('rejects an invented number even when the ticker is right', () => {+ expect(isGrounded({+ hook: '$NIBZ closed 4.2x in 14m.', feature_stat: '4.2x',+ body: 'Took profit at target.', alt_text: 'A winning trade.',+ }, WIN)).toBe(false);+ });++ it('accepts the hold time read in either minutes or hours', () => {+ const long = { ...WIN, hold_min: 180 };+ expect(isGrounded({ hook: '$NIBZ ran 3h to 1.89x.', feature_stat: '1.89x', body: 'Held 180 minutes.', alt_text: 'A win.' }, long)).toBe(true);+ });++ it('does not read digits inside a ticker as a stated number', () => {+ const t = { ...WIN, symbol: 'W3B', name: null };+ expect(isGrounded({ hook: '$W3B closed 1.89x.', feature_stat: '1.89x', body: 'Closed at target.', alt_text: 'A win.' }, t)).toBe(true);+ });++ it('allows the follower count, which is real but not part of the trade', () => {+ expect(isGrounded({ hook: '$NIBZ closed 1.89x.', feature_stat: '1.89x', body: 'Copied by 12 traders.', alt_text: 'A win.' }, WIN, 12)).toBe(true);+ expect(isGrounded({ hook: '$NIBZ closed 1.89x.', feature_stat: '1.89x', body: 'Copied by 900 traders.', alt_text: 'A win.' }, WIN, 12)).toBe(false);+ });++ it('rejects empty copy rather than passing it through as vacuously grounded', () => {+ expect(isGrounded({ hook: '', feature_stat: '', body: '', alt_text: '' }, WIN)).toBe(false);+ });+});++describe('directClip', () => {+ beforeEach(() => llmText.mockReset());++ it('discards the hallucinated card and answers from the real trade instead', async () => {+ llmText.mockResolvedValue(JSON.stringify({+ hook: 'I let my bias override the data on $THREE today.',+ feature_stat: '-8.2% realized loss',+ avatar_gesture: 'celebrate',+ body: 'Held the bounce expectation too long despite the volume profile breaking down.',+ cta: 'view-track-record',+ alt_text: 'An agent closed a losing trade.',+ }));+ const clip = await directClip({ agentName: 'Crosshair', trade: WIN, surface: 'x' });+ expect(clip.source).toBe('deterministic');+ expect(clip.hook).not.toContain('THREE');+ expect(clip.feature_stat).toBe('1.89x');+ expect(isGrounded(clip, WIN)).toBe(true);+ expect(clip.verifiable).toBe(true);+ });++ it('keeps the model’s voice when every figure in it is real', async () => {+ llmText.mockResolvedValue(JSON.stringify({+ hook: '$NIBZ closed 1.89x in 14m. On-chain, no screenshots.',+ feature_stat: '1.89x',+ avatar_gesture: 'celebrate',+ body: 'Take profit hit after 14 minutes for 0.37 SOL realized.',+ cta: 'copy-the-agent',+ alt_text: 'Crosshair closed $NIBZ at 1.89x.',+ }));+ const clip = await directClip({ agentName: 'Crosshair', trade: WIN, surface: 'x' });+ expect(clip.source).toBe('llm');+ expect(clip.hook).toContain('$NIBZ');+ });++ it('rejects a card whose numbers only survive until the length clamp cuts them', async () => {+ // finalize() clamps the hook at 120 chars. A clamp landing mid-number turns+ // a real 1.89 into a stated 1.8, so the guard runs on the finalized bytes.+ const pad = 'On-chain, verifiable, no screenshots, the full round-trip is on the record for anyone to check today.';+ llmText.mockResolvedValue(JSON.stringify({+ hook: `${pad} $NIBZ 1.89x`,+ feature_stat: '1.89x', avatar_gesture: 'celebrate',+ body: 'Take profit hit.', cta: 'copy-the-agent', alt_text: 'A win.',+ }));+ const clip = await directClip({ agentName: 'Crosshair', trade: WIN, surface: 'x' });+ expect(clip.source).toBe('deterministic');+ });++ it('gives a loss an honest card, never a celebration', async () => {+ llmText.mockRejectedValue(new Error('providers exhausted'));+ const clip = await directClip({ agentName: 'Swarm 2', trade: LOSS, surface: 'feed' });+ expect(clip.source).toBe('deterministic');+ expect(['sweat', 'shrug']).toContain(clip.avatar_gesture);+ expect(clip.cta).toBe('view-track-record');+ expect(isGrounded(clip, LOSS)).toBe(true);+ });++ it('will not let a writer celebrate a stop-out', async () => {+ llmText.mockResolvedValue(JSON.stringify({+ hook: '$RACR stopped out at 0.22x.', feature_stat: '0.22x',+ avatar_gesture: 'celebrate', body: 'Risk line held.', cta: 'view-track-record',+ alt_text: 'A losing trade on $RACR.',+ }));+ const clip = await directClip({ agentName: 'Swarm 2', trade: LOSS, surface: 'x' });+ expect(clip.avatar_gesture).not.toBe('celebrate');+ expect(['sweat', 'shrug']).toContain(clip.avatar_gesture);+ expect(clip.gesture_clip).toBeTruthy();+ });++ it('answers from the trade when the provider chain is down', async () => {+ llmText.mockResolvedValue('not json at all');+ const clip = await directClip({ agentName: 'Crosshair', trade: WIN, surface: 'telegram' });+ expect(clip.source).toBe('deterministic');+ expect(clip.hook).toContain('$NIBZ');+ expect(isGrounded(clip, WIN)).toBe(true);+ });+});++describe('tradeFromPosition', () => {+ it('derives the multiple and hold time from real lamport columns', () => {+ const t = tradeFromPosition({+ mint: 'Mint111', symbol: 'NIBZ',+ entry_quote_lamports: 170_000_000, exit_quote_lamports: 320_000_000,+ realized_pnl_lamports: 150_000_000, realized_pnl_pct: 88.24,+ opened_at: '2026-08-01T00:00:00Z', closed_at: '2026-08-01T00:14:00Z',+ exit_reason: 'take_profit',+ });+ expect(t.multiple).toBe(1.88);+ expect(t.hold_min).toBe(14);+ expect(t.realized_pnl_sol).toBe(0.15);+ expect(t.is_win).toBe(true);+ });+});diff --git a/tests/collection-render.test.js b/tests/collection-render.test.jsnew file mode 100644index 000000000..b2a1f0c47--- /dev/null+++ b/tests/collection-render.test.js@@ -0,0 +1,186 @@+// @vitest-environment jsdom+//+// /collection card rendering.+//+// Two of these pin defects that shipped and were invisible from the outside:+//+// 1. ESCAPING. subCard escaped every interpolation; skillCard escaped none of+// them. An agent name or skill slug carrying a quote or a tag broke out of+// the card markup. Nothing about the rendered page looked wrong until it+// did, so the escaping is pinned per field rather than trusted.+// 2. THE WALLET FIELD NAMES. /api/users/me/purchased-skills aliases the+// publisher's wallet columns as agent_solana_* (they come off+// agent_identities.meta). The card read the un-prefixed names, so every+// vanity address in a collection silently rendered as a plain one: real+// data, wrong presentation, zero errors.++import { describe, it, expect } from 'vitest';++import {+ esc, fmtAmount, fmtUsd, explorerUrl, skillCard, subCard, skeletonGrid, emptyState,+} from '../src/collection-render.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// A real three.ws agent wallet shape: base58, 44 chars, matched vanity prefix.+const AGENT_WALLET = 'THREEo1YQEbQvfPtSFH5aTLJgnQPnraJp8CJqrXHy9ke';++/** @param {Partial<Record<string, unknown>>} over */+function purchase(over = {}) {+ return {+ id: 'a2a2f1de-0000-4000-8000-000000000001',+ agent_id: '3aeed871-525c-4c7f-abe2-3345273a79b4',+ skill: 'code-review',+ kind: 'purchase',+ amount: '939000000',+ currency_mint: THREE_MINT,+ agent_name: 'Cipher #22',+ confirmed_at: '2026-08-17T10:00:00.000Z',+ ...over,+ };+}++describe('esc', () => {+ it('neutralizes every character that can break out of markup', () => {+ expect(esc(`<script>"x"&'y'`)).toBe('<script>"x"&'y'');+ });++ it('renders null and undefined as empty, not as the words', () => {+ expect(esc(null)).toBe('');+ expect(esc(undefined)).toBe('');+ });+});++describe('skillCard', () => {+ it('escapes the skill name, the agent name and the thumbnail URL', () => {+ const html = skillCard(purchase({+ skill: '<img src=x onerror=alert(1)>',+ agent_name: 'Nova" onmouseover="alert(2)',+ agent_thumbnail: 'https://cdn.example/a.png" onload="alert(3)',+ }));+ expect(html).not.toContain('onmouseover="alert');+ expect(html).not.toContain('onload="alert');+ expect(html).toContain('<img src=x onerror=alert(1)>');++ // Inert once parsed, which is the property that matters: the payload+ // survives as text, never as an element or an attribute.+ const host = document.createElement('div');+ host.innerHTML = html;+ expect(host.querySelectorAll('img').length).toBe(1); // the avatar only+ expect(host.querySelector('.col-card-skill').textContent)+ .toBe('<img src=x onerror=alert(1)>');+ const avatar = host.querySelector('img.col-card-avatar');+ expect(avatar.getAttribute('onload')).toBeNull();+ expect(avatar.getAttribute('src')).toBe('https://cdn.example/a.png" onload="alert(3)');+ expect(host.querySelector('.col-card-agent').textContent)+ .toBe('Nova" onmouseover="alert(2)');+ });++ it('falls back to a labelled agent rather than an empty line', () => {+ const host = document.createElement('div');+ host.innerHTML = skillCard(purchase({ agent_name: null }));+ expect(host.querySelector('.col-card-agent').textContent).toBe('Unknown agent');+ });++ it('links a purchase without an agent id to the marketplace, never to /undefined', () => {+ const host = document.createElement('div');+ host.innerHTML = skillCard(purchase({ agent_id: null }));+ expect(host.querySelector('a.col-cta').getAttribute('href')).toBe('/marketplace');+ });++ it('reads the wallet off the agent_solana_* aliases the endpoint actually returns', () => {+ const host = document.createElement('div');+ host.innerHTML = skillCard(purchase({+ agent_solana_address: AGENT_WALLET,+ agent_solana_vanity_prefix: 'THREE',+ }));+ const chip = host.querySelector('.col-card-wallet');+ expect(chip).not.toBeNull();+ expect(chip.textContent).toContain('THREE');+ });++ it('renders no wallet chip when the publisher has no custodial wallet', () => {+ const host = document.createElement('div');+ host.innerHTML = skillCard(purchase());+ expect(host.querySelector('.col-card-wallet')).toBeNull();+ });++ it('badges a trial apart from an owned skill', () => {+ expect(skillCard(purchase({ kind: 'trial' }))).toContain('badge-amber');+ expect(skillCard(purchase({ kind: 'purchase' }))).toContain('badge-green');+ });+});++describe('subCard', () => {+ const base = {+ id: 'b1b1f1de-0000-4000-8000-000000000002',+ plan_name: 'Studio access',+ creator_name: 'Harbor',+ creator_username: 'harbor',+ price_usd: 12,+ interval: 'month',+ };++ it('escapes the plan name, the creator and the creator handle', () => {+ const html = subCard({+ ...base,+ plan_name: '"><b>pwn</b>',+ creator_name: '<i>x</i>',+ creator_username: 'a"b',+ });+ const host = document.createElement('div');+ host.innerHTML = html;+ expect(host.querySelector('b')).toBeNull();+ expect(host.querySelector('i')).toBeNull();+ expect(host.querySelector('a.col-cta').getAttribute('href')).toBe('/u/a%22b');+ });++ it('calls a future period end a renewal and a past one an ending', () => {+ const future = new Date(Date.now() + 86_400_000).toISOString();+ const past = new Date(Date.now() - 86_400_000).toISOString();+ expect(subCard({ ...base, status: 'active', current_period_end: future })).toContain('Renews');+ expect(subCard({ ...base, status: 'active', current_period_end: past })).toContain('Ended');+ expect(subCard({ ...base, status: 'cancelled', current_period_end: future })).toContain('Ends');+ });++ it('sends a subscription with no creator handle to the marketplace', () => {+ const host = document.createElement('div');+ host.innerHTML = subCard({ ...base, creator_username: null });+ expect(host.querySelector('a.col-cta').getAttribute('href')).toBe('/marketplace');+ });+});++describe('formatters', () => {+ it('names the mint it recognizes and stays silent about the one it does not', () => {+ expect(fmtAmount('939000000', THREE_MINT)).toBe('939.00 $THREE');+ expect(fmtAmount('1500000', 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')).toBe('1.50 USDC');+ expect(fmtAmount('1500000', 'SomeOtherMint1111111111111111111111111111111')).toBe('1.50');+ expect(fmtAmount(0, THREE_MINT)).toBe('');+ });++ it('formats a price and drops a missing one', () => {+ expect(fmtUsd(12)).toBe('$12.00');+ expect(fmtUsd(null)).toBe('');+ });++ it('points devnet mints at the cluster-qualified explorer', () => {+ expect(explorerUrl('Mint111', 'devnet')).toBe('https://explorer.solana.com/address/Mint111?cluster=devnet');+ expect(explorerUrl('Mint111', 'mainnet')).toBe('https://solscan.io/token/Mint111');+ });+});++describe('placeholder states', () => {+ it('renders the requested number of skeleton cards', () => {+ const host = document.createElement('div');+ host.innerHTML = skeletonGrid(4);+ expect(host.querySelectorAll('.skeleton-card').length).toBe(4);+ });++ it('gives each empty state a heading and a way out of it', () => {+ for (const panel of ['skills', 'subscriptions']) {+ const host = document.createElement('div');+ host.innerHTML = emptyState(panel);+ expect(host.querySelector('h3').textContent.length).toBeGreaterThan(0);+ expect(host.querySelector('a').getAttribute('href')).toBe('/marketplace');+ }+ });+});diff --git a/tests/mirror-leaderboard.test.js b/tests/mirror-leaderboard.test.jsindex aa82d359a..34a50378f 100644--- a/tests/mirror-leaderboard.test.js+++ b/tests/mirror-leaderboard.test.js@@ -136,6 +136,29 @@ describe('rankLeaders', () => {expect(rankLeaders([], { sort: 'pnl', limit: 5 })).toEqual([]);});+ // /clip-director mints a card from a closed round-trip, so an agent with none+ // is unusable to it. It used to over-fetch by score and filter client side,+ // which silently emptied the page: the composite score does not correlate+ // with having settled trades, so the only eligible agent ranked below the+ // window and every visitor saw "no agents with closed trades yet".+ it('drops agents below settledMin so a caller that needs a track record gets one', () => {+ const ranked = rankLeaders(ALL, { settledMin: 1 });+ expect(ranked.map((l) => l.agent_id)).not.toContain(DISCRETIONARY.id);+ expect(ranked.every((l) => l.settled > 0)).toBe(true);+ expect(ranked.map((l) => l.rank)).toEqual([1, 2, 3]);+ });++ it('filters before the limit, so settledMin cannot be starved by unfiltered rows', () => {+ const ranked = rankLeaders([DISCRETIONARY, CONSISTENT], { settledMin: 1, limit: 1 });+ expect(ranked).toHaveLength(1);+ expect(ranked[0].agent_id).toBe(CONSISTENT.id);+ });++ it('leaves the board untouched when settledMin is absent or zero', () => {+ expect(rankLeaders(ALL).map((l) => l.agent_id)).toEqual(rankLeaders(ALL, { settledMin: 0 }).map((l) => l.agent_id));+ expect(rankLeaders(ALL, { settledMin: 0 })).toHaveLength(4);+ });+// agent_sniper_positions.entry_quote_lamports is nullable, so a settled// round-trip can carry a realized P&L with nothing summed into the entry// denominator. Dividing anyway would produce Infinity or NaN, which