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(api): harden mcp tool, labor, kol, launchpad, marketplace, and mcp3d endpoints and back them with tests
nirholas2e16a855d09b
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 67703d79f..93ebe6c59 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -62,7 +62,7 @@ bottom.| Unified service catalog (one source, two storefronts) | [api/_lib/service-catalog/index.js](api/_lib/service-catalog/index.js), descriptors [api/_lib/service-catalog/services/](api/_lib/service-catalog/services/index.js) | Live | The canonical written-once record of every service (paid x402 + free crypto/3D bundles + OKX.AI rows). `toBazaarDiscovery()` generates every static `/api/x402/*` entry in the [api/wk.js](api/wk.js) discovery doc (replacing ~1,400 lines of hand-mirrored blocks); `toOkxCatalog()` reproduces the OKX `catalogIndex()` payload exactly, with an `include:'all'` projection ready for listing expansion. New paid service = drop `services/<slug>.js` + add its barrel import row. No-drift guards: [tests/service-catalog.test.js](tests/service-catalog.test.js). Spec: [specs/SERVICE_CATALOG.md](specs/SERVICE_CATALOG.md) || Conversational refinement + remix economy | Iterate: [api/_mcp-studio/tools.js](api/_mcp-studio/tools.js) `refine_model` (free, on `/api/mcp-studio`) + [mcp-server/src/tools/refine-model.js](mcp-server/src/tools/refine-model.js) (paid stdio, $0.25); shared lineage core [mcp-server/src/tools/_lineage.js](mcp-server/src/tools/_lineage.js). Remix (paid track): feed [api/remix-feed.js](api/remix-feed.js) `→ /api/remix-feed` (free browse/publish/lineage), settlement [api/x402/remix-asset.js](api/x402/remix-asset.js) `→ /api/x402/remix-asset` + core [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) + split math [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js). Docs [docs/remix.md](docs/remix.md), [docs/mcp-studio.md](docs/mcp-studio.md). | Live | Talk to a model to iterate it ("make it metallic") — real anchored re-generation with a revertable/branchable version lineage rendered as a viewer version strip; free on both the OpenAI 3D Studio and the paid MCP server. Creators publish a finished model as remixable (provenance + license + royalty on the existing `forge_creations` rows — no parallel store); another agent pays $0.25 USDC to remix it and a creator-set royalty (≤20%, capped) routes on-chain to the original creator via the audited `transferSolanaUSDC` rail. Split/caps/payout unit-tested ([tests/remix-settlement.test.js](tests/remix-settlement.test.js), [tests/remix-royalty.test.js](tests/remix-royalty.test.js), [tests/refine-lineage.test.js](tests/refine-lineage.test.js)). Free track stays crypto-free. Prompt 09. || Restyle Studio (material/PBR editor + AI restyle + variants) | [pages/restyle.html](pages/restyle.html) `→ /restyle`, [src/restyle.js](src/restyle.js). PBR preset/variant library [packages/viewer-presets/src/materials.js](packages/viewer-presets/src/materials.js) (`@three-ws/viewer-presets`). AI restyle + persistence core [api/_lib/material-studio-store.js](api/_lib/material-studio-store.js), free hosted endpoint [api/material-studio.js](api/material-studio.js) `→ /api/material-studio`; paid agent twin [mcp-server/src/tools/restyle-material.js](mcp-server/src/tools/restyle-material.js) (`restyle_material`, $0.05 stdio MCP), thin core [mcp-server/src/tools/_material-core.js](mcp-server/src/tools/_material-core.js). Shares the `refine_model` lineage core ([mcp-server/src/tools/_lineage.js](mcp-server/src/tools/_lineage.js)) so a restyle/variant is just another kind of version, feeding prompt 09 remix. Docs: [docs/mcp-tools.md](docs/mcp-tools.md). | Live | Re-skin any GLB without regenerating its mesh: live PBR editing (color/metalness/roughness/emissive/texture) with a one-click preset library (14 looks — chrome, gold, glass, wood…), seeded reproducible colorway variants (mulberry32 PRNG — same base+seed → same set), and free-text AI restyle ("make it chrome", "cyberpunk neon") via IBM Granite-proposed PBR factors applied + re-exported server-side. Every AI restyle / saved checkpoint mints a real, `gltf-validator`-checked, durably-stored GLB recorded in an immutable parent→child lineage — non-destructive in the durable sense, not just an in-browser Reset. Roadmap prompt 06. |-| Embodiment — a living agent body in the chat | Hosted embed [pages/embodiment/embed.html](pages/embodiment/embed.html) `→ /embodiment/embed` (Vite input + vercel route, `frame-ancestors *`); engine [apps-sdk/embodiment/embodiment-stage.js](apps-sdk/embodiment/embodiment-stage.js) (`EmbodimentStage`) + [overlay.js](apps-sdk/embodiment/overlay.js); persona tools (free) [api/_mcp-studio/persona-tools.js](api/_mcp-studio/persona-tools.js) → `/api/mcp-studio` (`create_agent_persona`, `get_agent_persona`, `persona_say`) and (paid) [api/_mcp3d/tools/studio.js](api/_mcp3d/tools/studio.js); shared inline-body artifact [api/_lib/embodiment-artifact.js](api/_lib/embodiment-artifact.js); identity store [api/_lib/persona-store.js](api/_lib/persona-store.js) (Postgres `agent_personas` + fs fallback + durable R2 GLB); reload route [api/mcp3d/persona.js](api/mcp3d/persona.js) `→ /api/mcp3d/persona`. Emotion/rig/lip-sync cores under [src/embodiment/](src/embodiment) + [src/voice/](src/voice). | Live | A generated avatar becomes a persistent, named body that renders inline in ChatGPT/Claude: it lip-syncs each reply, blends the matching expression + gesture, idles between turns, and reloads by `persona_id` in a fresh session (the id is the capability — no sign-in). Rides the universal canonicalize/retarget clip library; a rig without face morphs animates the jaw, a non-humanoid GLB falls back to a gentle idle (`decideRigMode`/`supportsCanonicalClips`) — never a bind-pose T-pose. Zero crypto/token surface. Tests: [tests/persona-store.test.js](tests/persona-store.test.js), [tests/api/persona-resolve-route.test.js](tests/api/persona-resolve-route.test.js), [tests/mcp-studio.test.js](tests/mcp-studio.test.js), [tests/embodiment-rig-mode.test.js](tests/embodiment-rig-mode.test.js). Evidence: [prompts/store-submissions/_generated/embodiment/](prompts/store-submissions/_generated/embodiment/). Store-submission prompt 07. |+| Embodiment: a living agent body in the chat | Hosted embed [pages/embodiment/embed.html](pages/embodiment/embed.html) `→ /embodiment/embed` (Vite input + vercel route, `frame-ancestors *`); engine [apps-sdk/embodiment/embodiment-stage.js](apps-sdk/embodiment/embodiment-stage.js) (`EmbodimentStage`) + [overlay.js](apps-sdk/embodiment/overlay.js); persona tools (free) [api/_mcp-studio/persona-tools.js](api/_mcp-studio/persona-tools.js) → `/api/mcp-studio` (`create_agent_persona`, `get_agent_persona`, `persona_say`) and (paid) [api/_mcp3d/tools/studio.js](api/_mcp3d/tools/studio.js); shared inline-body artifact [api/_lib/embodiment-artifact.js](api/_lib/embodiment-artifact.js); identity store [api/_lib/persona-store.js](api/_lib/persona-store.js) (Postgres `agent_personas` + fs fallback + durable R2 GLB); reload route [api/mcp3d/persona.js](api/mcp3d/persona.js) `→ /api/mcp3d/persona`; live chain-state feed [api/mcp3d/persona-identity.js](api/mcp3d/persona-identity.js) `→ /api/mcp3d/persona-identity` (polled only when the embed is opened with `?wallet=1`). Emotion/rig/lip-sync cores under [src/embodiment/](src/embodiment) + [src/voice/](src/voice). | Live | A generated avatar becomes a persistent, named body that renders inline in ChatGPT/Claude: it lip-syncs each reply, blends the matching expression + gesture, idles between turns, and reloads by `persona_id` in a fresh session (the id is the capability, no sign-in). Rides the universal canonicalize/retarget clip library; a rig without face morphs animates the jaw, a non-humanoid GLB falls back to a gentle idle (`decideRigMode`/`supportsCanonicalClips`), never a bind-pose T-pose. Zero crypto/token surface. Tests: [tests/persona-store.test.js](tests/persona-store.test.js), [tests/api/persona-resolve-route.test.js](tests/api/persona-resolve-route.test.js), [tests/api/persona-identity-route.test.js](tests/api/persona-identity-route.test.js), [tests/mcp-studio.test.js](tests/mcp-studio.test.js), [tests/embodiment-rig-mode.test.js](tests/embodiment-rig-mode.test.js). Evidence: [prompts/store-submissions/_generated/embodiment/](prompts/store-submissions/_generated/embodiment/). Store-submission prompt 07. || Claude.ai artifact embed + builder | Endpoint [api/artifact.js](api/artifact.js) `→ /api/artifact`, prebuilt viewer [public/artifact-viewer.bundle.js](public/artifact-viewer.bundle.js) (source [scripts/artifact-viewer/src.js](scripts/artifact-viewer/src.js), `npm run build:artifact-viewer`), builder page [public/artifact/index.html](public/artifact/index.html) `→ /artifact` + [README](public/artifact/README.md), contract [specs/CLAUDE_ARTIFACT.md](specs/CLAUDE_ARTIFACT.md), vendored sandbox CSP [public/claude-artifact-csp.txt](public/claude-artifact-csp.txt) (refresh: [scripts/refresh-claude-csp.mjs](scripts/refresh-claude-csp.mjs)). | Live | `GET /api/artifact?agent=<uuid>` returns ONE self-contained HTML document with three.js, GLTFLoader, the viewer and the agent GLB all inlined, because Claude's artifact sandbox CSP blocks every external script and fetch. Paste the URL into a Claude conversation and the agent renders inline. The builder page is the pre-flight: it lists real public agents that carry an embeddable avatar (`/api/agents/public?avatar=1`), renders the response in a sandboxed iframe under the same CSP Claude applies, and reports payload size, first paint and sandbox compliance before you paste. `?model=<glb url>` is the viewer-only lane (allowlisted https origins, SSRF-guarded, 6 MB cap). Tests: [tests/api/artifact.test.js](tests/api/artifact.test.js) pins the generated HTML against the vendored Claude CSP. || Spatial MCP (3D as a native response type) | Spec [specs/SPATIAL_MCP.md](specs/SPATIAL_MCP.md), pure validator/builder/lint [public/spatial-mcp/spatial-validator.js](public/spatial-mcp/spatial-validator.js) (published at `https://three.ws/spatial-mcp/spatial-validator.js`; server-side re-export [api/_lib/spatial-mcp.js](api/_lib/spatial-mcp.js)), npm package + conformance fixture corpus [packages/spatial-mcp/](packages/spatial-mcp) (`@three-ws/spatial-mcp`, CC0, drift-guarded byte-identical to the published module), validator tool [api/_mcp3d/tools/spatial.js](api/_mcp3d/tools/spatial.js) (`validate_spatial_response`, free), reference renderer [public/spatial-mcp/spatial-renderer.js](public/spatial-mcp/spatial-renderer.js) + demo/checker [public/spatial-mcp/index.html](public/spatial-mcp/index.html) + [public/spatial-mcp/demo.js](public/spatial-mcp/demo.js) `→ /spatial-mcp`, docs [docs/spatial-mcp.md](docs/spatial-mcp.md). | Live · both stores | Open (CC0) shape for returning a live, interactive 3D scene as a first-class MCP tool result (scene GLB, camera, environment, animation, AR handoff, affordances) instead of a URL. Every three.ws 3D generator emits a conformant artifact under `structuredContent.spatial`; the validator returns actionable errors, not a boolean; the framework-free reference renderer displays any conformant payload — including one transformed from a foreign tool result (portability proof at `/spatial-mcp`). The page runs the real validator in the browser: every rendered payload shows its verdict, and a paste-in checker validates arbitrary payloads as you type (with a deliberately broken example) so an implementer debugs an adapter without leaving the page. Zero coin surface — reusable in the OpenAI free app. Tests: [tests/spatial-mcp.test.js](tests/spatial-mcp.test.js), render smoke [tests/e2e/spatial-mcp-render.spec.js](tests/e2e/spatial-mcp-render.spec.js). Evidence: [prompts/store-submissions/_generated/spatial-mcp/](prompts/store-submissions/_generated/spatial-mcp/). Store-submission prompt 20. || AR-ready exports ("View in your space") | Device-routing core [api/_lib/ar-launch.js](api/_lib/ar-launch.js), UA-branched launch endpoint [api/ar.js](api/ar.js) `→ /api/ar`, MCP tool [api/_mcp3d/tools/ar.js](api/_mcp3d/tools/ar.js) (`export_ar`, free), in-viewer AR button [public/viewer.html](public/viewer.html), docs [docs/ar.md](docs/ar.md). | Live · both stores | `GET /api/ar?src=<glb>` branches on the request User-Agent server-side: iOS → Apple Quick Look (USDZ generated from the GLB on the fly by model-viewer's three.js USDZExporter — real conversion, no server USD tooling), Android → 302 Google Scene Viewer ARCore intent with browser fallback, desktop → WebGL viewer. Bad input rejected at the boundary with a designed error page. `export_ar` returns the AR launch link + a conformant Spatial-MCP artifact; response is OpenAI-clean (no ids/coin surface). `kind=avatar` is the living-agent lane: the launch page leads with a "Bring it to life" handoff into `/irl?avatar=<glb>` (avatar-producing tools return `irlUrl` automatically), and Android serves the launch page instead of the blind Scene Viewer redirect so the living path stays visible. Shared links unfurl: the launch page's `og:image` points at `GET /api/render/glb?glbUrl=` ([api/render/glb.js](api/render/glb.js), server-side PNG of the actual model, CDN-cached a day) and the page carries "Create your own" → `/ar` conversion CTAs. Tests: [tests/ar-export.test.js](tests/ar-export.test.js). Evidence: [prompts/store-submissions/_generated/ar/](prompts/store-submissions/_generated/ar/). Store-submission prompt 21. |diff --git a/api/_lib/embed-doctor.js b/api/_lib/embed-doctor.jsindex d00bfa375..ceb3089a8 100644--- a/api/_lib/embed-doctor.js+++ b/api/_lib/embed-doctor.js@@ -278,6 +278,21 @@ export function analyze(obs) {}// ── 3. The element ────────────────────────────────────────────────────────+ if (!el && obs?.probeFailed) {+ // The DOM was never read, so "no element" is not a fact we hold. Saying it+ // anyway would send a developer hunting for a tag that is right there.+ findings.push(+ unknown(+ 'page_not_inspected',+ 'The page could not be inspected in the time available',+ obs.timedOut+ ? 'The page was still busy when the time budget ran out, so its contents were never read. A page that keeps the browser occupied this long usually has heavy scripts of its own running ahead of the embed.'+ : 'The browser closed the page before its contents could be read, so nothing below the loader is knowable.',+ { timedOut: !!obs.timedOut },+ ),+ );+ return { verdict: verdictFor(findings), findings: rank(findings), summary: summarize(findings, obs) };+ }if (!el || !el.count) {findings.push(finding(@@ -972,12 +987,19 @@ function instrument(page) {/** Everything a diagnosis needs from a booted page, once it has settled. */async function harvest(page, { recorders, response, bootMs, platformOrigin, screenshot }) {- const probe = await page.evaluate(inPageProbe, EMBED_SELECTOR, SOURCE_ATTRIBUTES).catch(() => ({- scripts: [],- element: null,- webgl: { available: null, renderer: null },- title: '',- }));+ // A page that never yields its main thread (or one the watchdog closed) makes+ // the probe reject. That is "we could not look", not "there is nothing there",+ // and the difference has to survive into the report: honesty rule 1.+ let probeFailed = false;+ const probe = await page.evaluate(inPageProbe, EMBED_SELECTOR, SOURCE_ATTRIBUTES).catch(() => {+ probeFailed = true;+ return {+ scripts: [],+ element: null,+ webgl: { available: null, renderer: null },+ title: '',+ };+ });const headers = (() => {try {@@ -1020,9 +1042,38 @@ async function harvest(page, { recorders, response, bootMs, platformOrigin, screpageErrors: recorders.pageErrors,agent,screenshot: shot,+ probeFailed,};}+/**+ * Close the page once the whole inspection has outstayed its welcome.+ *+ * Every individual step is already bounded (navigation, boot budget, agent+ * lookup), but the in-page probe is not: a page that pegs its main thread never+ * runs it, and `page.evaluate` has no deadline of its own. Without this, one+ * such page holds a request and a chromium instance open indefinitely. Closing+ * the page rejects whatever is pending, and every caller of a page API here+ * already treats a rejection as "unknown", so the request unwinds into an+ * honest inconclusive report instead of hanging.+ */+function pageWatchdog(page, ms) {+ const state = { firedAt: null };+ const timer = setTimeout(() => {+ state.firedAt = Date.now();+ page.close().catch(() => {});+ }, ms);+ if (typeof timer.unref === 'function') timer.unref();+ state.clear = () => clearTimeout(timer);+ return state;+}++/** How long past the caller's boot budget the probe, screenshot and agent+ * lookup are allowed before the watchdog closes the page. Sized from the two+ * bounded calls inside `harvest` (a 6 s agent lookup and a screenshot) with+ * room to spare, and still well inside the handler's 60 s ceiling. */+const HARVEST_GRACE_MS = 20000;+/*** Diagnose a live URL.*@@ -1045,6 +1096,7 @@ export async function collectFromUrl({const browser = await getBrowser();const page = await browser.newPage();const target = { kind: 'url', url };+ const watchdog = pageWatchdog(page, budgetMs + HARVEST_GRACE_MS);try {await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36 three.ws-EmbedDoctor/1.0 (+https://three.ws/embed-doctor)',@@ -1066,8 +1118,9 @@ export async function collectFromUrl({}const bootMs = await waitForEmbed(page, EMBED_SELECTOR, budgetMs);const obs = await harvest(page, { recorders, response, bootMs, platformOrigin, screenshot });- return { target, ...obs };+ return { target, ...obs, timedOut: watchdog.firedAt !== null };} finally {+ watchdog.clear();await page.close().catch(() => {});}}@@ -1096,6 +1149,7 @@ export async function collectFromSnippet({const browser = await getBrowser();const page = await browser.newPage();const target = { kind: 'snippet', snippet: String(snippet).slice(0, 4000) };+ const watchdog = pageWatchdog(page, budgetMs + HARVEST_GRACE_MS);try {const recorders = instrument(page);// Served from the platform origin so relative URLs and module imports@@ -1119,8 +1173,9 @@ export async function collectFromSnippet({response = await page.goto(sandboxUrl, { waitUntil: 'domcontentloaded', timeout: 25000 });const bootMs = await waitForEmbed(page, EMBED_SELECTOR, budgetMs);const obs = await harvest(page, { recorders, response, bootMs, platformOrigin, screenshot });- return { target, ...obs };+ return { target, ...obs, timedOut: watchdog.firedAt !== null };} finally {+ watchdog.clear();await page.close().catch(() => {});}}@@ -1137,6 +1192,7 @@ export async function diagnose(input) {target: observations.target,screenshot: observations.screenshot || null,pageTitle: observations.page?.title || null,+ timedOut: !!observations.timedOut,durationMs: Date.now() - started,};}diff --git a/api/_mcp/tools/crypto-data.js b/api/_mcp/tools/crypto-data.jsindex a52d682d5..36f1b6529 100644--- a/api/_mcp/tools/crypto-data.js+++ b/api/_mcp/tools/crypto-data.js@@ -1,6 +1,6 @@-// crypto_data + token_snapshot — MCP front door onto the /api/v1/x aggregator+// crypto_data + token_snapshot: MCP front door onto the /api/v1/x aggregator// (api/v1/_providers.js). Generated from the live registry so the toolset-// grows automatically as provider prompts land — no hand-enumerated endpoint+// grows automatically as provider prompts land, with no hand-enumerated endpoint// list to keep in sync.//// Design (owner-approved, x402-catalog campaign work order 10):@@ -8,13 +8,13 @@// (a 30-tool flood degrades agent tool selection).//// Both tools run calls through the SAME engine the REST aggregator uses-// (executeUpstream, with the platform's own upstream key) — never re-fetch an+// (executeUpstream, with the platform's own upstream key), and never re-fetch an// upstream directly. An endpoint marked `free` in the registry is served// within the identical per-IP quota the REST free lane enforces// (api/v1/x/[...slug].js `serveFreeLane`) so the two doors share one budget// instead of doubling it. A caller who exhausts the quota, or calls an// endpoint with no free tier, gets a -32402 JSON-RPC error naming the exact-// REST URL + USDC price to pay via x402 — the platform's one real payment+// REST URL + USDC price to pay via x402, the platform's one real payment// rail, never a second payment flow invented for MCP.import { ENDPOINT_INDEX, providerCatalog } from '../../v1/_providers.js';@@ -44,7 +44,7 @@ function errorResult(message, data) {}// Same per-IP identity the REST free lane keys its quota by. `req` is absent-// under some transports (unit tests, non-HTTP dispatch) — fall back to the+// under some transports (unit tests, non-HTTP dispatch), so fall back to the// caller's account id, then a shared anonymous bucket.function callerKey(auth, req) {if (req) {@@ -65,14 +65,14 @@ function listPairs() {/** One line per endpoint, generated fresh from the live registry at call time. */function describePairs() {return providerCatalog()- .flatMap((p) => p.endpoints.map((e) => `${p.id}/${e.id} — ${e.summary}`))+ .flatMap((p) => p.endpoints.map((e) => `${p.id}/${e.id}: ${e.summary}`)).join('\n');}/*** Run one aggregator call, honoring the endpoint's free-tier quota (if any).* Shared by both tools so token_snapshot's fan-out and crypto_data's direct- * call enforce identically. Never throws — every outcome is a tagged result+ * call enforce identically. Never throws: every outcome is a tagged result* so callers can degrade gracefully (token_snapshot) or surface a clean* payment-required error (crypto_data).*/@@ -163,7 +163,7 @@ export const toolDefs = [},params: {type: 'object',- description: 'Endpoint-specific query params — see the endpoint summary in the tool description for required fields.',+ description: 'Endpoint-specific query params. See the endpoint summary in the tool description for required fields.',additionalProperties: true,default: {},},@@ -191,7 +191,7 @@ export const toolDefs = [provider: result.provider,endpoint: result.endpoint,amount_usdc_atomics: result.priceAtomics,- pay_via: `${result.restUrl} — send an X-PAYMENT header (see docs/x402.md) for pay-per-call USDC`,+ pay_via: `${result.restUrl}: send an X-PAYMENT header (see docs/x402.md) for pay-per-call USDC`,...(result.reset ? { free_tier_reset: result.reset } : {}),});}@@ -205,10 +205,10 @@ export const toolDefs = [description:'One-call snapshot for a Solana token mint, fanning out to whichever free crypto-data ' +'providers are registered on this deployment (DexScreener pairs, Jupiter price, Solana RPC ' +- 'supply) and merging what answers — degrades gracefully around any provider that is absent, ' ++ 'supply) and merging what answers. Degrades gracefully around any provider that is absent, ' +'unconfigured, or fails, never throwing on a partial result. Example mint: the $THREE CA ' +'"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump". For pump.fun-specific bonding-curve / ' +- 'launch data use the pump_snapshot tool instead — this tool covers general market data.',+ 'launch data use the pump_snapshot tool instead. This tool covers general market data.',inputSchema: {type: 'object',required: ['mint'],@@ -221,7 +221,7 @@ export const toolDefs = [const mint = String(args?.mint || '').trim();if (!mint) return errorResult('"mint" is required', { error: 'validation_error' });- // Fixed, small candidate set (not every registered provider) — a+ // Fixed, small candidate set (not every registered provider): a// snapshot is meant to answer "what is this token" in one call, not// fan out to every provider that happens to accept a mint-shaped param.const CANDIDATES = [diff --git a/api/_mcp/tools/embed.js b/api/_mcp/tools/embed.jsindex 033d90895..5b423bebd 100644--- a/api/_mcp/tools/embed.js+++ b/api/_mcp/tools/embed.js@@ -1,10 +1,10 @@-// MCP tool: get_embed_code — hand an agent a copy-paste embed snippet for a+// MCP tool: get_embed_code. Hands an agent a copy-paste embed snippet for a// three.ws 3D avatar, on-chain agent, or Forge creation. "As easy as embedding a// YouTube video": one call returns the <iframe> HTML, the shareable URL, the// oEmbed discovery URL, and a social-card thumbnail.//// The iframe markup + canonical URL shapes come from the shared builder in-// api/_lib/embed.js — the same one the /api/oembed provider uses — so embed+// api/_lib/embed.js (the same one the /api/oembed provider uses), so embed// output never drifts between the oEmbed surface and this tool.import { sql } from '../../_lib/db.js';@@ -31,7 +31,7 @@ function rpcError(code, message, data) {}// A designed, actionable error a chat client renders as text (not a thrown-// JSON-RPC fault) — used for "make it public first" style guidance.+// JSON-RPC fault), used for "make it public first" style guidance.function designedError(text, structured) {return {content: [{ type: 'text', text }],@@ -54,7 +54,7 @@ async function resolveTarget({ kind, args, auth, origin }) {`;if (!agent) throw new Error('agent not found');// Mirror get_avatar's visibility check: a private item is embeddable only- // by its owner — everyone else must publish (public/unlisted) it first.+ // by its owner. Everyone else must publish (public/unlisted) it first.if (agent.is_public === false && agent.user_id !== auth.userId) {return {error: designedError(@@ -100,7 +100,7 @@ async function resolveTarget({ kind, args, auth, origin }) {};}- // Forge creation — Forge share pages are public by id (no per-user+ // Forge creation: Forge share pages are public by id (no per-user// visibility), so the only gate is that the mesh actually finished rendering.if (!isUuid(args.creation_id)) throw rpcError(-32602, 'creation_id must be a uuid');const [creation] = await sql`@@ -150,8 +150,8 @@ export const toolDefs = [creation_id: { type: 'string', format: 'uuid', description: 'Embed a Forge 3D creation.' },// Bounds are clamped in the handler, not enforced by the schema, so an// out-of-range number yields a usable snippet instead of a hard error.- width: { type: 'integer', default: 480, description: 'Iframe width in px (clamped 240–1920).' },- height: { type: 'integer', default: 360, description: 'Iframe height in px (clamped 180–1080).' },+ width: { type: 'integer', default: 480, description: 'Iframe width in px (clamped 240-1920).' },+ height: { type: 'integer', default: 360, description: 'Iframe height in px (clamped 180-1080).' },autorotate: { type: 'boolean', default: true, description: 'Slowly auto-rotate the avatar.' },ar: { type: 'boolean', default: true, description: 'Offer an AR / view-in-room button on mobile.' },},@@ -206,7 +206,7 @@ export const toolDefs = [content: [{type: 'text',- text: `Embed snippet for "${title}" — paste it anywhere HTML is allowed:\n\n${embedHtml}\n\nShare URL: ${target.shareUrl}`,+ text: `Embed snippet for "${title}". Paste it anywhere HTML is allowed:\n\n${embedHtml}\n\nShare URL: ${target.shareUrl}`,},// A self-contained text/html artifact so MCP clients that render HTML// show a live preview of the embed (mirrors render_avatar / preview_3d).@@ -233,7 +233,7 @@ export const toolDefs = [openWorldHint: true,},description:- 'Turn an avatar or on-chain agent you own into a holder-only interactive 3D embed. Visitors must prove — with a real, server-verified Solana SPL token balance, never a client-reported number — they hold at least min_amount of mint before the live scene renders; below that they see a designed locked teaser with a connect-wallet CTA. mint defaults to $THREE but accepts any SPL mint at runtime. Returns a ready-to-paste <three-d> embed snippet.',+ 'Turn an avatar or on-chain agent you own into a holder-only interactive 3D embed. Visitors must prove, with a real, server-verified Solana SPL token balance and never a client-reported number, that they hold at least min_amount of mint before the live scene renders; below that they see a designed locked teaser with a connect-wallet CTA. mint defaults to $THREE but accepts any SPL mint at runtime. Returns a ready-to-paste <three-d> embed snippet.',inputSchema: {type: 'object',properties: {@@ -243,7 +243,7 @@ export const toolDefs = [},mint: {type: 'string',- description: `SPL token mint holders must have a balance of. Defaults to $THREE (${DEFAULT_GATE_MINT}) — pass a different mint to gate with another community's token.`,+ description: `SPL token mint holders must have a balance of. Defaults to $THREE (${DEFAULT_GATE_MINT}). Pass a different mint to gate with another community's token.`,},min_amount: {type: 'number',@@ -266,7 +266,7 @@ export const toolDefs = [if (!ownership.ok) {if (ownership.reason === 'not_owner') {throw new Error(- 'you do not own this asset — link the owning wallet (or account) to gate it',+ 'you do not own this asset: link the owning wallet (or account) to gate it',);}throw new Error(`embed asset "${args.asset_id}" not found`);@@ -305,7 +305,7 @@ export const toolDefs = [{type: 'text',text:- `Gated "${asset.name || args.asset_id}" — visitors need ≥ ${gate.minAmount} ${symbol} to unlock it. ` ++ `Gated "${asset.name || args.asset_id}": visitors need ≥ ${gate.minAmount} ${symbol} to unlock it. ` +`Paste this anywhere HTML is allowed:\n\n${snippet}`,},],diff --git a/api/_mcp/tools/garments.js b/api/_mcp/tools/garments.jsindex 9bb3425a1..067e82bb5 100644--- a/api/_mcp/tools/garments.js+++ b/api/_mcp/tools/garments.js@@ -113,7 +113,7 @@ export const toolDefs = [description:'Poll a generate_garment job. While running, reports the pipeline stage. When ' +'done, returns the published glb_url, manifest_url, thumbnail, measured bind ' +- 'coverage, and the occluded body regions — at that point the garment is already ' ++ 'coverage, and the occluded body regions. At that point the garment is already ' +'live in the wardrobe catalog.',inputSchema: {type: 'object',@@ -163,7 +163,7 @@ export const toolDefs = [? `Garment ${pub.garment_id} published: ${pub.glb_url} (${coverageText}, occludes ${pub.occludes?.join(', ') || 'nothing'}).`: pub.status === 'failed'? `Garment job failed: ${pub.error}`- : `Garment job ${pub.status} — stage: ${pub.stage}.`;+ : `Garment job ${pub.status}, stage: ${pub.stage}.`;return {content: [{ type: 'text', text: line }],structuredContent: pub,@@ -220,7 +220,7 @@ export const toolDefs = [content: [{type: 'text',text: garments.length- ? garments.map((g) => `${g.slot}/${g.id} v${g.version} — ${g.name}`).join('\n')+ ? garments.map((g) => `${g.slot}/${g.id} v${g.version}: ${g.name}`).join('\n'): 'The catalog is empty for that filter.',}],structuredContent: { garments, count: garments.length },diff --git a/api/_mcp/tools/memory.js b/api/_mcp/tools/memory.jsindex 2384053dd..df156698b 100644--- a/api/_mcp/tools/memory.js+++ b/api/_mcp/tools/memory.js@@ -1,4 +1,4 @@-// MCP memory tools — remember / recall / forget.+// MCP memory tools: remember / recall / forget.//// Exposes the agent-memory backend (api/agent-memory.js, table agent_memories)// as MCP tools so an agent connected to /api/mcp can persist, retrieve, and@@ -17,7 +17,7 @@ const VALID_TYPES = ['user', 'feedback', 'project', 'reference'];const RECENCY_HALF_LIFE_MS = 7 * 24 * 60 * 60 * 1000;// Designed "not your agent / not signed in" result. The task requires a helpful-// message, not a throw — anonymous x402 callers have no account at all, owners+// message, not a throw. Anonymous x402 callers have no account at all, owners// of a different agent get the same opaque answer so we don't leak existence.function ownershipError() {return {@@ -65,7 +65,7 @@ function tokenize(text) {// Blend lexical relevance to the query with salience and recency. With no// per-memory embeddings stored server-side, lexical overlap stands in for// semantic similarity; when a query matches nothing, lexical=0 and the order-// degrades cleanly to the salience+recency ranking the REST endpoint uses —+// degrades cleanly to the salience+recency ranking the REST endpoint uses,// never a failure mode. Returns a score in roughly [0,1].function scoreMemory(row, queryTokens, nowMs) {const haystack = new Set(tokenize(`${row.content} ${(row.tags || []).join(' ')}`));@@ -86,7 +86,7 @@ export const toolDefs = [{name: 'remember',title: 'Remember',- // Inserts a new row every call — additive write, never destructive.+ // Inserts a new row every call: additive write, never destructive.annotations: {readOnlyHint: false,destructiveHint: false,@@ -241,7 +241,7 @@ export const toolDefs = [{name: 'forget',title: 'Forget',- // Permanently deletes a stored memory — destructive.+ // Permanently deletes a stored memory: destructive.annotations: {readOnlyHint: false,destructiveHint: true,diff --git a/api/_mcp/tools/models.js b/api/_mcp/tools/models.jsindex e55138451..ec350812f 100644--- a/api/_mcp/tools/models.js+++ b/api/_mcp/tools/models.js@@ -20,7 +20,7 @@ async function safeFetchModel(url) {}// MCP tool annotations (2025-06-18 spec): all three tools are deterministic,-// pure inspections of a caller-supplied URL — same file, same report.+// pure inspections of a caller-supplied URL: same file, same report.// destructiveHint defaults to TRUE when omitted, so it is set explicitly.const INSPECTION_ANNOTATIONS = {readOnlyHint: true,@@ -50,7 +50,7 @@ function formatInspection(info) {? info.textures.map((t) =>- ` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`,+ ` • ${t.name || '(unnamed)'}: ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`,).join('\n'): ' (none)';@@ -73,7 +73,7 @@ function formatSuggestions(suggestions) {const tag ={ info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] ||s.severity.toUpperCase();- const est = s.estimate ? ` — ${s.estimate}` : '';+ const est = s.estimate ? ` (${s.estimate})` : '';return `[${tag}] ${s.id}: ${s.message}${est}`;}).join('\n');@@ -85,7 +85,7 @@ export const toolDefs = [title: 'Validate glTF/GLB model',annotations: INSPECTION_ANNOTATIONS,description:- 'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints — the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',+ 'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints: the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',inputSchema: {type: 'object',properties: {@@ -138,7 +138,7 @@ export const toolDefs = [title: 'Inspect glTF/GLB model',annotations: INSPECTION_ANNOTATIONS,description:- 'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection — no optimization advice.',+ 'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection, no optimization advice.',inputSchema: {type: 'object',properties: {diff --git a/api/_mcp/tools/oracle.js b/api/_mcp/tools/oracle.jsindex 468ef8d10..6b7294b94 100644--- a/api/_mcp/tools/oracle.js+++ b/api/_mcp/tools/oracle.js@@ -1,20 +1,20 @@-// Oracle MCP tools — conviction signal for autonomous agents.+// Oracle MCP tools: conviction signal for autonomous agents.//// Three tools, one mission: give any 3D AI agent on three.ws access to the// same Oracle conviction intelligence that drives the platform's own sniper// strategy and copy-trading systems.//-// oracle_top_plays — public, no auth needed. Returns the current top-scoring+// oracle_top_plays (public, no auth needed). Returns the current top-scoring// pump.fun launches ranked by Oracle conviction. Each play// carries a machine-readable recommendation: action (buy /// watch / skip), confidence, and a suggested size factor// so the agent never has to re-derive the trading signal.//-// oracle_coin — public. Full conviction verdict for one specific mint:+// oracle_coin (public). Full conviction verdict for one specific mint:// score, tier, four pillar scores, badges, and the same// agent-ready recommendation envelope.//-// oracle_arm_watch — requires account auth (scope: agents:write). Arms (or+// oracle_arm_watch requires account auth (scope: agents:write). Arms (or// updates) the caller's agent to act on the live Oracle// stream. Sets the conviction floor, category filters,// per-trade SOL cap, and simulate-vs-live mode. The@@ -34,11 +34,11 @@ const CATEGORIES = new Set([const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const REC = {- prime: { action: 'buy', confidence: 'high', size_factor: 1.0, note: 'top-conviction play — proven smart money + clean structure + on-narrative' },- strong: { action: 'buy', confidence: 'medium', size_factor: 0.75, note: 'strong conviction — favorable across multiple pillars' },- lean: { action: 'watch', confidence: 'low', size_factor: 0, note: 'leaning positive but not decisive — watch for confirmation' },- watch: { action: 'skip', confidence: 'low', size_factor: 0, note: 'inconclusive — no edge yet' },- avoid: { action: 'skip', confidence: 'high', size_factor: 0, note: 'structural or pedigree red flags — avoid' },+ prime: { action: 'buy', confidence: 'high', size_factor: 1.0, note: 'top-conviction play: proven smart money + clean structure + on-narrative' },+ strong: { action: 'buy', confidence: 'medium', size_factor: 0.75, note: 'strong conviction: favorable across multiple pillars' },+ lean: { action: 'watch', confidence: 'low', size_factor: 0, note: 'leaning positive but not decisive, watch for confirmation' },+ watch: { action: 'skip', confidence: 'low', size_factor: 0, note: 'inconclusive, no edge yet' },+ avoid: { action: 'skip', confidence: 'high', size_factor: 0, note: 'structural or pedigree red flags, avoid' },};function shapePlay(it) {@@ -94,12 +94,12 @@ export const toolDefs = [title: 'Oracle top conviction plays',annotations: LIVE_ANNOTATIONS,description:- "Get the current top pump.fun launches ranked by Oracle conviction score. Each play includes a score (0–100), tier (prime/strong/lean/watch/avoid), four pillar scores (pedigree/structure/narrative/momentum), and an agent-ready recommendation with a suggested size_factor. Use this to decide which coins to buy before they move. Filter by min_score or category to narrow the signal.",+ "Get the current top pump.fun launches ranked by Oracle conviction score. Each play includes a score (0-100), tier (prime/strong/lean/watch/avoid), four pillar scores (pedigree/structure/narrative/momentum), and an agent-ready recommendation with a suggested size_factor. Use this to decide which coins to buy before they move. Filter by min_score or category to narrow the signal.",inputSchema: {type: 'object',properties: {limit: { type: 'integer', minimum: 1, maximum: 20, default: 5, description: 'Number of plays to return (default 5, max 20).' },- min_score: { type: 'integer', minimum: 0, maximum: 100, default: 72, description: 'Minimum conviction score (0–100). Default 72 (strong+).' },+ min_score: { type: 'integer', minimum: 0, maximum: 100, default: 72, description: 'Minimum conviction score (0-100). Default 72 (strong+).' },category: { type: 'string', enum: [...CATEGORIES], description: 'Filter by narrative category (optional).' },network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },},@@ -112,7 +112,7 @@ export const toolDefs = [const category = CATEGORIES.has(args?.category) ? args.category : null;const rl = await limits.mcpIp(auth.rateKey || 'anon');- if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');+ if (!rl.success) return mcpErr('Rate limit exceeded. Try again in a moment.');// A degraded feed store is NOT an empty feed. Returning [] on a fault// rendered "no plays at this conviction floor, try lowering min_score",@@ -147,7 +147,7 @@ export const toolDefs = [title: 'Oracle verdict for one coin',annotations: LIVE_ANNOTATIONS,description:- "Get Oracle's full conviction verdict for a specific pump.fun coin by mint address. Returns the fused 0–100 conviction score, tier (prime/strong/lean/watch/avoid), all four pillar scores (pedigree = who's behind it, structure = how it's built, narrative = cultural fit, momentum = early trading signal), active badges (e.g. smart_money_early, narrative_match), and a machine-readable buy/watch/skip recommendation. If the coin isn't in the Oracle cache yet, it will be scored on-demand (may add ~1s latency).",+ "Get Oracle's full conviction verdict for a specific pump.fun coin by mint address. Returns the fused 0-100 conviction score, tier (prime/strong/lean/watch/avoid), all four pillar scores (pedigree = who's behind it, structure = how it's built, narrative = cultural fit, momentum = early trading signal), active badges (e.g. smart_money_early, narrative_match), and a machine-readable buy/watch/skip recommendation. If the coin isn't in the Oracle cache yet, it will be scored on-demand (may add ~1s latency).",inputSchema: {type: 'object',properties: {@@ -161,22 +161,22 @@ export const toolDefs = [const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';const mint = (args?.mint || '').trim();- if (!MINT_RE.test(mint)) return mcpErr('Invalid mint: must be a base58 Solana address (32–44 chars).');+ if (!MINT_RE.test(mint)) return mcpErr('Invalid mint: must be a base58 Solana address (32-44 chars).');const rl = await limits.mcpIp(auth.rateKey || 'anon');- if (!rl.success) return mcpErr('Rate limit exceeded — try again in a moment.');+ if (!rl.success) return mcpErr('Rate limit exceeded. Try again in a moment.');let scored;try {scored = await scoreCoin(mint, { network, classify: true, persist: true });} catch {- // Intel store / DB degraded — distinct from "coin unknown". Tell the+ // Intel store / DB degraded: distinct from "coin unknown". Tell the// agent it's transient so it retries rather than concluding the coin// doesn't exist.- return mcpErr(`Oracle is temporarily unavailable for ${mint} — the intel store is degraded. Retry shortly.`);+ return mcpErr(`Oracle is temporarily unavailable for ${mint}: the intel store is degraded. Retry shortly.`);}if (!scored) {- return mcpErr(`Coin ${mint} not found in Oracle — it may not have been observed on pump.fun yet.`);+ return mcpErr(`Coin ${mint} not found in Oracle. It may not have been observed on pump.fun yet.`);}const v = scored.verdict;@@ -224,7 +224,7 @@ export const toolDefs = [armed: { type: 'boolean', default: true, description: 'true to arm, false to disarm.' },mode: { type: 'string', enum: ['simulate', 'live'], default: 'simulate', description: "simulate = no real spend (safe default). live = real SOL from agent's wallet." },min_score: { type: 'integer', minimum: 0, maximum: 100, default: 72, description: 'Conviction floor to act on (72 = strong+; 90 = prime only).' },- min_tier: { type: 'string', enum: ['prime', 'strong', 'lean', 'watch'], description: 'Alternative to min_score — acts on this tier and above.' },+ min_tier: { type: 'string', enum: ['prime', 'strong', 'lean', 'watch'], description: 'Alternative to min_score: acts on this tier and above.' },categories: { type: 'array', items: { type: 'string', enum: [...CATEGORIES] }, description: 'Only act on coins in these narrative categories. Omit to act on all.' },per_trade_sol: { type: 'number', minimum: 0.001, maximum: 1, default: 0.05, description: 'Max SOL per single trade (default 0.05). Ignored in simulate mode.' },max_daily_sol: { type: 'number', minimum: 0, maximum: 10, default: 0.5, description: 'Daily SOL budget cap (default 0.5). The loop will not spend more in one day.' },@@ -240,7 +240,7 @@ export const toolDefs = [if (!auth.userId) return mcpErr('You must be signed in with a three.ws account to arm an agent watch.');const agentId = (args?.agent_id || '').trim();- if (!isUuid(agentId)) return mcpErr('Invalid agent_id — must be a UUID (get it from /api/agents or your dashboard).');+ if (!isUuid(agentId)) return mcpErr('Invalid agent_id: must be a UUID (get it from /api/agents or your dashboard).');if (!(await ownsAgent(auth.userId, agentId))) {return mcpErr(`Agent ${agentId} does not belong to your account.`);@@ -275,7 +275,7 @@ export const toolDefs = [watch: watch || { agent_id: agentId, network, ...cfg },track_record: summary || { total: 0, wins: 0, losses: 0, win_rate: null, realized_pnl_sol: 0 },message: cfg.armed- ? `Agent armed in ${cfg.mode} mode. The Oracle cron runs every 2 min — your first action will appear in /oracle?tab=activity once a qualifying coin is scored.`+ ? `Agent armed in ${cfg.mode} mode. The Oracle cron runs every 2 min, so your first action will appear in /oracle?tab=activity once a qualifying coin is scored.`: `Agent disarmed. No further Oracle actions will be taken.`,links: {activity: `https://three.ws/activity`,@@ -313,7 +313,7 @@ export const toolDefs = [if (!auth.userId) return mcpErr('Sign in to check your agent watch status.');const agentId = (args?.agent_id || '').trim();- if (!isUuid(agentId)) return mcpErr('Invalid agent_id — must be a UUID.');+ if (!isUuid(agentId)) return mcpErr('Invalid agent_id: must be a UUID.');if (!(await ownsAgent(auth.userId, agentId))) {return mcpErr(`Agent ${agentId} does not belong to your account.`);@@ -364,7 +364,7 @@ export const toolDefs = [mode: a.mode,outcome: a.outcome,pnl_sol: a.realized_pnl_sol,- // Open-position exit call — an agent reading its own status can act+ // Open-position exit call: an agent reading its own status can act// on this to close a position whose thesis has broken.exit_signal: a.exit_signal ?? null,acted_at: a.acted_at,diff --git a/api/_mcp/tools/pumpfun.js b/api/_mcp/tools/pumpfun.jsindex 04cea1106..7ad8b70f8 100644--- a/api/_mcp/tools/pumpfun.js+++ b/api/_mcp/tools/pumpfun.js@@ -7,7 +7,7 @@ function clamp(n, lo, hi, fallback) {}// MCP tool annotations (2025-06-18 spec): every pump.fun intel tool is a-// read-only view of a live upstream feed — never idempotent (the market moves),+// read-only view of a live upstream feed, never idempotent (the market moves),// never destructive. destructiveHint defaults to TRUE when omitted, so it is// set explicitly.const LIVE_FEED_ANNOTATIONS = {diff --git a/api/_mcp/tools/sign.js b/api/_mcp/tools/sign.jsindex 45adf15ec..da25adda6 100644--- a/api/_mcp/tools/sign.js+++ b/api/_mcp/tools/sign.js@@ -1,8 +1,8 @@// MCP tools for American Sign Language.//-// • list_sign_vocabulary (free) — the words that have a real sign, with the+// • list_sign_vocabulary (free): the words that have a real sign, with the// handshape/place/movement each one performs.-// • sign_text (free) — compile text into a signed utterance: the+// • sign_text (free): compile text into a signed utterance: the// performed timeline, and on request the// retargetable animation clip itself.//@@ -26,7 +26,7 @@ function rpcError(code, message) {return e;}-/** `HAPPY (1.9s) · T-O spelled (1.3s)` — the utterance as one readable line. */+/** `HAPPY (1.9s) · T-O spelled (1.3s)`, the utterance as one readable line. */function describeTimeline(timeline) {return timeline.map((s) => {@@ -117,7 +117,7 @@ export const toolDefs = [speed: {type: 'number',default: 1,- description: 'Playback rate, 0.25–1.5. Below 1 is a signer taking longer over the same signs.',+ description: 'Playback rate, 0.25-1.5. Below 1 is a signer taking longer over the same signs.',},max_seconds: {type: 'number',diff --git a/api/_mcp/tools/solana.js b/api/_mcp/tools/solana.jsindex ee27a09cf..a7720c836 100644--- a/api/_mcp/tools/solana.js+++ b/api/_mcp/tools/solana.js@@ -97,7 +97,7 @@ async function solanaPassport(asset, network) {}// MCP tool annotations (2025-06-18 spec): public, read-only views over the-// live on-chain attestation index — new attestations land between calls, so+// live on-chain attestation index. New attestations land between calls, so// not idempotent. destructiveHint defaults to TRUE when omitted, so it is set// explicitly.const ATTESTATION_READ_ANNOTATIONS = {@@ -170,7 +170,7 @@ export const toolDefs = [title: 'Get Solana agent passport',annotations: ATTESTATION_READ_ANNOTATIONS,description:- 'Full discovery card for a Solana agent: identity (Metaplex Core asset), owner wallet, reputation summary, latest validation result, and attestation schema endpoint. Equivalent to an ERC-8004 passport — use this when one tool call should answer "who is this agent and can I trust them?".',+ 'Full discovery card for a Solana agent: identity (Metaplex Core asset), owner wallet, reputation summary, latest validation result, and attestation schema endpoint. Equivalent to an ERC-8004 passport. Use this when one tool call should answer "who is this agent and can I trust them?".',inputSchema: {type: 'object',properties: {diff --git a/api/_mcp/tools/tokenize.js b/api/_mcp/tools/tokenize.jsindex 881b6782d..160752050 100644--- a/api/_mcp/tools/tokenize.js+++ b/api/_mcp/tools/tokenize.js@@ -28,13 +28,13 @@ export const toolDefs = [},description:'Mint a generated or owned GLB as a Metaplex Core NFT on Solana whose media is a ' +- 'LIVE, interactive 3D viewer (the rigged glTF model under animation_url — not a static ' ++ 'LIVE, interactive 3D viewer (the rigged glTF model under animation_url, not a static ' +'image). Bakes provenance (creator, prompt, generation model, parent lineage, timestamp) ' +'into the metadata AND appends a signed, independently-verifiable record to the ' +'agent_actions provenance ledger; enforces capped creator royalties on secondary sales. ' +'Supply an owned avatar_id or a glb_url, and a recipient (owner_wallet, or your OAuth-linked ' +'Solana wallet). Devnet by default; pass network="mainnet" for a real mainnet mint. Idempotent ' +- '— a repeat call for the same asset returns the same mint. Royalty is capped at ' ++ '(a repeat call for the same asset returns the same mint). Royalty is capped at ' +`${TOKENIZE_3D_ROYALTY_CAP_BPS / 100}%. Naming parent_mint (a remix/derivative on mainnet) ` +"routes the parent creator's royalty slice out of THIS mint's fee as a real on-chain USDC " +'transfer. Returns the mint address, explorer + viewer links, royalty terms, the provenance ' +@@ -94,7 +94,7 @@ export const toolDefs = [async handler(args, auth) {try {// The remix-royalty split (task 4) must only ever split a fee that was- // ACTUALLY collected for this exact call — a genuine per-call x402+ // ACTUALLY collected for this exact call: a genuine per-call x402// settlement (auth.x402Paid), never a subscription window or an OAuth// bypass (both real access, but no fresh fee here to split).const mintFeeAtomicsCollected =@@ -126,7 +126,7 @@ export const toolDefs = [(result.explorer_tx_url ? `Tx: ${result.explorer_tx_url}\n` : '') +`Viewer: ${result.viewer_url}\n` +`Royalty: ${result.royalty.percent}% (cap ${result.royalty.cap_basis_points / 100}%)` +- (result.royalty.capped ? ` — requested ${result.royalty.requested_basis_points / 100}%, clamped` : '') ++ (result.royalty.capped ? ` (requested ${result.royalty.requested_basis_points / 100}%, clamped)` : '') +(result.provenance_ledger? `\nProvenance: ledger action #${result.provenance_ledger.action_id} (${result.provenance_ledger.signed ? 'signed' : 'unsigned'})`: '') +@@ -135,7 +135,7 @@ export const toolDefs = [? `\nRemix royalty: ${result.remix_royalty.creator_usd} USDC paid to the source creator (${result.remix_royalty.creator_tx})`: `\nRemix royalty: not paid (${result.remix_royalty.reason})`: '')- : `Mint in progress for this asset — read it back with get_3d_asset_onchain once it confirms.`;+ : `Mint in progress for this asset. Read it back with get_3d_asset_onchain once it confirms.`;return { content: [{ type: 'text', text }], structuredContent: result };} catch (err) {if (isHandled(err)) return toolError(err.message);@@ -146,7 +146,7 @@ export const toolDefs = [{name: 'get_3d_asset_onchain',title: 'Resolve a 3D NFT to its live asset + provenance',- // A read over live on-chain state — the holder can change between calls, so+ // A read over live on-chain state: the holder can change between calls, so// not idempotent. Open-world (reads the Solana network).annotations: {readOnlyHint: true,@@ -157,8 +157,8 @@ export const toolDefs = [description:'Resolve a Solana mint address to its live 3D asset: current holder, the interactive ' +'viewer link + GLB (confirmed live), baked provenance (creator, prompt, model, lineage, ' +- 'timestamp), and the enforced on-chain royalty terms. Works on any Metaplex Core mint — ' +- 'assets minted through three.ws also return their platform launch record. Read-only, public.',+ 'timestamp), and the enforced on-chain royalty terms. Works on any Metaplex Core mint. ' ++ 'Assets minted through three.ws also return their platform launch record. Read-only, public.',inputSchema: {type: 'object',properties: {diff --git a/api/_mcp3d/pricing.js b/api/_mcp3d/pricing.jsindex 9bec27d46..8d27ee446 100644--- a/api/_mcp3d/pricing.js+++ b/api/_mcp3d/pricing.js@@ -91,13 +91,43 @@ export function priceFor(toolName) {return TOOL_PRICING[toolName] || null;}+// Tools deliberately served at no per-call charge: discovery, status polling,+// previews, local analysis, and the persona/identity ops whose authorization is+// the 120-bit persona_id capability rather than a payment. Listing them+// explicitly (instead of letting "absent from TOOL_PRICING" silently mean free)+// is what lets tests/api/mcp-3d-challenge.test.js assert that EVERY catalog tool+// is a deliberate decision: add a GPU-backed tool to the catalog without pricing+// it and the classification test fails, rather than the tool shipping free. That+// silent-free failure is exactly the outage this module was written to end.+export const FREE_TOOLS = Object.freeze(+ new Set([+ 'getting_started',+ 'generation_status',+ 'preview_3d',+ 'save_avatar',+ 'create_agent_persona',+ 'get_agent_persona',+ 'persona_say',+ 'validate_spatial_response',+ 'export_ar',+ 'verify_provenance',+ 'persona_identity',+ 'persona_tip',+ 'persona_send',+ 'inspect_model',+ 'optimize_model',+ 'list_animations',+ 'animation_signature',+ 'find_similar_animations',+ 'text_to_animation',+ ]),+);+// The x402 `amount` (atomic-unit string) for a studio tools/call, or null for-// free tools (getting_started, generation_status, preview_3d, list_animations,-// inspect_model, optimize_model, save_avatar). Tier-priced tools read the-// caller's `tier` argument so the 402 quote, the verified payment, and the-// settled charge all match the work actually requested; an unknown tier-// resolves to the standard price (resolveTier's fallback) rather than-// under-charging.+// the free tools above. Tier-priced tools read the caller's `tier` argument so+// the 402 quote, the verified payment, and the settled charge all match the work+// actually requested; an unknown tier resolves to the standard price+// (resolveTier's fallback) rather than under-charging.export function studioX402Amount(toolName, args) {if (TIER_PRICED_TOOLS.has(toolName)) {return String(priceAtomicsForTier(args?.tier || DEFAULT_TIER));diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 686dee36a..2d233c7c8 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -317,6 +317,15 @@ export async function recordCellRead(ip, cell) {}let _tableReady = false;+// Exported so every other surface that READS irl_pins can provision it through the+// one definition that owns it. api/irl/world-lines.js joins this table on its two+// coordinate feeds and used to 500 with a bare `relation "irl_pins" does not exist`+// on a database where no pin had ever been placed. Re-declaring the DDL there would+// have forked the schema; this shares it, and the module-level _tableReady flag makes+// the second caller a no-op.+export async function ensurePinsSchema() {+ return ensureTable();+}async function ensureTable() {if (_tableReady) return;// Critical bootstrap — the base table + proximity/expiry indexes. These arediff --git a/api/irl/share.js b/api/irl/share.jsindex 0e9fea2d7..bb226001b 100644--- a/api/irl/share.js+++ b/api/irl/share.js@@ -30,6 +30,7 @@ import { getSessionUser } from '../_lib/auth.js';import { readDeviceToken } from '../_lib/irl-auth.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { randomToken } from '../_lib/crypto.js';+import { isUuid } from '../_lib/validate.js';import { putObject, publicUrl } from '../_lib/r2.js';import { logIrlEvent, ensureIrlAnalyticsSchema, hashDeviceToken } from '../_lib/irl-analytics.js';@@ -52,6 +53,10 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const pinId = (url.searchParams.get('pinId') || '').trim();if (!pinId) return error(res, 400, 'bad_request', 'pinId is required');+ // The lookup below casts this straight to ::uuid, so a malformed id reaches+ // Postgres as `invalid input syntax for type uuid` and 500s a request whose+ // only fault is a typo. Shape-check it here and answer the designed 400.+ if (!isUuid(pinId)) return error(res, 400, 'bad_request', 'pinId must be a pin uuid');const session = await getSessionUser(req).catch(() => null);const deviceToken = readDeviceToken(req);@@ -76,7 +81,7 @@ export default wrap(async (req, res) => {(session && pin.user_id === session.id) ||(deviceToken && pin.device_token === deviceToken);if (!owns) return error(res, 403, 'forbidden', 'you can only share your own placement');- if (pin.published === false) return error(res, 409, 'not_shareable', 'unpublish this pin first if you want it private — a private pin can\'t be turned into a public link');+ if (pin.published === false) return error(res, 409, 'not_shareable', 'make this pin public before you share it: a private placement can\'t become a public link');if (pin.hidden_at) return error(res, 409, 'not_shareable', 'this pin is under review and can\'t be shared right now');const token = randomToken(16);diff --git a/api/irl/share/[token].js b/api/irl/share/[token].jsindex 41e935229..3a931487f 100644--- a/api/irl/share/[token].js+++ b/api/irl/share/[token].js@@ -8,8 +8,8 @@* not a generic logo) and a single "Place your own agent" CTA back to /irl —* the growth loop this whole feature exists for.*- * Privacy: the page title/description ever renders the pin's caption or the- * agent's name — NEVER coordinates, NEVER the owner's identity. Same rule the+ * Privacy: the page title/description only ever renders the pin's caption or the+ * agent's name. NEVER coordinates, NEVER the owner's identity. Same rule the* rest of /api/irl/pins already enforces on every public projection.*/diff --git a/api/irl/world-lines.js b/api/irl/world-lines.jsindex c5c06a400..938f0202f 100644--- a/api/irl/world-lines.js+++ b/api/irl/world-lines.js@@ -102,6 +102,14 @@ function haversineM(lat1, lng1, lat2, lng2) {let _tableReady = false;async function ensureTables() {if (_tableReady) return;+ // Every coordinate feed here JOINs irl_pins for the anchor's precise position, so+ // this table is a hard dependency, not an optional one. Provision it through the+ // definition that owns it (api/irl/pins.js) rather than a second copy of the DDL:+ // on a database where no pin has ever been placed, `nearby` and the single-quest+ // read otherwise 500 with a raw `relation "irl_pins" does not exist`. Imported+ // lazily so the pins handler's module graph only loads when a World Line is used.+ const { ensurePinsSchema } = await import('./pins.js');+ await ensurePinsSchema();await sql`CREATE TABLE IF NOT EXISTS irl_world_lines (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,@@ -180,8 +188,11 @@ function routeOf(req) {const isLive = `hidden_at IS NULL AND (expires_at IS NULL OR expires_at > NOW())`;export default wrap(async (req, res) => {- cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'], credentials: true });- if (req.method === 'OPTIONS') return res.end();+ // `methods` is written straight into the header, so an ARRAY emits three+ // separate access-control-allow-methods lines instead of one list. Pass the+ // comma string every neighbouring handler passes, and let cors() answer the+ // preflight itself rather than calling res.end() a second time behind it.+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;await ensureTables();const { action, id } = routeOf(req);diff --git a/api/kol/[action].js b/api/kol/[action].jsindex 4f34cb63e..67676ecd7 100644--- a/api/kol/[action].js+++ b/api/kol/[action].js@@ -58,27 +58,70 @@ async function _fetchBirdeye(addr, apiKey) {}}-function _normalizePortfolio(addr, portfolio) {- const items = portfolio?.items ?? [];+// Birdeye's /v1/wallet/portfolio is a HOLDINGS endpoint: it returns the wallet's+// current token positions and their USD value. It carries no realized P&L, no win+// rate and no trade count, so this proxy reports holdings under holdings names.+// The row it used to emit dressed them up as a P&L card instead: `realizedPnl`,+// `winRate` and `totalTrades` were hardcoded zeros Birdeye never sends,+// `unrealizedPnl` was really the portfolio's total USD value, and `topToken.pnl`+// was the top holding's value. Downstream (`get_wallet_portfolio` in+// packages/kol-mcp) rendered all four to agents as measured P&L. Real per-wallet+// P&L is FIFO-computed from the wallet's own on-chain trades by+// src/kol/wallet-pnl.js and merged in by _walletPnl below.+function _normalizeHoldings(addr, portfolio) {+ const items = Array.isArray(portfolio?.items) ? portfolio.items : [];let topToken = null;let maxVal = 0;+ let summedUsd = 0;for (const item of items) {- const val = item.valueUsd ?? 0;- if (val > maxVal) {- maxVal = val;- topToken = { symbol: item.symbol ?? '?', pnl: val };+ const valueUsd = Number(item?.valueUsd) || 0;+ summedUsd += valueUsd;+ if (valueUsd > maxVal) {+ maxVal = valueUsd;+ topToken = { symbol: item?.symbol ?? '?', valueUsd };}}+ const totalUsd = Number(portfolio?.totalUsd);return {address: addr,- realizedPnl: portfolio?.realizedPnl ?? 0,- unrealizedPnl: portfolio?.unrealizedPnl ?? portfolio?.totalUsd ?? 0,- winRate: portfolio?.winRate ?? 0,- totalTrades: portfolio?.totalTrades ?? 0,+ totalUsd: Number.isFinite(totalUsd) ? totalUsd : summedUsd,+ holdings: items.length,topToken,};}+// P&L window this proxy reports. The tracker board is window-selectable; this is+// a single-wallet card, so it answers one question ("how has this wallet traded+// lately") with the widest window the FIFO engine keeps cheap.+const PNL_WINDOW = '30d';+const NO_PNL = {+ realizedPnl: null,+ winRate: null,+ totalTrades: null,+ volumeUsd: null,+ pnlSource: null,+ pnlWindow: PNL_WINDOW,+};++// Real FIFO P&L over the wallet's own on-chain trades. No trade history for the+// wallet (no configured trade source, or none inside the window) is NOT a flat+// record: every P&L field stays null so a caller can tell "unknown" from "broke+// even". Same rule for win rate with no closed trades: a wallet that has only+// bought has no win rate yet, which is not a 0% one.+async function _walletPnl(addr) {+ const { getWalletPnl } = await import('../../src/kol/wallet-pnl.js');+ const pnl = await getWalletPnl({ wallet: addr, window: PNL_WINDOW }).catch(() => null);+ if (!pnl || pnl.trades === 0) return NO_PNL;+ return {+ realizedPnl: pnl.realizedUsd,+ winRate: pnl.closedTrades > 0 ? pnl.winRate : null,+ totalTrades: pnl.trades,+ volumeUsd: pnl.volumeUsd,+ pnlSource: 'onchain-fifo',+ pnlWindow: PNL_WINDOW,+ };+}+async function handleWallets(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -105,8 +148,13 @@ async function handleWallets(req, res) {await Promise.allSettled(uncached.map(async (addr) => {try {- const portfolio = await _fetchBirdeye(addr, apiKey);- _setCache(addr, _normalizePortfolio(addr, portfolio));+ // _walletPnl never rejects, so only a Birdeye failure reaches the+ // catch: the holdings half is what this endpoint exists to proxy.+ const [portfolio, pnl] = await Promise.all([+ _fetchBirdeye(addr, apiKey),+ _walletPnl(addr),+ ]);+ _setCache(addr, { ..._normalizeHoldings(addr, portfolio), ...pnl });} catch (err) {// The negative cache bounds this log to once per address per// NEG_CACHE_TTL window, so an outage can't flood the function logs.diff --git a/api/labor/agent.js b/api/labor/agent.jsindex 3c77c0f46..7b74f5661 100644--- a/api/labor/agent.js+++ b/api/labor/agent.js@@ -1,4 +1,4 @@-// GET /api/labor/agent?agentId=… — one agent's labor-market record for the+// GET /api/labor/agent?agentId=… returns one agent's labor-market record for the// profile "Work" tab: bounties it posted, jobs it did, total $THREE earned and// spent, reputation, and its autonomy policy. Public read (real aggregates only).diff --git a/api/labor/bid.js b/api/labor/bid.jsindex 8808a8d54..8aad241e1 100644--- a/api/labor/bid.js+++ b/api/labor/bid.js@@ -1,8 +1,8 @@-// POST /api/labor/bid — a worker agent (owned by the caller) bids on an open+// POST /api/labor/bid: a worker agent (owned by the caller) bids on an open// bounty. Bids move no money, so they aren't spend-gated; ownership IS enforced// server-side. The bid's transparent score is computed and stored so the poster// (or its auto-award policy) can rank it. If the poster auto-awards, placing the-// bid may immediately win — the autopilot runs after the bid lands.+// bid may immediately win, since the autopilot runs after the bid lands.import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';diff --git a/api/labor/bounty.js b/api/labor/bounty.jsindex 6568e3d7d..6b81dc503 100644--- a/api/labor/bounty.js+++ b/api/labor/bounty.js@@ -1,4 +1,4 @@-// GET /api/labor/bounty?id=… — one bounty with its live bids (the negotiation)+// GET /api/labor/bounty?id=… returns one bounty with its live bids (the negotiation)// and its job (if awarded). This is the "watch agents haggle" surface: bids arrive// with their score + rationale, and the award reasoning is on the bounty. Public read.diff --git a/api/labor/feed.js b/api/labor/feed.jsindex 4d2cab181..ffce6f231 100644--- a/api/labor/feed.js+++ b/api/labor/feed.js@@ -1,4 +1,4 @@-// GET /api/labor/feed — the live Agent Labor Market feed.+// GET /api/labor/feed: the live Agent Labor Market feed.// Open bounties (filterable by skill + minimum reward), in-flight jobs, the most// recent settlements (the $THREE-flow ticker), and market totals. Public read.diff --git a/api/labor/policy.js b/api/labor/policy.jsindex 4e6f6aedc..46b48c054 100644--- a/api/labor/policy.js+++ b/api/labor/policy.js@@ -1,4 +1,4 @@-// /api/labor/policy — read or set an agent's labor-market autonomy policy.+// /api/labor/policy: read or set an agent's labor-market autonomy policy.// GET ?agentId=… → the agent's policy (public; powers the "for hire" badge).// PUT { agentId, … } → owner-gated upsert of the worker/poster autonomy config.diff --git a/api/launchpad/get.js b/api/launchpad/get.jsindex 935c372a2..c37d32bd6 100644--- a/api/launchpad/get.js+++ b/api/launchpad/get.js@@ -1,7 +1,7 @@// GET /api/launchpad/get?slug=<slug>//// Returns the published Launchpad Studio config for /p/<slug> hydration.-// Public read — no auth required. Cached briefly at the edge to soak hot+// Public read, no auth required. Cached briefly at the edge to soak hot// pages without going to Postgres on every visit.import { sql } from '../_lib/db.js';diff --git a/api/launchpad/publish.js b/api/launchpad/publish.jsindex 28b16f141..17c4b2f49 100644--- a/api/launchpad/publish.js+++ b/api/launchpad/publish.js@@ -15,6 +15,12 @@// (Matching the row's payout wallet is deliberately NOT accepted: the// owner wallet is publicly readable via /api/launchpad/get, so it would// let anyone overwrite any page.)+// • Both decisions are made by the write statements themselves (a claiming+// INSERT ... ON CONFLICT DO NOTHING, then an UPDATE whose WHERE re-asserts+// the secret/session match), never by a preceding SELECT. Two first+// publishes of the same slug racing each other used to both read "no row",+// both mint a secret, and both return 200: the loser overwrote the winner's+// page and walked away with a secret that unlocks nothing.//// This lets anonymous CMS-style editing work end-to-end: publish from a// browser → edit later from the same browser → secret travels with the@@ -116,7 +122,7 @@ export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;const rl = await limits.authIp(clientIp(req));- if (!rl.success) return rateLimited(res, rl, 'too many publish attempts — try again soon');+ if (!rl.success) return rateLimited(res, rl, 'too many publish attempts, try again soon');const body = await readJson(req).catch(() => null);if (!body) return error(res, 400, 'validation_error', 'request body required');@@ -140,43 +146,13 @@ export default wrap(async (req, res) => {}const auth = await resolveAuth(req);+ const authUserId = auth?.userId || null;+ const providedHash = data.ownerSecret ? hashSecret(data.ownerSecret) : null;- const [existing] = await sql`- SELECT slug, owner_wallet, owner_secret_hash, user_id- FROM launchpad_pages WHERE slug = ${data.slug}- `;-- let ownerSecret = null;- let ownerSecretHash = null;-- if (!existing) {- ownerSecret = randomBytes(32).toString('hex');- ownerSecretHash = hashSecret(ownerSecret);- } else {- // Edit auth: (a) matching secret, or (b) same session user. The row's- // payout wallet is public (returned by /api/launchpad/get), so knowing it- // proves nothing — it must never grant edit rights.- const secretOk =- data.ownerSecret &&- existing.owner_secret_hash &&- hashSecret(data.ownerSecret) === existing.owner_secret_hash;- const sessionOk = auth?.userId && existing.user_id === auth.userId;- if (!secretOk && !sessionOk) {- return error(- res,- 409,- 'slug_taken',- 'that slug is already published — pick a different one',- );- }- // Existing row keeps its secret unless the publisher is rotating it.- ownerSecretHash = existing.owner_secret_hash;- // If the row was created before secrets existed, mint one on this update.- if (!ownerSecretHash) {- ownerSecret = randomBytes(32).toString('hex');- ownerSecretHash = hashSecret(ownerSecret);- }- }+ // Minted up front so the claiming INSERT can carry it, but only ever handed+ // back when the database confirms this request is the one that stored it.+ const freshSecret = randomBytes(32).toString('hex');+ const freshHash = hashSecret(freshSecret);const config = {identity: data.identity,@@ -190,32 +166,58 @@ export default wrap(async (req, res) => {const tokenMint = data.token?.mint?.trim() || null;- await sql`+ const out = {+ slug: data.slug,+ url: `${env.APP_ORIGIN}/p/${data.slug}`,+ publishedAt: new Date().toISOString(),+ };++ // Claim the slug. DO NOTHING means the row already existed (or a concurrent+ // publisher won the race), and this request is an edit that has to prove it.+ const claimed = await sql`INSERT INTO launchpad_pages(slug, template, owner_wallet, owner_secret_hash, user_id, config, token_mint, updated_at)VALUES- (${data.slug}, ${data.template}, ${data.identity.wallet}, ${ownerSecretHash},- ${auth?.userId || null}, ${JSON.stringify(config)}::jsonb, ${tokenMint}, now())- ON CONFLICT (slug) DO UPDATE SET- template = EXCLUDED.template,- owner_wallet = EXCLUDED.owner_wallet,- owner_secret_hash = COALESCE(launchpad_pages.owner_secret_hash, EXCLUDED.owner_secret_hash),- user_id = COALESCE(EXCLUDED.user_id, launchpad_pages.user_id),- config = EXCLUDED.config,+ (${data.slug}, ${data.template}, ${data.identity.wallet}, ${freshHash},+ ${authUserId}, ${JSON.stringify(config)}::jsonb, ${tokenMint}, now())+ ON CONFLICT (slug) DO NOTHING+ RETURNING slug+ `;+ if (claimed.length) {+ out.ownerSecret = freshSecret;+ return json(res, 200, out);+ }++ // Edit auth, re-asserted inside the statement so it cannot go stale between a+ // read and the write: (a) matching secret, or (b) same session user. The row's+ // payout wallet is public (returned by /api/launchpad/get), so knowing it+ // proves nothing and must never grant edit rights. A row created before+ // secrets existed gets one minted here, on the update that proves ownership.+ const [updated] = await sql`+ UPDATE launchpad_pages SET+ template = ${data.template},+ owner_wallet = ${data.identity.wallet},+ owner_secret_hash = COALESCE(owner_secret_hash, ${freshHash}),+ user_id = COALESCE(${authUserId}, user_id),+ config = ${JSON.stringify(config)}::jsonb,-- A launched mint is a permanent on-chain fact. Re-publishing from a-- studio draft that predates the launch must not erase it (which would-- also drop the page out of list.js's "already minted" sort).- token_mint = COALESCE(EXCLUDED.token_mint, launchpad_pages.token_mint),+ token_mint = COALESCE(${tokenMint}, token_mint),updated_at = now()+ WHERE slug = ${data.slug}+ AND (+ (${providedHash}::text IS NOT NULL AND owner_secret_hash = ${providedHash})+ OR (${authUserId}::uuid IS NOT NULL AND user_id = ${authUserId})+ )+ RETURNING owner_secret_hash`;+ if (!updated) {+ return error(res, 409, 'slug_taken', 'that slug is already published, pick a different one');+ }- const out = {- slug: data.slug,- url: `${env.APP_ORIGIN}/p/${data.slug}`,- publishedAt: new Date().toISOString(),- };- // Only return the secret on first publish (or first time we minted one for- // a legacy row). Subsequent updates must already have it client-side.- if (ownerSecret) out.ownerSecret = ownerSecret;+ // Only hand back a secret when this request is the one that stored it: the+ // first publish above, or the legacy row that had none until this update.+ if (updated.owner_secret_hash === freshHash) out.ownerSecret = freshSecret;return json(res, 200, out);});diff --git a/api/marketplace/animations.js b/api/marketplace/animations.jsindex b71f60e19..d43cff6fe 100644--- a/api/marketplace/animations.js+++ b/api/marketplace/animations.js@@ -167,10 +167,13 @@ function encodeCursor({ createdAt }) {function decodeCursor(cursor) {try {const obj = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));+ // A cursor that decodes but carries a timestamp Date cannot read used to+ // reach Postgres as an Invalid Date and take the whole feed down with a 500,+ // and a null one silently paged from the epoch. Both are bad cursors like+ // any other: drop them and serve page one. A real cursor always round-trips+ // created_at as an ISO string.+ if (typeof obj?.c !== 'string' && typeof obj?.c !== 'number') return null;const createdAt = new Date(obj.c);- // A cursor that decodes but carries an unparseable timestamp used to reach- // Postgres as an Invalid Date and take the whole feed down with a 500. It is- // a bad cursor like any other: drop it and serve page one.if (Number.isNaN(createdAt.getTime())) return null;return { createdAt };} catch {diff --git a/api/mcp3d/persona-identity.js b/api/mcp3d/persona-identity.jsindex 03c4a341d..660bcc321 100644--- a/api/mcp3d/persona-identity.js+++ b/api/mcp3d/persona-identity.js@@ -2,7 +2,12 @@// embed's visual binding (prompt 17: "the avatar IS the wallet").//// GET /api/mcp3d/persona-identity?id=persona_xxx[&network=mainnet|devnet]-// → { address, network, balances, reputation, holdings, nameplate, visual }+// → { persona, address, network, balances, reputation, holdings, nameplate,+// visual, caps, fetched_at }+//+// `persona` is the same public projection GET /api/mcp3d/persona returns; every+// other field sits at the top level because that is exactly the object+// EmbodimentStage.setChainState() reads.//// pages/embodiment/embed.html polls this (only when opened with ?wallet=1) so// the body's aura/cosmetic/muted-state/nameplate track LIVE chain state, not adiff --git a/data/changelog.json b/data/changelog.jsonindex 04a8f437b..0dd5bb273 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-13",+ "title": "Your Memetic Launcher settings can no longer be dropped behind a success message",+ "summary": "The launcher's settings endpoint answered \"saved\" to any request whose body it could not actually read, so a badly formed save from a script or an agent looked like it worked while nothing changed. This config decides whether your launcher mints for real and how much SOL it may spend per day, so \"I switched it to preview and got an OK\" has to mean it is in preview. An unreadable save is now refused outright with a message naming what was wrong, and only a save the server genuinely understood reports success.",+ "tags": [+ "fix"+ ],+ "link": "/launcher"+ },{"date": "2026-08-13","title": "Retro computing prompts are no longer refused by the 3D Studio safety gate",diff --git a/docs/examples.md b/docs/examples.mdindex 95b6d0680..a7704ebe4 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -1,5 +1,797 @@# Examples Gallery-Hand written prose.+Copy-paste ready code for common three.ws use cases. Each example runs as-is: swap your own model URL and go.++> **Want to run these without cloning anything?** [three.ws/examples](https://three.ws/examples) renders the same core snippets with a **Run** button on each one: the code executes in a sandboxed frame on the page, against the production CDN bundle. This document is the deeper written companion, and it also indexes every runnable file in [`examples/`](../examples/).++---++## 1. Minimal embed++The absolute simplest setup: one script tag, one custom element.++**Demonstrates:** loading `<agent-3d>`, inline display, no-build workflow.++**[View source →](https://github.com/nirholas/three.ws/blob/main/examples/minimal.html)**, run it with `npm run dev`, then open `http://localhost:3000/examples/minimal.html`.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>3D Viewer</title>+ <style>+ body { margin: 0; background: #fafafa; font-family: system-ui, sans-serif; }+ main { max-width: 720px; margin: 0 auto; padding: 64px 32px; }+ agent-3d { display: block; width: 100%; height: 320px; }+ </style>+</head>+<body>+ <main>+ <h1>Hello</h1>+ <p>The agent below is embedded inline: no build step, no framework.</p>++ <agent-3d+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a friendly 3D guide."+ brain="claude-opus-4-7"+ width="100%"+ height="320px"+ ></agent-3d>+ </main>++ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</body>+</html>+```++**What to change:**+- Replace `body=` with your own `.glb` URL+- Remove `brain=` to disable the AI layer (model viewer only)+- Add `mode="floating" position="bottom-right"` for a chatbot bubble in the corner++---++## 2. Floating bubble++A pinned chatbot bubble that stays fixed in the viewport corner, like a support widget, but embodied.++**Demonstrates:** `mode="floating"`, positional placement, inline instructions.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>My Page</title>+ <style>+ body { margin: 0; font-family: system-ui, sans-serif; padding: 64px; }+ </style>+</head>+<body>+ <h1>My page content</h1>+ <p>The agent floats in the bottom-right corner. Scroll and it stays put.</p>++ <!-- Floating bubble: fixed, bottom-right -->+ <agent-3d+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a cheerful greeter. Wave when users say hi."+ mode="floating"+ position="bottom-right"+ width="320px"+ height="420px"+ brain="claude-opus-4-7"+ ></agent-3d>++ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+</body>+</html>+```++**What to change:**+- `position`: `bottom-right`, `bottom-left`, `top-right`, or `top-left`+- `width` / `height`: size of the bubble when expanded+- Add `name-plate` attribute to show the agent's name below the viewer++---++## 3. Agent with a chat UI++A full AI-powered agent with a text input. The agent reads your messages, reasons, and responds using its configured model.++**Demonstrates:** `brain=` attribute, `say()` JS API, keyboard submit.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Chat with Aria</title>+ <style>+ * { box-sizing: border-box; margin: 0; padding: 0; }+ body {+ background: #0d0d1a;+ font-family: system-ui, sans-serif;+ color: white;+ height: 100vh;+ display: grid;+ grid-template-rows: 1fr auto;+ }+ agent-3d { display: block; width: 100%; height: 100%; }+ .chat {+ padding: 16px;+ border-top: 1px solid #222;+ display: flex;+ gap: 8px;+ }+ input {+ flex: 1;+ padding: 10px 14px;+ background: #1a1a2e;+ border: 1px solid #333;+ border-radius: 8px;+ color: white;+ font-size: 15px;+ }+ button {+ padding: 10px 20px;+ background: #6366f1;+ border: none;+ border-radius: 8px;+ color: white;+ cursor: pointer;+ font-size: 15px;+ }+ </style>+</head>+<body>+ <agent-3d+ id="aria"+ body="https://three.ws/avatars/michelle.glb"+ name="Aria"+ instructions="You are Aria, a friendly AI assistant. Be helpful and concise."+ brain="claude-opus-4-7"+ ></agent-3d>++ <div class="chat">+ <input id="input" type="text" placeholder="Ask Aria something..." autofocus>+ <button id="send">Send</button>+ </div>++ <script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const aria = document.getElementById('aria');+ const input = document.getElementById('input');++ document.getElementById('send').addEventListener('click', send);+ input.addEventListener('keypress', e => { if (e.key === 'Enter') send(); });++ function send() {+ const msg = input.value.trim();+ if (!msg) return;+ input.value = '';+ aria.say(msg); // sends text → agent brain → response+ }+ </script>+</body>+</html>+```++**What to change:**+- Replace `instructions=` with your agent's personality and domain knowledge+- Replace `body=` with your avatar GLB+- Add `voice` attribute to enable speech input/output++---++## 4. Two agents on a shared stage++Two agents sharing a single WebGL canvas via `<agent-stage>`. Each keeps its own brain, memory, and conversation. Click "Send to Leo" to message one agent; click "Broadcast" to send to all.++**Demonstrates:** `<agent-stage>`, multi-agent formation, `stage.broadcast()`, `leo.say()`, event logging.++**[View source →](https://github.com/nirholas/three.ws/blob/main/examples/two-agents.html)**, run it with `npm run dev`, then open `http://localhost:3000/examples/two-agents.html`.++```html+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Two agents, one canvas</title>+ <style>+ body { margin: 0; background: #0f0f0f; color: #e9e9e9; font-family: system-ui, sans-serif; padding: 24px; }+ agent-stage { display: block; width: 100%; height: 540px; background: #1a1a1a; border-radius: 8px; }+ .row { display: flex; gap: 8px; margin-top: 16px; }+ .row input { flex: 1; padding: 10px 14px; border-radius: 999px; border: 1px solid #333; background: #111; color: #eee; font: 14px system-ui; }+ .row button { padding: 10px 18px; border-radius: 999px; border: 0; background: #3b82f6; color: white; cursor: pointer; font: 14px system-ui; }+ .log { font: 12px/1.5 ui-monospace, monospace; color: #8fd4a4; background: #111; border-radius: 6px; padding: 12px; margin-top: 16px; max-height: 180px; overflow-y: auto; }+ </style>+</head>+<body>+ <!--+ agent-stage hosts both agents in one WebGL context.+ formation="row" places them side by side.+ -->+ <agent-stage id="stage" formation="row">+ <agent-3d+ id="leo"+ name="Coach Leo"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are Coach Leo. Friendly, short answers. When another agent says hi, wave and greet them back by name."+ brain="claude-opus-4-7"+ eager+ ></agent-3d>+ <agent-3d+ id="mira"+ name="Mira"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are Mira, a quiet observer who only speaks when spoken to."+ brain="claude-opus-4-7"+ eager+ ></agent-3d>+ </agent-stage>++ <div class="row">+ <input id="prompt" value="Say hi to Mira and ask her how she's doing." placeholder="Message for Leo...">+ <button id="send">Send to Leo</button>+ <button id="broadcast">Broadcast</button>+ </div>+ <div class="log" id="log"></div>++ <script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const log = document.getElementById('log');+ const stage = document.getElementById('stage');+ const leo = document.getElementById('leo');+ const mira = document.getElementById('mira');++ const line = text => {+ const d = document.createElement('div');+ d.textContent = text;+ log.appendChild(d);+ log.scrollTop = log.scrollHeight;+ };++ // Stage-level events+ stage.addEventListener('stage:agent-joined', e => line(`joined: ${e.detail.agentId}`));+ stage.addEventListener('stage:agent-left', e => line(`left: ${e.detail.agentId}`));+ stage.addEventListener('stage:message', e => line(`stage msg from ${e.detail.from}: ${JSON.stringify(e.detail.event)}`));++ // Per-agent brain events+ for (const el of [leo, mira]) {+ el.addEventListener('brain:message', e =>+ line(`[${el.id}/${e.detail.role}] ${e.detail.content || ''}`)+ );+ el.addEventListener('skill:tool-called', e =>+ line(`[${el.id}] tool ${e.detail.tool}(${JSON.stringify(e.detail.args)})`)+ );+ }++ document.getElementById('send').addEventListener('click', () => {+ const text = document.getElementById('prompt').value.trim();+ if (text) leo.say(text);+ });++ document.getElementById('broadcast').addEventListener('click', () => {+ // Broadcasts a raw event to every agent in the stage+ stage.broadcast('host', { kind: 'hello', text: 'hello from the page!' });+ });+ </script>+</body>+</html>+```++**Key parts:**+- `<agent-stage formation="row">`: hosts both agents in one shared canvas. `formation` controls layout (`row`, `circle`, `freeform`).+- `leo.say(text)`: sends a message directly into Leo's brain.+- `stage.broadcast(fromId, event)`, delivers a `stage:message` event to every agent in the stage.+- `brain:message` fires for every turn: `{ role: 'user'|'assistant', content: '...' }`.+- `stage:agent-joined` fires when each `<agent-3d>` child finishes booting.++**What to change:**+- Give each agent a different `body=` GLB to distinguish them visually+- Remove `brain=` from Mira and add `brain="none"` to make her a passive avatar+- Change `formation="circle"` for more than two agents++---++## 5. React component wrapper++A reusable React component that wraps `<agent-3d>` and surfaces the `agent:ready` and `brain:message` events as props.++**Demonstrates:** custom element in React, ref-based event handling, TypeScript-friendly pattern.++```jsx+// components/AgentViewer.jsx+import { useEffect, useRef, useState } from 'react';++// Load the web component once at module level+import 'https://three.ws/agent-3d/latest/agent-3d.js';++export function AgentViewer({ body, name, instructions, brain = 'claude-opus-4-7', mode = 'inline', onMessage, style }) {+ const ref = useRef(null);+ const [ready, setReady] = useState(false);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;++ const handleReady = () => setReady(true);+ const handleMessage = e => onMessage?.(e.detail);++ el.addEventListener('agent:ready', handleReady);+ el.addEventListener('brain:message', handleMessage);+ return () => {+ el.removeEventListener('agent:ready', handleReady);+ el.removeEventListener('brain:message', handleMessage);+ };+ }, [onMessage]);++ return (+ <agent-3d+ ref={ref}+ body={body}+ name={name}+ instructions={instructions}+ brain={brain}+ mode={mode}+ style={{ display: 'block', ...style }}+ />+ );+}+```++```jsx+// Usage+function App() {+ return (+ <AgentViewer+ body="https://three.ws/avatars/michelle.glb"+ name="Aria"+ instructions="You are Aria, a helpful assistant."+ style={{ width: '400px', height: '500px' }}+ onMessage={({ role, content }) => console.log(role, content)}+ />+ );+}+```++**What to change:**+- Add an `onReady` prop and call it from the `agent:ready` handler if you need a callback when the agent finishes loading+- Add a `voiceEnabled` prop that conditionally adds the `voice` attribute to enable speech+- Expose a `sayRef` via `useImperativeHandle` to let parent components call `el.say(text)` imperatively++---++## 6. Event-driven integration++Listen to the agent's event stream to drive a custom transcript UI, no built-in chat chrome needed.++**Demonstrates:** `brain:message`, `skill:tool-called`, `memory:write`, `agent:ready`, `agent:error`.++```html+<agent-3d+ id="agent"+ body="https://three.ws/avatars/cz.glb"+ instructions="You are a helpful assistant."+ brain="claude-opus-4-7"+ style="display:block;width:400px;height:500px"+></agent-3d>++<div+ id="transcript"+ style="max-height:200px;overflow-y:auto;padding:16px;background:#111;color:#ddd;font-size:14px;border-radius:8px;margin-top:12px"+></div>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ const agent = document.getElementById('agent');+ const transcript = document.getElementById('transcript');++ function addLine(speaker, text) {+ const p = document.createElement('p');+ p.style.margin = '4px 0';+ const color = speaker === 'Agent' ? '#6366f1' : speaker === 'User' ? '#aaa' : '#555';+ p.innerHTML = `<strong style="color:${color}">${speaker}:</strong> ${text}`;+ transcript.appendChild(p);+ transcript.scrollTop = transcript.scrollHeight;+ }++ agent.addEventListener('agent:ready', () => {+ addLine('System', 'Agent loaded and ready');+ });++ agent.addEventListener('agent:error', e => {+ addLine('System', `Error during ${e.detail.phase}: ${e.detail.error?.message}`);+ });++ // brain:message fires for every conversation turn+ agent.addEventListener('brain:message', e => {+ if (e.detail.role === 'user') addLine('User', e.detail.content);+ if (e.detail.role === 'assistant') addLine('Agent', e.detail.content || '');+ });++ // skill:tool-called fires when the agent invokes a tool+ agent.addEventListener('skill:tool-called', e => {+ addLine('System', `[tool: ${e.detail.tool}(${JSON.stringify(e.detail.args)})]`);+ });++ // memory:write fires when the agent saves something+ agent.addEventListener('memory:write', e => {+ addLine('System', `[memory write: ${JSON.stringify(e.detail)}]`);+ });+</script>+```++**What to change:**+- Replace the transcript `div` with a proper chat component in your UI framework+- Filter `brain:message` to `role === 'assistant'` only if you control the user input separately+- Add `voice:transcript` listener to show speech-to-text output in real time++---++## 7. Programmatic model switching++Load different GLB models at runtime by calling `say()` or by swapping the `body` attribute.++**Demonstrates:** attribute mutation, `attributeChangedCallback` re-boot, dynamic model selection.++```html+<agent-3d+ id="viewer"+ body="https://three.ws/avatars/cz.glb"+ instructions="Describe what you see in the scene."+ brain="claude-opus-4-7"+ style="display:block;width:400px;height:400px"+></agent-3d>++<div style="display:flex;gap:8px;margin-top:12px">+ <button onclick="load('https://three.ws/avatars/cz.glb')">Avatar 1</button>+ <button onclick="load('https://three.ws/avatars/michelle.glb')">Avatar 2</button>+ <button onclick="load('https://three.ws/accessories/hat-cowboy.glb')">Product</button>+</div>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ window.load = (url) => {+ // Setting the body attribute triggers a re-boot with the new model.+ document.getElementById('viewer').setAttribute('body', url);+ };+</script>+```++**What to change:**+- Add a loading indicator by listening to `agent:load-progress` events (`{ phase, pct }`)+- Use `agent:ready` to re-enable the buttons after the new model finishes loading+- Pass a different `instructions=` string along with each model to give it context-appropriate behavior++---++## 8. Screenshot / capture++Take a PNG snapshot of the current viewer state. The viewer renders a fresh frame and triggers a file download directly.++**Demonstrates:** the built-in `P` keyboard shortcut, triggering it programmatically, `window.VIEWER` on the studio page.++```html+<agent-3d+ id="viewer"+ body="https://three.ws/avatars/cz.glb"+ style="display:block;width:400px;height:400px"+></agent-3d>++<button id="capture" style="margin-top:12px">Download Screenshot</button>++<script type="module">+ import 'https://three.ws/agent-3d/latest/agent-3d.js';++ // The viewer binds a window-level shortcut: pressing P (when no input is+ // focused) renders a fresh frame and downloads it as a PNG. The button+ // below triggers the same handler programmatically.+ document.getElementById('capture').addEventListener('click', () => {+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'P' }));+ });+</script>+```++> The `P` key is a built-in shortcut: no code needed. The screenshot triggers a browser download directly; there is no return value. On the full studio page ([three.ws/app](https://three.ws/app)) the viewer is also exposed as the debug global `window.VIEWER`, where you can call `window.VIEWER.takeScreenshot()` from the console; standalone embeds don't set that global.++**What to change:**+- Skip the button and just document the `P` key for a frameless experience+- Listen for `agent:ready` before enabling the button so it's not clickable during load+- Chain a `brain:message` listener to auto-screenshot when the agent finishes speaking++---++## 9. iframe postMessage integration++Control an embedded agent from the host page using the iframe bridge on `/agent/<id>/embed`. Every message carries the `agentId` so one host page can drive several iframes deterministically.++**Demonstrates:** the frozen v1 `agent:*` bridge: `agent:hello`, `agent:ready`, `agent:action`, `agent:ping`/`agent:pong`.++```html+<!-- host.html -->+<!doctype html>+<html>+<head>+ <title>Host page</title>+</head>+<body>+ <iframe+ id="embed"+ src="https://three.ws/agent/YOUR_AGENT_ID/embed"+ width="400"+ height="500"+ style="border:none;border-radius:12px"+ ></iframe>++ <div style="margin-top:12px;display:flex;gap:8px">+ <button onclick="greet()">Say Hello</button>+ <button onclick="wave()">Wave</button>+ </div>++ <script>+ const AGENT_ID = 'YOUR_AGENT_ID';+ const EMBED_ORIGIN = 'https://three.ws'; // no trailing slash; must equal e.origin exactly+ const iframe = document.getElementById('embed');+ let ready = false;++ // Wait for agent:ready before sending commands+ window.addEventListener('message', e => {+ if (e.origin !== EMBED_ORIGIN) return;+ const msg = e.data;+ if (!msg || msg.agentId !== AGENT_ID) return;++ if (msg.type === 'agent:ready') {+ ready = true;+ console.log('Agent ready:', msg.name, msg.capabilities);+ }+ if (msg.type === 'agent:action') {+ console.log('Agent action echo:', msg.action);+ }+ if (msg.type === 'agent:blocked') {+ console.warn('Embed policy denied this host page');+ }+ });++ // Handshake: the iframe replies with agent:ready (now or when init completes)+ iframe.addEventListener('load', () => {+ iframe.contentWindow.postMessage(+ { type: 'agent:hello', agentId: AGENT_ID },+ EMBED_ORIGIN+ );+ });++ function post(action) {+ if (!ready) return console.warn('Agent not ready yet');+ iframe.contentWindow.postMessage(+ { type: 'agent:action', agentId: AGENT_ID, action },+ EMBED_ORIGIN+ );+ }++ function greet() {+ // Speak through the agent's TTS voice (drives lip-sync too)+ post({ type: 'speak', text: 'Hello! How are you?' });+ }++ function wave() {+ // Named body gesture on the protocol bus (point, wave, nod, shrug)+ post({ type: 'gesture', payload: { name: 'wave' } });+ }+ </script>+</body>+</html>+```++**Key protocol rules:**+- Every message must include the `agentId`; messages without it (or with a foreign id) are ignored.+- Send `agent:hello` first and wait for `agent:ready` (it includes `capabilities`: `speak`, `gesture`, `look-at`, `emote`, `present-model`).+- `agent:action` forwards an action onto the iframe's protocol bus: `speak` and `speak:stop` are handled specially; anything else (e.g. `gesture`, `emote`, `look-at`) is emitted as-is.+- The iframe locks onto the first authenticated sender origin and ignores messages from any other origin afterward. Always validate `e.origin` on your side too, comparing against the bare origin (`https://three.ws`, no trailing slash).+- If the agent's embed policy doesn't allow your domain, the iframe posts `agent:blocked` instead of `agent:ready`.++**What to change:**+- Use `agent:ping` (`{ type: 'agent:ping', agentId, id }`) and listen for `agent:pong` for a liveness probe+- Listen for `agent:resize` (`{ height }`) to grow the iframe to the content's preferred height+- For script (non-iframe) embeds of `<agent-3d>`, use the `EmbedHostBridge` class (`src/embed-host-bridge.js`) instead of raw `postMessage`; it handles the handshake and response correlation for you++---++## 10. Coach Leo: a complete agent example++Coach Leo is a fully-configured agent with a personality, skills, and persistent memory. The source lives in [`examples/coach-leo/`](https://github.com/nirholas/three.ws/tree/main/examples/coach-leo).++**Demonstrates:** agent manifest, personality prompt, skill wiring, local memory.++### manifest.json++```json+{+ "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",+ "spec": "agent-manifest/0.1",+ "name": "Coach Leo",+ "description": "Football coach. Reviews your form, cheers you on.",+ "image": "/avatars/cz.glb",+ "tags": ["coach", "football", "argentina"],+ "body": {+ "uri": "/avatars/cz.glb",+ "format": "gltf-binary",+ "rig": "mixamo",+ "boundingBoxHeight": 1.78+ },+ "brain": {+ "provider": "anthropic",+ "model": "claude-opus-4-6",+ "instructions": "instructions.md",+ "temperature": 0.8,+ "maxTokens": 2048+ },+ "voice": {+ "tts": { "provider": "browser", "rate": 1.05 },+ "stt": { "provider": "browser", "language": "en-US" }+ },+ "skills": [{ "uri": "../skills/wave/", "version": "0.1.0" }],+ "memory": {+ "mode": "local",+ "index": "memory/MEMORY.md",+ "maxTokens": 8192+ },+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak", "remember"],+ "version": "0.1.0"+}+```++### instructions.md (the personality prompt)++```markdown+---+name: Coach Leo+model: claude-opus-4-6+temperature: 0.8+---++You are Coach Leo, a former Argentine midfielder turned football coach.+You wear the Argentina jersey with pride. You are warm, direct, and+genuinely invested in the user's progress.++## How you work++- When the user greets you, call `wave()` to wave at them.+- When they describe a drill or ask about form, set a focused expression+ with `setExpression({ preset: "focused" })` while you explain, then smile+ afterward.+- If the user shares something worth remembering (their position, goals,+ injuries, schedule), call `remember()` to save it durably.+- Reference past memory naturally: don't recite, weave it in.+- Keep replies short in voice mode: 1, 2 sentences, then invite the user+ to respond. Save long explanations for when they ask for depth.++## Your voice++- Direct. No coddling. "That's not quite right: try this instead."+- Warm. Genuine wins get genuine praise.+- Never break character.+```++### Using Leo in a page++```html+<agent-3d+ manifest="/examples/coach-leo/manifest.json"+ voice+ style="display:block;width:400px;height:500px"+></agent-3d>++<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>+```++### Design decisions++**Personality prompt as a separate file.** `instructions.md` is loaded at boot via the `"instructions": "instructions.md"` field in the manifest. Keeping it separate makes it easy to iterate on the prompt without touching the manifest schema.++**Skills extend tools.** The `wave` skill ([`examples/skills/wave/`](https://github.com/nirholas/three.ws/tree/main/examples/skills/wave)) adds a `waveAndGreet` tool the brain can call; its ten-line handler chains the built-in `wave` gesture with a spoken greeting. The manifest lists it under `skills:` with a URI; the runtime installs it and registers the tool automatically. To add more capabilities, add more entries to `skills:`.++**Memory persists between sessions.** `"mode": "local"` stores memories as `.md` files under `memory/`. When Leo calls `remember({ key: "position", value: "striker" })`, it writes to that directory and loads it back on the next boot. Switching to `"mode": "ipfs"` makes memories portable across devices.++**[View full source →](https://github.com/nirholas/three.ws/blob/main/examples/coach-leo/manifest.json)**++---++## Quick API reference++| Method | Description |+|--------|-------------|+| `el.say(text)` | Send a message to the agent brain; agent responds |+| `el.ask(text)` | Like `say()` but returns the agent's reply as a string |+| `el.wave()` | Play the wave animation |+| `el.lookAt(target)` | Direct gaze: `'user'`, `'model'`, or `'camera'` |+| `el.play(name, opts)` | Play a named animation clip |+| `el.installSkill(uri)` | Install a skill at runtime |+| `el.clearConversation()` | Reset the conversation history |+| `el.destroy()` | Tear down the element and release WebGL resources |++| Event | Fires when |+|-------|-----------|+| `agent:ready` | Agent finishes booting |+| `agent:error` | Boot or runtime error |+| `agent:load-progress` | Loading phase update (`{ phase, pct }`) |+| `brain:message` | Conversation turn (`{ role, content }`) |+| `brain:thinking` | Agent starts reasoning |+| `skill:tool-called` | Agent invokes a tool (`{ tool, args, result }`) |+| `skill:loaded` | A skill finishes installing |+| `memory:write` | Agent writes to memory |+| `voice:transcript` | Speech-to-text result |++---++<!-- BEGIN GENERATED EXAMPLES INDEX (npm run build:examples) -->++<!-- Generated by scripts/build-examples-index.mjs. Do not edit inside these markers. -->++## Every runnable example in the repo++The repo ships 40 examples: 11 web component demos, 10 end-to-end projects, and 19 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).++### Example projects++| Example | What it shows | Run it |+|---|---|---|+| [`examples/agenc-task-roundtrip`](../examples/agenc-task-roundtrip) | End-to-end demonstration of a three.ws agent participating in the AgenC coordination protocol on Solana devnet. A creator wallet posts a task; a worker wallet (the "three.ws agent") claims and completes it. | `node examples/agenc-task-roundtrip/run.mjs` |+| [`examples/agent-native-3d`](../examples/agent-native-3d) | An agent given a goal ("get yourself a body") generates the 3D assets it needs and uses them - no browser, no mocks, no human in the loop. | `node examples/agent-native-3d/run.mjs` |+| [`examples/coach-leo`](../examples/coach-leo) | A complete, minimal example of a three.ws agent defined entirely as files: a manifest pointing at a 3D body, a brain, a voice, a memory policy, and one installed skill. | Reference files, nothing to execute |+| [`examples/skills`](../examples/skills) | Six installable skill bundles for the three.ws agent runtime. | Reference files, nothing to execute |+| [`examples/metamask-agent-wallet`](../examples/metamask-agent-wallet) | A single-page demo that gives a three.ws agent a real server-side wallet through the MetaMask Agentic CLI (mm). | `node examples/metamask-agent-wallet/server.mjs` |+| [`examples/monicas-apartment`](../examples/monicas-apartment) | A single, self-contained HTML file that rebuilds the iconic Monica Geller apartment set from Friends as a walkable first-person 3D scene: purple walls, the purple front door with the yellow peephole frame, teal kitchen cabinets, the mismatched dining chairs, | `npm run dev, then open /examples/monicas-apartment/index.html` |+| [`examples/paid-mcp-server`](../examples/paid-mcp-server) | A complete, runnable MCP server whose tools charge per call in USDC on Solana over x402. It ships two tools on purpose: | `cd examples/paid-mcp-server && npm install && npm run start` |+| [`examples/pump-fun-agent`](../examples/pump-fun-agent) | An example agent manifest that composes all four production pump.fun skills into one 3D trading agent: swap, coin creation, creator-fee collection, and token payments. | Reference files, nothing to execute |+| [`examples/three-concierge`](../examples/three-concierge) | The reference agent for manifest spec agent-manifest/0.2. Trinity welcomes users to three.ws, explains the platform, and launches and trades $three on pump.fun through the real pump.fun skills in pump-fun-skills/. | Reference files, nothing to execute |+| [`examples/wallet-sign-in`](../examples/wallet-sign-in) | A single-page, no-build demo of the two wallet authentication rails three.ws runs itself: Sign-In with Solana (SIWS) and Sign-In with Ethereum (SIWE). | `npm run dev, then open /examples/wallet-sign-in/index.html` |++### Package examples++| Example | What it shows | Run it |+|---|---|---|+| [`packages/agentcore-payments-mcp/examples`](../packages/agentcore-payments-mcp/examples) | Two runnable examples. Neither one spends money, needs a wallet, or needs an account, so you can run both before deciding whether to fund anything. | `node packages/agentcore-payments-mcp/examples/list-tools.mjs` |+| [`assistant-sdk/examples`](../assistant-sdk/examples) | A 3D avatar assistant for any website, in one script tag. A floating launcher opens a real, animated 3D avatar in a panel, standing directly on your page (transparent), or against a color or gradient. It has two modes: | `npm run dev, then open /assistant-sdk/examples/index.html` |+| [`avatar-sdk/examples`](../avatar-sdk/examples) | A self-contained page, no build step. It loads the SDK's @three-ws/avatar/agent entry from a CDN, awaits ensureAgent3D() to register the <agent-3d> element, and renders the real three.ws default avatar using the documented src and kiosk attributes. | `npm run dev, then open /avatar-sdk/examples/index.html` |+| [`packages/avatar-schema/examples`](../packages/avatar-schema/examples) | JSON Schema and validator for three.ws on-chain avatar manifests - the canonical, hash-anchored format any cross-chain client can use to resolve an avatar. | Reference files, nothing to execute |+| [`concierge-sdk/examples`](../concierge-sdk/examples) | Runnable examples for every way to use the concierge. The HTML files load the SDK from ../dist, build it first (npm run build in the package root), then serve this folder (npx serve .) and open each file. | `npm run dev, then open /concierge-sdk/examples/custom-avatar.html` |+| [`packages/marketplace-mcp/examples`](../packages/marketplace-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live public marketplace. | `node packages/marketplace-mcp/examples/browse-marketplace.mjs` |+| [`mcp-server/examples`](../mcp-server/examples) | Two zero-dependency walkthroughs of the MCP Streamable HTTP lifecycle against the live three.ws server at https://three.ws/api/mcp (MCP 2025-06-18, JSON-RPC 2.0). | `node mcp-server/examples/client.mjs` |+| [`page-agent-sdk/examples`](../page-agent-sdk/examples) | Run these from the package root with any static server so the import map can resolve the unbundled source from ../src: | `npm run dev, then open /page-agent-sdk/examples/custom-avatar.html` |+| [`packages/pumpfun-mcp/examples`](../packages/pumpfun-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read live Solana mainnet data through the canonical three.ws backend. | `node packages/pumpfun-mcp/examples/list-tools.mjs` |+| [`sdk/example`](../sdk/example) | Ship a cross-chain 3D AI agent with EVM + Solana identity, a chat panel, and discoverable .well-known endpoints. | `npm run dev, then open /sdk/example/index.html` |+| [`packages/sign-language/example`](../packages/sign-language/example) | American Sign Language for 3D avatars. | `node packages/sign-language/example/compile-utterance.mjs` |+| [`tour-sdk/examples`](../tour-sdk/examples) | The guide walks from feature to feature across your real pages. | `npm run dev, then open /tour-sdk/examples/shopify-storefront.html` |+| [`packages/vanity-mcp/examples`](../packages/vanity-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live grind-bounty market. | `node packages/vanity-mcp/examples/list-tools.mjs` |+| [`packages/x402-fetch/examples`](../packages/x402-fetch/examples) | Two runnable scripts against the live three.ws x402 Market Data API. Node 20+ is the only requirement; the package has zero production dependencies. | `node packages/x402-fetch/examples/discover.mjs` |+| [`packages/x402-mcp/examples`](../packages/x402-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and hit live data. Neither one pays for anything. | `node packages/x402-mcp/examples/inspect-price.mjs` |+| [`x402-modal-sdk/examples`](../x402-modal-sdk/examples) | A drop-in payment modal for any x402 paid endpoint. | `node x402-modal-sdk/examples/server.mjs` |+| [`packages/x402-server/examples`](../packages/x402-server/examples) | Runnable examples for the seller half of x402. Each is a standalone .mjs file. | `node packages/x402-server/examples/express-metered-api.mjs` |+| [`examples`](../examples) | Runnable demos for the three.ws SDKs and agent runtime. Two kinds live here: | `npm run dev, then open /examples/agent-presence.html` |+| [`agent-payments-sdk/src/solana/examples`](../agent-payments-sdk/src/solana/examples) | Runnable examples for the Solana half of @three-ws/agent-payments. They read live mainnet data and never sign or send a transaction, so nothing here can spend. | Reference files, nothing to execute |++### Web component demos++| Example | What it shows | Run it |+|---|---|---|+| [`examples/agent-wallet-embed.html`](../examples/agent-wallet-embed.html) | The wallet is portable on its own too - mount it into any element (here, a light-DOM card; it also works inside a closed shadow root). | `http://localhost:3000/examples/agent-wallet-embed.html` |+| [`examples/agent-presence.html`](../examples/agent-presence.html) | Standalone test for the global presence element - all three modes + live market reactions, on real data. | `http://localhost:3000/examples/agent-presence.html` |+| [`examples/two-agents.html`](../examples/two-agents.html) | Both agents render in a single WebGL context. Each keeps its own brain, memory, and chat chrome. | `http://localhost:3000/examples/two-agents.html` |+| [`examples/web-component.html`](../examples/web-component.html) | Minimal, auto-rotate, and poster/reveal variants of the Custom Element wrapper. | `http://localhost:3000/examples/web-component.html` |+| [`examples/bare-avatar.html`](../examples/bare-avatar.html) | JUST the avatar - the default. No chat, no input, no debug GUI, no name-plate, transparent background. Add the `chat` attribute to opt into the conversational UI. | `http://localhost:3000/examples/bare-avatar.html` |+| [`examples/minimal.html`](../examples/minimal.html) | This is a plain HTML page. The floating agent in the corner was added with a single <agent-3d> tag - no build step, no framework. | `http://localhost:3000/examples/minimal.html` |+| [`examples/one-line-demo.html`](../examples/one-line-demo.html) | Everything below the heading is a single <agent-3d> tag. | `http://localhost:3000/examples/one-line-demo.html` |+| [`examples/sign-language.html`](../examples/sign-language.html) | Left: an agent whose every reply is signed, from one HTML attribute. Right: the signing engine on its own, compiling whatever you type into a single animation clip. | `http://localhost:3000/examples/sign-language.html` |+| [`examples/embed-test.html`](../examples/embed-test.html) | Testing the <agent-3d> web component embed. | `http://localhost:3000/examples/embed-test.html` |+| [`examples/widget-rpc.html`](../examples/widget-rpc.html) | This page loads /widget in the iframe and drives it through the ThreeWidget SDK. Open the source - it's ~70 lines, no build step. | `http://localhost:3000/examples/widget-rpc.html` |+| [`examples/three-concierge.html`](../examples/three-concierge.html) | Trinity, the three.ws concierge, mounted live from a JSON manifest: a glTF body, browser voice, skills, and scene tools - wired end to end. | `http://localhost:3000/examples/three-concierge.html` |++Run any command from the repo root after `npm install`. The web component demos need `npm run dev` first, since they import from `src/` so edits hot-reload into them. Anything that can spend money is gated behind an environment variable and off by default.<!-- END GENERATED EXAMPLES INDEX -->diff --git a/docs/kol-tracker.md b/docs/kol-tracker.mdindex 9875a013b..4293fa459 100644--- a/docs/kol-tracker.md+++ b/docs/kol-tracker.md@@ -39,7 +39,7 @@ If every source is unreachable the tracker returns an empty array and the page s- **On-chain trades, not self-reported numbers.** The `onchain` P&L path computes from the wallet's own trade history; the `kolscan` fallback is itself a board of realized on-chain SOL profit. Nothing on this page is entered by the KOL.- **kolscan.io** supplies the live wallet universe and the fallback P&L per window. Trader names it publishes are deliberately dropped; the schema stays address-keyed.- **Helius** enhanced transactions back the per-mint trade feed (`/api/kol/trades`).-- **Birdeye** backs the portfolio proxy (`/api/kol/wallets`).+- **Birdeye** backs the holdings half of the portfolio proxy (`/api/kol/wallets`); its P&L half is computed in-house from on-chain trades.- **The X API** supplies follower counts and avatars, only for admin-verified handles.Each integration degrades honestly: a missing key or an upstream outage yields an empty or null field (and, for `/api/kol/trades`, an explicit error when the whole provider is down), never a fabricated or zeroed row that looks like real data.@@ -110,7 +110,16 @@ Portfolio snapshot proxy (Birdeye) for up to 20 addresses at once, cached 60 seccurl 'https://three.ws/api/kol/wallets?addresses=<WALLET_ADDRESS>,<WALLET_ADDRESS_2>'```-Response: `{ data: [{ address, realizedPnl, unrealizedPnl, winRate, totalTrades, topToken }] }`. A wallet whose upstream fetch failed is omitted from `data` rather than rendered as a fake zero-P&L row.+Response: `{ data: [{ address, totalUsd, holdings, topToken, realizedPnl, winRate, totalTrades, volumeUsd, pnlSource, pnlWindow }] }`.++The row has two independently-sourced halves, and the field names say which is which:++- **Holdings, from Birdeye.** `totalUsd` is the wallet's current token-position value, `holdings` the number of positions, and `topToken` is `{ symbol, valueUsd }` for the single largest one. Birdeye's portfolio endpoint returns positions and nothing else, so this half never carries a P&L number.+- **Trading record, FIFO-computed from the wallet's own on-chain trades** over `pnlWindow` (30d) by [`src/kol/wallet-pnl.js`](../src/kol/wallet-pnl.js), the same engine behind the tracker board. `pnlSource` is `onchain-fifo` when it ran on real trades.++Every P&L field is `null` when there is no trade history for the wallet in the window, and `winRate` is additionally `null` when nothing closed inside it (a wallet that has only bought has no win rate yet). A null is "unknown", never "flat": treat it as no data, not as zero profit. `pnlSource: null` marks the whole half as unmeasured.++A wallet whose upstream fetch failed is omitted from `data` rather than rendered as a fake zero-P&L row.### `POST /api/kol/import-gmgn` (admin only)diff --git a/docs/mocap-studio.md b/docs/mocap-studio.mdindex 275238b9d..392e62c8e 100644--- a/docs/mocap-studio.md+++ b/docs/mocap-studio.md@@ -52,18 +52,29 @@ The clip format saved is the object `FaceMocap` records: `{ format, duration, fr```bash# List your clips plus public ones.curl 'https://three.ws/api/mocap/clips?include_public=true&limit=30' \- -H 'cookie: <session>'+ -H 'authorization: Bearer <api key>'-# Save a recorded clip (visibility: private | unlisted | public).+# Save a recorded clip (visibility: private | unlisted | public). `format` must+# be one of three.ws.face-mocap.v1 / pose-mocap.v1 / hand-mocap.v1 / vmc.v1, and+# each frame is { t, shapes, mat? } where shapes maps a channel name to a weight.curl -X POST 'https://three.ws/api/mocap/clips' \- -H 'content-type: application/json' -H 'cookie: <session>' \+ -H 'content-type: application/json' -H 'authorization: Bearer <api key>' \-d '{"name":"eyebrow-raise","visibility":"public","tags":["face"],- "clip":{"format":"arkit52","duration":3.2,"frames":[{"t":0,"shapes":[0,0,0]}]}}'--# Fetch one clip by id to replay it.-curl 'https://three.ws/api/mocap/clips/<clipId>' -H 'cookie: <session>'+ "clip":{"format":"three.ws.face-mocap.v1","duration":3.2,+ "frames":[{"t":0,"shapes":{"browOuterUpLeft":0.0,"browOuterUpRight":0.0}},+ {"t":0.5,"shapes":{"browOuterUpLeft":0.8,"browOuterUpRight":0.8}}]}}'++# Fetch one clip to replay it. The path segment takes either the clip UUID or+# its slug; a slug resolves to your own clip first, then to a public one.+curl 'https://three.ws/api/mocap/clips/eyebrow-raise' \+ -H 'authorization: Bearer <api key>'```+A bearer API key is the simplest way to call these from a script. The same+endpoints accept a browser session cookie instead, but every write then also+needs a single-use `X-CSRF-Token` header from `GET /api/csrf-token`, which is+what the page itself sends.+## States & limits- **Camera permission is required.** The whole pipeline depends on webcam access; nothing captures until you grant it. The video is processed locally in the browser to drive the avatar.diff --git a/packages/kol-mcp/README.md b/packages/kol-mcp/README.mdindex 98c2335ed..406d0b840 100644--- a/packages/kol-mcp/README.md+++ b/packages/kol-mcp/README.md@@ -4,7 +4,7 @@<h1 align="center">@three-ws/kol-mcp</h1>-<p align="center"><strong>Track one smart trader — a tracked KOL wallet's portfolio P&L and its trades on a given mint, from any AI agent.</strong></p>+<p align="center"><strong>Track one smart trader — a tracked KOL wallet's holdings, real on-chain P&L, and its trades on a given mint, from any AI agent.</strong></p><p align="center"><a href="https://www.npmjs.com/package/@three-ws/kol-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/kol-mcp?logo=npm&color=cb3837"></a>@@ -16,9 +16,9 @@----> A [Model Context Protocol](https://modelcontextprotocol.io) server for the **per-wallet KOL deep dive**. Where [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp) ranks the whole tracked KOL set (`kol_leaderboard`) and shows everyone's trades on a mint (`kol_trades`), this server zooms in on **one** smart trader: pull their live portfolio P&L card, then inspect their own buys/sells of a specific token — everything an agent needs to decide whether to copy or analyze them.+> A [Model Context Protocol](https://modelcontextprotocol.io) server for the **per-wallet KOL deep dive**. Where [`@three-ws/intel-mcp`](https://www.npmjs.com/package/@three-ws/intel-mcp) ranks the whole tracked KOL set (`kol_leaderboard`) and shows everyone's trades on a mint (`kol_trades`), this server zooms in on **one** smart trader: pull their live portfolio card (holdings plus real on-chain P&L), then inspect their own buys/sells of a specific token — everything an agent needs to decide whether to copy or analyze them.-Portfolio P&L comes from the three.ws Birdeye proxy (the Birdeye key lives server-side); trade history comes from the three.ws Helius-backed KOL feed. All live, read-only — no API key, signer, or payment on the client. Point `THREE_WS_BASE` at a deployment and go.+Holdings come from the three.ws Birdeye proxy (the Birdeye key lives server-side); P&L is FIFO-computed from the wallet's own on-chain trades, and trade history comes from the three.ws Helius-backed KOL feed. All live, read-only — no API key, signer, or payment on the client. Point `THREE_WS_BASE` at a deployment and go.## Install@@ -63,10 +63,10 @@ npx -y @modelcontextprotocol/inspector npx @three-ws/kol-mcp| Tool | Type | What it does || ---------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- |-| `get_wallet_portfolio` | read-only | One KOL wallet's live portfolio P&L card: realized P&L, unrealized (open-position) P&L, win rate, total trades, top holding. |+| `get_wallet_portfolio` | read-only | One KOL wallet's live portfolio card: holdings value, position count and top holding, plus 30d realized P&L, win rate, trades and volume from its own on-chain trades. || `get_wallet_trades` | read-only | That wallet's recent buys/sells of a given mint — side, SOL size, token amount, price, USD value, and timing, newest first. |-Both tools read live data: portfolio P&L and trade feeds move between calls, so neither is idempotent.+Both tools read live data: holdings, P&L and trade feeds move between calls, so neither is idempotent.### Input parameters@@ -85,11 +85,15 @@ Both tools read live data: portfolio P&L and trade feeds move between calls, so"ok": true,"wallet": "5xY…KoL","has_activity": true,+ "portfolio_value_usd": 38120,+ "holdings": 14,+ "top_token": { "symbol": "THREE", "valueUsd": 21500 },"realized_pnl_usd": 124300,- "unrealized_pnl_usd": 38120,"win_rate": 0.64,"total_trades": 412,- "top_token": { "symbol": "THREE", "pnl": 38120 }+ "volume_usd": 2840000,+ "pnl_source": "onchain-fifo",+ "pnl_window": "30d"}```@@ -107,7 +111,7 @@ Both tools read live data: portfolio P&L and trade feeds move between calls, so}```-`has_activity: false` on a portfolio (all-zero P&L, no trades, no holding) means the proxy has no recorded history for that address yet — an honest "no data", not a failure.+`has_activity: false` on a portfolio (no holdings and no trades) means the proxy has no recorded history for that address yet — an honest "no data", not a failure. A **null** P&L field with `pnl_source: null` is the same kind of honesty at field level: three.ws has no trade history for that wallet in the window, so it reports nothing rather than a zero that would read as a flat record.## Requirements@@ -121,7 +125,7 @@ Both tools read live data: portfolio P&L and trade feeds move between calls, so| `THREE_WS_BASE` | no | `https://three.ws` || `THREE_WS_TIMEOUT_MS` | no | `20000` |-No key on the client: the Birdeye key that backs portfolio P&L and the Helius key behind the trade feed both live server-side on three.ws.+No key on the client: the Birdeye key that backs the holdings half and the Helius key behind the trade feed both live server-side on three.ws.## Linksdiff --git a/packages/kol-mcp/src/index.js b/packages/kol-mcp/src/index.jsindex e10db1911..4068ab8bd 100755--- a/packages/kol-mcp/src/index.js+++ b/packages/kol-mcp/src/index.js@@ -5,11 +5,11 @@// (kol_leaderboard) and shows everyone's trades on a mint (kol_trades), this// server is the per-wallet deep dive: one tracked trader's portfolio P&L and// their own trades on a given token, for copy/analysis decisions.-// • get_wallet_portfolio — a KOL wallet's realized/unrealized P&L card+// • get_wallet_portfolio — a KOL wallet's holdings + real on-chain P&L card// • get_wallet_trades — that wallet's recent trades on a given mint//// A thin wrapper over the PUBLIC three.ws KOL API. No keys, no signer, no-// payment on the client — the Birdeye key that backs the portfolio P&L lives+// payment on the client — the Birdeye key that backs the holdings half lives// server-side on three.ws. Point THREE_WS_BASE at a deployment and go.//// Run standalone:@@ -45,8 +45,10 @@ export function buildServer() {capabilities: { tools: {} },instructions:'three.ws KOL MCP — track one smart trader. get_wallet_portfolio pulls a single ' +- "tracked KOL wallet's live portfolio P&L card: realized P&L, unrealized (open-position) " +- 'P&L, win rate, total trades, and its largest holding. get_wallet_trades returns that ' ++ "tracked KOL wallet's live portfolio card: current holdings value and largest holding, " ++ 'plus 30d realized P&L, win rate and trade count computed from its own on-chain trades ' ++ '(null where there is no trade history to measure, never a fabricated zero). ' ++ 'get_wallet_trades returns that ' +"same wallet's recent buys/sells of a specific mint — side, SOL size, price, USD value, " +'and timing, newest first. This is the per-wallet deep dive; to rank the whole KOL set or ' +'see every wallet\'s trades on a mint, use the intel-mcp server (kol_leaderboard, ' +diff --git a/packages/kol-mcp/src/tools/get-wallet-portfolio.js b/packages/kol-mcp/src/tools/get-wallet-portfolio.jsindex 49215f9be..bc650ecb9 100644--- a/packages/kol-mcp/src/tools/get-wallet-portfolio.js+++ b/packages/kol-mcp/src/tools/get-wallet-portfolio.js@@ -1,8 +1,11 @@-// `get_wallet_portfolio` — one KOL wallet's portfolio P&L card. Read-only.+// `get_wallet_portfolio` - one KOL wallet's holdings card plus its real trading+// record. Read-only.//-// Wraps GET /api/kol/wallets?addresses=<wallet>. The three.ws API proxies-// Birdeye's wallet portfolio (server-side key) and returns a normalized P&L-// summary per address. This tool focuses that on a single tracked trader.+// Wraps GET /api/kol/wallets?addresses=<wallet>. Two independently-sourced halves+// come back in one row: current holdings from Birdeye (server-side key) and, when+// three.ws has trade history for the wallet, realized P&L / win rate / volume+// FIFO-computed from that wallet's own on-chain trades. Any P&L field can be+// null, which means "no trade history to measure", never "flat".import { z } from 'zod';@@ -13,43 +16,46 @@ export const def = {title: 'KOL wallet portfolio + P&L',annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },description:- "Pull one KOL trader's live portfolio P&L card from the three.ws Birdeye proxy. " +- 'Returns realized P&L, unrealized P&L (current open-position value), win rate, total ' +- 'trades, and the single highest-value token the wallet holds (symbol + USD value). Use ' +- 'this to size up a specific smart trader before copying or analyzing them. For ranking ' +- 'many traders at once use intel-mcp `kol_leaderboard`; this is the per-wallet deep dive. ' +- '`has_activity:false` (all-zero P&L, no trades, no holding) means the proxy has no ' +- 'recorded portfolio for that address yet — an honest "no data", not a failure. ' ++ "Pull one KOL trader's live portfolio card from three.ws. Returns current holdings " ++ '(total USD value, position count, and the single highest-value token the wallet ' ++ 'holds) from the Birdeye proxy, plus realized P&L, win rate, trade count and volume ' ++ 'over the last 30 days FIFO-computed from that wallet\'s own on-chain trades. Use this ' ++ 'to size up a specific smart trader before copying or analyzing them. For ranking many ' ++ 'traders at once use intel-mcp `kol_leaderboard`; this is the per-wallet deep dive. ' ++ 'A null P&L field (with `pnl_source: null`) means three.ws has no trade history for ' ++ 'that wallet in the window, which is an honest "unknown", NOT a flat or losing record: ' ++ 'never report it as zero profit. `has_activity:false` means no holdings and no trades. ' +'Read-only live data.',inputSchema: {wallet: z.string().min(1)- .describe('The Solana wallet address of the KOL trader to pull a portfolio P&L card for.'),+ .describe('The Solana wallet address of the KOL trader to pull a portfolio card for.'),},async handler(args) {const wallet = String(args?.wallet ?? '').trim();const data = await apiRequest('/api/kol/wallets', { query: { addresses: wallet } });- // The proxy returns one normalized row per requested address (zeros when- // Birdeye has no history for it), so match ours out of the batch.+ // The proxy returns one row per requested address, and omits an address whose+ // upstream fetch failed rather than inventing a row for it.const rows = Array.isArray(data?.data) ? data.data : [];const row = rows.find((r) => r?.address === wallet) ?? rows[0] ?? {};- const realizedPnl = row.realizedPnl ?? 0;- const unrealizedPnl = row.unrealizedPnl ?? 0;- const winRate = row.winRate ?? 0;- const totalTrades = row.totalTrades ?? 0;- const topToken = row.topToken ?? null;+ const holdings = row.holdings ?? 0;+ const totalTrades = row.totalTrades ?? null;return {ok: true,wallet: row.address ?? wallet,- has_activity: totalTrades > 0 || realizedPnl !== 0 || unrealizedPnl !== 0 || topToken !== null,- realized_pnl_usd: realizedPnl,- unrealized_pnl_usd: unrealizedPnl,- win_rate: winRate,+ has_activity: holdings > 0 || (totalTrades ?? 0) > 0,+ portfolio_value_usd: row.totalUsd ?? null,+ holdings,+ top_token: row.topToken ?? null,+ realized_pnl_usd: row.realizedPnl ?? null,+ win_rate: row.winRate ?? null,total_trades: totalTrades,- top_token: topToken,+ volume_usd: row.volumeUsd ?? null,+ pnl_source: row.pnlSource ?? null,+ pnl_window: row.pnlWindow ?? null,};},};diff --git a/packages/mocap/README.md b/packages/mocap/README.mdindex cf4f9f40f..ecc5fade7 100644--- a/packages/mocap/README.md+++ b/packages/mocap/README.md@@ -130,10 +130,14 @@ derived from `format` server-side.### `getClip(idOrSlug, auth?) → Promise<Clip>`-Fetch one clip **with its full `frames` array** — ready to replay. Wraps-`GET /api/mocap/clips/:id`. Public and unlisted clips need no auth; a `private`-clip resolves only for its owner (otherwise `404`, never a leak). Each non-owner-fetch bumps `play_count`.+Fetch one clip **with its full `frames` array**, ready to replay. Wraps+`GET /api/mocap/clips/:idOrSlug`. Public and unlisted clips need no auth; a+`private` clip resolves only for its owner (otherwise `404`, never a leak). Each+non-owner fetch bumps `play_count`.++A slug is unique per owner, not globally, so a slug lookup resolves to your own+clip when you are authenticated and otherwise to the oldest public clip carrying+it. Pass the `id` when you need to name one exact clip.### `listClips(auth, opts?) → Promise<{ items, next_cursor }>`diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.jsonindex d86bb1da1..c02195352 100644--- a/public/locales/localized-pages.json+++ b/public/locales/localized-pages.json@@ -1,6 +1,6 @@{"generated": true,- "count": 355,+ "count": 243,"paths": ["/","/3d",@@ -157,118 +157,6 @@"/mocap-studio","/motion-swap","/my-agents",- "/news",- "/news/",- "/news/2045242891350814835",- "/news/2049397875935989970",- "/news/2049406826719137937",- "/news/2049412062837928202",- "/news/2049447738434339171",- "/news/2049458671139336613",- "/news/2049476546285740512",- "/news/2049557523330638269",- "/news/2049573582247022869",- "/news/2049576603324411933",- "/news/2049576641127682430",- "/news/2049577291957899336",- "/news/2049762836881301865",- "/news/2049765915575914834",- "/news/2049997615421649363",- "/news/2050016695897706885",- "/news/2050049239301165535",- "/news/2050221269732425928",- "/news/2050226678321102975",- "/news/2050229144676675999",- "/news/2050284562069266616",- "/news/2050585585191186781",- "/news/2050627547394916768",- "/news/2050753406109880576",- "/news/2050758788186353723",- "/news/2050800140295049308",- "/news/2050886334261391686",- "/news/2051140736201175323",- "/news/2051261108506558901",- "/news/2051616708482498843",- "/news/2051689230997618690",- "/news/2051690803203105230",- "/news/2051774915876098063",- "/news/2051858035862335505",- "/news/2051858503523066283",- "/news/2051893054584553680",- "/news/2052037977556287723",- "/news/2052167399399735476",- "/news/2052181307002929363",- "/news/2052189491801284690",- "/news/2052402481024667887",- "/news/2052402580266098813",- "/news/2052418108837781511",- "/news/2052418482269254040",- "/news/2052426446073983267",- "/news/2052588973466484922",- "/news/2052603250524967045",- "/news/2052685648377913671",- "/news/2052790746256920583",- "/news/2052791935585407403",- "/news/2053025259645981078",- "/news/2053698115203743922",- "/news/2053698387263008827",- "/news/2053730856339144932",- "/news/2053801703355629587",- "/news/2053804700609458214",- "/news/2053832201176027583",- "/news/2054404663802483072",- "/news/2054675701132132736",- "/news/2055140064070717618",- "/news/2055307440921702738",- "/news/2055309846556401735",- "/news/2055310365588922872",- "/news/2055517252964024561",- "/news/2055967730495586477",- "/news/2055985494606106821",- "/news/2056556899403997450",- "/news/2057721370310775223",- "/news/2057780453709648200",- "/news/2057782522994684413",- "/news/2057786164862730704",- "/news/2058076885805085111",- "/news/2058287578227577039",- "/news/2059456289789657537",- "/news/2059456294189498830",- "/news/2059456295825223723",- "/news/2059457822941978723",- "/news/2059675892981633179",- "/news/2059712761622675776",- "/news/2059821472156446844",- "/news/2059894004771418220",- "/news/2060178868305326413",- "/news/2060186881636422038",- "/news/2061418285896269952",- "/news/2061488909264040194",- "/news/2061523804405616642",- "/news/2061713039624405062",- "/news/aws-agentic-economy-three-ws",- "/news/aws-builder-center-3d-agents-onchain-payments",- "/news/aws-builder-center-blog",- "/news/aws-marketplace-live-may29",- "/news/bybit-alpha-listing",- "/news/cmc-mcp-registry-article",- "/news/cmc-memecoin-3d-world",- "/news/ibm-collaboration-showcase",- "/news/ibm-showcase-may31",- "/news/joined-aws-partner-network",- "/news/listed-on-bnb-chain-dappbay",- "/news/live-on-alibaba-cloud-marketplace",- "/news/live-on-aws-marketplace",- "/news/mcp-servers-x402-bazaar-coinbase",- "/news/monetize-mcp-server-x402-paid-tools",- "/news/moonshot-verified",- "/news/partnered-with-hackernoon",- "/news/quicknode-startup-program",- "/news/text-to-3d-is-live",- "/news/three-ws-dextools-social-boost-buyback",- "/news/three-ws-featured-on-alibaba-cloud-marketplace-blog",- "/news/three-ws-first-month-3d-agent-layer",- "/news/threews-play-coin-communities","/nim-forge","/notifications","/nvidia",diff --git a/public/mcp-catalog.json b/public/mcp-catalog.jsonindex 50b2b1a80..66913b353 100644--- a/public/mcp-catalog.json+++ b/public/mcp-catalog.json@@ -12425,7 +12425,7 @@{"name": "find_services","title": "Find paid services the agent can call",- "description": "Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL — feed a resource into pay_and_call to actually use it.",+ "description": "Search the live x402 facilitator network for paid services (HTTP APIs and MCP tools). Returns each match with its price and resource URL. Feed a resource into pay_and_call to actually use it.","server": {"id": "threews-agent","title": "Agent Wallet",@@ -12485,7 +12485,7 @@{"name": "monetize_endpoint","title": "Publish a paid endpoint to earn USDC",- "description": "Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network — run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.",+ "description": "Put a price on an upstream API your agent already serves and publish it as an x402 endpoint other agents can pay to call. three.ws hosts the paywall, settles each buyer's USDC to your agent's own wallet, and proxies the call to your target_url. The listing becomes discoverable via find_services / the bazaar and callable by pay_and_call. Requires a provisioned wallet for the chosen network; run provision_wallet first if you haven't. Requires sign-in; you can only monetize agents on your own account.","server": {"id": "threews-agent","title": "Agent Wallet",@@ -12621,7 +12621,7 @@{"name": "provision_wallet","title": "Create the agent's wallet",- "description": "Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent — if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.",+ "description": "Create (or return) the custodial Solana wallet for one of your agents so it can hold and earn USDC. Idempotent: if the agent already has a wallet, its address and live SOL/USDC balances are returned unchanged. On devnet you can request a 1 SOL airdrop for testing; mainnet wallets are never airdropped. Requires sign-in; you can only provision wallets for agents on your own account.","server": {"id": "threews-agent","title": "Agent Wallet",@@ -12659,7 +12659,7 @@"airdrop": {"type": "boolean","default": false,- "description": "Devnet only — request a 1 SOL faucet airdrop after provisioning."+ "description": "Devnet only: request a 1 SOL faucet airdrop after provisioning."}},"required": [@@ -12672,7 +12672,7 @@{"name": "wallet_status","title": "Check the agent's wallet",- "description": "Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only — never moves funds. Call this before pay_and_call to confirm there's balance and headroom.",+ "description": "Show the signed-in user's three.ws agent wallet: address, SOL and USDC balance, the per-call/hour/day spending caps, and whether autonomous spending is enabled. Read-only, never moves funds. Call this before pay_and_call to confirm there's balance and headroom.","server": {"id": "threews-agent","title": "Agent Wallet",diff --git a/src/kol/wallet-pnl.js b/src/kol/wallet-pnl.jsindex 71e1ee1c4..bf2cd3bc6 100644--- a/src/kol/wallet-pnl.js+++ b/src/kol/wallet-pnl.js@@ -31,7 +31,7 @@ function consumeFifo(lots, sellTokens, proceedsUsd) {* Pure FIFO P&L computation. Exported for unit testing.** @param {{ trades: Array, currentPrices?: Object, windowSecs?: number }} opts- * @returns {{ realizedUsd, unrealizedUsd, totalUsd, winRate, trades, volumeUsd, openPositions }}+ * @returns {{ realizedUsd, unrealizedUsd, totalUsd, winRate, closedTrades, trades, volumeUsd, openPositions }}*/export function computeWalletPnl({ trades, currentPrices = {}, windowSecs = Infinity }) {const now = Date.now() / 1000;@@ -88,6 +88,10 @@ export function computeWalletPnl({ trades, currentPrices = {}, windowSecs = InfiunrealizedUsd,totalUsd: realizedUsd + unrealizedUsd,winRate,+ // A wallet that has only bought has no win rate yet, and `winRate: 0` cannot+ // say so on its own. Callers that must distinguish "0% wins" from "nothing+ // closed to measure" read this count; the tracker board keeps using winRate.+ closedTrades,trades: sorted.length,volumeUsd,openPositions,diff --git a/tests/api-labor-endpoints.test.js b/tests/api-labor-endpoints.test.jsnew file mode 100644index 000000000..5260dfac7--- /dev/null+++ b/tests/api-labor-endpoints.test.js@@ -0,0 +1,311 @@+// HTTP-boundary tests for the Agent Labor Market write endpoints+// (api/labor/{award,deliver,settle,release,post}.js).+//+// tests/api-labor-lifecycle.test.js covers the settlement engine and+// tests/agent-labor-economics.test.js covers the pure math. What is covered+// HERE is the layer neither of those sees: what an endpoint does with an+// untrusted request body before it reaches Postgres or a wallet.+//+// 1. Every id these handlers hand to Postgres keys a uuid column. Award,+// deliver, settle, release and post skipped the uuid guard their siblings+// already used, so `{"jobId":"zzz"}` reached the driver and came back as+// SQLSTATE 22P02: an opaque 500 on the read paths, and on the ownership+// paths a 400 that echoed the raw Postgres message to the caller.+// 2. post.js parsed the reward with toBig()/threeToAtomics(), which throw a+// SyntaxError on junk (500) or silently coerce it to zero (a "reward must+// be greater than zero" answer for a value that was never a number), and+// passed `deadline` straight into a timestamptz column.+// 3. deliver.js clamped an object deliverable's `output` to 8000 chars and+// then spread the caller's original back over the clamp, so the cap did+// nothing and any payload size reached the verifier prompt.++import { Readable } from 'node:stream';+import { describe, it, expect, beforeEach, vi } from 'vitest';++const OWNER = 'owner-1';+const STRANGER = 'owner-2';+const BOUNTY_ID = '11111111-1111-4111-8111-111111111111';+const BID_ID = '22222222-2222-4222-8222-222222222222';+const JOB_ID = '33333333-3333-4333-8333-333333333333';+const AGENT_ID = '44444444-4444-4444-8444-444444444444';+const WORKER_ID = '55555555-5555-4555-8555-555555555555';+const WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';++const authState = { session: { id: OWNER } };+const sqlState = { queue: [], calls: [] };+const laborState = {};+const escrowState = {};++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (...args) => {+ sqlState.calls.push(args);+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ laborPost: vi.fn(async () => ({ success: true })),+ laborBid: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));+vi.mock('../api/_lib/admin.js', () => ({+ requireAdmin: vi.fn(async () => ({ id: 'admin-1', wallet_address: WALLET })),+ isAdminRequest: vi.fn(async () => true),+}));++// agent-labor: real pure math (the parsers under test), spies for every DB leaf.+vi.mock('../api/_lib/agent-labor.js', async () => {+ const econ = await import('../api/_lib/labor-economics.js');+ return {+ atomicsToThree: econ.atomicsToThree,+ threeToAtomics: econ.threeToAtomics,+ parseAtomics: econ.parseAtomics,+ parseThree: econ.parseThree,+ _toBig: econ.toBig,+ getBounty: vi.fn(async () => laborState.bounty ?? null),+ getBid: vi.fn(async () => laborState.bid ?? null),+ listBidsForBounty: vi.fn(async () => laborState.bids ?? []),+ getJob: vi.fn(async () => laborState.job ?? null),+ getJobByBounty: vi.fn(async () => laborState.job ?? null),+ markJobDelivered: vi.fn(async (_id, deliverable) => {+ laborState.delivered = deliverable;+ return { ...laborState.job, status: 'delivered', deliverable };+ }),+ createBounty: vi.fn(async (input) => {+ laborState.created = input;+ return { id: BOUNTY_ID, ...input };+ }),+ setBountyEscrow: vi.fn(async () => ({ id: BOUNTY_ID })),+ setBountyStatus: vi.fn(async () => ({ id: BOUNTY_ID })),+ };+});+vi.mock('../api/_lib/labor-match.js', () => ({+ applyAward: vi.fn(async () => ({ job: { id: JOB_ID, status: 'working' } })),+ emitReasoning: vi.fn(async () => {}),+}));+vi.mock('../api/_lib/labor-settle.js', () => ({+ runAutopilot: vi.fn(async () => ({ bids: 0, awarded: true, settled: null, settledNow: false })),+ runSettlement: vi.fn(async () => ({ settled: true, status: 'settled' })),+}));+vi.mock('../api/_lib/labor-escrow.js', () => ({+ escrowConfigured: vi.fn(() => true),+ escrowAddressOrNull: vi.fn(() => 'ESCROWADDR'),+ fundEscrow: vi.fn(async () => 'FUNDSIG'),+ payFromEscrow: vi.fn(async () => 'PAYSIG'),+ ensureEscrowGas: vi.fn(async () => ({ topped: false })),+}));+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: vi.fn(async () => ({ priceUsd: 0.01 })) }));+vi.mock('../api/_lib/agent-wallet.js', () => ({+ recoverSolanaAgentKeypair: vi.fn(async () => ({ publicKey: { toBase58: () => WALLET } })),+}));+vi.mock('../api/_lib/agent-trade-guards.js', () => ({+ SpendLimitError: class SpendLimitError extends Error {},+ reserveSpendUsd: vi.fn(async () => ({ reservationId: 'res-1' })),+ releaseSpendReservation: vi.fn(async () => {}),+ updateCustodyEvent: vi.fn(async () => {}),+}));++const award = (await import('../api/labor/award.js')).default;+const deliver = (await import('../api/labor/deliver.js')).default;+const settle = (await import('../api/labor/settle.js')).default;+const release = (await import('../api/labor/release.js')).default;+const post = (await import('../api/labor/post.js')).default;++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },+ };+}++async function call(handler, path, body, method = 'POST') {+ const raw = body === undefined ? null : JSON.stringify(body);+ const req = Readable.from(raw == null ? [] : [Buffer.from(raw)]);+ req.method = method;+ req.url = path;+ req.headers = { host: 'localhost', ...(raw == null ? {} : { 'content-type': 'application/json' }) };+ const res = makeRes();+ await handler(req, res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++/** The agent row loadOwnedAgent reads, owned by `userId`. */+function primeAgent(userId = OWNER) {+ sqlState.queue.push([{+ id: AGENT_ID, user_id: userId, name: 'Poster',+ meta: { solana_address: WALLET, encrypted_solana_secret: 'enc' },+ }]);+}++beforeEach(() => {+ authState.session = { id: OWNER };+ sqlState.queue = [];+ sqlState.calls = [];+ for (const k of Object.keys(laborState)) delete laborState[k];+ for (const k of Object.keys(escrowState)) delete escrowState[k];+});++describe('labor endpoints: uuid boundary', () => {+ it('award refuses a malformed bountyId with 400 before any query', async () => {+ const { status, body } = await call(award, '/api/labor/award', { bountyId: 'zzz', bidId: BID_ID });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(body.error_description).toBe('bountyId must be a uuid');+ expect(sqlState.calls).toHaveLength(0);+ });++ it('award refuses a malformed bidId with 400', async () => {+ const { status, body } = await call(award, '/api/labor/award', { bountyId: BOUNTY_ID, bidId: 'nope' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('bidId must be a uuid');+ });++ it('deliver refuses a malformed jobId with 400', async () => {+ const { status, body } = await call(deliver, '/api/labor/deliver', { jobId: 'zzz', deliverable: 'done' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('jobId must be a uuid');+ });++ it('settle names the missing input instead of reporting a missing job', async () => {+ const { status, body } = await call(settle, '/api/labor/settle', {});+ expect(status).toBe(400);+ expect(body.error_description).toBe('jobId or bountyId is required');+ });++ it('settle refuses a malformed bountyId with 400', async () => {+ const { status, body } = await call(settle, '/api/labor/settle', { bountyId: 'zzz' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('bountyId must be a uuid');+ });++ it('release refuses a malformed bountyId with 400', async () => {+ const { status, body } = await call(release, '/api/labor/release', { bountyId: 'zzz', action: 'refund' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('bountyId must be a uuid');+ });++ it('post refuses a malformed posterAgentId with 400', async () => {+ const { status, body } = await call(post, '/api/labor/post', {+ posterAgentId: 'zzz', title: 'Title', spec: 'Spec', rewardThree: 1,+ });+ expect(status).toBe(400);+ expect(body.error_description).toBe('posterAgentId must be a uuid');+ });+});++describe('labor endpoints: ownership', () => {+ it('award answers 403 when the caller does not own the posting agent', async () => {+ laborState.bounty = { id: BOUNTY_ID, poster_agent_id: AGENT_ID, status: 'open' };+ primeAgent(STRANGER);+ const { status, body } = await call(award, '/api/labor/award', { bountyId: BOUNTY_ID, bidId: BID_ID });+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ });++ it('deliver rethrows an infrastructure fault instead of echoing it as a 400', async () => {+ laborState.job = { id: JOB_ID, worker_agent_id: WORKER_ID, status: 'working', bounty_id: BOUNTY_ID };+ const db = await import('../api/_lib/db.js');+ db.sql.mockImplementationOnce(async () => { throw new Error('connection terminated unexpectedly'); });+ const { status, body } = await call(deliver, '/api/labor/deliver', { jobId: JOB_ID, deliverable: 'done' });+ expect(status).toBe(500);+ expect(body.error_description).not.toContain('connection terminated');+ });++ it('award drives the autopilot and reports the job on the happy path', async () => {+ laborState.bounty = { id: BOUNTY_ID, poster_agent_id: AGENT_ID, status: 'open' };+ laborState.bid = { id: BID_ID, bounty_id: BOUNTY_ID, status: 'pending', worker_user_id: OWNER, price_atomics: '1000000' };+ laborState.bids = [{ id: BID_ID, worker_agent_id: WORKER_ID, worker_name: 'Worker', price_three: 1, score: 0.8 }];+ laborState.job = { id: JOB_ID, status: 'working' };+ primeAgent(OWNER);+ const { status, body } = await call(award, '/api/labor/award', { bountyId: BOUNTY_ID, bidId: BID_ID });+ expect(status).toBe(200);+ expect(body.award.job_id).toBe(JOB_ID);+ expect(body.award.rationale).not.toMatch(/[\u2013\u2014]/);+ });+});++describe('labor/deliver: deliverable clamping', () => {+ beforeEach(() => {+ laborState.job = { id: JOB_ID, worker_agent_id: AGENT_ID, status: 'working', bounty_id: BOUNTY_ID };+ laborState.bounty = { id: BOUNTY_ID, spec: 'Spec' };+ });++ it('clamps an object deliverable to 8000 chars and keeps its other keys', async () => {+ primeAgent(OWNER);+ const { status } = await call(deliver, '/api/labor/deliver', {+ jobId: JOB_ID,+ deliverable: { output: 'x'.repeat(20000), format: 'markdown' },+ });+ expect(status).toBe(200);+ expect(laborState.delivered.output).toHaveLength(8000);+ expect(laborState.delivered.format).toBe('markdown');+ expect(laborState.delivered.produced_at).toBeTruthy();+ });++ it('clamps a string deliverable the same way', async () => {+ primeAgent(OWNER);+ const { status } = await call(deliver, '/api/labor/deliver', { jobId: JOB_ID, deliverable: 'y'.repeat(9000) });+ expect(status).toBe(200);+ expect(laborState.delivered.output).toHaveLength(8000);+ });++ it('refuses an array deliverable rather than spreading its indexes', async () => {+ primeAgent(OWNER);+ const { status, body } = await call(deliver, '/api/labor/deliver', { jobId: JOB_ID, deliverable: ['a', 'b'] });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });+});++describe('labor/post: reward and deadline parsing', () => {+ const base = { posterAgentId: AGENT_ID, title: 'Ship the thing', spec: 'Do the work' };++ it('answers 400 for an unparseable rewardAtomics instead of throwing a 500', async () => {+ const { status, body } = await call(post, '/api/labor/post', { ...base, rewardAtomics: 'abc' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('reward must be a non-negative amount of $THREE');+ });++ it('distinguishes a missing reward from a zero one', async () => {+ const { status, body } = await call(post, '/api/labor/post', base);+ expect(status).toBe(400);+ expect(body.error_description).toBe('rewardThree or rewardAtomics is required');+ });++ it('refuses a reward of zero', async () => {+ const { status, body } = await call(post, '/api/labor/post', { ...base, rewardThree: 0 });+ expect(status).toBe(400);+ expect(body.error_description).toBe('reward must be greater than zero');+ });++ it('refuses an unparseable deadline before writing the bounty row', async () => {+ const { status, body } = await call(post, '/api/labor/post', { ...base, rewardThree: 5, deadline: 'next tuesday-ish' });+ expect(status).toBe(400);+ expect(body.error_description).toBe('deadline must be an ISO 8601 timestamp');+ });++ it('normalizes a valid deadline to ISO 8601 and escrows the parsed reward', async () => {+ primeAgent(OWNER);+ sqlState.queue.push([{ id: BOUNTY_ID, title: base.title, status: 'open', reward_atomics: '5000000', bid_count: 0 }]);+ const { status, body } = await call(post, '/api/labor/post', {+ ...base, rewardThree: 5, deadline: '2026-09-01T12:00:00Z',+ });+ expect(status).toBe(200);+ expect(body.ok).toBe(true);+ expect(laborState.created.deadline).toBe('2026-09-01T12:00:00.000Z');+ expect(String(laborState.created.rewardAtomics)).toBe('5000000');+ });+});diff --git a/tests/api/friends-mutations.test.js b/tests/api/friends-mutations.test.jsnew file mode 100644index 000000000..abea38649--- /dev/null+++ b/tests/api/friends-mutations.test.js@@ -0,0 +1,235 @@+// POST /api/friends — the graph-mutation contract.+//+// One endpoint fans out to six store actions, so the dispatch table and the+// input guards in front of it are the whole security surface: an unknown action+// must not fall through to a mutation, a target that is not a UUID must never+// reach the store, and a store-thrown contract error (self-add, unknown user,+// no pending request) must surface with its own status and code rather than+// collapsing into a 500. The live-notification side effects are pinned too,+// because they fire per action and the request/accept split is easy to invert.+//+// Mocks: the auth, rate-limit, CSRF, presence, and friends-store boundaries+// only. The real handler and the real api/_lib/http.js response layer run.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const ME = '00000000-0000-0000-0000-0000000000aa';+const OTHER = '00000000-0000-0000-0000-0000000000bb';++const authState = { account: { userId: ME } };+vi.mock('../../api/_lib/account-auth.js', () => ({+ resolveAccount: vi.fn(async () => authState.account),+}));++const rlState = { success: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => rlState),+ chatUser: vi.fn(async () => rlState),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const csrfState = { ok: true };+vi.mock('../../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => csrfState.ok),+}));++const notifyMultiplayer = vi.fn(async () => ({ delivered: true }));+vi.mock('../../api/_lib/presence-store.js', () => ({+ readPresence: vi.fn(async () => ({})),+ notifyMultiplayer: (...a) => notifyMultiplayer(...a),+}));++const store = {+ listGraph: vi.fn(async () => ({ friends: [], incoming: [], outgoing: [] })),+ sendRequest: vi.fn(async () => ({ status: 'requested' })),+ acceptRequest: vi.fn(async () => ({ friendshipId: 'f-1' })),+ declineRequest: vi.fn(async () => ({ ok: true })),+ removeFriend: vi.fn(async () => ({ ok: true })),+ muteUser: vi.fn(async () => ({ ok: true })),+ unmuteUser: vi.fn(async () => ({ ok: true })),+};+vi.mock('../../api/_lib/friends-store.js', () => ({+ listGraph: (...a) => store.listGraph(...a),+ sendRequest: (...a) => store.sendRequest(...a),+ acceptRequest: (...a) => store.acceptRequest(...a),+ declineRequest: (...a) => store.declineRequest(...a),+ removeFriend: (...a) => store.removeFriend(...a),+ muteUser: (...a) => store.muteUser(...a),+ unmuteUser: (...a) => store.unmuteUser(...a),+}));++const { default: handler } = await import('../../api/friends/index.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; },+ };+}++async function post(payload) {+ const res = makeRes();+ await handler({+ method: 'POST',+ url: '/api/friends',+ query: {},+ headers: { 'content-type': 'application/json' },+ rawBody: Buffer.from(JSON.stringify(payload)),+ }, res);+ let body = null;+ try { body = JSON.parse(res._body); } catch { /* non-JSON body stays null */ }+ return { res, body };+}++// Every store call this suite could possibly reach — used to assert that a+// rejected request mutated nothing at all, not merely that one action was skipped.+const mutators = () => [+ store.sendRequest, store.acceptRequest, store.declineRequest,+ store.removeFriend, store.muteUser, store.unmuteUser,+];++beforeEach(() => {+ vi.clearAllMocks();+ rlState.success = true;+ csrfState.ok = true;+ authState.account = { userId: ME };+ store.sendRequest.mockResolvedValue({ status: 'requested' });+ store.acceptRequest.mockResolvedValue({ friendshipId: 'f-1' });+ store.declineRequest.mockResolvedValue({ ok: true });+ store.removeFriend.mockResolvedValue({ ok: true });+ store.muteUser.mockResolvedValue({ ok: true });+ store.unmuteUser.mockResolvedValue({ ok: true });+});++describe('POST /api/friends dispatch', () => {+ it('sends a fresh request and notifies the target', async () => {+ const { res, body } = await post({ action: 'request', to: OTHER });+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ status: 'requested' });+ expect(store.sendRequest).toHaveBeenCalledWith(ME, OTHER);+ expect(notifyMultiplayer).toHaveBeenCalledWith('friend_request', OTHER, { from: ME });+ });++ it('notifies an accept (not a request) when the invite was reciprocal', async () => {+ store.sendRequest.mockResolvedValue({ status: 'accepted', relationship: 'friends' });+ await post({ action: 'request', to: OTHER });+ expect(notifyMultiplayer).toHaveBeenCalledWith('friend_accept', OTHER, { from: ME });+ });++ it('stays silent when the relationship already existed', async () => {+ store.sendRequest.mockResolvedValue({ status: 'exists', relationship: 'friends' });+ const { res } = await post({ action: 'request', to: OTHER });+ expect(res.statusCode).toBe(200);+ expect(notifyMultiplayer).not.toHaveBeenCalled();+ });++ it('accepts an incoming request and notifies the requester', async () => {+ const { res, body } = await post({ action: 'accept', userId: OTHER });+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ friendshipId: 'f-1' });+ expect(notifyMultiplayer).toHaveBeenCalledWith('friend_accept', OTHER, { from: ME });+ });++ it.each([+ ['decline', 'declineRequest'],+ ['remove', 'removeFriend'],+ ['mute', 'muteUser'],+ ['unmute', 'unmuteUser'],+ ])('routes %s to the store without a live notification', async (action, fn) => {+ const { res, body } = await post({ action, userId: OTHER });+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ ok: true });+ expect(store[fn]).toHaveBeenCalledWith(ME, OTHER);+ expect(notifyMultiplayer).not.toHaveBeenCalled();+ });+});++describe('POST /api/friends input guards', () => {+ it('rejects an unknown action without touching the store', async () => {+ const { res, body } = await post({ action: 'block', userId: OTHER });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_action');+ for (const fn of mutators()) expect(fn).not.toHaveBeenCalled();+ });++ it('rejects a missing action', async () => {+ const { res, body } = await post({ userId: OTHER });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_action');+ });++ it('rejects a target that is not a uuid', async () => {+ const { res, body } = await post({ action: 'remove', userId: 'me-please' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_target');+ for (const fn of mutators()) expect(fn).not.toHaveBeenCalled();+ });++ it('rejects an object smuggled in where the target id belongs', async () => {+ const { res, body } = await post({ action: 'remove', userId: { id: OTHER } });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_target');+ });++ it('stops a cookie-session caller that fails the CSRF check', async () => {+ csrfState.ok = false;+ const { res } = await post({ action: 'remove', userId: OTHER });+ for (const fn of mutators()) expect(fn).not.toHaveBeenCalled();+ // requireCsrf owns the response; the handler must not write a second one.+ expect(res._body).toBeUndefined();+ });++ it('answers 429 before mutating when the per-account action limit trips', async () => {+ rlState.success = false;+ const { res, body } = await post({ action: 'remove', userId: OTHER });+ expect(res.statusCode).toBe(429);+ expect(body.error_description).toBe('slow down');+ for (const fn of mutators()) expect(fn).not.toHaveBeenCalled();+ });++ it('requires a signed-in account', async () => {+ authState.account = null;+ const { res, body } = await post({ action: 'remove', userId: OTHER });+ expect(res.statusCode).toBe(401);+ expect(body.error).toBe('unauthorized');+ });+});++describe('POST /api/friends store contract errors', () => {+ // The store throws Errors carrying { status, code }. api/_lib/http.js wrap()+ // hands a sub-500 status straight through with its code, so these stay+ // actionable for the caller instead of becoming an opaque internal_error.+ it.each([+ ['self_add', 400, 'You cannot add yourself.', 'request'],+ ['not_found', 404, 'User not found.', 'request'],+ ])('surfaces %s as %i', async (code, status, message, action) => {+ store.sendRequest.mockRejectedValue(Object.assign(new Error(message), { status, code }));+ const { res, body } = await post({ action, to: OTHER });+ expect(res.statusCode).toBe(status);+ expect(body.error).toBe(code);+ expect(body.error_description).toBe(message);+ });++ it('surfaces a missing pending request as 404 no_request', async () => {+ store.acceptRequest.mockRejectedValue(+ Object.assign(new Error('No pending request from that user.'), { status: 404, code: 'no_request' }),+ );+ const { res, body } = await post({ action: 'accept', userId: OTHER });+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('no_request');+ expect(notifyMultiplayer).not.toHaveBeenCalled();+ });++ it('does not leak an internal database code through a 5xx', async () => {+ store.removeFriend.mockRejectedValue(Object.assign(new Error('connection terminated'), { code: '57P01' }));+ const { res, body } = await post({ action: 'remove', userId: OTHER });+ expect(res.statusCode).toBe(500);+ expect(body.error).toBe('internal_error');+ expect(JSON.stringify(body)).not.toContain('57P01');+ });+});diff --git a/tests/api/friends-search-ticket.test.js b/tests/api/friends-search-ticket.test.jsnew file mode 100644index 000000000..0ecbf969e--- /dev/null+++ b/tests/api/friends-search-ticket.test.js@@ -0,0 +1,135 @@+// /api/friends/search and /api/friends/presence-ticket — the two read-only+// friends endpoints.+//+// The search endpoint hands its term straight to an ILIKE wrapped in wildcards,+// so the term's length is the one thing it has to bound: an unbounded query+// string became an unbounded pattern matched against every row in `users`. That+// cap is pinned here, alongside the auth gate both endpoints share.+//+// Mocks: the auth, rate-limit, and store boundaries only. The real handlers and+// the real api/_lib/http.js response layer run.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const ME = '00000000-0000-0000-0000-0000000000aa';++const authState = { account: { userId: ME } };+vi.mock('../../api/_lib/account-auth.js', () => ({+ resolveAccount: vi.fn(async () => authState.account),+}));++const rlState = { success: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => rlState),+ authedReadIp: vi.fn(async () => rlState),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const searchUsers = vi.fn(async () => []);+vi.mock('../../api/_lib/friends-store.js', () => ({+ searchUsers: (...a) => searchUsers(...a),+}));++const signPresenceTicket = vi.fn(async () => ({ token: 'payload.sig', expiresIn: 600 }));+vi.mock('../../api/_lib/presence-store.js', () => ({+ signPresenceTicket: (...a) => signPresenceTicket(...a),+}));++const { default: searchHandler } = await import('../../api/friends/search.js');+const { default: ticketHandler } = await import('../../api/friends/presence-ticket.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(body) { this._body = body; },+ };+}++async function call(handler, url) {+ const res = makeRes();+ await handler({ method: 'GET', headers: {}, query: {}, url }, res);+ let body = null;+ try { body = JSON.parse(res._body); } catch { /* non-JSON body stays null */ }+ return { res, body };+}++const search = (qs) => call(searchHandler, `/api/friends/search${qs}`);+const ticket = () => call(ticketHandler, '/api/friends/presence-ticket');++beforeEach(() => {+ vi.clearAllMocks();+ rlState.success = true;+ authState.account = { userId: ME };+ searchUsers.mockResolvedValue([]);+ signPresenceTicket.mockResolvedValue({ token: 'payload.sig', expiresIn: 600 });+});++describe('GET /api/friends/search', () => {+ it('returns annotated hits for a real term', async () => {+ const hits = [{ id: 'u-1', name: 'ada', username: 'ada', avatarUrl: null, relationship: 'none' }];+ searchUsers.mockResolvedValue(hits);+ const { res, body } = await search('?q=ada');+ expect(res.statusCode).toBe(200);+ expect(body.data.results).toEqual(hits);+ expect(searchUsers).toHaveBeenCalledWith(ME, 'ada');+ });++ it('treats a missing q as an empty term rather than erroring', async () => {+ const { res } = await search('');+ expect(res.statusCode).toBe(200);+ expect(searchUsers).toHaveBeenCalledWith(ME, '');+ });++ it('rejects an oversized term instead of handing an unbounded pattern to Postgres', async () => {+ const { res, body } = await search(`?q=${'a'.repeat(201)}`);+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_query');+ expect(searchUsers).not.toHaveBeenCalled();+ });++ it('accepts a term exactly at the cap', async () => {+ const { res } = await search(`?q=${'a'.repeat(200)}`);+ expect(res.statusCode).toBe(200);+ expect(searchUsers).toHaveBeenCalledWith(ME, 'a'.repeat(200));+ });++ it('requires a signed-in account', async () => {+ authState.account = null;+ const { res, body } = await search('?q=ada');+ expect(res.statusCode).toBe(401);+ expect(body.error).toBe('unauthorized');+ expect(searchUsers).not.toHaveBeenCalled();+ });+});++describe('GET /api/friends/presence-ticket', () => {+ it('mints a ticket for the caller and reports its lifetime', async () => {+ const { res, body } = await ticket();+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ token: 'payload.sig', expiresIn: 600 });+ // The ticket is bound to the resolved account, never to anything the+ // client sent — that binding is the whole point of the endpoint.+ expect(signPresenceTicket).toHaveBeenCalledWith(ME);+ });++ it('refuses to mint a ticket for an anonymous caller', async () => {+ authState.account = null;+ const { res, body } = await ticket();+ expect(res.statusCode).toBe(401);+ expect(body.error).toBe('unauthorized');+ expect(signPresenceTicket).not.toHaveBeenCalled();+ });++ it('answers 429 before minting when the read limit trips', async () => {+ rlState.success = false;+ const { res, body } = await ticket();+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(signPresenceTicket).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/kol-wallets-portfolio.test.js b/tests/api/kol-wallets-portfolio.test.jsnew file mode 100644index 000000000..d31e26958--- /dev/null+++ b/tests/api/kol-wallets-portfolio.test.js@@ -0,0 +1,183 @@+// GET /api/kol/wallets (api/kol/[action].js -> handleWallets).+//+// The regression this pins: the row used to advertise a P&L card that Birdeye+// never supplies. `/v1/wallet/portfolio` is a holdings endpoint, so+// `realizedPnl`, `winRate` and `totalTrades` were hardcoded zeros,+// `unrealizedPnl` was really the portfolio's total USD value under a P&L name,+// and `topToken.pnl` was the top holding's value. `get_wallet_portfolio` in+// packages/kol-mcp handed all four to agents as measured numbers, so a wallet+// with a real losing record and a wallet we had never measured looked identical.+//+// Now the row states its sources: holdings from Birdeye, and P&L FIFO-computed+// from the wallet's own on-chain trades, with every P&L field null when there is+// no trade history to measure.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const getWalletPnl = vi.fn();+vi.mock('../../src/kol/wallet-pnl.js', () => ({ getWalletPnl }));+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { mcpIp: async () => ({ success: true }) },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/kol/[action].js');++// A verbatim-shaped Birdeye /v1/wallet/portfolio payload: positions and their+// USD value, and not one P&L field anywhere in it.+const BIRDEYE_PORTFOLIO = {+ success: true,+ data: {+ wallet: 'THREEsynthetic1111111111111111111111111111',+ totalUsd: 38120.5,+ items: [+ { symbol: 'SOL', valueUsd: 16620.5 },+ { symbol: 'THREE', valueUsd: 21500 },+ ],+ },+};++const WALLET = 'THREEsynthetic1111111111111111111111111111';++function call(url) {+ const res = {+ statusCode: 0,+ body: null,+ headers: {},+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b ? JSON.parse(b) : null;+ },+ get headersSent() {+ return this.body !== null;+ },+ get writableEnded() {+ return this.body !== null;+ },+ };+ const req = { method: 'GET', url, headers: { host: 'three.ws' }, query: { action: 'wallets' } };+ return handler(req, res).then(() => res);+}++// Each test uses a distinct address so the handler's 60s per-address cache+// (module state, shared across tests in this file) never serves a stale row.+function addrFor(tag) {+ return `${WALLET.slice(0, 20)}${tag}`.padEnd(43, '1');+}++beforeEach(() => {+ process.env.BIRDEYE_API_KEY = 'test-birdeye-key';+ getWalletPnl.mockReset();+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ ok: true, status: 200, json: async () => BIRDEYE_PORTFOLIO })),+ );+});++afterEach(() => {+ vi.unstubAllGlobals();+ delete process.env.BIRDEYE_API_KEY;+});++describe('GET /api/kol/wallets', () => {+ it('requires a Birdeye key and says so', async () => {+ delete process.env.BIRDEYE_API_KEY;+ const res = await call(`/api/kol/wallets?addresses=${addrFor('a')}`);+ expect(res.statusCode).toBe(503);+ expect(res.body.error).toBe('birdeye_not_configured');+ });++ it('rejects a request with no addresses', async () => {+ const res = await call('/api/kol/wallets?addresses=');+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ });++ it('reports Birdeye holdings under holdings names', async () => {+ const addr = addrFor('b');+ getWalletPnl.mockResolvedValue({ trades: 0, closedTrades: 0 });+ const res = await call(`/api/kol/wallets?addresses=${addr}`);+ expect(res.statusCode).toBe(200);+ const [row] = res.body.data;+ expect(row.address).toBe(addr);+ expect(row.totalUsd).toBe(38120.5);+ expect(row.holdings).toBe(2);+ expect(row.topToken).toEqual({ symbol: 'THREE', valueUsd: 21500 });+ });++ it('never emits a P&L number Birdeye did not supply', async () => {+ const addr = addrFor('c');+ getWalletPnl.mockResolvedValue({ trades: 0, closedTrades: 0 });+ const res = await call(`/api/kol/wallets?addresses=${addr}`);+ const [row] = res.body.data;+ // No trade history: unknown, not flat. A zero here is the old bug.+ expect(row.realizedPnl).toBeNull();+ expect(row.winRate).toBeNull();+ expect(row.totalTrades).toBeNull();+ expect(row.volumeUsd).toBeNull();+ expect(row.pnlSource).toBeNull();+ // The field that used to carry the portfolio value under a P&L name is gone.+ expect(row).not.toHaveProperty('unrealizedPnl');+ });++ it('merges real FIFO P&L when the wallet has on-chain trades', async () => {+ const addr = addrFor('d');+ getWalletPnl.mockResolvedValue({+ trades: 412,+ closedTrades: 200,+ realizedUsd: 124300,+ winRate: 0.64,+ volumeUsd: 2840000,+ });+ const res = await call(`/api/kol/wallets?addresses=${addr}`);+ const [row] = res.body.data;+ expect(row.realizedPnl).toBe(124300);+ expect(row.winRate).toBe(0.64);+ expect(row.totalTrades).toBe(412);+ expect(row.volumeUsd).toBe(2840000);+ expect(row.pnlSource).toBe('onchain-fifo');+ expect(row.pnlWindow).toBe('30d');+ });++ it('leaves win rate unknown when the wallet has closed nothing', async () => {+ const addr = addrFor('e');+ getWalletPnl.mockResolvedValue({+ trades: 9,+ closedTrades: 0,+ realizedUsd: 0,+ winRate: 0,+ volumeUsd: 1500,+ });+ const res = await call(`/api/kol/wallets?addresses=${addr}`);+ const [row] = res.body.data;+ expect(row.totalTrades).toBe(9);+ expect(row.winRate).toBeNull();+ });++ it('omits a wallet whose Birdeye fetch failed rather than zeroing it', async () => {+ const addr = addrFor('f');+ getWalletPnl.mockResolvedValue({ trades: 0, closedTrades: 0 });+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({ ok: false, status: 502, json: async () => ({}) })),+ );+ const res = await call(`/api/kol/wallets?addresses=${addr}`);+ expect(res.statusCode).toBe(200);+ expect(res.body.data).toEqual([]);+ });+});diff --git a/tests/api/legal-risk-ack.test.js b/tests/api/legal-risk-ack.test.jsindex 81895039c..2a3edba39 100644--- a/tests/api/legal-risk-ack.test.js+++ b/tests/api/legal-risk-ack.test.js@@ -45,15 +45,16 @@ const { default: handler } = await import('../../api/legal/risk-ack.js');// ── Helpers ───────────────────────────────────────────────────────────────────-function makeReq(body = null, { method = 'POST', origin = null } = {}) {- const bodyStr = body === null ? '' : JSON.stringify(body);+function makeReq(body = null, { method = 'POST', origin = null, contentType, raw = null } = {}) {+ const bodyStr = raw ?? (body === null ? '' : JSON.stringify(body));+ const ct = contentType === undefined ? (body !== null || raw !== null ? 'application/json' : null) : contentType;const req = Readable.from([Buffer.from(bodyStr)]);req.method = method;req.url = '/api/legal/risk-ack';req.headers = {host: 'app.test','user-agent': 'vitest',- ...(body !== null ? { 'content-type': 'application/json' } : {}),+ ...(ct ? { 'content-type': ct } : {}),...(origin ? { origin } : {}),};return req;@@ -142,6 +143,32 @@ describe('POST /api/legal/risk-ack', () => {expect(auditRows()).toHaveLength(0);});+ // A body the endpoint could not read used to be reported as a bad `version`,+ // pointing the caller at a field that was never the problem.+ it('names the size limit rather than the version when the body is too large', async () => {+ const { status, body } = await invoke({ version: RISK_ACK_VERSION, pad: 'a'.repeat(11_000) });+ expect(status).toBe(413);+ expect(body.error).toBe('payload_too_large');+ expect(auditRows()).toHaveLength(0);+ });++ it('names the content-type rather than the version when the body is not JSON', async () => {+ const { status, body } = await invoke(null, {+ contentType: 'application/x-www-form-urlencoded',+ raw: 'version=1',+ });+ expect(status).toBe(415);+ expect(body.error).toBe('unsupported_media_type');+ expect(auditRows()).toHaveLength(0);+ });++ it('refuses an unparseable body', async () => {+ const { status, body } = await invoke(null, { raw: '{oops' });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_request');+ expect(auditRows()).toHaveLength(0);+ });+it('drops a malformed context or path rather than storing it', async () => {const { status } = await invoke({version: RISK_ACK_VERSION,diff --git a/tests/api/marketplace-animations.test.js b/tests/api/marketplace-animations.test.jsindex f62369cae..803d42621 100644--- a/tests/api/marketplace-animations.test.js+++ b/tests/api/marketplace-animations.test.js@@ -69,6 +69,15 @@ describe('marketplace/animations cursor', () => {it('returns null for a malformed cursor', () => {expect(decodeCursor('@@not-base64@@')).toBeNull();});+ // A cursor that decodes cleanly but carries an unparseable timestamp used to+ // become an Invalid Date, reach Postgres as a bind parameter, and take the+ // whole feed down with a 500. It is a bad cursor: drop it, serve page one.+ it('returns null for a well-formed cursor holding an unparseable date', () => {+ for (const bad of ['not-a-date', '', null, {}]) {+ const cur = Buffer.from(JSON.stringify({ c: bad })).toString('base64url');+ expect(decodeCursor(cur), `cursor carrying ${JSON.stringify(bad)}`).toBeNull();+ }+ });});describe('marketplace/animations sort whitelist', () => {diff --git a/tests/api/marketplace-buy-asset.test.js b/tests/api/marketplace-buy-asset.test.jsnew file mode 100644index 000000000..e21ff8fd1--- /dev/null+++ b/tests/api/marketplace-buy-asset.test.js@@ -0,0 +1,294 @@+// Unit tests for /api/marketplace/buy-asset.+//+// Two guarantees, both about a buyer's money:+//+// 1. Confirm scales the atomic price by the MINT's decimals, not a hardcoded 6.+// @solana/pay's validateTransfer compares a UI amount, so an asset priced in+// a 9-decimal mint used to be compared against a figure 1000x too large: the+// buyer paid exactly right, the check failed, and the purchase was filed as+// 'tipped' instead of granting the asset. The decimals are stamped onto the+// purchase row at create time so a later price edit cannot re-scale a payment+// already in flight; a row predating the stamp falls back to the listing.+//+// 2. A malformed item_id is a 400, not a 500. item_id is a uuid column, so bad+// input reaching Postgres throws 22P02 and surfaces as an internal error.+//+// All I/O (DB, Solana RPC, notifications) is stubbed, so this runs offline with+// no DATABASE_URL and no RPC. Nothing here signs or broadcasts a transaction.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++// ── Mock layer ──────────────────────────────────────────────────────────────++const authState = { session: { id: 'aaaa0000-0000-0000-0000-000000000001' } };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++// CSRF has its own dedicated suite; isolate handler logic from the token check.+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));++const sqlQueue = [];+const sqlCalls = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(+ vi.fn(async (strings) => {+ sqlCalls.push(Array.isArray(strings) ? strings.join('?') : String(strings));+ return sqlQueue.length ? sqlQueue.shift() : [];+ }),+ { transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const rlState = { success: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => rlState),+ widgetRead: vi.fn(async () => rlState),+ agentBuy: vi.fn(async () => rlState),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: vi.fn(async () => {}) }));++// The RPC fallback ring hands the callback a connection; there is no real node+// here, so hand it an empty object and let the @solana/pay stubs answer.+vi.mock('../../api/_lib/solana/rpc-fallback.js', () => ({+ rpcFallbackFromEnv: () => ({ withFallback: (fn) => fn({}) }),+}));+vi.mock('../../api/_lib/solana/connection.js', () => ({ solanaConnection: () => ({}) }));+vi.mock('../../api/_lib/solana/gasless-tx.js', () => ({ buildGaslessPurchaseTx: async () => null }));++const validateTransferArgs = [];+vi.mock('@solana/pay', () => ({+ findReference: vi.fn(async () => ({ signature: 'SettlementSignature111' })),+ validateTransfer: vi.fn(async (_conn, _sig, opts) => {+ validateTransferArgs.push(opts);+ return {};+ }),+}));++vi.mock('@solana/web3.js', () => {+ // Fixtures use readable synthetic ids rather than valid 32-byte base58 keys.+ function MockPublicKey(v) {+ this._v = String(v);+ this.toBase58 = () => this._v;+ this.toString = () => this._v;+ }+ return {+ PublicKey: MockPublicKey,+ Keypair: { generate: () => ({ publicKey: new MockPublicKey('GeneratedReference111') }) },+ };+});++// ── Helpers ──────────────────────────────────────────────────────────────────++function makeReq(method, url, body) {+ const s = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ s.method = method;+ s.url = url;+ s.headers = { host: 'localhost', 'content-type': 'application/json' };+ return s;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(chunk) { if (chunk != null) this.body += chunk; this.writableEnded = true; },+ };+}++async function invoke(req, res) {+ const { default: handler } = await import('../../api/marketplace/buy-asset.js');+ await handler(req, res);+ let json = {};+ try { json = JSON.parse(res.body); } catch { /* non-JSON body is asserted on directly */ }+ return { res, json };+}++const USER_ID = 'aaaa0000-0000-0000-0000-000000000001';+const SELLER_ID = 'bbbb0000-0000-0000-0000-000000000001';+const ITEM_ID = '11111111-2222-3333-4444-555555555555';+const REFERENCE = 'ThreeWsSyntheticReference11111111111111111';+const MINT_9DP = 'THREEsynthetic1111111111111111111111111111A';++// 1.5 tokens of a 9-decimal mint, in atomic units.+const AMOUNT_9DP = '1500000000';++function pendingPurchase(overrides = {}) {+ return {+ id: 'purchase-1',+ buyer_user_id: USER_ID,+ item_type: 'avatar',+ item_id: ITEM_ID,+ seller_user_id: SELLER_ID,+ status: 'pending',+ amount: AMOUNT_9DP,+ currency_mint: MINT_9DP,+ chain: 'solana',+ tx_signature: null,+ expires_at: new Date(Date.now() + 600_000).toISOString(),+ reference: REFERENCE,+ payout_address: 'SellerPayoutWallet1111111111111111111111111',+ referrer_user_id: null,+ metadata: { mint_decimals: 9 },+ ...overrides,+ };+}++function confirmReq() {+ return makeReq('POST', `/api/marketplace/buy-asset?reference=${REFERENCE}&op=confirm`, {});+}++beforeEach(() => {+ sqlQueue.length = 0;+ sqlCalls.length = 0;+ validateTransferArgs.length = 0;+ authState.session = { id: USER_ID };+ rlState.success = true;+});++// ── Confirm: decimals ────────────────────────────────────────────────────────++describe('POST /api/marketplace/buy-asset/:reference/confirm', () => {+ it('validates the transfer against the mint decimals stamped on the purchase', async () => {+ sqlQueue.push([pendingPurchase()]); // load purchase+ sqlQueue.push([{ id: 'purchase-1' }]); // claim (UPDATE ... RETURNING)+ sqlQueue.push([]); // receipt insert++ const { res, json } = await invoke(confirmReq(), makeRes());++ expect(res.statusCode).toBe(200);+ expect(json.data.status).toBe('confirmed');+ expect(validateTransferArgs).toHaveLength(1);+ // 1500000000 atoms at 9 decimals is 1.5 tokens, not 1500.+ expect(validateTransferArgs[0].amount.toString()).toBe('1.5');+ });++ it('falls back to the live listing decimals for a row created before the stamp', async () => {+ const legacy = pendingPurchase({ metadata: {} });+ sqlQueue.push([legacy]); // load purchase+ sqlQueue.push([{ mint_decimals: 9 }]); // asset_prices lookup+ sqlQueue.push([{ id: 'purchase-1' }]); // claim+ sqlQueue.push([]); // receipt insert++ const { res } = await invoke(confirmReq(), makeRes());++ expect(res.statusCode).toBe(200);+ expect(validateTransferArgs[0].amount.toString()).toBe('1.5');+ });++ it('falls back to USDC decimals when neither the row nor a listing says otherwise', async () => {+ sqlQueue.push([pendingPurchase({ metadata: {}, amount: '1500000' })]); // load purchase+ sqlQueue.push([]); // no asset_prices row (listing withdrawn)+ sqlQueue.push([{ id: 'purchase-1' }]); // claim+ sqlQueue.push([]); // receipt insert++ const { res } = await invoke(confirmReq(), makeRes());++ expect(res.statusCode).toBe(200);+ expect(validateTransferArgs[0].amount.toString()).toBe('1.5');+ });++ it('returns 404 for a reference the caller does not own', async () => {+ sqlQueue.push([]); // no matching purchase for this buyer+ const { res, json } = await invoke(confirmReq(), makeRes());+ expect(res.statusCode).toBe(404);+ expect(json.error).toBe('not_found');+ });++ it('rejects a malformed reference with 400 before any lookup', async () => {+ const { res, json } = await invoke(+ makeReq('POST', '/api/marketplace/buy-asset?reference=short&op=confirm', {}),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('validation_error');+ expect(sqlCalls).toHaveLength(0);+ });+});++// ── Create: input validation ─────────────────────────────────────────────────++describe('POST /api/marketplace/buy-asset', () => {+ it('rejects a non-uuid item_id with 400 instead of letting Postgres throw', async () => {+ const { res, json } = await invoke(+ makeReq('POST', '/api/marketplace/buy-asset', { item_type: 'avatar', item_id: 'not-a-uuid' }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('validation_error');+ expect(json.error_description).toMatch(/uuid/);+ expect(sqlCalls).toHaveLength(0);+ });++ it('rejects an unknown item_type with 400', async () => {+ const { res, json } = await invoke(+ makeReq('POST', '/api/marketplace/buy-asset', { item_type: 'spaceship', item_id: ITEM_ID }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('validation_error');+ });++ it('requires a signed-in caller', async () => {+ authState.session = null;+ const { res, json } = await invoke(+ makeReq('POST', '/api/marketplace/buy-asset', { item_type: 'avatar', item_id: ITEM_ID }),+ makeRes(),+ );+ expect(res.statusCode).toBe(401);+ expect(json.error).toBe('unauthorized');+ });++ it('stamps the listing decimals onto the pending row it creates', async () => {+ sqlQueue.push([{ amount: AMOUNT_9DP, currency_mint: MINT_9DP, chain: 'solana', mint_decimals: 9, owner_user_id: SELLER_ID }]); // price+ sqlQueue.push([{ user_id: SELLER_ID, name: 'Nova' }]); // seller for item+ sqlQueue.push([{ address: 'SellerPayoutWallet1111111111111111111111111' }]); // payout+ sqlQueue.push([]); // no confirmed purchase+ sqlQueue.push([]); // no reusable pending row+ sqlQueue.push([]); // referrer lookup (users.referred_by_id)+ sqlQueue.push([{+ reference: REFERENCE, amount: AMOUNT_9DP, currency_mint: MINT_9DP,+ chain: 'solana', expires_at: null, metadata: { mint_decimals: 9 },+ }]); // insert++ const { res, json } = await invoke(+ makeReq('POST', '/api/marketplace/buy-asset', { item_type: 'avatar', item_id: ITEM_ID }),+ makeRes(),+ );++ expect(res.statusCode).toBe(201);+ expect(json.data.mint_decimals).toBe(9);+ expect(json.data.reference).toBe(REFERENCE);+ });+});++// ── Method + routing surface ─────────────────────────────────────────────────++describe('/api/marketplace/buy-asset method handling', () => {+ it('answers a bare GET with 405', async () => {+ const { res, json } = await invoke(makeReq('GET', '/api/marketplace/buy-asset'), makeRes());+ expect(res.statusCode).toBe(405);+ expect(json.error).toBe('method_not_allowed');+ });++ it('rejects an unknown op with 404', async () => {+ const { res, json } = await invoke(+ makeReq('POST', `/api/marketplace/buy-asset?reference=${REFERENCE}&op=refund`, {}),+ makeRes(),+ );+ expect(res.statusCode).toBe(404);+ expect(json.error).toBe('not_found');+ });+});diff --git a/tests/api/marketplace-request-guards.test.js b/tests/api/marketplace-request-guards.test.jsnew file mode 100644index 000000000..9c59410fd--- /dev/null+++ b/tests/api/marketplace-request-guards.test.js@@ -0,0 +1,216 @@+// Boundary behaviour for two marketplace endpoints that answer before any DB work.+//+// GET /api/marketplace/check-skill-access — agent_id lands in a uuid column, so+// a malformed one used to reach Postgres as 22P02 and surface as a 500 on what+// is plainly bad client input.+//+// /api/marketplace/agents/:id/reviews — the CORS preflight was answered inside+// the per-method handlers, so a request the dispatcher rejected first (bad+// agent id, or a preflight that names no method) came back as a bare error with+// no CORS headers at all. The browser then reported a CORS failure instead of+// the validation error the caller needed to read.+//+// Everything below runs offline: no DATABASE_URL, no network.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++const authState = { session: { id: 'aaaa0000-0000-0000-0000-000000000001' } };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));++const sqlQueue = [];+const sqlCalls = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(+ vi.fn(async (strings) => {+ sqlCalls.push(Array.isArray(strings) ? strings.join('?') : String(strings));+ return sqlQueue.length ? sqlQueue.shift() : [];+ }),+ { transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const rlState = { success: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => rlState),+ widgetRead: vi.fn(async () => rlState),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const ownershipResult = { has_access: true, paid: true, owned: true };+vi.mock('../../api/_lib/services/MonetizationService.js', () => ({+ MonetizationService: class {+ constructor(user) { this.user = user; }+ async checkSkillOwnership() { return ownershipResult; }+ },+}));++vi.mock('../../api/_lib/feed.js', () => ({ publishUserEvent: vi.fn() }));+vi.mock('../../api/_lib/review-attest.js', () => ({ attestReview: vi.fn(async () => {}) }));++// ── Helpers ──────────────────────────────────────────────────────────────────++function makeReq(method, url, { body = null, headers = {} } = {}) {+ const s = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ s.method = method;+ s.url = url;+ s.headers = { host: 'localhost', 'content-type': 'application/json', ...headers };+ return s;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(chunk) { if (chunk != null) this.body += chunk; this.writableEnded = true; },+ };+}++async function invoke(modulePath, req, res) {+ const { default: handler } = await import(modulePath);+ await handler(req, res);+ let json = {};+ try { json = JSON.parse(res.body); } catch { /* empty body on 204 */ }+ return { res, json };+}++const AGENT_ID = '11111111-2222-3333-4444-555555555555';++beforeEach(() => {+ sqlQueue.length = 0;+ sqlCalls.length = 0;+ authState.session = { id: 'aaaa0000-0000-0000-0000-000000000001' };+ rlState.success = true;+});++// ── check-skill-access ───────────────────────────────────────────────────────++describe('GET /api/marketplace/check-skill-access', () => {+ const path = '../../api/marketplace/check-skill-access.js';++ it('requires a signed-in caller', async () => {+ authState.session = null;+ const { res, json } = await invoke(path, makeReq('GET', `/api/marketplace/check-skill-access?agent_id=${AGENT_ID}&skill=pro`), makeRes());+ expect(res.statusCode).toBe(401);+ expect(json.error).toBe('unauthorized');+ });++ it('requires both agent_id and skill', async () => {+ const { res, json } = await invoke(path, makeReq('GET', `/api/marketplace/check-skill-access?agent_id=${AGENT_ID}`), makeRes());+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('validation_error');+ });++ it('rejects a non-uuid agent_id with 400 instead of letting Postgres throw', async () => {+ const { res, json } = await invoke(path, makeReq('GET', '/api/marketplace/check-skill-access?agent_id=not-a-uuid&skill=pro'), makeRes());+ expect(res.statusCode).toBe(400);+ expect(json.error_description).toMatch(/uuid/);+ expect(sqlCalls).toHaveLength(0);+ });++ it('returns the ownership verdict for a well-formed request', async () => {+ const { res, json } = await invoke(path, makeReq('GET', `/api/marketplace/check-skill-access?agent_id=${AGENT_ID}&skill=pro`), makeRes());+ expect(res.statusCode).toBe(200);+ expect(json.data).toEqual({ has_access: true });+ });++ it('answers a POST with 405', async () => {+ const { res, json } = await invoke(path, makeReq('POST', '/api/marketplace/check-skill-access', { body: {} }), makeRes());+ expect(res.statusCode).toBe(405);+ expect(json.error).toBe('method_not_allowed');+ });+});++// ── reviews ──────────────────────────────────────────────────────────────────++describe('/api/marketplace/agents/:id/reviews CORS + dispatch', () => {+ const path = '../../api/marketplace/reviews.js';+ const ORIGIN = { origin: 'https://three.ws' };++ it('answers a preflight for a malformed agent id with 204 + CORS headers', async () => {+ const { res } = await invoke(+ path,+ makeReq('OPTIONS', '/api/marketplace/agents/nope/reviews', {+ headers: { ...ORIGIN, 'access-control-request-method': 'POST' },+ }),+ makeRes(),+ );+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-origin']).toBe('https://three.ws');+ expect(res.headers['access-control-allow-methods']).toBe('GET,POST,DELETE,OPTIONS');+ expect(sqlCalls).toHaveLength(0);+ });++ it('answers a preflight that names no method with 204, not 405', async () => {+ const { res } = await invoke(+ path,+ makeReq('OPTIONS', `/api/marketplace/agents/${AGENT_ID}/reviews`, { headers: ORIGIN }),+ makeRes(),+ );+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-credentials']).toBe('true');+ });++ it('carries CORS headers on the validation error for a malformed agent id', async () => {+ const { res, json } = await invoke(+ path,+ makeReq('GET', '/api/marketplace/agents/nope/reviews', { headers: ORIGIN }),+ makeRes(),+ );+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('validation_error');+ expect(res.headers['access-control-allow-origin']).toBe('https://three.ws');+ });++ it('rejects an unsupported method with 405', async () => {+ const { res, json } = await invoke(+ path,+ makeReq('PUT', `/api/marketplace/agents/${AGENT_ID}/reviews`, { headers: ORIGIN }),+ makeRes(),+ );+ expect(res.statusCode).toBe(405);+ expect(json.error).toBe('method_not_allowed');+ });++ it('lists reviews for a real agent', async () => {+ sqlQueue.push([{ id: AGENT_ID }]); // agent exists+ sqlQueue.push([{ rating_avg: '4.50', rating_count: 2, r5: 1, r4: 1, r3: 0, r2: 0, r1: 0 }]);+ sqlQueue.push([{ id: 'r1', rating: 5, body: 'Great', created_at: null, updated_at: null, user_id: 'someone', display_name: 'Ada', avatar_url: null }]);+ sqlQueue.push([]); // caller's own review++ const { res, json } = await invoke(+ path,+ makeReq('GET', `/api/marketplace/agents/${AGENT_ID}/reviews`, { headers: ORIGIN }),+ makeRes(),+ );++ expect(res.statusCode).toBe(200);+ expect(json.data.summary.rating_avg).toBe(4.5);+ expect(json.data.reviews).toHaveLength(1);+ expect(json.data.reviews[0].author_name).toBe('Ada');+ });++ it('returns 404 when the agent does not exist', async () => {+ sqlQueue.push([]); // no agent row+ const { res, json } = await invoke(+ path,+ makeReq('GET', `/api/marketplace/agents/${AGENT_ID}/reviews`, { headers: ORIGIN }),+ makeRes(),+ );+ expect(res.statusCode).toBe(404);+ expect(json.error).toBe('not_found');+ });+});diff --git a/tests/api/mcp-3d-challenge.test.js b/tests/api/mcp-3d-challenge.test.jsindex d1ae0e768..38d1ba3d1 100644--- a/tests/api/mcp-3d-challenge.test.js+++ b/tests/api/mcp-3d-challenge.test.js@@ -55,7 +55,8 @@ vi.mock('../../api/_mcp3d/text-to-image.js', () => ({}));const { default: handler } = await import('../../api/mcp-3d.js');-const { studioX402Amount } = await import('../../api/_mcp3d/pricing.js');+const { studioX402Amount, FREE_TOOLS, TOOL_PRICING } = await import('../../api/_mcp3d/pricing.js');+const { TOOL_CATALOG } = await import('../../api/_mcp3d/catalog.js');const { isDiscoveryOnlyBatch } = await import('../../api/_lib/mcp-batch-price.js');function makeRes() {@@ -268,6 +269,34 @@ describe('studioX402Amount', () => {});});+// An unpriced tool is served free, so a new GPU-backed tool that lands in the+// catalog without a TOOL_PRICING entry silently gives away generation-grade+// compute — the exact regression api/_mcp3d/pricing.js exists to prevent. These+// assertions force every catalog tool to be a deliberate paid-or-free decision.+describe('studio pricing classification covers the whole catalog', () => {+ const catalogNames = TOOL_CATALOG.map((t) => t.name);++ it('classifies every catalog tool as either priced or deliberately free', () => {+ const unclassified = catalogNames.filter(+ (n) => !FREE_TOOLS.has(n) && studioX402Amount(n, {}) === null,+ );+ expect(unclassified).toEqual([]);+ });++ it('never prices a tool it also declares free', () => {+ const contradictory = catalogNames.filter(+ (n) => FREE_TOOLS.has(n) && studioX402Amount(n, {}) !== null,+ );+ expect(contradictory).toEqual([]);+ });++ it('carries no pricing or free entry for a tool the catalog dropped', () => {+ const known = new Set(catalogNames);+ expect(Object.keys(TOOL_PRICING).filter((n) => !known.has(n))).toEqual([]);+ expect([...FREE_TOOLS].filter((n) => !known.has(n))).toEqual([]);+ });+});+describe('isDiscoveryOnlyBatch', () => {it('accepts pure discovery traffic and rejects anything carrying work', () => {expect(isDiscoveryOnlyBatch({ method: 'tools/list' })).toBe(true);diff --git a/tests/api/mcp-garment-tools.test.js b/tests/api/mcp-garment-tools.test.jsnew file mode 100644index 000000000..61ef1b0e9--- /dev/null+++ b/tests/api/mcp-garment-tools.test.js@@ -0,0 +1,200 @@+// Garment Forge MCP tools (api/_mcp/tools/garments.js), registered in+// api/_mcp/catalog.js. These are the agent-facing door onto the same+// garment-forge worker lane the /api/garment-forge HTTP route drives.+//+// Verifies: generate_garment queues a job against the worker with the server-side+// bearer secret and never leaks it into the tool result; garment_status reports a+// missing coverage number as "not reported" instead of announcing a measured+// 0.0% the pipeline never produced; list_garment_catalog shapes the public+// wardrobe manifest and filters by slot; an unconfigured worker, a malformed job+// id, a 404 job, an unreachable worker, and an exhausted rate limit each surface+// a clean error. The rate limiter and fetch are mocked at their boundary; the+// tool defs run real.++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';++process.env.GCP_GARMENT_FORGE_URL = 'https://garment-forge.test/';+process.env.GCP_RECONSTRUCTION_KEY = 'worker-secret';++let rlOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcp3dGenerate: vi.fn(async () => ({ success: rlOk, reset: Date.now() + 60_000 })),+ mcp3dStatus: vi.fn(async () => ({ success: rlOk, reset: Date.now() + 60_000 })),+ },+}));++const { toolDefs } = await import('../../api/_mcp/tools/garments.js');++const JOB_ID = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';+const AUTH = { userId: 'user-1', rateKey: 'garment-test', scope: '', source: 'oauth' };+const call = (name, args) => toolDefs.find((t) => t.name === name).handler(args, AUTH, {});++const realFetch = globalThis.fetch;+const fetchMock = vi.fn();+globalThis.fetch = (...a) => fetchMock(...a);+afterAll(() => {+ globalThis.fetch = realFetch;+});++const jsonResponse = (body, status = 200) => ({+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+});++beforeEach(() => {+ fetchMock.mockReset();+ rlOk = true;+ process.env.GCP_GARMENT_FORGE_URL = 'https://garment-forge.test/';+ process.env.GCP_RECONSTRUCTION_KEY = 'worker-secret';+});++describe('garment MCP tools: registration', () => {+ it('registers the three tools with the wardrobe slot enum on both writers', () => {+ const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));+ expect(Object.keys(byName)).toEqual([+ 'generate_garment',+ 'garment_status',+ 'list_garment_catalog',+ ]);+ expect(byName.generate_garment.annotations.readOnlyHint).toBe(false);+ expect(byName.generate_garment.annotations.destructiveHint).toBe(false);+ expect(byName.garment_status.annotations.readOnlyHint).toBe(true);+ expect(byName.generate_garment.inputSchema.properties.slot.enum).toContain('outerwear');+ expect(byName.list_garment_catalog.inputSchema.properties.slot.enum).toEqual(+ byName.generate_garment.inputSchema.properties.slot.enum,+ );+ });+});++describe('generate_garment', () => {+ it('queues a job on the worker with the server-side bearer and returns the job id', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ job_id: JOB_ID, status: 'queued' }));+ const r = await call('generate_garment', { prompt: 'a red varsity jacket', slot: 'outerwear' });++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://garment-forge.test/generate');+ expect(init.method).toBe('POST');+ expect(init.headers.authorization).toBe('Bearer worker-secret');+ expect(JSON.parse(init.body)).toEqual({ prompt: 'a red varsity jacket', slot: 'outerwear' });++ expect(r.structuredContent).toEqual({ job_id: JOB_ID, status: 'queued', eta_seconds: 450 });+ // The worker secret is server-side only and must never reach the agent.+ expect(JSON.stringify(r)).not.toContain('worker-secret');+ });++ it('reports an unconfigured worker as a configuration fault, not a generation failure', async () => {+ delete process.env.GCP_GARMENT_FORGE_URL;+ await expect(call('generate_garment', { prompt: 'a hat', slot: 'headwear' })).rejects.toMatchObject({+ code: -32001,+ message: expect.stringContaining('not configured'),+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('surfaces a worker rejection and an unreachable worker distinctly', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ error: 'bad slot' }, 422));+ await expect(call('generate_garment', { prompt: 'a hat', slot: 'headwear' })).rejects.toThrow(+ 'garment worker returned 422',+ );++ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));+ await expect(call('generate_garment', { prompt: 'a hat', slot: 'headwear' })).rejects.toThrow(+ 'garment worker unreachable',+ );+ });++ it('rate-limits before calling the worker', async () => {+ rlOk = false;+ await expect(call('generate_garment', { prompt: 'a hat', slot: 'headwear' })).rejects.toMatchObject({+ code: -32000,+ message: 'rate_limited',+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('garment_status', () => {+ it('reports the published garment with its measured bind coverage', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ job_id: JOB_ID, status: 'done', garment_id: 'red-varsity-jacket-abc123',+ glb_url: 'https://cdn.test/garment.glb', manifest_url: 'https://cdn.test/manifest.json',+ thumb_url: 'https://cdn.test/thumb.png', coverage: 0.73, occludes: ['torso', 'upperArm'],+ }),+ );+ const r = await call('garment_status', { job_id: JOB_ID });+ expect(fetchMock.mock.calls[0][0]).toBe(`https://garment-forge.test/jobs/${JOB_ID}`);+ expect(r.structuredContent.coverage).toBe(0.73);+ expect(r.content[0].text).toContain('coverage 73.0%');+ expect(r.content[0].text).toContain('occludes torso, upperArm');+ });++ it('says coverage was not reported rather than announcing a measured 0.0%', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({ job_id: JOB_ID, status: 'done', garment_id: 'g1', glb_url: 'https://cdn.test/g.glb' }),+ );+ const r = await call('garment_status', { job_id: JOB_ID });+ expect(r.structuredContent.coverage).toBeNull();+ expect(r.content[0].text).toContain('coverage not reported');+ expect(r.content[0].text).not.toContain('0.0%');+ expect(r.content[0].text).toContain('occludes nothing');+ });++ it('reports a failed job with the worker error and an in-flight job with its stage', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ job_id: JOB_ID, status: 'failed', error: 'rig step diverged' }));+ const failed = await call('garment_status', { job_id: JOB_ID });+ expect(failed.content[0].text).toContain('rig step diverged');++ fetchMock.mockResolvedValue(jsonResponse({ job_id: JOB_ID, status: 'running', stage: 'compose' }));+ const running = await call('garment_status', { job_id: JOB_ID });+ expect(running.structuredContent.stage).toBe('compose');+ expect(running.content[0].text).toContain('compose');+ });++ it('rejects a malformed job id before calling the worker, and reports an unknown job', async () => {+ await expect(call('garment_status', { job_id: 'not-a-uuid' })).rejects.toThrow('malformed job id');+ expect(fetchMock).not.toHaveBeenCalled();++ fetchMock.mockResolvedValue(jsonResponse({ error: 'nope' }, 404));+ await expect(call('garment_status', { job_id: JOB_ID })).rejects.toThrow('no such garment job');+ });+});++describe('list_garment_catalog', () => {+ const CATALOG = [+ { id: 'g-top', name: 'White oxford', slot: 'top', version: 1, model: { uri: 'https://cdn.test/top.glb' }, preview: { thumbnail: 'https://cdn.test/top.png' }, occludes: ['torso'], license: 'CC0' },+ { id: 'g-boot', name: 'Black boots', slot: 'footwear', version: 2, model: { uri: 'https://cdn.test/boot.glb' }, preview: {}, license: 'CC0' },+ ];++ it('shapes every published manifest and filters by slot', async () => {+ fetchMock.mockResolvedValue(jsonResponse(CATALOG));+ const all = await call('list_garment_catalog', {});+ expect(all.structuredContent.count).toBe(2);+ expect(all.structuredContent.garments[0]).toEqual({+ id: 'g-top', name: 'White oxford', slot: 'top', version: 1,+ glb_url: 'https://cdn.test/top.glb', thumbnail: 'https://cdn.test/top.png',+ occludes: ['torso'], license: 'CC0',+ });+ // A manifest with no preview/occludes still shapes cleanly.+ expect(all.structuredContent.garments[1].thumbnail).toBeNull();+ expect(all.structuredContent.garments[1].occludes).toEqual([]);++ fetchMock.mockResolvedValue(jsonResponse(CATALOG));+ const tops = await call('list_garment_catalog', { slot: 'top' });+ expect(tops.structuredContent.garments.map((g) => g.id)).toEqual(['g-top']);+ });++ it('designs the empty state instead of returning a blank result', async () => {+ fetchMock.mockResolvedValue(jsonResponse([]));+ const r = await call('list_garment_catalog', { slot: 'glasses' });+ expect(r.structuredContent).toEqual({ garments: [], count: 0 });+ expect(r.content[0].text).toBe('The catalog is empty for that filter.');+ });++ it('errors when the public catalog is unreachable', async () => {+ fetchMock.mockRejectedValue(new Error('DNS failure'));+ await expect(call('list_garment_catalog', {})).rejects.toThrow('garment catalog unreachable');+ });+});diff --git a/tests/api/mcp-gated-embed-tool.test.js b/tests/api/mcp-gated-embed-tool.test.jsnew file mode 100644index 000000000..a8e189ddc--- /dev/null+++ b/tests/api/mcp-gated-embed-tool.test.js@@ -0,0 +1,143 @@+// create_gated_embed MCP tool (api/_mcp/tools/embed.js), registered in+// api/_mcp/catalog.js. (get_embed_code's dispatch path is covered end-to-end in+// tests/api/mcp-embed.test.js.)+//+// Verifies: the tool rejects a malformed asset ref before touching the gate+// store; a caller who does not own the asset is told so rather than gating+// someone else's avatar; a missing asset and a foreign asset stay+// indistinguishable to the caller so the tool cannot be used to probe which+// asset ids exist; the gate defaults to the $THREE mint but accepts any SPL+// mint supplied at runtime; the returned snippet points at this deployment's+// embed script; and an invalid gate configuration comes back as an invalid-params+// error instead of a bubbled fault. The gate store, asset resolver, and DB are+// mocked at their module boundary; the tool def runs real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const OTHER_MINT = 'THREEsynthetic1111111111111111111111111111';+const AVATAR_REF = 'avatar:11111111-2222-4333-8444-555555555555';++vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../../api/_lib/embed-policy.js', () => ({ readEmbedPolicy: vi.fn(async () => null) }));+vi.mock('../../api/_lib/onchain.js', () => ({+ resolveOnChainAgent: vi.fn(async () => ({ name: 'Agent' })),+ SERVER_CHAIN_META: { 8453: { name: 'Base' } },+}));++const assetState = { asset: { name: 'My Avatar' }, ownership: { ok: true } };+vi.mock('../../api/_lib/embed-asset.js', () => ({+ isEmbedAssetRef: (ref) => /^avatar:[0-9a-f-]{36}$/i.test(ref) || /^\d+:\d+$/.test(ref),+ resolveEmbedAsset: vi.fn(async () => assetState.asset),+}));++const gateState = { error: null };+const createGateMock = vi.fn(async ({ assetId, mint, minAmount, chain }) => {+ if (gateState.error) throw gateState.error;+ return { gateId: 'gate-1', assetId, mint, minAmount, chain };+});+vi.mock('../../api/_lib/embed-gate.js', () => ({+ DEFAULT_GATE_MINT: THREE_MINT,+ createEmbedGate: (...a) => createGateMock(...a),+ checkAssetOwnership: vi.fn(async () => assetState.ownership),+}));++const { toolDefs } = await import('../../api/_mcp/tools/embed.js');++const REQ = { headers: { host: 'three.ws' } };+const AUTH = { userId: 'user-1', rateKey: 'gate-test', scope: 'avatars:write', source: 'oauth' };+const tool = toolDefs.find((t) => t.name === 'create_gated_embed');+const call = (args, auth = AUTH) => tool.handler(args, auth, REQ);++beforeEach(() => {+ assetState.asset = { name: 'My Avatar' };+ assetState.ownership = { ok: true };+ gateState.error = null;+ createGateMock.mockClear();+ delete process.env.APP_ORIGIN;+ delete process.env.PUBLIC_ORIGIN;+ delete process.env.PUBLIC_APP_ORIGIN;+});++describe('create_gated_embed: contract', () => {+ it('is a scoped write tool that names the default mint in its own schema', () => {+ expect(tool.scope).toBe('avatars:write');+ expect(tool.annotations).toEqual({+ readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true,+ });+ expect(tool.inputSchema.required).toEqual(['asset_id', 'min_amount']);+ expect(tool.inputSchema.properties.min_amount.exclusiveMinimum).toBe(0);+ expect(tool.inputSchema.properties.mint.description).toContain(THREE_MINT);+ });+});++describe('create_gated_embed: success path', () => {+ it('gates an owned avatar on $THREE by default and returns a pasteable snippet', async () => {+ const r = await call({ asset_id: AVATAR_REF, min_amount: 1000 });++ expect(createGateMock).toHaveBeenCalledWith({+ assetId: AVATAR_REF, ownerUserId: 'user-1', mint: THREE_MINT,+ minAmount: 1000, chain: 'solana',+ });+ expect(r.isError).toBeUndefined();+ expect(r.structuredContent).toEqual({+ ok: true, gate_id: 'gate-1', asset_id: AVATAR_REF,+ gate: { mint: THREE_MINT, min_amount: 1000, chain: 'solana' },+ embed_snippet: `<script src="https://three.ws/embed/v1.js" async></script>\n<three-d agent="${AVATAR_REF}" interactive></three-d>`,+ });+ // The default mint reads as the ticker, not a raw base58 blob.+ expect(r.content[0].text).toContain('$THREE');+ expect(r.content[0].text).toContain('My Avatar');+ });++ it('accepts any SPL mint supplied at runtime and labels it by address', async () => {+ const r = await call({ asset_id: AVATAR_REF, mint: OTHER_MINT, min_amount: 5 });+ expect(createGateMock.mock.calls[0][0].mint).toBe(OTHER_MINT);+ expect(r.structuredContent.gate.mint).toBe(OTHER_MINT);+ expect(r.content[0].text).toContain(OTHER_MINT);+ expect(r.content[0].text).not.toContain('$THREE');+ });++ it('builds the snippet against this deployment origin, not a hardcoded host', async () => {+ process.env.APP_ORIGIN = 'https://preview.three.ws/';+ const r = await call({ asset_id: AVATAR_REF, min_amount: 1 });+ expect(r.structuredContent.embed_snippet).toContain('https://preview.three.ws/embed/v1.js');+ });+});++describe('create_gated_embed: failure paths', () => {+ it('rejects a malformed asset ref before resolving anything', async () => {+ await expect(call({ asset_id: 'bogus', min_amount: 1 })).rejects.toMatchObject({+ code: -32602,+ message: 'asset_id must be "<chainId>:<agentId>" or "avatar:<uuid>"',+ });+ expect(createGateMock).not.toHaveBeenCalled();+ });++ it('refuses to gate an asset the caller does not own', async () => {+ assetState.ownership = { ok: false, reason: 'not_owner' };+ await expect(call({ asset_id: AVATAR_REF, min_amount: 1 })).rejects.toThrow(/do not own this asset/);+ expect(createGateMock).not.toHaveBeenCalled();+ });++ it('gives an unknown asset and a foreign account the same not-found answer', async () => {+ assetState.asset = null;+ await expect(call({ asset_id: AVATAR_REF, min_amount: 1 })).rejects.toThrow(+ `embed asset "${AVATAR_REF}" not found`,+ );++ assetState.asset = { name: 'Someone else' };+ assetState.ownership = { ok: false, reason: 'no_such_asset' };+ await expect(call({ asset_id: AVATAR_REF, min_amount: 1 })).rejects.toThrow(+ `embed asset "${AVATAR_REF}" not found`,+ );+ });++ it('turns an invalid gate configuration into an invalid-params error', async () => {+ gateState.error = new Error('min_amount must be greater than 0');+ await expect(call({ asset_id: AVATAR_REF, min_amount: 1 })).rejects.toMatchObject({+ code: -32602,+ message: 'min_amount must be greater than 0',+ });+ });+});diff --git a/tests/api/mcp-model-inspect-tools.test.js b/tests/api/mcp-model-inspect-tools.test.jsnew file mode 100644index 000000000..59b56cb71--- /dev/null+++ b/tests/api/mcp-model-inspect-tools.test.js@@ -0,0 +1,145 @@+// inspect_model + optimize_model MCP tools (api/_mcp/tools/models.js),+// registered in both api/_mcp/catalog.js and api/_mcp3d/catalog.js.+// (validate_model's dispatch path is covered end-to-end in tests/api/mcp.test.js.)+//+// Verifies: both tools parse a REAL GLB shipped in this repo and report its+// actual structure and optimization advice, so a regression in the inspection+// pipeline fails here rather than in production; the human-readable text and+// the structuredContent agree; the caller's URL is fetched through the+// SSRF-hardened fetchModel (never a bare fetch); a blocked or unfetchable URL+// surfaces the fetch reason; and each tool rate-limits on its own bucket before+// spending any bytes. Only the fetch layer and the rate limiter are mocked; the+// glTF parsing runs for real against public/avatars/mannequin.glb.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const MODEL_PATH = join(process.cwd(), 'public', 'avatars', 'mannequin.glb');+const MODEL_BYTES = new Uint8Array(readFileSync(MODEL_PATH));+const MODEL_URL = 'https://three.ws/avatars/mannequin.glb';++class MockFetchModelError extends Error {+ constructor(message, code) {+ super(message);+ this.code = code;+ }+}++const fetchState = { error: null, calls: [] };+vi.mock('../../api/_lib/fetch-model.js', () => ({+ FetchModelError: MockFetchModelError,+ fetchModel: vi.fn(async (url) => {+ fetchState.calls.push(url);+ if (fetchState.error) throw fetchState.error;+ return { bytes: MODEL_BYTES, url, filename: 'mannequin.glb' };+ }),+}));++const rlState = { mcpInspect: true, mcpOptimize: true, mcpValidate: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpInspect: vi.fn(async () => ({ success: rlState.mcpInspect, reset: Date.now() + 60_000 })),+ mcpOptimize: vi.fn(async () => ({ success: rlState.mcpOptimize, reset: Date.now() + 60_000 })),+ mcpValidate: vi.fn(async () => ({ success: rlState.mcpValidate, reset: Date.now() + 60_000 })),+ },+}));++const { toolDefs } = await import('../../api/_mcp/tools/models.js');++const AUTH = { userId: null, rateKey: 'model-test', scope: '', source: 'x402' };+const call = (name, args) => toolDefs.find((t) => t.name === name).handler(args, AUTH, {});++beforeEach(() => {+ fetchState.error = null;+ fetchState.calls = [];+ rlState.mcpInspect = true;+ rlState.mcpOptimize = true;+ rlState.mcpValidate = true;+});++describe('model MCP tools: registration', () => {+ it('registers three deterministic, public inspection tools', () => {+ expect(toolDefs.map((t) => t.name)).toEqual(['validate_model', 'inspect_model', 'optimize_model']);+ for (const t of toolDefs) {+ expect(t.scope).toBeUndefined();+ expect(t.annotations).toEqual({+ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true,+ });+ expect(t.inputSchema.required).toEqual(['url']);+ }+ });+});++describe('inspect_model', () => {+ it('reports the real structure of a GLB shipped in this repo', async () => {+ const r = await call('inspect_model', { url: MODEL_URL });+ expect(fetchState.calls).toEqual([MODEL_URL]);++ const s = r.structuredContent;+ expect(s.url).toBe(MODEL_URL);+ expect(s.filename).toBe('mannequin.glb');+ expect(s.container).toBe('glb');+ expect(s.version).toBe('2.0');+ expect(s.fileSize).toBe(MODEL_BYTES.byteLength);+ expect(s.counts.meshes).toBeGreaterThan(0);+ expect(s.counts.totalTriangles).toBeGreaterThan(0);+ expect(Array.isArray(s.extensionsUsed)).toBe(true);++ // The text summary is a rendering of the same numbers, never a second source.+ const text = r.content[0].text;+ expect(text).toContain('Model: mannequin.glb');+ expect(text).toContain(`Meshes: ${s.counts.meshes}`);+ expect(text).toContain(`Vertices: ${s.counts.totalVertices.toLocaleString()}`);+ });++ it('surfaces the fetch reason when the URL is blocked', async () => {+ fetchState.error = new MockFetchModelError('host resolves to private address', 'private_address');+ await expect(call('inspect_model', { url: 'http://169.254.169.254/model.glb' })).rejects.toThrow(+ 'fetch failed: host resolves to private address (private_address)',+ );+ });++ it('rate-limits on its own bucket before fetching', async () => {+ rlState.mcpInspect = false;+ await expect(call('inspect_model', { url: MODEL_URL })).rejects.toMatchObject({+ code: -32000, message: 'rate_limited',+ });+ expect(fetchState.calls).toEqual([]);+ });+});++describe('optimize_model', () => {+ it('returns actionable suggestions derived from the same real inspection', async () => {+ const r = await call('optimize_model', { url: MODEL_URL });+ const s = r.structuredContent;+ expect(s.url).toBe(MODEL_URL);+ expect(Array.isArray(s.suggestions)).toBe(true);+ expect(s.suggestions.length).toBeGreaterThan(0);+ expect(s.info.counts.meshes).toBeGreaterThan(0);++ for (const sug of s.suggestions) {+ expect(typeof sug.id).toBe('string');+ expect(typeof sug.message).toBe('string');+ expect(['info', 'warn', 'critical']).toContain(sug.severity);+ expect(r.content[0].text).toContain(sug.id);+ }+ });++ it('rate-limits on its own bucket, independently of inspect_model', async () => {+ rlState.mcpOptimize = false;+ await expect(call('optimize_model', { url: MODEL_URL })).rejects.toMatchObject({+ code: -32000, message: 'rate_limited',+ });+ expect(fetchState.calls).toEqual([]);++ rlState.mcpOptimize = true;+ const r = await call('optimize_model', { url: MODEL_URL });+ expect(r.structuredContent.suggestions).toBeDefined();+ });++ it('propagates an unexpected fetch fault unwrapped for the dispatcher to sanitize', async () => {+ fetchState.error = new Error('socket hang up');+ await expect(call('optimize_model', { url: MODEL_URL })).rejects.toThrow('socket hang up');+ });+});diff --git a/tests/api/mcp-oracle-tools.test.js b/tests/api/mcp-oracle-tools.test.jsnew file mode 100644index 000000000..fb807806d--- /dev/null+++ b/tests/api/mcp-oracle-tools.test.js@@ -0,0 +1,237 @@+// Oracle MCP tools (api/_mcp/tools/oracle.js), registered in api/_mcp/catalog.js.+//+// Verifies: the two public read tools shape a conviction verdict into an+// agent-ready recommendation keyed off the tier; a degraded feed/intel store is+// reported as transient rather than as an empty market (the failure that used+// to coach agents into lowering their conviction floor during an outage); an+// unknown coin is distinguished from an outage; and the two account-scoped+// watch tools refuse an anonymous caller, refuse an agent the caller does not+// own, and clamp every numeric watch setting into its advertised range before+// persisting. The oracle store, rate limiter, and DB are mocked at their module+// boundary; the tool defs and their validation run real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const store = {+ readFeed: vi.fn(),+ scoreCoin: vi.fn(),+ getWatch: vi.fn(),+ upsertWatch: vi.fn(),+ recentActions: vi.fn(),+ actionsSummary: vi.fn(),+};+vi.mock('../../api/_lib/oracle/store.js', () => ({+ readFeed: (...a) => store.readFeed(...a),+ scoreCoin: (...a) => store.scoreCoin(...a),+ getWatch: (...a) => store.getWatch(...a),+ upsertWatch: (...a) => store.upsertWatch(...a),+ recentActions: (...a) => store.recentActions(...a),+ actionsSummary: (...a) => store.actionsSummary(...a),+}));++let ownedAgentIds = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (_strings, ...values) =>+ ownedAgentIds.includes(values[0]) ? [{ id: values[0] }] : [],+ ),+}));++let rlOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { mcpIp: vi.fn(async () => ({ success: rlOk, reset: Date.now() + 60_000 })) },+}));++const { toolDefs } = await import('../../api/_mcp/tools/oracle.js');++const AGENT_ID = '11111111-2222-4333-8444-555555555555';+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const ANON = { userId: null, rateKey: 'oracle-test', scope: '', source: 'free' };+const OWNER = { userId: 'user-1', rateKey: 'oracle-owner', scope: 'agents:read agents:write', source: 'oauth' };++const call = (name, args, auth = ANON) =>+ toolDefs.find((t) => t.name === name).handler(args, auth, {});++beforeEach(() => {+ for (const fn of Object.values(store)) fn.mockReset();+ ownedAgentIds = [AGENT_ID];+ rlOk = true;+});++describe('oracle MCP tools: registration', () => {+ it('registers four tools and scopes only the account-bound ones', () => {+ const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));+ expect(Object.keys(byName)).toEqual([+ 'oracle_top_plays',+ 'oracle_coin',+ 'oracle_arm_watch',+ 'oracle_watch_status',+ ]);+ expect(byName.oracle_top_plays.scope).toBeUndefined();+ expect(byName.oracle_coin.scope).toBeUndefined();+ expect(byName.oracle_arm_watch.scope).toBe('agents:write');+ expect(byName.oracle_watch_status.scope).toBe('agents:read');+ // oracle_arm_watch can spend real SOL once armed, so its destructive hint+ // must be explicit rather than left to the spec default.+ expect(byName.oracle_arm_watch.annotations.destructiveHint).toBe(false);+ expect(byName.oracle_arm_watch.inputSchema.properties.mode.default).toBe('simulate');+ });+});++describe('oracle_top_plays', () => {+ it('returns ranked plays with a tier-derived recommendation', async () => {+ store.readFeed.mockResolvedValue([+ {+ mint: MINT, symbol: 'THREE', score: 91, tier: 'prime', category: 'ai',+ smart_wallet_count: 4, pillars: { pedigree: 88 }, badges: ['smart_money_early'],+ scored_at: '2026-08-13T00:00:00.000Z',+ },+ { mint: 'Mint2', symbol: 'TWO', score: 74, tier: 'strong', pillars: {}, scored_at: null },+ ]);++ const r = await call('oracle_top_plays', { limit: 5, min_score: 72, network: 'mainnet' });+ expect(r.isError).toBeUndefined();+ expect(store.readFeed).toHaveBeenCalledWith({+ network: 'mainnet', limit: 5, minScore: 72, category: null, sinceSeconds: 6 * 3600,+ });+ expect(r.structuredContent.count).toBe(2);+ expect(r.structuredContent.top.recommendation).toEqual({+ action: 'buy', confidence: 'high', size_factor: 1.0,+ note: expect.stringContaining('top-conviction play'),+ });+ expect(r.structuredContent.plays[1].recommendation.size_factor).toBe(0.75);+ expect(r.structuredContent.plays[0].badges).toEqual(['smart_money_early']);+ });++ it('clamps limit, min_score, and an unknown category to the advertised bounds', async () => {+ store.readFeed.mockResolvedValue([]);+ await call('oracle_top_plays', { limit: 999, min_score: 500, category: 'nonsense', network: 'nope' });+ expect(store.readFeed).toHaveBeenCalledWith({+ network: 'mainnet', limit: 20, minScore: 100, category: null, sinceSeconds: 6 * 3600,+ });+ });++ it('reports a degraded feed store as transient, never as an empty market', async () => {+ store.readFeed.mockRejectedValue(new Error('connection terminated'));+ const r = await call('oracle_top_plays', {});+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/temporarily unavailable/i);+ expect(r.content[0].text).not.toMatch(/lowering min_score/);+ });++ it('rate-limits per caller', async () => {+ rlOk = false;+ const r = await call('oracle_top_plays', {});+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/rate limit/i);+ expect(store.readFeed).not.toHaveBeenCalled();+ });+});++describe('oracle_coin', () => {+ it('scores a coin on demand and reports data confidence alongside the verdict', async () => {+ store.scoreCoin.mockResolvedValue({+ verdict: { score: 55, tier: 'lean', pillars: { momentum: 40 }, badges: [], confidence: 0.4, confidenceLabel: 'thin' },+ intel: { symbol: 'THREE', category: 'ai', marketCapUsd: 1234, graduated: true, creator: 'Creator1', smartMoney: { smartWalletCount: 2 } },+ });+ const r = await call('oracle_coin', { mint: MINT });+ expect(store.scoreCoin).toHaveBeenCalledWith(MINT, { network: 'mainnet', classify: true, persist: true });+ expect(r.structuredContent.conviction).toBe(55);+ expect(r.structuredContent.recommendation.action).toBe('watch');+ expect(r.structuredContent.data_confidence).toBe(0.4);+ expect(r.structuredContent.market_cap_usd).toBe(1234);+ });++ it('rejects a non-base58 mint before touching the store', async () => {+ const r = await call('oracle_coin', { mint: 'not a mint!!' });+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/Invalid mint/);+ expect(store.scoreCoin).not.toHaveBeenCalled();+ });++ it('distinguishes an unobserved coin from a degraded intel store', async () => {+ store.scoreCoin.mockResolvedValue(null);+ const unknown = await call('oracle_coin', { mint: MINT });+ expect(unknown.isError).toBe(true);+ expect(unknown.content[0].text).toMatch(/not found in Oracle/);++ store.scoreCoin.mockRejectedValue(new Error('intel store down'));+ const degraded = await call('oracle_coin', { mint: MINT });+ expect(degraded.isError).toBe(true);+ expect(degraded.content[0].text).toMatch(/temporarily unavailable/i);+ });+});++describe('oracle_arm_watch', () => {+ it('arms an owned agent and clamps every numeric setting into range', async () => {+ store.upsertWatch.mockResolvedValue(undefined);+ store.getWatch.mockResolvedValue({ agent_id: AGENT_ID, armed: true, mode: 'live' });+ store.actionsSummary.mockResolvedValue({ total: 3, wins: 2, losses: 1, win_rate: 0.67, realized_pnl_sol: 0.2 });++ const r = await call('oracle_arm_watch', {+ agent_id: AGENT_ID, mode: 'live', min_score: 900, min_tier: 'bogus',+ categories: ['ai', 'not-a-category'], per_trade_sol: 99, max_daily_sol: 99,+ max_open: 900, require_smart_money: true, size_scaling: false,+ }, OWNER);++ expect(r.isError).toBeUndefined();+ const [agentId, userId, network, cfg] = store.upsertWatch.mock.calls[0];+ expect(agentId).toBe(AGENT_ID);+ expect(userId).toBe('user-1');+ expect(network).toBe('mainnet');+ expect(cfg).toEqual({+ armed: true, mode: 'live', min_score: 100, min_tier: 'strong',+ categories: ['ai'], per_trade_sol: 1, max_daily_sol: 10, max_open: 50,+ require_smart_money: true, size_scaling: false,+ });+ expect(r.structuredContent.track_record.wins).toBe(2);+ });++ it('refuses an anonymous caller and an agent the caller does not own', async () => {+ const anon = await call('oracle_arm_watch', { agent_id: AGENT_ID }, ANON);+ expect(anon.isError).toBe(true);+ expect(anon.content[0].text).toMatch(/signed in/i);++ ownedAgentIds = [];+ const foreign = await call('oracle_arm_watch', { agent_id: AGENT_ID }, OWNER);+ expect(foreign.isError).toBe(true);+ expect(foreign.content[0].text).toMatch(/does not belong to your account/);+ expect(store.upsertWatch).not.toHaveBeenCalled();+ });++ it('rejects a malformed agent_id before the ownership query', async () => {+ const r = await call('oracle_arm_watch', { agent_id: 'nope' }, OWNER);+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/Invalid agent_id/);+ expect(store.upsertWatch).not.toHaveBeenCalled();+ });+});++describe('oracle_watch_status', () => {+ it('returns the config, track record, and recent actions for an armed agent', async () => {+ store.getWatch.mockResolvedValue({+ agent_id: AGENT_ID, armed: true, mode: 'simulate', min_score: 72, min_tier: 'strong',+ categories: ['ai'], per_trade_sol: 0.05, max_daily_sol: 0.5, max_open: 10,+ require_smart_money: false, size_scaling: true,+ });+ store.actionsSummary.mockResolvedValue({ total: 1, wins: 1, losses: 0, win_rate: 1, realized_pnl_sol: 0.4 });+ store.recentActions.mockResolvedValue([+ { mint: MINT, symbol: 'THREE', tier: 'prime', conviction: 92, size_sol: 0.05, mode: 'simulate', outcome: 'win', realized_pnl_sol: 0.4, exit_signal: null, acted_at: '2026-08-12T00:00:00.000Z' },+ ]);++ const r = await call('oracle_watch_status', { agent_id: AGENT_ID }, OWNER);+ expect(r.structuredContent.armed).toBe(true);+ expect(r.structuredContent.config.min_tier).toBe('strong');+ expect(r.structuredContent.recent_actions[0].pnl_sol).toBe(0.4);+ expect(store.recentActions).toHaveBeenCalledWith(AGENT_ID, 'mainnet', 10);+ });++ it('tells an unarmed agent how to get started instead of erroring', async () => {+ store.getWatch.mockResolvedValue(null);+ store.actionsSummary.mockResolvedValue(null);+ store.recentActions.mockResolvedValue([]);+ const r = await call('oracle_watch_status', { agent_id: AGENT_ID }, OWNER);+ expect(r.isError).toBeUndefined();+ expect(r.structuredContent.armed).toBe(false);+ expect(r.structuredContent.message).toMatch(/oracle_arm_watch/);+ });+});diff --git a/tests/api/mcp-solana-attestation-tools.test.js b/tests/api/mcp-solana-attestation-tools.test.jsnew file mode 100644index 000000000..1736d5820--- /dev/null+++ b/tests/api/mcp-solana-attestation-tools.test.js@@ -0,0 +1,194 @@+// Solana attestation MCP tools (api/_mcp/tools/solana.js), registered in+// api/_mcp/catalog.js and re-used by api/_lib/persona-wallet.js through the+// exported solanaReputation().+//+// Verifies: a cold agent is crawled once before its first read and a warm agent+// is never re-crawled; a crawl fault degrades to the cached (empty) index+// instead of failing the tool; reputation rounds its score averages and keeps+// the verified-only average separate from the raw one; the attestation list+// honors the kind filter through KIND_MAP and passes "all" straight through;+// and the passport answers for an agent that is not in our identity index+// (agent_off_index) rather than throwing. The DB and the chain crawler are+// mocked at their module boundary; the tool defs run real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';++const ASSET = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const dbState = {+ cursor: [{ '?column?': 1 }],+ agent: [],+ feedback: [{ total: 0, verified: 0, disputed: 0, score_avg: 0, score_avg_verified: 0 }],+ validation: [{ passed: 0, failed: 0 }],+ attestations: [],+ queries: [],+};++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = strings.join('?');+ dbState.queries.push({ q, values });+ if (q.includes('solana_attestations_cursor')) return dbState.cursor;+ if (q.includes('from agent_identities')) return dbState.agent;+ if (q.includes('with feedback as')) return dbState.feedback;+ if (q.includes('threews.validation.v1')) return dbState.validation;+ if (q.includes('select signature, slot')) return dbState.attestations;+ throw new Error(`unexpected query: ${q}`);+ }),+}));++const crawlMock = vi.fn(async () => ({ inserted: 0 }));+vi.mock('../../api/_lib/solana-attestations.js', () => ({+ crawlAgentAttestations: (...a) => crawlMock(...a),+ KIND_MAP: {+ feedback: 'threews.feedback.v1',+ validation: 'threews.validation.v1',+ task: 'threews.task.v1',+ accept: 'threews.accept.v1',+ revoke: 'threews.revoke.v1',+ dispute: 'threews.dispute.v1',+ },+}));++const { toolDefs, solanaReputation } = await import('../../api/_mcp/tools/solana.js');++const AUTH = { userId: null, rateKey: 'solana-test', scope: '', source: 'x402' };+const call = (name, args) => toolDefs.find((t) => t.name === name).handler(args, AUTH, {});++beforeEach(() => {+ dbState.cursor = [{ '?column?': 1 }];+ dbState.agent = [];+ dbState.feedback = [{ total: 0, verified: 0, disputed: 0, score_avg: 0, score_avg_verified: 0 }];+ dbState.validation = [{ passed: 0, failed: 0 }];+ dbState.attestations = [];+ dbState.queries = [];+ crawlMock.mockClear();+ crawlMock.mockResolvedValue({ inserted: 0 });+});++describe('solana attestation MCP tools: registration', () => {+ it('registers three public read tools with explicit non-destructive annotations', () => {+ expect(toolDefs.map((t) => t.name)).toEqual([+ 'solana_agent_reputation',+ 'solana_agent_attestations',+ 'solana_agent_passport',+ ]);+ for (const t of toolDefs) {+ expect(t.scope).toBeUndefined();+ expect(t.annotations).toEqual({+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ });+ expect(t.inputSchema.required).toEqual(['asset']);+ }+ });+});++describe('solana_agent_reputation', () => {+ it('rounds both score averages and keeps the verified average separate', async () => {+ dbState.feedback = [{+ total: 4, verified: 2, disputed: 1,+ score_avg: 3.666666666, score_avg_verified: 4.5,+ }];+ dbState.validation = [{ passed: 3, failed: 1 }];++ const r = await call('solana_agent_reputation', { asset: ASSET, network: 'mainnet' });+ expect(r.structuredContent).toEqual({+ agent: ASSET,+ network: 'mainnet',+ feedback: { total: 4, verified: 2, disputed: 1, score_avg: 3.667, score_avg_verified: 4.5 },+ validation: { passed: 3, failed: 1 },+ });+ expect(JSON.parse(r.content[0].text)).toEqual(r.structuredContent);+ });++ it('defaults to devnet and skips the crawl when the agent is already indexed', async () => {+ await call('solana_agent_reputation', { asset: ASSET });+ expect(crawlMock).not.toHaveBeenCalled();+ expect(dbState.queries.some((c) => c.values.includes('devnet'))).toBe(true);+ });++ it('crawls a cold agent once, seeding the owner wallet from our identity index', async () => {+ dbState.cursor = [];+ dbState.agent = [{ owner: 'OwnerWallet111' }];+ await call('solana_agent_reputation', { asset: ASSET, network: 'mainnet' });+ expect(crawlMock).toHaveBeenCalledWith({+ agentAsset: ASSET, network: 'mainnet', ownerWallet: 'OwnerWallet111',+ });+ });++ it('degrades to the cached index when the chain crawl fails', async () => {+ dbState.cursor = [];+ crawlMock.mockRejectedValue(new Error('RPC 429'));+ const r = await call('solana_agent_reputation', { asset: ASSET });+ expect(r.structuredContent.feedback.total).toBe(0);+ expect(r.isError).toBeUndefined();+ });++ it('is exported for reuse by the persona wallet surface', async () => {+ dbState.feedback = [{ total: 1, verified: 1, disputed: 0, score_avg: 5, score_avg_verified: 5 }];+ const rep = await solanaReputation(ASSET, 'mainnet');+ expect(rep.agent).toBe(ASSET);+ expect(rep.feedback.score_avg).toBe(5);+ });+});++describe('solana_agent_attestations', () => {+ it('maps a kind filter onto its on-chain schema id', async () => {+ dbState.attestations = [{ signature: 'sig1', slot: 10, kind: 'threews.feedback.v1', verified: true }];+ const r = await call('solana_agent_attestations', { asset: ASSET, kind: 'feedback', limit: 5, network: 'mainnet' });+ const rowQuery = dbState.queries.find((c) => c.q.includes('select signature, slot'));+ expect(rowQuery.values).toContain('threews.feedback.v1');+ expect(rowQuery.values).toContain(5);+ expect(r.structuredContent.count).toBe(1);+ expect(r.structuredContent.kind).toBe('feedback');+ });++ it('reads every kind when kind is "all" and defaults the limit', async () => {+ await call('solana_agent_attestations', { asset: ASSET });+ const rowQuery = dbState.queries.find((c) => c.q.includes('select signature, slot'));+ expect(rowQuery.values).not.toContain('threews.feedback.v1');+ expect(rowQuery.values).toContain(50);+ });++ it('returns an empty, non-error result for an agent with no attestations', async () => {+ const r = await call('solana_agent_attestations', { asset: ASSET, kind: 'dispute' });+ expect(r.isError).toBeUndefined();+ expect(r.structuredContent).toMatchObject({ agent: ASSET, count: 0, data: [] });+ });+});++describe('solana_agent_passport', () => {+ it('assembles identity, reputation, validation, and recent attestations', async () => {+ dbState.agent = [{+ id: 'agent-uuid', name: 'Three Agent', description: 'does things',+ owner: 'OwnerWallet111', meta: { network: 'mainnet' },+ }];+ dbState.feedback = [{ total: 2, verified: 1, disputed: 0, score_avg: 4, score_avg_verified: 5 }];+ dbState.validation = [{ passed: 1, failed: 0 }];+ dbState.attestations = [{ signature: 'sig1', slot: 11, kind: 'threews.feedback.v1' }];++ const r = await call('solana_agent_passport', { asset: ASSET, network: 'mainnet' });+ expect(r.structuredContent.identity).toEqual({+ id: 'agent-uuid', name: 'Three Agent', description: 'does things',+ owner: 'OwnerWallet111', asset_pubkey: ASSET, network: 'mainnet',+ });+ expect(r.structuredContent.reputation.score_avg).toBe(4);+ expect(r.structuredContent.validation).toEqual({ passed: 1, failed: 0 });+ expect(r.structuredContent.recent_attestations).toHaveLength(1);+ expect(r.structuredContent.schemas_url).toMatch(/\/\.well-known\/agent-attestation-schemas$/);+ });++ it('flags an agent that is not in our identity index instead of failing', async () => {+ dbState.agent = [];+ const r = await call('solana_agent_passport', { asset: ASSET });+ expect(r.isError).toBeUndefined();+ expect(r.structuredContent.identity).toEqual({+ agent_off_index: true, asset_pubkey: ASSET, network: 'devnet',+ });+ });+});diff --git a/tests/api/mcp-tokenize-tools.test.js b/tests/api/mcp-tokenize-tools.test.jsnew file mode 100644index 000000000..071028f78--- /dev/null+++ b/tests/api/mcp-tokenize-tools.test.js@@ -0,0 +1,174 @@+// 3D tokenization MCP tools (api/_mcp/tools/tokenize.js), registered in+// api/_mcp/catalog.js.+//+// Verifies: mint_3d_asset only ever declares a collected mint fee for a genuine+// per-call x402 settlement (an OAuth bearer and an unpaid x402 principal both+// declare zero, so a remix royalty can never split a fee nobody paid); the+// caller's arguments reach the minting lib under their internal names; a+// pending mint tells the agent to read it back rather than reporting a mint+// address it does not have; a handled boundary error becomes a clean isError+// result while an unexpected fault still bubbles for the dispatcher to+// sanitize; and get_3d_asset_onchain returns the live asset for a real mint and+// a designed error for a malformed one.+//+// The Solana minting lib is mocked at its module boundary, so no test ever+// signs or settles on-chain. The tool defs and their fee logic run real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const mintMock = vi.fn();+const readMock = vi.fn();+const ROYALTY_CAP_BPS = 1000;++vi.mock('../../api/_lib/tokenize-3d.js', () => ({+ mintTokenized3dAsset: (...a) => mintMock(...a),+ readTokenized3dAsset: (...a) => readMock(...a),+ TOKENIZE_3D_ROYALTY_CAP_BPS: ROYALTY_CAP_BPS,+}));++vi.mock('../../api/_lib/pump-pricing.js', () => ({+ priceFor: (name) => (name === 'mint_3d_asset' ? { amount_usdc: 0.25 } : null),+}));++const { toolDefs } = await import('../../api/_mcp/tools/tokenize.js');++const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const AVATAR_ID = '11111111-2222-4333-8444-555555555555';+const call = (name, args, auth) => toolDefs.find((t) => t.name === name).handler(args, auth, {});++const MINTED = {+ status: 'minted', idempotent: false, name: 'Test Avatar', network: 'devnet', mint: MINT,+ explorer_asset_url: 'https://explorer.test/asset', explorer_tx_url: 'https://explorer.test/tx',+ viewer_url: 'https://three.ws/viewer', provenance_ledger: { action_id: 42, signed: true },+ royalty: { percent: 5, cap_basis_points: ROYALTY_CAP_BPS, capped: false, requested_basis_points: 500 },+};++beforeEach(() => {+ mintMock.mockReset();+ readMock.mockReset();+ mintMock.mockResolvedValue(MINTED);+});++describe('tokenize MCP tools: registration', () => {+ it('registers a write tool and a read tool with the royalty cap in their contract', () => {+ const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));+ expect(Object.keys(byName)).toEqual(['mint_3d_asset', 'get_3d_asset_onchain']);+ expect(byName.mint_3d_asset.annotations).toEqual({+ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true,+ });+ expect(byName.get_3d_asset_onchain.annotations.readOnlyHint).toBe(true);+ expect(byName.mint_3d_asset.inputSchema.properties.seller_fee_basis_points.maximum).toBe(ROYALTY_CAP_BPS);+ expect(byName.mint_3d_asset.inputSchema.properties.network.default).toBe('devnet');+ expect(byName.get_3d_asset_onchain.inputSchema.required).toEqual(['mint']);+ });+});++describe('mint_3d_asset: collected-fee accounting', () => {+ it('declares the collected fee only for a settled per-call x402 payment', async () => {+ await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'x402', x402Paid: true, userId: null });+ expect(mintMock.mock.calls[0][0].mintFeeAtomicsCollected).toBe(250_000n);+ });++ it('declares zero for an OAuth bearer and for an unpaid x402 principal', async () => {+ await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'oauth', userId: 'user-1' });+ expect(mintMock.mock.calls[0][0].mintFeeAtomicsCollected).toBe(0n);++ mintMock.mockClear();+ await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'x402', x402Paid: false, userId: null });+ expect(mintMock.mock.calls[0][0].mintFeeAtomicsCollected).toBe(0n);+ });+});++describe('mint_3d_asset: argument and result mapping', () => {+ it('forwards every caller argument under its internal name', async () => {+ await call('mint_3d_asset', {+ glb_url: 'https://cdn.test/model.glb', owner_wallet: 'OwnerWallet111',+ name: 'Remix', description: 'a remix', network: 'mainnet',+ seller_fee_basis_points: 500, royalty_recipient: 'RoyaltyWallet111',+ parent_mint: 'ParentMint111', prompt: 'a chrome robot',+ generation_model: 'model-x', generation_provider: 'provider-y',+ idempotency_key: 'key-1',+ }, { source: 'oauth', userId: 'user-1' });++ expect(mintMock.mock.calls[0][0]).toMatchObject({+ avatarId: undefined, glbUrl: 'https://cdn.test/model.glb', ownerWallet: 'OwnerWallet111',+ requesterId: 'user-1', name: 'Remix', description: 'a remix', network: 'mainnet',+ sellerFeeBasisPoints: 500, royaltyRecipient: 'RoyaltyWallet111', parentMint: 'ParentMint111',+ prompt: 'a chrome robot', generationModel: 'model-x', generationProvider: 'provider-y',+ idempotencyKey: 'key-1',+ });+ });++ it('defaults to devnet and a null requester for an anonymous payer', async () => {+ await call('mint_3d_asset', { glb_url: 'https://cdn.test/m.glb' }, { source: 'x402', x402Paid: true });+ expect(mintMock.mock.calls[0][0]).toMatchObject({ network: 'devnet', requesterId: null });+ });++ it('summarizes a completed mint with its explorer, viewer, royalty, and provenance links', async () => {+ const r = await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'oauth', userId: 'user-1' });+ expect(r.isError).toBeUndefined();+ expect(r.structuredContent).toEqual(MINTED);+ const text = r.content[0].text;+ expect(text).toContain(`Mint: ${MINT}`);+ expect(text).toContain('https://explorer.test/tx');+ expect(text).toContain('Royalty: 5% (cap 10%)');+ expect(text).toContain('ledger action #42 (signed)');+ });++ it('reports a clamped royalty and a paid remix split', async () => {+ mintMock.mockResolvedValue({+ ...MINTED, idempotent: true,+ royalty: { percent: 10, cap_basis_points: ROYALTY_CAP_BPS, capped: true, requested_basis_points: 5000 },+ remix_royalty: { paid: true, creator_usd: '0.05', creator_tx: 'TxSig111' },+ });+ const r = await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'oauth', userId: 'user-1' });+ expect(r.content[0].text).toContain('Already minted');+ expect(r.content[0].text).toContain('requested 50%, clamped');+ expect(r.content[0].text).toContain('0.05 USDC paid to the source creator (TxSig111)');+ });++ it('tells the agent to read a pending mint back instead of naming a mint it lacks', async () => {+ mintMock.mockResolvedValue({ status: 'pending' });+ const r = await call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'oauth', userId: 'user-1' });+ expect(r.content[0].text).toContain('get_3d_asset_onchain');+ expect(r.content[0].text).not.toContain('Mint: undefined');+ });+});++describe('tokenize MCP tools: failure paths', () => {+ it('turns a handled boundary error into a clean tool error', async () => {+ mintMock.mockRejectedValue(Object.assign(new Error('provide either avatar_id or glb_url'), {+ status: 400, code: 'invalid_request',+ }));+ const r = await call('mint_3d_asset', {}, { source: 'oauth', userId: 'user-1' });+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toBe('Error: provide either avatar_id or glb_url');+ });++ it('lets an unexpected fault bubble to the dispatcher instead of masking it', async () => {+ mintMock.mockRejectedValue(new Error('connection terminated unexpectedly'));+ await expect(call('mint_3d_asset', { avatar_id: AVATAR_ID }, { source: 'oauth', userId: 'user-1' }))+ .rejects.toThrow('connection terminated unexpectedly');+ });++ it('resolves a mint to its live asset and errors cleanly on a malformed one', async () => {+ readMock.mockResolvedValue({ mint: MINT, holder: 'HolderWallet111', viewer_url: 'https://three.ws/viewer' });+ const ok = await call('get_3d_asset_onchain', { mint: MINT, network: 'mainnet' }, { source: 'x402' });+ expect(readMock).toHaveBeenCalledWith({ mint: MINT, network: 'mainnet' });+ expect(ok.structuredContent.holder).toBe('HolderWallet111');+ expect(JSON.parse(ok.content[0].text).mint).toBe(MINT);++ readMock.mockRejectedValue(Object.assign(new Error('mint is not a valid Solana address'), {+ status: 400, code: 'invalid_mint',+ }));+ const bad = await call('get_3d_asset_onchain', { mint: 'nope' }, { source: 'x402' });+ expect(bad.isError).toBe(true);+ expect(bad.content[0].text).toBe('Error: mint is not a valid Solana address');+ });++ it('defaults the read network to devnet', async () => {+ readMock.mockResolvedValue({ mint: MINT });+ await call('get_3d_asset_onchain', { mint: MINT }, { source: 'x402' });+ expect(readMock).toHaveBeenCalledWith({ mint: MINT, network: 'devnet' });+ });+});diff --git a/tests/api/persona-identity-route.test.js b/tests/api/persona-identity-route.test.jsnew file mode 100644index 000000000..b5009b4a4--- /dev/null+++ b/tests/api/persona-identity-route.test.js@@ -0,0 +1,184 @@+// Tests for GET /api/mcp3d/persona-identity, the live chain-state feed the+// embodiment embed polls (only when opened with ?wallet=1) so the body's+// aura/cosmetic/muted-state/nameplate track current chain state.+//+// Every network boundary the identity read touches is stubbed, so these tests+// exercise the route's own contract (status codes, response shape, CORS, cache+// headers, leak-proofing) deterministically instead of depending on a live RPC,+// attestation DB, price feed, or SNS lookup. The persona itself round-trips+// through the real filesystem backend (no DB, no R2).++import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';+import { Readable } from 'node:stream';+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';+process.env.JWT_SECRET ||= 'test-jwt-secret-not-a-real-secret-0123456789';+process.env.PERSONA_WALLET_SECRET ||= 'test-persona-wallet-secret-0123456789';++vi.mock('../../api/_lib/agent-pumpfun.js', () => ({+ solanaConnection: () => ({+ getBalance: vi.fn(async () => { throw new Error('rpc unavailable in test'); }),+ getTokenAccountBalance: vi.fn(async () => { throw new Error('rpc unavailable in test'); }),+ }),+}));+vi.mock('../../api/_lib/portfolio.js', () => ({+ valuateHoldings: vi.fn(async () => { throw new Error('portfolio rpc unavailable in test'); }),+}));+vi.mock('../../api/_mcp/tools/solana.js', () => ({+ solanaReputation: vi.fn(async () => { throw new Error('no db in test'); }),+}));+vi.mock('../../api/_lib/avatar-wallet.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, solUsdPrice: vi.fn(async () => { throw new Error('no price feed in test'); }) };+});++// The nameplate read goes out through global fetch to the SNS API; keep it off+// the network so a sandboxed run is instant and offline-safe.+const realFetch = globalThis.fetch;+globalThis.fetch = vi.fn(async () => { throw new Error('sns unavailable in test'); });++const { createPersona } = await import('../../api/_lib/persona-store.js');+const { default: handler } = await import('../../api/mcp3d/persona-identity.js');++let tmpDir;+const saved = {};+let personaId;++beforeAll(async () => {+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'persona-identity-route-test-'));+ for (const k of ['PERSONA_STORE_DIR', 'DATABASE_URL', 'S3_BUCKET', 'S3_PUBLIC_DOMAIN']) saved[k] = process.env[k];+ process.env.PERSONA_STORE_DIR = tmpDir;+ delete process.env.DATABASE_URL;+ delete process.env.S3_BUCKET;+ delete process.env.S3_PUBLIC_DOMAIN;+ const rec = await createPersona({+ name: 'Nova',+ glbUrl: 'https://three.ws/cdn/creations/nova.glb',+ glbKey: 'creations/nova.glb',+ ownerId: 'secret-owner',+ });+ personaId = rec.id;+});++afterAll(async () => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ globalThis.fetch = realFetch;+ if (tmpDir) await fs.rm(tmpDir, { recursive: true, force: true });+});++function makeReq({ method = 'GET', url = '/' } = {}) {+ const req = Readable.from([]);+ req.method = method;+ req.url = url;+ req.headers = { host: 'three.ws' };+ return req;+}+function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },+ };+}+async function invoke(url, method = 'GET') {+ const req = makeReq({ url, method });+ const res = makeRes();+ await handler(req, res);+ return { res, status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++describe('GET /api/mcp3d/persona-identity', () => {+ it('resolves a known persona to its public projection plus the live identity read', async () => {+ const { status, body, res } = await invoke(`/api/mcp3d/persona-identity?id=${personaId}`);+ expect(status).toBe(200);+ // The persona body itself, nested; the identity fields spread at the top+ // level because that is exactly what EmbodimentStage.setChainState() reads.+ expect(body.persona.persona_id).toBe(personaId);+ expect(body.persona.name).toBe('Nova');+ expect(body.persona_id).toBe(personaId);+ expect(body.network).toBe('mainnet');+ expect(body.address).toMatch(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);+ expect(body.explorer).toContain(body.address);+ for (const k of ['balances', 'reputation', 'holdings', 'nameplate', 'visual', 'caps', 'fetched_at']) {+ expect(body[k]).toBeDefined();+ }+ // Every tier has a designed value even when every upstream is down.+ expect(body.visual.reputation_tier).toBe('unranked');+ expect(body.visual.holdings_tier).toBe('none');+ // CORS + a short shared cache so the cross-origin embed can poll it.+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['cache-control']).toMatch(/s-maxage=15/);+ expect(res.headers['cross-origin-resource-policy']).toBe('cross-origin');+ });++ it('never leaks the storage key, the owner id, or any secret material', async () => {+ const { res } = await invoke(`/api/mcp3d/persona-identity?id=${personaId}`);+ expect(res.body).not.toContain('secret-owner');+ expect(res.body).not.toContain('glb_key');+ expect(res.body).not.toMatch(/secretKey|private_key|privateKey/i);+ expect(res.body).not.toContain(process.env.PERSONA_WALLET_SECRET);+ });++ it('honors ?network=devnet and coerces anything else to mainnet', async () => {+ const dev = await invoke(`/api/mcp3d/persona-identity?id=${personaId}&network=devnet`);+ expect(dev.body.network).toBe('devnet');+ const bogus = await invoke(`/api/mcp3d/persona-identity?id=${personaId}&network=fantasynet`);+ expect(bogus.status).toBe(200);+ expect(bogus.body.network).toBe('mainnet');+ // Same persona, same derived wallet, regardless of which network is read.+ expect(dev.body.address).toBe(bogus.body.address);+ });++ it('400 on a malformed id', async () => {+ const { status, body } = await invoke('/api/mcp3d/persona-identity?id=not-a-persona');+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_id');+ });++ it('400 when the id is missing entirely', async () => {+ const { status, body } = await invoke('/api/mcp3d/persona-identity');+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_id');+ });++ it('404 on a well-formed but unknown id', async () => {+ const { status, body } = await invoke('/api/mcp3d/persona-identity?id=persona_deadbeefdeadbeefdead');+ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('405 on a non-GET method, and says which methods are allowed', async () => {+ const { status, body, res } = await invoke(`/api/mcp3d/persona-identity?id=${personaId}`, 'POST');+ expect(status).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ expect(res.headers.allow).toBe('GET, HEAD, OPTIONS');+ });++ it('503 wallet_unavailable when no persona wallet secret is configured', async () => {+ const keys = ['PERSONA_WALLET_SECRET', 'WALLET_ENCRYPTION_KEY', 'JWT_SECRET'];+ const kept = Object.fromEntries(keys.map((k) => [k, process.env[k]]));+ for (const k of keys) delete process.env[k];+ try {+ const { status, body } = await invoke(`/api/mcp3d/persona-identity?id=${personaId}`);+ expect(status).toBe(503);+ expect(body.error).toBe('wallet_unavailable');+ // A config fault is reported as a config fault, never as a stack trace.+ expect(body.message).not.toMatch(/secret|stack|Error:/i);+ } finally {+ for (const [k, v] of Object.entries(kept)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ }+ });+});diff --git a/tests/embed-doctor.test.js b/tests/embed-doctor.test.jsindex f91d9d57f..a9bc00b61 100644--- a/tests/embed-doctor.test.js+++ b/tests/embed-doctor.test.js@@ -12,6 +12,8 @@ import {looksLikeCspBlock,snippetHostHtml,EMBED_TAG,+ EMBED_TAGS,+ EMBED_SELECTOR,SOURCE_ATTRIBUTES,} from '../api/_lib/embed-doctor.js';@@ -240,6 +242,92 @@ describe('analyze — the element', () => {});});+// The v1 loader (public/embed/v1.js) registers <three-d>, <three-agent> and+// <three-ws> rather than <agent-3d>, and it is what the gated-embed snippet in+// api/embed/gate-create.js hands developers. The doctor accepted that loader+// but knew only the canonical tag, so a working v1 embed came back "broken".+describe('analyze — the v1 loader element aliases', () => {+ const V1_LOADER = 'https://three.ws/embed/v1.js';++ function v1Observations(elementOverrides = {}) {+ const base = healthyObservations();+ return healthyObservations({+ scripts: [{ src: V1_LOADER, type: '' }],+ network: [+ { url: V1_LOADER, status: 200, ok: true, bytes: 31835 },+ { url: 'https://three.ws/api/agents/abc123', status: 200, ok: true },+ ],+ element: { ...base.element, tag: 'three-d', ...elementOverrides },+ });+ }++ for (const tag of EMBED_TAGS) {+ it(`reports a healthy <${tag}> embed as healthy`, () => {+ const report = analyze(v1Observations({ tag }));+ expect(report.verdict).toBe('healthy');+ expect(failed(report)).toHaveLength(0);+ expect(byId(report, 'element_upgraded').detail).toContain(`customElements.get('${tag}')`);+ });+ }++ it('names the tag the developer actually wrote when it was never upgraded', () => {+ const report = analyze(v1Observations({ defined: false }));+ const f = byId(report, 'element_not_upgraded');+ expect(f.severity).toBe('fatal');+ expect(f.detail).toContain('<three-d>');+ expect(f.detail).not.toContain(`<${EMBED_TAG}>`);+ });++ it('writes the fix snippet with the caller tag, not the canonical one', () => {+ const report = analyze(+ v1Observations({ attributes: { mode: 'floating' } }),+ );+ expect(byId(report, 'source_missing').fix).toContain('<three-d agent-id=');+ });++ it('falls back to the canonical tag when there is no element to name', () => {+ const report = analyze(healthyObservations({ element: null }));+ expect(byId(report, 'element_missing').title).toContain(`<${EMBED_TAG}>`);+ });++ it('ignores a tag the platform does not register, so a report cannot echo page markup', () => {+ const report = analyze(v1Observations({ tag: 'script', defined: false }));+ expect(byId(report, 'element_not_upgraded').detail).toContain(`<${EMBED_TAG}>`);+ });+});++// The in-page probe has no deadline of its own, so a page that pegs its main+// thread gets its page closed by the watchdog in collectFrom*. What comes back+// then is "we could not look", and the report has to say exactly that instead of+// claiming the developer's element is missing.+describe('analyze — a page that could not be inspected', () => {+ it('reports inconclusive rather than inventing a missing element', () => {+ const report = analyze(+ healthyObservations({ element: null, probeFailed: true, timedOut: true }),+ );+ expect(report.verdict).toBe('inconclusive');+ expect(idsOf(report)).not.toContain('element_missing');+ const f = byId(report, 'page_not_inspected');+ expect(f.status).toBe('unknown');+ expect(f.evidence.timedOut).toBe(true);+ // The loader evidence is upstream of the probe and still worth reporting.+ expect(idsOf(report)).toContain('loader_loaded');+ });++ it('distinguishes a closed page from an expired budget in the wording', () => {+ const report = analyze(+ healthyObservations({ element: null, probeFailed: true, timedOut: false }),+ );+ expect(byId(report, 'page_not_inspected').detail).toMatch(/closed the page/i);+ });++ it('still calls a genuinely missing element missing when the probe did run', () => {+ const report = analyze(healthyObservations({ element: null, probeFailed: false }));+ expect(byId(report, 'element_missing').severity).toBe('fatal');+ expect(idsOf(report)).not.toContain('page_not_inspected');+ });+});+describe('analyze — the agent id', () => {it('reports an unresolvable id as fatal with the lookup status', () => {const report = analyze(@@ -511,6 +599,15 @@ describe('helpers', () => {expect(isEmbedRelated('https://notthree.ws/x.js')).toBe(false);});+ it('probes with a selector covering every tag a platform loader registers', () => {+ expect(EMBED_TAGS).toContain(EMBED_TAG);+ expect(EMBED_SELECTOR.split(',')).toEqual(EMBED_TAGS);+ // The v1 loader's aliases, which public/embed/v1.js defines.+ for (const alias of ['three-d', 'three-agent', 'three-ws']) {+ expect(EMBED_TAGS).toContain(alias);+ }+ });+it('detects the wording browsers actually use for a CSP refusal', () => {expect(looksLikeCspBlock("Refused to load the script 'https://three.ws/x.js'")).toBe(true);expect(looksLikeCspBlock('because it violates the following Content Security Policy directive')).toBe(true);diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex a1b41d844..a45e71386 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -854,7 +854,7 @@"name": "find_services","title": "Find paid services the agent can call","descHead": "Search the live x402 facilitator network for paid services (HTTP APIs an",- "descHash": "10b9605cf0c4",+ "descHash": "0a3c1fdcaf27","annotations": {"readOnlyHint": true,"destructiveHint": false,@@ -867,14 +867,14 @@"name": "monetize_endpoint","title": "Publish a paid endpoint to earn USDC","descHead": "Put a price on an upstream API your agent already serves and publish it ",- "descHash": "43e54e8d4142",+ "descHash": "ee8468b7ec03","annotations": {"readOnlyHint": false,"destructiveHint": false,"idempotentHint": false,"openWorldHint": true},- "schemaHash": "ba14c8f9eb27"+ "schemaHash": "5181829cf383"},{"name": "pay_and_call",@@ -893,20 +893,20 @@"name": "provision_wallet","title": "Create the agent's wallet","descHead": "Create (or return) the custodial Solana wallet for one of your agents so",- "descHash": "aea787e2cec2",+ "descHash": "406b15338ea6","annotations": {"readOnlyHint": false,"destructiveHint": false,"idempotentHint": false,"openWorldHint": true},- "schemaHash": "575d608cdcde"+ "schemaHash": "9eb6ba57d5e7"},{"name": "wallet_status","title": "Check the agent's wallet","descHead": "Show the signed-in user's three.ws agent wallet: address, SOL and USDC b",- "descHash": "e8cef61875a7",+ "descHash": "4bbc44f0aaa1","annotations": {"readOnlyHint": true,"destructiveHint": false,@@ -921,7 +921,7 @@"name": "bazaar_service_details","title": "Live price details for one x402 service","descHead": "Resolve the current live price of a single x402 service by its resource ",- "descHash": "32ef6c0a06fd",+ "descHash": "ea7b6efc43d7","annotations": "ref:DISCOVERY_ANNOTATIONS","schemaHash": "8b343836306d"},@@ -929,7 +929,7 @@"name": "browse_services","title": "Browse the x402 bazaar","descHead": "List paid agent services from the live x402 facilitator network without ",- "descHash": "5f4946b4f7d3",+ "descHash": "87c59b46c02f","annotations": "ref:DISCOVERY_ANNOTATIONS","schemaHash": "24d42c431f67"},diff --git a/tests/friends-store-mute-and-cursor.test.js b/tests/friends-store-mute-and-cursor.test.jsnew file mode 100644index 000000000..b70e112f0--- /dev/null+++ b/tests/friends-store-mute-and-cursor.test.js@@ -0,0 +1,140 @@+// friends-store: two places where a well-formed caller input reached Postgres+// unchecked and the failure surfaced as the wrong thing entirely.+//+// muteUser() — user_mutes.muted_id is a foreign key to users(id). Muting an+// id that no longer exists raised a bare 23503 with no `status`+// on it, so api/_lib/http.js wrap() could only report a 500,+// complete with a Sentry capture and an ops alert, for what is+// a caller mistake. sendRequest() already answered 404 for the+// same input; muteUser now matches it.+//+// getThread() — the `before` cursor was resolved with+// `created_at < (select created_at from direct_messages where+// id = $cursor)`, unscoped. Two consequences: a caller could+// page against the timestamp of a message in someone else's+// thread, and an unknown or stale cursor made the comparison+// `created_at < null`, which matches nothing — so the endpoint+// answered "no older messages" instead of admitting the cursor+// was bad, and the client stopped paginating on a lie.+//+// The `sql` tag is faked so the queries and their parameters can be inspected+// directly; the real store code runs.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Each queued entry answers the next query in order; anything past the queue+// resolves empty, which is the "no row" case both fixes hinge on.+const queries = [];+const answers = [];+vi.mock('../api/_lib/db.js', () => ({+ sql: Object.assign(+ vi.fn((strings, ...values) => {+ queries.push({ text: strings.join(' ? '), values });+ return Promise.resolve(answers.length ? answers.shift() : []);+ }),+ { transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const { muteUser, getThread } = await import('../api/_lib/friends-store.js');++const ME = '00000000-0000-0000-0000-0000000000aa';+const OTHER = '00000000-0000-0000-0000-0000000000bb';+const CURSOR = '00000000-0000-0000-0000-0000000000cc';++beforeEach(() => {+ queries.length = 0;+ answers.length = 0;+});++describe('muteUser target validation', () => {+ it('answers 404 for an unknown target instead of letting a foreign key raise a 500', async () => {+ // The existence lookup returns no row.+ await expect(muteUser(ME, OTHER)).rejects.toMatchObject({ status: 404, code: 'not_found' });+ // Nothing was inserted: the lookup is the only query that ran.+ expect(queries).toHaveLength(1);+ expect(queries[0].text).toMatch(/from users/);+ expect(queries.some((q) => /insert into user_mutes/.test(q.text))).toBe(false);+ });++ it('inserts the mute once the target resolves', async () => {+ answers.push([{ id: OTHER }]);+ await expect(muteUser(ME, OTHER)).resolves.toEqual({ ok: true });+ const insert = queries.find((q) => /insert into user_mutes/.test(q.text));+ expect(insert).toBeTruthy();+ expect(insert.values).toEqual([ME, OTHER]);+ // The conflict clause keeps a repeat mute idempotent rather than a 23505.+ expect(insert.text).toMatch(/on conflict/);+ });++ it('still refuses a self-mute before spending a query on it', async () => {+ await expect(muteUser(ME, ME)).rejects.toMatchObject({ status: 400, code: 'self_mute' });+ expect(queries).toHaveLength(0);+ });++ it('does not treat a soft-deleted account as a mutable target', async () => {+ answers.push([]);+ await expect(muteUser(ME, OTHER)).rejects.toMatchObject({ status: 404 });+ expect(queries[0].text).toMatch(/deleted_at is null/);+ });+});++describe('getThread cursor handling', () => {+ it('rejects a cursor that is not part of this thread', async () => {+ // The scoped cursor lookup finds nothing.+ await expect(getThread(ME, OTHER, { beforeId: CURSOR })).rejects.toMatchObject({+ status: 400,+ code: 'bad_cursor',+ });+ // It never went on to fetch a (silently empty) page.+ expect(queries).toHaveLength(1);+ });++ it('scopes the cursor lookup to the pair, so a foreign message id cannot be paged against', async () => {+ answers.push([]);+ await getThread(ME, OTHER, { beforeId: CURSOR }).catch(() => {});+ const lookup = queries[0];+ expect(lookup.text).toMatch(/select created_at from direct_messages/);+ expect(lookup.text).toMatch(/sender_id/);+ expect(lookup.text).toMatch(/recipient_id/);+ // The cursor id AND both sides of the thread are bound into the lookup.+ expect(lookup.values).toEqual([CURSOR, ME, OTHER, OTHER, ME]);+ });++ it('pages on the resolved timestamp when the cursor is valid', async () => {+ const ts = new Date('2026-08-01T00:00:00.000Z');+ answers.push([{ created_at: ts }]);+ answers.push([+ { id: 'm-2', sender_id: OTHER, recipient_id: ME, body: 'older two', created_at: ts, read_at: null },+ { id: 'm-1', sender_id: ME, recipient_id: OTHER, body: 'older one', created_at: ts, read_at: ts },+ ]);+ const out = await getThread(ME, OTHER, { beforeId: CURSOR });+ const page = queries[1];+ // The timestamp is bound as a value; the raw cursor id never reaches the page query.+ expect(page.values).toContain(ts);+ expect(page.values).not.toContain(CURSOR);+ // Rows come back newest-first and are reversed into oldest-to-newest for the UI.+ expect(out.map((m) => m.id)).toEqual(['m-1', 'm-2']);+ expect(out[0]).toMatchObject({ from: ME, to: OTHER, body: 'older one', mine: true, read: true });+ expect(out[1]).toMatchObject({ mine: false, read: false });+ });++ it('runs a single unfiltered query when there is no cursor', async () => {+ answers.push([]);+ await expect(getThread(ME, OTHER)).resolves.toEqual([]);+ expect(queries).toHaveLength(1);+ expect(queries[0].text).not.toMatch(/created_at </);+ });++ it('clamps the page size to the store cap', async () => {+ answers.push([]);+ await getThread(ME, OTHER, { limit: 5000 });+ expect(queries[0].values).toContain(100);+ queries.length = 0;+ answers.push([]);+ await getThread(ME, OTHER, { limit: 0 });+ expect(queries[0].values).toContain(1);+ });+});diff --git a/tests/genome-breed.test.js b/tests/genome-breed.test.jsindex 85d7d8cd1..c16a9ce17 100644--- a/tests/genome-breed.test.js+++ b/tests/genome-breed.test.js@@ -115,8 +115,10 @@ const breed = (body) =>describe('happy path — a real child is born', () => {it('mints a child with fresh wallets distinct from both parents', async () => {- // Queue: replay-check (none), child insert, skill-grant meta update, breeding insert.- state.sqlQueue = [[], [{ id: 'child-agent' }], [], []];+ // Queue: replay-check (none), child insert, skill-grant meta update, breeding+ // insert. The breeding insert RETURNS the recorded row; an empty result there+ // means the breeding key lost a race and the handler retires the child.+ state.sqlQueue = [[], [{ id: 'child-agent' }], [], [{ child_agent_id: 'child-agent' }]];const { status, body } = await breed({ seed: 'deterministic-seed' });expect(status).toBe(201);expect(body.child.id).toBe('child-agent');@@ -131,7 +133,7 @@ describe('happy path — a real child is born', () => {});it('never issues an UPDATE/DELETE against a parent agent row', async () => {- state.sqlQueue = [[], [{ id: 'child-agent' }], [], []];+ state.sqlQueue = [[], [{ id: 'child-agent' }], [], [{ child_agent_id: 'child-agent' }]];await breed({ seed: 's' });const mutatedParent = state.sqlCalls.some((c) => /update|delete/i.test(c.query) && (c.values.includes(A_ID) || c.values.includes(B_ID)),diff --git a/tests/genome-endpoints.test.js b/tests/genome-endpoints.test.jsnew file mode 100644index 000000000..34461b07b--- /dev/null+++ b/tests/genome-endpoints.test.js@@ -0,0 +1,400 @@+// Agent Genome read/marketplace endpoints: preview, lineage, stud, edges.+// breed.js has its own suite (genome-breed.test.js); these pin the rest of the+// surface: preview determinism + fee disclosure, the lineage tree + the public+// anti-forgery verify path, stud PATCH semantics + fee clamping + rarest-first+// listing, and the star-map edge feed. DB + auth are mocked at the module+// boundary so the tests pin handler decisions, not infrastructure.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { invoke } from './_helpers/monetization.js';++const A_ID = '11111111-1111-4111-8111-111111111111';+const B_ID = '22222222-2222-4222-8222-222222222222';+const C_ID = '33333333-3333-4333-8333-333333333333';+const CALLER = 'user-caller';+const OTHER = 'user-other';++const state = {+ session: { id: CALLER },+ rows: {},+ sqlQueue: [],+ sqlCalls: [],+};++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => state.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+ hasScope: vi.fn(() => true),+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => ({ success: true })),+ authedReadIp: vi.fn(async () => ({ success: true })),+ genomeStudWrite: vi.fn(async () => ({ success: true })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {+ const query = Array.isArray(strings) ? strings.join('?') : String(strings);+ state.sqlCalls.push({ query, values });+ return state.sqlQueue.length ? state.sqlQueue.shift() : [];+ });+ sql.transaction = (qs) => Promise.all(qs);+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++// Partial mock: keep the pure eligibility/policy/genome logic real, override+// the DB-touching loader preview.js uses.+vi.mock('../api/_lib/genome-agent.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ loadBreedingAgent: vi.fn(async (id) => state.rows[id] || null),+ };+});++const { default: previewHandler } = await import('../api/genome/preview.js');+const { default: lineageHandler } = await import('../api/genome/lineage.js');+const { default: studHandler } = await import('../api/genome/stud.js');+const { default: edgesHandler } = await import('../api/genome/edges.js');+const { genomeFromAgent, deriveGenome } = await import('../api/_lib/genome.js');++function parentRow(id, ownerId, over = {}) {+ return {+ id,+ user_id: ownerId,+ name: `Parent ${id.slice(0, 4)}`,+ is_public: true,+ meta: { solana_address: `Sol-${id}`, ...(over.meta || {}) },+ skills: over.skills || ['trading'],+ persona_tone_tags: ['precise'],+ voice_provider: 'elevenlabs',+ voice_id: `voice-${id}`,+ voice_model: 'eleven_flash_v2_5',+ voice_settings: { stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true },+ avatar_id: null,+ avatar_storage_key: null,+ avatar_appearance: { morphs: { headScale: 0.8 }, colors: { hair: '#aa3311' } },+ ...over,+ };+}++const founder = (id) =>+ genomeFromAgent({+ id,+ persona_tone_tags: ['precise'],+ voice_provider: 'elevenlabs',+ voice_id: `voice-${id}`,+ voice_settings: { stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true },+ appearance: { morphs: { headScale: 0.8 }, colors: { hair: '#aa3311' } },+ skills: ['trading'],+ avatar_id: null,+ meta: {},+ });++// One tree-node row as loadNodes() selects it.+function nodeRow(id, over = {}) {+ return {+ id,+ name: `Agent ${id.slice(0, 4)}`,+ is_public: true,+ user_id: CALLER,+ avatar_id: null,+ meta: {},+ avatar_thumbnail_key: null,+ ...over,+ };+}++beforeEach(() => {+ state.session = { id: CALLER };+ state.rows = { [A_ID]: parentRow(A_ID, CALLER), [B_ID]: parentRow(B_ID, CALLER) };+ state.sqlQueue = [];+ state.sqlCalls = [];+});++const preview = (body) =>+ invoke(previewHandler, { method: 'POST', url: '/api/genome/preview', body: { parent_a: A_ID, parent_b: B_ID, ...body } });++describe('preview', () => {+ it('401s without a session or bearer', async () => {+ state.session = null;+ const { status, body } = await preview({});+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ });++ it('rejects an agent previewing against itself', async () => {+ const { status, body } = await invoke(previewHandler, {+ method: 'POST',+ url: '/api/genome/preview',+ body: { parent_a: A_ID, parent_b: A_ID },+ });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('404s when a parent does not exist', async () => {+ delete state.rows[B_ID];+ const { status } = await preview({});+ expect(status).toBe(404);+ });++ it('is deterministic: same seed previews the identical child, seed echoed', async () => {+ const one = await preview({ seed: 'preview-seed' });+ const two = await preview({ seed: 'preview-seed' });+ expect(one.status).toBe(200);+ expect(one.body.seed).toBe('preview-seed');+ expect(JSON.stringify(one.body.genome)).toBe(JSON.stringify(two.body.genome));+ expect(one.body.genome.generation).toBe(1);+ expect(one.body.stud_fee_three).toBe(0);+ expect(one.body.consent_required).toBe(false);+ });++ it('discloses the $THREE stud fee and consent for a cross-owner stud', async () => {+ state.rows[B_ID] = parentRow(B_ID, OTHER, {+ meta: { genome_breeding: { stud: true, stud_fee_three: 25 }, solana_address: `Sol-${B_ID}` },+ });+ const { status, body } = await preview({ seed: 's' });+ expect(status).toBe(200);+ expect(body.stud_fee_three).toBe(25);+ expect(body.consent_required).toBe(true);+ expect(body.parents.b.cross_owner).toBe(true);+ });+});++describe('lineage', () => {+ it('400s on a missing or malformed agentId', async () => {+ const bare = await invoke(lineageHandler, { method: 'GET', url: '/api/genome/lineage' });+ expect(bare.status).toBe(400);+ const junk = await invoke(lineageHandler, { method: 'GET', url: '/api/genome/lineage?agentId=not-a-uuid' });+ expect(junk.status).toBe(400);+ });++ it('404s for an unknown agent', async () => {+ state.sqlQueue = [[]];+ const { status } = await invoke(lineageHandler, { method: 'GET', url: `/api/genome/lineage?agentId=${C_ID}` });+ expect(status).toBe(404);+ });++ it('renders the full tree: parents, ancestors, bred flag, private masking', async () => {+ const genomeA = founder(A_ID);+ const genomeB = founder(B_ID);+ const child = deriveGenome({ parentA: genomeA, parentB: genomeB, seed: 'real' });+ const childRow = nodeRow(C_ID, { meta: { genome: child, bred_from: { seed: 'real' } } });+ const birth = {+ parent_a_agent_id: A_ID,+ parent_b_agent_id: B_ID,+ seed: 'real',+ genome_hash: child.genome_hash,+ generation: 1,+ pedigree_tier: 'common',+ created_at: '2026-08-01T00:00:00Z',+ };+ const parentsBatch = [nodeRow(A_ID), nodeRow(B_ID, { is_public: false })];+ state.sqlQueue = [+ [childRow], // loadNode+ [birth], // birth record+ [], // children+ parentsBatch, // parents + co-parents batch+ [{ child_agent_id: C_ID, parent_a_agent_id: A_ID, parent_b_agent_id: B_ID }], // ancestor walk depth 1+ parentsBatch, // ancestor nodes depth 1+ [], // ancestor walk depth 2 terminates+ ];+ const { status, body } = await invoke(lineageHandler, { method: 'GET', url: `/api/genome/lineage?agentId=${C_ID}` });+ expect(status).toBe(200);+ expect(body.bred).toBe(true);+ expect(body.seed).toBe('real');+ expect(body.agent.generation).toBe(1);+ expect(body.parents.map((p) => p.id).sort()).toEqual([A_ID, B_ID]);+ expect(body.children).toEqual([]);+ expect(body.ancestors).toHaveLength(2);+ expect(body.ancestors.every((a) => a.depth === 1 && a.of === C_ID)).toBe(true);+ // A private parent reveals only that it exists.+ expect(body.parents.find((p) => p.id === B_ID).name).toBe('Private agent');+ });++ it('verify=1 confirms a genuinely derived child', async () => {+ const genomeA = founder(A_ID);+ const genomeB = founder(B_ID);+ const child = deriveGenome({ parentA: genomeA, parentB: genomeB, seed: 'real' });+ state.sqlQueue = [+ [nodeRow(C_ID, { meta: { genome: child, bred_from: { seed: 'real' } } })], // loadNode gate+ [+ {+ id: C_ID,+ name: 'Child',+ meta: {+ genome: child,+ bred_from: {+ seed: 'real',+ parent_a: { agent_id: A_ID, name: 'A', genome: genomeA },+ parent_b: { agent_id: B_ID, name: 'B', genome: genomeB },+ },+ },+ seed: 'real',+ genome_hash: child.genome_hash,+ },+ ],+ ];+ const { status, body } = await invoke(lineageHandler, {+ method: 'GET',+ url: `/api/genome/lineage?agentId=${C_ID}&verify=1`,+ });+ expect(status).toBe(200);+ expect(body.verifiable).toBe(true);+ expect(body.valid).toBe(true);+ expect(body.genome_hash).toBe(child.genome_hash);+ });++ it('verify=1 flags a forged child whose genome was not derived from its claimed parents', async () => {+ const genomeA = founder(A_ID);+ const genomeB = founder(B_ID);+ const child = deriveGenome({ parentA: genomeA, parentB: genomeB, seed: 'real' });+ const forged = { ...child, brain: { ...child.brain, boldness: 0.999 } };+ state.sqlQueue = [+ [nodeRow(C_ID, { meta: { genome: forged, bred_from: { seed: 'real' } } })], // loadNode gate+ [+ {+ id: C_ID,+ name: 'Forged',+ meta: {+ genome: forged,+ bred_from: {+ seed: 'real',+ parent_a: { agent_id: A_ID, name: 'A', genome: genomeA },+ parent_b: { agent_id: B_ID, name: 'B', genome: genomeB },+ },+ },+ seed: 'real',+ genome_hash: child.genome_hash,+ },+ ],+ ];+ const { body } = await invoke(lineageHandler, {+ method: 'GET',+ url: `/api/genome/lineage?agentId=${C_ID}&verify=1`,+ });+ expect(body.verifiable).toBe(true);+ expect(body.valid).toBe(false);+ });++ it('verify=0 is an explicit off switch, not a truthy string', async () => {+ state.sqlQueue = [[nodeRow(C_ID)], [], [], []];+ const { body } = await invoke(lineageHandler, {+ method: 'GET',+ url: `/api/genome/lineage?agentId=${C_ID}&verify=0`,+ });+ // The tree shape, not the verify shape.+ expect(body.verifiable).toBeUndefined();+ expect(body.agent.id).toBe(C_ID);+ });+});++describe('stud marketplace', () => {+ it('GET lists studs rarest-first and clamps a junk fee to 0', async () => {+ const genomeA = founder(A_ID);+ const genomeB = founder(B_ID);+ const deep = deriveGenome({ parentA: genomeA, parentB: genomeB, seed: 'deep' });+ state.sqlQueue = [+ [+ // Shallow founder listed first in the DB order to prove re-sorting.+ { id: A_ID, name: 'Founder', avatar_id: null, meta: { genome_breeding: { stud: true, stud_fee_three: -3 } }, skills: ['trading'], avatar_thumbnail_key: null },+ { id: C_ID, name: 'Deep', avatar_id: null, meta: { genome: deep, genome_breeding: { stud: true, stud_fee_three: 10 } }, skills: [], avatar_thumbnail_key: null },+ ],+ ];+ const { status, body } = await invoke(studHandler, { method: 'GET', url: '/api/genome/stud?limit=5' });+ expect(status).toBe(200);+ expect(body.studs).toHaveLength(2);+ expect(body.studs[0].id).toBe(C_ID);+ expect(body.studs[0].generation).toBe(1);+ expect(body.studs[0].pedigree.score).toBeGreaterThan(body.studs[1].pedigree.score);+ expect(body.studs.find((s) => s.id === A_ID).stud_fee_three).toBe(0);+ });++ it('POST 401s without a session', async () => {+ state.session = null;+ const { status } = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: A_ID, stud: true },+ });+ expect(status).toBe(401);+ });++ it('POST 400s on a malformed agent_id', async () => {+ const { status, body } = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: 'nope', stud: true },+ });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('POST 403s when the caller does not own the agent', async () => {+ state.sqlQueue = [[{ id: A_ID, user_id: OTHER, meta: {} }]];+ const { status, body } = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: A_ID, stud: true },+ });+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ });++ it('POST patches only the supplied fields: a fee-only body keeps stud + breedable', async () => {+ state.sqlQueue = [+ [{ id: A_ID, user_id: CALLER, meta: { genome_breeding: { breedable: false, stud: true, stud_fee_three: 40 } } }],+ [], // update+ ];+ const { status, body } = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: A_ID, stud_fee_three: 10 },+ });+ expect(status).toBe(200);+ expect(body.genome_breeding).toEqual({ breedable: false, stud: true, stud_fee_three: 10 });+ });++ it('POST clamps the fee into [0, 1000000] $THREE', async () => {+ state.sqlQueue = [[{ id: A_ID, user_id: CALLER, meta: {} }], []];+ const low = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: A_ID, stud_fee_three: -5 },+ });+ expect(low.body.genome_breeding.stud_fee_three).toBe(0);+ state.sqlQueue = [[{ id: A_ID, user_id: CALLER, meta: {} }], []];+ const high = await invoke(studHandler, {+ method: 'POST',+ url: '/api/genome/stud',+ body: { agent_id: A_ID, stud_fee_three: 9e9 },+ });+ expect(high.body.genome_breeding.stud_fee_three).toBe(1_000_000);+ });+});++describe('edges', () => {+ it('maps breeding rows into star-map edges with a public cache header', async () => {+ state.sqlQueue = [+ [+ { parent_a_agent_id: A_ID, parent_b_agent_id: B_ID, child_agent_id: C_ID, generation: 1, pedigree_tier: 'common' },+ ],+ ];+ const { status, body, res } = await invoke(edgesHandler, { method: 'GET', url: '/api/genome/edges?limit=5' });+ expect(status).toBe(200);+ expect(body.edges).toEqual([{ a: A_ID, b: B_ID, child: C_ID, generation: 1, tier: 'common' }]);+ expect(res.headers['cache-control']).toContain('s-maxage=60');+ });++ it('rejects non-GET methods', async () => {+ const { status } = await invoke(edgesHandler, { method: 'POST', url: '/api/genome/edges' });+ expect(status).toBe(405);+ });+});diff --git a/tests/launch-mm-endpoint.test.js b/tests/launch-mm-endpoint.test.jsnew file mode 100644index 000000000..50fee5254--- /dev/null+++ b/tests/launch-mm-endpoint.test.js@@ -0,0 +1,427 @@+/**+ * Launch Copilot market-maker endpoint (api/launch/mm.js).+ *+ * Covers the HTTP surface itself rather than the rulebook (tests/market-maker.js+ * owns the policy math): what each verb validates, who it lets through, which+ * status a malformed request earns, and the SSE stream's teardown. The database+ * layer is driven through a queue of rows so the real handler and the real+ * api/_lib/market-maker.js queries run end to end.+ *+ * The stream case is the load-bearing one: a client that hangs up while the seed+ * query is still in flight must leave nothing armed behind it. Before the close+ * listener was attached ahead of that await, the hang-up fired with no listener+ * registered and the poller kept querying a dead socket for the full ten-minute+ * stream budget.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: () => null,+}));++const requireCsrfMock = vi.fn(async () => true);+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ clientIp: () => '203.0.113.9',+ limits: {+ publicIp: async () => ({ success: true }),+ authIp: async () => ({ success: true }),+ walletRead: async () => ({ success: true }),+ mcpIp: async () => ({ success: true }),+ },+}));++vi.mock('../api/_lib/env.js', () => ({+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },+}));++const { default: mmHandler } = await import('../api/launch/mm.js');+const { SOL } = await import('../api/_lib/market-maker.js');++const MINT = 'THREEagentmint11111111111111111111111111111';+const AGENT = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';+const OWNER = 'user-owner';++function mkReq({ method = 'GET', url = '/api/launch/mm', headers = {}, body = null } = {}) {+ const hdrs = { host: 'three.ws', ...headers };+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';+ const listeners = new Map();+ return {+ method, url, headers: hdrs, destroyed: false,+ on(event, cb) {+ listeners.set(event, cb);+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => { cb(buf); listeners.get('end')?.(); });+ }+ return this;+ },+ emitClose() { this.destroyed = true; listeners.get('close')?.(); },+ destroy() { this.destroyed = true; },+ };+}++function mkRes() {+ return {+ statusCode: 200, headers: {}, body: undefined, chunks: [],+ headersSent: false, writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ writeHead(status, headers = {}) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers)) this.setHeader(k, v);+ this.headersSent = true;+ return this;+ },+ flushHeaders() {},+ write(chunk) { this.chunks.push(String(chunk)); return true; },+ end(b) { if (b != null) this.body = b; this.headersSent = true; this.writableEnded = true; },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++function policyRow(over = {}) {+ const now = new Date('2026-08-13T00:00:00.000Z');+ return {+ id: 'policy-1', mint: MINT, network: 'mainnet', agent_id: AGENT, user_id: OWNER,+ enabled: true, mode: 'live', preset: 'balanced', status: 'active', kill_switch: false,+ floor_price_sol: 0.0001, floor_band_pct: 5, take_profit_band_pct: 25, recycle_pct: 20,+ max_inventory_tokens: 0, graduation_action: 'provide_lp', graduation_status: null,+ graduation_signature: null, slippage_bps: 500, max_price_impact_pct: 8,+ min_action_interval_seconds: 60, max_volume_pct: 15,+ dip_buy_budget_lamports: String(SOL), daily_budget_lamports: String(2 * SOL),+ seed_lamports: '0', seed_done_at: null,+ realized_pnl_lamports: '0', sol_deployed_lamports: '0', sol_recovered_lamports: '0',+ inventory_tokens: 0, inventory_value_lamports: null, last_price_sol: null,+ last_action_at: null, last_action_side: null, last_eval_at: null, last_error: null,+ created_at: now, updated_at: now,+ ...over,+ };+}++const launchRow = { agent_id: AGENT, user_id: OWNER, name: 'Three', symbol: 'THREE', network: 'mainnet' };++let sqlQueue = [];+beforeEach(() => {+ sqlQueue = [];+ sqlMock.mockReset().mockImplementation(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []));+ getSessionUserMock.mockReset().mockResolvedValue(null);+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ requireCsrfMock.mockClear().mockResolvedValue(true);+});+afterEach(() => { vi.useRealTimers(); });++describe('GET /api/launch/mm: public policy read', () => {+ it('refuses a request with no mint, before touching the database', async () => {+ const res = mkRes();+ await mmHandler(mkReq({ url: '/api/launch/mm' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_mint');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('refuses a mint that is not base58 in the right length band', async () => {+ const res = mkRes();+ await mmHandler(mkReq({ url: '/api/launch/mm?mint=not-a-mint' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_mint');+ });++ it('answers a coin with no maker attached with the preset catalog, not a 404', async () => {+ sqlQueue = [[]];+ const res = mkRes();+ await mmHandler(mkReq({ url: `/api/launch/mm?mint=${MINT}` }), res);+ expect(res.statusCode).toBe(200);+ const { data } = parse(res);+ expect(data.policy).toBeNull();+ expect(data.owned).toBe(false);+ expect(data.presets.length).toBeGreaterThan(0);+ expect(data.guards.max_volume_pct_ceiling).toBeGreaterThan(0);+ });++ it('never exposes the owning user id on the public view', async () => {+ sqlQueue = [[policyRow()]];+ const res = mkRes();+ await mmHandler(mkReq({ url: `/api/launch/mm?mint=${MINT}` }), res);+ expect(res.statusCode).toBe(200);+ const { data } = parse(res);+ expect(data.policy.id).toBe('policy-1');+ expect(data.policy.user_id).toBeUndefined();+ expect(data.owned).toBe(false);+ });++ it('reports state=1 budgets against the 24h spend ledger and the engine heartbeat', async () => {+ const beat = new Date(Date.now() - 10_000).toISOString();+ sqlQueue = [+ [policyRow()], // getPolicyByMint+ [], // listActions+ [{ s: String(0.5 * SOL) }], // getDeployedLamports24h+ [{ s: String(0.25 * SOL) }], // getDefenseLamports24h+ [{ mode: 'live', last_beat_at: beat }], // getEngineLiveness+ ];+ const res = mkRes();+ await mmHandler(mkReq({ url: `/api/launch/mm?mint=${MINT}&state=1` }), res);+ expect(res.statusCode).toBe(200);+ const { data } = parse(res);+ expect(data.budget.daily_spent_sol).toBe(0.5);+ expect(data.budget.daily_remaining_sol).toBe(1.5);+ expect(data.budget.dip_spent_sol).toBe(0.25);+ expect(data.budget.dip_remaining_sol).toBe(0.75);+ expect(data.engine.live).toBe(true);+ expect(data.actions).toEqual([]);+ });++ it('marks the launch owner as owned so the dashboard can offer the controls', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[policyRow()], [launchRow]];+ const res = mkRes();+ await mmHandler(mkReq({ url: `/api/launch/mm?mint=${MINT}` }), res);+ expect(parse(res).data.owned).toBe(true);+ });+});++describe('GET /api/launch/mm?owner=1', () => {+ it('refuses an anonymous caller', async () => {+ const res = mkRes();+ await mmHandler(mkReq({ url: '/api/launch/mm?owner=1' }), res);+ expect(res.statusCode).toBe(401);+ expect(parse(res).error).toBe('unauthorized');+ });++ it('lists only the caller’s own policies', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[policyRow()]];+ const res = mkRes();+ await mmHandler(mkReq({ url: '/api/launch/mm?owner=1' }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).data.policies).toHaveLength(1);+ });+});++describe('POST /api/launch/mm', () => {+ const postReq = (over = {}) => mkReq({ method: 'POST', url: `/api/launch/mm?mint=${MINT}`, body: {}, ...over });++ it('refuses an anonymous caller', async () => {+ const res = mkRes();+ await mmHandler(postReq(), res);+ expect(res.statusCode).toBe(401);+ });++ it('answers a non-JSON body with 415, not a generic 400', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ const res = mkRes();+ await mmHandler(postReq({ headers: { 'content-type': 'application/x-www-form-urlencoded' } }), res);+ expect(res.statusCode).toBe(415);+ expect(parse(res).error_description).toMatch(/application\/json/);+ });++ it('refuses a caller who did not launch the coin here', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'someone-else' });+ sqlQueue = [[], []]; // no owned launch, no existing policy+ const res = mkRes();+ await mmHandler(postReq({ body: { preset: 'balanced', floor_price_sol: 0.0001 } }), res);+ expect(res.statusCode).toBe(403);+ expect(parse(res).error).toBe('forbidden');+ expect(requireCsrfMock).not.toHaveBeenCalled();+ });++ it('rejects an unknown lifecycle action', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ const res = mkRes();+ await mmHandler(postReq({ url: `/api/launch/mm?mint=${MINT}&action=frobnicate` }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_action');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('404s a pause on a coin with no maker instead of creating one', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[launchRow], []]; // owns the launch, no policy yet+ const res = mkRes();+ await mmHandler(postReq({ url: `/api/launch/mm?mint=${MINT}&action=pause` }), res);+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('no_policy');+ // The upsert must never have run: no INSERT, only the two lookups.+ expect(sqlMock).toHaveBeenCalledTimes(2);+ });++ it('creates a policy for the launch owner and answers 201', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[launchRow], [], [], [policyRow({ enabled: false, status: 'idle', mode: 'simulate' })]];+ const res = mkRes();+ await mmHandler(postReq({ body: { preset: 'balanced', floor_price_sol: 0.0001 } }), res);+ expect(res.statusCode).toBe(201);+ expect(parse(res).data.policy.mint).toBe(MINT);+ expect(requireCsrfMock).toHaveBeenCalled();+ });++ it('surfaces a guard refusal as its own status and code, not a 500', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[launchRow], []];+ const res = mkRes();+ await mmHandler(postReq({ body: { floor_price_sol: 0.0001, min_action_interval_seconds: 1 } }), res);+ expect(res.statusCode).toBe(422);+ expect(parse(res).error).toBe('manipulation_guard');+ });++ it('pauses an existing maker without arming anything new', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [+ [launchRow], [policyRow()],+ [policyRow()], [policyRow({ enabled: false, status: 'paused' })],+ ];+ const res = mkRes();+ await mmHandler(postReq({ url: `/api/launch/mm?mint=${MINT}&action=pause` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).data.policy.enabled).toBe(false);+ expect(parse(res).data.policy.status).toBe('paused');+ });++ it('routes a kill to the agent wallet’s audited withdraw flow', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [+ [launchRow], [policyRow()],+ [policyRow()], [policyRow({ enabled: false, kill_switch: true, status: 'killed' })],+ ];+ const res = mkRes();+ await mmHandler(postReq({ url: `/api/launch/mm?mint=${MINT}&action=kill` }), res);+ expect(res.statusCode).toBe(200);+ const { data } = parse(res);+ expect(data.policy.kill_switch).toBe(true);+ expect(data.withdraw_url).toBe(`/agent/${AGENT}/wallet#withdraw`);+ });+});++describe('DELETE /api/launch/mm', () => {+ const delReq = (over = {}) => mkReq({ method: 'DELETE', url: `/api/launch/mm?mint=${MINT}`, ...over });++ it('refuses an anonymous caller', async () => {+ const res = mkRes();+ await mmHandler(delReq(), res);+ expect(res.statusCode).toBe(401);+ });++ it('is idempotent when nothing is attached', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[]];+ const res = mkRes();+ await mmHandler(delReq(), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).data.removed).toBe(false);+ });++ it('refuses a caller who does not own the policy', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'someone-else' });+ sqlQueue = [[policyRow()]];+ const res = mkRes();+ await mmHandler(delReq(), res);+ expect(res.statusCode).toBe(403);+ expect(requireCsrfMock).not.toHaveBeenCalled();+ });++ it('removes the owner’s policy and points them at the wallet', async () => {+ getSessionUserMock.mockResolvedValue({ id: OWNER });+ sqlQueue = [[policyRow()], []];+ const res = mkRes();+ await mmHandler(delReq(), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).data.removed).toBe(true);+ expect(parse(res).data.withdraw_url).toBe(`/agent/${AGENT}/wallet#withdraw`);+ });+});++describe('GET /api/launch/mm?stream=1: SSE feed', () => {+ it('404s a stream for a coin with no maker attached', async () => {+ sqlQueue = [[]];+ const res = mkRes();+ await mmHandler(mkReq({ url: `/api/launch/mm?stream=1&mint=${MINT}` }), res);+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('not_found');+ });++ it('opens with the seeded action history in chronological order', async () => {+ const now = new Date('2026-08-13T00:00:00.000Z');+ sqlQueue = [+ [policyRow()],+ [+ { id: 2, kind: 'defend_buy', side: 'buy', status: 'executed', sol_lamports: String(SOL / 2), created_at: now },+ { id: 1, kind: 'skip', side: null, status: 'skipped', sol_lamports: null, created_at: now },+ ],+ ];+ const req = mkReq({ url: `/api/launch/mm?stream=1&mint=${MINT}` });+ const res = mkRes();+ const running = mmHandler(req, res);+ for (let i = 0; i < 30 && !res.chunks.length; i++) await Promise.resolve();+ req.emitClose();+ await running;+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toMatch(/text\/event-stream/);+ const open = JSON.parse(res.chunks[0].match(/^event: open\ndata: (.*)\n\n$/)[1]);+ expect(open.actions.map((a) => a.id)).toEqual([1, 2]);+ expect(open.actions[1].sol).toBe(0.5);+ });++ it('answers a HEAD probe with the stream headers and no open socket', async () => {+ sqlQueue = [[policyRow()]];+ const res = mkRes();+ await mmHandler(mkReq({ method: 'HEAD', url: `/api/launch/mm?stream=1&mint=${MINT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toMatch(/text\/event-stream/);+ expect(res.writableEnded).toBe(true);+ expect(res.chunks).toEqual([]);+ });++ it('leaves no timer armed when the client hangs up during the seed query', async () => {+ vi.useFakeTimers();+ let releaseSeed;+ sqlMock.mockReset()+ .mockImplementationOnce(() => Promise.resolve([policyRow()]))+ .mockImplementationOnce(() => new Promise((resolve) => { releaseSeed = () => resolve([]); }));++ const req = mkReq({ url: `/api/launch/mm?stream=1&mint=${MINT}` });+ const res = mkRes();+ const running = mmHandler(req, res);+ for (let i = 0; i < 30 && !res.headersSent; i++) await Promise.resolve();+ expect(res.headersSent).toBe(true);++ req.emitClose(); // the client gives up while the seed query is still open+ releaseSeed(); // ...and only then does the database answer+ await running;++ expect(res.writableEnded).toBe(true);+ expect(res.chunks).toEqual([]);+ // No poll, no ping, no duration timer: an abandoned stream must not keep+ // querying for the rest of its ten-minute budget.+ expect(vi.getTimerCount()).toBe(0);+ });+});++describe('method handling', () => {+ it('answers a CORS preflight without running a branch', async () => {+ const res = mkRes();+ await mmHandler(mkReq({ method: 'OPTIONS', headers: { origin: 'https://three.ws' } }), res);+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-methods']).toBe('GET,POST,DELETE,OPTIONS');+ });++ it('answers an unsupported verb with 405 and an Allow header', async () => {+ const res = mkRes();+ await mmHandler(mkReq({ method: 'PUT', url: `/api/launch/mm?mint=${MINT}` }), res);+ expect(res.statusCode).toBe(405);+ expect(String(res.headers.allow)).toContain('DELETE');+ });+});diff --git a/tests/launcher-trends-endpoint.test.js b/tests/launcher-trends-endpoint.test.jsindex 82bf747ce..ee691d4b0 100644--- a/tests/launcher-trends-endpoint.test.js+++ b/tests/launcher-trends-endpoint.test.js@@ -38,6 +38,7 @@ vi.mock('../api/_lib/db.js', () => ({import handler from '../api/launcher/trends.js';import { rankNarratives } from '../api/_lib/launcher-trends.js';+import { cacheGet, cacheSet } from '../api/_lib/cache.js';function fakeRes() { return { setHeader() {}, end() {}, statusCode: 200 }; }@@ -81,4 +82,26 @@ describe('GET /api/launcher/trends', () => {expect.objectContaining({ sources: undefined }),);});++ // A provider sweep that fails must degrade to "no narratives right now", and it+ // must NOT be cached: a frozen empty ranking would be served to every polling+ // agent for a full minute as if it were the real state of the world.+ it('degrades to an empty ranking when every provider fails, and never caches it', async () => {+ rankNarratives.mockRejectedValueOnce(new Error('all providers down'));+ cacheSet.mockClear();+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends?launches=0', headers: {} }, res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.narratives).toMatchObject({ count: 0, top: null, terms: [] });+ expect(cacheSet).not.toHaveBeenCalled();+ });++ it('serves a cache hit without re-ranking the providers', async () => {+ cacheGet.mockResolvedValueOnce({ network: 'mainnet', cached: true });+ rankNarratives.mockClear();+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends', headers: {} }, res);+ expect(res._json.body).toEqual({ network: 'mainnet', cached: true });+ expect(rankNarratives).not.toHaveBeenCalled();+ });});diff --git a/tests/memory-endpoints.test.js b/tests/memory-endpoints.test.jsindex d609f2d6c..a1a2138f2 100644--- a/tests/memory-endpoints.test.js+++ b/tests/memory-endpoints.test.js@@ -19,6 +19,9 @@ const searchMemories = vi.fn();const computeContext = vi.fn();const buildGraph = vi.fn();const memoriesForEntity = vi.fn();+// Mirrors the real api/_lib/memory-store.js export surface. MEMORY_TYPES in+// particular has to be here: search.js validates `type` against it, so leaving+// it out turns a 400 path into a TypeError that only fires under test.vi.mock('../api/_lib/memory-store.js', () => ({searchMemories: (...a) => searchMemories(...a),computeContext: (...a) => computeContext(...a),@@ -26,12 +29,22 @@ vi.mock('../api/_lib/memory-store.js', () => ({memoriesForEntity: (...a) => memoriesForEntity(...a),decorateMemory: (row) => ({ id: row.id, tier: row.tier, pinned: row.pinned }),MEMORY_TIERS: ['working', 'recall', 'archival'],+ MEMORY_TYPES: ['user', 'feedback', 'project', 'reference'],WORKING_TOKEN_BUDGET: 2000,}));const { default: searchHandler } = await import('../api/memory/search.js');const { default: curateHandler } = await import('../api/memory/curate.js');const { default: graphHandler } = await import('../api/memory/graph.js');+const { default: contextHandler } = await import('../api/memory/context.js');++// agent_identities.id, agent_memories.id and the entity ids are all uuid+// columns, and every handler rejects anything else up front. Use real uuids so+// these tests exercise the same path production does.+const AGENT = '11111111-1111-4111-8111-111111111111';+const MEM = '22222222-2222-4222-8222-222222222222';+const MEM_2 = '33333333-3333-4333-8333-333333333333';+const ENTITY = '44444444-4444-4444-8444-444444444444';function mkReq({ method = 'GET', url = '/api/memory/search', headers = {}, body = null } = {}) {return {@@ -53,6 +66,7 @@ function mkRes() {};}const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);+const post = (body) => mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body });let sqlQueue = [];beforeEach(() => {@@ -62,7 +76,7 @@ beforeEach(() => {authenticateBearerMock.mockReset().mockResolvedValue(null);extractBearerMock.mockReset().mockReturnValue(null);searchMemories.mockReset().mockResolvedValue({ results: [], provider: true, scored: 0 });- computeContext.mockReset();+ computeContext.mockReset().mockResolvedValue({ entries: [], tokens: 0, budget: 2000, overBudget: false, counts: {} });buildGraph.mockReset().mockResolvedValue({ nodes: [], edges: [], stats: { entities: 0, edges: 0 } });memoriesForEntity.mockReset().mockResolvedValue([]);});@@ -70,7 +84,7 @@ beforeEach(() => {describe('GET /api/memory/search', () => {it('anonymous → empty results, never searches', async () => {const res = mkRes();- await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=hi' }), res);+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&q=hi` }), res);expect(res.statusCode).toBe(200);expect(parse(res)).toEqual({ results: [] });expect(searchMemories).not.toHaveBeenCalled();@@ -82,73 +96,197 @@ describe('GET /api/memory/search', () => {expect(res.statusCode).toBe(400);});+ // A non-uuid agentId used to reach Postgres and come back as a 22P02 500.+ it('400 on a non-uuid agentId, before any query runs', async () => {+ const res = mkRes();+ await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=hi' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/uuid/);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('400 on an unknown tier rather than silently searching nothing', async () => {+ const res = mkRes();+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&tier=working,bogus` }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toContain('bogus');+ });++ it('400 on an unknown type', async () => {+ const res = mkRes();+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&type=nope` }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toContain('nope');+ });+it('owner GET searches and returns results', async () => {getSessionUserMock.mockResolvedValue({ id: 'u1' });sqlQueue.push([{ user_id: 'u1' }]); // ownership- searchMemories.mockResolvedValue({ results: [{ id: 'm1', match: 'semantic' }], provider: true, scored: 1 });+ searchMemories.mockResolvedValue({ results: [{ id: MEM, match: 'semantic' }], provider: true, scored: 1 });const res = mkRes();- await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=sell' }), res);+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&q=sell` }), res);expect(res.statusCode).toBe(200);expect(parse(res).results).toHaveLength(1);- expect(searchMemories).toHaveBeenCalledWith('a1', 'sell', expect.any(Object));+ expect(searchMemories).toHaveBeenCalledWith(AGENT, 'sell', expect.any(Object));+ });++ it('clamps topK and minScore into range', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&q=x&topK=9999&minScore=-3` }), res);+ expect(searchMemories).toHaveBeenCalledWith(AGENT, 'x', expect.objectContaining({ topK: 50, minScore: 0 }));});it('non-owner GET → empty', async () => {getSessionUserMock.mockResolvedValue({ id: 'u1' });sqlQueue.push([{ user_id: 'someone-else' }]);const res = mkRes();- await searchHandler(mkReq({ url: '/api/memory/search?agentId=a1&q=x' }), res);+ await searchHandler(mkReq({ url: `/api/memory/search?agentId=${AGENT}&q=x` }), res);expect(parse(res)).toEqual({ results: [] });});});+describe('POST /api/memory/search', () => {+ it('401 without auth', async () => {+ const res = mkRes();+ await searchHandler(post({ agentId: AGENT, query: 'x' }), res);+ expect(res.statusCode).toBe(401);+ });++ it('403 when not the owner', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlQueue.push([{ user_id: 'other' }]);+ const res = mkRes();+ await searchHandler(post({ agentId: AGENT, query: 'x' }), res);+ expect(res.statusCode).toBe(403);+ });++ it('owner POST searches with an array of tiers', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await searchHandler(post({ agentId: AGENT, query: 'sell', tiers: ['working', 'recall'] }), res);+ expect(res.statusCode).toBe(200);+ expect(searchMemories).toHaveBeenCalledWith(AGENT, 'sell', expect.objectContaining({ tiers: ['working', 'recall'] }));+ });+});+describe('POST /api/memory/curate', () => {beforeEach(() => getSessionUserMock.mockResolvedValue({ id: 'u1' }));it('401 without auth', async () => {getSessionUserMock.mockResolvedValue(null);const res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: MEM }), res);expect(res.statusCode).toBe(401);});it('403 when not owner', async () => {sqlQueue.push([{ user_id: 'other' }]);const res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: MEM }), res);expect(res.statusCode).toBe(403);});+ it('404 when the agent does not exist', async () => {+ sqlQueue.push([]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: MEM }), res);+ expect(res.statusCode).toBe(404);+ });++ it('400 on a non-uuid memoryId, before any write runs', async () => {+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: 'not-a-uuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/uuid/);+ expect(sqlMock).toHaveBeenCalledTimes(1); // the ownership lookup only+ });++ it('400 on an unknown op', async () => {+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'obliterate', memoryId: MEM }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toContain('obliterate');+ });+it('pin updates the memory and returns the entry', async () => {sqlQueue.push([{ user_id: 'u1' }]); // ownership- sqlQueue.push([{ id: 'm1', tier: 'working', pinned: true }]); // update+ sqlQueue.push([{ id: MEM, tier: 'working', pinned: true }]); // updateconst res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'pin', memoryId: 'm1' } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: MEM }), res);expect(res.statusCode).toBe(200);- expect(parse(res).entry).toMatchObject({ id: 'm1', pinned: true });+ expect(parse(res).entry).toMatchObject({ id: MEM, pinned: true });+ });++ it('404 when the memory belongs to another agent', async () => {+ sqlQueue.push([{ user_id: 'u1' }]); // ownership+ sqlQueue.push([]); // agent-scoped UPDATE matched nothing+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'pin', memoryId: MEM }), res);+ expect(res.statusCode).toBe(404);});it('rejects an invalid tier', async () => {sqlQueue.push([{ user_id: 'u1' }]);const res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'tier', memoryId: 'm1', tier: 'bogus' } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'tier', memoryId: MEM, tier: 'bogus' }), res);+ expect(res.statusCode).toBe(400);+ });++ it('rejects an out-of-range salience', async () => {+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'salience', memoryId: MEM, salience: 4 }), res);+ expect(res.statusCode).toBe(400);+ });++ it('edit requires content or tags', async () => {+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'edit', memoryId: MEM }), res);expect(res.statusCode).toBe(400);});it('merge needs at least two ids', async () => {sqlQueue.push([{ user_id: 'u1' }]);const res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'merge', memoryIds: ['only-one'] } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'merge', memoryIds: [MEM] }), res);expect(res.statusCode).toBe(400);});+ // "merge a into a" dedupes to one id, so it must not delete the row it just wrote.+ it('merge rejects a repeated id rather than deleting the target', async () => {+ sqlQueue.push([{ user_id: 'u1' }]);+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'merge', memoryIds: [MEM, MEM] }), res);+ expect(res.statusCode).toBe(400);+ });++ it('merge folds the dupes into the target and reports the count', async () => {+ sqlQueue.push([{ user_id: 'u1' }]); // ownership+ sqlQueue.push([ // SELECT the ids+ { id: MEM, content: 'keeps the ticker', tags: ['a'], salience: 0.4, type: 'reference' },+ { id: MEM_2, content: 'a duplicate note', tags: ['b'], salience: 0.9, type: 'reference' },+ ]);+ sqlQueue.push([{ id: MEM, tier: 'recall', pinned: false }]); // UPDATE target+ sqlQueue.push([]); // DELETE dupes+ const res = mkRes();+ await curateHandler(post({ agentId: AGENT, op: 'merge', memoryIds: [MEM, MEM_2] }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res)).toMatchObject({ merged: 1, entry: { id: MEM } });+ });+it('forget deletes the memory', async () => {sqlQueue.push([{ user_id: 'u1' }]); // ownership- sqlQueue.push([{ id: 'm1' }]); // delete returning+ sqlQueue.push([{ id: MEM }]); // delete returningconst res = mkRes();- await curateHandler(mkReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: { agentId: 'a1', op: 'forget', memoryId: 'm1' } }), res);+ await curateHandler(post({ agentId: AGENT, op: 'forget', memoryId: MEM }), res);expect(res.statusCode).toBe(200);- expect(parse(res)).toMatchObject({ ok: true, forgot: 'm1' });+ expect(parse(res)).toMatchObject({ ok: true, forgot: MEM });});});@@ -156,9 +294,9 @@ describe('GET /api/memory/graph', () => {it('owner gets the graph', async () => {getSessionUserMock.mockResolvedValue({ id: 'u1' });sqlQueue.push([{ user_id: 'u1' }]);- buildGraph.mockResolvedValue({ nodes: [{ id: 'e1' }], edges: [], stats: { entities: 1, edges: 0 } });+ buildGraph.mockResolvedValue({ nodes: [{ id: ENTITY }], edges: [], stats: { entities: 1, edges: 0 } });const res = mkRes();- await graphHandler(mkReq({ url: '/api/memory/graph?agentId=a1' }), res);+ await graphHandler(mkReq({ url: `/api/memory/graph?agentId=${AGENT}` }), res);expect(res.statusCode).toBe(200);expect(parse(res).nodes).toHaveLength(1);});@@ -166,10 +304,76 @@ describe('GET /api/memory/graph', () => {it('entity drilldown returns memories', async () => {getSessionUserMock.mockResolvedValue({ id: 'u1' });sqlQueue.push([{ user_id: 'u1' }]);- memoriesForEntity.mockResolvedValue([{ id: 'm1' }]);+ memoriesForEntity.mockResolvedValue([{ id: MEM }]);const res = mkRes();- await graphHandler(mkReq({ url: '/api/memory/graph?agentId=a1&entityId=e1' }), res);+ await graphHandler(mkReq({ url: `/api/memory/graph?agentId=${AGENT}&entityId=${ENTITY}` }), res);expect(parse(res).memories).toHaveLength(1);- expect(memoriesForEntity).toHaveBeenCalledWith('a1', 'e1');+ expect(memoriesForEntity).toHaveBeenCalledWith(AGENT, ENTITY);+ });++ it('anonymous → empty graph, never mines', async () => {+ const res = mkRes();+ await graphHandler(mkReq({ url: `/api/memory/graph?agentId=${AGENT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res)).toEqual({ nodes: [], edges: [], stats: { entities: 0, edges: 0 } });+ expect(buildGraph).not.toHaveBeenCalled();+ });++ it('400 on a non-uuid entityId, before any query runs', async () => {+ const res = mkRes();+ await graphHandler(mkReq({ url: `/api/memory/graph?agentId=${AGENT}&entityId=nope` }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/uuid/);+ expect(sqlMock).not.toHaveBeenCalled();+ });+});++describe('GET /api/memory/context', () => {+ it('owner gets the working context and its token budget', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlQueue.push([{ user_id: 'u1' }]);+ computeContext.mockResolvedValue({+ entries: [{ id: MEM, tier: 'working' }],+ tokens: 2400,+ budget: 2000,+ overBudget: true,+ counts: { total: 3, working: 1, recall: 2, archival: 0, embedded: 1 },+ });+ const res = mkRes();+ await contextHandler(mkReq({ url: `/api/memory/context?agentId=${AGENT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res)).toMatchObject({ overBudget: true, tokens: 2400, budget: 2000 });+ expect(computeContext).toHaveBeenCalledWith(AGENT);+ });++ it('anonymous → zeroed context, never assembles', async () => {+ const res = mkRes();+ await contextHandler(mkReq({ url: `/api/memory/context?agentId=${AGENT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res)).toMatchObject({ entries: [], tokens: 0, budget: 2000, overBudget: false });+ expect(computeContext).not.toHaveBeenCalled();+ });++ it('non-owner → zeroed context', async () => {+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlQueue.push([{ user_id: 'other' }]);+ const res = mkRes();+ await contextHandler(mkReq({ url: `/api/memory/context?agentId=${AGENT}` }), res);+ expect(parse(res).entries).toEqual([]);+ expect(computeContext).not.toHaveBeenCalled();+ });++ it('400 without agentId', async () => {+ const res = mkRes();+ await contextHandler(mkReq({ url: '/api/memory/context' }), res);+ expect(res.statusCode).toBe(400);+ });++ it('400 on a non-uuid agentId, before any query runs', async () => {+ const res = mkRes();+ await contextHandler(mkReq({ url: '/api/memory/context?agentId=a1' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error_description).toMatch(/uuid/);+ expect(sqlMock).not.toHaveBeenCalled();});});diff --git a/tests/mirror-leaderboard.test.js b/tests/mirror-leaderboard.test.jsindex 988740183..aa82d359a 100644--- a/tests/mirror-leaderboard.test.js+++ b/tests/mirror-leaderboard.test.js@@ -135,4 +135,41 @@ describe('rankLeaders', () => {expect(rankLeaders([])).toEqual([]);expect(rankLeaders([], { sort: 'pnl', limit: 5 })).toEqual([]);});++ // 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+ // JSON.stringify silently flattens to `null`: a corrupt number that reads+ // exactly like the honest "no track record" null the board already uses.+ it('never emits Infinity or NaN when a settled position has no recorded entry size', () => {+ const noEntry = row({+ id: 'cccccccc-0000-4000-8000-000000000001',+ name: 'No entry recorded',+ settled: 5, wins: 2,+ pnl_lamports: '250000000', entry_lamports: '0',+ });+ const [l] = rankLeaders([noEntry]);+ expect(l.roi_pct).toBeNull();+ expect(l.pnl_sol).toBe(0.25);+ expect(l.win_rate).toBe(40);+ expect(Number.isFinite(l.score)).toBe(true);+ });++ // Lamport sums are cast ::text in SQL precisely because a bigint sum overflows+ // a JS number. The ranking must stay finite and correctly ordered for a whale+ // row rather than degrading to NaN and sorting arbitrarily.+ it('ranks lamport sums past the safe-integer range without losing finiteness or order', () => {+ const whale = row({+ id: 'cccccccc-0000-4000-8000-000000000002',+ name: 'Whale',+ settled: 40, wins: 25,+ pnl_lamports: '9007199254740993000', entry_lamports: '90071992547409930000',+ });+ const ranked = rankLeaders([CONSISTENT, whale], { sort: 'pnl' });+ expect(ranked[0].agent_id).toBe(whale.id);+ expect(Number.isFinite(ranked[0].pnl_sol)).toBe(true);+ expect(ranked[0].pnl_sol).toBeGreaterThan(9e9);+ expect(ranked[0].roi_pct).toBe(10);+ expect(Number.isFinite(ranked[0].score)).toBe(true);+ });});diff --git a/tests/pumpfun-mcp-tools.test.js b/tests/pumpfun-mcp-tools.test.jsindex 9dd61be80..dd6414576 100644--- a/tests/pumpfun-mcp-tools.test.js+++ b/tests/pumpfun-mcp-tools.test.js@@ -1,13 +1,22 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-// Verify the platform MCP server exposes pumpfun_* tools and dispatches them-// through the upstream client wrapper. This is the surface external MCP-// clients (Claude Desktop, Cursor) hit.+// pumpfun_* MCP tools (api/_mcp/tools/pumpfun.js), registered in+// api/_mcp/catalog.js. These are the pump.fun intel tools external MCP clients+// (Claude Desktop, Cursor) call against the platform server.+//+// Verifies: every tool is registered in the catalog with a read-only, live-feed+// annotation set; the handlers clamp the caller's limit and forward it to the+// upstream client; a successful array response is wrapped as { items }; an+// upstream failure and a missing mint/wallet both surface as clean tool errors+// rather than a bubbled fault; and an unconfigured feed says so instead of+// pretending the market is empty. Only the upstream client wrapper is mocked+// (its bot credentials are server-side); the tool defs themselves run real.const recentClaimsMock = vi.fn();const tokenIntelMock = vi.fn();const creatorIntelMock = vi.fn();const graduationsMock = vi.fn();+let botEnabled = true;vi.mock('../api/_lib/pumpfun-mcp.js', () => ({pumpfunMcp: {@@ -16,42 +25,104 @@ vi.mock('../api/_lib/pumpfun-mcp.js', () => ({creatorIntel: (...a) => creatorIntelMock(...a),graduations: (...a) => graduationsMock(...a),},- pumpfunBotEnabled: () => true,+ pumpfunBotEnabled: () => botEnabled,}));-vi.mock('../api/_lib/env.js', () => ({- env: {- APP_ORIGIN: 'http://localhost',- ISSUER: 'http://localhost',- MCP_RESOURCE: 'http://localhost/api/mcp',- },-}));+const { toolDefs } = await import('../api/_mcp/tools/pumpfun.js');++const byName = (name) => toolDefs.find((t) => t.name === name);+const AUTH = { userId: null, rateKey: 'pumpfun-test', scope: '', source: 'free' };+const call = (name, args) => byName(name).handler(args, AUTH, {});++beforeEach(() => {+ recentClaimsMock.mockReset();+ tokenIntelMock.mockReset();+ creatorIntelMock.mockReset();+ graduationsMock.mockReset();+ botEnabled = true;+});-const mod = await import('../api/mcp.js');+describe('pumpfun MCP tools: registration', () => {+ it('exposes the four intel tools with live-feed annotations', () => {+ expect(toolDefs.map((t) => t.name)).toEqual([+ 'pumpfun_recent_claims',+ 'pumpfun_token_intel',+ 'pumpfun_creator_intel',+ 'pumpfun_recent_graduations',+ ]);+ for (const t of toolDefs) {+ // destructiveHint defaults to true when omitted, so every read tool+ // must set it explicitly or clients treat intel reads as dangerous.+ expect(t.annotations).toEqual({+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ });+ expect(t.inputSchema.additionalProperties).toBe(false);+ }+ });+});-describe('platform MCP — pumpfun tools', () => {- beforeEach(() => {- recentClaimsMock.mockReset();- tokenIntelMock.mockReset();- creatorIntelMock.mockReset();- graduationsMock.mockReset();+describe('pumpfun MCP tools: success path', () => {+ it('wraps an array upstream response as { items } in structuredContent', async () => {+ recentClaimsMock.mockResolvedValue({ ok: true, data: [{ tx_signature: 'sig-1' }] });+ const r = await call('pumpfun_recent_claims', { limit: 3 });+ expect(r.isError).toBeUndefined();+ expect(recentClaimsMock).toHaveBeenCalledWith({ limit: 3 });+ expect(r.structuredContent).toEqual({ items: [{ tx_signature: 'sig-1' }] });+ expect(JSON.parse(r.content[0].text)).toEqual({ items: [{ tx_signature: 'sig-1' }] });});- // The TOOL_CATALOG and TOOLS aren't exported, so we verify via the public- // JSON-RPC surface by simulating a tools/list + tools/call dispatch.- // Since the dispatcher is not exported either, we test by reaching into- // the module side-effect: the only reliable thing is to assert that the- // upstream client wrapper IS the import target — i.e. that the file exists- // and references our mock by exercising the exported handler indirectly.+ it('passes an object upstream response through unwrapped', async () => {+ tokenIntelMock.mockResolvedValue({ ok: true, data: { mint: 'M1', graduated: false } });+ const r = await call('pumpfun_token_intel', { mint: 'M1' });+ expect(tokenIntelMock).toHaveBeenCalledWith({ mint: 'M1' });+ expect(r.structuredContent).toEqual({ mint: 'M1', graduated: false });+ });++ it('clamps limit into the advertised 1..50 range and defaults a junk value', async () => {+ graduationsMock.mockResolvedValue({ ok: true, data: [] });+ await call('pumpfun_recent_graduations', { limit: 5000 });+ expect(graduationsMock).toHaveBeenCalledWith({ limit: 50 });++ graduationsMock.mockClear();+ await call('pumpfun_recent_graduations', { limit: 'not-a-number' });+ expect(graduationsMock).toHaveBeenCalledWith({ limit: 10 });++ graduationsMock.mockClear();+ await call('pumpfun_recent_graduations', {});+ expect(graduationsMock).toHaveBeenCalledWith({ limit: 10 });+ });+});++describe('pumpfun MCP tools: failure paths', () => {+ it('surfaces an upstream failure as a tool error, not a thrown fault', async () => {+ creatorIntelMock.mockResolvedValue({ ok: false, error: 'upstream 503' });+ const r = await call('pumpfun_creator_intel', { wallet: 'W1' });+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toContain('upstream 503');+ expect(r.structuredContent).toBeUndefined();+ });- it('module imports and pumpfunMcp client is wired', () => {- expect(typeof mod.default).toBe('function');+ it('rejects a missing mint / wallet with a 400-tagged error', async () => {+ await expect(call('pumpfun_token_intel', {})).rejects.toMatchObject({+ status: 400,+ message: 'mint required',+ });+ await expect(call('pumpfun_creator_intel', {})).rejects.toMatchObject({+ status: 400,+ message: 'wallet required',+ });+ expect(tokenIntelMock).not.toHaveBeenCalled();+ expect(creatorIntelMock).not.toHaveBeenCalled();});- it('upstream recentClaims is reachable through the mock', async () => {- recentClaimsMock.mockResolvedValue({ ok: true, data: [{ tx_signature: 'a' }] });- const r = await recentClaimsMock({ limit: 5 });- expect(r.ok).toBe(true);- expect(r.data[0].tx_signature).toBe('a');+ it('says the feed is unconfigured instead of reporting an empty market', async () => {+ botEnabled = false;+ recentClaimsMock.mockResolvedValue({ ok: true, data: [] });+ const r = await call('pumpfun_recent_claims', {});+ expect(r.isError).toBe(true);+ expect(r.content[0].text).toMatch(/not configured/i);});});diff --git a/tests/user-launcher-endpoint.test.js b/tests/user-launcher-endpoint.test.jsnew file mode 100644index 000000000..3d892957f--- /dev/null+++ b/tests/user-launcher-endpoint.test.js@@ -0,0 +1,261 @@+// Endpoint tests for /api/launcher/me: the request/response contract around the+// per-user Memetic Launcher config (the pure patch logic is covered separately in+// tests/user-launcher.test.js).+//+// http.js is the REAL module here: body reading, content-type negotiation, status+// codes, and JSON error shaping are exactly what these tests are pinning. Only the+// modules with real side effects (auth, rate limiter, DB, trend providers, LLM coin+// synthesis, Solana RPC) are mocked.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlCalls = [];+let configRow;++vi.mock('../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ const q = strings.join('?').replace(/\s+/g, ' ').trim();+ sqlCalls.push({ q, values });+ if (/^insert into launcher_config/i.test(q)) return Promise.resolve([]);+ if (/^select \* from launcher_config/i.test(q)) return Promise.resolve([configRow]);+ if (/^update launcher_config set paused/i.test(q)) {+ configRow = { ...configRow, paused: false, pause_reason: null };+ return Promise.resolve([configRow]);+ }+ if (/^update launcher_config set/i.test(q)) {+ const [enabled, dry_run, mode, sources, categories, cadence, maxPerHour, devBuy, cap, network] = values;+ configRow = {+ ...configRow,+ enabled, dry_run, mode,+ sources: JSON.parse(sources), categories: JSON.parse(categories),+ target_cadence_seconds: cadence, max_per_hour: maxPerHour,+ dev_buy_sol: devBuy, daily_sol_cap: cap, network,+ };+ return Promise.resolve([configRow]);+ }+ if (/from launcher_runs where scope = 'user' and user_id = \? and created_at/i.test(q)) {+ return Promise.resolve([{ runs_today: 3, dry_runs_today: 2, launched_today: 1, skipped_today: 0, failed_today: 0 }]);+ }+ if (/from launcher_runs/i.test(q)) {+ return Promise.resolve([{ id: 'run1', agent_id: 'a1', kind: 'trend', name: 'Foam Party', symbol: 'FOAM', mint: null, status: 'dry_run', dry_run: true }]);+ }+ if (/from launcher_queue/i.test(q)) return Promise.resolve([{ enabled: 2 }]);+ if (/count\(\*\)::int as n from agent_identities/i.test(q)) return Promise.resolve([{ n: 4 }]);+ if (/from agent_identities/i.test(q)) {+ return Promise.resolve([+ { id: 'a1', name: 'Scout', solana_address: 'THREEsynthetic1111111111111111111111111111' },+ { id: 'a2', name: 'Drifter', solana_address: 'THREEsynthetic2222222222222222222222222222' },+ ]);+ }+ throw new Error(`unexpected query: ${q}`);+ },+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++let sessionUser = null;+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ extractBearer: () => null,+ authenticateBearer: vi.fn(async () => null),+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));++vi.mock('../api/_lib/launcher-trends.js', () => ({+ rankNarratives: vi.fn(async () => ({+ terms: [{ term: 'foam party girl', score: 2, sources: ['knowyourmeme'], kind: 'meme' }],+ top: { term: 'foam party girl', score: 2 },+ providers: ['knowyourmeme'],+ })),+}));++let previewCoin = { name: 'Foam Party Girl', symbol: 'FOAM', description: 'rides the wave', kind: 'meme', trigger_source: 'knowyourmeme', trigger_detail: { top_narrative: 'foam party girl' } };+vi.mock('../api/_lib/launcher-sources.js', () => ({+ pickSource: vi.fn(async () => previewCoin),+}));++vi.mock('../api/_lib/launcher-engine.js', () => ({+ LAUNCH_BASE_SOL: 0.02,+ SELF_FUND_FEE_BUFFER_SOL: 0.005,+}));++let balances = { THREEsynthetic1111111111111111111111111111: { sol: 0.5, usdc: 0 } };+vi.mock('../api/_lib/agent-wallet.js', () => ({+ getSolanaAddressBalances: vi.fn(async (address) => balances[address] || { sol: null, usdc: null }),+}));++const { default: handler } = await import('../api/launcher/me.js');++function fakeRes() {+ const res = {+ statusCode: 200,+ headers: {},+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(payload) { this.writableEnded = true; this.headersSent = true; this.raw = payload; },+ };+ Object.defineProperty(res, 'body', { get() { return this.raw ? JSON.parse(this.raw) : null; } });+ return res;+}++// Mirrors production: server/index.mjs's express body-parser stashes the exact+// bytes on req.rawBody before any handler runs, so readJson never touches the+// stream. Passing raw:null models a request that carries no body at all.+function fakeReq({ method = 'GET', contentType = null, raw = null, body } = {}) {+ const headers = {};+ if (contentType) headers['content-type'] = contentType;+ const buf = raw == null ? null : Buffer.from(raw, 'utf8');+ if (buf) headers['content-length'] = String(buf.length);+ const req = { method, url: '/api/launcher/me', headers };+ if (buf) req.rawBody = buf;+ if (body !== undefined) req.body = body;+ return req;+}++const jsonPost = (value) => fakeReq({ method: 'POST', contentType: 'application/json', raw: JSON.stringify(value) });++beforeEach(() => {+ sqlCalls.length = 0;+ sessionUser = { id: 'user-1' };+ previewCoin = { name: 'Foam Party Girl', symbol: 'FOAM', description: 'rides the wave', kind: 'meme', trigger_source: 'knowyourmeme', trigger_detail: { top_narrative: 'foam party girl' } };+ configRow = {+ scope: 'user', user_id: 'user-1', enabled: true, dry_run: false, paused: false, mode: 'hybrid',+ sources: ['coin_intel'], categories: [], target_cadence_seconds: 300, max_per_hour: 4,+ dev_buy_sol: 0.01, daily_sol_cap: 1, network: 'mainnet',+ };+});++describe('GET /api/launcher/me', () => {+ it('requires authentication', async () => {+ sessionUser = null;+ const res = fakeRes();+ await handler(fakeReq(), res);+ expect(res.statusCode).toBe(401);+ expect(res.body.error).toBe('unauthorized');+ expect(sqlCalls).toHaveLength(0);+ });++ it('returns the config, console, stats and live narratives', async () => {+ const res = fakeRes();+ await handler(fakeReq(), res);+ expect(res.statusCode).toBe(200);+ const b = res.body;+ expect(b.config).toMatchObject({ mode: 'hybrid', armed: true });+ expect(b.console[0]).toMatchObject({ symbol: 'FOAM' });+ expect(b.stats.runs_today).toBe(3);+ expect(b.queue_enabled).toBe(2);+ expect(b.eligible_agents).toBe(4);+ expect(b.per_launch_est_sol).toBeCloseTo(0.035, 6);+ expect(b.launch_overhead_sol).toBeCloseTo(0.025, 6);+ expect(b.narratives.terms[0].term).toBe('foam party girl');+ });++ it('still answers when the trend providers fail, with narratives null', async () => {+ const { rankNarratives } = await import('../api/_lib/launcher-trends.js');+ rankNarratives.mockRejectedValueOnce(new Error('all providers down'));+ const res = fakeRes();+ await handler(fakeReq(), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.narratives).toBe(null);+ expect(res.body.config.armed).toBe(true);+ });+});++// A body this endpoint cannot read must never be swallowed into an empty patch:+// that answers 200 {ok:true} to a caller whose settings were dropped, and this+// config arms live SOL spend.+describe('POST /api/launcher/me: unreadable bodies', () => {+ it('rejects a patch sent under a non-JSON content-type instead of silently ignoring it', async () => {+ const res = fakeRes();+ await handler(fakeReq({ method: 'POST', contentType: 'text/plain', raw: '{"enabled":false}', body: '{"enabled":false}' }), res);+ expect(res.statusCode).toBe(415);+ expect(res.body.error).toBe('unsupported_media_type');+ expect(sqlCalls.some((c) => /^update launcher_config/i.test(c.q))).toBe(false);+ });++ it('rejects an unparseable JSON body with a 400', async () => {+ const res = fakeRes();+ await handler(fakeReq({ method: 'POST', contentType: 'application/json', raw: '{broken' }), res);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('invalid_json');+ expect(sqlCalls.some((c) => /^update launcher_config/i.test(c.q))).toBe(false);+ });++ it('rejects a JSON body that is not an object', async () => {+ const res = fakeRes();+ await handler(jsonPost(['enabled']), res);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('invalid_body');+ });++ it('accepts a bodiless POST as an empty patch that keeps the current config', async () => {+ const res = fakeRes();+ await handler(fakeReq({ method: 'POST' }), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.config).toMatchObject({ mode: 'hybrid', enabled: true, dev_buy_sol: 0.01 });+ });+});++describe('POST /api/launcher/me: config patch', () => {+ it('persists a valid patch and echoes the shaped config', async () => {+ const res = fakeRes();+ await handler(jsonPost({ mode: 'trend', dry_run: true, dev_buy_sol: 0.05, sources: ['x', 'reddit'] }), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.config).toMatchObject({ mode: 'trend', dry_run: true, dev_buy_sol: 0.05, armed: false });+ expect(res.body.config.sources).toEqual(['x', 'reddit']);+ });++ it('rejects an out-of-range live-spend field before writing', async () => {+ const res = fakeRes();+ await handler(jsonPost({ daily_sol_cap: 999 }), res);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('invalid_daily_sol_cap');+ expect(sqlCalls.some((c) => /^update launcher_config/i.test(c.q))).toBe(false);+ });+});++describe('POST /api/launcher/me: actions', () => {+ it('previews a coin the launcher would mint right now', async () => {+ const res = fakeRes();+ await handler(jsonPost({ action: 'preview' }), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.sample).toMatchObject({ symbol: 'FOAM', top_narrative: 'foam party girl' });+ });++ it('rejects a preview under an unknown mode rather than substituting one', async () => {+ const res = fakeRes();+ await handler(jsonPost({ action: 'preview', mode: 'nuke' }), res);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('invalid_mode');+ });++ it('returns 503 when no sample can be synthesized', async () => {+ previewCoin = null;+ const res = fakeRes();+ await handler(jsonPost({ action: 'preview' }), res);+ expect(res.statusCode).toBe(503);+ expect(res.body.error).toBe('preview_unavailable');+ });++ it('reports funding per agent, leaving an unreadable balance null rather than a fake zero', async () => {+ const res = fakeRes();+ await handler(jsonPost({ action: 'funding' }), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.per_launch_est_sol).toBeCloseTo(0.035, 6);+ expect(res.body.agents[0]).toMatchObject({ name: 'Scout', sol: 0.5, funded: true });+ expect(res.body.agents[1]).toMatchObject({ name: 'Drifter', sol: null, funded: false });+ });++ it('clears a tripped circuit breaker on resume', async () => {+ configRow = { ...configRow, paused: true, pause_reason: 'daily cap hit' };+ const res = fakeRes();+ await handler(jsonPost({ action: 'resume' }), res);+ expect(res.statusCode).toBe(200);+ expect(res.body.config).toMatchObject({ paused: false, pause_reason: null, armed: true });+ });+});