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
style(api): replace the banned dashes in the launch, mocap, and og copy and the tests asserting it
nirholas9e3cf795af4a
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 2af291ec0..67858729c 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -536,7 +536,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = falseif (res.status === 429) {if (detail) console.warn(`[text-to-image] replicate throttled: ${detail}`);throw Object.assign(- new Error('Image generation is briefly busy upstream — please retry in a few seconds.'),+ new Error('Image generation is briefly busy upstream, please retry in a few seconds.'),{code: 'rate_limited',providerDetail: detail,diff --git a/api/launch/mm.js b/api/launch/mm.jsindex 0c75b58d6..c783e32ee 100644--- a/api/launch/mm.js+++ b/api/launch/mm.js@@ -1,4 +1,4 @@-// Launch Copilot — market-maker policy control surface.+// Launch Copilot, market-maker policy control surface.//// GET /api/launch/mm?mint=&network= → policy (public view) + presets// GET /api/launch/mm/:mint?state=1 → live state: policy + budget + recent actions@@ -11,7 +11,7 @@//// A policy can only be attached to a coin launched THROUGH three.ws (a row in// pump_agent_mints) by its owner. The MM trades from that launch's own agent-// wallet through the shared firewall + spend-guard + custody pipeline — this+// wallet through the shared firewall + spend-guard + custody pipeline, this// endpoint never moves funds; it owns policy state + the kill switch, and routes// the owner to the agent wallet's audited withdraw flow for funds.@@ -197,7 +197,7 @@ async function handlePost(req, res, url) {return json(res, 200, { data: { policy: toPublicPolicy(row), withdraw_url: `/agent/${agentId}/wallet#withdraw` } });}if (action === 'withdraw') {- // The MM never holds custody — funds live in the agent wallet. Halt the+ // The MM never holds custody, funds live in the agent wallet. Halt the// maker, then route the owner to the wallet's audited withdraw flow.const row = await upsertPolicy({ mint, network, agentId, userId: auth.userId, patch: { enabled: false, kill_switch: true } });return json(res, 200, {@@ -255,7 +255,7 @@ async function handleStream(req, res, url, headProbe = false) {Connection: 'keep-alive','X-Accel-Buffering': 'no',};- // A HEAD probe gets the headers a GET would send and nothing else — holding+ // A HEAD probe gets the headers a GET would send and nothing else, holding// the socket open for the full stream duration would answer nothing.if (headProbe) {res.writeHead(200, head);diff --git a/api/launchpad/list.js b/api/launchpad/list.jsindex 440185868..3005fbc07 100644--- a/api/launchpad/list.js+++ b/api/launchpad/list.js@@ -1,6 +1,6 @@// GET /api/launchpad/list?limit=24&offset=0[&template=token-launchpad]//-// Public showcase feed of published Launchpad Studio pages — powers the+// Public showcase feed of published Launchpad Studio pages, powers the// "Built on three.ws" gallery on /launchpad so the surface opens with real// proof instead of an empty editor. Read-only, no auth: every row is already// public (is_public = true) and served at /p/<slug>.@@ -8,7 +8,7 @@// Returns only the presentation-safe projection of each page's config (no// owner secret, no gated scene URL) plus the live view_count, so the gallery// can sort by "most viewed" without a second round trip. Cached briefly at the-// edge — the showcase shifts slowly and many tabs hit it on page load.+// edge, the showcase shifts slowly and many tabs hit it on page load.import { sql } from '../_lib/db.js';import { cors, error, json, method, wrap } from '../_lib/http.js';@@ -97,7 +97,7 @@ export default wrap(async (req, res) => {const pages = rows.slice(0, limit).map(toCard);// Cheap aggregate so the hero can show a real "N pages live" stat. Counts the- // same set the caller is paging through — an unfiltered count next to a+ // same set the caller is paging through, an unfiltered count next to a// template-filtered list reads as "24 gated showrooms" when only one exists.// Harmless if it races slightly with the list above.let total = null;diff --git a/api/mocap/[id].js b/api/mocap/[id].jsindex 615d3b0e5..4621f7126 100644--- a/api/mocap/[id].js+++ b/api/mocap/[id].js@@ -1,6 +1,6 @@-// GET /api/mocap/clips/:id — fetch a clip (frames included)-// PATCH /api/mocap/clips/:id — update metadata (name, description, tags, visibility, price)-// DELETE /api/mocap/clips/:id — soft-delete (owner only)+// GET /api/mocap/clips/:id, fetch a clip (frames included)+// PATCH /api/mocap/clips/:id, update metadata (name, description, tags, visibility, price)+// DELETE /api/mocap/clips/:id, soft-delete (owner only)import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';import { sql } from '../_lib/db.js';@@ -47,7 +47,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') return handleGet(req, res, auth, id);if (!auth) return error(res, 401, 'unauthorized', 'authentication required');// Cookie-session mutations need a CSRF token; bearer callers self-exempt- // inside requireCsrf. Mirrors api/avatars/[id].js — this endpoint is+ // inside requireCsrf. Mirrors api/avatars/[id].js, this endpoint is// credentialed CORS, and the allowlist includes partner origins, so a// same-site cookie alone is not proof of intent.if (!(await requireCsrf(req, res, auth.userId))) return;@@ -78,7 +78,7 @@ async function handleGet(req, res, auth, id) {}// Bump play_count only when someone other than the owner fetches a- // playable clip — recording your own clip doesn't inflate counters.+ // playable clip, recording your own clip doesn't inflate counters.if (!ownerView) {// Fire-and-forget; failure must not block the response.queueMicrotask(async () => {diff --git a/api/mocap/clips.js b/api/mocap/clips.jsindex d8126ae37..99f9c3df4 100644--- a/api/mocap/clips.js+++ b/api/mocap/clips.js@@ -1,5 +1,5 @@-// GET /api/mocap/clips — list (caller's own + ?include_public=true)-// POST /api/mocap/clips — create from inline frames JSON+// GET /api/mocap/clips, list (caller's own + ?include_public=true)+// POST /api/mocap/clips, create from inline frames JSON//// The runtime-recorded format is the JSON object returned by FaceMocap// .getRecording(): `{ format, duration, frames: [{ t, shapes, mat? }] }`.@@ -89,7 +89,7 @@ async function handleList(req, res, auth) {cursorAt = decodeCursor(cursor);// A cursor that does not decode to a real timestamp used to reach Postgres// as an Invalid Date, whose toISOString() throws inside the driver and- // answered 500. It is caller input, so it answers 400 — and never a silent+ // answered 500. It is caller input, so it answers 400, and never a silent// restart at page one, which would loop a paginating client forever.if (!cursorAt) return error(res, 400, 'invalid_cursor', 'cursor is malformed');}@@ -199,7 +199,7 @@ async function handleCreate(req, res, auth) {res,413,'payload_too_large',- `inline clip exceeds ${MAX_BYTES_INLINE} bytes — record a shorter clip or split it`,+ `inline clip exceeds ${MAX_BYTES_INLINE} bytes, record a shorter clip or split it`,);}if (input.avatar_id) {diff --git a/api/og/three-token-badge.js b/api/og/three-token-badge.jsindex 6fd08560c..b1c42fd1a 100644--- a/api/og/three-token-badge.js+++ b/api/og/three-token-badge.js@@ -1,7 +1,7 @@/*** GET /api/og/three-token-badge*- * Dynamic Open Graph image for the $THREE token — a shareable badge that+ * Dynamic Open Graph image for the $THREE token, a shareable badge that* previews with live market data wherever the link is posted (X, Telegram,* Discord, Slack, iMessage, Farcaster).*@@ -12,21 +12,21 @@* Every figure on the card is real, and read from the same two sources that back* GET /api/three-token/stats (what the /three-token page renders), so the card* and the page can never disagree:- * market data — fetchTokenMarketData() (Birdeye → DexScreener → GeckoTerminal+ * market data, fetchTokenMarketData() (Birdeye → DexScreener → GeckoTerminal* failover with a stale cache)- * agent count — the same agent_identities count the stats endpoint runs+ * agent count, the same agent_identities count the stats endpoint runs* Nothing is hardcoded. $THREE is the only coin this card ever references.** The card degrades gracefully: if the stats fetch fails or a field is missing- * we render the figure as "—" and still emit a valid, branded 1200×630 card —+ * we render the figure as "-" and still emit a valid, branded 1200×630 card,* we never 5xx and never redirect to a static fallback over missing enrichment.** Card anatomy (1200×630, dark):- * top — three.ws wordmark + "TOKEN"- * hero — $THREE glyph mark + symbol + truncated mint- * price — large USD price + 24h change pill (green up / red down)- * stats — market cap · holders · 24h volume · on-chain agents grid- * footer — contract address + "three.ws/three-token"+ * top, three.ws wordmark + "TOKEN"+ * hero, $THREE glyph mark + symbol + truncated mint+ * price, large USD price + 24h change pill (green up / red down)+ * stats, market cap · holders · 24h volume · on-chain agents grid+ * footer, contract address + "three.ws/three-token"*/import { cors, wrap } from '../_lib/http.js';@@ -39,7 +39,7 @@ import { sql } from '../_lib/db.js';// the OG URL repeatedly) off the lambda and off the market-data providers.const CACHE = 'public, max-age=60, s-maxage=600, stale-while-revalidate=120';-// $THREE brand gradient — the violet→cyan pair used across the platform.+// $THREE brand gradient, the violet→cyan pair used across the platform.const C1 = '#8b5cf6';const C2 = '#06b6d4';const UP = '#10b981';@@ -60,7 +60,7 @@ function shortMint(addr) {// USD price: keep enough significant digits for a sub-cent token without a wall// of zeros. >= $1 → 2dp; >= $0.01 → 4dp; otherwise 6 significant figures.function fmtPrice(n) {- if (n == null || !Number.isFinite(n)) return '—';+ if (n == null || !Number.isFinite(n)) return '-';if (n >= 1) return `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;if (n >= 0.01) return `$${n.toFixed(4)}`;if (n <= 0) return '$0';@@ -85,7 +85,7 @@ function heroTextWidth(s, fontSize) {// Compact USD for market cap / volume: $1.2M, $640K, $12.3B.function fmtCompactUsd(n) {- if (n == null || !Number.isFinite(n)) return '—';+ if (n == null || !Number.isFinite(n)) return '-';const abs = Math.abs(n);if (abs >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;if (abs >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;@@ -94,7 +94,7 @@ function fmtCompactUsd(n) {}function fmtInt(n) {- if (n == null || !Number.isFinite(n)) return '—';+ if (n == null || !Number.isFinite(n)) return '-';return Math.round(n).toLocaleString('en-US');}@@ -227,7 +227,7 @@ export default wrap(async (req, res) => {try {data = await loadBadgeData();} catch {- // Never 5xx a crawler — render the branded card with blank figures.+ // Never 5xx a crawler, render the branded card with blank figures.data = { price: null, change24h: null, marketCap: null, volume24h: null, holders: null, agents: null };}diff --git a/data/changelog.json b/data/changelog.jsonindex 0080bdafc..a396b6d94 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": "FBX export on the OKX 3D studio works again",+ "summary": "The paid FBX export service at /api/okx/3d/fbx-export was handing the conversion engine the wrong parameter names, so every call came back as a rejected request instead of a converted model, and the format you asked for was dropped on the way through. The adapter now speaks the engine's own parameter names, so a rigged GLB converts to FBX (or OBJ, STL, PLY, USDZ, 3MF) and keeps its skeleton, skin weights, and blendshapes. Buyers were never charged for the failed calls. A contract test now checks every OKX studio service against the schema its engine actually publishes, so a renamed parameter cannot slip through again. Separately, a Chinese-language brand brief sent to the Agent Identity Studio now has its first sentence picked out correctly when the prompt director is unavailable, instead of the whole brief crowding out the style hints.",+ "tags": [+ "fix"+ ],+ "link": "/api/okx/3d/catalog"+ },{"date": "2026-08-13","title": "The decentralized inference demo stops sending your prompt to a gateway that is no longer Livepeer",diff --git a/prompts/swarm-100/api-galaxy-01.md b/prompts/swarm-100/api-galaxy-01.mddeleted file mode 100644index b1c7b8f6e..000000000--- a/prompts/swarm-100/api-galaxy-01.md+++ /dev/null@@ -1,101 +0,0 @@-# API audit: api/galaxy batch 01 (1 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/galaxy/flows.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-galaxy-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/prompts/swarm-100/api-guardian-01.md b/prompts/swarm-100/api-guardian-01.mddeleted file mode 100644index f4c263800..000000000--- a/prompts/swarm-100/api-guardian-01.md+++ /dev/null@@ -1,101 +0,0 @@-# API audit: api/guardian batch 01 (1 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/guardian/assess.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-guardian-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/prompts/swarm-100/api-ledger-01.md b/prompts/swarm-100/api-ledger-01.mddeleted file mode 100644index e87b418bb..000000000--- a/prompts/swarm-100/api-ledger-01.md+++ /dev/null@@ -1,102 +0,0 @@-# API audit: api/ledger batch 01 (2 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/ledger/[agentId].js-- api/ledger/verify/[agentId].js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-ledger-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/api/llm-health-handler.test.js b/tests/api/llm-health-handler.test.jsindex 03ff44832..9ca708a1c 100644--- a/tests/api/llm-health-handler.test.js+++ b/tests/api/llm-health-handler.test.js@@ -1,10 +1,10 @@-// GET /api/llm/health — the gate in front of the provider report.+// GET /api/llm/health, the gate in front of the provider report.//// The report names every configured provider and quotes the upstream's own// error text, which is exactly the material an attacker wants: which vendor key// is dead, which account is out of credits, which lane is currently carrying// traffic. The probe itself is covered in llm-health-vertex.test.js; what is-// pinned here is the handler around it — the cron secret gate (both header+// pinned here is the handler around it, the cron secret gate (both header// forms), the method gate, the unconfigured-deployment response, and the ops// page that fires on a degraded verdict.diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.jsindex 8d70f00d5..072fc90b1 100644--- a/tests/api/text-to-image.test.js+++ b/tests/api/text-to-image.test.js@@ -5,8 +5,8 @@// • vertex-imagen must reject mangled service-account JSON with a designed// `unconfigured` error, not a raw JSON.parse SyntaxError.// • textToImage must fall back to Replicate flux when the preferred Vertex-// path throws for any reason (it previously trusted isConfigured() — which-// only checks GOOGLE_CLOUD_PROJECT — and never fell back).+// path throws for any reason (it previously trusted isConfigured(), which+// only checks GOOGLE_CLOUD_PROJECT, and never fell back).// • A Vertex data: URI result must be persisted to object storage and// returned as an https URL (Replicate caps inline data URIs well below an// Imagen PNG's size, so forwarding the data URI breaks reconstruction).@@ -72,7 +72,7 @@ function stubFetch(routes) {return calls;}-// NIM FLUX artifacts are JPEG (probed live — tasks/nvidia-nim/probes/flux.md),+// NIM FLUX artifacts are JPEG (probed live, tasks/nvidia-nim/probes/flux.md),// so the fixture carries real JPEG magic bytes (ff d8 ff) for the format sniff.const NIM_JPEG_BYTES = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from('nim-jpeg-bytes')]);@@ -115,7 +115,7 @@ afterEach(() => {vi.restoreAllMocks();});-describe('textToImage — Vertex quality lane leads by default', () => {+describe('textToImage: Vertex quality lane leads by default', () => {it('serves from Vertex before NIM when both are configured (credit-burner first)', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';@@ -132,7 +132,7 @@ describe('textToImage — Vertex quality lane leads by default', () => {expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');expect(vertexState.generate).toHaveBeenCalledOnce();- expect(calls).toHaveLength(0); // NIM never touched — Vertex led and served+ expect(calls).toHaveLength(0); // NIM never touched, Vertex led and served});it('falls from a failed Vertex lead to NIM without surfacing an error', async () => {@@ -170,7 +170,7 @@ describe('textToImage — Vertex quality lane leads by default', () => {});});-describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {+describe('textToImage: NIM FLUX free lane (legacy NIM-first order)', () => {beforeEach(() => {// These pin the legacy ladder (NIM → Vertex → Replicate), preserved// behind VERTEX_IMAGEN_FIRST=0.@@ -189,7 +189,7 @@ describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {const result = await textToImage('a red teapot');expect(result.model).toBe('black-forest-labs/flux.1-schnell');- // NIM output is JPEG — persisted bytes, key extension, and Content-Type+ // NIM output is JPEG, persisted bytes, key extension, and Content-Type// must all say jpeg, not png (regression cover for the probe finding).expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.jpg$/);// NIM artifact persisted to R2; Vertex and Replicate left untouched.@@ -291,7 +291,7 @@ describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {}});- it('does NOT retry a NIM timeout — hands off immediately to avoid a double wait', async () => {+ it('does NOT retry a NIM timeout: hands off immediately to avoid a double wait', async () => {process.env.NVIDIA_API_KEY = 'nvapi-test';process.env.REPLICATE_API_TOKEN = 'r8_test_token';const calls = stubFetch([@@ -312,7 +312,7 @@ describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {const result = await textToImage('a red teapot');expect(result.imageUrl).toBe('https://replicate.delivery/out.png');- // NIM attempted exactly once — a timeout already burned the full window.+ // NIM attempted exactly once, a timeout already burned the full window.expect(calls.filter((c) => c.url.includes('ai.api.nvidia.com'))).toHaveLength(1);});@@ -364,7 +364,7 @@ describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {const nimAfterFirst = calls.filter((c) => c.url.includes('ai.api.nvidia.com')).length;expect(nimAfterFirst).toBe(1);- // Second call sees the cooldown and skips NIM straight to Replicate — no new NIM hit.+ // Second call sees the cooldown and skips NIM straight to Replicate, no new NIM hit.await textToImage('a blue teapot');const nimAfterSecond = calls.filter((c) => c.url.includes('ai.api.nvidia.com')).length;expect(nimAfterSecond).toBe(1);@@ -383,7 +383,7 @@ function livepeerSuccessResponse(url = 'https://gateway.test/images/out.png') {});}-describe('textToImage — Livepeer federation lane counts as a real fallback', () => {+describe('textToImage: Livepeer federation lane counts as a real fallback', () => {beforeEach(() => {process.env.LIVEPEER_FEDERATION_ENABLED = '1';process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.test';@@ -429,7 +429,7 @@ describe('textToImage — Livepeer federation lane counts as a real fallback', (});});-describe('textToImage — Vertex → Replicate fallback', () => {+describe('textToImage: Vertex → Replicate fallback', () => {it('falls back to Replicate flux when the Vertex path throws', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';process.env.REPLICATE_API_TOKEN = 'r8_test_token';@@ -464,7 +464,7 @@ describe('textToImage — Vertex → Replicate fallback', () => {// The production incident: a low-credit Replicate account throttles// prediction creation and its `detail` names the balance. We must parse the// reset hint for backoff and keep the raw detail for logs (providerDetail),- // but the surfaced message must be clean — no credit numbers, no $ amounts.+ // but the surfaced message must be clean, no credit numbers, no $ amounts.process.env.REPLICATE_API_TOKEN = 'r8_test_token';const RAW_DETAIL ='Request was throttled. Your rate limit for creating predictions is reduced to 6 requests ' +@@ -491,14 +491,14 @@ describe('textToImage — Vertex → Replicate fallback', () => {expect(caught.code).toBe('rate_limited');expect(caught.retryAfter).toBe(10); // parsed from "resets in ~10s"expect(caught.providerDetail).toBe(RAW_DETAIL); // retained for server logs- expect(caught.message).toBe('Image generation is briefly busy upstream — please retry in a few seconds.');+ expect(caught.message).toBe('Image generation is briefly busy upstream, please retry in a few seconds.');expect(caught.message).not.toMatch(/credit|\$5|throttl|rate limit/i);});it('queues against the Replicate rate gate and waits for the reserved slot before submitting', async () => {// Under the reduced-rate account state Replicate paces creation to 6/min; the// gate reserves the next slot and tells us to hold for it. We must wait out- // that slot, THEN submit — never fire early into a throttle 429.+ // that slot, THEN submit, never fire early into a throttle 429.process.env.REPLICATE_API_TOKEN = 'r8_test_token';rateState.result = { ok: true, waitMs: 5_000 };const calls = stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);@@ -510,7 +510,7 @@ describe('textToImage — Vertex → Replicate fallback', () => {// Mid-wait: the reserved slot has not opened, so no prediction is created yet.await vi.advanceTimersByTimeAsync(4_000);expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(false);- // Slot opens — the submit fires and resolves.+ // Slot opens, the submit fires and resolves.await vi.advanceTimersByTimeAsync(2_000);const result = await p;expect(result.imageUrl).toBe('https://replicate.delivery/out.png');@@ -537,7 +537,7 @@ describe('textToImage — Vertex → Replicate fallback', () => {expect(caught.code).toBe('rate_limited');expect(caught.queued).toBe(true);expect(caught.retryAfter).toBe(12); // ceil(12000ms / 1000)- // The Replicate prediction was never created — we shed before firing.+ // The Replicate prediction was never created, we shed before firing.expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(false);// The buyer-facing message names the queue, not the account's rate state.expect(caught.message).not.toMatch(/credit|\$|throttl|rate limit/i);@@ -546,7 +546,7 @@ describe('textToImage — Vertex → Replicate fallback', () => {it('masks a Replicate 402 out-of-credit failure as a buyer-safe billing error', async () => {// The incident the user hit: the free NIM lane fell through to the paid// Replicate backstop, which had zero credit. Replicate returns the hard- // "purchase credit at replicate.com/billing" copy on a 402 — that vendor+ // "purchase credit at replicate.com/billing" copy on a 402, that vendor// billing page must never reach the buyer. We keep the raw detail for logs// (providerDetail) but the surfaced message must be neutral.process.env.REPLICATE_API_TOKEN = 'r8_test_token';@@ -721,7 +721,7 @@ describe('textToImage — Vertex → Replicate fallback', () => {});});-describe('textToImage — VERTEX_IMAGEN_ENABLED gate', () => {+describe('textToImage: VERTEX_IMAGEN_ENABLED gate', () => {it('unset ⇒ current behavior: Vertex serves when the project is set', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';process.env.REPLICATE_API_TOKEN = 'r8_test_token';@@ -776,7 +776,7 @@ describe('textToImage — VERTEX_IMAGEN_ENABLED gate', () => {});});-describe('enhanceFluxPrompt — realism + 3D-reference isolation suffixes', () => {+describe('enhanceFluxPrompt: realism + 3D-reference isolation suffixes', () => {const ISOLATION = ', isolated subject, bright studio lighting, plain white background';const REALISM =', photorealistic, true-to-life materials and surface detail, sharp focus, professional product photograph';@@ -791,8 +791,8 @@ describe('enhanceFluxPrompt — realism + 3D-reference isolation suffixes', () =expect(enhanceFluxPrompt('a red teapot')).toBe('a red teapot' + REALISM + ISOLATION);});- it('respects a named art style — isolation stays, realism words are withheld', async () => {- // Regression (older): "cartoon"/"stylized" must never suppress isolation —+ it('respects a named art style: isolation stays, realism words are withheld', async () => {+ // Regression (older): "cartoon"/"stylized" must never suppress isolation,// a cartoon fox still needs a plain background to reconstruct cleanly.// New contract: those same words DO suppress the realism cues, which would// otherwise fight the caller's explicit style.@@ -816,12 +816,12 @@ describe('enhanceFluxPrompt — realism + 3D-reference isolation suffixes', () =}});- it('matches whole words only — substrings never trigger or suppress', async () => {+ it('matches whole words only: substrings never trigger or suppress', async () => {const enhanceFluxPrompt = await enhance();// "light" inside "lightsaber" is not a composition cue…expect(enhanceFluxPrompt('a glowing lightsaber')).toBe('a glowing lightsaber' + REALISM + ISOLATION);// …and "cartoonish" IS a style signal via the word boundary on "cartoon"?- // No: \b matches inside "cartoonish" only at the start — the suffix "ish"+ // No: \b matches inside "cartoonish" only at the start, the suffix "ish"// keeps the word alive, so assert the boundary behaves as written.expect(enhanceFluxPrompt('a legolas figure')).toBe('a legolas figure' + REALISM + ISOLATION);});@@ -833,7 +833,7 @@ describe('enhanceFluxPrompt — realism + 3D-reference isolation suffixes', () =});});-describe('vertex-imagen — service-account JSON hardening', () => {+describe('vertex-imagen: service-account JSON hardening', () => {it('rejects mangled GCP_SERVICE_ACCOUNT_JSON with a designed unconfigured error', async () => {process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';// The classic secrets-UI mangle: escaped quotes but no usable key material.diff --git a/tests/lobehub-plugin-endpoint.test.js b/tests/lobehub-plugin-endpoint.test.jsindex 0a4a5c5ba..070311344 100644--- a/tests/lobehub-plugin-endpoint.test.js+++ b/tests/lobehub-plugin-endpoint.test.js@@ -1,5 +1,5 @@/**- * api/lobehub/[action].js — the host-facing half of the LobeHub / LobeChat+ * api/lobehub/[action].js, the host-facing half of the LobeHub / LobeChat* plugin (manifest, .well-known config, handshake).** `api/_lib/db.js` and `api/_lib/rate-limit.js` are mocked so every branch runs