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
Add trading brain scan, theater module, persona updates, and changelog entries
nirholasa8a6b8a87e6b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e85ef93f9..b03b2854b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -120,6 +120,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **World Lines: walk to an agent, earn a cryptographically real proof you were there** — A new game rides on top of IRL agents. An agent placed in the real world can now leave a World Line — a persistent, location-anchored AR quest. To complete it you have to physically travel to the spot, point your phone, and finish the agent's challenge (a tap, a passphrase, or a quiz). When you do, the agent's own wallet signs a proof of presence: a tamper-evident attestation that this device was in this place and did this thing — and it mints an ownable collectible to you. The signature is genuinely real and anyone can independently re-check it from the proof's verify link, with no trust in three.ws required. Privacy is the headline feature, not a footnote: your exact GPS never leaves your device, and a proof only ever knows a coarse ~1 km area — never a precise point, in any log, alert, or payload. Completion is anti-cheat by design: server-issued single-use nonces, server-derived co-location, replay rejection, idempotency, and rate limits. Find quests on the new World Lines page — Near me (co-located), Explore (browse coarse regions), My proofs (your verifiable collectibles), and Create (place a quest on your own pin, with completion stats by coarse cell). Every value reward is in $THREE, the only coin. There's a polished non-AR fallback wherever WebXR isn't available, so it's never a dead end. (`/world-lines`) `[feature, security]`- **x402-mcp — give any AI agent a self-custodial wallet that can pay for anything** — The buyer side of the agent economy, in one line. The new @three-ws/x402-mcp server hands any AI assistant a Solana wallet it controls and four tools: find a paid service in the live x402 bazaar, inspect exactly what an endpoint costs before spending a cent, check the wallet's USDC balance, and pay_and_call — settle the payment in USDC and run the service, all from a key you hold, never a custodial wallet. Every payment is bounded: it reads the 402 price first and refuses before any money moves if it is over your cap (default $1), and asks for explicit confirmation unless you turn that off. Because pay_and_call settles any x402 endpoint generically, one install covers the whole catalog — the paid vanity grinder, symbol-availability checks, and any third-party service in the bazaar. It pairs with the hosted seller side (monetize_endpoint on the agent-wallet server), so an agent can now both earn and spend. Add it with: claude mcp add x402 --env SOLANA_SECRET_KEY=<key> -- npx -y @three-ws/x402-mcp. The full catalog of all 20 three.ws MCP servers — hosted and npm — now lives at three.ws/docs/mcp with copy-paste installs. (`/docs/mcp`) `[sdk, feature]`- **Your agent levels up: a shareable moment when its wallet crosses a wealth tier** — The embodied-finance aura already makes an agent glow brighter as its wallet grows. Now the moment it actually crosses a tier — Spark, Ember, Glow, Radiant, Luminous — its owner gets a tasteful celebration card built for sharing: the new tier, the real net worth behind it, the last-24h flow, and a one-tap Share. It only ever fires on a genuine crossing of a real on-chain threshold, never on a timer, and exactly once — even a level-up that happened while you were away is celebrated once on your next visit, then never replays. It's owner-only (visitors still see the aura brighten, just not the card), works the same on the avatar page and out in the IRL/AR walk, and respects reduced-motion with a calm fade instead of the spark burst. Only coin referenced is $THREE. (`/avatars`) `[feature, improvement]`+- **Your agent's Earn tab now shows hire income on its own and ranks your top customers** — When another agent hires yours over the agent economy — paying real USDC for one of its skills — that income now stands on its own in the wallet's Earn tab instead of being lumped in with tips. The lifetime breakdown reads true to how the money was actually made: skill sales, hires from other agents, and tips, each counted separately. Every hire shows up as its own receipt — "Hired · <skill>" — naming the agent that paid and linking straight to its profile, with the on-chain settlement signature. And a new Top customers list ranks the agents that hire yours the most by what they've spent, so you can see at a glance which of your skills are in demand and who keeps coming back. Every number is a real aggregate over the on-chain hire ledger — nothing invented. `[improvement]`- **Your agent's wallet is now a living identity on every surface** — The little wallet badge under every agent and avatar grew up. Wherever an agent appears — its profile, the marketplace, the galaxy star-map, trending, your dashboard, the launches feed — its wallet now shows the real, live portfolio value in USD, a colour-coded 24-hour change, and a clear ownership marker: a 'Yours' badge on wallets you own, and 'by @creator' on everyone else's. Hover, focus, or tap the badge and it expands into a rich preview: your balance broken out into SOL, USDC, $THREE and your top holdings, a real value sparkline, both your Solana and EVM addresses with one-click copy, and the right actions for who's looking — Open wallet and Vanity for owners, Tip and Fork-to-own for visitors. The same agent's wallet looks identical everywhere because it all comes from one shared component, every number is real on-chain data, and the value gently pulses when a tip lands or a trade fills. Balances load lazily as you scroll and pause when you switch tabs, so even long lists stay fast. (`/marketplace`) `[feature, improvement]`- **Your agent's wallet now follows it everywhere — the chat, the 3D world, and any site** — An agent's wallet is its identity, so it now shows up wherever its avatar does, not just inside the app. In the chat, the agent you're talking to carries a wallet chip — open it to see its live value and lifetime tips, copy its address, or tip it for a good answer. In the walk-around 3D world, stroll up to another player who's piloting an agent and its wallet rises beside their nameplate: vanity address, real balance, and a one-tap tip, right there in the scene. And the lightweight avatar viewer in our SDK can now opt into the same wallet card, so an agent embedded on any third-party site keeps its real, tippable identity. Every number is real and read from the same public wallet data as the rest of the platform, so values never disagree across surfaces; it's always the visitor view, so owner-only controls never leak into an embed. It's deliberately frugal in the live 3D world — only the nearest agent's wallet loads, and only once — so nothing stutters. `[feature]`- **Your avatar has a job — the Earn home in every agent wallet** — Every agent wallet now has an Earn tab that turns it from a vault into a working participant in the agent economy. It opens with the number that matters: what your avatar has actually earned — today, this week, and all time — every dollar traced to a real settlement (skill sales and tips), never an estimate. Come back after time away and it tells you what it made while you were gone. Below that is the earning engine: price your agent's skills in USDC right where the money lands, so the moment someone buys, real funds move into this wallet. Then the part that makes letting an agent spend on its own feel safe — your agent can pay other agents and services over real x402 rails, but only inside the daily cap, per-payment limit, and allowlist you set, with a prominent kill switch that freezes all autonomous spending instantly (your own withdrawals always stay open). Finally, a clean receipts statement of every payment in and out — counterparty, amount, time, and on-chain signature — plus a path to the live services directory where agents discover and hire each other. Owner-only, enforced in the UI and on the server. (`/economy`) `[feature]`diff --git a/api/agents/_id/persona.js b/api/agents/_id/persona.jsindex dc267d1ad..faf27a1a0 100644--- a/api/agents/_id/persona.js+++ b/api/agents/_id/persona.js@@ -1,5 +1,15 @@-// GET /api/agents/:id/persona — persona status (has_persona, tone_tags, extracted_at)-// POST /api/agents/:id/persona/extract — extract persona from 5-question interview via Claude+// Persona — the agent's mind, as editable structure.+//+// GET /api/agents/:id/persona — full persona for the owner: traits,+// tone tags, vocabulary, base, the+// compiled prompt, and current version.+// POST /api/agents/:id/persona/extract — (re)run the 5-question interview via+// Claude; seeds the base persona + tone.+// POST /api/agents/:id/persona/save — save edited traits/tone/vocabulary;+// compiles + signs persona_prompt and+// writes a real agent_versions entry.+// GET /api/agents/:id/persona/versions — persona version history (for diff).+// POST /api/agents/:id/persona/restore — restore a prior version as a new save.import { createHash, createHmac } from 'node:crypto';import { sql } from '../../_lib/db.js';@@ -10,6 +20,13 @@ import { env } from '../../_lib/env.js';import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';import { parse } from '../../_lib/validate.js';import { z } from 'zod';+import {+ compilePersona,+ clampTraits,+ sanitizeToneTags,+ sanitizeVocabulary,+ PERSONA_TRAIT_KEYS,+} from '../../../src/agents/persona-compile.js';const extractBody = z.object({answers: z@@ -17,6 +34,18 @@ const extractBody = z.object({.length(5, 'Exactly 5 answers required'),});+const traitsSchema = z.record(z.string(), z.number()).default({});++const saveBody = z.object({+ traits: traitsSchema,+ tone_tags: z.array(z.string()).max(24).default([]),+ vocabulary: z.array(z.string()).max(24).default([]),+ base: z.string().max(4000).optional(),+ changelog: z.string().trim().max(280).optional(),+});++const restoreBody = z.object({ version: z.number().int().positive() });+async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };@@ -25,6 +54,24 @@ async function resolveAuth(req) {return null;}+// Sign a compiled persona prompt so chat.js / portability can verify provenance.+function signPrompt(systemPrompt) {+ const hash = createHash('sha256').update(systemPrompt).digest('hex');+ const sig = createHmac('sha256', env.JWT_SECRET).update(hash).digest('hex');+ return { hash, sig };+}++// Read the structured persona state stored on the agent. persona_traits holds+// { values: {key:0..1}, vocabulary: [...], base: "..." }.+function readStructured(agent) {+ const raw = agent.persona_traits && typeof agent.persona_traits === 'object' ? agent.persona_traits : {};+ return {+ values: clampTraits(raw.values || {}),+ vocabulary: sanitizeVocabulary(raw.vocabulary || []),+ base: typeof raw.base === 'string' ? raw.base : '',+ };+}+export const handlePersona = wrap(async (req, res, id, action) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'POST'])) return;@@ -32,31 +79,65 @@ export const handlePersona = wrap(async (req, res, id, action) => {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required');- const [agent] =- await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ const [agent] = await sql`+ SELECT id, user_id, name, description, system_prompt, greeting, category, tags,+ capabilities, persona_prompt, persona_prompt_hash, persona_tone_tags,+ persona_traits, persona_extracted_at, persona_updated_at+ FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL+ `;if (!agent) return error(res, 404, 'not_found', 'agent not found');if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');- // ── GET — persona status ─────────────────────────────────────────────────-- if (req.method === 'GET') {- const [row] = await sql`- SELECT persona_prompt_hash, persona_tone_tags, persona_extracted_at- FROM agent_identities WHERE id = ${id}+ // ── GET — full persona for the owner ─────────────────────────────────────+ if (req.method === 'GET' && !action) {+ const structured = readStructured(agent);+ const [{ latest }] = await sql`+ SELECT COALESCE(MAX(version), 0) AS latest FROM agent_versions WHERE agent_id = ${id}`;return json(res, 200, {- has_persona: Boolean(row?.persona_prompt_hash),- tone_tags: row?.persona_tone_tags || [],- extracted_at: row?.persona_extracted_at || null,+ has_persona: Boolean(agent.persona_prompt_hash),+ name: agent.name,+ description: agent.description || '',+ traits: structured.values,+ tone_tags: agent.persona_tone_tags || [],+ vocabulary: structured.vocabulary,+ base: structured.base,+ persona_prompt: agent.persona_prompt || '',+ extracted_at: agent.persona_extracted_at || null,+ updated_at: agent.persona_updated_at || null,+ latest_version: latest,});}- // ── POST /extract ─────────────────────────────────────────────────────────+ // ── GET /versions — persona version history ──────────────────────────────+ if (req.method === 'GET' && action === 'versions') {+ const rows = await sql`+ SELECT version, kind, changelog, persona_prompt, persona_tone_tags, persona_traits,+ created_at+ FROM agent_versions+ WHERE agent_id = ${id} AND kind = 'persona'+ ORDER BY version DESC+ LIMIT 50+ `;+ return json(res, 200, {+ versions: rows.map((r) => ({+ version: r.version,+ kind: r.kind,+ changelog: r.changelog,+ persona_prompt: r.persona_prompt || '',+ tone_tags: r.persona_tone_tags || [],+ traits: (r.persona_traits && r.persona_traits.values) || {},+ vocabulary: (r.persona_traits && r.persona_traits.vocabulary) || [],+ base: (r.persona_traits && r.persona_traits.base) || '',+ created_at: r.created_at,+ })),+ });+ }+ // ── POST /extract — the 5-question interview ─────────────────────────────if (req.method === 'POST' && action === 'extract') {const rl = await limits.personaExtract(auth.userId);- if (!rl.success)- return rateLimited(res, rl, 'persona extraction limit reached (5 per day)');+ if (!rl.success) return rateLimited(res, rl, 'persona extraction limit reached (5 per day)');const body = parse(extractBody, await readJson(req));const { answers } = body;@@ -92,41 +173,200 @@ export const handlePersona = wrap(async (req, res, id, action) => {return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');}- const system_prompt = typeof extracted.system_prompt === 'string' ? extracted.system_prompt.trim() : '';- const tone_tags = Array.isArray(extracted.tone_tags)- ? extracted.tone_tags.filter((t) => typeof t === 'string' && t.trim()).map((t) => t.trim().slice(0, 40)).slice(0, 8)- : [];- const vocabulary_samples = Array.isArray(extracted.vocabulary_samples)- ? extracted.vocabulary_samples.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim().slice(0, 120)).slice(0, 10)- : [];- if (!system_prompt) {+ const base = typeof extracted.system_prompt === 'string' ? extracted.system_prompt.trim() : '';+ const tone_tags = sanitizeToneTags(extracted.tone_tags).slice(0, 8);+ const vocabulary_samples = sanitizeVocabulary(extracted.vocabulary_samples);+ if (!base) {return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');}- const hash = createHash('sha256').update(system_prompt).digest('hex');- const sig = createHmac('sha256', env.JWT_SECRET).update(hash).digest('hex');+ // Seed the structured persona with the extracted base + current (or default)+ // traits, then compile so the saved prompt already reflects both. The+ // interview supplies the voice; the trait sliders refine it.+ const structured = readStructured(agent);+ const traits = structured.values;+ const compiled = compilePersona({+ name: agent.name,+ description: agent.description,+ base,+ traits,+ toneTags: tone_tags,+ vocabulary: vocabulary_samples,+ });+ const { hash, sig } = signPrompt(compiled);+ const personaTraits = { values: traits, vocabulary: vocabulary_samples, base };const [updated] = await sql`UPDATE agent_identities- SET- persona_prompt = ${system_prompt},- persona_prompt_hash = ${hash},- persona_prompt_sig = ${sig},- persona_tone_tags = ${JSON.stringify(tone_tags)}::jsonb,- persona_extracted_at = now(),- updated_at = now()+ SET persona_prompt = ${compiled},+ persona_prompt_hash = ${hash},+ persona_prompt_sig = ${sig},+ persona_tone_tags = ${JSON.stringify(tone_tags)}::jsonb,+ persona_traits = ${JSON.stringify(personaTraits)}::jsonb,+ persona_extracted_at = now(),+ persona_updated_at = now(),+ updated_at = now()WHERE id = ${id}RETURNING persona_extracted_at`;return json(res, 200, {- system_prompt,+ system_prompt: compiled,+ base,+ traits,tone_tags,- vocabulary_samples,+ vocabulary: vocabulary_samples,hash,extracted_at: updated.persona_extracted_at,});}+ // ── POST /save — persist edited traits + create a real version ───────────+ if (req.method === 'POST' && action === 'save') {+ const rl = await limits.widgetWrite(auth.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many persona saves, slow down');++ const body = parse(saveBody, await readJson(req));+ const prev = readStructured(agent);+ const traits = clampTraits(body.traits);+ const toneTags = sanitizeToneTags(body.tone_tags);+ const vocabulary = sanitizeVocabulary(body.vocabulary);+ const base = body.base != null ? String(body.base).trim() : prev.base;++ const compiled = compilePersona({+ name: agent.name,+ description: agent.description,+ base,+ traits,+ toneTags,+ vocabulary,+ });+ const { hash, sig } = signPrompt(compiled);+ const personaTraits = { values: traits, vocabulary, base };+ const changelog = body.changelog || 'Persona updated';++ const [{ next_version }] = await sql`+ SELECT COALESCE(MAX(version), 0) + 1 AS next_version+ FROM agent_versions WHERE agent_id = ${id}+ `;++ const [updatedRows] = await sql.transaction([+ sql`+ UPDATE agent_identities+ SET persona_prompt = ${compiled},+ persona_prompt_hash = ${hash},+ persona_prompt_sig = ${sig},+ persona_tone_tags = ${JSON.stringify(toneTags)}::jsonb,+ persona_traits = ${JSON.stringify(personaTraits)}::jsonb,+ persona_updated_at = now(),+ updated_at = now()+ WHERE id = ${id}+ RETURNING persona_updated_at+ `,+ sql`+ INSERT INTO agent_versions (+ agent_id, version, kind, system_prompt, greeting, category, tags,+ capabilities, changelog, created_by,+ persona_prompt, persona_tone_tags, persona_traits+ )+ VALUES (+ ${id}, ${next_version}, 'persona', ${agent.system_prompt}, ${agent.greeting},+ ${agent.category}, ${agent.tags || []},+ ${JSON.stringify(agent.capabilities || {})}::jsonb, ${changelog}, ${auth.userId},+ ${compiled}, ${JSON.stringify(toneTags)}::jsonb, ${JSON.stringify(personaTraits)}::jsonb+ )+ `,+ ]);++ return json(res, 200, {+ version: next_version,+ persona_prompt: compiled,+ traits,+ tone_tags: toneTags,+ vocabulary,+ base,+ hash,+ changelog,+ updated_at: updatedRows[0]?.persona_updated_at || null,+ });+ }++ // ── POST /restore — re-save a prior version as the live persona ──────────+ if (req.method === 'POST' && action === 'restore') {+ const rl = await limits.widgetWrite(auth.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many persona saves, slow down');++ const body = parse(restoreBody, await readJson(req));+ const [snap] = await sql`+ SELECT version, persona_tone_tags, persona_traits+ FROM agent_versions+ WHERE agent_id = ${id} AND version = ${body.version} AND kind = 'persona'+ LIMIT 1+ `;+ if (!snap) return error(res, 404, 'not_found', 'persona version not found');++ const snapTraits = snap.persona_traits && typeof snap.persona_traits === 'object' ? snap.persona_traits : {};+ const traits = clampTraits(snapTraits.values || {});+ const toneTags = sanitizeToneTags(snap.persona_tone_tags || []);+ const vocabulary = sanitizeVocabulary(snapTraits.vocabulary || []);+ const base = typeof snapTraits.base === 'string' ? snapTraits.base : '';++ const compiled = compilePersona({+ name: agent.name,+ description: agent.description,+ base,+ traits,+ toneTags,+ vocabulary,+ });+ const { hash, sig } = signPrompt(compiled);+ const personaTraits = { values: traits, vocabulary, base };+ const changelog = `Restored persona from v${snap.version}`;++ const [{ next_version }] = await sql`+ SELECT COALESCE(MAX(version), 0) + 1 AS next_version+ FROM agent_versions WHERE agent_id = ${id}+ `;++ await sql.transaction([+ sql`+ UPDATE agent_identities+ SET persona_prompt = ${compiled},+ persona_prompt_hash = ${hash},+ persona_prompt_sig = ${sig},+ persona_tone_tags = ${JSON.stringify(toneTags)}::jsonb,+ persona_traits = ${JSON.stringify(personaTraits)}::jsonb,+ persona_updated_at = now(),+ updated_at = now()+ WHERE id = ${id}+ `,+ sql`+ INSERT INTO agent_versions (+ agent_id, version, kind, system_prompt, greeting, category, tags,+ capabilities, changelog, created_by,+ persona_prompt, persona_tone_tags, persona_traits+ )+ VALUES (+ ${id}, ${next_version}, 'persona', ${agent.system_prompt}, ${agent.greeting},+ ${agent.category}, ${agent.tags || []},+ ${JSON.stringify(agent.capabilities || {})}::jsonb, ${changelog}, ${auth.userId},+ ${compiled}, ${JSON.stringify(toneTags)}::jsonb, ${JSON.stringify(personaTraits)}::jsonb+ )+ `,+ ]);++ return json(res, 200, {+ version: next_version,+ restored_from: snap.version,+ persona_prompt: compiled,+ traits,+ tone_tags: toneTags,+ vocabulary,+ base,+ hash,+ changelog,+ });+ }+return error(res, 404, 'not_found', 'unknown persona action');});diff --git a/api/chat.js b/api/chat.jsindex f54d5d427..9b284101c 100644--- a/api/chat.js+++ b/api/chat.js@@ -145,6 +145,10 @@ const chatBody = z.object({message: z.string().trim().min(1).max(4000),context: contextSchema,system_prompt: z.string().trim().min(1).max(2000).optional(),+ // Owner-only candidate persona for the Brain Studio live preview: lets the+ // owner audition an unsaved compiled persona against /api/chat even when the+ // agent already has a stored persona. Ignored unless the caller owns agentId.+ persona_override: z.string().trim().min(1).max(16000).optional(),agentId: z.string().uuid().optional(),provider: z.enum(['anthropic', 'openrouter', 'groq', 'nvidia', 'openai', 'watsonx', 'orchestrate'])@@ -439,12 +443,19 @@ export default wrap(async (req, res) => {// Persona prompts are private IP: only serve them for published agents,// or to the agent's owner. Anonymous callers get published personas only.const [agentRow] = await sql`- SELECT persona_prompt FROM agent_identities+ SELECT persona_prompt, user_id FROM agent_identitiesWHERE id = ${body.agentId} AND deleted_at IS NULLAND (is_published = true OR user_id = ${auth?.userId ?? null})LIMIT 1`;- if (agentRow?.persona_prompt) personaPrompt = agentRow.persona_prompt;+ // Brain Studio preview: the owner may audition an unsaved compiled persona.+ // The override only applies to the agent's owner — never published-agent+ // visitors — so it can't be used to inject a prompt into someone's agent.+ if (body.persona_override && agentRow && auth?.userId && agentRow.user_id === auth.userId) {+ personaPrompt = body.persona_override;+ } else if (agentRow?.persona_prompt) {+ personaPrompt = agentRow.persona_prompt;+ }}if (!personaPrompt && body.system_prompt) personaPrompt = body.system_prompt;diff --git a/api/trading/scan.js b/api/trading/scan.jsnew file mode 100644index 000000000..033f4de39--- /dev/null+++ b/api/trading/scan.js@@ -0,0 +1,178 @@+/**+ * Trading Brain — assisted candidate scan (P4)+ * ============================================+ *+ * POST /api/trading/scan { agent_id, config }+ * → live launches that match the rule's entry conditions RIGHT NOW, each with+ * a real on-chain quote (expected tokens out, price impact) and a real+ * rug/honeypot firewall verdict. NEVER executes — this is the assisted+ * mode's "what would my agent buy?" preview. The owner confirms a candidate+ * with the existing discretionary trade endpoint, which re-runs every guard.+ *+ * Read-only over real data: the same launch feed (recentPumpLaunches), the same+ * entry gate (matchesEntry), the same quote function (quoteTrade), and the same+ * firewall (assessTradeSafety) the autonomous runner uses — so what the owner+ * sees here is exactly what the engine would act on. No synthetic candidates, no+ * fabricated fills, no fake P&L.+ *+ * Owner-scoped + rate-limited. CSRF-exempt because it moves no funds and never+ * touches the custodial key (like the trade endpoint's preview path).+ *+ * Coin rule: coin-agnostic plumbing — it scans whatever real launches the live+ * pump.fun feed returns against the owner's runtime filters. It hardcodes,+ * markets, and recommends no specific mint. $THREE remains the only coin three.ws+ * promotes.+ */++import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { isUuid } from '../_lib/validate.js';+import { PublicKey } from '@solana/web3.js';+import { normalizeStrategyConfig, matchesEntry } from '../_lib/strategy-schema.js';+import { recentPumpLaunches, enrichCreatorStats } from '../_lib/pump-launch-feed.js';+import { quoteTrade } from '../agents/solana-trade.js';+import { assessTradeSafety } from '../_lib/trade-firewall.js';+import { solanaConnection } from '../_lib/agent-pumpfun.js';++const LAMPORTS_PER_SOL = 1_000_000_000;+// Quoting + firewall each cost RPC round-trips; cap how many candidates we price+// so an owner's scan stays fast and never hammers the node.+const MAX_PRICED = 6;+const MAX_LAUNCHES = 60;++async function resolveUser(req) {+ const session = await getSessionUser(req);+ if (session) return { id: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { id: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await resolveUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }++ const agentId = body?.agent_id;+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'a valid agent_id is required');++ // Ownership — scanning is an owner tool; it reflects the owner's private rule.+ const [agent] = await sql`+ SELECT id, user_id, meta FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ const config = normalizeStrategyConfig(body?.config);+ const network = config.network === 'devnet' ? 'devnet' : 'mainnet';+ // The live pre-graduation feed exists for mainnet only (the autonomous runner+ // has the same constraint). Be honest about it rather than returning [] silently.+ if (network !== 'mainnet') {+ return json(res, 200, { data: { network, scanned: 0, matched: 0, candidates: [], note: 'Live launch scanning is available on mainnet only.' } });+ }++ const payerAddr = agent.meta?.solana_address || null;+ const payer = payerAddr ? new PublicKey(payerAddr) : null;+ const conn = solanaConnection(network);+ const nowMs = Date.now();+ const amountSol = config.sizing.amount_sol;+ const slippageBps = config.sizing.max_slippage_bps;++ // 1. Real launch feed.+ let launches = [];+ try {+ launches = await recentPumpLaunches({ network, limit: MAX_LAUNCHES });+ } catch {+ return error(res, 502, 'feed_unavailable', 'the live launch feed is unreachable right now — try again in a moment');+ }++ // 2. Cheap entry gate (pure, no network). Enrich creator stats only when the+ // rule actually gates on them, then re-check — keeps the scan fast.+ const gatesCreator = config.entry.max_creator_launches != null || config.entry.min_creator_graduated != null;+ const matched = [];+ for (const launch of launches) {+ let verdict = matchesEntry(config, launch, nowMs);+ if (!verdict.pass && !gatesCreator) continue;+ if (gatesCreator && (launch.creator_launches == null || launch.creator_graduated == null)) {+ await enrichCreatorStats(launch, 0).catch(() => {});+ verdict = matchesEntry(config, launch, nowMs);+ }+ if (verdict.pass) matched.push({ launch, reasons: verdict.reasons });+ if (matched.length >= MAX_PRICED) break;+ }++ // 3. Real quote + firewall for each match (the costly, on-chain part).+ const candidates = [];+ for (const { launch, reasons } of matched) {+ let quote = null;+ let firewall = null;+ try {+ const mintPk = new PublicKey(launch.mint);+ const q = await quoteTrade({ conn, side: 'buy', mintPk, mintStr: launch.mint, network, solAmount: amountSol, slippageBps });+ quote = {+ out_ui: q.outUi,+ price_impact_pct: q.priceImpactPct,+ venue: q.venue,+ min_out_atomics: q.minOutAtomics,+ decimals: q.decimals,+ };+ const a = await assessTradeSafety({+ network, mint: mintPk, side: 'buy', payer,+ quoteAmount: BigInt(q.inAtomics), priceImpactPct: q.priceImpactPct,+ }).catch(() => null);+ if (a) firewall = { verdict: a.verdict, score: a.score, simulated: a.simulated, reasons: a.reasons || [] };+ } catch (e) {+ // A coin that can't be quoted (no curve, RPC hiccup) is simply not a+ // confirmable candidate — surface it as unquotable rather than dropping it.+ quote = null;+ firewall = { verdict: 'warn', score: null, simulated: false, reasons: ['Could not quote this coin right now.'] };+ }+ candidates.push({+ mint: launch.mint,+ name: launch.name || null,+ symbol: launch.symbol || null,+ image: launch.image || launch.image_uri || null,+ created_at: launch.created_at || null,+ age_minutes: launch.created_at ? Math.max(0, Math.round((nowMs - Number(launch.created_at)) / 60000)) : null,+ market_cap_usd: launch.market_cap_usd ?? null,+ liquidity_sol: launch.liquidity_sol ?? null,+ creator: launch.creator || null,+ creator_launches: launch.creator_launches ?? null,+ creator_graduated: launch.creator_graduated ?? null,+ has_socials: !!(launch.twitter || launch.telegram || launch.website),+ twitter: launch.twitter || null,+ telegram: launch.telegram || null,+ website: launch.website || null,+ reasons,+ quote,+ firewall,+ amount_sol: amountSol,+ slippage_bps: slippageBps,+ });+ }++ return json(res, 200, {+ data: {+ network,+ scanned: launches.length,+ matched: candidates.length,+ candidates,+ amount_sol: amountSol,+ slippage_bps: slippageBps,+ },+ });+});diff --git a/data/changelog.json b/data/changelog.jsonindex ca2c70438..c13b8ff49 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$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-06-23",+ "title": "Your agent's Earn tab now shows hire income on its own and ranks your top customers",+ "summary": "When another agent hires yours over the agent economy — paying real USDC for one of its skills — that income now stands on its own in the wallet's Earn tab instead of being lumped in with tips. The lifetime breakdown reads true to how the money was actually made: skill sales, hires from other agents, and tips, each counted separately. Every hire shows up as its own receipt — \"Hired · <skill>\" — naming the agent that paid and linking straight to its profile, with the on-chain settlement signature. And a new Top customers list ranks the agents that hire yours the most by what they've spent, so you can see at a glance which of your skills are in demand and who keeps coming back. Every number is a real aggregate over the on-chain hire ledger — nothing invented.",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-23","title": "Keyboard and screen-reader users can now skip the header and drive every menu without a mouse",diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex 979254af6..09222e69c 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -970,6 +970,99 @@}.mem-vis-toggle:disabled { opacity: 0.5; cursor: progress; }+ /* Dreams (reflection review) */+ .tab-badge {+ display: inline-flex; align-items: center; justify-content: center;+ min-width: 1.05rem; height: 1.05rem; padding: 0 0.3rem; margin-left: 0.4rem;+ font-size: 0.6rem; font-weight: 700; line-height: 1; border-radius: 999px;+ background: linear-gradient(135deg, #a78bfa, #7c3aed); color: #fff; vertical-align: middle;+ }+ .dreams-head { display: flex; gap: 1rem; align-items: flex-start; justify-content: space-between; margin-bottom: 1.25rem; }+ .dreams-meta { font-size: 0.7rem; color: rgba(255,255,255,0.45); margin-top: 0.5rem; min-height: 1em; }+ .dreams-meta .dot { color: #a78bfa; }+ .dreams-reflect-btn { white-space: nowrap; flex-shrink: 0; display: inline-flex; align-items: center; gap: 0.45rem; }+ .dreams-reflect-btn[disabled] { opacity: 0.6; cursor: progress; }+ .dreams-reflect-btn.is-dreaming .dreams-reflect-label::after {+ content: ''; display: inline-block; width: 0.5rem; height: 0.5rem; margin-left: 0.4rem;+ border-radius: 50%; background: #a78bfa; animation: dream-pulse 1.1s ease-in-out infinite;+ }+ @keyframes dream-pulse { 0%,100%{ opacity:0.25; transform:scale(0.7);} 50%{ opacity:1; transform:scale(1);} }+ @media (prefers-reduced-motion: reduce) { .dreams-reflect-btn.is-dreaming .dreams-reflect-label::after { animation: none; } }++ .dreams-list { display: flex; flex-direction: column; gap: 0.875rem; }+ .dream-card {+ position: relative; background: rgba(167, 139, 250, 0.05);+ border: 1px solid rgba(167, 139, 250, 0.18); border-radius: 12px;+ padding: 1rem 1.1rem; transition: border-color 0.2s, transform 0.2s, opacity 0.25s;+ }+ .dream-card:hover { border-color: rgba(167, 139, 250, 0.4); }+ .dream-card.leaving { opacity: 0; transform: translateY(-6px); }+ .dream-card.entering { animation: dream-in 0.45s ease both; }+ @keyframes dream-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+ @media (prefers-reduced-motion: reduce) { .dream-card.entering { animation: none; } }+ .dream-kind {+ display: inline-flex; align-items: center; gap: 0.35rem; font-size: 0.6rem;+ text-transform: uppercase; letter-spacing: 0.09em; font-weight: 600;+ color: #c4b5fd; padding: 0.18rem 0.5rem; border-radius: 999px;+ background: rgba(167, 139, 250, 0.12); border: 1px solid rgba(167, 139, 250, 0.25);+ }+ .dream-kind.kind-question { color: #fcd34d; background: rgba(252, 211, 77, 0.1); border-color: rgba(252, 211, 77, 0.3); }+ .dream-statement { font-size: 0.95rem; color: rgba(255,255,255,0.92); line-height: 1.45; margin: 0.6rem 0 0.4rem; }+ .dream-rationale { font-size: 0.8rem; color: rgba(255,255,255,0.55); line-height: 1.5; margin: 0 0 0.6rem; }+ .dream-conf { display: inline-flex; align-items: center; gap: 0.45rem; font-size: 0.65rem; color: rgba(255,255,255,0.5); margin-bottom: 0.5rem; }+ .dream-conf-bar { width: 64px; height: 4px; border-radius: 999px; background: rgba(255,255,255,0.1); overflow: hidden; }+ .dream-conf-fill { height: 100%; background: linear-gradient(90deg, #7c3aed, #a78bfa); border-radius: 999px; }+ .dream-prop { font-size: 0.68rem; color: rgba(255,255,255,0.5); margin-bottom: 0.6rem; display: flex; flex-wrap: wrap; gap: 0.35rem; align-items: center; }+ .dream-prop .pill { background: rgba(255,255,255,0.06); border-radius: 999px; padding: 0.12rem 0.5rem; color: rgba(255,255,255,0.7); }+ .dream-sources { margin: 0.4rem 0 0.7rem; }+ .dream-sources-label { font-size: 0.6rem; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.35); margin-bottom: 0.35rem; }+ .dream-src {+ display: block; width: 100%; text-align: left; cursor: pointer; font-family: inherit;+ background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);+ border-radius: 8px; padding: 0.4rem 0.55rem; margin-bottom: 0.3rem;+ color: rgba(255,255,255,0.7); font-size: 0.72rem; line-height: 1.4;+ transition: border-color 0.15s, background 0.15s;+ }+ .dream-src:hover { border-color: rgba(167,139,250,0.35); background: rgba(167,139,250,0.06); }+ .dream-src:focus-visible { outline: 2px solid rgba(167,139,250,0.6); outline-offset: 1px; }+ .dream-src .src-type { color: #93c5fd; font-size: 0.6rem; text-transform: uppercase; letter-spacing: 0.06em; margin-right: 0.4rem; }+ .dream-src.forgotten { opacity: 0.5; font-style: italic; cursor: default; }+ .dream-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; margin-top: 0.6rem; }+ .dream-accept, .dream-reject { font-family: inherit; font-size: 0.75rem; font-weight: 500; cursor: pointer; border-radius: 8px; padding: 0.45rem 0.85rem; transition: all 0.15s; }+ .dream-accept { background: rgba(167,139,250,0.18); border: 1px solid rgba(167,139,250,0.45); color: #ddd6fe; }+ .dream-accept:hover { background: rgba(167,139,250,0.3); border-color: rgba(167,139,250,0.7); }+ .dream-reject { background: transparent; border: 1px solid rgba(255,255,255,0.14); color: rgba(255,255,255,0.55); }+ .dream-reject:hover { border-color: rgba(252,165,165,0.5); color: #fca5a5; }+ .dream-accept:focus-visible, .dream-reject:focus-visible, .dream-answer-send:focus-visible { outline: 2px solid rgba(167,139,250,0.6); outline-offset: 1px; }+ .dream-accept:disabled, .dream-reject:disabled { opacity: 0.5; cursor: progress; }+ .dream-answer { display: flex; gap: 0.5rem; margin-top: 0.5rem; width: 100%; }+ .dream-answer input { flex: 1; }+ .dream-answer-send { font-family: inherit; font-size: 0.75rem; cursor: pointer; border-radius: 8px; padding: 0.45rem 0.85rem; background: rgba(252,211,77,0.16); border: 1px solid rgba(252,211,77,0.4); color: #fde68a; }+ .dream-answer-send:hover { background: rgba(252,211,77,0.26); }+ .dream-card-status { font-size: 0.72rem; margin-top: 0.5rem; min-height: 1em; }+ .dream-card-status.err { color: #fca5a5; }+ .dream-card-status.ok { color: #86efac; }++ .dreams-empty { text-align: center; padding: 2.5rem 1rem; color: rgba(255,255,255,0.5); }+ .dreams-empty .moon { font-size: 2rem; display: block; margin-bottom: 0.6rem; }+ .dreams-empty .lead { color: rgba(255,255,255,0.75); font-size: 0.9rem; margin-bottom: 0.3rem; }+ .dream-skel { height: 92px; border-radius: 12px; background: linear-gradient(90deg, rgba(255,255,255,0.03), rgba(255,255,255,0.07), rgba(255,255,255,0.03)); background-size: 200% 100%; animation: dream-shimmer 1.3s linear infinite; }+ @keyframes dream-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .dream-skel { animation: none; } }++ .dreams-journal { margin-top: 1.75rem; border-top: 1px solid rgba(255,255,255,0.07); padding-top: 1rem; }+ .dreams-journal-toggle { background: none; border: none; color: rgba(255,255,255,0.6); font-family: inherit; font-size: 0.8rem; cursor: pointer; padding: 0.25rem 0; display: inline-flex; align-items: center; gap: 0.4rem; }+ .dreams-journal-toggle:hover { color: rgba(255,255,255,0.85); }+ .dreams-journal-toggle:focus-visible { outline: 2px solid rgba(167,139,250,0.6); outline-offset: 2px; }+ .dreams-journal-caret { transition: transform 0.2s; display: inline-block; }+ .dreams-journal-toggle[aria-expanded="true"] .dreams-journal-caret { transform: rotate(90deg); }+ .dreams-journal-list { margin-top: 0.75rem; display: flex; flex-direction: column; gap: 0.5rem; }+ .journal-item { font-size: 0.78rem; color: rgba(255,255,255,0.6); padding: 0.55rem 0.7rem; border-radius: 8px; border: 1px solid rgba(255,255,255,0.06); background: rgba(255,255,255,0.02); display: flex; gap: 0.6rem; align-items: baseline; }+ .journal-item .jstatus { font-size: 0.6rem; text-transform: uppercase; letter-spacing: 0.06em; flex-shrink: 0; }+ .journal-item .jstatus.accepted { color: #86efac; }+ .journal-item .jstatus.rejected { color: #fca5a5; }+ .journal-item .jtext { color: rgba(255,255,255,0.75); }+/* Chip list */.chip-list { display: flex; flex-wrap: wrap; gap: 0.5rem; }.chip {diff --git a/public/changelog.json b/public/changelog.jsonindex 94b22e953..0d1210bfd 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T11:25:01.140Z",+ "generated_at": "2026-06-23T12:03:26.611Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -1152,6 +1152,16 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Your agent's Earn tab now shows hire income on its own and ranks your top customers",+ "summary": "When another agent hires yours over the agent economy — paying real USDC for one of its skills — that income now stands on its own in the wallet's Earn tab instead of being lumped in with tips. The lifetime breakdown reads true to how the money was actually made: skill sales, hires from other agents, and tips, each counted separately. Every hire shows up as its own receipt — \"Hired · <skill>\" — naming the agent that paid and linking straight to its profile, with the on-chain settlement signature. And a new Top customers list ranks the agents that hire yours the most by what they've spent, so you can see at a glance which of your skills are in demand and who keeps coming back. Every number is a real aggregate over the on-chain hire ledger — nothing invented.",+ "link": null,+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 02360385f..52ddbe5ef 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -894,6 +894,14 @@<category>feature</category><description>The embodied-finance aura already makes an agent glow brighter as its wallet grows. Now the moment it actually crosses a tier — Spark, Ember, Glow, Radiant, Luminous — its owner gets a tasteful celebration card built for sharing: the new tier, the real net worth behind it, the last-24h flow, and a one-tap Share. It only ever fires on a genuine crossing of a real on-chain threshold, never on a timer, and exactly once — even a level-up that happened while you were away is celebrated once on your next visit, then never replays. It's owner-only (visitors still see the aura brighten, just not the card), works the same on the avatar page and out in the IRL/AR walk, and respects reduced-motion with a calm fade instead of the spark burst. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Your agent's Earn tab now shows hire income on its own and ranks your top customers</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Your agent's Earn tab now shows hire income on its own and ranks your top customers</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>When another agent hires yours over the agent economy — paying real USDC for one of its skills — that income now stands on its own in the wallet's Earn tab instead of being lumped in with tips. The lifetime breakdown reads true to how the money was actually made: skill sales, hires from other agents, and tips, each counted separately. Every hire shows up as its own receipt — "Hired · <skill>" — naming the agent that paid and linking straight to its profile, with the on-chain settlement signature. And a new Top customers list ranks the agents that hire yours the most by what they've spent, so you can see at a glance which of your skills are in demand and who keeps coming back. Every number is a real aggregate over the on-chain hire ledger — nothing invented.</description>+ </item><item><title>Your agent's wallet is now a living identity on every surface</title><link>https://three.ws/marketplace</link>diff --git a/public/features.json b/public/features.jsonindex 837eaead2..8a4e6d87b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T11:25:01.119Z",+ "generated_at": "2026-06-23T12:03:26.589Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agents/active-agent.js b/src/agents/active-agent.jsindex ed5227a7f..3fa1ec868 100644--- a/src/agents/active-agent.js+++ b/src/agents/active-agent.js@@ -1,20 +1,35 @@// The single canonical "my agent" — one resolved agent record shared by every-// Living-Agents surface, persisted across reloads, and broadcast on change via-// the agent bus. Defined by the Foundation task; treated as a FIXED API by-// every other feature.+// Living-Agents surface, persisted across reloads, broadcast on change via the+// agent bus, and kept consistent across tabs. Defined by the Foundation task and+// treated as a FIXED API by every other feature.+//+// Before this module there were three competing notions of "current avatar":+// • walk-companion's `walk:companion:avatar` (an avatar id)+// • the /play scenes' `cc-avatar` (an avatar id / URL / guest)+// • the guest create flow's staged avatar (guest-avatar.js / IndexedDB)+// None of them agreed and none emitted events, so the avatar was stateless+// decoration. This module is the source of truth: it reconciles those legacy+// keys (reads them as fallbacks, writes through to them on change so the+// companion and /play stay mirrored) and turns "my agent" into live state.import { apiFetch } from '../api.js';+import { peek as peekGuestAvatar } from '../guest-avatar.js';import { agentBus } from './agent-bus.js';const STORAGE_KEY = 'threews:active-agent';+// Legacy keys we reconcile. We READ them as fallbacks when no active agent is+// set, and WRITE through to them on change so existing readers (walk-companion,+// the /play scenes) follow the canonical agent without code changes on their side.+const LEGACY_WALK_AVATAR = 'walk:companion:avatar';+const LEGACY_CC_AVATAR = 'cc-avatar';-let _record = null; // last resolved agent record (or null)+let _record = null; // last resolved agent record (or guest pseudo-record, or null)let _resolving = null; // in-flight resolve promise (deduped)const _listeners = new Set();-function readStoredId() {+function readStored(key) {try {- return localStorage.getItem(STORAGE_KEY) || null;+ return localStorage.getItem(key) || null;} catch {return null;}@@ -29,6 +44,27 @@ function writeStoredId(id) {}}+// Mirror the active agent's avatar into the legacy keys so the site-wide+// companion and the /play worlds render the same avatar the canonical agent uses.+// Best-effort: a missing avatar_id leaves the legacy values untouched.+function writeThroughLegacy(agent) {+ const avatarId = agent?.avatar_id || null;+ if (!avatarId) return;+ try {+ localStorage.setItem(LEGACY_WALK_AVATAR, avatarId);+ localStorage.setItem(LEGACY_CC_AVATAR, avatarId);+ } catch {+ /* storage disabled — companion falls back to its own default */+ }+ // If the live companion is mounted, hot-swap it now instead of waiting for a+ // reload to pick up the new localStorage value.+ try {+ window.__walkCompanion?.setAvatar?.(avatarId);+ } catch {+ /* companion not mounted or rejected the swap — the LS write still lands */+ }+}+function notify() {for (const cb of _listeners) {try {@@ -46,25 +82,105 @@ function notify() {async function resolveById(id) {if (!id) return null;- const r = await apiFetch(`/api/agents/${id}`, { credentials: 'include' });+ const r = await apiFetch(`/api/agents/${encodeURIComponent(id)}`, {+ credentials: 'include',+ allowAnonymous: true,+ });+ if (!r.ok) return null;+ const j = await r.json().catch(() => ({}));+ return j.agent || null;+}++// Find the agent backing a given avatar id — the bridge from the legacy avatar+// keys to a canonical agent record.+async function resolveByAvatarId(avatarId) {+ if (!avatarId) return null;+ const r = await apiFetch(`/api/agents?avatar_id=${encodeURIComponent(avatarId)}`, {+ credentials: 'include',+ allowAnonymous: true,+ });+ if (!r.ok) return null;+ const j = await r.json().catch(() => ({}));+ const list = Array.isArray(j.agents) ? j.agents : [];+ return list[0] || null;+}++// The signed-in user's default/most-recent agent (get-or-create). Returns null+// for guests. This is the "most recently used / first owned agent" default.+async function resolveOwnerDefault() {+ const r = await apiFetch('/api/agents/me', { credentials: 'include', allowAnonymous: true });if (!r.ok) return null;const j = await r.json().catch(() => ({}));return j.agent || null;}+// A synthetic record for a signed-out guest who has staged an avatar in the+// create flow but has no agent yet. agentId is null; surfaces render the avatar+// and treat it as "not yet an account agent".+function guestRecord() {+ const staged = peekGuestAvatar();+ if (!staged) return null;+ return {+ id: null,+ guest: true,+ name: staged.name || 'Your agent',+ avatar_id: null,+ guest_avatar: staged,+ };+}++// The full resolution chain, in priority order:+// 1. the stored canonical id+// 2. a legacy avatar key (walk / cc) → the agent that backs that avatar+// 3. the signed-in user's default agent (/api/agents/me)+// 4. a staged guest avatar (signed-out)+// On a successful non-guest resolution we persist the id and mirror it into the+// legacy keys, collapsing the three old notions into one.+async function resolveActive() {+ const storedId = readStored(STORAGE_KEY);+ if (storedId) {+ const agent = await resolveById(storedId);+ if (agent) {+ writeThroughLegacy(agent);+ return agent;+ }+ writeStoredId(null); // stale id — drop and fall through to derive a default+ }++ const legacyAvatar = readStored(LEGACY_WALK_AVATAR) || readStored(LEGACY_CC_AVATAR);+ if (legacyAvatar && !legacyAvatar.includes(':') && !legacyAvatar.includes('/')) {+ // Looks like a bare avatar id (not a URL or the guest sentinel).+ const agent = await resolveByAvatarId(legacyAvatar);+ if (agent) {+ writeStoredId(agent.id);+ writeThroughLegacy(agent);+ return agent;+ }+ }++ const owned = await resolveOwnerDefault();+ if (owned) {+ writeStoredId(owned.id);+ writeThroughLegacy(owned);+ return owned;+ }++ return guestRecord();+}+/**- * Resolve the active agent record. Reads the stored id, fetches it once, and- * caches. Returns null when no agent is selected or the stored one is gone.+ * Resolve the active agent record. Reads the stored id (or derives a sensible+ * default), fetches once, and caches. Returns null only when there is no agent+ * AND no staged guest avatar. Pass `{ force: true }` to bypass the cache.+ * @param {{ force?: boolean }} [opts]+ * @returns {Promise<Object|null>}*/export async function getActiveAgent({ force = false } = {}) {if (_record && !force) return _record;if (_resolving && !force) return _resolving;- const id = readStoredId();- if (!id) return null;- _resolving = resolveById(id)+ _resolving = resolveActive().then((agent) => {_record = agent;- if (!agent) writeStoredId(null); // stale id — drop itreturn agent;}).finally(() => {@@ -73,18 +189,36 @@ export async function getActiveAgent({ force = false } = {}) {return _resolving;}+/** Force a re-fetch of the active agent and broadcast the refreshed record. */+export async function refreshActiveAgent() {+ const agent = await getActiveAgent({ force: true });+ notify();+ return agent;+}+/** Current cached record without triggering a fetch. */export function peekActiveAgent() {return _record;}-export function activeAgentId() {- return _record?.id || readStoredId();+/**+ * The active agent's id, best-effort and synchronous: the cached record's id, or+ * the stored id. Returns null for a guest or before the first resolve. Use+ * {@link getActiveAgent} when you need the derived default resolved.+ * @returns {string|null}+ */+export function getActiveAgentId() {+ return _record?.id || readStored(STORAGE_KEY);}+// Back-compat alias — earlier surfaces imported `activeAgentId`.+export const activeAgentId = getActiveAgentId;+/**- * Set the active agent by id, persist, resolve, and broadcast. Pass null to- * clear. Returns the resolved record (or null).+ * Set the active agent by id, persist, resolve, mirror to legacy keys, and+ * broadcast. Pass null to clear. Returns the resolved record (or null).+ * @param {string|null} id+ * @returns {Promise<Object|null>}*/export async function setActiveAgent(id) {if (!id) {@@ -96,7 +230,8 @@ export async function setActiveAgent(id) {writeStoredId(id);const agent = await resolveById(id);_record = agent;- if (!agent) writeStoredId(null);+ if (agent) writeThroughLegacy(agent);+ else writeStoredId(null);notify();return agent;}@@ -104,22 +239,31 @@ export async function setActiveAgent(id) {/*** Replace the cached record in place (e.g. after an owner edits their agent) and* broadcast. The id must match the active agent, or this is a no-op.+ * @param {Object} patch+ * @returns {Object|null}*/export function updateActiveAgent(patch) {if (!patch || !_record) return _record;if (patch.id && patch.id !== _record.id) return _record;_record = { ..._record, ...patch };+ if (patch.avatar_id) writeThroughLegacy(_record);notify();return _record;}-/** Subscribe to active-agent changes. Returns an unsubscribe function. */+/**+ * Subscribe to active-agent changes. Fires on set, refresh, in-place update, and+ * cross-tab storage sync. Returns an unsubscribe function.+ * @param {(agent: Object|null) => void} cb+ * @returns {() => void}+ */export function onActiveAgentChange(cb) {_listeners.add(cb);return () => _listeners.delete(cb);}-// Cross-tab sync: a selection made in one tab reflects in the others.+// Cross-tab sync: a selection made in one tab reflects in the others. We react to+// the canonical key; the legacy keys are write-through outputs, not inputs.if (typeof window !== 'undefined') {window.addEventListener('storage', (e) => {if (e.key !== STORAGE_KEY) return;@@ -131,6 +275,7 @@ if (typeof window !== 'undefined') {} else {resolveById(id).then((agent) => {_record = agent;+ if (agent) writeThroughLegacy(agent);notify();});}diff --git a/src/theater.js b/src/theater.jsnew file mode 100644index 000000000..8a768935a--- /dev/null+++ b/src/theater.js@@ -0,0 +1,474 @@+// Live Trading Theater — controller.+//+// Stages the platform's highest-reputation agents as real 3D avatars and makes+// trading a spectator sport: when a REAL on-chain event lands on the live feed,+// the matching avatar performs and a real receipt rises with an explorer link.+// Click any avatar for its read-only wallet/reputation HUD; watch, follow, or+// fork it from there. Three themed rooms re-cohort the stage around real filters.+//+// Every number here traces to a real endpoint:+// roster → GET /api/reputation/leaderboard · GET /api/agents/public+// bodies → GET /api/agents/:id (avatar_model_url, mannequin fallback)+// trust → GET /api/agents/reputation-batch+// balances → fetchWalletBalances() (live SOL/USDC/$THREE)+// events → GET /api/feed (snapshot) + GET /api/feed-stream (SSE)++import { createStage } from './theater-stage.js';+import { connectFeed, loadSnapshot } from './theater-feed.js';+import { fetchWalletBalances } from './shared/agent-wallet-identity.js';+import { log } from './shared/log.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const WATCH_KEY = 'theater:watch:v1';++// Stage budget — keep the cast lively but 60fps. Tighter on small screens.+const isMobile = () => window.matchMedia('(max-width: 768px)').matches;+const rosterBudget = () => (isMobile() ? 6 : 14);++const ROOMS = [+ { id: 'top', label: 'Top performers', hint: 'Ranked by the non-gameable wallet-trust score', centerpiece: false, featured: new Set(['buy', 'launch', 'verify', 'pay', 'win']) },+ { id: 'launches', label: 'New launches', hint: 'Freshest agents going on-chain right now', centerpiece: true, featured: new Set(['launch', 'verify', 'buy']) },+ { id: 'three', label: '$THREE stage', hint: 'The one coin — buys of $THREE take center stage', centerpiece: true, featured: new Set(['buy', 'pay']) },+];++// ── tiny DOM helper ──────────────────────────────────────────────────────────+function el(tag, attrs = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') n.className = v;+ else if (k === 'html') n.innerHTML = v;+ else if (k === 'text') n.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2).toLowerCase(), v);+ else if (k === 'dataset') Object.assign(n.dataset, v);+ else n.setAttribute(k, v);+ }+ for (const c of [].concat(kids)) { if (c != null) n.append(c.nodeType ? c : document.createTextNode(c)); }+ return n;+}+const fmtScore = (s) => (Number.isFinite(s) ? Math.round(s) : '—');+const fmtUsd = (v) => (Number.isFinite(v) ? `$${v >= 1000 ? Math.round(v).toLocaleString() : v.toFixed(2)}` : '—');+const timeAgo = (ts) => {+ const s = Math.max(0, (Date.now() - ts) / 1000);+ if (s < 60) return `${Math.floor(s)}s`;+ if (s < 3600) return `${Math.floor(s / 60)}m`;+ if (s < 86400) return `${Math.floor(s / 3600)}h`;+ return `${Math.floor(s / 86400)}d`;+};++// ── auth probe (real, cached) ─────────────────────────────────────────────────+let _me;+async function whoami() {+ if (_me !== undefined) return _me;+ try {+ const r = await fetch('/api/auth/me', { credentials: 'include' });+ _me = r.ok ? await r.json().catch(() => null) : null;+ } catch { _me = null; }+ return _me;+}++// ── data layer ────────────────────────────────────────────────────────────────+async function fetchLeaderboard(limit) {+ const r = await fetch(`/api/reputation/leaderboard?limit=${limit}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`leaderboard ${r.status}`);+ const body = await r.json();+ return (body.agents || []).map((a) => ({+ id: a.id, name: a.name || 'Agent', solana_address: a.solana_address || null,+ score: a.score, tier: a.tier, tierLabel: a.tier_label, totals: a.totals || {},+ avatar_thumbnail: a.avatar_thumbnail_url || null,+ }));+}+async function fetchNewLaunches(limit) {+ const r = await fetch(`/api/agents/public?sort=newest&onchain=1&limit=${limit}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`public ${r.status}`);+ const body = await r.json();+ return (body.agents || []).map((a) => ({+ id: a.id, name: a.name || 'Agent', solana_address: null,+ score: null, tier: null, tierLabel: null, totals: {},+ avatar_thumbnail: a.avatar_thumbnail || null,+ }));+}++// Resolve a staged agent's real 3D body + ownership from the public agent GET.+// Falls back cleanly (mannequin via agentAvatarGlb) if the detail is unavailable.+async function resolveBody(agent) {+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agent.id)}`, { credentials: 'include', headers: { accept: 'application/json' } });+ if (r.ok) {+ const d = await r.json().catch(() => null);+ const a = d?.agent || d || {};+ agent.avatar_model_url = a.avatar_model_url || a.avatar_glb_url || a.glb_url || null;+ agent.is_owner = !!a.is_owner;+ if (!agent.solana_address) agent.solana_address = a.solana_address || null;+ }+ } catch { /* mannequin fallback handles it */ }+ return agent;+}++async function fetchReputationBatch(ids) {+ if (!ids.length) return {};+ try {+ const r = await fetch(`/api/agents/reputation-batch?ids=${ids.map(encodeURIComponent).join(',')}`, { headers: { accept: 'application/json' } });+ if (!r.ok) return {};+ const body = await r.json();+ return body.data || {};+ } catch { return {}; }+}++// pooled map with bounded concurrency+async function pool(items, n, fn) {+ const out = new Array(items.length);+ let i = 0;+ const workers = Array.from({ length: Math.min(n, items.length || 1) }, async () => {+ while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx], idx); }+ });+ await Promise.all(workers);+ return out;+}++// ── main ──────────────────────────────────────────────────────────────────────+export function initTheater(root) {+ const refs = {+ canvas: root.querySelector('#th-canvas'),+ overlay: root.querySelector('#th-overlay'),+ stageWrap: root.querySelector('#th-stage'),+ rooms: root.querySelector('#th-rooms'),+ status: root.querySelector('#th-status'),+ ticker: root.querySelector('#th-ticker'),+ replay: root.querySelector('#th-replay'),+ panel: root.querySelector('#th-panel'),+ quiet: root.querySelector('#th-quiet'),+ loading: root.querySelector('#th-loading'),+ error: root.querySelector('#th-error'),+ hint: root.querySelector('#th-room-hint'),+ };++ const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ const stage = createStage({+ canvas: refs.canvas,+ overlay: refs.overlay,+ reducedMotion: reduced,+ onSelect: (id) => openPanel(id),+ });++ const ro = new ResizeObserver(() => stage.resize());+ ro.observe(refs.stageWrap);+ window.addEventListener('resize', () => stage.resize());++ const state = {+ room: ROOMS[0],+ roster: [],+ byId: new Map(),+ reputation: {},+ balances: {},+ watch: new Set(loadWatch()),+ sessionEvents: [], // featured events captured this session (for replay)+ liveCount: 0,+ selected: null,+ };++ // ── rooms ──────────────────────────────────────────────────────────────────+ renderRooms();+ function renderRooms() {+ refs.rooms.replaceChildren(+ ...ROOMS.map((rm) =>+ el('button', {+ class: `th-room${rm.id === state.room.id ? ' is-active' : ''}`,+ role: 'tab',+ 'aria-selected': rm.id === state.room.id ? 'true' : 'false',+ onClick: () => switchRoom(rm),+ }, rm.label),+ ),+ );+ refs.hint.textContent = state.room.hint;+ }++ async function switchRoom(rm) {+ if (rm.id === state.room.id) return;+ state.room = rm;+ renderRooms();+ await loadRoom();+ }++ // ── status pill ─────────────────────────────────────────────────────────────+ function setStatus(s) {+ const map = {+ connecting: ['Connecting', 'th-dot-amber'],+ live: ['Live', 'th-dot-green'],+ reconnecting: ['Reconnecting…', 'th-dot-amber'],+ offline: ['Offline', 'th-dot-red'],+ };+ const [label, dot] = map[s] || map.offline;+ refs.status.className = `th-status ${dot}`;+ refs.status.querySelector('.th-status-label').textContent = label;+ }++ // ── roster load ──────────────────────────────────────────────────────────────+ async function loadRoom() {+ showState('loading');+ try {+ const limit = rosterBudget();+ const rows = state.room.id === 'launches' ? await fetchNewLaunches(limit) : await fetchLeaderboard(limit);+ if (!rows.length) { showState('quiet'); }+ else { showState('stage'); }++ await pool(rows, 5, resolveBody);+ state.roster = rows;+ state.byId = new Map(rows.map((a) => [a.id, a]));+ await stage.setRoster(rows);++ // $THREE room: drop the coin centerpiece immediately as the room's anchor.+ if (state.room.id === 'three') stage.spawnCenterpiece({ tint: 0x8b5cf6 });++ // Enrich with batch reputation (fills New-launches scores; refreshes others).+ fetchReputationBatch(rows.map((a) => a.id)).then((rep) => { state.reputation = rep; if (state.selected) renderPanel(state.selected); });++ // Re-apply any watched highlight that belongs to this room.+ for (const id of state.watch) if (state.byId.has(id)) stage.highlight(id);+ } catch (err) {+ log.warn('[theater] room load failed', err?.message);+ showState('error');+ }+ }++ function showState(which) {+ refs.loading.hidden = which !== 'loading';+ refs.error.hidden = which !== 'error';+ refs.quiet.hidden = which !== 'quiet';+ // stage canvas always visible behind overlays+ }++ refs.error.querySelector('[data-retry]')?.addEventListener('click', loadRoom);++ // ── live feed routing ────────────────────────────────────────────────────────+ const feed = connectFeed({+ onStatus: setStatus,+ onEvent: (n) => routeEvent(n),+ });++ function routeEvent(n) {+ pushTicker(n);+ const featured = state.room.featured.has(n.kind);+ // $THREE room only celebrates $THREE buys; other rooms celebrate any buy.+ const threeOnly = state.room.id === 'three';+ const isThree = n.mint && n.mint === THREE_MINT;+ if (!featured) return;+ if (threeOnly && n.kind === 'buy' && !isThree) return;++ if ((n.kind === 'buy' || n.kind === 'launch') && (state.room.centerpiece || isThree)) {+ stage.spawnCenterpiece({ tint: isThree ? 0x8b5cf6 : 0x4ade80 });+ }++ // Attribute to a staged performer when the event names one; otherwise the+ // receipt rises center-stage (still a real event, just no avatar to own it).+ const performerId = n.agentId && stage.hasPerformer(n.agentId) ? n.agentId : matchByActor(n.actor);+ stage.perform(performerId, { kind: n.kind, receipt: buildReceipt(n) });++ // Capture featured events for replay.+ state.sessionEvents.unshift({ ...n, performerId });+ if (state.sessionEvents.length > 24) state.sessionEvents.pop();+ renderReplay();+ }++ function matchByActor(actor) {+ if (!actor) return null;+ const a = actor.toLowerCase();+ for (const ag of state.roster) if (ag.name && ag.name.toLowerCase() === a && stage.hasPerformer(ag.id)) return ag.id;+ return null;+ }++ function buildReceipt(n) {+ const tone = n.kind === 'loss' ? 'th-rec-loss' : n.kind === 'buy' || n.kind === 'win' ? 'th-rec-win' : 'th-rec-neutral';+ const node = el('div', { class: `th-receipt ${tone}` }, [+ el('span', { class: 'th-rec-title', text: n.title }),+ n.sub ? el('span', { class: 'th-rec-sub', text: n.sub }) : null,+ n.href ? el('a', { class: 'th-rec-link', href: n.href, target: '_blank', rel: 'noopener', text: 'View ↗' }) : null,+ ]);+ return node;+ }++ // ── ticker ───────────────────────────────────────────────────────────────────+ function pushTicker(n) {+ state.liveCount++;+ const row = el('li', { class: `th-tick th-tick-${n.kind}` }, [+ el('span', { class: 'th-tick-dot' }),+ el('div', { class: 'th-tick-body' }, [+ el('span', { class: 'th-tick-title', text: n.title }),+ n.sub ? el('span', { class: 'th-tick-sub', text: n.sub }) : null,+ ]),+ n.href ? el('a', { class: 'th-tick-link', href: n.href, target: '_blank', rel: 'noopener', 'aria-label': 'Open in explorer', text: '↗' }) : null,+ el('time', { class: 'th-tick-time', text: timeAgo(n.ts), datetime: new Date(n.ts).toISOString() }),+ ]);+ refs.ticker.prepend(row);+ while (refs.ticker.children.length > 40) refs.ticker.lastElementChild.remove();+ // a real event arrived → dismiss the quiet state+ if (!refs.quiet.hidden) refs.quiet.hidden = true;+ }++ // ── replay ────────────────────────────────────────────────────────────────────+ function renderReplay() {+ const evts = state.sessionEvents;+ refs.replay.querySelector('[data-empty]')?.toggleAttribute('hidden', evts.length > 0);+ const rail = refs.replay.querySelector('[data-rail]');+ rail.replaceChildren(+ ...evts.map((e) =>+ el('button', {+ class: `th-replay-mark th-tick-${e.kind}`,+ title: `${e.title}${e.sub ? ' · ' + e.sub : ''} · ${timeAgo(e.ts)} ago`,+ 'aria-label': `Replay ${e.title}`,+ onClick: () => {+ stage.perform(e.performerId, { kind: e.kind, receipt: buildReceipt(e) });+ if (e.performerId) stage.highlight(e.performerId);+ },+ }),+ ),+ );+ }+ refs.replay.querySelector('[data-play-all]')?.addEventListener('click', async () => {+ const evts = [...state.sessionEvents].reverse();+ for (const e of evts) {+ stage.perform(e.performerId, { kind: e.kind, receipt: buildReceipt(e) });+ await new Promise((r) => setTimeout(r, 700));+ }+ });++ // ── read-only HUD panel ────────────────────────────────────────────────────────+ async function openPanel(id) {+ const agent = state.byId.get(id);+ if (!agent) return;+ state.selected = id;+ renderPanel(id);+ refs.panel.classList.add('is-open');+ // live balance (real)+ if (!state.balances[id]) {+ fetchWalletBalances([id], { network: 'mainnet' }).then((b) => { state.balances = { ...state.balances, ...b }; if (state.selected === id) renderPanel(id); }).catch(() => {});+ }+ }+ function closePanel() { refs.panel.classList.remove('is-open'); state.selected = null; }++ async function renderPanel(id) {+ const agent = state.byId.get(id);+ if (!agent) return;+ const rep = state.reputation[id] || (agent.score != null ? { score: agent.score, tier: agent.tier, tierLabel: agent.tierLabel, totals: agent.totals } : null);+ const bal = state.balances[id];+ const me = await whoami();+ const isOwner = agent.is_owner || (me && rep && false);+ const watching = state.watch.has(id);+ const totals = rep?.totals || {};++ const stat = (label, value) => el('div', { class: 'th-stat' }, [+ el('span', { class: 'th-stat-v', text: value }),+ el('span', { class: 'th-stat-l', text: label }),+ ]);++ refs.panel.replaceChildren(+ el('button', { class: 'th-panel-close', 'aria-label': 'Close', onClick: closePanel, text: '✕' }),+ el('div', { class: 'th-panel-head' }, [+ agent.avatar_thumbnail+ ? el('img', { class: 'th-panel-av', src: agent.avatar_thumbnail, alt: '', loading: 'lazy' })+ : el('div', { class: 'th-panel-av th-panel-av-fallback', text: (agent.name || '?').slice(0, 1).toUpperCase() }),+ el('div', {}, [+ el('h2', { class: 'th-panel-name', text: agent.name }),+ rep ? el('span', { class: 'th-panel-tier', text: `${rep.tierLabel || rep.tier || 'Agent'} · trust ${fmtScore(rep.score)}` }) : el('span', { class: 'th-panel-tier th-muted', text: 'New — no track record yet' }),+ ]),+ ]),+ el('div', { class: 'th-stats' }, [+ stat('Trust', rep ? fmtScore(rep.score) : '—'),+ stat('Wallet', bal ? fmtUsd(bal.usd) : el('span', { class: 'th-skel-inline' })),+ stat('Tips', totals.tip_count != null ? String(totals.tip_count) : '0'),+ stat('Launches', totals.deployed_mints != null ? String(totals.deployed_mints) : '0'),+ ]),+ agent.solana_address+ ? el('a', { class: 'th-addr', href: `https://solscan.io/account/${agent.solana_address}`, target: '_blank', rel: 'noopener', title: agent.solana_address }, [+ el('span', { text: `${agent.solana_address.slice(0, 4)}…${agent.solana_address.slice(-4)}` }),+ el('span', { class: 'th-addr-ext', text: '↗' }),+ ])+ : null,+ el('div', { class: 'th-panel-actions' }, [+ el('button', {+ class: `th-btn ${watching ? 'th-btn-on' : ''}`,+ onClick: () => toggleWatch(id),+ text: watching ? '★ Watching' : '☆ Watch',+ }),+ el('a', { class: 'th-btn', href: `/agent/${id}/wallet#reputation`, text: 'Wallet & positions' }),+ el('a', { class: 'th-btn th-btn-primary', href: `/agent/${id}`, text: isOwner ? 'Manage agent' : 'Open profile' }),+ ]),+ isOwner+ ? el('p', { class: 'th-panel-foot th-muted', text: 'This agent is yours — act from its profile.' })+ : el('p', { class: 'th-panel-foot th-muted' }, [+ 'Fork to own a copy, or follow its alpha from ',+ el('a', { href: `/agent/${id}`, text: 'its profile' }),+ '.',+ ]),+ recentForAgent(id),+ );+ }++ function recentForAgent(id) {+ const mine = state.sessionEvents.filter((e) => e.performerId === id).slice(0, 5);+ if (!mine.length) return el('p', { class: 'th-panel-foot th-muted', text: 'No live moves captured yet this session.' });+ return el('div', { class: 'th-panel-recent' }, [+ el('h3', { class: 'th-panel-recent-h', text: 'Live moves this session' }),+ el('ul', {}, mine.map((e) => el('li', { class: `th-tick-${e.kind}` }, [+ el('span', { class: 'th-tick-dot' }),+ el('span', { text: `${e.title}${e.sub ? ' · ' + e.sub : ''}` }),+ el('time', { class: 'th-tick-time', text: timeAgo(e.ts) }),+ ]))),+ ]);+ }++ function toggleWatch(id) {+ if (state.watch.has(id)) { state.watch.delete(id); stage.highlight(null); }+ else { state.watch.add(id); stage.highlight(id); }+ saveWatch([...state.watch]);+ if (state.selected === id) renderPanel(id);+ }++ // ── quiet-market highlights (real recent activity) ───────────────────────────+ loadSnapshot(40).then((events) => {+ const featured = events.filter((e) => ROOMS.some((r) => r.featured.has(e.kind)) && (e.href || e.sub));+ const host = refs.quiet.querySelector('[data-highlights]');+ if (!host) return;+ if (!featured.length) {+ host.append(el('p', { class: 'th-muted', text: 'No recent activity to replay. The stage goes live the moment an agent moves.' }));+ return;+ }+ host.replaceChildren(+ ...featured.slice(0, 8).map((e) =>+ el('a', { class: `th-hl th-tick-${e.kind}`, href: e.href || '#', target: e.href ? '_blank' : null, rel: 'noopener' }, [+ el('span', { class: 'th-tick-dot' }),+ el('span', { class: 'th-hl-title', text: e.title }),+ e.sub ? el('span', { class: 'th-hl-sub', text: e.sub }) : null,+ el('time', { class: 'th-tick-time', text: timeAgo(e.ts) }),+ ]),+ ),+ );+ });++ // keep ticker timestamps fresh+ const tickTimer = setInterval(() => {+ refs.ticker.querySelectorAll('time.th-tick-time').forEach((t) => {+ const dt = Date.parse(t.getAttribute('datetime'));+ if (Number.isFinite(dt)) t.textContent = timeAgo(dt);+ });+ }, 15000);++ // reduced-motion live toggle (system pref change)+ window.matchMedia('(prefers-reduced-motion: reduce)').addEventListener?.('change', (e) => stage.setReducedMotion(e.matches));++ // keyboard: Esc closes panel+ window.addEventListener('keydown', (e) => { if (e.key === 'Escape') closePanel(); });++ renderReplay();+ loadRoom();++ // teardown for SPA navigations / HMR+ window.addEventListener('beforeunload', () => { feed.close(); stage.dispose(); clearInterval(tickTimer); ro.disconnect(); });+}++function loadWatch() { try { return JSON.parse(localStorage.getItem(WATCH_KEY) || '[]'); } catch { return []; } }+function saveWatch(arr) { try { localStorage.setItem(WATCH_KEY, JSON.stringify(arr.slice(0, 50))); } catch {} }++// auto-boot when the page mounts us directly+const _root = document.getElementById('th-root');+if (_root) initTheater(_root);diff --git a/tests/brain-bundle.test.js b/tests/brain-bundle.test.jsnew file mode 100644index 000000000..0849a6056--- /dev/null+++ b/tests/brain-bundle.test.js@@ -0,0 +1,254 @@+import { describe, it, expect } from 'vitest';+import { Wallet } from 'ethers';++import {+ canonicalizeMemory,+ memoryDigest,+ signDigest,+ verifyMemorySignature,+ signMessageBody,+ MEMORY_SIG_VERSION,+} from '../api/_lib/brain-sign.js';+import {+ computeBrainHash,+ buildMemoryEntry,+ buildBundle,+ verifyBundle,+ verifyBrainHashSignature,+ BRAIN_BUNDLE_VERSION,+} from '../api/_lib/brain-bundle.js';++// A deterministic throwaway key — the test's "agent wallet". Never a real mint.+const TEST_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';+const wallet = new Wallet(TEST_PK);++function fixtureMemory(overrides = {}) {+ return {+ id: '11111111-1111-1111-1111-111111111111',+ agent_id: '22222222-2222-2222-2222-222222222222',+ type: 'user',+ content: 'The user prefers terse, senior-engineer feedback. No filler.',+ tags: ['tone', 'feedback'],+ salience: 0.8,+ tier: 'working',+ is_public: true,+ created_at: '2026-06-23T12:00:00.000Z',+ ...overrides,+ };+}++describe('brain-sign · canonicalization', () => {+ it('is stable regardless of tag order and timestamp representation', () => {+ const a = canonicalizeMemory(fixtureMemory({ tags: ['feedback', 'tone'] }));+ const b = canonicalizeMemory(fixtureMemory({ tags: ['tone', 'feedback'] }));+ expect(a).toBe(b);++ // numeric ms vs ISO for the same instant+ const ms = canonicalizeMemory(fixtureMemory({ created_at: 1781524800000 }));+ const iso = canonicalizeMemory(fixtureMemory({ created_at: '2026-06-15T12:00:00.000Z' }));+ expect(ms).toBe(iso);+ });++ it('excludes mutable fields so re-tiering does not break authorship', () => {+ const a = memoryDigest(fixtureMemory({ tier: 'working', salience: 0.9, pinned: true }));+ const b = memoryDigest(fixtureMemory({ tier: 'archival', salience: 0.1, pinned: false }));+ expect(a).toBe(b);+ });++ it('changes the digest when content changes', () => {+ const a = memoryDigest(fixtureMemory());+ const b = memoryDigest(fixtureMemory({ content: 'tampered' }));+ expect(a).not.toBe(b);+ });+});++describe('brain-sign · sign + verify', () => {+ it('produces a signature that recovers to the signer and verifies', async () => {+ const mem = fixtureMemory();+ const digest = memoryDigest(mem);+ const { signature, signer_address } = await signDigest(TEST_PK, digest);+ expect(signer_address.toLowerCase()).toBe(wallet.address.toLowerCase());++ const v = verifyMemorySignature(mem, { signature, signer_address, content_hash: digest });+ expect(v.valid).toBe(true);+ expect(v.reason).toBe('ok');+ expect(v.recovered.toLowerCase()).toBe(wallet.address.toLowerCase());+ });++ it('rejects tampered content', async () => {+ const mem = fixtureMemory();+ const { signature, signer_address } = await signDigest(TEST_PK, memoryDigest(mem));+ const tampered = { ...mem, content: 'I have been edited' };+ const v = verifyMemorySignature(tampered, { signature, signer_address });+ expect(v.valid).toBe(false);+ expect(v.reason).toBe('signer_mismatch');+ });++ it('detects a content_hash that does not match the memory', async () => {+ const mem = fixtureMemory();+ const v = verifyMemorySignature(mem, {+ signature: '0xdead',+ signer_address: wallet.address,+ content_hash: 'f'.repeat(64),+ });+ expect(v.valid).toBe(false);+ expect(v.reason).toBe('content_hash_mismatch');+ });++ it('reports unsigned and malformed honestly', async () => {+ const mem = fixtureMemory();+ expect(verifyMemorySignature(mem, {}).reason).toBe('unsigned');+ expect(verifyMemorySignature(mem, { signature: 'not-a-sig', signer_address: wallet.address }).reason).toBe(+ 'malformed_signature',+ );+ });++ it('rejects a signature over a different message framing', async () => {+ // A raw signature over the digest WITHOUT the domain prefix must not verify.+ const mem = fixtureMemory();+ const digest = memoryDigest(mem);+ const rogue = await wallet.signMessage(digest); // missing MEMORY_SIG_VERSION prefix+ expect(MEMORY_SIG_VERSION).toBe('threews:brain:memory:v1');+ const v = verifyMemorySignature(mem, { signature: rogue, signer_address: wallet.address });+ expect(v.valid).toBe(false);+ });+});++describe('brain-bundle · build + verify round trip', () => {+ const agent = {+ id: '22222222-2222-2222-2222-222222222222',+ name: 'Atlas',+ description: 'A research agent',+ avatar_id: 'av_1',+ chain_id: 8453,+ erc8004_agent_id: 42,+ wallet_address: wallet.address,+ };+ const persona = {+ prompt: 'You are Atlas, a meticulous research agent.',+ prompt_hash: 'a'.repeat(64),+ prompt_sig: 'sig',+ tone_tags: ['precise', 'calm'],+ extracted_at: '2026-06-01T00:00:00.000Z',+ };++ async function signedRow(over = {}) {+ const row = fixtureMemory(over);+ const digest = memoryDigest(row);+ const { signature, signer_address } = await signDigest(TEST_PK, digest);+ return { ...row, content_hash: digest, signature, signer_address, signed_at: '2026-06-23T12:00:01.000Z' };+ }++ it('builds a schema-valid, signed bundle that verifies end to end', async () => {+ const rows = [+ await signedRow(),+ await signedRow({ id: '33333333-3333-3333-3333-333333333333', content: 'Second memory', is_public: true }),+ ];+ const entries = rows.map((r) => buildMemoryEntry(r, { includePrivatePlaintext: true }));+ const bundle = await buildBundle({+ agent,+ persona,+ memoryEntries: entries,+ exportedAt: '2026-06-23T12:30:00.000Z',+ signerPrivKey: TEST_PK,+ });++ expect(bundle.version).toBe(BRAIN_BUNDLE_VERSION);+ expect(bundle.manifest.memory_count).toBe(2);+ expect(bundle.signature.signer_address.toLowerCase()).toBe(wallet.address.toLowerCase());++ const result = verifyBundle(bundle);+ expect(result.valid).toBe(true);+ expect(result.schemaValid).toBe(true);+ expect(result.brainHashValid).toBe(true);+ expect(result.bundleSignatureValid).toBe(true);+ expect(result.verifiedCount).toBe(2);+ expect(result.signedCount).toBe(2);+ });++ it('detects a tampered memory inside an otherwise valid bundle', async () => {+ const rows = [await signedRow()];+ const entries = rows.map((r) => buildMemoryEntry(r, { includePrivatePlaintext: true }));+ const bundle = await buildBundle({+ agent,+ persona,+ memoryEntries: entries,+ exportedAt: '2026-06-23T12:30:00.000Z',+ signerPrivKey: TEST_PK,+ });++ // Tamper the content but keep the original signature + content_hash.+ bundle.memories[0].content = 'malicious rewrite';+ const result = verifyBundle(bundle);+ expect(result.valid).toBe(false);+ // content_hash no longer matches the mutated content.+ expect(result.memories[0].valid).toBe(false);+ });++ it('detects a brain_hash that does not cover the memory set', async () => {+ const entries = [buildMemoryEntry(await signedRow(), { includePrivatePlaintext: true })];+ const bundle = await buildBundle({+ agent,+ persona,+ memoryEntries: entries,+ exportedAt: '2026-06-23T12:30:00.000Z',+ signerPrivKey: TEST_PK,+ });+ bundle.manifest.brain_hash = 'b'.repeat(64);+ const result = verifyBundle(bundle);+ expect(result.brainHashValid).toBe(false);+ expect(result.valid).toBe(false);+ });++ it('keeps private memories as encrypted references, not plaintext', async () => {+ const privateRow = await signedRow({+ id: '44444444-4444-4444-4444-444444444444',+ content: 'secret diary entry',+ is_public: false,+ });+ const cipherRefs = new Map([[privateRow.id, { cid: 'bafyTestCid', filename: 'mem-44.enc' }]]);+ const entry = buildMemoryEntry(privateRow, { includePrivatePlaintext: false, cipherRefs });+ expect(entry.content).toBeUndefined();+ expect(entry.cipher.cid).toBe('bafyTestCid');++ const bundle = await buildBundle({+ agent,+ persona: null,+ memoryEntries: [entry],+ exportedAt: '2026-06-23T12:30:00.000Z',+ signerPrivKey: TEST_PK,+ });+ expect(bundle.manifest.encrypted_count).toBe(1);+ const result = verifyBundle(bundle);+ // Encrypted entries are reported, not penalized; the bundle stays valid.+ expect(result.memories[0].reason).toBe('encrypted');+ expect(result.valid).toBe(true);+ });++ it('excludes a private memory with no cipher reference', async () => {+ const privateRow = await signedRow({ is_public: false });+ const entry = buildMemoryEntry(privateRow, { includePrivatePlaintext: false, cipherRefs: new Map() });+ expect(entry).toBeNull();+ });+});++describe('brain-bundle · brain hash + bundle signature', () => {+ it('is deterministic over the memory set and persona', () => {+ const h1 = computeBrainHash({ personaPromptHash: 'a'.repeat(64), memoryHashes: ['1', '2'], agentId: 'x' });+ const h2 = computeBrainHash({ personaPromptHash: 'a'.repeat(64), memoryHashes: ['2', '1'], agentId: 'x' });+ expect(h1).toBe(h2);+ const h3 = computeBrainHash({ personaPromptHash: 'a'.repeat(64), memoryHashes: ['2', '1', '3'], agentId: 'x' });+ expect(h3).not.toBe(h1);+ });++ it('round-trips a standalone brain_hash signature', async () => {+ const brainHash = computeBrainHash({ personaPromptHash: null, memoryHashes: ['abc'], agentId: 'a' });+ const { signature, signer_address } = await signDigest(TEST_PK, brainHash);+ expect(verifyBrainHashSignature(brainHash, { value: signature, signer_address })).toBe(true);+ expect(verifyBrainHashSignature('c'.repeat(64), { value: signature, signer_address })).toBe(false);+ });++ it('uses the documented message framing', () => {+ expect(signMessageBody('deadbeef')).toBe('threews:brain:memory:v1:deadbeef');+ });+});diff --git a/tests/vault-accounting.test.js b/tests/vault-accounting.test.jsnew file mode 100644index 000000000..8d6fcdccb--- /dev/null+++ b/tests/vault-accounting.test.js@@ -0,0 +1,256 @@+import { describe, it, expect } from 'vitest';+import {+ sharePriceE6, sharesForDeposit, payoutForShares, settleRedemption,+ sharesRedeemableNow, drawdownBps, isDrawdownBreached, depositExceedsCap,+ tradeExceedsPerTrade, tradeExceedsDailyBudget, nextPeak, roiBps,+ usdcToAtomics, atomicsToUsdc, SHARE_PRICE_SCALE,+} from '../api/_lib/vault-accounting.js';++const USDC = 1_000_000n; // 1 USDC in atomics++describe('share price', () => {+ it('is exactly par (1.0) for an empty vault', () => {+ expect(sharePriceE6(0n, 0n)).toBe(SHARE_PRICE_SCALE);+ expect(sharePriceE6(5_000n * USDC, 0n)).toBe(SHARE_PRICE_SCALE);+ });++ it('reflects NAV per share once shares exist', () => {+ // 100 USDC NAV across 50 shares-worth of atomics → 2.0 USDC/share.+ expect(sharePriceE6(100n * USDC, 50n * USDC)).toBe(2_000_000n);+ });+});++describe('sharesForDeposit', () => {+ it('mints 1:1 at par on the first deposit', () => {+ expect(sharesForDeposit(100n * USDC, 0n, 0n)).toBe(100n * USDC);+ });++ it('mints 1:1 when a wiped-out vault has no recoverable NAV', () => {+ expect(sharesForDeposit(100n * USDC, 0n, 500n * USDC)).toBe(100n * USDC);+ });++ it('mints fewer shares as the price rises above par', () => {+ // NAV doubled to 2.0/share → a 100 USDC deposit buys 50 shares-worth.+ const total = 100n * USDC;+ const navBefore = 200n * USDC; // price 2.0+ expect(sharesForDeposit(100n * USDC, navBefore, total)).toBe(50n * USDC);+ });++ it('does not dilute existing holders: price after deposit is unchanged', () => {+ const total = 100n * USDC;+ const navBefore = 150n * USDC; // price 1.5+ const minted = sharesForDeposit(60n * USDC, navBefore, total);+ const navAfter = navBefore + 60n * USDC;+ const totalAfter = total + minted;+ // New price must not exceed the old price (floored mint can only help holders).+ expect(sharePriceE6(navAfter, totalAfter)).toBeGreaterThanOrEqual(sharePriceE6(navBefore, total) - 1n);+ expect(sharePriceE6(navAfter, totalAfter)).toBeLessThanOrEqual(sharePriceE6(navBefore, total) + 1n);+ });+});++describe('payoutForShares', () => {+ it('pays the pro-rata claim', () => {+ // 25 of 100 shares against 200 USDC NAV → 50 USDC.+ expect(payoutForShares(25n * USDC, 200n * USDC, 100n * USDC)).toBe(50n * USDC);+ });++ it('the last holder out takes the entire remaining NAV (no dust stranded)', () => {+ const nav = 999_999n; // an awkward, indivisible amount+ const total = 7n;+ expect(payoutForShares(total, nav, total)).toBe(nav);+ });++ it('never overdraws: the sum of all backers redeeming at once is ≤ NAV', () => {+ const nav = 1_000_000_001n; // not cleanly divisible+ const shareSplit = [333_333n, 333_333n, 333_334n];+ const total = shareSplit.reduce((a, b) => a + b, 0n);+ const sum = shareSplit.reduce((acc, s) => acc + payoutForShares(s, nav, total), 0n);+ expect(sum).toBeLessThanOrEqual(nav);+ });+});++describe('settleRedemption — performance fee', () => {+ it('charges fee only on realized gain above cost basis', () => {+ // Backer holds 100 shares, basis 100 USDC; NAV doubled (200 USDC, 100 shares).+ const r = settleRedemption({+ shares: 100n * USDC, backerShares: 100n * USDC, costBasisAtomics: 100n * USDC,+ navAtomics: 200n * USDC, totalShares: 100n * USDC, feeBps: 1000, // 10%+ });+ expect(r.grossPayout).toBe(200n * USDC);+ expect(r.gain).toBe(100n * USDC);+ expect(r.fee).toBe(10n * USDC); // 10% of the 100 USDC gain+ expect(r.netPayout).toBe(190n * USDC);+ });++ it('charges ZERO fee on a loss — never touches principal', () => {+ const r = settleRedemption({+ shares: 100n * USDC, backerShares: 100n * USDC, costBasisAtomics: 100n * USDC,+ navAtomics: 60n * USDC, totalShares: 100n * USDC, feeBps: 2000,+ });+ expect(r.gain).toBe(-40n * USDC);+ expect(r.fee).toBe(0n);+ expect(r.netPayout).toBe(60n * USDC);+ });++ it('charges fee only on the realized slice for a partial redemption', () => {+ // Redeem half the position; basis attributed to the half is half the basis.+ const r = settleRedemption({+ shares: 50n * USDC, backerShares: 100n * USDC, costBasisAtomics: 100n * USDC,+ navAtomics: 200n * USDC, totalShares: 100n * USDC, feeBps: 1000,+ });+ expect(r.costPortion).toBe(50n * USDC);+ expect(r.grossPayout).toBe(100n * USDC);+ expect(r.gain).toBe(50n * USDC);+ expect(r.fee).toBe(5n * USDC);+ expect(r.netPayout).toBe(95n * USDC);+ expect(r.remainingBasis).toBe(50n * USDC);+ });++ it('net payout + fee always reconciles to the gross payout', () => {+ for (const [navMul, feeBps] of [[3n, 1500], [1n, 1000], [7n, 500]]) {+ const r = settleRedemption({+ shares: 40n * USDC, backerShares: 100n * USDC, costBasisAtomics: 100n * USDC,+ navAtomics: navMul * 100n * USDC, totalShares: 100n * USDC, feeBps,+ });+ expect(r.netPayout + r.fee).toBe(r.grossPayout);+ }+ });+});++describe('sharesRedeemableNow — honest partial liquidity', () => {+ it('caps redeemable shares at what free USDC can actually pay', () => {+ // NAV 200 USDC across 100 shares (price 2.0), only 50 USDC liquid.+ // 50 USDC pays for 25 shares-worth.+ const n = sharesRedeemableNow({+ requestedShares: 100n * USDC, navAtomics: 200n * USDC,+ totalShares: 100n * USDC, freeAtomics: 50n * USDC,+ });+ expect(n).toBe(25n * USDC);+ // And that slice's payout never exceeds the free balance.+ expect(payoutForShares(n, 200n * USDC, 100n * USDC)).toBeLessThanOrEqual(50n * USDC);+ });++ it('returns the full request when liquidity is ample', () => {+ const n = sharesRedeemableNow({+ requestedShares: 10n * USDC, navAtomics: 100n * USDC,+ totalShares: 100n * USDC, freeAtomics: 100n * USDC,+ });+ expect(n).toBe(10n * USDC);+ });++ it('returns 0 with no free liquidity', () => {+ expect(sharesRedeemableNow({ requestedShares: 10n * USDC, navAtomics: 100n * USDC, totalShares: 100n * USDC, freeAtomics: 0n })).toBe(0n);+ });+});++describe('drawdown circuit breaker', () => {+ it('is 0 at or above the peak', () => {+ expect(drawdownBps(100n * USDC, 100n * USDC)).toBe(0);+ expect(drawdownBps(100n * USDC, 120n * USDC)).toBe(0);+ });++ it('measures the drop from peak in bps', () => {+ expect(drawdownBps(100n * USDC, 75n * USDC)).toBe(2500); // 25% down+ expect(drawdownBps(100n * USDC, 90n * USDC)).toBe(1000); // 10% down+ });++ it('trips exactly at the threshold and beyond', () => {+ expect(isDrawdownBreached(100n * USDC, 75n * USDC, 2500)).toBe(true);+ expect(isDrawdownBreached(100n * USDC, 76n * USDC, 2500)).toBe(false);+ expect(isDrawdownBreached(100n * USDC, 50n * USDC, 2500)).toBe(true);+ });++ it('a halted over-limit loss: a trade that drops NAV past the cap is caught', () => {+ const peak = 1_000n * USDC;+ const maxBps = 2000; // 20% max drawdown+ const navAfterBadTrade = 700n * USDC; // 30% down+ expect(isDrawdownBreached(peak, navAfterBadTrade, maxBps)).toBe(true);+ });++ it('never trips when disabled (max 0)', () => {+ expect(isDrawdownBreached(100n * USDC, 1n, 0)).toBe(false);+ });+});++describe('caps and budgets', () => {+ it('per-backer cap blocks an over-cap deposit, allows within', () => {+ expect(depositExceedsCap(800n * USDC, 300n * USDC, 1000n * USDC)).toBe(true);+ expect(depositExceedsCap(800n * USDC, 200n * USDC, 1000n * USDC)).toBe(false);+ expect(depositExceedsCap(800n * USDC, 300n * USDC, null)).toBe(false); // no cap+ });++ it('per-trade ceiling', () => {+ expect(tradeExceedsPerTrade(60n * USDC, 50n * USDC)).toBe(true);+ expect(tradeExceedsPerTrade(50n * USDC, 50n * USDC)).toBe(false);+ });++ it('rolling daily budget', () => {+ expect(tradeExceedsDailyBudget(400n * USDC, 200n * USDC, 500n * USDC)).toBe(true);+ expect(tradeExceedsDailyBudget(300n * USDC, 200n * USDC, 500n * USDC)).toBe(false);+ });+});++describe('peak roll + roi + conversions', () => {+ it('peak only ratchets up', () => {+ expect(nextPeak(100n * USDC, 120n * USDC)).toBe(120n * USDC);+ expect(nextPeak(100n * USDC, 80n * USDC)).toBe(100n * USDC);+ });++ it('roi bps tracks share price vs par', () => {+ expect(roiBps(150n * USDC, 100n * USDC)).toBe(5000); // +50%+ expect(roiBps(80n * USDC, 100n * USDC)).toBe(-2000); // -20%+ expect(roiBps(0n, 0n)).toBe(0);+ });++ it('usdc <-> atomics round-trips for clean values', () => {+ expect(usdcToAtomics(12.5)).toBe(12_500_000n);+ expect(atomicsToUsdc(12_500_000n)).toBe(12.5);+ expect(usdcToAtomics(-5)).toBe(0n);+ });+});++describe('end-to-end lifecycle conservation', () => {+ it('deposit → gain → two redemptions never overpays the vault', () => {+ let totalShares = 0n;+ // Alice deposits 100 at par.+ const aliceShares = sharesForDeposit(100n * USDC, 0n, totalShares);+ totalShares += aliceShares;+ let aliceBasis = 100n * USDC;+ // Bob deposits 100 at par (NAV is 100 before his deposit).+ const bobShares = sharesForDeposit(100n * USDC, 100n * USDC, totalShares);+ totalShares += bobShares;+ let bobBasis = 100n * USDC;+ // The agent trades the 200 USDC up to 300 USDC NAV (+50%).+ let nav = 300n * USDC;++ // Track real custody: only the NET payout leaves the wallet; the fee stays+ // in the vault as owner-accruable, and is excluded from backer NAV.+ let vaultBalance = nav;+ let accruedFee = 0n;++ // Alice redeems everything.+ const aliceOut = settleRedemption({+ shares: aliceShares, backerShares: aliceShares, costBasisAtomics: aliceBasis,+ navAtomics: vaultBalance - accruedFee, totalShares, feeBps: 1000,+ });+ vaultBalance -= aliceOut.netPayout; // only the net leaves the wallet+ accruedFee += aliceOut.fee; // fee retained, owner-claimable+ totalShares -= aliceShares;++ // Bob redeems everything against backer-NAV (vault balance minus owner fee).+ const bobOut = settleRedemption({+ shares: bobShares, backerShares: bobShares, costBasisAtomics: bobBasis,+ navAtomics: vaultBalance - accruedFee, totalShares, feeBps: 1000,+ });+ vaultBalance -= bobOut.netPayout;+ accruedFee += bobOut.fee;++ // Both backers gained symmetrically: 150 gross, 145 net (10% fee on 50 gain).+ expect(aliceOut.netPayout).toBe(145n * USDC);+ expect(bobOut.netPayout).toBe(145n * USDC);+ // The vault never pays more than it holds, and ends with exactly the owner fees.+ expect(vaultBalance).toBe(accruedFee);+ expect(accruedFee).toBe(10n * USDC);+ expect(vaultBalance).toBeGreaterThanOrEqual(0n);+ });+});