Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: refactor signal engine and enhance test stability with improved mocks
zprv9cdc11b2105a
diff --git a/api/_lib/signal-engine.js b/api/_lib/signal-engine.jsindex 07bde97d6..e67bdc9f8 100644--- a/api/_lib/signal-engine.js+++ b/api/_lib/signal-engine.js@@ -28,102 +28,21 @@ import { transferUsdcGuarded } from './agent-usdc-transfer.js';import { solanaConnection } from './agent-pumpfun.js';import { WSOL_MINT } from './pump-trade-args.js';-const LAMPORTS_PER_SOL = 1_000_000_000;-const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / LAMPORTS_PER_SOL);-const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));-const DEFAULT_MIRROR_SLIPPAGE_BPS = 300;--// --- Edge-score tuning. Transparent, named, tunable (cf. trader-stats). ---------const EDGE_WEIGHTS = { hitRate: 0.55, roi: 0.45 };-const EDGE_CONFIDENCE_FULL_AT = 10; // closed signals for full statistical confidence-const EDGE_NEUTRAL = 0.45; // unproven feeds regress toward this (slightly below mid)-const ROI_TANH_PCT = 50; // ~+50% avg realized ≈ a strongly positive ROI sub-score-const FLAT_OUTCOME_PCT = 1; // |realized| ≤ this counts as flat, not win/loss-const DUST_ORDER_SOL = 0.002; // mirror orders below this are skipped as dust--// ── PURE ──────────────────────────────────────────────────────────────────────--/** Realized P&L pct → win / loss / flat. A near-zero result is flat, not a win. */-export function classifyOutcome(realizedPnlPct) {- if (realizedPnlPct == null || !Number.isFinite(Number(realizedPnlPct))) return null;- const pct = Number(realizedPnlPct);- if (pct > FLAT_OUTCOME_PCT) return 'win';- if (pct < -FLAT_OUTCOME_PCT) return 'loss';- return 'flat';-}--/** This entry's size relative to the publisher's typical (median) entry. 1.0 = typical. */-export function computeSizeMultiple(entrySol, referenceEntrySol) {- const ref = Number(referenceEntrySol);- const entry = Number(entrySol);- if (!(ref > 0) || !(entry > 0)) return 1;- return Number((entry / ref).toFixed(4));-}--/**- * Conviction (0..1) from how large a bet this is vs the trader's norm. A trader- * sizing 3× their typical entry is maximally convicted; their typical entry sits- * near 0.33. Documented heuristic — bound to real sizing data, never declared.- */-export function computeConviction(sizeMultiple) {- const m = Number(sizeMultiple);- if (!(m > 0)) return 0;- return Number(clamp(m / 3, 0, 1).toFixed(3));-}--/**- * The subscriber's mirrored order size (SOL) for an entry:- * base_sol × size_multiple × size_scaling, hard-capped at max_per_trade_sol.- * Returns 0 when the sized order is dust (the caller skips it).- */-export function subscriberOrderSol({ baseSol, sizeMultiple, sizeScaling = 1, maxPerTradeSol }) {- const sized = Number(baseSol) * Number(sizeMultiple || 1) * Number(sizeScaling || 1);- const capped = clamp(sized, 0, Number(maxPerTradeSol) || sized);- return capped < DUST_ORDER_SOL ? 0 : Number(capped.toFixed(6));-}--/**- * A feed's proven realized edge (0–100), confidence-regressed. Until a feed has- * EDGE_CONFIDENCE_FULL_AT closed signals, its score is pulled toward a neutral- * blended with the publisher's own verified track-record score — so a strong- * trader's new feed isn't punished to neutral, but still must PROVE per-feed edge- * before it can top the board.- */-export function feedEdgeScore({ closedSignals, winningSignals, avgRealizedPct, publisherScore = 50 }) {- const closed = Number(closedSignals) || 0;- const hitRate = closed > 0 ? clamp((Number(winningSignals) || 0) / closed, 0, 1) : 0;- const roiComponent = 0.5 + 0.5 * Math.tanh((Number(avgRealizedPct) || 0) / ROI_TANH_PCT);- const raw = clamp(EDGE_WEIGHTS.hitRate * hitRate + EDGE_WEIGHTS.roi * roiComponent, 0, 1);- const confidence = clamp(closed / EDGE_CONFIDENCE_FULL_AT, 0, 1);- const prior = clamp((Number(publisherScore) || 50) / 100, 0, 1);- const neutral = (EDGE_NEUTRAL + prior) / 2;- const effective = raw * confidence + neutral * (1 - confidence);- return Math.round(100 * clamp(effective, 0, 1));-}--export const FEED_SORTS = new Set(['edge', 'roi', 'hitrate', 'subscribers', 'newest']);--const FEED_COMPARATORS = {- edge: (a, b) => b.edge_score - a.edge_score || b.closed_signals - a.closed_signals,- roi: (a, b) => (b.avg_realized_pct ?? -1e9) - (a.avg_realized_pct ?? -1e9) || b.edge_score - a.edge_score,- hitrate: (a, b) => (b.hit_rate ?? -1) - (a.hit_rate ?? -1) || b.closed_signals - a.closed_signals,- subscribers: (a, b) => b.subscribers - a.subscribers || b.edge_score - a.edge_score,- newest: (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),+// The PURE half lives in signal-engine-core.js (no DB / network / SDK imports) so+// it can be tested in isolation. Re-export it here so every production caller and+// the DB layer below keep importing from one place.+import {+ lamToSol, clamp, median,+ classifyOutcome, computeSizeMultiple, computeConviction, subscriberOrderSol,+ feedEdgeScore, rankFeeds, FEED_SORTS,+} from './signal-engine-core.js';++export {+ classifyOutcome, computeSizeMultiple, computeConviction, subscriberOrderSol,+ feedEdgeScore, rankFeeds, FEED_SORTS,};-/** Sort an already-scored feed list by the chosen key. Pure. */-export function rankFeeds(feeds, sort = 'edge') {- const cmp = FEED_COMPARATORS[sort] || FEED_COMPARATORS.edge;- return [...feeds].sort(cmp).map((f, i) => ({ rank: i + 1, ...f }));-}--/** Median of a numeric array (0 for empty). */-function median(values) {- if (!values.length) return 0;- const s = [...values].sort((a, b) => a - b);- const mid = Math.floor(s.length / 2);- return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;-}+const DEFAULT_MIRROR_SLIPPAGE_BPS = 300;// ── DB: publisher reference + verification ─────────────────────────────────────diff --git a/tests/api/all-modules-load.test.js b/tests/api/all-modules-load.test.jsindex 4b3f46998..cd6fa959b 100644--- a/tests/api/all-modules-load.test.js+++ b/tests/api/all-modules-load.test.js@@ -3,13 +3,28 @@// Catches broken import paths, wrong-stack imports, and placeholder code that// throws on module init. If this fails on a file that is intentionally a stub,// fix the stub or add it to SKIP_MODULES below with a clear reason.-import { describe, it, expect } from 'vitest';-import { readdirSync, statSync } from 'node:fs';+import { describe, it, expect, beforeAll } from 'vitest';+import { readdirSync, statSync, existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';import { join, relative } from 'node:path';import { pathToFileURL } from 'node:url';const API_DIR = join(process.cwd(), 'api');+// api/chat-skills.js and api/skills-manifest.js read data/_generated/skill-metadata.json+// at import time (a build artifact produced by `prebuild`, gitignored, never written+// by `npm test`). On a clean checkout the file is absent and those two modules throw+// ENOENT before their handler runs. Generate it the same way the build does — via the+// real generator script, no mock — so this smoke test is self-sufficient. Idempotent:+// skipped when the artifact already exists (e.g. after a prior build).+beforeAll(() => {+ const artifact = join(process.cwd(), 'data', '_generated', 'skill-metadata.json');+ if (existsSync(artifact)) return;+ execFileSync('node', [join(process.cwd(), 'scripts', 'build-skill-metadata.mjs')], {+ stdio: 'ignore',+ });+}, 60_000);+// Files we know fail because they load env-gated infrastructure not present in the// test sandbox (DB, RPC, keypair files). Add only with a clear reason; never to// hide a real bug.diff --git a/tests/api/forge-credit-exhaustion-rescue.test.js b/tests/api/forge-credit-exhaustion-rescue.test.jsindex f110c3d03..00a121a80 100644--- a/tests/api/forge-credit-exhaustion-rescue.test.js+++ b/tests/api/forge-credit-exhaustion-rescue.test.js@@ -63,6 +63,25 @@ vi.mock('../../api/_lib/forge-lane-health.js', () => ({markLaneUnhealthy: vi.fn(async () => {}),}));+// Pin the provider-health cooldown boundary to a clean state. The NIM-rescue in+// the credit-exhaustion path only fires when the free NIM lane is NOT in a+// recent-failure cooldown — exactly the scenario these tests model ("the gateway+// healthy again by the time the rescue runs"). That cooldown lives in the SHARED+// cache (Redis when configured, in-memory otherwise), so without stubbing it a+// sibling forge test that drove a NIM failure could leave NIM_TRELLIS cooling and+// suppress the rescue here — a cross-test flake, not a behavior change. Stubbing+// it makes this file hermetic; the cooldown router itself is covered by+// tests/api/forge-nim-cooldown.test.js. markProviderCooldown is a no-op so a+// failure inside one test never pins state for the next.+vi.mock('../../api/_lib/provider-health.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ providersInCooldown: vi.fn(async () => new Map()),+ markProviderCooldown: vi.fn(async () => {}),+ };+});+// FLUX reference-image synthesis is OUT OF CREDIT — the exact prod symptom. This// throws the billing envelope textToImage tags (code:'billing', providerStatus:402),// which is NOT upstream-unavailable.diff --git a/tests/api/security-csrf-gates.test.js b/tests/api/security-csrf-gates.test.jsindex fa8c5f7de..063208f1d 100644--- a/tests/api/security-csrf-gates.test.js+++ b/tests/api/security-csrf-gates.test.js@@ -117,6 +117,30 @@ vi.mock('../../src/solana/sns.js', () => ({reverseLookupAddress: vi.fn(async () => null),}));+// solana-trade.js imports getBuyQuote/getSellQuote from _lib/solana/sdk-bridge.js,+// which lazily `import('@nirholas/pump-sdk')` for bonding-curve pricing. That+// package ships an ESM exports map whose `import` condition vite's import-analysis+// cannot resolve under Vitest unless the postinstall `fix-pump-sdk-esm.mjs` patch+// has rewritten it (it resolves fine in plain node + the Vercel runtime). vite+// resolves that dynamic import while *transforming* sdk-bridge.js at collection+// time — before any module-level mock could intercept it — so the whole suite+// fails to load with "Failed to resolve entry for package @nirholas/pump-sdk".+// Mock sdk-bridge.js at the boundary instead: vitest serves the factory and never+// transforms the real file, so the unresolvable import is never reached. The+// session-authed gates short-circuit at the CSRF check before any quote is+// fetched; the one path that does reach a quote (preview:true, which is CSRF-+// exempt) gets the bridge's documented "no bonding curve" result — null — exactly+// as production returns for a curve-less mint, so the preview path degrades the+// same way it would live. Sibling suites handle the same SDK by skipping its+// static importers (tests/api/all-modules-load.test.js).+vi.mock('../../api/_lib/solana/sdk-bridge.js', () => ({+ getBuyQuote: vi.fn(async () => null),+ getSellQuote: vi.fn(async () => null),+ getTokenPrice: vi.fn(async () => null),+ getGraduationProgress: vi.fn(async () => null),+ getBondingCurveState: vi.fn(async () => null),+}));+vi.mock('../../api/_lib/notify.js', () => ({insertNotification: vi.fn(() => {}),}));diff --git a/tests/signal-engine.test.js b/tests/signal-engine.test.jsindex 435784e6d..89c68b106 100644--- a/tests/signal-engine.test.js+++ b/tests/signal-engine.test.js@@ -8,10 +8,13 @@*/import { describe, it, expect } from 'vitest';+// Import from the PURE core (no DB / network / SDK chain) so these logic tests+// load even when the delivery half's native deps aren't resolvable. signal-engine.js+// re-exports every one of these, so this is the same surface the product uses.import {classifyOutcome, computeSizeMultiple, computeConviction, subscriberOrderSol,feedEdgeScore, rankFeeds, FEED_SORTS,-} from '../api/_lib/signal-engine.js';+} from '../api/_lib/signal-engine-core.js';describe('classifyOutcome', () => {it('classifies clear wins and losses by sign', () => {