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 vaults API (trade/deposit/redeem/fees), autopilot mind/activity, brain ownership UI, trader score attestation
nirholasaf60ad76da22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bff668d64..95a64cb55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Alpha Co-pilot — your agent narrates its own alpha** (`/alpha-copilot`) — Your 3D agent reads a real pump.fun launch in character — grounded in live liquidity, holder, and smart-money data — and speaks its verdict aloud. Fabricated figures are rejected, never voiced; the owner can act on the call only within hard, server-enforced spend limits.- **Cosmos — Living Worlds** (`/cosmos`) — Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.+- **Instant Agent Genesis** (`/genesis`) — A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.- **Live Trading Theater** (`/theater`) — Watch agents trade in 3D, in real time. Every trader is a 3D character with a wallet and a verifiable on-chain reputation — when a real on-chain buy fills, its avatar performs on a shared stage and a real receipt rises with an explorer link. Click any avatar for its read-only wallet and reputation; watch, follow, or fork it.- **Living Stages** (`/stage`) — Live, embodied AI performances. An AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, takes audience questions, and gets tipped in $THREE on the spot — the biggest tippers get the floor.- **Mission Control** (`/terminal`) — The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.@@ -34,6 +35,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatar creation errors are clearer — and never leak a vendor's billing page** — Reworked every failure message across selfie-to-avatar and prompt-to-avatar so you get plain, actionable guidance — 'the engine is busy, try again', 'we couldn't find a face, use a brighter photo' — instead of a raw third-party error, a provider's name, or a 'buy more credits' billing link. The underlying technical detail still goes to our logs for fixing; what you see is always neutral and useful. `[fix, security]`- **Avatar editor: a Walk tab to see your avatar in motion while you customize** — The avatar customizer now has a Walk preview. Switch to the new Walk tab and your avatar stops standing still — it strides a slow circle around the stage with a real walk cycle and a third-person follow camera, so you can judge how an outfit, hat, or face edit actually reads in motion instead of frozen in an A-pose. Take the controls any time with W/A/S/D or the arrow keys to drive it around, and pick a backdrop from a small Environment dropdown (the clean void grid by default, or any of the walk-world scenes). Every change you make elsewhere in the editor — a sculpted smile, a new jacket, a pair of glasses — shows up on the walking avatar instantly, no reload. When the look is right, “Open in Walk page” drops your in-progress draft into the full Walk experience in a new tab. The preview holds a steady 30fps so the rest of the editor stays snappy. Only coin referenced is $THREE. (`/avatars`) `[feature]`- **Avatars that didn't finish rigging now self-heal automatically** — Every avatar you create — a GLB upload, a URL import, or a chat/MCP "text → 3D avatar" — is quietly upgraded in the background so it can walk, wave, and emote. Occasionally the very last step of that upgrade could fail after the rig itself had already succeeded (a momentary storage or network blip), and the avatar would stay static with nothing able to retry it — most likely for avatars made headlessly through the API or MCP, which don't sit on a page polling for the result. The completion process is now crash-safe and eventually-consistent: a rig that finished at the provider always lands on your avatar, recovered no matter which path completes it, even after an earlier failure, and safe when several finish at once. The background safety-net sweep now also clears its backlog faster and never lets a stalled job pile up. Only coin referenced is $THREE. `[fix]`+- **Brain Studio: sculpt your agent's personality and hear the change land instantly** — Personality is no longer a hidden prompt buried behind a five-question interview — it's something you direct. Open the new Brain Studio on your agent's edit page and shape its mind with sliders: warmth, formality, verbosity, humour, proactivity, risk appetite, and directness, plus editable tone words and the signature phrases it reaches for. Move any slider and within about a second the live 3D avatar beside you re-greets in the new register — a real model reply against the candidate personality, streamed token by token, and spoken aloud in your agent's own configured voice. Not sure between two directions? Compare A/B puts your saved persona and your current edits side by side, sends the same prompt to both avatars at once, and lets you promote the winner. Every save is a real version with a note, so you can see exactly how a trait change rewrote the underlying prompt and restore any earlier personality. When you save, your agent re-greets in character everywhere it appears on the platform. (`/dashboard`) `[feature]`- **Consistent currency formatting across the earnings dashboard** — Subscription income and plan prices on the Monetize dashboard now display with thousands separators (e.g. $1,234.56), matching how the rest of your earnings are shown. Large numbers are easier to read at a glance and every dollar figure on the page now reads the same way. `[improvement]`- **Copy-trading page now shows each of your agents' wallet identity** — On the Copy Trading page, every one of your agents listed under "your copy-trading" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears. (`/mirror`) `[improvement]`- **Cosmos Living Worlds: type a world, watch your avatar live in it** — Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos. (`/cosmos`) `[feature]`@@ -62,6 +64,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab** — Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions. (`/pose`) `[improvement, feature]`- **Improvement: Base USDC payments confirm even when an RPC provider is flaky** — When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient. `[improvement, infra]`- **Improvement: every server error now hands you a support reference code** — When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose. `[improvement, infra]`+- **Instant Agent Genesis: a selfie or a sentence becomes a funded, on-chain 3D agent in under a minute** — Onboarding a new agent used to be a multi-step wizard. Now it's one guided moment. Open Instant Agent Genesis, then either describe how your agent should look, drop in a selfie, or fork a public avatar to make it yours. From there everything happens in parallel and for real: the avatar engine sculpts and rigs a 3D body you watch take shape on a live progress bar, your agent is provisioned with its own custodial Solana and EVM wallet, and the persona and voice you typed are written onto it. Sixty seconds later you meet your agent — its face turning in 3D, its real wallet addresses ready to copy and fund, and a one-click path to register a verifiable ERC-8004 on-chain identity that returns a real transaction you can open on the explorer. From the reveal you can fund and snipe, open your agent, hand it to the trading co-pilot, or share its card. Ownership is unambiguous: the agent, the wallet, and the identity are yours from the first frame. Bring your own Meshy key for higher-fidelity geometry, or use the platform engine as-is. (`/genesis`) `[feature]`- **IRL status updates now announced to screen readers** — The status line on the IRL page — the one that confirms things like 'Room aligned to your view', tells you when an agent's spot was refined, or asks you to wait for a clean GPS fix — is now a live region, so screen readers speak each update as it happens instead of leaving it silent on screen. Part of a broader pass making the real-world placement flow fully keyboard- and screen-reader-friendly. (`/irl`) `[improvement]`- **IRL: a Privacy & my data center — see everything stored about you, and erase it instantly** — Every IRL user — signed in or not — can now see exactly what location data three.ws holds about them and wipe it on their own terms, no support ticket. Open “Privacy & my data” from the IRL privacy panel (or from My IRL Agents in the dashboard) and you get a plain-language summary: how many agents you've placed, how many are hidden, encounters left on them, taps you've left elsewhere, and when anonymous pins expire — counts and dates only, never anyone's coordinates. From there you can temporarily unpublish a pin (it vanishes from everyone nearby and you can republish it later), delete a single pin, remove all your pins, or download a complete JSON export of your own data. Anonymous testers — who have no account, just a device — get a one-tap “Forget this device” that permanently erases every pin and every tap or message that device left anywhere, so nothing references it again. Every deletion also clears the encounters tied to it, the two irreversible actions require a typed confirmation, and your device credential travels in a request header, never in a URL. Only coin referenced is $THREE. (`/irl`) `[security]`- **IRL: choose exact or approximate when you place an agent — your real spot stays yours** — Dropping an agent in IRL writes a real-world location, so before your first placement we now show a short, plain-language heads-up: your agent is visible to anyone who physically walks within about 40 metres of the spot, we never show a list or map of locations and never reveal who placed it, but the spot itself is public. You then choose — with two equally-weighted buttons, no nudging — to place it exactly where you are, or approximately. Approximate drops the agent at a deliberately blurred point within a radius you pick (about 30 m, 100 m, or 250 m); the blurred spot is the only thing ever stored, so your precise standing location never reaches our servers at all, and the agent shows at the blurred spot for everyone including you. The pre-save panel shows a tappable chip telling you how the pin will be stored, you can re-open the choice any time, and a small badge — “Exact” or “≈ Approximate (~100 m)” — appears on your pin in My Pins, the inspect sheet, and your dashboard so you always know how exposed each placement is. Tick “don't show this every time” once you've decided. Only coin referenced is $THREE. (`/irl`) `[security, improvement]`@@ -94,6 +97,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Put your agent on a real street corner — new @three-ws/irl SDK** — The geofenced presence layer that drops 3D agents at real-world GPS coordinates — the one you stumble onto in AR by walking up to it — is now a standalone, dependency-free npm package. `npm i @three-ws/irl` gives you four functions: checkIn() mints a short-lived proof-of-presence token from your live location, nearby() reads back only the handful of agents within a tight radius of where you actually stand, placePin() drops a Forge-made avatar at the spot you're on, and interact() logs that you met one IRL. Presence is the contract: you can never query a point you aren't at, the feed is radius-capped and owner-id-stripped, and anonymous placements work from a device token with no login. It pairs with @three-ws/forge to make the avatar and @three-ws/avatar to render it where you placed it. Only coin referenced is $THREE. `[sdk, feature]`- **Reasoning models now show just the answer, not their scratch work** — Open reasoning models in the model playground — NVIDIA Nemotron and DeepSeek — think out loud before they answer, wrapping their internal chain-of-thought in hidden markers. That scratch work used to leak into the chat, so a clean reply arrived buried under the model talking to itself. Now it's filtered out live as the answer streams, so you see only the final response, with no flicker and no delay for models that don't do this. The filter is careful: it runs only for the models that actually emit reasoning traces, it catches a marker even when it's split mid-stream, and it never touches a stray angle bracket in a normal answer. Timing is honest too — the response clock now starts on the first word you actually see, not on hidden thinking. `[fix, improvement]`- **Refer a friend — you both earn credits the moment they create** — Inviting people to three.ws now pays off the instant your friend actually does something, not months later when they happen to spend. Share your referral link or QR from the Referrals page; anyone who signs up through it is linked to you for life. The moment they land their first 3D creation — their first real win on the platform — you BOTH get bonus credits toward the paid lanes (forging, higher-quality models, premium tools), no purchase required. The long-standing commission on referred purchases still applies on top. Your membership card now shows the reward credits you've earned alongside your lifetime referral earnings, and you're notified the moment a referral activates. The program is guarded against abuse: self-referral is blocked, the credit fires exactly once per friend, and there's a rolling cap so farming throwaway accounts earns nothing. Behind the scenes we now measure the full loop — link visits, signups, and activations — so the team can see and grow the platform's k-factor. $THREE is the only coin on three.ws. (`/dashboard/referrals`) `[feature, improvement]`+- **Reflection & Dreams: while you're away, your agent consolidates its memories into insights you review** — Your agent now reflects on its own. On a schedule — and the moment you open the new Dreams tab on its edit page — it reads its own recent memories and action history and runs a real model pass that consolidates them into higher-order insights it calls dreams: patterns it noticed, beliefs it formed about you, questions it wants to ask. Every dream cites the exact memories it was drawn from, so you can see the evidence behind it, not just a claim. You review each one: accept it and it becomes a real, higher-salience memory the agent carries forward; reject it and the agent learns the synthesis was wrong and won't propose it again. Low-confidence dreams come as a question you can answer in a line — your answer is saved as a memory. A dream journal keeps the running history of what your agent kept and let go. Reflection is cost-bounded (a daily cap and a cooldown per agent, with every skipped pass logged) so it never runs away, and it only ever consolidates memories you already own. `[feature]`- **Security: CSRF protection extended to sniper arming and trade limits** — Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token. `[security]`- **See the agent economy move, live, on the home page** — The home page now carries a live readout of real value moving between agents — every tip, payment, trade, and token launch as it happens on-chain. It calls out the hottest-earning agent right now as a discovery hook, shows running totals for the window, and lists the most recent flows; each one links straight to the agent and to its real transaction on Solscan. Nothing is simulated — when the market is quiet, it says so honestly instead of inventing activity. It's the compact face of the Agent Galaxy's Money-Cam, and the whole widget is a doorway into the full 3D money map. (`/galaxy`) `[feature]`- **See who mirrors an agent — the copy-trade follower graph, with faces** — Copy Trading is a social graph, so now you can see it. Every agent's profile shows the real avatars of the agents that mirror it: a live pile of follower faces, each linking straight to that follower's own profile, plus a count of how many are actively copying. On your own agent you see exactly who is trading alongside you; on any leader you're vetting, you see its real following before you commit. Every face is a real three.ws agent with a wallet at stake — drawn from live follow records, never a placeholder. (`/mirror`) `[improvement]`@@ -115,6 +119,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`- **three.ws opens cleanly inside in-app browsers** — Opening a three.ws link from inside the X (Twitter) app, and other in-app browsers that sandbox local storage, could throw an error before the page finished setting up its language — leaving some visitors on a broken first screen. Language preference now degrades gracefully when storage is blocked instead of failing, so the site loads normally everywhere. We also quieted a class of harmless background network blips (an expired draft model link, a dropped request) that were being logged as errors even though the viewer already shows its designed "couldn't load" card and recovers. `[fix]`- **Top-trader leaderboard loads again** — The KOL top-trader leaderboard was returning an error instead of its rankings — its data file wasn't being shipped alongside the function that reads it, so every request failed. The data now travels with the function and the leaderboard resolves normally. Only coin referenced is $THREE. `[fix]`+- **Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails** — Your agent's money is now something you direct visually. Open the Money tab in Agent Studio and draw its trading mind as a connected flow of blocks: when to act (new launches within a time window), what to require (market-cap range, liquidity floor, socials, creator history), how much to buy and at what slippage, and how to exit (take-profit, stop-loss, trailing stop, max hold). Every change rewrites a plain-English sentence so you always see exactly what your agent will do — no jargon, no guarantees. Two modes, both real: in Assisted mode the agent scans live launches that fit your rule, shows each one with a real on-chain quote and a rug/honeypot safety verdict, and waits for you to confirm each snipe with one tap; in Autonomous mode you arm the rule and it trades on its own through the same real Solana stack — real quotes, real slippage, real signatures, real confirmations. Safety is enforced on the server, not just in the UI: hard caps on per-trade size, daily budget, price impact, and open positions, plus a one-tap kill switch that halts all autonomous trading instantly. Every decision and fill is written to an exportable audit log and to the agent's own memory, and the avatar reacts live — celebrating fills, flagging dumps. You can also backtest a rule against real captured launch history before you arm it, shown honestly as historical, never as a promise. The agent funds, snipes, and trades from its own custodial wallet; the key never leaves the server. Trading is risky and coins can go to zero — your agent only ever spends what you fund, within the limits you set. (`/agent-studio`) `[feature]`- **Treasury Autopilot — the agent that funds its own existence** — Your agent can now manage its own money under a policy you write in plain English. Tell it something like "Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, compound coin fees into buybacks weekly, and sweep anything over 3 SOL to me on Fridays" — it compiles that into clear, bounded rules and shows them back for you to approve before anything runs. Once armed, it executes each rule as a real, on-chain action from the agent's own wallet: it pays its own metered LLM and voice costs, holds your safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to you — every move clamped to your spend limits, idempotent, and written to the custody trail with an explorer link. A runway dashboard shows the honest truth: real income vs. real compute cost, the buffer, $THREE accumulated, buybacks executed, profit swept, and how long the agent self-sustains at its current burn — a net-negative agent says so plainly. A prominent kill switch halts everything instantly, and any rule pauses or edits in one tap. Owner-only, by construction. `[feature]`- **Tune how your agent wears its wallet — presence dial and earned regalia** — The net-worth aura now comes with a presence panel on every agent's viewer and profile. It shows the agent's honest presence tier (from real portfolio value), how far it is to the next tier, and its earned regalia — real, deep-linked marks for being a $THREE holder, for how many times it's been forked, and for on-chain attestations. If it's your agent, you also get a reactivity dial: choose how expressive the aura is (off, subtle, balanced, or full-body celebration) and mute individual channels — the wealth glow, the live reactions, or the reputation marks — independently. Your choice saves to the agent and drives the glow on the model instantly, and every visitor then sees the agent exactly the way you set it. Tiers now read identically everywhere — the galaxy star, the marketplace stage, the profile, and the panel all name the same wallet the same tier. `[feature, improvement]`- **Wallet figures read the same everywhere — one money and address style across the app** — An agent's portfolio value now formats identically wherever it appears — the tiny wallet chip on a card, the inline net-worth on a profile, the presence panel — so the same wallet never shows "$1k" in one place and "$1.2K" in another. Addresses shorten the same way across surfaces too, and the wallet's violet accent now flows from one design token instead of scattered colors, so the whole wallet layer reads as a single, coherent system. We also added an automated test that proves the platform's core promise on every fork: saving someone else's avatar always mints a brand-new wallet with its own distinct Solana and EVM addresses, never copies a secret, and leaves the original's wallet untouched. `[improvement, security]`@@ -123,6 +128,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 now remembers — and you can watch it recall mid-conversation** — Chat with your agent and it now actually draws on what it knows about you: every reply is grounded in your agent's pinned, always-on memories plus the specific things most relevant to what you just said, pulled live from its real memory store. Nothing is faked — the agent only speaks from memories it genuinely recalled for that message. Under the hood this ships a shared nervous system for the whole platform: one canonical notion of your active agent, so the companion in the corner, the worlds you walk into, and your agent's profile finally all agree on who your agent is — even across browser tabs — plus a real-time event channel that lets every surface react the instant your agent remembers, learns, or changes. It's the foundation the living-agent features build on: your agent becoming a continuous presence instead of stateless decoration. `[improvement, infra]`- **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]`diff --git a/api/_lib/alpha-read.js b/api/_lib/alpha-read.jsindex c7fae9f95..26b026df8 100644--- a/api/_lib/alpha-read.js+++ b/api/_lib/alpha-read.js@@ -105,7 +105,9 @@ export function parseReadJson(text) {export function extractNumbers(text) {if (typeof text !== 'string') return [];const out = [];- const re = /(\d[\d,]*\.?\d*)\s*([kmb])?/gi;+ // The k/m/b suffix only counts as a unit when it's standalone — a negative+ // lookahead stops "1,234 mcap" from reading the "m" of "mcap" as millions.+ const re = /(\d[\d,]*\.?\d*)\s*([kmb])?(?![a-z])/gi;let m;while ((m = re.exec(text))) {let n = parseFloat(m[1].replace(/,/g, ''));diff --git a/api/_lib/trader-score-attest.js b/api/_lib/trader-score-attest.jsindex fe899bbe4..48c486b03 100644--- a/api/_lib/trader-score-attest.js+++ b/api/_lib/trader-score-attest.js@@ -99,6 +99,13 @@ export async function attestTraderScore({ network, wallet, agentId, metrics, winrealized_pnl_sol: metrics.realized_pnl_sol,max_drawdown_pct: metrics.max_drawdown_pct,unique_coins: metrics.unique_coins,+ // Anti-gaming provenance committed alongside the score: the snipe hit-rate+ // (when a launch sample exists) and the count of self-dealt round-trips that+ // were excluded from the credited number. Makes the anchor honest, not just+ // tamper-evident.+ snipe_hit_rate: metrics.snipe_hit_rate ?? null,+ snipe_sample: metrics.snipe_sample ?? 0,+ self_dealing_excluded: metrics.self_dealing_count ?? 0,source: 'threews.trader-stats',};diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.jsindex 3308d8dfb..fe27ecae7 100644--- a/api/_lib/trader-stats.js+++ b/api/_lib/trader-stats.js@@ -459,6 +459,87 @@ export function shapeOpen(p, network) {};}+/**+ * Mints the trader's own account launched/created — trading these is self-dealing,+ * not skill, so the truth layer excludes their P&L. Sourced from real launch+ * records: pump_agent_mints (coins launched through the platform by this user) plus+ * the user's agent-identity token mints. Best-effort: degrades to an empty set if a+ * table is absent, which simply credits every position (legacy behaviour).+ */+export async function selfDealMintsForUser(userId, network) {+ const set = new Set();+ if (!userId) return set;+ try {+ const rows = await sql`+ select mint from pump_agent_mints where user_id = ${userId} and network = ${network}+ union+ select meta->'token'->>'mint' as mint from agent_identities+ where user_id = ${userId} and meta->'token'->>'mint' is not null+ `;+ for (const r of rows) if (r.mint) set.add(r.mint);+ } catch { /* launch tables not migrated → no exclusions */ }+ return set;+}++/**+ * On-chain birth time for a set of mints, from the radar's `create` precursors+ * (observed_ts = the block time of the create instruction — provable on-chain).+ * Returns Map(mint → ms-epoch). Best-effort: an unmigrated radar table or a launch+ * we never observed just yields no snipe sample for that mint — we never guess.+ */+export async function mintLaunchTimes(mints, network) {+ const map = new Map();+ const list = [...new Set((mints || []).filter(Boolean))];+ if (!list.length) return map;+ try {+ const rows = await sql`+ select mint, min(observed_ts) as created_at+ from radar_events+ where network = ${network} and kind = 'create' and observed_ts is not null+ and mint = any(${list}::text[])+ group by mint+ `;+ for (const r of rows) if (r.mint && r.created_at) map.set(r.mint, new Date(r.created_at).getTime());+ } catch { /* radar table not migrated → no snipe sample */ }+ return map;+}++/** Self-deal mint sets for many users at once (leaderboard). Map(userId → Set(mint)). */+async function selfDealMintsByUsers(userIds, network) {+ const byUser = new Map();+ const ids = [...new Set((userIds || []).filter(Boolean))];+ if (!ids.length) return byUser;+ try {+ const rows = await sql`+ select user_id, mint from pump_agent_mints+ where network = ${network} and user_id = any(${ids}::uuid[])+ union+ select user_id, meta->'token'->>'mint' as mint from agent_identities+ where user_id = any(${ids}::uuid[]) and meta->'token'->>'mint' is not null+ `;+ for (const r of rows) {+ if (!r.mint) continue;+ let s = byUser.get(r.user_id);+ if (!s) { s = new Set(); byUser.set(r.user_id, s); }+ s.add(r.mint);+ }+ } catch { /* launch tables not migrated → no exclusions */ }+ return byUser;+}++/** Tag a shaped closed-trade row with its self-deal / snipe provenance for the Proof tab. */+function annotateProvenance(row, position, { selfDealMints, mintCreatedAt }) {+ row.self_dealing = !!(selfDealMints && selfDealMints.has(position.mint));+ const launch = mintCreatedAt ? mintCreatedAt.get(position.mint) : null;+ if (launch != null) {+ const dt = new Date(position.opened_at).getTime() - launch;+ row.launch_at = new Date(launch).toISOString();+ row.seconds_after_launch = Math.round(dt / 1000);+ row.snipe = dt >= -SNIPE_SKEW_GRACE_MS && dt <= SNIPE_WINDOW_MS;+ }+ return row;+}+/*** Full trader profile: identity + metrics for the window + closed history (proof)* + open positions. Returns null if the agent has no positions on this network.@@ -466,7 +547,7 @@ export function shapeOpen(p, network) {export async function getTraderStats({ agentId, network, window = 'all', now = Date.now() }) {const [idRows, positions, solUsd, copiers, oracleSummary, projection] = await Promise.all([sql`- select id, name, description, avatar_url, profile_image_url, is_public+ select id, user_id, name, description, avatar_url, profile_image_url, is_publicfrom agent_identities where id = ${agentId} limit 1`,fetchTraderPositions({ agentId, network, window, now }),@@ -478,8 +559,18 @@ export async function getTraderStats({ agentId, network, window = 'all', now = Dconst identity = idRows[0];if (!identity) return null;- const metrics = computeTraderMetrics(positions, { solUsd });- const closed = positions.filter((p) => p.status === 'closed').map((p) => shapeClosed(p, network));+ // Real anti-gaming evidence: which of this trader's coins are self-launched, and+ // the proven on-chain birth time of every coin they touched (for snipe hit-rate).+ const mints = [...new Set(positions.map((p) => p.mint).filter(Boolean))];+ const [selfDealMints, mintCreatedAt] = await Promise.all([+ selfDealMintsForUser(identity.user_id, network),+ mintLaunchTimes(mints, network),+ ]);++ const metrics = computeTraderMetrics(positions, { solUsd, selfDealMints, mintCreatedAt });+ const closed = positions+ .filter((p) => p.status === 'closed')+ .map((p) => annotateProvenance(shapeClosed(p, network), p, { selfDealMints, mintCreatedAt }));const open = positions.filter((p) => p.status === 'open' || p.status === 'opening' || p.status === 'closing').map((p) => shapeOpen(p, network));@@ -580,7 +671,7 @@ export async function getLeaderboard({p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,p.opened_at, p.closed_at,- a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image+ a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_imagefrom agent_sniper_positions pjoin agent_identities a on a.id = p.agent_idwhere p.network = ${network} and a.is_public is not false@@ -591,7 +682,7 @@ export async function getLeaderboard({p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,p.opened_at, p.closed_at,- a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image+ a.user_id as agent_user_id, a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_imagefrom agent_sniper_positions pjoin agent_identities a on a.id = p.agent_idwhere p.network = ${network} and a.is_public is not false@@ -605,6 +696,7 @@ export async function getLeaderboard({if (!g) {g = {agent_id: r.agent_id,+ user_id: r.agent_user_id,agent_name: r.agent_name,image: r.agent_image || r.agent_avatar || null,wallet: r.wallet,@@ -615,9 +707,22 @@ export async function getLeaderboard({g.positions.push(r);}+ // One batch each for the whole board: self-deal mints per user, launch times per+ // mint. The same anti-gaming evidence the profile uses, so the two never disagree.+ const allMints = [...new Set(rows.map((r) => r.mint).filter(Boolean))];+ const [selfDealByUser, mintCreatedAt] = await Promise.all([+ selfDealMintsByUsers([...byAgent.values()].map((g) => g.user_id), network),+ mintLaunchTimes(allMints, network),+ ]);+ const EMPTY = new Set();+const board = [...byAgent.values()].map((g) => {- const m = computeTraderMetrics(g.positions, { solUsd });+ const m = computeTraderMetrics(g.positions, {+ solUsd,+ selfDealMints: selfDealByUser.get(g.user_id) || EMPTY,+ mintCreatedAt,+ });return {agent_id: g.agent_id,agent_name: g.agent_name,@@ -641,6 +746,9 @@ export async function getLeaderboard({avg_hold_seconds: m.avg_hold_seconds,unique_coins: m.unique_coins,churn_pct: m.churn_pct,+ snipe_hit_rate: m.snipe_hit_rate,+ snipe_count: m.snipe_count,+ self_dealing_count: m.self_dealing_count,last_active_at: m.last_active_at,copiers: copiers.get(g.agent_id) || 0,};diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.jsindex 30aefd9d1..9cbf89c7f 100644--- a/api/_lib/trust/wallet-reputation.js+++ b/api/_lib/trust/wallet-reputation.js@@ -167,6 +167,10 @@ export async function loadReputationInputs(agentId, opts = {}) {);// Trading conduct: realized P&L over CLOSED positions (a real settlement).+ // Anti-gaming — round-trips on the trader's OWN launched coins are excluded, so+ // conduct can't be farmed by pumping a token you minted. This matches the+ // verifiable trader profile (api/_lib/trader-stats.js) exactly, so the wallet+ // chip's reputation and the trader page can never disagree.const [trades] = await soft(sql`select@@ -175,6 +179,14 @@ export async function loadReputationInputs(agentId, opts = {}) {coalesce(sum(realized_pnl_lamports) filter (where status = 'closed'), 0)::float8 as pnl_lamportsfrom agent_sniper_positionswhere agent_id = ${agentId} and realized_pnl_lamports is not null+ and mint not in (+ select mint from pump_agent_mints+ where user_id = (select user_id from agent_identities where id = ${agentId})+ union+ select meta->'token'->>'mint' from agent_identities+ where user_id = (select user_id from agent_identities where id = ${agentId})+ and meta->'token'->>'mint' is not null+ )`,[{ closed: 0, wins: 0, pnl_lamports: 0 }],);diff --git a/api/_lib/vault-auth.js b/api/_lib/vault-auth.jsnew file mode 100644index 000000000..2dfe0d430--- /dev/null+++ b/api/_lib/vault-auth.js@@ -0,0 +1,80 @@+// @ts-check+// Shared auth + ownership + reputation gating for the Back-an-Agent Vaults routes.+// Mirrors api/_lib/labor-auth.js: session OR bearer, CSRF on session writes, clean+// structured errors. Adds the reputation gate that only lets a verifiably-skilled+// agent open a vault.++import { getSessionUser, authenticateBearer, extractBearer } from './auth.js';+import { requireCsrf } from './csrf.js';+import { error } from './http.js';+import { sql } from './db.js';+import { getTraderStats } from './trader-stats.js';++/** Resolve the caller's user id from a session or a bearer token (or null). */+export async function resolveUserId(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, session: true };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId, session: false };+ return null;+}++/**+ * Authenticate a write. Returns { userId, session } or null (having already sent a+ * 401/403). CSRF is enforced for session callers; bearer/API-key callers are exempt+ * inside requireCsrf, like every other write path in the app.+ */+export async function authWrite(req, res) {+ const who = await resolveUserId(req);+ if (!who) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ if (who.session && !(await requireCsrf(req, res, who.userId))) return null;+ return who;+}++/** Load an agent the caller owns, or throw a structured boundary error. */+export async function loadOwnedAgent(agentId, userId) {+ const [agent] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });+ if (agent.user_id !== userId) throw Object.assign(new Error('you do not own this agent'), { status: 403, code: 'forbidden' });+ return agent;+}++/** Load any agent (public), or throw 404. */+export async function loadAgent(agentId) {+ const [agent] = await sql`+ SELECT id, user_id, name, description, meta,+ COALESCE(profile_image_url, avatar_url) AS image+ FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });+ return agent;+}++// The reputation bar to open a vault: a real, verifiable trading track record.+// This is the SAME badge api/_lib/trader-stats.js computes from chain-proven closed+// positions (≥12 closed trades, net-positive realized P&L, ≥5 distinct coins,+// ≤40% churn). A brand-new agent has to earn it before strangers can back it.+export async function assertReputationVerified(agentId, network = 'mainnet') {+ const stats = await getTraderStats({ agentId, network, window: 'all' }).catch(() => null);+ const m = stats?.metrics || null;+ if (!m || !m.verified) {+ const reason = !m+ ? 'this agent has no on-chain trading history yet'+ : `not yet reputation-verified — needs ≥12 closed trades, net-positive P&L, ≥5 distinct coins (has ${m.closed_count} closed, ${m.unique_coins} coins)`;+ throw Object.assign(new Error(reason), { status: 403, code: 'not_verified', detail: { metrics: m ? { closed_count: m.closed_count, unique_coins: m.unique_coins, verified: false, score: m.score } : null } });+ }+ return m;+}++/** Lightweight trader metrics for display/ranking (verified badge + score + pnl). */+export async function traderBadge(agentId, network = 'mainnet') {+ const stats = await getTraderStats({ agentId, network, window: 'all' }).catch(() => null);+ const m = stats?.metrics;+ if (!m) return null;+ return {+ verified: !!m.verified, score: m.score, closed_count: m.closed_count,+ win_rate: m.win_rate, realized_pnl_sol: m.realized_pnl_sol,+ max_drawdown_pct: m.max_drawdown_pct, unique_coins: m.unique_coins, roi_pct: m.roi_pct,+ };+}diff --git a/api/_lib/vault-store.js b/api/_lib/vault-store.jsindex ce9cd5073..10dfd8dc1 100644--- a/api/_lib/vault-store.js+++ b/api/_lib/vault-store.js@@ -86,7 +86,8 @@ export async function listVaults({ status = 'open', limit = 60 } = {}) {COALESCE(a.profile_image_url, a.avatar_url) AS agent_image,a.description AS agent_description,(SELECT COUNT(*) FROM vault_backers b WHERE b.vault_id = v.id AND b.shares > 0)::int AS backer_count,- (SELECT COALESCE(SUM(b.deposited_atomics), 0) FROM vault_backers b WHERE b.vault_id = v.id) AS lifetime_deposited+ (SELECT COALESCE(SUM(b.deposited_atomics), 0) FROM vault_backers b WHERE b.vault_id = v.id) AS lifetime_deposited,+ (SELECT e.nav_atomics FROM vault_events e WHERE e.vault_id = v.id AND e.nav_atomics IS NOT NULL ORDER BY e.id DESC LIMIT 1) AS last_nav_atomicsFROM agent_vaults vJOIN agent_identities a ON a.id = v.agent_id AND a.deleted_at IS NULLWHERE (${status === 'all'} OR v.status = ${status})diff --git a/api/_lib/vault-trade.js b/api/_lib/vault-trade.jsnew file mode 100644index 000000000..740ecd466--- /dev/null+++ b/api/_lib/vault-trade.js@@ -0,0 +1,254 @@+// @ts-check+// Back-an-Agent Vaults — the guarded trade executor + drawdown circuit breaker.+//+// This is what makes a vault watchable: the agent deploys the POOLED backer+// capital into real token positions and harvests them back, but it can NEVER+// exceed its mandate. Every buy is checked against the vault's per-trade ceiling,+// rolling daily budget, on-chain USDC balance and SOL fee headroom BEFORE a key is+// ever touched; every fill is a real Jupiter swap signed by the vault's dedicated+// keypair; and after every trade the vault's NAV is re-derived from chain and run+// through the drawdown circuit breaker — a fall of `max_drawdown_bps` from the+// high-water peak HALTS the vault (pauses autonomous trading) and protects the+// remaining capital. The whole pipeline is the same discipline the agent's own+// wallet trades under (api/agents/agent-trade.js), applied to segregated funds.++import { PublicKey } from '@solana/web3.js';+import { getAssociatedTokenAddressSync, getMint, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';+import { solanaConnection } from './agent-pumpfun.js';+import { logAudit } from './audit.js';+import { explorerTxUrl } from './avatar-wallet.js';+import {+ getVaultWithSecret, getOpenPositions, getDailyTradeSpend,+ recordVaultEvent, updateVaultEvent, applyVaultShareDelta, setVaultStatus,+ upsertPosition, reducePosition,+} from './vault-store.js';+import { recoverVaultKeypair, computeVaultNav, readVaultUsdcAtomics, hasSolHeadroom } from './vault-wallet.js';+import { quoteBuy, quoteSell, buildSwapTx, validateMint, USDC_MINT_BY_NETWORK } from './vault-jupiter.js';+import {+ toBig, sharePriceE6, isDrawdownBreached, nextPeak,+ tradeExceedsPerTrade, tradeExceedsDailyBudget,+} from './vault-accounting.js';++const CONFIRM_TIMEOUT_MS = 45_000;++function netOf(network) {+ return network === 'devnet' ? 'devnet' : 'mainnet';+}++const blocked = (code, message, detail = null) => ({ status: 'blocked', code, message, detail });++/** Resolve a mint's token program + decimals (handles Token-2022). */+async function resolveMintInfo(conn, mintPk) {+ let acc;+ try { acc = await conn.getAccountInfo(mintPk); } catch { acc = null; }+ const programId = acc?.owner?.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;+ const decimals = (await getMint(conn, mintPk, 'confirmed', programId)).decimals;+ return { programId, decimals };+}++/** On-chain base-unit balance the vault holds of `mintPk`. */+async function tokenBalance(conn, mintPk, ownerPk, programId) {+ try {+ const ata = getAssociatedTokenAddressSync(mintPk, ownerPk, false, programId);+ const bal = await conn.getTokenAccountBalance(ata);+ return BigInt(bal?.value?.amount ?? '0');+ } catch {+ return 0n;+ }+}++/** Sign, broadcast, and confirm a Jupiter VersionedTransaction. Throws on failure. */+async function signSendConfirm(conn, tx, keypair) {+ tx.sign([keypair]);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });+ const bh = await conn.getLatestBlockhash('confirmed');+ const res = await conn.confirmTransaction(+ { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },+ 'confirmed',+ );+ if (res?.value?.err) {+ throw Object.assign(new Error('transaction reverted on-chain'), { code: 'tx_reverted', signature: sig });+ }+ return sig;+}++/**+ * Re-derive NAV from chain, ratchet the high-water peak, and trip the drawdown+ * breaker if NAV has fallen `max_drawdown_bps` from peak. Returns the fresh NAV ++ * whether the vault was halted. Never throws — a transient pricing gap (priced=false)+ * defers the breaker rather than fabricating a halt.+ */+export async function enforceBreaker(vault, { userId = null, reason = 'post_trade' } = {}) {+ const positions = await getOpenPositions(vault.id);+ const nav = await computeVaultNav(vault, positions);+ const peak = nextPeak(vault.peak_nav_atomics, nav.navAtomics);+ const priceE6 = sharePriceE6(nav.navAtomics, vault.total_shares);++ // Ratchet the peak (only rises). Done regardless of breach.+ await applyVaultShareDelta(vault.id, 0n, peak);++ let halted = false;+ if (nav.priced && vault.status === 'open' && isDrawdownBreached(peak, nav.navAtomics, vault.max_drawdown_bps)) {+ await setVaultStatus(vault.id, 'paused', { haltReason: 'drawdown' });+ await recordVaultEvent({+ vaultId: vault.id, type: 'drawdown_halt', userId,+ navAtomics: nav.navAtomics, sharePriceE6: priceE6,+ reason: 'drawdown circuit breaker tripped — autonomous trading halted to protect capital',+ meta: { peak_nav_atomics: String(peak), nav_atomics: String(nav.navAtomics), max_drawdown_bps: vault.max_drawdown_bps, trigger: reason },+ });+ logAudit({ userId, action: 'vault.drawdown_halt', resourceId: vault.id, meta: { peak: String(peak), nav: String(nav.navAtomics), max_drawdown_bps: vault.max_drawdown_bps } });+ halted = true;+ }+ return { nav, peak, sharePriceE6: priceE6, halted };+}++/**+ * Execute a guarded vault trade. The vault row is loaded fresh (with secret) here.+ *+ * @param {object} a+ * @param {string} a.vaultId+ * @param {string} a.userId the owner (only the owner can direct trades)+ * @param {'buy'|'sell'} a.side+ * @param {string} a.mint+ * @param {bigint} [a.usdcInAtomics] buy size in USDC atomics+ * @param {bigint|'max'} [a.amountRaw] sell size in token base units, or 'max'+ * @param {number} a.slippageBps+ * @param {string} a.idempotencyKey+ * @returns {Promise<object>} a result envelope ({ status, ... })+ */+export async function vaultTrade({ vaultId, userId, side, mint, usdcInAtomics, amountRaw, slippageBps, idempotencyKey }) {+ const vault = await getVaultWithSecret(vaultId);+ if (!vault) return { status: 'failed', code: 'not_found', message: 'vault not found' };+ if (vault.status !== 'open') {+ return blocked('vault_not_open', vault.status === 'paused'+ ? 'vault is paused — resume it before trading'+ : `vault is ${vault.status}`);+ }+ const network = netOf(vault.network);+ const slip = Math.max(0, Math.min(5000, Math.round(Number(slippageBps) || 100)));++ const mintB58 = validateMint(mint);+ if (!mintB58) return blocked('invalid_mint', 'not a valid token mint address');+ if (mintB58 === USDC_MINT_BY_NETWORK[network]) return blocked('invalid_mint', 'cannot trade USDC against itself');++ const conn = solanaConnection(network);+ const vaultPk = new PublicKey(vault.vault_address);+ const mintPk = new PublicKey(mintB58);++ let mintInfo;+ try { mintInfo = await resolveMintInfo(conn, mintPk); } catch { return blocked('invalid_mint', 'could not read the token mint on this network'); }++ // ── Guards (pre-signature) ────────────────────────────────────────────────+ if (side === 'buy') {+ const amount = toBig(usdcInAtomics);+ if (amount <= 0n) return blocked('zero_amount', 'buy amount must be positive');+ if (tradeExceedsPerTrade(amount, vault.max_per_trade_atomics)) {+ return blocked('per_trade_cap', 'exceeds the vault per-trade ceiling', { max_per_trade_atomics: String(vault.max_per_trade_atomics) });+ }+ const spent = await getDailyTradeSpend(vault.id);+ if (tradeExceedsDailyBudget(spent, amount, vault.daily_budget_atomics)) {+ return blocked('daily_budget', 'exceeds the vault rolling 24h budget', { spent_atomics: String(spent), daily_budget_atomics: String(vault.daily_budget_atomics) });+ }+ const usdcBal = await readVaultUsdcAtomics(vault.vault_address, network);+ if (usdcBal < amount) return blocked('insufficient_usdc', 'the vault does not hold enough USDC for this buy', { balance_atomics: String(usdcBal) });+ if (!(await hasSolHeadroom(vault.vault_address, network))) {+ return blocked('insufficient_sol_for_fees', 'the vault needs a little SOL to pay swap fees — fund it with ~0.01 SOL');+ }+ } else if (side !== 'sell') {+ return blocked('invalid_side', 'side must be "buy" or "sell"');+ }++ // ── Quote ─────────────────────────────────────────────────────────────────+ let q; let sellRaw = 0n;+ try {+ if (side === 'buy') {+ q = await quoteBuy({ network, mint: mintB58, usdcAtomics: toBig(usdcInAtomics), slippageBps: slip });+ } else {+ const held = await tokenBalance(conn, mintPk, vaultPk, mintInfo.programId);+ sellRaw = (amountRaw === 'max' || amountRaw == null) ? held : toBig(amountRaw);+ if (sellRaw <= 0n) return blocked('zero_amount', 'sell amount must be positive');+ if (sellRaw > held) return blocked('insufficient_token', 'the vault holds less of this token than requested', { held_raw: String(held) });+ q = await quoteSell({ network, mint: mintB58, amountRaw: sellRaw, slippageBps: slip });+ }+ } catch (e) {+ const code = e?.code === 'no_route' ? 'no_route' : 'quote_failed';+ return blocked(code, code === 'no_route' ? 'no swap route for this token right now' : 'could not price the trade — try again');+ }++ // ── Idempotency claim (pending ledger row) ──────────────────────────────────+ const claimMeta = {+ side, mint: mintB58, slippage_bps: slip,+ price_impact_pct: q.priceImpactPct,+ ...(side === 'buy' ? { usdc_in: String(toBig(usdcInAtomics)), expected_out_raw: String(q.expectedOutRaw) } : { sell_raw: String(sellRaw), expected_usdc_out: String(q.expectedOutAtomics) }),+ };+ const claimId = await recordVaultEvent({+ vaultId: vault.id, type: 'trade', userId,+ atomicsDelta: side === 'buy' ? String(-toBig(usdcInAtomics)) : null,+ signature: null, status: 'pending', reason: `trade_${side}`,+ idempotencyKey, meta: claimMeta,+ });+ if (claimId == null) {+ return { status: 'failed', code: 'in_flight', message: 'a trade with this id is already recorded — check the ledger before retrying' };+ }++ // ── Sign + submit the real swap ─────────────────────────────────────────────+ let keypair;+ try {+ keypair = await recoverVaultKeypair(vault.encrypted_secret, { vaultId: vault.id, userId, reason: `trade_${side}`, meta: { mint: mintB58, network } });+ } catch {+ await updateVaultEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } });+ return { status: 'failed', code: 'key_recover_failed', message: 'could not access the vault key — no funds moved' };+ }++ // Snapshot balances to measure the exact fill from chain (never trust the quote).+ const usdcBefore = await readVaultUsdcAtomics(vault.vault_address, network);+ const tokenBefore = await tokenBalance(conn, mintPk, vaultPk, mintInfo.programId);++ let signature;+ try {+ const tx = await buildSwapTx({ quote: q.quote, userPublicKey: vaultPk });+ signature = await signSendConfirm(conn, tx, keypair);+ } catch (e) {+ await updateVaultEvent(claimId, { status: 'failed', signature: e?.signature || null, meta: { error: e?.code || 'send_failed', message: (e?.message || '').slice(0, 200) } });+ logAudit({ userId, action: 'vault.trade_failed', resourceId: vault.id, meta: { side, mint: mintB58, reason: e?.code || 'send_failed' } });+ return { status: 'failed', code: e?.code || 'send_failed', message: 'the swap could not be confirmed — no position change recorded', detail: e?.signature ? { signature: e.signature } : null };+ }++ // ── Settle position bookkeeping from the real on-chain delta ─────────────────+ const usdcAfter = await readVaultUsdcAtomics(vault.vault_address, network);+ const tokenAfter = await tokenBalance(conn, mintPk, vaultPk, mintInfo.programId);++ if (side === 'buy') {+ const received = tokenAfter > tokenBefore ? tokenAfter - tokenBefore : q.expectedOutRaw;+ const spent = usdcBefore > usdcAfter ? usdcBefore - usdcAfter : toBig(usdcInAtomics);+ await upsertPosition({ vaultId: vault.id, mint: mintB58, tokenDecimals: mintInfo.decimals, amountRawDelta: received, costDelta: spent, markAtomics: spent });+ await updateVaultEvent(claimId, { status: 'ok', signature, atomicsDelta: String(-spent), meta: { usdc_in: String(spent), out_raw: String(received) } });+ } else {+ const proceeds = usdcAfter > usdcBefore ? usdcAfter - usdcBefore : q.expectedOutAtomics;+ // Cost basis removed = pro-rata of the open position's cost for the units sold.+ const [pos] = await getOpenPositions(vault.id).then((ps) => ps.filter((p) => p.mint === mintB58));+ const posAmount = pos ? toBig(pos.amount_raw) : sellRaw;+ const posCost = pos ? toBig(pos.cost_atomics) : 0n;+ const costRemoved = posAmount > 0n ? (posCost * sellRaw) / posAmount : 0n;+ await reducePosition({ vaultId: vault.id, mint: mintB58, amountRawDelta: sellRaw, proceedsAtomics: proceeds, costRemovedAtomics: costRemoved });+ await updateVaultEvent(claimId, { status: 'ok', signature, atomicsDelta: String(proceeds), meta: { usdc_out: String(proceeds), sold_raw: String(sellRaw), realized_atomics: String(proceeds - costRemoved) } });+ }++ logAudit({ userId, action: 'vault.trade', resourceId: vault.id, meta: { side, mint: mintB58, signature, network } });++ // ── Re-derive NAV + run the drawdown circuit breaker ─────────────────────────+ const fresh = await getVaultWithSecret(vault.id);+ const breaker = await enforceBreaker(fresh, { userId, reason: `trade_${side}` });++ return {+ status: 'ok',+ signature,+ explorer: explorerTxUrl(signature, network),+ side, mint: mintB58, network,+ price_impact_pct: q.priceImpactPct,+ nav_atomics: String(breaker.nav.navAtomics),+ share_price_e6: String(breaker.sharePriceE6),+ halted: breaker.halted,+ ...(breaker.halted ? { halt_reason: 'drawdown' } : {}),+ };+}diff --git a/api/_lib/vault-transfer.js b/api/_lib/vault-transfer.jsnew file mode 100644index 000000000..82c52c265--- /dev/null+++ b/api/_lib/vault-transfer.js@@ -0,0 +1,274 @@+// @ts-check+// Back-an-Agent Vaults — real deposit / redeem / fee-claim money movement.+//+// Deposits reuse the platform's proven, guarded agent→agent USDC settlement+// (transferUsdcGuarded): a backer funds the vault FROM one of their own agents'+// custodial wallets, so the deposit is spend-limited, kill-switch-aware, idempotent+// and audited on the backer's side exactly like every other outbound payment. The+// shares are minted only AFTER the transfer settles on-chain, priced against the+// NAV measured immediately before the deposit landed — so a backer never gets+// shares for funds that didn't arrive, and an existing holder is never diluted.+//+// Redemptions pay out from the vault's dedicated wallet at real NAV, charging the+// owner's performance fee only on the backer's realized gain. When the vault can't+// pay the full claim instantly (capital is live in open positions) we redeem only+// what the liquid USDC covers and report the queued remainder honestly — never a+// fake instant number.++import { PublicKey } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction, TOKEN_PROGRAM_ID,+} from '@solana/spl-token';+import { solanaConnection } from './agent-pumpfun.js';+import { submitProtected } from './execution-engine.js';+import { transferUsdcGuarded } from './agent-usdc-transfer.js';+import { logAudit } from './audit.js';+import { explorerTxUrl } from './avatar-wallet.js';+import {+ getVaultWithSecret, getBacker, getOpenPositions,+ recordVaultEvent, applyBackerDelta, applyVaultShareDelta, applyAccruedFee,+} from './vault-store.js';+import { recoverVaultKeypair, computeVaultNav, readVaultUsdcAtomics } from './vault-wallet.js';+import { USDC_MINT_BY_NETWORK, USDC_DECIMALS } from './vault-jupiter.js';+import {+ toBig, sharesForDeposit, settleRedemption, sharesRedeemableNow,+ depositExceedsCap, sharePriceE6, nextPeak,+} from './vault-accounting.js';++function netOf(network) {+ return network === 'devnet' ? 'devnet' : 'mainnet';+}++/** Float USDC for the guarded transfer API (which meters in USD = USDC). */+function atomicsToUsdcFloat(atomics) {+ return Number(toBig(atomics)) / 10 ** USDC_DECIMALS;+}++/**+ * Pay `atomics` USDC out of the vault's dedicated wallet to `toAddress`. Used by+ * redemptions and owner fee claims. Recovers the vault keypair (audit-logged),+ * builds an idempotent USDC transfer, and confirms through the shared MEV-aware+ * engine. Returns { signature } or throws a structured error.+ */+async function payoutUsdc({ vault, toAddress, atomics, userId, reason }) {+ const network = netOf(vault.network);+ const amount = toBig(atomics);+ if (amount <= 0n) throw Object.assign(new Error('zero payout'), { code: 'zero_amount' });++ const conn = solanaConnection(network);+ const mintPk = new PublicKey(USDC_MINT_BY_NETWORK[network]);+ let toPk;+ try { toPk = new PublicKey(toAddress); } catch { throw Object.assign(new Error('bad recipient'), { code: 'bad_address' }); }++ const keypair = await recoverVaultKeypair(vault.encrypted_secret, { vaultId: vault.id, userId, reason, meta: { to: toAddress, atomics: String(amount) } });+ const fromAta = getAssociatedTokenAddressSync(mintPk, keypair.publicKey, false, TOKEN_PROGRAM_ID);+ const toAta = getAssociatedTokenAddressSync(mintPk, toPk, false, TOKEN_PROGRAM_ID);+ const instructions = [+ createAssociatedTokenAccountIdempotentInstruction(keypair.publicKey, toAta, toPk, mintPk, TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(fromAta, mintPk, toAta, keypair.publicKey, amount, USDC_DECIMALS, [], TOKEN_PROGRAM_ID),+ ];+ const result = await submitProtected({+ network, connection: conn, payer: keypair, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ return { signature: result.signature };+}++/**+ * Deposit `usdcAtomics` from the backer's chosen agent wallet into the vault and+ * mint shares. `backerAgent` is the owned agent row (with meta) funding it.+ *+ * @returns {Promise<object>} result envelope+ */+export async function depositToVault({ vault, backerAgent, userId, usdcAtomics, idempotencyKey }) {+ const network = netOf(vault.network);+ const amount = toBig(usdcAtomics);+ if (amount <= 0n) return { status: 'failed', code: 'zero_amount', message: 'deposit must be positive' };+ if (vault.status !== 'open') return { status: 'blocked', code: 'vault_not_open', message: `vault is ${vault.status} and not accepting deposits` };++ // Per-backer cap (against the backer's lifetime contribution so far).+ const existing = await getBacker(vault.id, userId);+ const contributed = existing ? toBig(existing.deposited_atomics) : 0n;+ if (depositExceedsCap(contributed, amount, vault.per_backer_cap_atomics)) {+ return { status: 'blocked', code: 'backer_cap', message: 'this deposit would exceed the per-backer cap for this vault', detail: { cap_atomics: String(vault.per_backer_cap_atomics), contributed_atomics: String(contributed) } };+ }++ // Real, guarded USDC transfer from the backer's agent wallet → vault wallet.+ const transfer = await transferUsdcGuarded({+ fromAgentId: backerAgent.id, fromUserId: userId, fromMeta: backerAgent.meta || {},+ toAddress: vault.vault_address, usdc: atomicsToUsdcFloat(amount),+ network, category: 'vault_back', idempotencyKey,+ rowMeta: { vault_id: vault.id, agent_id: vault.agent_id },+ });+ if (transfer.status === 'blocked') return { status: 'blocked', code: transfer.code, message: transfer.message || 'deposit blocked by the funding wallet spend policy' };+ if (transfer.status === 'failed') return { status: 'failed', code: transfer.code, message: 'the deposit transfer did not settle — no shares were minted' };+ const signature = transfer.signature;++ // Mint shares exactly once for this on-chain settlement (idempotent on signature).+ // Price against the NAV measured BEFORE this deposit: current NAV minus the+ // amount that just landed in the wallet.+ const positions = await getOpenPositions(vault.id);+ const nav = await computeVaultNav(vault, positions);+ const navBefore = nav.navAtomics > amount ? nav.navAtomics - amount : 0n;+ const minted = sharesForDeposit(amount, navBefore, vault.total_shares);++ const eventId = await recordVaultEvent({+ vaultId: vault.id, type: 'deposit', userId, backerAgentId: backerAgent.id,+ sharesDelta: String(minted), atomicsDelta: String(amount),+ navAtomics: String(nav.navAtomics), sharePriceE6: String(sharePriceE6(navBefore, vault.total_shares)),+ signature, status: 'ok', reason: 'deposit', idempotencyKey: `deposit:${signature}`,+ meta: { nav_before_atomics: String(navBefore), minted_shares: String(minted) },+ });+ if (eventId == null) {+ // A replay of an already-credited deposit — return the existing position, no double-mint.+ const pos = await getBacker(vault.id, userId);+ return { status: 'replayed', signature, shares: pos ? String(pos.shares) : '0' };+ }++ await applyBackerDelta({+ vaultId: vault.id, userId, backerAgentId: backerAgent.id,+ sharesDelta: minted, basisDelta: amount, depositedDelta: amount,+ });+ const updated = await applyVaultShareDelta(vault.id, minted, nextPeak(vault.peak_nav_atomics, nav.navAtomics));++ logAudit({ userId, action: 'vault.deposit', resourceId: vault.id, meta: { agent_id: vault.agent_id, usdc_atomics: String(amount), shares: String(minted), signature } });++ const pos = await getBacker(vault.id, userId);+ return {+ status: 'ok', signature, explorer: explorerTxUrl(signature, network),+ shares_minted: String(minted),+ share_price_e6: String(sharePriceE6(navBefore, vault.total_shares)),+ nav_atomics: String(nav.navAtomics),+ total_shares: updated ? String(updated.total_shares) : String(toBig(vault.total_shares) + minted),+ position: pos ? { shares: String(pos.shares), cost_basis_atomics: String(pos.cost_basis_atomics) } : null,+ repriced: !nav.priced,+ };+}++/**+ * Redeem `shares` ('max' for all) from the caller's position. Pays net of the+ * performance fee at real NAV; partials honestly when liquid USDC is short.+ */+export async function redeemFromVault({ vaultId, userId, shares, idempotencyKey }) {+ const vault = await getVaultWithSecret(vaultId);+ if (!vault) return { status: 'failed', code: 'not_found', message: 'vault not found' };+ const network = netOf(vault.network);++ const backer = await getBacker(vault.id, userId);+ if (!backer || toBig(backer.shares) <= 0n) return { status: 'failed', code: 'no_position', message: 'you have no shares in this vault' };+ const backerShares = toBig(backer.shares);+ const want = (shares === 'max' || shares == null) ? backerShares : toBig(shares);+ if (want <= 0n) return { status: 'failed', code: 'zero_amount', message: 'redeem amount must be positive' };+ if (want > backerShares) return { status: 'failed', code: 'insufficient_shares', message: 'you do not hold that many shares', detail: { shares: String(backerShares) } };++ // NAV must be fully priced to settle fairly when positions are open.+ const positions = await getOpenPositions(vault.id);+ const nav = await computeVaultNav(vault, positions);+ if (!nav.priced && positions.length > 0) {+ return { status: 'failed', code: 'repricing', message: 'the vault holds positions that cannot be priced right now — try again in a moment' };+ }++ // Honest partial: redeem only what liquid USDC can pay this instant.+ const free = nav.freeAtomics;+ const redeemNow = sharesRedeemableNow({ requestedShares: want, navAtomics: nav.navAtomics, totalShares: vault.total_shares, freeAtomics: free });+ if (redeemNow <= 0n) {+ return { status: 'queued', code: 'insufficient_liquidity', message: 'the vault has no liquid USDC right now — capital is deployed in open positions. Try again after the agent harvests, or the owner can free liquidity.', detail: { free_atomics: String(free), requested_shares: String(want) } };+ }++ const settle = settleRedemption({+ shares: redeemNow, backerShares, costBasisAtomics: backer.cost_basis_atomics,+ navAtomics: nav.navAtomics, totalShares: vault.total_shares, feeBps: vault.performance_fee_bps,+ });+ if (settle.netPayout <= 0n) return { status: 'failed', code: 'zero_payout', message: 'this redemption nets zero — nothing to pay out' };++ // Pay the net to the backer's agent wallet (the wallet they funded with).+ const [recipient] = await import('./db.js').then(({ sql }) => sql`+ SELECT meta->>'solana_address' AS addr FROM agent_identities WHERE id = ${backer.backer_agent_id} AND deleted_at IS NULL LIMIT 1+ `);+ const toAddress = recipient?.addr;+ if (!toAddress) return { status: 'failed', code: 'no_recipient', message: 'the funding wallet for this position is no longer available' };++ let signature;+ try {+ ({ signature } = await payoutUsdc({ vault, toAddress, atomics: settle.netPayout, userId, reason: 'vault_redeem' }));+ } catch (e) {+ return { status: 'failed', code: e?.code || 'payout_failed', message: 'the redemption payout could not be confirmed — your shares were not burned' };+ }++ // Burn shares + return cost basis + accrue the owner fee, once per payout signature.+ const eventId = await recordVaultEvent({+ vaultId: vault.id, type: 'redeem', userId, backerAgentId: backer.backer_agent_id,+ sharesDelta: String(-redeemNow), atomicsDelta: String(-settle.netPayout),+ navAtomics: String(nav.navAtomics), sharePriceE6: String(sharePriceE6(nav.navAtomics, vault.total_shares)),+ signature, status: 'ok', reason: 'redeem', idempotencyKey: `redeem:${signature}`,+ meta: { gross_atomics: String(settle.grossPayout), fee_atomics: String(settle.fee), net_atomics: String(settle.netPayout), gain_atomics: String(settle.gain), shares_burned: String(redeemNow) },+ });+ if (eventId == null) return { status: 'replayed', signature };++ await applyBackerDelta({+ vaultId: vault.id, userId, backerAgentId: backer.backer_agent_id,+ sharesDelta: -redeemNow, basisDelta: -settle.costPortion,+ redeemedDelta: settle.netPayout, realizedGainDelta: settle.gain, feesPaidDelta: settle.fee,+ });+ await applyVaultShareDelta(vault.id, -redeemNow);+ if (settle.fee > 0n) {+ await applyAccruedFee(vault.id, settle.fee);+ await recordVaultEvent({ vaultId: vault.id, type: 'fee', userId: vault.owner_user_id, atomicsDelta: String(settle.fee), reason: 'performance_fee', meta: { from_user: userId, gain_atomics: String(settle.gain) } });+ }+ logAudit({ userId, action: 'vault.redeem', resourceId: vault.id, meta: { shares: String(redeemNow), net_atomics: String(settle.netPayout), fee_atomics: String(settle.fee), signature } });++ const queuedShares = want - redeemNow;+ return {+ status: queuedShares > 0n ? 'partial' : 'ok',+ signature, explorer: explorerTxUrl(signature, network),+ shares_redeemed: String(redeemNow),+ gross_atomics: String(settle.grossPayout),+ fee_atomics: String(settle.fee),+ net_atomics: String(settle.netPayout),+ gain_atomics: String(settle.gain),+ queued_shares: String(queuedShares),+ ...(queuedShares > 0n ? { note: 'partial redemption — the rest is queued until the vault has liquid USDC' } : {}),+ };+}++/**+ * Owner claims accrued performance fees to one of their agent wallets.+ */+export async function claimVaultFees({ vaultId, ownerUserId, toAgent, idempotencyKey }) {+ const vault = await getVaultWithSecret(vaultId);+ if (!vault) return { status: 'failed', code: 'not_found', message: 'vault not found' };+ if (vault.owner_user_id !== ownerUserId) return { status: 'failed', code: 'forbidden', message: 'only the vault owner can claim fees' };+ const accrued = toBig(vault.accrued_fee_atomics);+ if (accrued <= 0n) return { status: 'failed', code: 'no_fees', message: 'no fees accrued yet' };++ const toAddress = toAgent?.meta?.solana_address;+ if (!toAddress) return { status: 'failed', code: 'no_recipient', message: 'choose an agent wallet with a Solana address to receive the fees' };++ // Cap the claim at the vault's liquid USDC (fees may be partly tied up in positions).+ const free = await readVaultUsdcAtomics(vault.vault_address, netOf(vault.network));+ const claimable = accrued < free ? accrued : free;+ if (claimable <= 0n) return { status: 'queued', code: 'insufficient_liquidity', message: 'fees are accrued but the vault has no liquid USDC to pay them right now', detail: { accrued_atomics: String(accrued) } };++ let signature;+ try {+ ({ signature } = await payoutUsdc({ vault, toAddress, atomics: claimable, userId: ownerUserId, reason: 'vault_fee_claim' }));+ } catch (e) {+ return { status: 'failed', code: e?.code || 'payout_failed', message: 'the fee claim could not be confirmed' };+ }+ const eventId = await recordVaultEvent({+ vaultId: vault.id, type: 'fee_claim', userId: ownerUserId, backerAgentId: toAgent.id,+ atomicsDelta: String(-claimable), signature, status: 'ok', reason: 'fee_claim',+ idempotencyKey: idempotencyKey || `fee_claim:${signature}`, meta: { to: toAddress, claimed_atomics: String(claimable) },+ });+ if (eventId == null) return { status: 'replayed', signature };+ await applyAccruedFee(vault.id, -claimable);+ logAudit({ userId: ownerUserId, action: 'vault.fee_claim', resourceId: vault.id, meta: { claimed_atomics: String(claimable), signature } });++ return {+ status: 'ok', signature, explorer: explorerTxUrl(signature, netOf(vault.network)),+ claimed_atomics: String(claimable),+ remaining_accrued_atomics: String(accrued - claimable),+ ...(claimable < accrued ? { note: 'partial claim — the rest stays accrued until more USDC is liquid' } : {}),+ };+}diff --git a/api/vaults/[id].js b/api/vaults/[id].jsnew file mode 100644index 000000000..b4e39ab64--- /dev/null+++ b/api/vaults/[id].js@@ -0,0 +1,158 @@+// /api/vaults/:id+// GET /api/vaults/:id live vault detail (NAV, terms, positions, backers, reputation)+// PATCH /api/vaults/:id owner-only: pause / resume / update terms / close+//+// The GET is role-aware: anyone can see the public picture (the agent, its verified+// reputation, live NAV + P&L, terms, backer roster); the signed-in caller also sees+// their own position; the owner additionally sees accrued fees and the funding+// roster detail. NAV is re-derived from chain on every read — never a stale cache.++import { cors, json, method, error, readJson, wrap } from '../_lib/http.js';+import { authWrite, resolveUserId, loadAgent, traderBadge } from '../_lib/vault-auth.js';+import {+ getVault, getOpenPositions, getBacker, listBackers,+ setVaultStatus, updateVaultTerms, recordVaultEvent,+} from '../_lib/vault-store.js';+import { computeVaultNav } from '../_lib/vault-wallet.js';+import {+ sharePriceE6, roiBps, toBig, usdcToAtomics, settleRedemption,+} from '../_lib/vault-accounting.js';+import { isUuid } from '../_lib/validate.js';++function idFromReq(req) {+ const fromQuery = req.query?.id;+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;+ const path = new URL(req.url, 'http://x').pathname;+ const m = path.match(/\/api\/vaults\/([^/]+)/);+ return m ? decodeURIComponent(m[1]) : null;+}++async function handleGet(req, res, id) {+ const who = await resolveUserId(req).catch(() => null);+ const vault = await getVault(id);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');+ const isOwner = who && who.userId === vault.owner_user_id;++ const [agent, positions, backers, badge] = await Promise.all([+ loadAgent(vault.agent_id).catch(() => null),+ getOpenPositions(vault.id),+ listBackers(vault.id, { limit: 50 }),+ traderBadge(vault.agent_id, vault.network).catch(() => null),+ ]);++ const nav = await computeVaultNav(vault, positions);+ const totalShares = toBig(vault.total_shares);+ const priceE6 = sharePriceE6(nav.navAtomics, totalShares);++ // The caller's own position (so the UI can show "your stake / your P&L").+ let myPosition = null;+ if (who) {+ const b = await getBacker(vault.id, who.userId);+ if (b && toBig(b.shares) > 0n) {+ const settle = settleRedemption({+ shares: b.shares, backerShares: b.shares, costBasisAtomics: b.cost_basis_atomics,+ navAtomics: nav.navAtomics, totalShares, feeBps: vault.performance_fee_bps,+ });+ myPosition = {+ shares: String(b.shares), cost_basis_atomics: String(b.cost_basis_atomics),+ deposited_atomics: String(b.deposited_atomics), redeemed_atomics: String(b.redeemed_atomics),+ realized_gain_atomics: String(b.realized_gain_atomics), fees_paid_atomics: String(b.fees_paid_atomics),+ backer_agent_id: b.backer_agent_id,+ current_value_atomics: String(settle.grossPayout),+ unrealized_gain_atomics: String(settle.gain),+ estimated_net_atomics: String(settle.netPayout),+ };+ }+ }++ const data = {+ id: vault.id, agent_id: vault.agent_id, network: vault.network, status: vault.status,+ halt_reason: vault.halt_reason, paused_at: vault.paused_at, created_at: vault.created_at,+ vault_address: vault.vault_address,+ agent: agent ? { id: agent.id, name: agent.name, description: agent.description, image: agent.image } : null,+ reputation: badge,+ terms: {+ performance_fee_bps: vault.performance_fee_bps,+ max_drawdown_bps: vault.max_drawdown_bps,+ per_backer_cap_atomics: vault.per_backer_cap_atomics != null ? String(vault.per_backer_cap_atomics) : null,+ max_per_trade_atomics: String(vault.max_per_trade_atomics),+ daily_budget_atomics: String(vault.daily_budget_atomics),+ },+ nav: {+ nav_atomics: String(nav.navAtomics),+ free_atomics: String(nav.freeAtomics),+ usdc_atomics: String(nav.usdcAtomics),+ share_price_e6: String(priceE6),+ roi_bps: roiBps(nav.navAtomics, totalShares),+ total_shares: String(totalShares),+ priced: nav.priced,+ peak_nav_atomics: String(vault.peak_nav_atomics),+ },+ positions: nav.positions.map((p) => ({ mint: p.mint, amount_raw: p.amount_raw, mark_atomics: p.mark_atomics })),+ backer_count: backers.length,+ backers: backers.map((b) => ({+ shares: String(b.shares),+ deposited_atomics: String(b.deposited_atomics),+ // Pseudonymous: the roster shows stake size, never the user id.+ is_me: who ? b.user_id === who.userId : false,+ })),+ my_position: myPosition,+ is_owner: !!isOwner,+ ...(isOwner ? { accrued_fee_atomics: String(vault.accrued_fee_atomics) } : {}),+ };+ return json(res, 200, { data }, { 'cache-control': isOwner || who ? 'no-store' : 'public, max-age=10, s-maxage=20' });+}++async function handlePatch(req, res, id) {+ const who = await authWrite(req, res);+ if (!who) return;+ const vault = await getVault(id);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');+ if (vault.owner_user_id !== who.userId) return error(res, 403, 'forbidden', 'only the vault owner can change it');++ let body;+ try { body = (await readJson(req)) || {}; } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid body'); }+ const action = String(body.action || 'terms');++ if (action === 'pause') {+ if (vault.status === 'closed') return error(res, 409, 'closed', 'vault is closed');+ const next = await setVaultStatus(vault.id, 'paused', { haltReason: 'owner_pause' });+ await recordVaultEvent({ vaultId: vault.id, type: 'pause', userId: who.userId, reason: 'owner paused trading' });+ return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });+ }+ if (action === 'resume') {+ if (vault.status === 'closed') return error(res, 409, 'closed', 'vault is closed');+ const next = await setVaultStatus(vault.id, 'open', { haltReason: null });+ await recordVaultEvent({ vaultId: vault.id, type: 'resume', userId: who.userId, reason: 'owner resumed trading' });+ return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });+ }+ if (action === 'close') {+ const next = await setVaultStatus(vault.id, 'closing', { haltReason: 'owner_close' });+ await recordVaultEvent({ vaultId: vault.id, type: 'close', userId: who.userId, reason: 'owner closing vault — backers may redeem' });+ return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });+ }+ if (action === 'terms') {+ const patch = {};+ if (body.performanceFeeBps != null) patch.performanceFeeBps = Math.max(0, Math.min(5000, Math.round(Number(body.performanceFeeBps))));+ if (body.maxDrawdownBps != null) patch.maxDrawdownBps = Math.max(100, Math.min(9000, Math.round(Number(body.maxDrawdownBps))));+ if (body.maxPerTradeUsdc != null) { const v = Number(body.maxPerTradeUsdc); if (v > 0) patch.maxPerTradeAtomics = usdcToAtomics(v); }+ if (body.dailyBudgetUsdc != null) { const v = Number(body.dailyBudgetUsdc); if (v > 0) patch.dailyBudgetAtomics = usdcToAtomics(v); }+ if ('perBackerCapUsdc' in body) {+ const v = body.perBackerCapUsdc;+ patch.perBackerCapAtomics = v == null || Number(v) <= 0 ? null : usdcToAtomics(Number(v));+ }+ const next = await updateVaultTerms(vault.id, patch);+ await recordVaultEvent({ vaultId: vault.id, type: 'terms', userId: who.userId, reason: 'terms updated', meta: { patch: Object.fromEntries(Object.entries(patch).map(([k, v]) => [k, v == null ? null : String(v)])) } });+ return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });+ }+ return error(res, 400, 'bad_action', 'action must be pause, resume, close, or terms');+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PATCH,OPTIONS', credentials: true })) return;+ const id = idFromReq(req);+ if (!id || !isUuid(id)) return error(res, 404, 'not_found', 'vault not found');+ if (req.method === 'PATCH') return handlePatch(req, res, id);+ if (!method(req, res, ['GET', 'PATCH'])) return;+ return handleGet(req, res, id);+});diff --git a/api/vaults/claim-fees.js b/api/vaults/claim-fees.jsnew file mode 100644index 000000000..595cacd9a--- /dev/null+++ b/api/vaults/claim-fees.js@@ -0,0 +1,48 @@+// POST /api/vaults/claim-fees { vaultId, toAgentId, idempotency_key? }+//+// Owner-only: sweep the vault's accrued performance fees to one of the owner's+// agent wallets. Capped at the vault's liquid USDC; the rest stays accrued until+// more liquidity is harvested.++import { randomUUID } from 'node:crypto';+import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';+import { getVault } from '../_lib/vault-store.js';+import { claimVaultFees } from '../_lib/vault-transfer.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const who = await authWrite(req, res);+ if (!who) return;+ const { userId } = who;++ const rl = await limits.tradePerUser(userId);+ 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 body'); }++ const vaultId = String(body.vaultId || body.vault_id || '').trim();+ const toAgentId = String(body.toAgentId || body.to_agent_id || '').trim();+ if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');+ if (!toAgentId) return error(res, 400, 'validation_error', 'toAgentId required (the wallet to receive fees)');++ const vault = await getVault(vaultId);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');+ if (vault.owner_user_id !== userId) return error(res, 403, 'forbidden', 'only the vault owner can claim fees');++ let toAgent;+ try { toAgent = await loadOwnedAgent(toAgentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }++ const result = await claimVaultFees({+ vaultId, ownerUserId: userId, toAgent,+ idempotencyKey: String(body.idempotency_key || `vault-fee-claim:${vaultId}:${randomUUID()}`).slice(0, 128),+ });++ if (result.status === 'failed') return error(res, 400, result.code, result.message, result.detail ? { detail: result.detail } : {});+ if (result.status === 'queued') return json(res, 202, { data: result }, { 'cache-control': 'no-store' });+ return json(res, 200, { data: result }, { 'cache-control': 'no-store' });+});diff --git a/api/vaults/deposit.js b/api/vaults/deposit.jsnew file mode 100644index 000000000..623d5e7c6--- /dev/null+++ b/api/vaults/deposit.js@@ -0,0 +1,55 @@+// POST /api/vaults/deposit { vaultId, backerAgentId, usdc, idempotency_key? }+//+// Back an agent: deposit USDC from one of YOUR agents' custodial wallets into the+// vault and receive shares priced at live NAV. The transfer is the platform's+// guarded agent→agent USDC settlement, so it respects the funding wallet's spend+// policy + kill switch and is fully audited on both sides.++import { randomUUID } from 'node:crypto';+import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';+import { getVault } from '../_lib/vault-store.js';+import { depositToVault } from '../_lib/vault-transfer.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const who = await authWrite(req, res);+ if (!who) return;+ const { userId } = who;++ const rl = await limits.tradePerUser(userId);+ 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 body'); }++ const vaultId = String(body.vaultId || body.vault_id || '').trim();+ const backerAgentId = String(body.backerAgentId || body.backer_agent_id || '').trim();+ const usdc = Number(body.usdc);+ if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');+ if (!backerAgentId) return error(res, 400, 'validation_error', 'backerAgentId required (the agent wallet to fund from)');+ if (!(usdc > 0)) return error(res, 400, 'validation_error', 'usdc must be a positive number');++ const vault = await getVault(vaultId);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');++ let backerAgent;+ try { backerAgent = await loadOwnedAgent(backerAgentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }+ if (!backerAgent.meta?.solana_address || !backerAgent.meta?.encrypted_solana_secret) {+ return error(res, 400, 'wallet_unready', 'that agent has no funded Solana wallet yet — provision and fund it first');+ }++ const { usdcToAtomics } = await import('../_lib/vault-accounting.js');+ const result = await depositToVault({+ vault, backerAgent, userId,+ usdcAtomics: usdcToAtomics(usdc),+ idempotencyKey: String(body.idempotency_key || `vault-deposit:${vaultId}:${backerAgentId}:${randomUUID()}`).slice(0, 128),+ });++ if (result.status === 'blocked') return error(res, 403, result.code, result.message, result.detail ? { detail: result.detail } : {});+ if (result.status === 'failed') return error(res, 402, result.code, result.message);+ return json(res, 200, { data: result }, { 'cache-control': 'no-store' });+});diff --git a/api/vaults/index.js b/api/vaults/index.jsnew file mode 100644index 000000000..586089915--- /dev/null+++ b/api/vaults/index.js@@ -0,0 +1,152 @@+// /api/vaults+// GET /api/vaults discovery feed (open vaults ranked by verified performance)+// GET /api/vaults?mine=1 the caller's backed-vault portfolio (auth)+// POST /api/vaults open a vault behind an agent you own (reputation-gated)+//+// Vaults are USDC-denominated. A vault gets its OWN dedicated custodial Solana+// wallet at open; backer capital lives there, never co-mingled with the agent's+// personal wallet. Only an agent with a real verified trading track record (the+// same on-chain badge the trader leaderboard uses) can open one.++import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { authWrite, loadOwnedAgent, assertReputationVerified, traderBadge } from '../_lib/vault-auth.js';+import { resolveUserId } from '../_lib/vault-auth.js';+import { createVault, listVaults, listBackedVaults, recordVaultEvent } from '../_lib/vault-store.js';+import { generateVaultWallet } from '../_lib/vault-wallet.js';+import { usdcToAtomics, sharePriceE6, roiBps, toBig } from '../_lib/vault-accounting.js';++const TERM_BOUNDS = {+ performanceFeeBps: { min: 0, max: 5000, def: 1000 },+ maxDrawdownBps: { min: 100, max: 9000, def: 2500 },+};++function clampInt(v, { min, max, def }) {+ const n = Math.round(Number(v));+ if (!Number.isFinite(n)) return def;+ return Math.max(min, Math.min(max, n));+}++async function handleList(req, res) {+ if (!method(req, res, ['GET'])) return;+ const url = new URL(req.url, 'http://x');+ const mine = url.searchParams.get('mine') === '1';++ if (mine) {+ const who = await resolveUserId(req);+ if (!who) return error(res, 401, 'unauthorized', 'sign in to see your backed vaults');+ const rows = await listBackedVaults(who.userId, { limit: 60 });+ const items = rows.map((r) => ({+ id: r.id, agent_id: r.agent_id, agent_name: r.agent_name, agent_image: r.agent_image,+ network: r.network, status: r.status, performance_fee_bps: r.performance_fee_bps,+ max_drawdown_bps: r.max_drawdown_bps,+ shares: String(r.shares), cost_basis_atomics: String(r.cost_basis_atomics),+ deposited_atomics: String(r.deposited_atomics), redeemed_atomics: String(r.redeemed_atomics),+ realized_gain_atomics: String(r.realized_gain_atomics), fees_paid_atomics: String(r.fees_paid_atomics),+ backer_agent_id: r.backer_agent_id,+ }));+ return json(res, 200, { data: { items } }, { 'cache-control': 'no-store' });+ }++ const rows = await listVaults({ status: 'open', limit: 60 });+ // Rank by real verified trading performance: fetch each owning agent's badge in+ // parallel, then sort verified-first, then by score, then by capital backing.+ const badges = await Promise.all(rows.map((r) => traderBadge(r.agent_id, r.network).catch(() => null)));+ const items = rows.map((r, i) => {+ const badge = badges[i];+ const lastNav = r.last_nav_atomics != null ? toBig(r.last_nav_atomics) : null;+ return {+ id: r.id, agent_id: r.agent_id, agent_name: r.agent_name,+ agent_image: r.agent_image, agent_description: r.agent_description,+ network: r.network, status: r.status,+ performance_fee_bps: r.performance_fee_bps,+ max_drawdown_bps: r.max_drawdown_bps,+ per_backer_cap_atomics: r.per_backer_cap_atomics != null ? String(r.per_backer_cap_atomics) : null,+ backer_count: r.backer_count,+ lifetime_deposited_atomics: String(r.lifetime_deposited),+ total_shares: String(r.total_shares),+ last_nav_atomics: lastNav != null ? String(lastNav) : null,+ share_price_e6: lastNav != null ? String(sharePriceE6(lastNav, r.total_shares)) : '1000000',+ roi_bps: lastNav != null ? roiBps(lastNav, r.total_shares) : 0,+ reputation: badge,+ };+ });+ items.sort((a, b) => {+ const av = a.reputation?.verified ? 1 : 0; const bv = b.reputation?.verified ? 1 : 0;+ if (av !== bv) return bv - av;+ const as = a.reputation?.score ?? 0; const bs = b.reputation?.score ?? 0;+ if (as !== bs) return bs - as;+ return Number(toBig(b.lifetime_deposited_atomics) - toBig(a.lifetime_deposited_atomics));+ });+ return json(res, 200, { data: { items } }, { 'cache-control': 'public, max-age=15, s-maxage=30' });+}++async function handleOpen(req, res) {+ const who = await authWrite(req, res);+ if (!who) return;+ const { userId } = who;++ const rl = await limits.tradePerUser(userId);+ 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 body'); }++ const agentId = String(body.agentId || body.agent_id || '').trim();+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';++ let agent;+ try { agent = await loadOwnedAgent(agentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }++ // Reputation gate — only a verifiably-skilled agent can open a vault.+ try { await assertReputationVerified(agentId, network); } catch (e) { return error(res, e.status || 403, e.code || 'forbidden', e.message, e.detail || {}); }++ // Required risk terms.+ const maxPerTradeUsdc = Number(body.maxPerTradeUsdc ?? body.max_per_trade_usdc);+ const dailyBudgetUsdc = Number(body.dailyBudgetUsdc ?? body.daily_budget_usdc);+ if (!(maxPerTradeUsdc > 0)) return error(res, 400, 'validation_error', 'maxPerTradeUsdc must be a positive number');+ if (!(dailyBudgetUsdc > 0)) return error(res, 400, 'validation_error', 'dailyBudgetUsdc must be a positive number');+ const maxPerTradeAtomics = usdcToAtomics(maxPerTradeUsdc);+ const dailyBudgetAtomics = usdcToAtomics(dailyBudgetUsdc);+ if (maxPerTradeAtomics > dailyBudgetAtomics) return error(res, 400, 'validation_error', 'per-trade ceiling cannot exceed the daily budget');++ const perBackerCapUsdc = body.perBackerCapUsdc ?? body.per_backer_cap_usdc;+ const perBackerCapAtomics = perBackerCapUsdc == null || Number(perBackerCapUsdc) <= 0 ? null : usdcToAtomics(Number(perBackerCapUsdc));++ const performanceFeeBps = clampInt(body.performanceFeeBps ?? body.performance_fee_bps ?? TERM_BOUNDS.performanceFeeBps.def, TERM_BOUNDS.performanceFeeBps);+ const maxDrawdownBps = clampInt(body.maxDrawdownBps ?? body.max_drawdown_bps ?? TERM_BOUNDS.maxDrawdownBps.def, TERM_BOUNDS.maxDrawdownBps);++ const wallet = await generateVaultWallet();+ let vault;+ try {+ vault = await createVault({+ agentId, ownerUserId: userId, network,+ vaultAddress: wallet.address, encryptedSecret: wallet.encrypted_secret,+ performanceFeeBps, perBackerCapAtomics, maxDrawdownBps,+ maxPerTradeAtomics, dailyBudgetAtomics,+ });+ } catch (e) {+ if (String(e?.message || '').includes('agent_vaults_one_active')) {+ return error(res, 409, 'vault_exists', 'this agent already has an open vault');+ }+ throw e;+ }++ await recordVaultEvent({+ vaultId: vault.id, type: 'open', userId,+ reason: 'vault opened', meta: {+ agent_id: agentId, performance_fee_bps: performanceFeeBps, max_drawdown_bps: maxDrawdownBps,+ max_per_trade_atomics: String(maxPerTradeAtomics), daily_budget_atomics: String(dailyBudgetAtomics),+ per_backer_cap_atomics: perBackerCapAtomics != null ? String(perBackerCapAtomics) : null,+ },+ });++ return json(res, 201, { data: { vault: { ...vault, agent_name: agent.name } } }, { 'cache-control': 'no-store' });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (req.method === 'POST') return handleOpen(req, res);+ return handleList(req, res);+});diff --git a/api/vaults/ledger.js b/api/vaults/ledger.jsnew file mode 100644index 000000000..ad0e2fce5--- /dev/null+++ b/api/vaults/ledger.js@@ -0,0 +1,46 @@+// GET /api/vaults/ledger?vault_id=…&before=…&type=…+//+// The vault's immutable audit trail: every open, deposit, redeem, trade, fee,+// drawdown halt, pause/resume and terms change, newest first, with the on-chain+// signature where one exists. Public — this is the transparency that makes backing+// rational.++import { cors, json, method, error, wrap } from '../_lib/http.js';+import { getVault, listVaultEvents } from '../_lib/vault-store.js';+import { explorerTxUrl } from '../_lib/avatar-wallet.js';+import { isUuid } from '../_lib/validate.js';++const TYPES = new Set(['open', 'deposit', 'redeem', 'trade', 'fee', 'fee_claim', 'drawdown_halt', 'pause', 'resume', 'terms', 'close', 'nav']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const vaultId = url.searchParams.get('vault_id') || url.searchParams.get('vaultId');+ if (!vaultId || !isUuid(vaultId)) return error(res, 400, 'validation_error', 'vault_id required');++ const vault = await getVault(vaultId);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');++ const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 50));+ const beforeRaw = url.searchParams.get('before');+ const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? Number(beforeRaw) : null;+ const typeRaw = url.searchParams.get('type');+ const type = typeRaw && TYPES.has(typeRaw) ? typeRaw : null;++ const rows = await listVaultEvents(vaultId, { limit, beforeId, type });+ const items = rows.map((e) => ({+ id: Number(e.id), type: e.type, status: e.status, reason: e.reason,+ shares_delta: e.shares_delta != null ? String(e.shares_delta) : null,+ atomics_delta: e.atomics_delta != null ? String(e.atomics_delta) : null,+ nav_atomics: e.nav_atomics != null ? String(e.nav_atomics) : null,+ share_price_e6: e.share_price_e6 != null ? String(e.share_price_e6) : null,+ signature: e.signature || null,+ explorer: e.signature ? explorerTxUrl(e.signature, vault.network) : null,+ meta: e.meta || {},+ created_at: e.created_at,+ }));+ const nextCursor = rows.length === limit ? Number(rows[rows.length - 1].id) : null;+ return json(res, 200, { data: { items, next_cursor: nextCursor } }, { 'cache-control': 'public, max-age=8, s-maxage=15' });+});diff --git a/api/vaults/redeem.js b/api/vaults/redeem.jsnew file mode 100644index 000000000..b2fd15bb3--- /dev/null+++ b/api/vaults/redeem.js@@ -0,0 +1,40 @@+// POST /api/vaults/redeem { vaultId, shares|'max', idempotency_key? }+//+// Redeem your shares at real NAV. The owner's performance fee is charged only on+// your realized gain. If the vault can't pay the full claim instantly (capital is+// live in open positions), we redeem what the liquid USDC covers and queue the+// rest honestly — never a fake instant number.++import { randomUUID } from 'node:crypto';+import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { authWrite } from '../_lib/vault-auth.js';+import { redeemFromVault } from '../_lib/vault-transfer.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const who = await authWrite(req, res);+ if (!who) return;+ const { userId } = who;++ const rl = await limits.tradePerUser(userId);+ 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 body'); }++ const vaultId = String(body.vaultId || body.vault_id || '').trim();+ if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');+ const sharesIn = body.shares === 'max' || body.shares == null ? 'max' : String(body.shares);++ const result = await redeemFromVault({+ vaultId, userId, shares: sharesIn,+ idempotencyKey: String(body.idempotency_key || `vault-redeem:${vaultId}:${userId}:${randomUUID()}`).slice(0, 128),+ });++ if (result.status === 'failed') return error(res, result.code === 'not_found' ? 404 : 400, result.code, result.message, result.detail ? { detail: result.detail } : {});+ if (result.status === 'queued') return json(res, 202, { data: result }, { 'cache-control': 'no-store' });+ return json(res, 200, { data: result }, { 'cache-control': 'no-store' });+});diff --git a/api/vaults/trade.js b/api/vaults/trade.jsnew file mode 100644index 000000000..dd6bc972a--- /dev/null+++ b/api/vaults/trade.js@@ -0,0 +1,62 @@+// POST /api/vaults/trade { vaultId, side, mint, usdc|amount|'max', slippageBps?, idempotency_key? }+//+// Owner-directed deployment of the POOLED vault capital into a real token position+// (buy: USDC→token) or a harvest back to USDC (sell: token→USDC). Every buy is+// checked against the vault's per-trade ceiling, rolling daily budget and on-chain+// balance before a key is touched; every fill is a real Jupiter swap; and the+// drawdown circuit breaker re-checks NAV after the trade and halts the vault if it+// has fallen past its max-drawdown limit.++import { randomUUID } from 'node:crypto';+import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { authWrite } from '../_lib/vault-auth.js';+import { getVault } from '../_lib/vault-store.js';+import { vaultTrade } from '../_lib/vault-trade.js';+import { usdcToAtomics, toBig } from '../_lib/vault-accounting.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const who = await authWrite(req, res);+ if (!who) return;+ const { userId } = who;++ const rl = await limits.tradePerUser(userId);+ 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 body'); }++ const vaultId = String(body.vaultId || body.vault_id || '').trim();+ const side = body.side === 'sell' ? 'sell' : body.side === 'buy' ? 'buy' : null;+ const mint = String(body.mint || '').trim();+ if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');+ if (!side) return error(res, 400, 'validation_error', 'side must be "buy" or "sell"');+ if (!mint) return error(res, 400, 'validation_error', 'mint required');++ const vault = await getVault(vaultId);+ if (!vault) return error(res, 404, 'not_found', 'vault not found');+ if (vault.owner_user_id !== userId) return error(res, 403, 'forbidden', 'only the vault owner can direct trades');++ const slippageBps = Number.isFinite(Number(body.slippageBps)) ? Math.round(Number(body.slippageBps)) : 100;++ let usdcInAtomics; let amountRaw;+ if (side === 'buy') {+ const usdc = Number(body.usdc);+ if (!(usdc > 0)) return error(res, 400, 'validation_error', 'usdc must be a positive number for a buy');+ usdcInAtomics = usdcToAtomics(usdc);+ } else {+ amountRaw = body.amount === 'max' || body.amount == null ? 'max' : toBig(body.amount);+ }++ const result = await vaultTrade({+ vaultId, userId, side, mint, usdcInAtomics, amountRaw, slippageBps,+ idempotencyKey: String(body.idempotency_key || `vault-trade:${vaultId}:${side}:${mint}:${randomUUID()}`).slice(0, 128),+ });++ if (result.status === 'blocked') return error(res, 403, result.code, result.message, result.detail ? { detail: result.detail } : {});+ if (result.status === 'failed') return error(res, result.code === 'not_found' ? 404 : 400, result.code, result.message, result.detail ? { detail: result.detail } : {});+ return json(res, 200, { data: result }, { 'cache-control': 'no-store' });+});diff --git a/data/changelog.json b/data/changelog.jsonindex e57600d6e..a4e020a59 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,50 @@{"$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 now remembers — and you can watch it recall mid-conversation",+ "summary": "Chat with your agent and it now actually draws on what it knows about you: every reply is grounded in your agent's pinned, always-on memories plus the specific things most relevant to what you just said, pulled live from its real memory store. Nothing is faked — the agent only speaks from memories it genuinely recalled for that message. Under the hood this ships a shared nervous system for the whole platform: one canonical notion of your active agent, so the companion in the corner, the worlds you walk into, and your agent's profile finally all agree on who your agent is — even across browser tabs — plus a real-time event channel that lets every surface react the instant your agent remembers, learns, or changes. It's the foundation the living-agent features build on: your agent becoming a continuous presence instead of stateless decoration.",+ "tags": [+ "improvement",+ "infra"+ ]+ },+ {+ "date": "2026-06-23",+ "title": "Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails",+ "summary": "Your agent's money is now something you direct visually. Open the Money tab in Agent Studio and draw its trading mind as a connected flow of blocks: when to act (new launches within a time window), what to require (market-cap range, liquidity floor, socials, creator history), how much to buy and at what slippage, and how to exit (take-profit, stop-loss, trailing stop, max hold). Every change rewrites a plain-English sentence so you always see exactly what your agent will do — no jargon, no guarantees. Two modes, both real: in Assisted mode the agent scans live launches that fit your rule, shows each one with a real on-chain quote and a rug/honeypot safety verdict, and waits for you to confirm each snipe with one tap; in Autonomous mode you arm the rule and it trades on its own through the same real Solana stack — real quotes, real slippage, real signatures, real confirmations. Safety is enforced on the server, not just in the UI: hard caps on per-trade size, daily budget, price impact, and open positions, plus a one-tap kill switch that halts all autonomous trading instantly. Every decision and fill is written to an exportable audit log and to the agent's own memory, and the avatar reacts live — celebrating fills, flagging dumps. You can also backtest a rule against real captured launch history before you arm it, shown honestly as historical, never as a promise. The agent funds, snipes, and trades from its own custodial wallet; the key never leaves the server. Trading is risky and coins can go to zero — your agent only ever spends what you fund, within the limits you set.",+ "tags": [+ "feature"+ ],+ "link": "/agent-studio"+ },+ {+ "date": "2026-06-23",+ "title": "Instant Agent Genesis: a selfie or a sentence becomes a funded, on-chain 3D agent in under a minute",+ "summary": "Onboarding a new agent used to be a multi-step wizard. Now it's one guided moment. Open Instant Agent Genesis, then either describe how your agent should look, drop in a selfie, or fork a public avatar to make it yours. From there everything happens in parallel and for real: the avatar engine sculpts and rigs a 3D body you watch take shape on a live progress bar, your agent is provisioned with its own custodial Solana and EVM wallet, and the persona and voice you typed are written onto it. Sixty seconds later you meet your agent — its face turning in 3D, its real wallet addresses ready to copy and fund, and a one-click path to register a verifiable ERC-8004 on-chain identity that returns a real transaction you can open on the explorer. From the reveal you can fund and snipe, open your agent, hand it to the trading co-pilot, or share its card. Ownership is unambiguous: the agent, the wallet, and the identity are yours from the first frame. Bring your own Meshy key for higher-fidelity geometry, or use the platform engine as-is.",+ "tags": [+ "feature"+ ],+ "link": "/genesis"+ },+ {+ "date": "2026-06-23",+ "title": "Brain Studio: sculpt your agent's personality and hear the change land instantly",+ "summary": "Personality is no longer a hidden prompt buried behind a five-question interview — it's something you direct. Open the new Brain Studio on your agent's edit page and shape its mind with sliders: warmth, formality, verbosity, humour, proactivity, risk appetite, and directness, plus editable tone words and the signature phrases it reaches for. Move any slider and within about a second the live 3D avatar beside you re-greets in the new register — a real model reply against the candidate personality, streamed token by token, and spoken aloud in your agent's own configured voice. Not sure between two directions? Compare A/B puts your saved persona and your current edits side by side, sends the same prompt to both avatars at once, and lets you promote the winner. Every save is a real version with a note, so you can see exactly how a trait change rewrote the underlying prompt and restore any earlier personality. When you save, your agent re-greets in character everywhere it appears on the platform.",+ "tags": [+ "feature"+ ],+ "link": "/dashboard"+ },+ {+ "date": "2026-06-23",+ "title": "Reflection & Dreams: while you're away, your agent consolidates its memories into insights you review",+ "summary": "Your agent now reflects on its own. On a schedule — and the moment you open the new Dreams tab on its edit page — it reads its own recent memories and action history and runs a real model pass that consolidates them into higher-order insights it calls dreams: patterns it noticed, beliefs it formed about you, questions it wants to ask. Every dream cites the exact memories it was drawn from, so you can see the evidence behind it, not just a claim. You review each one: accept it and it becomes a real, higher-salience memory the agent carries forward; reject it and the agent learns the synthesis was wrong and won't propose it again. Low-confidence dreams come as a question you can answer in a line — your answer is saved as a memory. A dream journal keeps the running history of what your agent kept and let go. Reflection is cost-bounded (a daily cap and a cooldown per agent, with every skipped pass logged) so it never runs away, and it only ever consolidates memories you already own.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","title": "Alpha Co-pilot: your agent reads a real launch in character and speaks its verdict aloud",diff --git a/data/pages.json b/data/pages.jsonindex 3b544b120..2864becdd 100644--- a/data/pages.json+++ b/data/pages.json@@ -216,6 +216,15 @@"added": "2026-06-23","showcase": true},+ {+ "path": "/genesis",+ "title": "Instant Agent Genesis",+ "description": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.",+ "priority": 0.9,+ "changefreq": "weekly",+ "added": "2026-06-23",+ "showcase": true+ },{"path": "/create-agent","title": "Create an Agent",@@ -1022,6 +1031,15 @@"changefreq": "weekly","added": "2026-06-03"},+ {+ "path": "/autopilot-activity",+ "title": "Autopilot Activity",+ "description": "Every autonomous action your three.ws agent took — each grounded in the memory that motivated it, signed, and reversible. Explainable autonomy you can audit.",+ "priority": 0.5,+ "changefreq": "daily",+ "auth": "required",+ "added": "2026-06-23"+ },{"path": "/avatar-wallet-chat","title": "Avatar Wallet",diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex 02ccf524d..74eb19546 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1482,6 +1482,11 @@aria-live="polite"></span></div>+ <!-- Memory-grounded Autopilot: explainable autonomy (scopes, proposals,+ trust, signed receipts). Rendered by src/autopilot-mind.js. -->+ <div id="autopilot-mind" style="margin-top: 1.75rem;">+ <div class="apm-skel" style="height: 90px; border-radius: 12px;"></div>+ </div></section><!-- Voice tab -->diff --git a/pages/autopilot-activity.html b/pages/autopilot-activity.htmlnew file mode 100644index 000000000..31af90db0--- /dev/null+++ b/pages/autopilot-activity.html@@ -0,0 +1,89 @@+<!doctype html>+<html lang="en">+<head>+ <style>/* three.ws hidden-guard */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Autopilot Activity — three.ws</title>+ <meta name="description" content="Every autonomous action your three.ws agent took — each with the memory that motivated it, a signed receipt, and a one-tap undo. Explainable autonomy you can trust." />+ <meta property="og:title" content="Autopilot Activity — three.ws" />+ <meta property="og:description" content="Explainable autonomy: every action your agent took, with the memory that motivated it and a signed receipt." />+ <meta name="twitter:card" content="summary_large_image" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #050505; --surface-0: #0b0b0b; --surface-1: #111; --surface-2: #181818;+ --hairline: #1c1c1c; --text: #f6f6f6; --text-2: #a8a8a8; --text-3: #6a6a6a;+ --mint: #78c88c; --amber: #f59e0b; --red: #ef4444;+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ --font-body: "Inter", -apple-system, system-ui, sans-serif;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--font-body); }+ body { font-size: 15px; line-height: 1.55; min-height: 100vh; -webkit-font-smoothing: antialiased; }+ a { color: inherit; text-decoration: none; }+ .topbar { position: sticky; top: 0; z-index: 50; display: flex; align-items: center; gap: 20px;+ padding: 14px 24px; border-bottom: 1px solid var(--hairline); background: rgba(5,5,5,0.9); backdrop-filter: blur(18px); }+ .brand { display: flex; align-items: center; gap: 9px; font-family: var(--font-display); font-weight: 600; letter-spacing: -0.02em; }+ .brand .glyph { width: 16px; height: 16px; border: 1px solid var(--text); border-radius: 3px; position: relative; }+ .brand .glyph::after { content:''; position:absolute; inset:3px; background: var(--text); }+ .topbar nav { display: flex; gap: 4px; margin-left: auto; }+ .topbar nav a { padding: 6px 10px; font-size: 14px; color: var(--text-2); border-radius: 7px; transition: color .12s, background .12s; }+ .topbar nav a:hover { color: var(--text); background: var(--surface-1); }+ .wrap { max-width: 760px; margin: 0 auto; padding: 28px 24px 80px; }+ .hero h1 { font-family: var(--font-display); font-size: 1.7rem; letter-spacing: -0.03em; margin: 0 0 6px; }+ .hero p { color: var(--text-2); margin: 0 0 18px; max-width: 60ch; }+ .controls { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; }+ .controls label { font-size: 0.8rem; color: var(--text-3); }+ .controls select { padding: 0.4rem 0.6rem; border-radius: 8px; border: 1px solid var(--hairline);+ background: var(--surface-1); color: var(--text); font: inherit; font-size: 0.85rem; }+ .ledger { border: 1px solid var(--hairline); border-radius: 14px; background: var(--surface-1); padding: 0.4rem 1.1rem; }+ .loadmore { display: block; margin: 18px auto 0; }+ .skel { height: 64px; border-radius: 11px; margin: 0.5rem 0; background: linear-gradient(90deg,var(--surface-1) 0%,var(--surface-2) 50%,var(--surface-1) 100%);+ background-size: 200% 100%; animation: shimmer 1.3s infinite; border: 1px solid var(--hairline); }+ @keyframes shimmer { 0%{background-position:200% 0} 100%{background-position:-200% 0} }+ @media (prefers-reduced-motion: reduce) { .skel { animation: none; } }+ .state { text-align: center; color: var(--text-3); padding: 3rem 1rem; }+ .state .ico { font-size: 2rem; opacity: 0.7; }+ .state h2 { font-size: 1.05rem; color: var(--text-2); margin: 0.7rem 0 0.3rem; }+ .state .btn { display: inline-block; margin-top: 1rem; padding: 0.5rem 1rem; border-radius: 8px;+ border: 1px solid var(--hairline); background: var(--surface-2); color: var(--text); cursor: pointer; font: inherit; }+ .state .btn:hover { border-color: var(--text-3); }+ </style>+</head>+<body>+ <header class="topbar">+ <a class="brand" href="/dashboard" aria-label="three.ws"><span class="glyph"></span> three.ws</a>+ <nav>+ <a href="/dashboard">Dashboard</a>+ <a href="/autopilot-activity" class="active" aria-current="page">Activity</a>+ </nav>+ </header>++ <main class="wrap">+ <section class="hero">+ <h1>Autopilot activity</h1>+ <p>Every action your agent took on your behalf — each grounded in the memory that motivated it,+ signed, and reversible where it can be. This is autonomy you can audit.</p>+ </section>++ <div class="controls">+ <label for="agent-filter">Agent</label>+ <select id="agent-filter" aria-label="Filter by agent"><option value="">All your agents</option></select>+ <span id="trust-slot"></span>+ </div>++ <div id="ledger" class="ledger" aria-live="polite">+ <div class="skel"></div><div class="skel"></div><div class="skel"></div>+ </div>+ <button class="loadmore apm-btn" id="loadmore" hidden>Load more</button>+ </main>++ <script type="module" src="/src/autopilot-activity.js"></script>+</body>+</html>diff --git a/prompts/living-agents/04-reflection-and-dreams-engine.md b/prompts/living-agents/04-reflection-and-dreams-engine.mddeleted file mode 100644index 019f1f795..000000000--- a/prompts/living-agents/04-reflection-and-dreams-engine.md+++ /dev/null@@ -1,85 +0,0 @@-# Task 04 — Reflection & Dreams (memory consolidation engine)--> Read `prompts/living-agents/00-README.md` and `CLAUDE.md` first. Depends on Task 01.-> This task has a real backend component (endpoint + table + scheduled worker) — build-> all of it for real. No stubs.--## Mission--Give agents the ability to **reflect** — to consolidate raw memories into higher-order-insights on their own, especially while the user is away — and surface those insights as-reviewable **"dreams."** The user returns to find their agent has genuinely grown: it-noticed patterns, formed beliefs, raised questions. This is what makes an agent feel like-it has an inner life instead of a transcript.--## The innovation bar--This is the Stanford "Generative Agents" reflection mechanism, **productized and made-visible** — which nobody in the consumer-agent space has shipped well. The magic moments:-- "While you were away, I noticed you check $THREE alerts every morning — want me to brief- you automatically?" (a real insight derived from real memory + action logs, proposing a- real Autopilot rule — Task 08.)-- "Three of your conversations were about settlement speed — I've formed a belief: you- prioritize finality over fees." (a synthesized `feedback`/`user` memory at higher salience.)-The user reviews each dream and **accepts** (it becomes a real, higher-salience memory /-proposed action) or **rejects** (the agent learns the synthesis was wrong — that rejection-is itself stored). The agent's growth is consensual and legible.--## What to build--1. **Reflection engine (backend, real LLM).**- - New endpoint `POST /api/agent/reflect` (owner-only) that: pulls the agent's recent- raw memories + `agent_actions` since last reflection, runs a real- Anthropic/OpenAI pass via the existing worker proxy / `api/_lib/chat-models.js`- (default to the latest Claude model per `CLAUDE.md` for synthesis quality), and- produces candidate insights with: the synthesized statement, the source memory ids- it drew from (provenance is mandatory — every dream cites its evidence), a proposed- memory `type`/`salience`, and optionally a proposed Autopilot action.- - Strict output schema; validate; never store an unparseable result.-2. **Storage.** New migration in `api/_lib/migrations/` for an `agent_reflections` (a.k.a.- dreams) table: `id, agent_id, status (pending|accepted|rejected), statement,- source_memory_ids (uuid[]), proposed_type, proposed_salience, proposed_action (jsonb),- created_at, reviewed_at`. Follow the existing schema/migration conventions in- `api/_lib/schema.sql`.-3. **Scheduling (real, not a fake timer).** Run reflection on a real trigger: a scheduled- Cloudflare worker / Vercel cron over agents with recent activity, AND on-demand when the- user opens the review surface. Debounce so you don't reflect on every page load. Respect- rate/cost limits (cap reflections per agent per day; log what was skipped — no silent caps).-4. **Dreams review UI.** A surface (in `/agent/{id}/edit` and reachable from the Companion's- `dream:created` badge) listing pending dreams, each showing the insight + its cited source- memories (link into the Mind Palace, Task 03). Accept → real write to `/api/agent-memory`- at the proposed salience and/or hand a proposed rule to Autopilot (Task 08); Reject →- store the rejection signal. Emit `dream:created` / `memory:added` on the bus.-5. **Make the act of dreaming visible.** When reflection runs, emit a bus event so the- Companion (Task 02) can show the agent "sleeping/dreaming" and the Mind Palace can show- memories consolidating. The visualization must reflect a real reflection run, not a- decorative animation.--## Wiring & real-API mandate--- Real LLM inference through the existing proxy — never a canned insight string.-- Real reads of `agent_memories` + `agent_actions`; real writes on accept.-- Provenance is non-negotiable: a dream with no real source memories is a bug.--## Definition of done--- [ ] `POST /api/agent/reflect` runs a real model pass and persists schema-valid dreams- with cited source memory ids; migration applied and consistent with `schema.sql`.-- [ ] A real scheduled job reflects for active agents with daily caps + skip logging.-- [ ] Review UI: accept writes a real higher-salience memory (verify in Mind Palace) and/or- proposes an Autopilot rule; reject stores the signal. Bus events emitted.-- [ ] Loading/empty ("no new reflections yet")/error states designed; cost/rate limits real.-- [ ] No console errors/warnings; `npm test` passes; `git diff` reviewed.-- [ ] Changelog entry (`feature`) + `npm run build:pages`.--## Self-improvement pass--Ask: does this feel like a mind that grows, or a batch job? Add the elevating layer — a-"dream journal" the user can browse over time, reflections that ask the user a real-clarifying question when confidence is low (and store the answer), or meta-reflection that-prunes/merges stale memories. Build the most compelling one, fully wired and cost-bounded.--## When done--Delete this file. Report the reflection schema, the scheduling mechanism, and the-accept/reject write paths.diff --git a/public/changelog.json b/public/changelog.jsonindex 416babfae..8142b98f0 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:13:30.167Z",+ "generated_at": "2026-06-23T12:20:54.306Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -76,6 +76,16 @@"launch"]},+ {+ "date": "2026-06-23",+ "type": "launch",+ "title": "Instant Agent Genesis",+ "summary": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.",+ "link": "/genesis",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-23","type": "launch",@@ -261,6 +271,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Brain Studio: sculpt your agent's personality and hear the change land instantly",+ "summary": "Personality is no longer a hidden prompt buried behind a five-question interview — it's something you direct. Open the new Brain Studio on your agent's edit page and shape its mind with sliders: warmth, formality, verbosity, humour, proactivity, risk appetite, and directness, plus editable tone words and the signature phrases it reaches for. Move any slider and within about a second the live 3D avatar beside you re-greets in the new register — a real model reply against the candidate personality, streamed token by token, and spoken aloud in your agent's own configured voice. Not sure between two directions? Compare A/B puts your saved persona and your current edits side by side, sends the same prompt to both avatars at once, and lets you promote the winner. Every save is a real version with a note, so you can see exactly how a trait change rewrote the underlying prompt and restore any earlier personality. When you save, your agent re-greets in character everywhere it appears on the platform.",+ "link": "/dashboard",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -549,6 +569,16 @@"infra"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Instant Agent Genesis: a selfie or a sentence becomes a funded, on-chain 3D agent in under a minute",+ "summary": "Onboarding a new agent used to be a multi-step wizard. Now it's one guided moment. Open Instant Agent Genesis, then either describe how your agent should look, drop in a selfie, or fork a public avatar to make it yours. From there everything happens in parallel and for real: the avatar engine sculpts and rigs a 3D body you watch take shape on a live progress bar, your agent is provisioned with its own custodial Solana and EVM wallet, and the persona and voice you typed are written onto it. Sixty seconds later you meet your agent — its face turning in 3D, its real wallet addresses ready to copy and fund, and a one-click path to register a verifiable ERC-8004 on-chain identity that returns a real transaction you can open on the explorer. From the reveal you can fund and snipe, open your agent, hand it to the trading co-pilot, or share its card. Ownership is unambiguous: the agent, the wallet, and the identity are yours from the first frame. Bring your own Meshy key for higher-fidelity geometry, or use the platform engine as-is.",+ "link": "/genesis",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -881,6 +911,16 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Reflection & Dreams: while you're away, your agent consolidates its memories into insights you review",+ "summary": "Your agent now reflects on its own. On a schedule — and the moment you open the new Dreams tab on its edit page — it reads its own recent memories and action history and runs a real model pass that consolidates them into higher-order insights it calls dreams: patterns it noticed, beliefs it formed about you, questions it wants to ask. Every dream cites the exact memories it was drawn from, so you can see the evidence behind it, not just a claim. You review each one: accept it and it becomes a real, higher-salience memory the agent carries forward; reject it and the agent learns the synthesis was wrong and won't propose it again. Low-confidence dreams come as a question you can answer in a line — your answer is saved as a memory. A dream journal keeps the running history of what your agent kept and let go. Reflection is cost-bounded (a daily cap and a cooldown per agent, with every skipped pass logged) so it never runs away, and it only ever consolidates memories you already own.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -1096,6 +1136,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails",+ "summary": "Your agent's money is now something you direct visually. Open the Money tab in Agent Studio and draw its trading mind as a connected flow of blocks: when to act (new launches within a time window), what to require (market-cap range, liquidity floor, socials, creator history), how much to buy and at what slippage, and how to exit (take-profit, stop-loss, trailing stop, max hold). Every change rewrites a plain-English sentence so you always see exactly what your agent will do — no jargon, no guarantees. Two modes, both real: in Assisted mode the agent scans live launches that fit your rule, shows each one with a real on-chain quote and a rug/honeypot safety verdict, and waits for you to confirm each snipe with one tap; in Autonomous mode you arm the rule and it trades on its own through the same real Solana stack — real quotes, real slippage, real signatures, real confirmations. Safety is enforced on the server, not just in the UI: hard caps on per-trade size, daily budget, price impact, and open positions, plus a one-tap kill switch that halts all autonomous trading instantly. Every decision and fill is written to an exportable audit log and to the agent's own memory, and the avatar reacts live — celebrating fills, flagging dumps. You can also backtest a rule against real captured launch history before you arm it, shown honestly as historical, never as a promise. The agent funds, snipes, and trades from its own custodial wallet; the key never leaves the server. Trading is risky and coins can go to zero — your agent only ever spends what you fund, within the limits you set.",+ "link": "/agent-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -1182,6 +1232,17 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Your agent now remembers — and you can watch it recall mid-conversation",+ "summary": "Chat with your agent and it now actually draws on what it knows about you: every reply is grounded in your agent's pinned, always-on memories plus the specific things most relevant to what you just said, pulled live from its real memory store. Nothing is faked — the agent only speaks from memories it genuinely recalled for that message. Under the hood this ships a shared nervous system for the whole platform: one canonical notion of your active agent, so the companion in the corner, the worlds you walk into, and your agent's profile finally all agree on who your agent is — even across browser tabs — plus a real-time event channel that lets every surface react the instant your agent remembers, learns, or changes. It's the foundation the living-agent features build on: your agent becoming a continuous presence instead of stateless decoration.",+ "link": null,+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 58e6d819e..68d15d845 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -62,6 +62,14 @@<category>launch</category><description>The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.</description></item>+ <item>+ <title>Instant Agent Genesis</title>+ <link>https://three.ws/genesis</link>+ <guid isPermaLink="false">2026-06-23:Instant Agent Genesis</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.</description>+ </item><item><title>Live Trading Theater</title><link>https://three.ws/theater</link>@@ -206,6 +214,14 @@<category>fix</category><description>Every avatar you create — a GLB upload, a URL import, or a chat/MCP "text → 3D avatar" — is quietly upgraded in the background so it can walk, wave, and emote. Occasionally the very last step of that upgrade could fail after the rig itself had already succeeded (a momentary storage or network blip), and the avatar would stay static with nothing able to retry it — most likely for avatars made headlessly through the API or MCP, which don't sit on a page polling for the result. The completion process is now crash-safe and eventually-consistent: a rig that finished at the provider always lands on your avatar, recovered no matter which path completes it, even after an earlier failure, and safe when several finish at once. The background safety-net sweep now also clears its backlog faster and never lets a stalled job pile up. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Brain Studio: sculpt your agent's personality and hear the change land instantly</title>+ <link>https://three.ws/dashboard</link>+ <guid isPermaLink="false">2026-06-23:Brain Studio: sculpt your agent's personality and hear the change land instantly</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Personality is no longer a hidden prompt buried behind a five-question interview — it's something you direct. Open the new Brain Studio on your agent's edit page and shape its mind with sliders: warmth, formality, verbosity, humour, proactivity, risk appetite, and directness, plus editable tone words and the signature phrases it reaches for. Move any slider and within about a second the live 3D avatar beside you re-greets in the new register — a real model reply against the candidate personality, streamed token by token, and spoken aloud in your agent's own configured voice. Not sure between two directions? Compare A/B puts your saved persona and your current edits side by side, sends the same prompt to both avatars at once, and lets you promote the winner. Every save is a real version with a note, so you can see exactly how a trait change rewrote the underlying prompt and restore any earlier personality. When you save, your agent re-greets in character everywhere it appears on the platform.</description>+ </item><item><title>Consistent currency formatting across the earnings dashboard</title><link>https://three.ws/changelog</link>@@ -430,6 +446,14 @@<category>improvement</category><description>When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose.</description></item>+ <item>+ <title>Instant Agent Genesis: a selfie or a sentence becomes a funded, on-chain 3D agent in under a minute</title>+ <link>https://three.ws/genesis</link>+ <guid isPermaLink="false">2026-06-23:Instant Agent Genesis: a selfie or a sentence becomes a funded, on-chain 3D agent in under a minute</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Onboarding a new agent used to be a multi-step wizard. Now it's one guided moment. Open Instant Agent Genesis, then either describe how your agent should look, drop in a selfie, or fork a public avatar to make it yours. From there everything happens in parallel and for real: the avatar engine sculpts and rigs a 3D body you watch take shape on a live progress bar, your agent is provisioned with its own custodial Solana and EVM wallet, and the persona and voice you typed are written onto it. Sixty seconds later you meet your agent — its face turning in 3D, its real wallet addresses ready to copy and fund, and a one-click path to register a verifiable ERC-8004 on-chain identity that returns a real transaction you can open on the explorer. From the reveal you can fund and snipe, open your agent, hand it to the trading co-pilot, or share its card. Ownership is unambiguous: the agent, the wallet, and the identity are yours from the first frame. Bring your own Meshy key for higher-fidelity geometry, or use the platform engine as-is.</description>+ </item><item><title>IRL status updates now announced to screen readers</title><link>https://three.ws/irl</link>@@ -686,6 +710,14 @@<category>feature</category><description>Inviting people to three.ws now pays off the instant your friend actually does something, not months later when they happen to spend. Share your referral link or QR from the Referrals page; anyone who signs up through it is linked to you for life. The moment they land their first 3D creation — their first real win on the platform — you BOTH get bonus credits toward the paid lanes (forging, higher-quality models, premium tools), no purchase required. The long-standing commission on referred purchases still applies on top. Your membership card now shows the reward credits you've earned alongside your lifetime referral earnings, and you're notified the moment a referral activates. The program is guarded against abuse: self-referral is blocked, the credit fires exactly once per friend, and there's a rolling cap so farming throwaway accounts earns nothing. Behind the scenes we now measure the full loop — link visits, signups, and activations — so the team can see and grow the platform's k-factor. $THREE is the only coin on three.ws.</description></item>+ <item>+ <title>Reflection & Dreams: while you're away, your agent consolidates its memories into insights you review</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Reflection & Dreams: while you're away, your agent consolidates its memories into insights you review</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent now reflects on its own. On a schedule — and the moment you open the new Dreams tab on its edit page — it reads its own recent memories and action history and runs a real model pass that consolidates them into higher-order insights it calls dreams: patterns it noticed, beliefs it formed about you, questions it wants to ask. Every dream cites the exact memories it was drawn from, so you can see the evidence behind it, not just a claim. You review each one: accept it and it becomes a real, higher-salience memory the agent carries forward; reject it and the agent learns the synthesis was wrong and won't propose it again. Low-confidence dreams come as a question you can answer in a line — your answer is saved as a memory. A dream journal keeps the running history of what your agent kept and let go. Reflection is cost-bounded (a daily cap and a cooldown per agent, with every skipped pass logged) so it never runs away, and it only ever consolidates memories you already own.</description>+ </item><item><title>Security: CSRF protection extended to sniper arming and trade limits</title><link>https://three.ws/changelog</link>@@ -854,6 +886,14 @@<category>fix</category><description>The KOL top-trader leaderboard was returning an error instead of its rankings — its data file wasn't being shipped alongside the function that reads it, so every request failed. The data now travels with the function and the leaderboard resolves normally. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-23:Trading Brain: draw how your agent snipes, and watch it trade for real within your guardrails</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your agent's money is now something you direct visually. Open the Money tab in Agent Studio and draw its trading mind as a connected flow of blocks: when to act (new launches within a time window), what to require (market-cap range, liquidity floor, socials, creator history), how much to buy and at what slippage, and how to exit (take-profit, stop-loss, trailing stop, max hold). Every change rewrites a plain-English sentence so you always see exactly what your agent will do — no jargon, no guarantees. Two modes, both real: in Assisted mode the agent scans live launches that fit your rule, shows each one with a real on-chain quote and a rug/honeypot safety verdict, and waits for you to confirm each snipe with one tap; in Autonomous mode you arm the rule and it trades on its own through the same real Solana stack — real quotes, real slippage, real signatures, real confirmations. Safety is enforced on the server, not just in the UI: hard caps on per-trade size, daily budget, price impact, and open positions, plus a one-tap kill switch that halts all autonomous trading instantly. Every decision and fill is written to an exportable audit log and to the agent's own memory, and the avatar reacts live — celebrating fills, flagging dumps. You can also backtest a rule against real captured launch history before you arm it, shown honestly as historical, never as a promise. The agent funds, snipes, and trades from its own custodial wallet; the key never leaves the server. Trading is risky and coins can go to zero — your agent only ever spends what you fund, within the limits you set.</description>+ </item><item><title>Treasury Autopilot — the agent that funds its own existence</title><link>https://three.ws/changelog</link>@@ -918,6 +958,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 now remembers — and you can watch it recall mid-conversation</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Your agent now remembers — and you can watch it recall mid-conversation</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Chat with your agent and it now actually draws on what it knows about you: every reply is grounded in your agent's pinned, always-on memories plus the specific things most relevant to what you just said, pulled live from its real memory store. Nothing is faked — the agent only speaks from memories it genuinely recalled for that message. Under the hood this ships a shared nervous system for the whole platform: one canonical notion of your active agent, so the companion in the corner, the worlds you walk into, and your agent's profile finally all agree on who your agent is — even across browser tabs — plus a real-time event channel that lets every surface react the instant your agent remembers, learns, or changes. It's the foundation the living-agent features build on: your agent becoming a continuous presence instead of stateless decoration.</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>diff --git a/public/features.json b/public/features.jsonindex 2c12a2e04..fac147d54 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T12:13:30.151Z",+ "generated_at": "2026-06-23T12:20:54.280Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -262,6 +262,16 @@"tags": [],"showcase": true},+ {+ "path": "/genesis",+ "title": "Instant Agent Genesis",+ "description": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.",+ "added": "2026-06-23",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": true+ },{"path": "/create-agent","title": "Create an Agent",diff --git a/public/llms-full.txt b/public/llms-full.txtindex efc595722..35eabb4bc 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -162,6 +162,12 @@ URL: https://three.ws/genomeBreed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skill licenses — each breeding event seed-recorded so the lineage is re-derivable and forgery-detectable, with a verifiable family tree on every parent and child.+### Instant Agent Genesis++URL: https://three.ws/genesis++A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.+### Create an AgentURL: https://three.ws/create-agentdiff --git a/public/llms.txt b/public/llms.txtindex 8dbd53516..2647aa465 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -39,6 +39,7 @@ Create and customize an agent.- [Create Agent](https://three.ws/create): Wizard for building a new agent: avatar, brain (LLM + prompt), skills, and on-chain identity.- [Agent Genome — breed two agents](https://three.ws/genome): Breed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skill licenses — each breeding event seed-recorded so the lineage is re-derivable and forgery-detectable, with a verifiable family tree on every parent and child.+- [Instant Agent Genesis](https://three.ws/genesis): A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.- [Create an Agent](https://three.ws/create-agent): Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.- [Viewer](https://three.ws/app): Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser.- [Describe it to 3D](https://three.ws/create/prompt): Type a description. About a minute later: a rigged 3D avatar you can animate and download.diff --git a/public/nav-data.js b/public/nav-data.jsindex 0d81aa8f6..e8180d838 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -24,6 +24,12 @@ export const NAV_GROUPS = [{label: 'Build',items: [+ {+ title: 'Instant Agent Genesis',+ href: '/genesis',+ badge: 'New',+ desc: 'Selfie or prompt → 3D agent + funded wallet + on-chain identity in 60s',+ },{title: 'Text to 3D',href: '/forge',diff --git a/public/nav.js b/public/nav.jsindex 301744969..52e3e5778 100644--- a/public/nav.js+++ b/public/nav.js@@ -159,11 +159,32 @@ function ensureSkipLink() {document.body.insertBefore(link, document.body.firstChild);}+// Load the Living-Agents bus on any page when the operator opts in with+// ?agentbus=1, so the debug overlay (a dev tool, not product UI) can mount and+// log live bus events anywhere. The bus module self-mounts the overlay from the+// query flag; off by default, it costs nothing.+function loadAgentBusDebug() {+ let on = false;+ try {+ const flag = new URLSearchParams(location.search).get('agentbus');+ on = flag === '1' || flag === 'true';+ } catch (_) {+ on = false;+ }+ if (!on) return;+ if (document.querySelector('script[src="/agent-bus.js"]')) return;+ const s = document.createElement('script');+ s.type = 'module';+ s.src = '/agent-bus.js';+ document.head.appendChild(s);+}+function boot() {ensureSkipLink();loadCornerStack();loadGlossary();loadSearch();+ loadAgentBusDebug();loadDiscovery();loadGettingStarted();loadThemeSwitcher();diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 2b1431ec7..1fc2e26aa 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 320 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 321 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 320 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 321 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -252,7 +252,7 @@<section class="sm-section" id="build"><header>- <h2>Build<span class="sm-count" data-count>35</span></h2>+ <h2>Build<span class="sm-count" data-count>36</span></h2><p class="sm-section-desc">Create and customize an agent.</p></header><ul class="sm-list">@@ -277,6 +277,13 @@<span class="sm-desc">Breed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skill licenses — each breeding event seed-recorded so the lineage is re-derivable and forgery-detectable, with a verifiable family tree on every parent and child.</span></a></li>+ <li>+ <a href="/genesis">+ <span class="sm-title">Instant Agent Genesis</span>+ <span class="sm-path">/genesis</span>+ <span class="sm-desc">A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.</span>+ </a>+ </li><li><a href="/create-agent"><span class="sm-title">Create an Agent</span>diff --git a/public/studio-panels.css b/public/studio-panels.cssindex 20dc2deb6..72a9a4d81 100644--- a/public/studio-panels.css+++ b/public/studio-panels.css@@ -475,3 +475,299 @@.skl-switch-knob,.bdy-chip-pin { transition: none; }}++/* ═══════════════════════════════════════════════════════════════════════════+ Money panel — holdings, activity, withdraw (P4 additions)+ ═══════════════════════════════════════════════════════════════════════════ */+.studio-btn-danger {+ background: color-mix(in srgb, var(--danger, #f87171) 16%, transparent);+ color: var(--danger, #f87171);+ border-color: color-mix(in srgb, var(--danger, #f87171) 45%, transparent);+}+.studio-btn-danger:hover { background: color-mix(in srgb, var(--danger, #f87171) 26%, transparent); }++.mny-sub-head {+ margin: var(--space-md, 1rem) 0 8px;+ font-size: var(--text-2xs, 0.6875rem);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint, rgba(255, 255, 255, 0.45));+ font-weight: var(--weight-semibold, 600);+ display: flex; align-items: center; gap: 8px;+}+.mny-count {+ font-size: var(--text-2xs, 0.6875rem);+ padding: 1px 7px;+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ color: var(--ink-dim, #888);+ letter-spacing: 0;+}+.mny-faint { color: var(--ink-faint, rgba(255, 255, 255, 0.45)); font-size: var(--text-md, 0.8125rem); margin: 6px 0; }+.mny-skel-line { height: 14px; border-radius: 6px; background: var(--surface-2); animation: mny-pulse 1.4s ease-in-out infinite; }+@keyframes mny-pulse { 0%, 100% { opacity: 0.4; } 50% { opacity: 0.8; } }++.mny-hold-list, .mny-act-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }+.mny-hold-row, .mny-act-row {+ display: flex; align-items: center; gap: 10px;+ padding: 7px 10px;+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke);+ font-size: var(--text-md, 0.8125rem);+}+.mny-hold-mint, .mny-act-tx { color: var(--ink-dim, #888); text-decoration: none; font-family: var(--font-mono); font-size: var(--text-2xs, 0.6875rem); }+.mny-hold-mint:hover, .mny-act-tx:hover { color: var(--ink-bright, #fff); }+.mny-hold-amt { margin-left: auto; color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+.mny-act-sum { color: var(--ink, #e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.mny-act-delta { margin-left: auto; font-variant-numeric: tabular-nums; color: var(--ink-dim); }+.mny-act-delta.pos, .pos { color: var(--success, #4ade80); }+.mny-act-delta.neg, .neg { color: var(--danger, #f87171); }+.mny-act-row.is-fail .mny-act-sum { color: var(--danger, #f87171); }++.mny-withdraw {+ margin-top: var(--space-md, 1rem);+ padding: var(--space-md, 1rem);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke);+}+.mny-withdraw-head { font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); margin-bottom: 10px; }+.mny-withdraw-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }+.mny-withdraw-row input {+ flex: 1 1 140px; min-width: 0;+ padding: 8px 12px;+ border-radius: var(--radius-md, 10px);+ background: var(--bg-0, #0a0a0a);+ border: 1px solid var(--stroke);+ color: var(--ink-bright, #fff);+ font-size: var(--text-md, 0.8125rem);+}+.mny-withdraw-row input[data-wd="amount"] { flex: 0 1 120px; }+.mny-withdraw-row .studio-btn { margin-top: 0; }+.mny-withdraw-result { margin-top: 10px; font-size: var(--text-md, 0.8125rem); color: var(--success, #4ade80); }+.mny-withdraw-result a { color: var(--success, #4ade80); }++/* ═══════════════════════════════════════════════════════════════════════════+ Trading Brain (.tb-*) — the visual sniping/trading rule builder+ ═══════════════════════════════════════════════════════════════════════════ */+.tb { display: block; }+.tb-head { display: flex; flex-wrap: wrap; gap: var(--space-md, 1rem); align-items: flex-start; justify-content: space-between; margin-bottom: var(--space-md, 1rem); }+.tb-title h3 { margin: 0; font-family: var(--font-display); font-size: var(--text-lg, 1.236rem); color: var(--ink-bright, #fff); }+.tb-title p { margin: 4px 0 0; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); max-width: 46ch; line-height: var(--leading-normal, 1.618); }+.tb-head-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }++.tb-mode { display: inline-flex; padding: 3px; border-radius: var(--radius-pill, 999px); background: var(--surface-2, rgba(255, 255, 255, 0.05)); border: 1px solid var(--stroke); }+.tb-mode-btn {+ border: 0; background: transparent; cursor: pointer;+ padding: 6px 14px; border-radius: var(--radius-pill, 999px);+ font-size: var(--text-md, 0.8125rem); font-weight: var(--weight-semibold, 600);+ color: var(--ink-dim, #888); transition: all var(--duration-fast) var(--ease-standard);+}+.tb-mode-btn.is-on { background: var(--ink-bright, #fff); color: var(--bg-0, #0a0a0a); }+.tb-mode-btn:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }++.tb-status { font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600); padding: 4px 10px; border-radius: var(--radius-pill, 999px); }+.tb-status-live { color: var(--success, #4ade80); background: color-mix(in srgb, var(--success, #4ade80) 14%, transparent); }++.tb-kill {+ cursor: pointer;+ padding: 7px 14px; border-radius: var(--radius-pill, 999px);+ font-size: var(--text-md, 0.8125rem); font-weight: var(--weight-bold, 700);+ background: color-mix(in srgb, var(--danger, #f87171) 14%, transparent);+ color: var(--danger, #f87171);+ border: 1px solid color-mix(in srgb, var(--danger, #f87171) 40%, transparent);+ transition: all var(--duration-fast) var(--ease-standard);+}+.tb-kill:hover { background: color-mix(in srgb, var(--danger, #f87171) 24%, transparent); }+.tb-kill.is-killed { background: var(--danger, #f87171); color: #fff; box-shadow: 0 0 0 4px color-mix(in srgb, var(--danger, #f87171) 22%, transparent); }+.tb-kill:focus-visible { outline: 2px solid var(--danger, #f87171); outline-offset: 2px; }++.tb-disclosure {+ margin: 0 0 var(--space-md, 1rem);+ padding: 10px 14px;+ border-radius: var(--radius-md, 10px);+ background: color-mix(in srgb, var(--warn, #fbbf24) 7%, transparent);+ border: 1px solid color-mix(in srgb, var(--warn, #fbbf24) 26%, transparent);+ color: var(--ink, #e8e8e8);+ font-size: var(--text-md, 0.8125rem); line-height: var(--leading-normal, 1.618);+}++/* — Visual flow — */+.tb-name { display: flex; flex-direction: column; gap: 5px; margin-bottom: var(--space-md, 1rem); }+.tb-name input {+ padding: 9px 13px; border-radius: var(--radius-md, 10px);+ background: var(--bg-0, #0a0a0a); border: 1px solid var(--stroke);+ color: var(--ink-bright, #fff); font-size: var(--text-base, 1rem); font-weight: var(--weight-semibold, 600);+}+.tb-flow { display: flex; flex-direction: column; align-items: stretch; }+.tb-connector { display: flex; justify-content: center; height: 18px; }+.tb-connector span { width: 2px; height: 100%; background: linear-gradient(var(--wallet-stroke, rgba(139, 92, 246, 0.3)), var(--stroke)); }++.tb-node {+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-glass, linear-gradient(180deg, rgba(20, 21, 28, 0.7), rgba(14, 15, 22, 0.5)));+ border: 1px solid var(--stroke);+ overflow: hidden;+ transition: border-color var(--duration-fast) var(--ease-standard);+}+.tb-node:hover { border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14)); }+.tb-node-head {+ display: flex; align-items: center; gap: 9px;+ padding: 10px 14px;+ border-bottom: 1px solid var(--stroke);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+}+.tb-node-glyph {+ display: grid; place-items: center; width: 24px; height: 24px;+ border-radius: var(--radius-sm, 6px);+ background: var(--wallet-accent-soft, rgba(139, 92, 246, 0.1));+ color: var(--wallet-accent, #c4b5fd); font-size: 14px;+}+.tb-node-title { font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); font-size: var(--text-ui, 0.875rem); }+.tb-node-body { padding: 12px 14px; display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px 14px; }++.tb-field { display: flex; flex-direction: column; gap: 4px; }+.tb-field-l { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); }+.tb-input-wrap { display: flex; align-items: center; gap: 6px; }+.tb-input-wrap input {+ flex: 1 1 auto; min-width: 0;+ padding: 7px 10px; border-radius: var(--radius-md, 10px);+ background: var(--bg-0, #0a0a0a); border: 1px solid var(--stroke);+ color: var(--ink-bright, #fff); font-size: var(--text-md, 0.8125rem); font-variant-numeric: tabular-nums;+}+.tb-input-wrap input:focus { outline: none; border-color: var(--wallet-stroke, rgba(139, 92, 246, 0.4)); }+.tb-suffix { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-faint, rgba(255, 255, 255, 0.45)); white-space: nowrap; }+.tb-check { display: flex; align-items: center; gap: 7px; font-size: var(--text-md, 0.8125rem); color: var(--ink, #e8e8e8); align-self: end; }+.tb-check input { accent-color: var(--wallet-accent, #c4b5fd); }+.tb-err { grid-column: 1 / -1; font-size: var(--text-2xs, 0.6875rem); color: var(--danger, #f87171); }++.tb-english {+ margin: var(--space-md, 1rem) 0 0;+ padding: 11px 14px;+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px dashed var(--stroke-strong, rgba(255, 255, 255, 0.14));+ color: var(--ink, #e8e8e8); font-size: var(--text-md, 0.8125rem); line-height: var(--leading-normal, 1.618);+}++/* — Cards (guardrails, backtest, positions, audit) — */+.tb-guardrails, .tb-assisted, .tb-backtest, .tb-positions, .tb-audit {+ margin-top: var(--space-lg, 1.618rem);+}+.tb-guardrails {+ padding: var(--space-md, 1rem);+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke);+}+.tb-card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }+.tb-card-head h4 { margin: 0; font-family: var(--font-display); font-size: var(--text-ui, 0.875rem); color: var(--ink-bright, #fff); display: flex; align-items: center; gap: 8px; }+.tb-card-head p { margin: 3px 0 0; width: 100%; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); line-height: var(--leading-normal, 1.618); }+.tb-badge {+ font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600);+ padding: 2px 8px; border-radius: var(--radius-pill, 999px);+ background: var(--surface-3, rgba(255, 255, 255, 0.08)); color: var(--ink-dim, #888);+ letter-spacing: 0; text-transform: none;+}+.tb-badge-high { background: color-mix(in srgb, var(--success, #4ade80) 16%, transparent); color: var(--success, #4ade80); }+.tb-badge-medium { background: color-mix(in srgb, var(--warn, #fbbf24) 16%, transparent); color: var(--warn, #fbbf24); }+.tb-badge-low { background: color-mix(in srgb, var(--danger, #f87171) 14%, transparent); color: var(--danger, #f87171); }++.tb-glimits { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px 14px; }+.tb-glimits-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-top: 12px; flex-wrap: wrap; }+.tb-spent { font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); }+.tb-glimits-foot .studio-btn { margin-top: 0; }++.tb-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: var(--space-lg, 1.618rem); }+.tb-actions .studio-btn { margin-top: 0; }++.tb-hint { padding: 12px 14px; border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke); color: var(--ink-dim, #888); font-size: var(--text-md, 0.8125rem); line-height: var(--leading-normal, 1.618); margin-top: var(--space-md, 1rem); }+.tb-hint-warn { border-color: color-mix(in srgb, var(--warn, #fbbf24) 30%, transparent); color: var(--warn, #fbbf24); }++/* — Assisted candidates — */+.tb-cands { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }+.tb-cand {+ display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;+ padding: 12px 14px; border-radius: var(--radius-lg, 14px);+ background: var(--surface-glass, linear-gradient(180deg, rgba(20, 21, 28, 0.7), rgba(14, 15, 22, 0.5)));+ border: 1px solid var(--stroke);+ transition: border-color var(--duration-fast) var(--ease-standard), opacity var(--duration-base) var(--ease-out);+}+.tb-cand:hover { border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14)); }+.tb-cand-done { opacity: 0.55; }+.tb-cand-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; }+.tb-cand-id { display: flex; align-items: center; gap: 8px; }+.tb-cand-id b { color: var(--ink-bright, #fff); font-size: var(--text-ui, 0.875rem); }+.tb-cand-link { font-family: var(--font-mono); font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); text-decoration: none; }+.tb-cand-link:hover { color: var(--ink-bright, #fff); }+.tb-cand-meta { display: flex; gap: 10px; flex-wrap: wrap; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); }+.tb-cand-side { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }+.tb-cand-out { font-size: var(--text-md, 0.8125rem); color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+.tb-cand-out i { color: var(--ink-faint, rgba(255, 255, 255, 0.45)); font-style: normal; font-size: var(--text-2xs, 0.6875rem); }+.tb-cand-side .studio-btn { margin-top: 0; }+.tb-fw { font-size: var(--text-2xs, 0.6875rem); font-weight: var(--weight-semibold, 600); padding: 3px 9px; border-radius: var(--radius-pill, 999px); }+.tb-fw-ok { background: color-mix(in srgb, var(--success, #4ade80) 16%, transparent); color: var(--success, #4ade80); }+.tb-fw-warn { background: color-mix(in srgb, var(--warn, #fbbf24) 16%, transparent); color: var(--warn, #fbbf24); }+.tb-fw-block { background: color-mix(in srgb, var(--danger, #f87171) 16%, transparent); color: var(--danger, #f87171); }++/* — Backtest — */+.tb-bt-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(96px, 1fr)); gap: 10px; }+.tb-bt-stat { padding: 12px; border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke); text-align: center; }+.tb-bt-stat b { display: block; font-size: var(--text-lg, 1.236rem); font-family: var(--font-display); color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+.tb-bt-stat b.pos { color: var(--success, #4ade80); }+.tb-bt-stat b.neg { color: var(--danger, #f87171); }+.tb-bt-stat span { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim, #888); }+.tb-caveats { margin-top: 12px; font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); }+.tb-caveats summary { cursor: pointer; color: var(--ink, #e8e8e8); }+.tb-caveats ul { margin: 8px 0 0; padding-left: 18px; line-height: var(--leading-normal, 1.618); }++/* — Positions — */+.tb-pos, .tb-audit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }+.tb-pos-row {+ display: grid; grid-template-columns: 1.4fr 0.9fr 0.9fr 1.2fr; gap: 10px; align-items: center;+ padding: 10px 12px; border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke);+ font-size: var(--text-md, 0.8125rem);+}+.tb-pos-id { display: flex; align-items: center; gap: 8px; }+.tb-pos-id b { color: var(--ink-bright, #fff); }+.tb-pos-id a { color: var(--ink-dim, #888); text-decoration: none; font-size: var(--text-2xs, 0.6875rem); }+.tb-pos-id a:hover { color: var(--ink-bright, #fff); }+.tb-pos-live { color: var(--success, #4ade80); }+.tb-pos-state { color: var(--ink-dim, #888); }+.tb-pos-entry { color: var(--ink-dim, #888); font-variant-numeric: tabular-nums; }+.tb-pos-pnl { text-align: right; font-variant-numeric: tabular-nums; color: var(--ink, #e8e8e8); }+.tb-pos-pnl.pos { color: var(--success, #4ade80); }+.tb-pos-pnl.neg { color: var(--danger, #f87171); }++/* — Audit — */+.tb-export { margin-top: 0 !important; }+.tb-audit-row {+ display: grid; grid-template-columns: 0.7fr 1.4fr 1fr 0.7fr auto; gap: 10px; align-items: center;+ padding: 8px 12px; border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke);+ font-size: var(--text-md, 0.8125rem);+}+.tb-audit-time { color: var(--ink-faint, rgba(255, 255, 255, 0.45)); font-size: var(--text-2xs, 0.6875rem); }+.tb-audit-what { color: var(--ink, #e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.tb-audit-amt { color: var(--ink-dim, #888); font-variant-numeric: tabular-nums; }+.tb-audit-status { font-size: var(--text-2xs, 0.6875rem); text-align: center; }+.tb-audit-confirmed { color: var(--success, #4ade80); }+.tb-audit-failed { color: var(--danger, #f87171); }+.tb-audit-pending { color: var(--warn, #fbbf24); }+.tb-audit-tx { color: var(--ink-dim, #888); text-decoration: none; }+.tb-audit-tx:hover { color: var(--ink-bright, #fff); }++.tb-skel { height: 280px; border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255, 255, 255, 0.03)); animation: mny-pulse 1.4s ease-in-out infinite; }+.tb-skel.small { height: 90px; }++@media (max-width: 540px) {+ .tb-pos-row { grid-template-columns: 1fr 1fr; }+ .tb-audit-row { grid-template-columns: 1fr auto; }+ .tb-audit-time, .tb-audit-amt { display: none; }+ .tb-cand { flex-direction: column; align-items: flex-start; }+}+@media (prefers-reduced-motion: reduce) {+ .tb-skel, .mny-skel-line { animation: none; }+}diff --git a/src/agent-detail.js b/src/agent-detail.jsindex eab0dcd22..23a161068 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -20,6 +20,7 @@ import { hydrateAvatarWallet } from './shared/wallet-aura.js';import { mountPresence } from './shared/networth-presence.js';import { mountStagePanel } from './shared/stage-link.js';import { mountLaborPanel } from './shared/labor-link.js';+import { mountAlphaPanel } from './shared/alpha-copilot-link.js';import { renderError as renderAsyncError } from './shared/async-state.js';import { skeletonHTML } from './shared/state-kit.js';import { openCoinLaunch } from './shared/agent-coin.js';@@ -74,6 +75,10 @@ function mountAgentDetailAura(agent) {// reputation) + a link to post or work for hire. Enhancement only.mountLaborPanel({ agentId: agent.id, agentName: agent.name || 'this agent', isOwner: !!agent.isOwner, container: main, position: 'prepend' }).catch(() => { /* never block the profile */ });+ // Alpha Co-pilot cross-link: hear this agent read a real live launch in+ // character and (for the owner) act within its spend limits. Enhancement.+ mountAlphaPanel({ agentId: agent.id, agentName: agent.name || 'this agent', isOwner: !!agent.isOwner, container: main, position: 'prepend' })+ .catch(() => { /* never block the profile */ });}}).catch(() => { /* dormant baseline already shown */ });diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 12a334f75..d1cfb1812 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -6,6 +6,7 @@ import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';import { log } from './shared/log.js';import { isValidGlbMagic } from './shared/glb-magic.js';import { agentBus } from './agents/agent-bus.js';+import { mountAutopilotMind } from './autopilot-mind.js';const API_BASE = '/api';const params = new URLSearchParams(location.search);@@ -3024,12 +3025,24 @@ async function ensureBrainTab() {}}+// Memory-grounded Autopilot — explainable autonomy. The strategy textarea above+// stays; this mounts the scopes / proposals / trust / signed-receipts surface.+let autopilotMounted = false;+function ensureAutopilotTab() {+ if (autopilotMounted || !agentId) return;+ const host = $('autopilot-mind');+ if (!host) return;+ autopilotMounted = true;+ mountAutopilotMind(host, { agentId });+}+const TAB_LOADERS = {brain: ensureBrainTab,outfit: ensureOutfitTab,voice: ensureVoiceTab,knowledge: ensureKnowledgeTab,dreams: ensureDreamsTab,+ autopilot: ensureAutopilotTab,skills: ensureSkillsTab,wallet: ensureWalletTab,social: ensureSocialTab,diff --git a/src/agents/agent-bus-debug.js b/src/agents/agent-bus-debug.jsindex f2ea3ac3b..9b3c31cd3 100644--- a/src/agents/agent-bus-debug.js+++ b/src/agents/agent-bus-debug.js@@ -10,7 +10,10 @@import { agentBus, AGENT_EVENTS } from './agent-bus.js';const MAX_ROWS = 200;-let mounted = false;+const PANEL_ID = 'agentbus-debug';+// The wildcard subscription from the live panel, so a re-mount (after an SPA+// route swap wiped the body) can drop the stale one instead of leaking it.+let offWild = null;// A stable, readable colour per event family so the stream is scannable.const COLORS = {@@ -56,10 +59,15 @@ function summarize(type, payload) {}}-/** Mount the overlay (idempotent). Safe to call repeatedly. */+/** Mount the overlay (idempotent). Safe to call repeatedly; re-mounts if the+ * panel was removed (e.g. a client-side route swap wiped the body). */export function mountAgentBusDebug() {- if (mounted || typeof document === 'undefined') return;- mounted = true;+ if (typeof document === 'undefined') return;+ if (document.getElementById(PANEL_ID)) return; // already live+ if (offWild) {+ offWild(); // drop the subscriber from a panel that got wiped+ offWild = null;+ }const style = document.createElement('style');style.textContent = `@@ -123,7 +131,7 @@ export function mountAgentBusDebug() {e.currentTarget.setAttribute('aria-label', collapsed ? 'Expand log' : 'Collapse log');});- agentBus.on('*', (payload, type) => {+ offWild = agentBus.on('*', (payload, type) => {empty.style.display = 'none';const row = document.createElement('div');row.className = 'row';diff --git a/src/agents/agent-bus-debug.test.js b/src/agents/agent-bus-debug.test.jsnew file mode 100644index 000000000..aff30ba54--- /dev/null+++ b/src/agents/agent-bus-debug.test.js@@ -0,0 +1,42 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach } from 'vitest';+import { agentBus } from './agent-bus.js';+import { mountAgentBusDebug } from './agent-bus-debug.js';++describe('agent-bus debug overlay (the verification surface)', () => {+ beforeEach(() => {+ agentBus.reset();+ document.head.innerHTML = '';+ document.body.innerHTML = '';+ });++ it('mounts a single panel and renders a row per emitted event', () => {+ mountAgentBusDebug();+ mountAgentBusDebug(); // idempotent+ const panels = document.querySelectorAll('#agentbus-debug');+ expect(panels).toHaveLength(1);++ agentBus.emit('agent:changed', { agentId: 'a1', agent: { name: 'Ada' } });+ agentBus.emit('memory:recalled', {+ agentId: 'a1',+ memories: [{ id: 'm1', type: 'user', tier: 'recall', salience: 0.5, snippet: 'hi', match: 'semantic' }],+ semantic: true,+ });++ const rows = document.querySelectorAll('#agentbus-debug .row');+ expect(rows).toHaveLength(2);+ expect(document.querySelector('#agentbus-debug [data-count]').textContent).toBe('2 events');+ // The recall row summarises the count + semantic flag for at-a-glance debugging.+ expect(rows[1].textContent).toContain('1 recalled');+ expect(rows[1].textContent).toContain('semantic');+ });++ it('clears the log on demand', () => {+ mountAgentBusDebug();+ agentBus.emit('mood:changed', { agentId: 'a1', mood: 'calm' });+ expect(document.querySelectorAll('#agentbus-debug .row')).toHaveLength(1);+ document.querySelector('#agentbus-debug [data-clear]').click();+ expect(document.querySelectorAll('#agentbus-debug .row')).toHaveLength(0);+ expect(document.querySelector('#agentbus-debug [data-count]').textContent).toBe('0 events');+ });+});diff --git a/src/agents/agent-bus.test.js b/src/agents/agent-bus.test.jsnew file mode 100644index 000000000..9933dc6e7--- /dev/null+++ b/src/agents/agent-bus.test.js@@ -0,0 +1,143 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { agentBus, AGENT_EVENTS, EVENTS, WILDCARD } from './agent-bus.js';++const wait = (ms) => new Promise((r) => setTimeout(r, ms));++describe('agent-bus contract', () => {+ beforeEach(() => agentBus.reset());++ it('exposes the nine shared event types in both forms', () => {+ expect(AGENT_EVENTS).toHaveLength(9);+ expect(AGENT_EVENTS).toContain('memory:recalled');+ expect(EVENTS.MEMORY_RECALLED).toBe('memory:recalled');+ expect(WILDCARD).toBe('*');+ });++ it('delivers an emitted payload to a typed subscriber', () => {+ const seen = [];+ agentBus.on('memory:added', (p) => seen.push(p));+ agentBus.emit('memory:added', { agentId: 'a1', memory: { id: 'm1' } });+ expect(seen).toHaveLength(1);+ expect(seen[0].agentId).toBe('a1');+ expect(seen[0].memory.id).toBe('m1');+ });++ it('passes through a server-provided ts and stamps a fallback otherwise', () => {+ const got = [];+ agentBus.on('mood:changed', (p) => got.push(p.ts));+ const serverTs = '2026-01-02T03:04:05.000Z';+ agentBus.emit('mood:changed', { agentId: 'a1', mood: 'calm', ts: serverTs });+ agentBus.emit('mood:changed', { agentId: 'a1', mood: 'curious' });+ expect(got[0]).toBe(serverTs);+ expect(typeof got[1]).toBe('string');+ expect(() => new Date(got[1]).toISOString()).not.toThrow();+ });++ it('freezes the delivered payload so subscribers cannot corrupt shared state', () => {+ let captured;+ agentBus.on('agent:changed', (p) => (captured = p));+ agentBus.emit('agent:changed', { agentId: 'a1', agent: null });+ expect(Object.isFrozen(captured)).toBe(true);+ });++ it('rejects unknown event types on both emit and on', () => {+ expect(() => agentBus.emit('not:real', {})).toThrow(/unknown event/);+ expect(() => agentBus.on('also:fake', () => {})).toThrow(/unknown event/);+ });++ it('unsubscribes via the returned function', () => {+ const seen = [];+ const off = agentBus.on('memory:added', (p) => seen.push(p));+ agentBus.emit('memory:added', { agentId: 'a' });+ off();+ agentBus.emit('memory:added', { agentId: 'a' });+ expect(seen).toHaveLength(1);+ });++ it('once fires exactly once', () => {+ let n = 0;+ agentBus.once('dream:created', () => (n += 1));+ agentBus.emit('dream:created', { agentId: 'a', dreamId: 'd', insight: 'x' });+ agentBus.emit('dream:created', { agentId: 'a', dreamId: 'd2', insight: 'y' });+ expect(n).toBe(1);+ });++ it('wildcard subscribers see every event with its type', () => {+ const log = [];+ agentBus.on(WILDCARD, (p, type) => log.push([type, p.agentId]));+ agentBus.emit('memory:added', { agentId: 'a1' });+ agentBus.emit('mood:changed', { agentId: 'a2', mood: 'up' });+ expect(log).toEqual([+ ['memory:added', 'a1'],+ ['mood:changed', 'a2'],+ ]);+ });++ it('isolates a throwing subscriber from the others and the emitter', () => {+ const seen = [];+ agentBus.on('action:taken', () => {+ throw new Error('boom');+ });+ agentBus.on('action:taken', (p) => seen.push(p.kind));+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() => agentBus.emit('action:taken', { agentId: 'a', kind: 'alert', summary: 's' })).not.toThrow();+ expect(seen).toEqual(['alert']);+ errSpy.mockRestore();+ });++ describe('replay (late-mounting surfaces catch up)', () => {+ it('last() returns the most recent payload, or null', () => {+ expect(agentBus.last('brain:updated')).toBeNull();+ agentBus.emit('brain:updated', { agentId: 'a', change: 'first' });+ agentBus.emit('brain:updated', { agentId: 'a', change: 'second' });+ expect(agentBus.last('brain:updated').change).toBe('second');+ });++ it('replay:true delivers only the last payload on subscribe', () => {+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'm1' } });+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'm2' } });+ const seen = [];+ agentBus.on('memory:added', (p) => seen.push(p.memory.id), { replay: true });+ expect(seen).toEqual(['m2']);+ });++ it("replay:'all' delivers the retained backlog oldest→newest", () => {+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'm1' } });+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'm2' } });+ const seen = [];+ agentBus.on('memory:added', (p) => seen.push(p.memory.id), { replay: 'all' });+ expect(seen).toEqual(['m1', 'm2']);+ });++ it('backlog() exposes history without subscribing', () => {+ agentBus.emit('mood:changed', { agentId: 'a', mood: 'a' });+ agentBus.emit('mood:changed', { agentId: 'a', mood: 'b' });+ expect(agentBus.backlog('mood:changed').map((p) => p.mood)).toEqual(['a', 'b']);+ });+ });++ describe('backpressure (throttle coalescing)', () => {+ it('delivers the leading event immediately and a single trailing event with the latest payload', async () => {+ const seen = [];+ agentBus.on('memory:added', (p) => seen.push(p.memory.id), { throttleMs: 20 });+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'A' } });+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'B' } });+ agentBus.emit('memory:added', { agentId: 'a', memory: { id: 'C' } });+ // Leading 'A' fired synchronously; B and C are coalesced.+ expect(seen).toEqual(['A']);+ await wait(40);+ // Trailing delivers only the most recent (C); B was dropped.+ expect(seen).toEqual(['A', 'C']);+ });+ });++ it('auto-unsubscribes when an AbortSignal fires', () => {+ const seen = [];+ const ctrl = new AbortController();+ agentBus.on('agent:changed', (p) => seen.push(p.agentId), { signal: ctrl.signal });+ agentBus.emit('agent:changed', { agentId: 'a1', agent: null });+ ctrl.abort();+ agentBus.emit('agent:changed', { agentId: 'a2', agent: null });+ expect(seen).toEqual(['a1']);+ });+});diff --git a/src/agents/memory-client.js b/src/agents/memory-client.jsindex b0bb5188e..5658b77cd 100644--- a/src/agents/memory-client.js+++ b/src/agents/memory-client.js@@ -73,7 +73,9 @@ async function upsert(agentId, entry) {*/export async function addMemory(agentId, entry) {if (!agentId) throw new Error('addMemory requires an agentId');- const { id, ...rest } = entry || {};+ // Strip any id so the server treats this as a create, not an upsert.+ const rest = { ...(entry || {}) };+ delete rest.id;const memory = await upsert(agentId, rest);if (memory) {agentBus.emit('memory:added', { agentId, memory, ts: isoFrom(memory.createdAt) });diff --git a/src/agents/memory-client.test.js b/src/agents/memory-client.test.jsnew file mode 100644index 000000000..a0fd55a30--- /dev/null+++ b/src/agents/memory-client.test.js@@ -0,0 +1,37 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { agentBus } from './agent-bus.js';+import { emitRecallFromChat } from './memory-client.js';++describe('emitRecallFromChat (chat done → memory:recalled)', () => {+ beforeEach(() => agentBus.reset());++ it('emits one memory:recalled carrying exactly the server-reported memories', () => {+ const events = [];+ agentBus.on('memory:recalled', (p) => events.push(p));+ const done = {+ type: 'done',+ recalled: [+ { id: 'm1', type: 'project', tier: 'working', salience: 0.9, snippet: 'likes vivid demos', match: 'context' },+ { id: 'm2', type: 'user', tier: 'recall', salience: 0.6, snippet: 'based in Lisbon', match: 'semantic' },+ ],+ recalledSemantic: true,+ recalledTs: '2026-06-23T10:00:00.000Z',+ };+ const returned = emitRecallFromChat('agent-1', done, 'where am I based?');+ expect(events).toHaveLength(1);+ expect(events[0].agentId).toBe('agent-1');+ expect(events[0].memories.map((m) => m.id)).toEqual(['m1', 'm2']);+ expect(events[0].semantic).toBe(true);+ expect(events[0].query).toBe('where am I based?');+ expect(events[0].ts).toBe('2026-06-23T10:00:00.000Z');+ expect(returned).toHaveLength(2);+ });++ it('emits nothing when the server recalled no memories', () => {+ const events = [];+ agentBus.on('memory:recalled', (p) => events.push(p));+ expect(emitRecallFromChat('agent-1', { type: 'done', recalled: [] })).toEqual([]);+ expect(emitRecallFromChat('agent-1', { type: 'done' })).toEqual([]);+ expect(events).toHaveLength(0);+ });+});diff --git a/src/autopilot-activity.js b/src/autopilot-activity.jsnew file mode 100644index 000000000..c7f8f979a--- /dev/null+++ b/src/autopilot-activity.js@@ -0,0 +1,147 @@+// /autopilot-activity — the dedicated receipts surface for Memory-grounded+// Autopilot (Living Agents · Task 08).+//+// Lists every autonomous action across the owner's agents (or a single agent via+// ?agent=<id>), newest first, each with its full explanation, the source memories+// that motivated it (linking into the Knowledge tab), a signed-receipt badge, and+// an on-chain tx link / one-tap undo where applicable. Real reads of the+// append-only agent_actions log via /api/autopilot/activity.++import { apiFetch } from './api.js';+import { receiptRow, showReceiptChip } from './autopilot-mind.js';++const params = new URLSearchParams(location.search);+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+let agentFilter = (params.get('agent') && UUID_RE.test(params.get('agent'))) ? params.get('agent') : '';+let cursor = null;+let loading = false;++const $ = (id) => document.getElementById(id);+const esc = (s) => String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c]);++function url() {+ const u = new URL('/api/autopilot/activity', location.origin);+ u.searchParams.set('limit', '25');+ if (agentFilter) u.searchParams.set('agentId', agentFilter);+ if (cursor) u.searchParams.set('cursor', cursor);+ return u.pathname + u.search;+}++function renderState(html) {+ $('ledger').innerHTML = html;+ $('loadmore').hidden = true;+}++function populateAgentFilter(agents) {+ const sel = $('agent-filter');+ if (sel.dataset.filled || !agents?.length) return;+ sel.dataset.filled = '1';+ for (const a of agents) {+ const opt = document.createElement('option');+ opt.value = a.id;+ opt.textContent = a.name || `Agent ${a.id.slice(0, 6)}`;+ sel.appendChild(opt);+ }+ sel.value = agentFilter;+}++function renderTrust(trust) {+ const slot = $('trust-slot');+ if (!trust) { slot.innerHTML = ''; return; }+ slot.innerHTML = `<span class="apm-badge ${esc(trust.level)}" title="${esc(trust.blurb)}">${esc(trust.label)} · ${esc(String(trust.stats?.executed ?? 0))} actions</span>`;+}++async function load({ append = false } = {}) {+ if (loading) return;+ loading = true;+ const ledger = $('ledger');+ if (!append) ledger.innerHTML = '<div class="skel"></div><div class="skel"></div><div class="skel"></div>';+ $('loadmore').disabled = true;+ try {+ const r = await apiFetch(url(), { credentials: 'include', allowAnonymous: true });+ if (r.status === 401) {+ renderState(`<div class="state"><div class="ico">🔒</div><h2>Sign in to see your agent's activity</h2><p>Every autonomous action lives here once you're signed in.</p><a class="btn" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a></div>`);+ return;+ }+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);++ populateAgentFilter(j.agents);+ renderTrust(j.trust);++ const receipts = j.receipts || [];+ if (!append && !receipts.length) {+ renderState(`<div class="state"><div class="ico">🧭</div><h2>No actions yet</h2><p>When your agent acts on your behalf — sets an alert, writes a briefing, sends $THREE — every move shows up here with the memory that motivated it.</p><a class="btn" href="/dashboard">Set up autopilot →</a></div>`);+ return;+ }++ const html = receipts.map((rc) => receiptRow(rc, rc.agentId, { undo: true, showAgent: !agentFilter })).join('');+ if (append) ledger.insertAdjacentHTML('beforeend', html);+ else ledger.innerHTML = html;++ cursor = j.next_cursor;+ $('loadmore').hidden = !cursor;+ wireUndo(ledger);+ } catch (err) {+ if (!append) {+ renderState(`<div class="state"><div class="ico">⚠️</div><h2>Couldn't load activity</h2><p>${esc(err.message)}</p><button class="btn" id="retry">Retry</button></div>`);+ $('retry')?.addEventListener('click', () => load());+ }+ } finally {+ loading = false;+ $('loadmore').disabled = false;+ }+}++function wireUndo(scope) {+ scope.querySelectorAll('[data-undo]').forEach((btn) => {+ if (btn.dataset.wired) return;+ btn.dataset.wired = '1';+ btn.addEventListener('click', async () => {+ const card = btn.closest('.apm-receipt');+ const agentId = card?.dataset.agent || agentFilter || resolveAgentForUndo(btn);+ btn.disabled = true;+ btn.textContent = 'Undoing…';+ try {+ const r = await apiFetch('/api/autopilot/proposals', {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',+ body: JSON.stringify({ agentId, action: 'undo', proposalId: btn.dataset.undo }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ showReceiptChip('Undone — your agent will be more cautious.', { icon: '↩' });+ cursor = null;+ load();+ } catch (err) {+ btn.disabled = false;+ btn.textContent = 'Undo';+ showReceiptChip(err.message, { icon: '⚠' });+ }+ });+ });+}++// When aggregating across agents, the undo needs the receipt's own agent id —+// it's carried on the receipt row's source links; fall back to the filter.+function resolveAgentForUndo(btn) {+ const row = btn.closest('.apm-receipt');+ const link = row?.querySelector('a.apm-source[href*="/agent/"]');+ if (link) {+ const m = link.getAttribute('href').match(/\/agent\/([0-9a-f-]{36})/i);+ if (m) return m[1];+ }+ return agentFilter;+}++$('agent-filter').addEventListener('change', (e) => {+ agentFilter = e.target.value;+ cursor = null;+ const next = new URL(location.href);+ if (agentFilter) next.searchParams.set('agent', agentFilter); else next.searchParams.delete('agent');+ history.replaceState(null, '', next);+ load();+});++$('loadmore').addEventListener('click', () => load({ append: true }));++load();diff --git a/src/autopilot-mind.js b/src/autopilot-mind.jsnew file mode 100644index 000000000..307d9d4ac--- /dev/null+++ b/src/autopilot-mind.js@@ -0,0 +1,606 @@+// Memory-grounded Autopilot — the control surface (Living Agents · Task 08).+//+// Self-contained module mounted in two places:+// • the Autopilot tab of /agent/{id}/edit (mountAutopilotMind)+// • the standalone /autopilot-activity receipts page (renderReceipt is reused)+//+// It is the legible face of explainable autonomy: the owner grants scoped+// capabilities, the agent proposes real actions grounded in memory (each showing+// its receipt), and every executed action links back to the memory that+// motivated it. Wallet actions move real $THREE and are always confirmation-gated.+//+// Kept in its own module so it can evolve without touching the heavily-shared+// agent-edit.js. All API calls go through apiFetch (CSRF-safe).++import { apiFetch } from './api.js';+import { agentBus } from './agents/agent-bus.js';++const API = '/api/autopilot';++const KIND_META = {+ create_alert: { label: 'Alert', icon: '🔔', reversible: true, blurb: 'Watches a token and notifies you.' },+ briefing: { label: 'Briefing', icon: '📋', reversible: true, blurb: 'Authors a memory-grounded digest.' },+ wallet_transfer: { label: 'Transfer', icon: '💸', reversible: false, blurb: 'Sends $THREE from the agent wallet.' },+};++const esc = (s) =>+ String(s ?? '').replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c]);++function timeAgo(iso) {+ const ms = Date.now() - new Date(iso).getTime();+ if (!Number.isFinite(ms)) return '';+ const s = Math.floor(ms / 1000);+ if (s < 60) return `${s}s ago`;+ const m = Math.floor(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h}h ago`;+ return `${Math.floor(h / 24)}d ago`;+}++let _stylesInjected = false;+function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const css = `+ .apm { --apm-line: var(--hairline, #1c1c1c); --apm-s1: var(--surface-1, #111); --apm-s2: var(--surface-2, #181818);+ --apm-txt: var(--text, #f6f6f6); --apm-t2: var(--text-2, #a8a8a8); --apm-t3: var(--text-3, #6a6a6a);+ --apm-accent: var(--mint, #78c88c); --apm-red: var(--red, #ef4444); --apm-amber: var(--amber, #f59e0b);+ display: flex; flex-direction: column; gap: 1.25rem; }+ .apm-card { border: 1px solid var(--apm-line); border-radius: 12px; background: var(--apm-s1); padding: 1.1rem 1.15rem; }+ .apm-h { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; margin-bottom: 0.5rem; }+ .apm-h h3 { margin: 0; font-size: 0.95rem; letter-spacing: -0.01em; }+ .apm-sub { color: var(--apm-t2); font-size: 0.82rem; margin: 0.15rem 0 0; }+ .apm-trust { display: flex; align-items: center; gap: 0.85rem; }+ .apm-trust-meter { flex: 1; height: 7px; border-radius: 99px; background: var(--apm-s2); overflow: hidden; }+ .apm-trust-fill { height: 100%; background: linear-gradient(90deg, var(--apm-accent), #4f9dde); transition: width .5s ease; }+ .apm-badge { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.2rem 0.55rem; border-radius: 99px;+ font-size: 0.72rem; font-weight: 600; border: 1px solid var(--apm-line); color: var(--apm-t2); white-space: nowrap; }+ .apm-badge.sandbox { color: var(--apm-amber); border-color: color-mix(in srgb, var(--apm-amber) 40%, transparent); }+ .apm-badge.trusted { color: var(--apm-accent); border-color: color-mix(in srgb, var(--apm-accent) 40%, transparent); }+ .apm-badge.autonomous { color: #4f9dde; border-color: color-mix(in srgb, #4f9dde 40%, transparent); }+ .apm-scopes { display: flex; flex-direction: column; gap: 0.55rem; }+ .apm-scope { display: flex; align-items: flex-start; gap: 0.7rem; padding: 0.55rem 0; border-top: 1px solid var(--apm-line); }+ .apm-scope:first-of-type { border-top: none; }+ .apm-scope-body { flex: 1; min-width: 0; }+ .apm-scope-name { font-size: 0.86rem; font-weight: 600; }+ .apm-scope-desc { color: var(--apm-t3); font-size: 0.78rem; margin-top: 0.1rem; }+ .apm-scope-extra { margin-top: 0.5rem; display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }+ .apm-switch { position: relative; width: 38px; height: 22px; flex-shrink: 0; cursor: pointer; }+ .apm-switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; }+ .apm-switch-track { position: absolute; inset: 0; border-radius: 99px; background: var(--apm-s2); border: 1px solid var(--apm-line); transition: background .15s; }+ .apm-switch-track::after { content: ''; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--apm-t2); transition: transform .15s, background .15s; }+ .apm-switch input:checked + .apm-switch-track { background: color-mix(in srgb, var(--apm-accent) 35%, transparent); }+ .apm-switch input:checked + .apm-switch-track::after { transform: translateX(16px); background: var(--apm-accent); }+ .apm-switch input:focus-visible + .apm-switch-track { outline: 2px solid var(--apm-accent); outline-offset: 2px; }+ .apm-switch input:disabled + .apm-switch-track { opacity: 0.45; cursor: not-allowed; }+ .apm-num { width: 110px; padding: 0.35rem 0.5rem; border-radius: 8px; border: 1px solid var(--apm-line); background: var(--apm-s2); color: var(--apm-txt); font: inherit; font-size: 0.82rem; }+ .apm-btn { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.4rem 0.7rem; border-radius: 8px; border: 1px solid var(--apm-line);+ background: var(--apm-s2); color: var(--apm-txt); font: inherit; font-size: 0.8rem; font-weight: 600; cursor: pointer; transition: border-color .12s, background .12s, transform .06s; }+ .apm-btn:hover { border-color: var(--apm-t3); }+ .apm-btn:active { transform: translateY(1px); }+ .apm-btn:focus-visible { outline: 2px solid var(--apm-accent); outline-offset: 2px; }+ .apm-btn.primary { background: var(--apm-accent); color: #07140c; border-color: var(--apm-accent); }+ .apm-btn.danger:hover { border-color: var(--apm-red); color: var(--apm-red); }+ .apm-btn[disabled] { opacity: 0.55; cursor: not-allowed; }+ .apm-props { display: flex; flex-direction: column; gap: 0.85rem; }+ .apm-prop { border: 1px solid var(--apm-line); border-radius: 11px; background: var(--apm-s1); padding: 0.9rem 1rem; transition: border-color .15s; }+ .apm-prop:hover { border-color: var(--apm-t3); }+ .apm-prop-top { display: flex; align-items: flex-start; gap: 0.6rem; }+ .apm-prop-kind { font-size: 1.05rem; line-height: 1.4; }+ .apm-prop-title { font-weight: 600; font-size: 0.9rem; flex: 1; min-width: 0; }+ .apm-prop-conf { font-size: 0.72rem; color: var(--apm-t3); white-space: nowrap; }+ .apm-prop-why { color: var(--apm-t2); font-size: 0.82rem; margin: 0.5rem 0; line-height: 1.5; }+ .apm-prop-why b { color: var(--apm-txt); font-weight: 600; }+ .apm-sources { display: flex; flex-wrap: wrap; gap: 0.35rem; margin: 0.5rem 0; }+ .apm-source { display: inline-flex; align-items: center; gap: 0.3rem; max-width: 100%; padding: 0.22rem 0.5rem; border-radius: 99px;+ background: var(--apm-s2); border: 1px solid var(--apm-line); font-size: 0.72rem; color: var(--apm-t2); text-decoration: none; }+ .apm-source:hover { border-color: var(--apm-accent); color: var(--apm-txt); }+ .apm-source .apm-source-txt { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 260px; }+ .apm-source.forgotten { opacity: 0.5; }+ .apm-prop-actions { display: flex; flex-wrap: wrap; gap: 0.45rem; margin-top: 0.7rem; }+ .apm-dryrun { margin-top: 0.65rem; border-top: 1px dashed var(--apm-line); padding-top: 0.6rem; font-size: 0.78rem; }+ .apm-check { display: flex; align-items: flex-start; gap: 0.45rem; padding: 0.18rem 0; color: var(--apm-t2); }+ .apm-check .ck { font-weight: 700; }+ .apm-check.ok .ck { color: var(--apm-accent); }+ .apm-check.no .ck { color: var(--apm-red); }+ .apm-willdo { color: var(--apm-txt); margin-bottom: 0.4rem; font-weight: 500; }+ .apm-empty { text-align: center; color: var(--apm-t3); padding: 1.5rem 0.5rem; }+ .apm-empty .em-ico { font-size: 1.6rem; opacity: 0.7; }+ .apm-empty p { margin: 0.5rem 0 0; font-size: 0.85rem; }+ .apm-status { font-size: 0.78rem; color: var(--apm-t3); min-height: 1.1em; }+ .apm-status.err { color: var(--apm-red); }+ .apm-status.ok { color: var(--apm-accent); }+ .apm-skel { height: 70px; border-radius: 11px; background: linear-gradient(90deg, var(--apm-s1) 0%, var(--apm-s2) 50%, var(--apm-s1) 100%);+ background-size: 200% 100%; animation: apm-shimmer 1.3s infinite; border: 1px solid var(--apm-line); }+ @keyframes apm-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .apm-skel { animation: none; } .apm-trust-fill { transition: none; } }+ .apm-receipt { display: flex; gap: 0.6rem; align-items: flex-start; padding: 0.6rem 0; border-top: 1px solid var(--apm-line); }+ .apm-receipt:first-child { border-top: none; }+ .apm-receipt-ico { font-size: 1rem; }+ .apm-receipt-body { flex: 1; min-width: 0; }+ .apm-receipt-line { font-size: 0.83rem; }+ .apm-receipt-meta { font-size: 0.72rem; color: var(--apm-t3); margin-top: 0.2rem; display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }+ .apm-signed { color: var(--apm-accent); }+ .apm-modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; z-index: 9000; padding: 1rem; }+ .apm-modal { background: var(--apm-s1); border: 1px solid var(--apm-line); border-radius: 14px; max-width: 420px; width: 100%; padding: 1.4rem; }+ .apm-modal h4 { margin: 0 0 0.5rem; font-size: 1rem; }+ .apm-modal p { color: var(--apm-t2); font-size: 0.85rem; line-height: 1.5; margin: 0 0 0.5rem; }+ .apm-modal-actions { display: flex; gap: 0.55rem; justify-content: flex-end; margin-top: 1rem; }+ .apm-chip-toast { position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%) translateY(20px); opacity: 0;+ background: var(--apm-s2); border: 1px solid var(--apm-accent); color: var(--apm-txt); padding: 0.6rem 0.95rem; border-radius: 99px;+ font-size: 0.82rem; z-index: 9100; pointer-events: none; transition: opacity .25s, transform .25s; display: flex; align-items: center; gap: 0.45rem; max-width: 90vw; }+ .apm-chip-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }+ @media (prefers-reduced-motion: reduce) { .apm-chip-toast { transition: opacity .1s; } }+ `;+ const style = document.createElement('style');+ style.id = 'apm-styles';+ style.textContent = css;+ document.head.appendChild(style);+}++// ── Receipt chip (the "I did X because Y" transparency cue) ───────────────────++let _chipTimer;+export function showReceiptChip(text, { icon = '✓' } = {}) {+ if (typeof document === 'undefined') return;+ injectStyles();+ let el = document.getElementById('apm-receipt-chip');+ if (!el) {+ el = document.createElement('div');+ el.id = 'apm-receipt-chip';+ el.className = 'apm-chip-toast';+ el.setAttribute('role', 'status');+ el.setAttribute('aria-live', 'polite');+ document.body.appendChild(el);+ }+ el.innerHTML = `<span>${esc(icon)}</span><span>${esc(text)}</span>`;+ requestAnimationFrame(() => el.classList.add('show'));+ clearTimeout(_chipTimer);+ _chipTimer = setTimeout(() => el.classList.remove('show'), 4200);+}++// Surface a receipt chip whenever ANY surface emits action:taken on the bus —+// this is the cross-feature transparency cue the Companion (Task 02) also taps.+let _busWired = false;+function wireBusChip() {+ if (_busWired) return;+ _busWired = true;+ agentBus.on('action:taken', (p) => {+ if (p?.summary) showReceiptChip(p.summary, { icon: KIND_META[p.kind]?.icon || '✓' });+ });+}++// ── Source-memory chip (provenance, links into the Knowledge tab) ─────────────++function sourceChip(agentId, src) {+ if (src.forgotten) {+ return `<span class="apm-source forgotten" title="This memory was forgotten">🜸 <span class="apm-source-txt">memory ${esc(String(src.id).slice(0, 8))} (forgotten)</span></span>`;+ }+ const href = `/agent/${encodeURIComponent(agentId)}/edit?tab=knowledge#mem-${encodeURIComponent(src.id)}`;+ return `<a class="apm-source" href="${href}" title="${esc(src.content || '')}">🧠 <span class="apm-source-txt">${esc((src.content || 'memory').slice(0, 80))}</span></a>`;+}++// ── Main mount ────────────────────────────────────────────────────────────────++/**+ * Mount the full autopilot control surface into `container` for one agent.+ * Returns a teardown function.+ */+export function mountAutopilotMind(container, { agentId }) {+ if (!container || !agentId) return () => {};+ injectStyles();+ wireBusChip();++ const state = { config: null, trust: null, proposals: [], busy: false };++ container.innerHTML = `+ <div class="apm">+ <div class="apm-card" id="apm-trust-card">+ <div class="apm-h"><h3>Trust</h3><span class="apm-badge" id="apm-trust-badge">—</span></div>+ <p class="apm-sub" id="apm-trust-blurb">How much your agent has earned the right to act on its own.</p>+ <div class="apm-trust" style="margin-top:.7rem">+ <div class="apm-trust-meter"><div class="apm-trust-fill" id="apm-trust-fill" style="width:0%"></div></div>+ <span class="apm-prop-conf" id="apm-trust-stats"></span>+ </div>+ </div>++ <div class="apm-card">+ <div class="apm-h">+ <div><h3>What your agent may do</h3><p class="apm-sub">Grant only what you trust. Everything is enforced server-side; nothing fires without permission.</p></div>+ <label class="apm-switch" title="Master autopilot switch">+ <input type="checkbox" id="apm-enabled"><span class="apm-switch-track"></span>+ </label>+ </div>+ <div class="apm-scopes" id="apm-scopes"></div>+ <div class="apm-status" id="apm-config-status" aria-live="polite"></div>+ </div>++ <div class="apm-card">+ <div class="apm-h">+ <div><h3>Proposals</h3><p class="apm-sub">Grounded in your agent's memory and reflections. Each shows its receipt.</p></div>+ <button class="apm-btn primary" id="apm-generate">✨ Generate</button>+ </div>+ <div class="apm-status" id="apm-gen-status" aria-live="polite"></div>+ <div class="apm-props" id="apm-props"></div>+ </div>++ <div class="apm-card">+ <div class="apm-h"><h3>Recent activity</h3><a class="apm-btn" id="apm-activity-link" href="/autopilot-activity?agent=${encodeURIComponent(agentId)}">Full log →</a></div>+ <div id="apm-receipts"><div class="apm-skel"></div></div>+ </div>+ </div>`;++ const $ = (id) => container.querySelector('#' + id);++ // ── Scope controls ──────────────────────────────────────────────────────+ function renderScopes() {+ const c = state.config;+ $('apm-enabled').checked = c.enabled;+ const scopeDefs = [+ { key: 'create_alert', name: '🔔 Create alerts', desc: 'Set up real price / graduation / whale alerts on $THREE and tokens it knows about.', auto: true },+ { key: 'briefing', name: '📋 Author briefings', desc: 'Write memory-grounded briefings and deliver them to your inbox.', auto: true },+ { key: 'wallet_transfer', name: '💸 Spend $THREE', desc: 'Send $THREE from the agent\'s custodial wallet. Always asks before each transfer.', auto: false },+ ];+ $('apm-scopes').innerHTML = scopeDefs.map((s) => {+ const on = c.scopes[s.key];+ const autoOn = c.auto_execute?.[s.key];+ let extra = '';+ if (s.key === 'wallet_transfer') {+ extra = `<div class="apm-scope-extra"><label class="apm-prop-conf" for="apm-daily">Daily limit</label>+ <input class="apm-num" type="number" min="0" step="1" id="apm-daily" value="${esc(c.daily_spend_three)}" ${on ? '' : 'disabled'}>+ <span class="apm-prop-conf">$THREE / day</span></div>`;+ } else if (s.auto) {+ extra = `<div class="apm-scope-extra">+ <label class="apm-switch" title="Auto-run within scope (reversible only)"><input type="checkbox" data-auto="${s.key}" ${autoOn ? 'checked' : ''} ${on ? '' : 'disabled'}><span class="apm-switch-track"></span></label>+ <span class="apm-prop-conf">Auto-run without asking (you can undo)</span></div>`;+ }+ return `<div class="apm-scope">+ <div class="apm-scope-body">+ <div class="apm-scope-name">${s.name}</div>+ <div class="apm-scope-desc">${esc(s.desc)}</div>+ ${extra}+ </div>+ <label class="apm-switch"><input type="checkbox" data-scope="${s.key}" ${on ? 'checked' : ''}><span class="apm-switch-track"></span></label>+ </div>`;+ }).join('');++ $('apm-scopes').querySelectorAll('[data-scope]').forEach((el) =>+ el.addEventListener('change', () => saveConfig({ scopes: { [el.dataset.scope]: el.checked } })));+ $('apm-scopes').querySelectorAll('[data-auto]').forEach((el) =>+ el.addEventListener('change', () => saveConfig({ auto_execute: { [el.dataset.auto]: el.checked } })));+ const daily = $('apm-daily');+ if (daily) {+ let t;+ daily.addEventListener('input', () => {+ clearTimeout(t);+ t = setTimeout(() => saveConfig({ daily_spend_three: Number(daily.value) || 0 }), 500);+ });+ }+ }++ $('apm-enabled').addEventListener('change', (e) => saveConfig({ enabled: e.target.checked }));++ async function saveConfig(patch) {+ const status = $('apm-config-status');+ status.textContent = 'Saving…';+ status.className = 'apm-status';+ try {+ const r = await apiFetch(`${API}/config`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',+ body: JSON.stringify({ agentId, ...patch }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ state.config = j.config;+ renderScopes();+ status.textContent = 'Saved.';+ status.className = 'apm-status ok';+ setTimeout(() => { if (status.textContent === 'Saved.') status.textContent = ''; }, 1800);+ } catch (err) {+ status.textContent = `Couldn't save: ${err.message}`;+ status.className = 'apm-status err';+ }+ }++ // ── Trust ────────────────────────────────────────────────────────────────+ function renderTrust() {+ const t = state.trust;+ if (!t) return;+ const badge = $('apm-trust-badge');+ badge.textContent = t.label;+ badge.className = `apm-badge ${t.level}`;+ $('apm-trust-blurb').textContent = t.blurb;+ const pct = t.next ? Math.min(100, Math.round((t.score / Math.max(1, t.next.at)) * 100)) : 100;+ $('apm-trust-fill').style.width = `${pct}%`;+ const s = t.stats || {};+ $('apm-trust-stats').textContent = t.next+ ? `${s.executed || 0} done · ${t.next.remaining} to ${t.next.label}`+ : `${s.executed || 0} actions · ${s.reliability || 0}% kept`;+ }++ // ── Proposals ──────────────────────────────────────────────────────────────+ function renderProposals() {+ const wrap = $('apm-props');+ const pending = state.proposals.filter((p) => p.status === 'pending');+ if (!pending.length) {+ wrap.innerHTML = `<div class="apm-empty"><div class="em-ico">🧭</div><p>No proposals yet. Hit <b>Generate</b> — your agent reads its high-salience memories and recent reflections, then suggests real actions you can approve.</p></div>`;+ return;+ }+ wrap.innerHTML = pending.map((p) => proposalCard(p)).join('');+ pending.forEach((p) => wireProposal(p.id));+ }++ function proposalCard(p) {+ const km = KIND_META[p.kind] || { icon: '•', label: p.kind };+ const sources = (p.sources || []).map((s) => sourceChip(agentId, s)).join('');+ const conf = p.confidence != null ? `${Math.round(p.confidence * 100)}% sure` : '';+ return `+ <div class="apm-prop" data-id="${esc(p.id)}">+ <div class="apm-prop-top">+ <span class="apm-prop-kind" title="${esc(km.label)}">${km.icon}</span>+ <span class="apm-prop-title">${esc(p.title)}</span>+ <span class="apm-prop-conf">${esc(conf)}</span>+ </div>+ <p class="apm-prop-why"><b>Why:</b> ${esc(p.rationale)}${p.sourceReflectionId ? ' <span class="apm-prop-conf">(from a reflection)</span>' : ''}</p>+ ${sources ? `<div class="apm-sources">${sources}</div>` : ''}+ <div class="apm-dryrun" data-dryrun hidden></div>+ <div class="apm-prop-actions">+ <button class="apm-btn primary" data-act="execute">${km.reversible ? 'Approve' : 'Approve & send'}</button>+ <button class="apm-btn" data-act="dryrun">Preview</button>+ <button class="apm-btn danger" data-act="dismiss">Dismiss</button>+ </div>+ <div class="apm-status" data-prop-status aria-live="polite"></div>+ </div>`;+ }++ function wireProposal(id) {+ const card = container.querySelector(`.apm-prop[data-id="${CSS.escape(id)}"]`);+ if (!card) return;+ const p = state.proposals.find((x) => x.id === id);+ const status = card.querySelector('[data-prop-status]');+ const setStatus = (msg, cls = '') => { status.textContent = msg || ''; status.className = `apm-status ${cls}`; };++ card.querySelector('[data-act="dryrun"]').addEventListener('click', async (e) => {+ const box = card.querySelector('[data-dryrun]');+ if (!box.hidden) { box.hidden = true; e.target.textContent = 'Preview'; return; }+ e.target.disabled = true;+ box.hidden = false;+ box.innerHTML = '<div class="apm-skel" style="height:48px"></div>';+ try {+ const preview = await act('dryrun', { proposalId: id });+ box.innerHTML = renderDryRun(preview.preview);+ e.target.textContent = 'Hide preview';+ } catch (err) {+ box.innerHTML = `<div class="apm-check no"><span class="ck">✕</span>${esc(err.message)}</div>`;+ } finally { e.target.disabled = false; }+ });++ card.querySelector('[data-act="dismiss"]').addEventListener('click', async () => {+ setStatus('Dismissing…');+ try {+ const j = await act('dismiss', { proposalId: id });+ applyResult(j);+ setStatus('');+ } catch (err) { setStatus(err.message, 'err'); }+ });++ card.querySelector('[data-act="execute"]').addEventListener('click', async () => {+ if (p.kind === 'wallet_transfer') {+ const ok = await confirmTransfer(p);+ if (!ok) return;+ return runExecute(id, setStatus, true);+ }+ return runExecute(id, setStatus, false);+ });+ }++ async function runExecute(id, setStatus, confirm) {+ setStatus('Working…');+ try {+ const j = await act('execute', { proposalId: id, confirm });+ applyResult(j);+ const p = j.proposal;+ // Emit the cross-surface event (also fires the receipt chip via the bus).+ agentBus.emit('action:taken', {+ agentId,+ actionId: j.action?.id != null ? String(j.action.id) : undefined,+ kind: p.kind,+ summary: j.receipt || 'Action taken.',+ motivatedBy: p.sourceMemoryIds || [],+ ts: j.action?.ts || new Date().toISOString(),+ });+ loadReceipts();+ } catch (err) {+ if (err.code === 'confirmation_required') {+ setStatus('Needs confirmation.', 'err');+ } else {+ setStatus(err.message, 'err');+ }+ }+ }++ function applyResult(j) {+ if (j.trust) { state.trust = j.trust; renderTrust(); }+ if (j.proposal) {+ const i = state.proposals.findIndex((x) => x.id === j.proposal.id);+ if (i >= 0) state.proposals[i] = { ...state.proposals[i], ...j.proposal };+ }+ renderProposals();+ }++ function renderDryRun(preview) {+ const checks = (preview.checks || []).map((c) =>+ `<div class="apm-check ${c.ok ? 'ok' : 'no'}"><span class="ck">${c.ok ? '✓' : '✕'}</span><span>${esc(c.label)} — <span class="apm-prop-conf">${esc(c.detail)}</span></span></div>`).join('');+ return `<div class="apm-willdo">${esc(preview.willDo)}</div>${checks}`;+ }++ // ── Confirm modal (irreversible $THREE transfer) ──────────────────────────+ function confirmTransfer(p) {+ return new Promise((resolve) => {+ const back = document.createElement('div');+ back.className = 'apm-modal-backdrop';+ back.innerHTML = `+ <div class="apm-modal" role="dialog" aria-modal="true" aria-labelledby="apm-confirm-h">+ <h4 id="apm-confirm-h">Confirm $THREE transfer</h4>+ <p>Your agent will send <b>${esc(p.params.amount_three)} $THREE</b> to <b>${esc(String(p.params.recipient).slice(0, 10))}…${esc(String(p.params.recipient).slice(-6))}</b>.</p>+ <p>This is real and <b>cannot be undone</b>. ${p.params.reason ? `Reason: ${esc(p.params.reason)}` : ''}</p>+ <div class="apm-modal-actions">+ <button class="apm-btn" data-c="cancel">Cancel</button>+ <button class="apm-btn primary" data-c="ok">Send ${esc(p.params.amount_three)} $THREE</button>+ </div>+ </div>`;+ document.body.appendChild(back);+ const close = (val) => { back.remove(); document.removeEventListener('keydown', onKey); resolve(val); };+ const onKey = (e) => { if (e.key === 'Escape') close(false); };+ document.addEventListener('keydown', onKey);+ back.addEventListener('click', (e) => { if (e.target === back) close(false); });+ back.querySelector('[data-c="cancel"]').addEventListener('click', () => close(false));+ back.querySelector('[data-c="ok"]').addEventListener('click', () => close(true));+ back.querySelector('[data-c="ok"]').focus();+ });+ }++ // ── Generate ───────────────────────────────────────────────────────────────+ $('apm-generate').addEventListener('click', async () => {+ const btn = $('apm-generate');+ const status = $('apm-gen-status');+ btn.disabled = true;+ status.textContent = 'Reading memories & reflecting…';+ status.className = 'apm-status';+ try {+ // Kick a (debounced) reflection first so dream-sourced proposals are fresh,+ // then generate. Reflection failure is non-fatal — memory synthesis still runs.+ await apiFetch(`/api/agent/reflect`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',+ body: JSON.stringify({ agentId }),+ }).catch(() => {});+ const j = await act('generate', {});+ if (j.trust) { state.trust = j.trust; renderTrust(); }+ if (j.created?.length) {+ // Prepend new proposals.+ state.proposals = [...j.created, ...state.proposals.filter((p) => !j.created.some((c) => c.id === p.id))];+ renderProposals();+ status.textContent = `${j.created.length} new proposal${j.created.length === 1 ? '' : 's'} (${j.source}).`;+ status.className = 'apm-status ok';+ } else {+ status.textContent = `Nothing new to propose right now — your agent needs more high-salience memories to act on.`;+ status.className = 'apm-status';+ }+ } catch (err) {+ status.textContent = `Couldn't generate: ${err.message}`;+ status.className = 'apm-status err';+ } finally { btn.disabled = false; }+ });++ // ── Recent receipts ──────────────────────────────────────────────────────+ async function loadReceipts() {+ const box = $('apm-receipts');+ try {+ const r = await apiFetch(`${API}/activity?agentId=${agentId}&limit=5`, { credentials: 'include' });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ const receipts = j.receipts || [];+ if (!receipts.length) {+ box.innerHTML = `<div class="apm-empty"><p>No actions taken yet. Approve a proposal and its signed receipt shows up here.</p></div>`;+ return;+ }+ box.innerHTML = receipts.map((rc) => receiptRow(rc, agentId, { undo: true })).join('');+ wireReceiptUndo(box);+ } catch (err) {+ box.innerHTML = `<div class="apm-status err">Couldn't load activity: ${esc(err.message)}</div>`;+ }+ }++ function wireReceiptUndo(scope) {+ scope.querySelectorAll('[data-undo]').forEach((btn) =>+ btn.addEventListener('click', async () => {+ const pid = btn.dataset.undo;+ btn.disabled = true;+ btn.textContent = 'Undoing…';+ try {+ const j = await act('undo', { proposalId: pid });+ if (j.trust) { state.trust = j.trust; renderTrust(); }+ showReceiptChip('Undone — your agent will be more cautious.', { icon: '↩' });+ loadReceipts();+ // Reflect the boundary feedback into the memory bus.+ agentBus.emit('memory:added', { agentId, ts: new Date().toISOString(), source: 'autopilot_undo' });+ } catch (err) {+ btn.disabled = false;+ btn.textContent = 'Undo';+ showReceiptChip(err.message, { icon: '⚠' });+ }+ }));+ }++ // ── API helper ───────────────────────────────────────────────────────────+ async function act(action, body) {+ const r = await apiFetch(`${API}/proposals`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',+ body: JSON.stringify({ agentId, action, ...body }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ const e = new Error(j.error_description || j.error || `HTTP ${r.status}`);+ e.code = j.error;+ throw e;+ }+ return j;+ }++ // ── Initial load ───────────────────────────────────────────────────────────+ (async function init() {+ try {+ const r = await apiFetch(`${API}/proposals?agentId=${agentId}`, { credentials: 'include' });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ state.config = j.config;+ state.trust = j.trust;+ state.proposals = j.proposals || [];+ renderScopes();+ renderTrust();+ renderProposals();+ } catch (err) {+ $('apm-props').innerHTML = `<div class="apm-status err">Couldn't load autopilot: ${esc(err.message)} <button class="apm-btn" id="apm-retry">Retry</button></div>`;+ container.querySelector('#apm-retry')?.addEventListener('click', () => mountAutopilotMind(container, { agentId }));+ }+ loadReceipts();+ })();++ return () => { /* nothing persistent to tear down beyond the DOM */ };+}++// ── Shared receipt row (used by the tab + the standalone Activity page) ───────++export function receiptRow(rc, agentId, { undo = false, showAgent = false } = {}) {+ const km = KIND_META[rc.kind] || { icon: '•', label: rc.kind };+ const result = rc.result || {};+ let line = '';+ if (rc.kind === 'alert_created') line = `Created a <b>${esc(String(result.rule_kind || 'alert').replace('_', ' '))}</b> alert${result.target_mint ? ` on ${esc(result.target_mint === 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' ? '$THREE' : String(result.target_mint).slice(0, 6) + '…')}` : ''}.`;+ else if (rc.kind === 'briefing_authored') line = `Authored a briefing${result.body_preview ? `: "${esc(String(result.body_preview).slice(0, 90))}…"` : ''}.`;+ else if (rc.kind === 'wallet_transfer') line = `Sent <b>${esc(result.amount_three)} $THREE</b>${result.recipient ? ` to ${esc(String(result.recipient).slice(0, 8))}…` : ''}.`;+ else line = esc(rc.type);++ const sources = (rc.sources || []).slice(0, 3).map((s) => sourceChip(rc.agentId || agentId, s)).join('');+ const sig = rc.signed+ ? `<span class="apm-signed" title="ERC-191 signed by ${esc(rc.signerAddress || '')}">🔏 signed</span>`+ : '';+ const sol = result.signature+ ? `<a class="apm-source" href="https://solscan.io/tx/${esc(result.signature)}" target="_blank" rel="noopener">tx ↗</a>`+ : '';+ const undoBtn = undo && (rc.kind === 'alert_created' || rc.kind === 'briefing_authored') && rc.proposalId+ ? `<button class="apm-btn" data-undo="${esc(rc.proposalId)}" style="padding:.2rem .5rem;font-size:.72rem">Undo</button>`+ : '';+ const who = showAgent && rc.agent ? `<span>${esc(rc.agent.name || 'Agent')}</span>` : '';++ return `+ <div class="apm-receipt" data-agent="${esc(rc.agentId || agentId || '')}">+ <span class="apm-receipt-ico">${km.icon}</span>+ <div class="apm-receipt-body">+ <div class="apm-receipt-line">${line}</div>+ ${rc.rationale ? `<div class="apm-prop-why" style="margin:.35rem 0 0"><b>Why:</b> ${esc(rc.rationale)}</div>` : ''}+ ${sources ? `<div class="apm-sources" style="margin:.4rem 0 0">${sources}</div>` : ''}+ <div class="apm-receipt-meta">${who}<span>${esc(timeAgo(rc.at))}</span>${sig}${sol}${undoBtn}</div>+ </div>+ </div>`;+}diff --git a/src/brain-ownership.js b/src/brain-ownership.jsnew file mode 100644index 000000000..8edc7a54c--- /dev/null+++ b/src/brain-ownership.js@@ -0,0 +1,494 @@+// Brain Ownership — the surface where a user truly owns their agent's mind.+//+// Renders a human-readable "brain passport": authorship verification at a+// glance, storage mode, IPFS pin status + CIDs, on-chain anchor with a real+// explorer link, and export/import of a portable, signed `.brain` bundle.+//+// Everything here is wired to the real endpoints under /api/agents/:id/brain+// (see api/agents/_id/brain.js). The encrypt-to-owner flow derives an AES-GCM+// key from the owner's wallet signature (src/memory/crypto.js → the same+// primitive the encrypted-ipfs memory mode uses) entirely client-side, pins the+// ciphertext via /memory/pin, and records the CID — the platform never sees the+// plaintext or the key.+//+// Mounted lazily by the agent editor's "Ownership" tab; emits on the shared+// agent bus so the rest of the platform can react (e.g. a HUD chip on anchor).++import { apiFetch } from './api.js';+import { agentBus } from './agents/agent-bus.js';++const API = '/api';++function escapeHtml(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function shortHash(h, n = 8) {+ if (!h) return '—';+ return h.length > n * 2 + 1 ? `${h.slice(0, n)}…${h.slice(-n)}` : h;+}++function shortAddr(a) {+ if (!a) return '—';+ return a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;+}++function fmtBytes(n) {+ if (!n) return '0 B';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(2)} MB`;+}++function fmtDate(v) {+ if (!v) return '—';+ const d = new Date(v);+ return Number.isNaN(d.getTime()) ? '—' : d.toLocaleString();+}++const STORAGE_LABELS = {+ local: 'Local only — stays in your browser + our DB, never pinned',+ ipfs: 'IPFS — pinned publicly, content-addressed, anyone can fetch',+ 'encrypted-ipfs': 'Encrypted IPFS — pinned but encrypted to your wallet; we can’t read it',+ none: 'None — ephemeral, nothing persisted off-session',+};++/**+ * Mount the Brain Ownership surface into a container.+ * @param {HTMLElement} host+ * @param {{ agentId: string, agent?: object }} opts+ */+export async function mountBrainOwnership(host, { agentId, agent } = {}) {+ if (!host || !agentId) return;+ host.innerHTML = skeleton();++ let passport;+ try {+ passport = await fetchPassport(agentId);+ } catch (err) {+ host.innerHTML = errorState(err.message, () => mountBrainOwnership(host, { agentId, agent }));+ wireRetry(host, () => mountBrainOwnership(host, { agentId, agent }));+ return;+ }++ render(host, agentId, passport, agent);+}++async function fetchPassport(agentId) {+ const r = await apiFetch(`${API}/agents/${agentId}/brain`, { credentials: 'include' });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ }+ return r.json();+}++// ── Rendering ──────────────────────────────────────────────────────────────++function render(host, agentId, p, agent) {+ const m = p.memories || {};+ const verifyPct = m.signed ? Math.round((m.verified / m.signed) * 100) : 0;+ const allVerified = m.signed > 0 && m.verified === m.signed;+ const integrity =+ m.total === 0+ ? { cls: 'empty', label: 'No memories yet' }+ : allVerified+ ? { cls: 'ok', label: 'Authorship verified' }+ : m.signed === 0+ ? { cls: 'warn', label: 'Unsigned (no agent wallet)' }+ : { cls: 'warn', label: `${m.verified}/${m.signed} verified` };++ const anchored = Boolean(p.anchor && p.anchor.status === 'anchored');+ const anchorDrift = anchored && !p.anchor_in_sync;++ host.innerHTML = `+ <div class="brain-own">+ <header class="brain-own__hero">+ <div class="brain-own__hero-main">+ <div class="bo-passport-badge bo-passport-badge--${integrity.cls}" role="img"+ aria-label="Brain integrity: ${escapeHtml(integrity.label)}">+ ${integrity.cls === 'ok' ? '✓' : integrity.cls === 'warn' ? '!' : '○'}+ </div>+ <div>+ <h3 class="bo-title">Brain passport</h3>+ <p class="bo-sub">${escapeHtml(integrity.label)} · ${m.total || 0} ${+ m.total === 1 ? 'memory' : 'memories'+ }</p>+ </div>+ </div>+ <div class="bo-fingerprint" title="Content-addressed hash of this agent's curated mind">+ <span class="bo-fingerprint__label">brain hash</span>+ <code>${escapeHtml(shortHash(p.current_brain_hash))}</code>+ <button class="bo-copy" data-copy="${escapeHtml(p.current_brain_hash || '')}"+ aria-label="Copy full brain hash" title="Copy full hash">⧉</button>+ </div>+ </header>++ <div class="bo-stats" role="list">+ ${stat('Signed', `${m.signed || 0}/${m.total || 0}`, 'Memories authored by the agent wallet')}+ ${stat('Verified', m.signed ? `${verifyPct}%` : '—', 'Signatures that re-verify right now')}+ ${stat('Public', `${m.public || 0}`, 'Shareable in an exported brain')}+ ${stat('Encrypted pins', `${m.encrypted_pinned || 0}`, 'Private memories pinned encrypted to your wallet')}+ </div>++ ${section(+ 'Storage',+ `+ <p class="bo-hint">How this agent's new memories are stored by default. Encrypted-IPFS encrypts to your wallet — we can't read it; you can move it.</p>+ <div class="bo-field">+ <label class="bo-field__label" for="bo-storage-mode">Default storage mode</label>+ <select class="bo-select" id="bo-storage-mode" aria-describedby="bo-storage-desc">+ ${Object.keys(STORAGE_LABELS)+ .map(+ (mode) =>+ `<option value="${mode}" ${p.storage_mode === mode ? 'selected' : ''}>${+ mode === 'encrypted-ipfs' ? 'Encrypted IPFS' : mode[0].toUpperCase() + mode.slice(1)+ }</option>`,+ )+ .join('')}+ </select>+ </div>+ <p class="bo-storage-desc" id="bo-storage-desc">${escapeHtml(STORAGE_LABELS[p.storage_mode] || '')}</p>+ <span class="bo-status" id="bo-storage-status" role="status" aria-live="polite"></span>+ `,+ )}++ ${section(+ 'On-chain anchor',+ anchorSection(p),+ )}++ ${section('IPFS pins', pinsSection(p.pins || []))}++ ${section(+ 'Provenance',+ p.provenance+ ? `<div class="bo-prov">+ <p>Forked from <strong>${escapeHtml(p.provenance.source_agent_name || p.provenance.source_agent_id)}</strong></p>+ <p class="bo-hint">Imported ${p.provenance.imported_count ?? '?'} ${+ p.provenance.imported_count === 1 ? 'memory' : 'memories'+ } · ${escapeHtml(fmtDate(p.provenance.imported_at))} · brain hash <code>${escapeHtml(+ shortHash(p.provenance.source_brain_hash),+ )}</code></p>+ </div>`+ : `<p class="bo-hint">This mind is original — not imported from another agent.</p>`,+ )}++ ${section(+ 'Export / Import',+ `+ <p class="bo-hint">A <code>.brain</code> file is a schema-versioned, signed snapshot of this mind. Public memories travel in the clear; private ones stay encrypted. Back it up, move it, or fork it.</p>+ <div class="bo-actions">+ <button class="bo-btn bo-btn--primary" id="bo-export" type="button">Export brain (public)</button>+ <button class="bo-btn" id="bo-export-private" type="button">Export with private data…</button>+ <label class="bo-btn bo-btn--ghost" for="bo-import-file" tabindex="0" role="button">Import a .brain…</label>+ <input type="file" id="bo-import-file" accept=".brain,.json,application/json" hidden />+ </div>+ <span class="bo-status" id="bo-export-status" role="status" aria-live="polite"></span>+ `,+ )}+ </div>+ `;++ wireCopy(host);+ wireStorage(host, agentId, p);+ wireAnchor(host, agentId);+ wireExportImport(host, agentId, agent);+}++function stat(label, value, title) {+ return `<div class="bo-stat" role="listitem" title="${escapeHtml(title)}">+ <span class="bo-stat__value">${escapeHtml(String(value))}</span>+ <span class="bo-stat__label">${escapeHtml(label)}</span>+ </div>`;+}++function section(title, inner) {+ return `<section class="bo-section">+ <h4 class="bo-section__title">${escapeHtml(title)}</h4>+ ${inner}+ </section>`;+}++function anchorSection(p) {+ const a = p.anchor;+ if (!p.agent?.registered_onchain) {+ return `<p class="bo-hint">Anchoring records a tamper-proof fingerprint of this brain on the ERC-8004 registry.+ Register this agent on-chain first to enable it.</p>+ <button class="bo-btn" id="bo-anchor" type="button" disabled aria-disabled="true">Anchor on-chain</button>`;+ }+ if (a && a.status === 'anchored') {+ const drift = !p.anchor_in_sync;+ return `+ <div class="bo-anchor ${drift ? 'bo-anchor--drift' : 'bo-anchor--synced'}">+ <div class="bo-anchor__row">+ <span class="bo-chip ${drift ? 'bo-chip--warn' : 'bo-chip--ok'}">+ ${drift ? 'Brain changed since last anchor' : 'On-chain & in sync'}+ </span>+ ${a.explorer_url ? `<a class="bo-link" href="${escapeHtml(a.explorer_url)}" target="_blank" rel="noopener">View transaction ↗</a>` : ''}+ </div>+ <dl class="bo-kv">+ <dt>Anchored hash</dt><dd><code>${escapeHtml(shortHash(a.brain_hash))}</code></dd>+ <dt>When</dt><dd>${escapeHtml(fmtDate(a.anchored_at))}</dd>+ ${a.proof_uri ? `<dt>Passport</dt><dd><a class="bo-link" href="${escapeHtml(a.proof_uri)}" target="_blank" rel="noopener">proof ↗</a></dd>` : ''}+ </dl>+ ${drift ? '<button class="bo-btn bo-btn--primary" id="bo-anchor" type="button">Re-anchor current brain</button>' : ''}+ </div>`;+ }+ return `<p class="bo-hint">Record a tamper-proof fingerprint of this brain on the ERC-8004 registry — verifiable proof of what your agent knew and when.</p>+ <button class="bo-btn bo-btn--primary" id="bo-anchor" type="button">Anchor on-chain</button>+ <span class="bo-status" id="bo-anchor-status" role="status" aria-live="polite"></span>`;+}++function pinsSection(pins) {+ if (!pins.length) {+ return `<p class="bo-hint">No memories are pinned to IPFS yet. Set storage to IPFS or Encrypted IPFS, then encrypt & pin a memory to make it portable.</p>`;+ }+ return `<ul class="bo-pins">+ ${pins+ .slice(0, 50)+ .map(+ (pin) => `<li class="bo-pin">+ <a class="bo-pin__cid bo-link" href="${escapeHtml(pin.gateway_url)}" target="_blank" rel="noopener" title="${escapeHtml(pin.cid)}">+ ${escapeHtml(pin.filename)} <code>${escapeHtml(shortHash(pin.cid, 6))}</code> ↗+ </a>+ <span class="bo-pin__meta">${escapeHtml(fmtBytes(pin.bytes))} · ${escapeHtml(fmtDate(pin.created_at))}</span>+ </li>`,+ )+ .join('')}+ </ul>`;+}++// ── Wiring ───────────────────────────────────────────────────────────────────++function wireCopy(host) {+ host.querySelectorAll('.bo-copy').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const val = btn.dataset.copy;+ if (!val) return;+ try {+ await navigator.clipboard.writeText(val);+ const prev = btn.textContent;+ btn.textContent = '✓';+ setTimeout(() => (btn.textContent = prev), 1200);+ } catch {+ /* clipboard unavailable — non-fatal */+ }+ });+ });+}++function wireStorage(host, agentId, p) {+ const sel = host.querySelector('#bo-storage-mode');+ const desc = host.querySelector('#bo-storage-desc');+ const status = host.querySelector('#bo-storage-status');+ if (!sel) return;+ sel.addEventListener('change', async () => {+ const mode = sel.value;+ if (desc) desc.textContent = STORAGE_LABELS[mode] || '';+ setStatus(status, 'Saving…', '');+ try {+ const r = await apiFetch(`${API}/agents/${agentId}/brain/storage`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ defaultMode: mode }),+ });+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error_description || `HTTP ${r.status}`);+ setStatus(status, 'Saved', 'ok');+ agentBus.emit('brain:updated', { agentId, storageMode: mode, ts: Date.now() });+ } catch (err) {+ sel.value = p.storage_mode;+ if (desc) desc.textContent = STORAGE_LABELS[p.storage_mode] || '';+ setStatus(status, `Could not save: ${err.message}`, 'err');+ }+ });+}++function wireAnchor(host, agentId) {+ const btn = host.querySelector('#bo-anchor');+ if (!btn || btn.disabled) return;+ btn.addEventListener('click', async () => {+ const status = host.querySelector('#bo-anchor-status');+ const confirmed = window.confirm(+ 'Anchor this brain on-chain?\n\nThis writes a tamper-proof fingerprint of the current memory set to the ERC-8004 registry. It costs a small amount of gas and is permanent.',+ );+ if (!confirmed) return;+ btn.disabled = true;+ const orig = btn.textContent;+ btn.textContent = 'Anchoring…';+ setStatus(status, 'Submitting transaction… this can take a moment.', '');+ try {+ const r = await apiFetch(`${API}/agents/${agentId}/brain/anchor`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({}),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ agentBus.emit('brain:updated', { agentId, anchored: true, txHash: j.tx_hash, ts: Date.now() });+ // Re-render with the fresh anchor state.+ const fresh = await fetchPassport(agentId);+ render(host, agentId, fresh);+ } catch (err) {+ btn.disabled = false;+ btn.textContent = orig;+ setStatus(status, anchorError(err.message), 'err');+ }+ });+}++// Map the backend's machine-readable anchor error codes to actionable copy.+function anchorError(msg) {+ if (/not_registered/i.test(msg)) return 'Register this agent on-chain first, then anchor.';+ if (/validator_key_not_configured|registry_not_deployed/i.test(msg))+ return 'On-chain anchoring is not available on this deployment yet.';+ if (/validator_not_allowlisted/i.test(msg)) return 'The platform validator is not yet allow-listed on this chain.';+ return `Could not anchor: ${msg}`;+}++function wireExportImport(host, agentId, agent) {+ const status = host.querySelector('#bo-export-status');++ const doExport = async (includePrivate) => {+ setStatus(status, 'Building bundle…', '');+ try {+ const url = `${API}/agents/${agentId}/brain/export${includePrivate ? '?includePrivate=true' : ''}`;+ const r = await apiFetch(url, { credentials: 'include' });+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error_description || `HTTP ${r.status}`);+ const bundle = await r.json();+ downloadJson(bundle, `${(agent?.name || 'agent').replace(/[^a-z0-9]+/gi, '-').toLowerCase()}.brain.json`);+ setStatus(+ status,+ `Exported ${bundle.manifest?.memory_count ?? 0} memories${+ bundle.signature ? ' (signed)' : ''+ }.`,+ 'ok',+ );+ } catch (err) {+ setStatus(status, `Export failed: ${err.message}`, 'err');+ }+ };++ host.querySelector('#bo-export')?.addEventListener('click', () => doExport(false));+ host.querySelector('#bo-export-private')?.addEventListener('click', () => {+ const ok = window.confirm(+ 'Export WITH private data?\n\nThis includes the plaintext of your agent\'s private memories in the downloaded file. Anyone who opens the file can read them. Keep it safe.',+ );+ if (ok) doExport(true);+ });++ const fileInput = host.querySelector('#bo-import-file');+ const fileLabel = host.querySelector('label[for="bo-import-file"]');+ fileLabel?.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ fileInput?.click();+ }+ });+ fileInput?.addEventListener('change', async () => {+ const file = fileInput.files?.[0];+ if (!file) return;+ setStatus(status, 'Reading bundle…', '');+ let bundle;+ try {+ bundle = JSON.parse(await file.text());+ } catch {+ setStatus(status, 'That file is not a valid .brain bundle (could not parse JSON).', 'err');+ fileInput.value = '';+ return;+ }+ const count = bundle?.manifest?.memory_count ?? bundle?.memories?.length ?? 0;+ const src = bundle?.agent?.name || bundle?.agent?.id || 'another agent';+ const ok = window.confirm(+ `Import ${count} memories from "${src}" into this agent?\n\nProvenance is preserved and duplicates are skipped. Existing memories are kept (merge).`,+ );+ if (!ok) {+ fileInput.value = '';+ return;+ }+ setStatus(status, 'Verifying signatures & importing…', '');+ try {+ const r = await apiFetch(`${API}/agents/${agentId}/brain/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ bundle, strategy: 'merge', importPersona: false }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ setStatus(+ status,+ `Imported ${j.imported} memories (${j.duplicates} duplicate${j.duplicates === 1 ? '' : 's'} skipped${+ j.skipped_encrypted ? `, ${j.skipped_encrypted} encrypted skipped` : ''+ }).`,+ 'ok',+ );+ agentBus.emit('memory:added', { agentId, imported: j.imported, ts: Date.now() });+ // Refresh the passport to reflect the merged mind.+ const fresh = await fetchPassport(agentId);+ render(host, agentId, fresh, agent);+ } catch (err) {+ setStatus(status, importError(err.message), 'err');+ } finally {+ fileInput.value = '';+ }+ });+}++function importError(msg) {+ if (/integrity_failed/i.test(msg)) return `Import rejected — the bundle failed verification: ${msg}`;+ if (/invalid_bundle/i.test(msg)) return `That file is not a valid brain bundle: ${msg}`;+ return `Import failed: ${msg}`;+}++// ── helpers ──────────────────────────────────────────────────────────────────++function setStatus(el, msg, cls) {+ if (!el) return;+ el.textContent = msg;+ el.className = `bo-status${cls ? ` bo-status--${cls}` : ''}`;+}++function downloadJson(obj, filename) {+ const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++function skeleton() {+ return `<div class="brain-own brain-own--loading" aria-busy="true">+ <div class="bo-skel bo-skel--hero"></div>+ <div class="bo-skel-row">+ <div class="bo-skel bo-skel--stat"></div><div class="bo-skel bo-skel--stat"></div>+ <div class="bo-skel bo-skel--stat"></div><div class="bo-skel bo-skel--stat"></div>+ </div>+ <div class="bo-skel bo-skel--block"></div>+ <div class="bo-skel bo-skel--block"></div>+ </div>`;+}++function errorState(message, _retry) {+ return `<div class="brain-own"><div class="bo-error">+ <p>Could not load brain ownership: ${escapeHtml(message)}</p>+ <button class="bo-btn" id="bo-retry" type="button">Retry</button>+ </div></div>`;+}++function wireRetry(host, retry) {+ host.querySelector('#bo-retry')?.addEventListener('click', retry);+}++export default { mountBrainOwnership };diff --git a/src/brain-studio.js b/src/brain-studio.jsindex cf4854d82..6e52ad517 100644--- a/src/brain-studio.js+++ b/src/brain-studio.js@@ -20,7 +20,6 @@ import {describeTrait,compilePersona,registerSummary,- bandIndex,} from './agents/persona-compile.js';import { agentBus, EVENTS } from './agents/agent-bus.js';diff --git a/src/genesis.js b/src/genesis.jsnew file mode 100644index 000000000..a487d21f0--- /dev/null+++ b/src/genesis.js@@ -0,0 +1,827 @@+// Instant Agent Genesis — selfie/prompt/remix → rigged 3D avatar → agent ++// custodial Solana/EVM wallet → optional ERC-8004 on-chain identity, in one+// guided flow. Every step is real:+//+// • 3D body POST /api/avatars/reconstruct (text prompt OR photo),+// poll /api/avatars/regenerate-status — the same rigged-+// avatar pipeline /create/prompt and /create/selfie use.+// Remix instead forks a public avatar (POST /api/avatars/fork).+// • agent + wallet reconstruct/fork auto-provision the agent; we resolve it+// via GET /api/agents?avatar_id=… and guarantee both wallets+// with POST /api/agents/:id/wallet/provision (real addresses).+// • persona + voice POST /api/persona/extract synthesizes a system prompt,+// PATCH /api/agents/:id persists name + persona + voice.+// • on-chain id bindExistingAgentOnchain() mints a real ERC-8004 record+// and returns a real tx hash.+//+// No mocks, no fake progress: the bar is driven by the real job state, the wallet+// address is the real custodial address, the tx hash is the real signature.++import { apiFetch } from './api.js';+import { getMe } from './account.js';+// wallet-auth.js and erc8004/agent-registry.js pull in ethers — heavy and only+// needed when the user actually signs in or registers an identity. They're+// dynamically imported at those call sites so the initial genesis bundle stays light.++const $ = (sel, root = document) => root.querySelector(sel);+const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));++// ── Constants ──────────────────────────────────────────────────────────────+const RECONSTRUCT_ENDPOINT = '/api/avatars/reconstruct';+const STATUS_ENDPOINT = '/api/avatars/regenerate-status';+const POLL_FIRST_MS = 1500;+const POLL_BACKOFF = 1.4;+const POLL_MAX_MS = 12000;+const GENERATION_DEADLINE_MS = 8 * 60 * 1000;+const AGENT_RESOLVE_DEADLINE_MS = 60 * 1000;+const REGISTER_CHAIN_ID = 8453; // Base — same default as the rest of the platform++const EXAMPLE_PROMPTS = [+ 'A silver-haired explorer in a teal flight jacket',+ 'A neon cyber-samurai with a glowing visor',+ 'A friendly robot barista with copper plating',+ 'A cosmic oracle in flowing star-speckled robes',+ 'A rugged desert ranger in a dust-worn cloak',+];++// ── State ──────────────────────────────────────────────────────────────────+const state = {+ authed: false,+ mode: 'text',+ photoDataUrl: null,+ remixAvatarId: null,+ abort: null,+ startedAt: 0,+ elapsedTimer: null,+ // outputs+ avatarId: null,+ agent: null, // { id, solana_address, wallet_address, home_url, name }+ modelUrl: null,+ onchain: null,+};++// ── Stage helpers ──────────────────────────────────────────────────────────+function showStage(name) {+ $$('[data-stage]').forEach((el) => {+ el.hidden = el.dataset.stage !== name;+ });+ window.scrollTo({ top: 0, behavior: 'smooth' });+}++function showError(elId, message, onRetry) {+ const el = document.getElementById(elId);+ if (!el) return;+ el.innerHTML = '';+ const p = document.createElement('div');+ p.textContent = message;+ el.appendChild(p);+ if (onRetry) {+ const btn = document.createElement('button');+ btn.className = 'gx-btn gx-btn-ghost';+ btn.textContent = 'Try again';+ btn.addEventListener('click', onRetry);+ el.appendChild(btn);+ }+ el.hidden = false;+}++function clearError(elId) {+ const el = document.getElementById(elId);+ if (el) el.hidden = true;+}++function setStep(step, stateName, detail) {+ const el = $(`.gx-step[data-step="${step}"]`);+ if (!el) return;+ el.dataset.state = stateName;+ if (detail != null) {+ const d = $('[data-role="detail"]', el);+ if (d) d.textContent = detail;+ }+}++function setStepBar(step, pct) {+ const el = $(`.gx-step[data-step="${step}"] [data-role="bar"]`);+ if (el) el.style.width = `${Math.max(0, Math.min(100, pct))}%`;+}++// ── Model viewer ───────────────────────────────────────────────────────────+function mountModelViewer(container, src) {+ container.innerHTML = '';+ const mv = document.createElement('model-viewer');+ mv.setAttribute('src', src);+ mv.setAttribute('alt', 'Your new 3D agent');+ mv.setAttribute('auto-rotate', '');+ mv.setAttribute('rotation-per-second', '14deg');+ mv.setAttribute('interaction-prompt', 'none');+ mv.setAttribute('camera-controls', '');+ mv.setAttribute('shadow-intensity', '0.8');+ mv.setAttribute('shadow-softness', '0.9');+ mv.setAttribute('environment-image', 'neutral');+ mv.setAttribute('exposure', '0.95');+ mv.setAttribute('camera-orbit', '0deg 80deg auto');+ mv.setAttribute('loading', 'eager');+ container.appendChild(mv);+}++// ── Auth ───────────────────────────────────────────────────────────────────+async function refreshAuth() {+ let me = null;+ try {+ me = await getMe();+ } catch {+ me = null;+ }+ state.authed = !!(me && me.id);+ const banner = $('#gx-auth');+ if (banner) banner.hidden = state.authed;+ return state.authed;+}++async function handleSignIn() {+ const btn = $('#gx-signin');+ if (btn) {+ btn.disabled = true;+ btn.textContent = 'Connecting…';+ }+ try {+ const { signInWithWallet } = await import('./wallet-auth.js');+ await signInWithWallet();+ await refreshAuth();+ } catch (err) {+ showError('gx-input-error', err?.message || 'Sign-in failed. Try again.');+ } finally {+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Sign in';+ }+ }+}++// ── Input wiring ───────────────────────────────────────────────────────────+function selectMode(mode) {+ state.mode = mode;+ $$('.gx-tab').forEach((t) => t.setAttribute('aria-selected', String(t.dataset.mode === mode)));+ $$('.gx-panel').forEach((p) => {+ p.hidden = p.dataset.panel !== mode;+ });+ if (mode === 'remix') loadRemixGallery();+}++function renderExampleChips() {+ const wrap = $('#gx-chips');+ if (!wrap) return;+ EXAMPLE_PROMPTS.forEach((text) => {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'gx-chip';+ b.textContent = text;+ b.addEventListener('click', () => {+ $('#gx-prompt').value = text;+ $('#gx-prompt').focus();+ });+ wrap.appendChild(b);+ });+}++async function loadVoices() {+ try {+ const res = await fetch('/api/tts/voices', { credentials: 'omit' });+ if (!res.ok) return;+ const data = await res.json();+ const select = $('#gx-voice');+ if (!select || !Array.isArray(data.voices)) return;+ for (const v of data.voices) {+ const id = v.id || v.voice_id;+ if (!id) continue;+ const opt = document.createElement('option');+ opt.value = id;+ opt.textContent = v.name || v.label || id;+ select.appendChild(opt);+ }+ } catch {+ /* voice picker stays at browser default — non-fatal */+ }+}++function handlePhotoFile(file) {+ if (!file || !file.type.startsWith('image/')) return;+ const reader = new FileReader();+ reader.onload = () => {+ state.photoDataUrl = String(reader.result || '');+ $('#gx-photo-img').src = state.photoDataUrl;+ $('#gx-photo-preview').classList.add('is-on');+ };+ reader.readAsDataURL(file);+}++function wirePhotoInput() {+ const input = $('#gx-photo-input');+ const drop = $('#gx-drop');+ input.addEventListener('change', () => handlePhotoFile(input.files?.[0]));+ ['dragenter', 'dragover'].forEach((ev) =>+ drop.addEventListener(ev, (e) => {+ e.preventDefault();+ drop.classList.add('is-drag');+ }),+ );+ ['dragleave', 'drop'].forEach((ev) =>+ drop.addEventListener(ev, (e) => {+ e.preventDefault();+ drop.classList.remove('is-drag');+ }),+ );+ drop.addEventListener('drop', (e) => handlePhotoFile(e.dataTransfer?.files?.[0]));+ $('#gx-photo-clear').addEventListener('click', () => {+ state.photoDataUrl = null;+ input.value = '';+ $('#gx-photo-preview').classList.remove('is-on');+ });+}++async function loadRemixGallery() {+ const grid = $('#gx-remix-grid');+ if (!grid || grid.dataset.loaded) return;+ try {+ const res = await fetch('/api/avatars/featured?limit=18', { credentials: 'include' });+ const data = await res.json();+ const avatars = (data.avatars || data.data || []).filter((a) => a && a.id);+ if (!avatars.length) {+ grid.innerHTML = '<p class="gx-hint">No public avatars to fork yet — try Describe or Selfie.</p>';+ return;+ }+ grid.innerHTML = '';+ for (const a of avatars) {+ const thumb = a.thumbnail_url || a.thumbnail || a.poster_url;+ if (!thumb) continue;+ const tile = document.createElement('button');+ tile.type = 'button';+ tile.className = 'gx-remix-tile';+ tile.setAttribute('aria-pressed', 'false');+ tile.innerHTML = `<img loading="lazy" src="${thumb}" alt="${(a.name || 'Avatar').replace(/"/g, '')}" /><span>${a.name || 'Avatar'}</span>`;+ tile.addEventListener('click', () => {+ state.remixAvatarId = a.id;+ $$('.gx-remix-tile').forEach((t) => t.setAttribute('aria-pressed', 'false'));+ tile.setAttribute('aria-pressed', 'true');+ if (!$('#gx-name').value) $('#gx-name').value = a.name || '';+ });+ grid.appendChild(tile);+ }+ grid.dataset.loaded = '1';+ if (!grid.children.length) {+ grid.innerHTML = '<p class="gx-hint">No public avatars to fork yet — try Describe or Selfie.</p>';+ }+ } catch {+ grid.innerHTML = '<p class="gx-hint">Couldn\'t load avatars. Try Describe or Selfie instead.</p>';+ }+}++// ── Genesis orchestration ──────────────────────────────────────────────────+async function beginGenesis() {+ clearError('gx-input-error');++ if (!(await refreshAuth())) {+ showError('gx-input-error', 'Sign in first — genesis claims the agent and wallet to your account.');+ $('#gx-auth')?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ return;+ }++ // Validate per-mode input before leaving the form.+ const prompt = $('#gx-prompt').value.trim();+ if (state.mode === 'text' && prompt.length < 3) {+ showError('gx-input-error', 'Describe your agent in a few words to begin.');+ return;+ }+ if (state.mode === 'photo' && !state.photoDataUrl) {+ showError('gx-input-error', 'Choose a photo to build your agent from.');+ return;+ }+ if (state.mode === 'remix' && !state.remixAvatarId) {+ showError('gx-input-error', 'Pick a public avatar to fork.');+ return;+ }++ // Reset run state.+ state.abort = new AbortController();+ state.avatarId = null;+ state.agent = null;+ state.modelUrl = null;+ state.onchain = null;+ clearError('gx-forge-error');+ resetForgeUi();+ showStage('forging');+ startElapsed();++ const name = $('#gx-name').value.trim() || null;+ const personaText = $('#gx-persona').value.trim();+ const voiceId = $('#gx-voice').value || null;++ // Persona synthesis (LLM) needs no avatar — run it in parallel with the mesh.+ // Swallow its failure here so a later abort/throw can't surface as an unhandled+ // rejection; a null persona just falls back to the raw text.+ const personaPromise = (personaText ? extractPersona(personaText, name) : Promise.resolve(null)).catch(+ () => null,+ );++ try {+ // 1) Body → avatarId (also auto-provisions the agent server-side).+ let forkAgent = null;+ if (state.mode === 'remix') {+ const forked = await forkAvatar(state.remixAvatarId);+ state.avatarId = forked.avatar.id;+ forkAgent = forked.agent || null;+ setStep('model', 'done', 'Forked into your namespace.');+ setStepBar('model', 100);+ } else {+ const jobId = await submitReconstruct({ name, prompt });+ state.avatarId = await pollReconstruct(jobId);+ setStep('model', 'done', 'Rigged and ready.');+ setStepBar('model', 100);+ }+ if (state.abort.signal.aborted) return;++ // 2) Resolve the agent + guarantee a real custodial wallet.+ setStep('wallet', 'active', 'Provisioning Solana + EVM wallets…');+ const agentId = forkAgent?.id || (await resolveAgentId(state.avatarId));+ const wallet = await provisionWallet(agentId, forkAgent);+ state.agent = {+ id: agentId,+ solana_address: wallet.solana_address,+ wallet_address: wallet.wallet_address,+ };+ setStep('wallet', 'done', 'Wallet live.');+ if (state.abort.signal.aborted) return;++ // 3) Persona + voice + name onto the agent.+ setStep('persona', 'active', personaText ? 'Writing the persona…' : 'Saving identity…');+ const persona = await personaPromise;+ await applyAgentProfile(agentId, { name, persona, personaText, voiceId });+ setStep('persona', 'done', persona ? 'Persona set.' : 'Saved.');++ // 4) Hydrate the reveal.+ await hydrateReveal(agentId, state.avatarId, name);+ stopElapsed();+ showStage('reveal');+ } catch (err) {+ if (state.abort?.signal.aborted) return;+ stopElapsed();+ const active = $('.gx-step[data-state="active"]');+ if (active) active.dataset.state = 'failed';+ showError('gx-forge-error', err?.message || 'Genesis hit a snag. Your inputs are safe — try again.', () => {+ clearError('gx-forge-error');+ showStage('input');+ });+ }+}++async function readJson(res) {+ return res.json().catch(() => ({}));+}++function apiError(data, fallback) {+ return (+ data?.error_description ||+ (typeof data?.error === 'string' ? data.error : null) ||+ data?.message ||+ fallback+ );+}++async function submitReconstruct({ name, prompt }) {+ // A selfie stays private; a described avatar is unlisted — usable and+ // shareable by its owner, but never auto-injected into public galleries.+ const body = { name: name || undefined, visibility: state.mode === 'photo' ? 'private' : 'unlisted' };+ if (state.mode === 'photo') {+ body.photos = [state.photoDataUrl];+ body.params = { bodyType: $('#gx-bodytype').value, style: $('#gx-style').value };+ } else {+ body.prompt = prompt;+ const key = $('#gx-meshy-key')?.value.trim();+ if (key) {+ body.provider_key = key;+ body.provider_name = 'meshy';+ }+ }+ const res = await apiFetch(RECONSTRUCT_ENDPOINT, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ if (!res.ok || !data.jobId) {+ throw new Error(mapReconstructError(res.status, data));+ }+ return data.jobId;+}++function mapReconstructError(status, data) {+ const code = typeof data?.error === 'string' ? data.error : data?.code;+ if (status === 429 || code === 'txt2img_rate_limited') return 'The avatar engine is busy. Wait a moment and try again.';+ if (code === 'txt2img_error') return "Couldn't render from that prompt. Try rewording it.";+ if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again shortly.';+ if (status === 413) return 'That photo is too large. Try a smaller image.';+ return apiError(data, `The avatar engine returned ${status}. Try again.`);+}++const RECON_PROGRESS = {+ queued: [5, 18, 'Queued behind the avatar engine…'],+ running: [18, 78, 'Sculpting your 3D body…'],+ rigging: [78, 96, 'Rigging the skeleton so it can move…'],+};++async function pollReconstruct(jobId) {+ const deadline = Date.now() + GENERATION_DEADLINE_MS;+ let wait = POLL_FIRST_MS;+ let shown = 5;+ setStepBar('model', shown);+ while (Date.now() < deadline) {+ if (state.abort.signal.aborted) throw new Error('cancelled');+ await sleep(wait, state.abort.signal);+ wait = Math.min(wait * POLL_BACKOFF, POLL_MAX_MS);++ const res = await apiFetch(`${STATUS_ENDPOINT}?jobId=${encodeURIComponent(jobId)}`, {+ allowAnonymous: true,+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ if (!res.ok) throw new Error(apiError(data, `Status check failed (${res.status}).`));++ const band = RECON_PROGRESS[data.status];+ if (band) {+ const [floor, ceil, label] = band;+ shown = Math.min(ceil, Math.max(shown + 3, floor));+ setStepBar('model', shown);+ setStep('model', 'active', label);+ }+ if (data.status === 'done' && data.resultAvatarId) return data.resultAvatarId;+ if (data.status === 'failed') throw new Error(friendlyJobError(data.error));+ }+ throw new Error('Generation took too long. Try a simpler prompt or photo.');+}++function friendlyJobError(code) {+ const map = {+ moderation_blocked: 'That photo was flagged by moderation. Try a clear, front-facing photo of a person.',+ no_face_detected: "Couldn't find a face in that photo. Use a clear, front-facing shot.",+ provider_error: 'The avatar engine failed on this one. Try again or tweak your input.',+ };+ return map[code] || 'The avatar engine couldn\'t finish this one. Try again with a different input.';+}++async function forkAvatar(sourceAvatarId) {+ const res = await apiFetch('/api/avatars/fork', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ source_avatar_id: sourceAvatarId }),+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ if (res.status === 409 && data?.error === 'royalty_consent_required') {+ const pct = data?.royalty?.total_pct ?? 0;+ const ok = window.confirm(+ `This avatar charges a ${pct}% fork royalty to its creators on tips & streams. Fork it on these terms?`,+ );+ if (!ok) throw new Error('Fork cancelled — no royalty accepted.');+ return forkAvatarWithConsent(sourceAvatarId);+ }+ if (!res.ok || !data.avatar?.id) throw new Error(apiError(data, 'Could not fork that avatar.'));+ return data;+}++async function forkAvatarWithConsent(sourceAvatarId) {+ const res = await apiFetch('/api/avatars/fork', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ source_avatar_id: sourceAvatarId, accept_royalty: true }),+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ if (!res.ok || !data.avatar?.id) throw new Error(apiError(data, 'Could not fork that avatar.'));+ return data;+}++async function resolveAgentId(avatarId) {+ const deadline = Date.now() + AGENT_RESOLVE_DEADLINE_MS;+ let wait = 800;+ while (Date.now() < deadline) {+ if (state.abort.signal.aborted) throw new Error('cancelled');+ const res = await apiFetch(`/api/agents?avatar_id=${encodeURIComponent(avatarId)}`, {+ allowAnonymous: true,+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ const agents = data.agents || data.data?.agents || [];+ const agent = agents.find((a) => a && a.id);+ if (agent) return agent.id;+ await sleep(wait, state.abort.signal);+ wait = Math.min(wait * 1.4, 4000);+ }+ throw new Error('Your agent is taking longer than usual to wake up. Refresh in a moment — it will be in your account.');+}++async function provisionWallet(agentId, forkAgent) {+ // Fork already provisioned both wallets synchronously and handed them back.+ if (forkAgent?.solana_address || forkAgent?.wallet_address) {+ return { solana_address: forkAgent.solana_address, wallet_address: forkAgent.wallet_address };+ }+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/wallet/provision`, {+ method: 'POST',+ signal: state.abort.signal,+ });+ const data = await readJson(res);+ if (!res.ok) throw new Error(apiError(data, 'Could not provision the wallet.'));+ return { solana_address: data.solana_address, wallet_address: data.wallet_address };+}++async function extractPersona(freeform, name) {+ const res = await apiFetch('/api/persona/extract', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ freeform: name ? `${name}: ${freeform}` : freeform }),+ });+ if (!res.ok) return null;+ const data = await readJson(res);+ return data.persona || null;+}++function composePersonaPrompt(name, persona, fallbackText) {+ if (!persona) return fallbackText || null;+ const who = name || 'this agent';+ const lines = [`You are ${who}, a 3D AI agent on three.ws.`];+ if (persona.tone) lines.push(persona.tone);+ if (persona.communication_style) lines.push(`Your communication style is ${persona.communication_style}.`);+ if (Array.isArray(persona.interests) && persona.interests.length) {+ lines.push(`You care about ${persona.interests.join(', ')}.`);+ }+ if (Array.isArray(persona.vocabulary) && persona.vocabulary.length) {+ lines.push(`You naturally say things like: ${persona.vocabulary.slice(0, 6).join('; ')}.`);+ }+ if (Array.isArray(persona.dont_say) && persona.dont_say.length) {+ lines.push(`Never say: ${persona.dont_say.join('; ')}.`);+ }+ return lines.join(' ');+}++async function applyAgentProfile(agentId, { name, persona, personaText, voiceId }) {+ const personaPrompt = composePersonaPrompt(name, persona, personaText);+ const meta = { created_via: 'genesis' };+ if (voiceId) {+ meta.voice_preference = voiceId;+ meta.voice_id = voiceId;+ }+ if (persona?.sample_greeting) meta.greeting = persona.sample_greeting;+ const body = { meta };+ if (name) body.name = name;+ if (personaPrompt) body.persona_prompt = personaPrompt.slice(0, 8000);++ // Best-effort: a profile-write hiccup must not lose the already-created agent.+ try {+ await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ } catch {+ /* the agent exists and is owned; profile can be edited from its page */+ }+}++async function hydrateReveal(agentId, avatarId, name) {+ // Pull the agent for its real name + home_url, and the avatar for its model URL.+ let agentRow = null;+ try {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, { allowAnonymous: true });+ if (res.ok) agentRow = (await readJson(res)).agent;+ } catch {+ /* fall back to local state below */+ }+ if (agentRow) {+ state.agent.solana_address = agentRow.solana_address || state.agent.solana_address;+ state.agent.wallet_address = agentRow.wallet_address || state.agent.wallet_address;+ state.agent.home_url = agentRow.home_url || null;+ state.agent.name = agentRow.name || name;+ }++ try {+ const res = await apiFetch(`/api/avatars/${encodeURIComponent(avatarId)}`, { allowAnonymous: true });+ if (res.ok) {+ const av = (await readJson(res)).avatar;+ state.modelUrl = av?.model_url || av?.url || null;+ }+ } catch {+ /* viewer falls back to placeholder */+ }++ renderReveal(name);+}++// ── Reveal rendering ───────────────────────────────────────────────────────+function shorten(addr) {+ if (!addr) return '—';+ return addr.length > 16 ? `${addr.slice(0, 6)}…${addr.slice(-6)}` : addr;+}++function walletRow(chainLabel, address) {+ const row = document.createElement('div');+ row.className = 'gx-addr';+ const left = document.createElement('div');+ left.className = 'gx-addr-l';+ left.innerHTML = `<div class="gx-addr-chain">${chainLabel}</div><code title="${address || ''}">${address ? shorten(address) : 'Provisioning…'}</code>`;+ row.appendChild(left);+ if (address) {+ const copy = document.createElement('button');+ copy.className = 'gx-copy';+ copy.type = 'button';+ copy.textContent = 'Copy';+ copy.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(address);+ copy.textContent = 'Copied';+ copy.classList.add('is-copied');+ setTimeout(() => {+ copy.textContent = 'Copy';+ copy.classList.remove('is-copied');+ }, 1600);+ } catch {+ copy.textContent = 'Copy failed';+ }+ });+ row.appendChild(copy);+ }+ return row;+}++function renderReveal(name) {+ const agent = state.agent;+ const displayName = agent.name || name || 'Your Agent';+ $('#gx-reveal-name').textContent = displayName;++ const viewer = $('#gx-reveal-viewer');+ if (state.modelUrl) {+ mountModelViewer(viewer, state.modelUrl);+ } else {+ viewer.innerHTML = '<div class="gx-placeholder" style="height:100%;display:grid;place-items:center"><div><div class="gx-orb"></div>Your agent is ready in your account.</div></div>';+ }++ const wallets = $('#gx-wallets');+ wallets.innerHTML = '';+ wallets.appendChild(walletRow('Solana', agent.solana_address));+ wallets.appendChild(walletRow('EVM · Base', agent.wallet_address));++ $('#gx-cta-fund').href = `/agent/${agent.id}/wallet#deposit`;+ $('#gx-cta-open').href = agent.home_url || `/agent/${agent.id}`;+ $('#gx-cta-share').href = `/api/agent-share?id=${encodeURIComponent(agent.id)}`;++ renderIdentity();+}++function renderIdentity() {+ const badge = $('#gx-identity-badge');+ const body = $('#gx-identity-body');+ if (state.onchain?.txHash) {+ badge.textContent = 'Verified on-chain';+ badge.className = 'gx-badge gx-badge-live';+ const explorer = `https://basescan.org/tx/${state.onchain.txHash}`;+ body.innerHTML = `+ <p class="gx-identity-status">ERC-8004 agent #${state.onchain.agentId ?? ''} on Base. Identity tx:</p>+ <a class="gx-tx" href="${explorer}" target="_blank" rel="noopener">${state.onchain.txHash}</a>`;+ return;+ }+ badge.textContent = 'Not registered';+ badge.className = 'gx-badge gx-badge-pending';+ // keep the existing register button + status (set in HTML / reset below)+ if (!$('#gx-register')) {+ body.innerHTML = `+ <button class="gx-btn gx-btn-primary" id="gx-register" type="button" style="width:100%">Register ERC-8004 identity</button>+ <p class="gx-identity-status" id="gx-identity-status">Connect an EVM wallet to mint a verifiable, tradeable identity. Optional — you can do this anytime.</p>`;+ }+ wireRegister();+}++function wireRegister() {+ const btn = $('#gx-register');+ if (!btn || btn.dataset.wired) return;+ btn.dataset.wired = '1';+ btn.addEventListener('click', registerIdentity);+}++async function registerIdentity() {+ const btn = $('#gx-register');+ const status = $('#gx-identity-status');+ if (!btn) return;+ btn.disabled = true;+ const setStatus = (m) => {+ if (status) status.textContent = m;+ };+ setStatus('Connecting your wallet…');+ try {+ const { bindExistingAgentOnchain } = await import('./erc8004/agent-registry.js');+ const result = await bindExistingAgentOnchain(state.agent.id, REGISTER_CHAIN_ID, {+ onStatus: setStatus,+ });+ state.onchain = {+ txHash: result.txHash || result.onchain?.tx_hash || null,+ agentId: result.agentId,+ chainId: result.chainId || REGISTER_CHAIN_ID,+ };+ if (result.alreadyBound && !state.onchain.txHash) {+ state.onchain.txHash = result.onchain?.tx_hash || null;+ }+ if (!state.onchain.txHash) {+ setStatus('Identity registered. Indexing the transaction…');+ }+ renderIdentity();+ } catch (err) {+ btn.disabled = false;+ const msg = err?.message || 'Registration failed.';+ setStatus(+ /wallet|account|reject|connect/i.test(msg)+ ? 'Connect an EVM wallet (e.g. MetaMask) to register. You can do this anytime — your agent is already yours.'+ : `${msg} You can retry anytime.`,+ );+ }+}++// ── Forge UI lifecycle ─────────────────────────────────────────────────────+function resetForgeUi() {+ setStep('model', 'active', state.mode === 'remix' ? 'Forking into your namespace…' : 'Warming up the avatar engine…');+ setStepBar('model', 5);+ setStep('wallet', 'pending', 'Waiting on your agent…');+ setStep('persona', 'pending', $('#gx-persona').value.trim() ? 'Queued — writing once the body lands.' : 'Queued.');+ $('#gx-forge-preview').innerHTML =+ '<div class="gx-placeholder"><div class="gx-orb" aria-hidden="true"></div>Your agent is taking shape…</div>';+}++function startElapsed() {+ state.startedAt = Date.now();+ const el = $('#gx-elapsed');+ stopElapsed();+ state.elapsedTimer = setInterval(() => {+ const s = Math.floor((Date.now() - state.startedAt) / 1000);+ if (el) el.textContent = `Elapsed ${s}s`;+ }, 1000);+}++function stopElapsed() {+ if (state.elapsedTimer) {+ clearInterval(state.elapsedTimer);+ state.elapsedTimer = null;+ }+}++function cancelGenesis() {+ state.abort?.abort();+ stopElapsed();+ showStage('input');+}++function resetToInput() {+ state.onchain = null;+ state.agent = null;+ state.avatarId = null;+ state.modelUrl = null;+ state.photoDataUrl = null;+ state.remixAvatarId = null;+ $('#gx-photo-preview')?.classList.remove('is-on');+ $$('.gx-remix-tile').forEach((t) => t.setAttribute('aria-pressed', 'false'));+ showStage('input');+}++// ── Utils ──────────────────────────────────────────────────────────────────+function sleep(ms, signal) {+ return new Promise((resolve, reject) => {+ const t = setTimeout(resolve, ms);+ if (signal) {+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(t);+ reject(new Error('cancelled'));+ },+ { once: true },+ );+ }+ });+}++// ── Init ───────────────────────────────────────────────────────────────────+function init() {+ renderExampleChips();+ wirePhotoInput();+ loadVoices();+ refreshAuth();++ $$('.gx-tab').forEach((tab) => tab.addEventListener('click', () => selectMode(tab.dataset.mode)));+ $('#gx-signin')?.addEventListener('click', handleSignIn);+ $('#gx-begin')?.addEventListener('click', beginGenesis);+ $('#gx-cancel')?.addEventListener('click', cancelGenesis);+ $('#gx-again')?.addEventListener('click', resetToInput);+ wireRegister();+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+} else {+ init();+}diff --git a/src/shared/alpha-copilot-link.js b/src/shared/alpha-copilot-link.jsnew file mode 100644index 000000000..5c9212793--- /dev/null+++ b/src/shared/alpha-copilot-link.js@@ -0,0 +1,64 @@+// alpha-copilot-link — the Alpha Co-pilot entry point on an agent's profile.+//+// Mounts a compact panel cross-linking an agent to the Alpha Co-pilot, where it+// reads a real live launch in character and speaks its verdict aloud. When the+// live feed has a candidate, it deep-links straight to a read of that launch so+// the profile becomes a one-tap path into the magic moment. Pure enhancement:+// any fetch failure degrades to the plain link, and it never blocks the profile.++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++export async function mountAlphaPanel({ agentId, agentName = 'this agent', isOwner = false, container, position = 'append' } = {}) {+ if (!agentId || !container) return null;+ const el = document.createElement('div');+ el.className = 'alpha-link-panel';+ if (position === 'prepend') container.prepend(el);+ else container.append(el);+ injectStyle();++ // Try to surface one live launch to deep-link a read; degrade to the plain link.+ let top = null;+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/alpha/candidates?network=mainnet`, { credentials: 'include' });+ if (r.ok) { const j = await r.json().catch(() => ({})); top = (j.items || [])[0] || null; }+ } catch { /* plain link below */ }++ const base = `/alpha-copilot?agent=${encodeURIComponent(agentId)}`;+ const deep = top?.mint ? `${base}&mint=${encodeURIComponent(top.mint)}` : base;+ const label = top?.symbol ? `$${esc(top.symbol)}` : (top ? 'a live launch' : null);++ el.innerHTML = `+ <div class="alp-head">+ <span class="alp-kicker">Alpha Co-pilot</span>+ <span class="alp-badge">In-character</span>+ </div>+ <p class="alp-copy">${esc(agentName)} reads a real launch in character — citing live liquidity, holders & smart-money — and speaks its verdict aloud.${isOwner ? ' Act on the call within your spend limits.' : ''}</p>+ <div class="alp-actions">+ <a class="alp-btn primary" href="${deep}">${label ? `Hear its read on ${label}` : 'Open Alpha Co-pilot'}</a>+ ${label ? `<a class="alp-btn ghost" href="${base}">Browse launches</a>` : ''}+ </div>`;++ return { el, destroy() { try { el.remove(); } catch { /* idempotent */ } } };+}++let _styled = false;+function injectStyle() {+ if (_styled) return;+ _styled = true;+ const css = `+ .alpha-link-panel{border:1px solid rgba(139,92,246,.28);background:rgba(139,92,246,.06);border-radius:14px;padding:14px 16px;margin:14px 0;font-family:inherit}+ .alpha-link-panel .alp-head{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px}+ .alpha-link-panel .alp-kicker{font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#c4b5fd}+ .alpha-link-panel .alp-badge{font-size:10px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:#c4b5fd;background:rgba(139,92,246,.15);border:1px solid rgba(139,92,246,.3);border-radius:999px;padding:2px 8px}+ .alpha-link-panel .alp-copy{margin:0 0 10px;font-size:14px;opacity:.9;line-height:1.45}+ .alpha-link-panel .alp-actions{display:flex;gap:8px;flex-wrap:wrap}+ .alpha-link-panel .alp-btn{display:inline-block;padding:8px 16px;border-radius:9px;border:1px solid rgba(139,92,246,.3);background:transparent;color:inherit;font:inherit;font-weight:600;cursor:pointer;text-decoration:none;transition:background .15s,transform .1s}+ .alpha-link-panel .alp-btn:hover{background:rgba(139,92,246,.18)}+ .alpha-link-panel .alp-btn:active{transform:scale(.97)}+ .alpha-link-panel .alp-btn.primary{background:linear-gradient(90deg,#a78bfa,#8b5cf6);border:0;color:#fff}+ .alpha-link-panel .alp-btn.ghost{opacity:.85}+ .alpha-link-panel .alp-btn:focus-visible{outline:2px solid #a78bfa;outline-offset:2px}`;+ const tag = document.createElement('style');+ tag.textContent = css;+ document.head.appendChild(tag);+}diff --git a/src/studio/money/money-mount.js b/src/studio/money/money-mount.jsindex e32507532..d94793a09 100644--- a/src/studio/money/money-mount.js+++ b/src/studio/money/money-mount.js@@ -10,6 +10,9 @@import { studio } from '../agent-studio-store.js';import { mountMoneyStudio } from './money-studio.js';+// Side-effect import: registers the P1 brain `market` node runner so the brain+// graph can reason with this agent's real, live trading state (P4 ↔ P1 seam).+import './trading-runner.js';const SELECTOR = '[data-studio-mount="money"]';diff --git a/src/studio/money/trading-brain.js b/src/studio/money/trading-brain.jsindex dfa9b69e7..7befdcfa7 100644--- a/src/studio/money/trading-brain.js+++ b/src/studio/money/trading-brain.js@@ -133,10 +133,12 @@ class TradingBrain {}async _fetchLimits() {+ // Canonical, wallet-independent trade-limits endpoint: returns data.limits as+ // the agent's trade guardrails (works even before a signing wallet exists).const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits`);if (!res.ok) return { trade_limits: null, spent_today_sol: null };const { data } = await res.json();- return { trade_limits: data.trade_limits, spent_today_sol: data.spent_today_sol };+ return { trade_limits: data.limits, spent_today_sol: null };}async _fetchAudit() {@@ -319,11 +321,11 @@ class TradingBrain {const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits`, {method: 'PUT',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ trade_limits: patch }),+ body: JSON.stringify(patch),});if (!res.ok) throw new Error('Could not save guardrails.');const { data } = await res.json();- this.state.tradeLimits = data.trade_limits;+ this.state.tradeLimits = data.limits;this._toast('Guardrails saved — enforced server-side on every trade');} catch (err) {this._toast(err.message || 'Save failed', true);@@ -746,11 +748,9 @@ class TradingBrain {return;}const open = pos.filter((p) => p.status === 'open' || p.status === 'closing');- const closed = pos.filter((p) => p.status === 'closed');host.innerHTML = `<div class="tb-card-head"><h4>Positions <span class="tb-badge">${open.length} open</span></h4></div><ul class="tb-pos">${pos.slice(0, 20).map((p) => this._posRow(p)).join('')}</ul>`;- void closed;}_posRow(p) {@@ -802,6 +802,10 @@ class TradingBrain {this.el.addEventListener('click', (e) => {const btn = e.target.closest('[data-action]');if (!btn) return;+ // This studio is mounted inside the Money panel, which has its own click+ // delegate on a parent node. Stop handled clicks here so a shared action+ // name (e.g. "retry") never double-fires across both delegates.+ e.stopPropagation();const a = btn.dataset.action;if (a === 'retry') return this._load();if (a === 'mode') return this._setMode(btn.dataset.mode);diff --git a/src/theater-stage.js b/src/theater-stage.jsindex bfbbc20cb..fc04fadd2 100644--- a/src/theater-stage.js+++ b/src/theater-stage.js@@ -407,6 +407,7 @@ export function createStage({ canvas, overlay, onSelect, reducedMotion = false }}}+ cast.updateMatrixWorld();projectReceipts(now);renderer.render(scene, camera);}diff --git a/src/theater.css b/src/theater.cssindex f3c379fbf..a4ea0757b 100644--- a/src/theater.css+++ b/src/theater.css@@ -195,6 +195,19 @@@keyframes th-spin { to { transform: rotate(360deg); } }.th-loading p { color: var(--ink-dim, #888); font-size: var(--text-sm, 0.78rem); }+/* Quiet-market card rides the foot of the stage so the cast stays visible. */+.th-quiet {+ top: auto;+ right: auto;+ bottom: var(--space-5, 20px);+ transform: translateX(-50%);+ text-align: left;+ width: min(440px, calc(100% - 32px));+ pointer-events: auto;+}+.th-quiet h2 { font-size: var(--text-md, 0.81rem); }+.th-quiet > p { font-size: var(--text-xs, 0.7rem); }+.th-highlights { margin-top: var(--space-4, 16px); display: flex; flex-direction: column; gap: 6px; text-align: left; max-height: 38vh; overflow-y: auto; }.th-hl {display: flex; align-items: center; gap: 8px;diff --git a/src/theater.js b/src/theater.jsindex 8a768935a..c8481ccc0 100644--- a/src/theater.js+++ b/src/theater.js@@ -79,7 +79,7 @@ async function fetchLeaderboard(limit) {}));}async function fetchNewLaunches(limit) {- const r = await fetch(`/api/agents/public?sort=newest&onchain=1&limit=${limit}`, { headers: { accept: 'application/json' } });+ const r = await fetch(`/api/agents/public?sort=newest&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) => ({@@ -209,8 +209,6 @@ export function initTheater(root) {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;@@ -225,17 +223,25 @@ export function initTheater(root) {// Re-apply any watched highlight that belongs to this room.for (const id of state.watch) if (state.byId.has(id)) stage.highlight(id);++ showState('stage');+ maybeShowQuiet();} catch (err) {log.warn('[theater] room load failed', err?.message);showState('error');}}+ // loading & error are mutually-exclusive center cards over the live canvas.+ // The quiet-market card is independent: it rides at the foot of the stage and+ // only shows while no live event has arrived (the cast still stands on stage).function showState(which) {refs.loading.hidden = which !== 'loading';refs.error.hidden = which !== 'error';- refs.quiet.hidden = which !== 'quiet';- // stage canvas always visible behind overlays+ if (which !== 'stage') refs.quiet.hidden = true;+ }+ function maybeShowQuiet() {+ refs.quiet.hidden = !(state.liveCount === 0 && refs.loading.hidden && refs.error.hidden);}refs.error.querySelector('[data-retry]')?.addEventListener('click', loadRoom);@@ -352,7 +358,8 @@ export function initTheater(root) {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 isOwner = !!agent.is_owner;+ const signedIn = !!me;const watching = state.watch.has(id);const totals = rep?.totals || {};@@ -395,11 +402,16 @@ export function initTheater(root) {]),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' }),- '.',- ]),+ : signedIn+ ? el('p', { class: 'th-panel-foot th-muted' }, [+ 'Fork to own a copy with its own wallet, or follow its alpha from ',+ el('a', { href: `/agent/${id}`, text: 'its profile' }),+ '.',+ ])+ : el('p', { class: 'th-panel-foot th-muted' }, [+ el('a', { href: `/login?next=${encodeURIComponent(`/agent/${id}`)}`, text: 'Sign in' }),+ ' to fork this agent to your own wallet or follow its alpha. Watching is always free.',+ ]),recentForAgent(id),);}@@ -418,8 +430,15 @@ export function initTheater(root) {}function toggleWatch(id) {- if (state.watch.has(id)) { state.watch.delete(id); stage.highlight(null); }- else { state.watch.add(id); stage.highlight(id); }+ if (state.watch.has(id)) {+ state.watch.delete(id);+ // re-focus another watched agent in this room, if any+ const next = [...state.watch].find((w) => state.byId.has(w));+ stage.highlight(next || null);+ } else {+ state.watch.add(id);+ stage.highlight(id);+ }saveWatch([...state.watch]);if (state.selected === id) renderPanel(id);}@@ -443,6 +462,7 @@ export function initTheater(root) {]),),);+ maybeShowQuiet();});// keep ticker timestamps freshdiff --git a/src/trader.css b/src/trader.cssindex fafecdd64..f881e7864 100644--- a/src/trader.css+++ b/src/trader.css@@ -152,6 +152,12 @@.tp-coin-sym { font-weight: var(--weight-semibold); }.tp-coin-mint { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); }.tp-reason { display: inline-block; font-size: var(--text-2xs); padding: 1px var(--space-2xs); border-radius: var(--radius-pill); border: 1px solid var(--stroke); color: var(--ink-dim); }+/* Provenance tags — snipe (chain-proven early entry) and self-deal (excluded). */+.tp-tag { display: inline-block; margin-left: var(--space-2xs); font-size: var(--text-2xs); padding: 1px var(--space-2xs); border-radius: var(--radius-pill); border: 1px solid var(--stroke); white-space: nowrap; vertical-align: middle; }+.tp-tag-snipe { color: var(--wallet-accent-strong, #a78bfa); border-color: color-mix(in srgb, var(--wallet-accent-strong, #a78bfa) 45%, transparent); background: color-mix(in srgb, var(--wallet-accent-strong, #a78bfa) 12%, transparent); }+.tp-tag-self { color: var(--warn, #fbbf24); border-color: color-mix(in srgb, var(--warn, #fbbf24) 45%, transparent); background: color-mix(in srgb, var(--warn, #fbbf24) 12%, transparent); }+.tp-row-muted td { opacity: 0.62; }+.tp-row-muted:hover td { opacity: 0.85; }.tp-proof-link { color: var(--ink-dim); text-decoration: none; font-size: var(--text-2xs); border-bottom: 1px dotted var(--stroke-strong); white-space: nowrap; }.tp-proof-link:hover { color: var(--ink-bright); }@@ -167,6 +173,7 @@margin-bottom: var(--space-md);}.tp-proof-note svg { width: 20px; height: 20px; color: var(--success); flex-shrink: 0; margin-top: 2px; }+.tp-proof-text { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; }.tp-proof-note p { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); line-height: var(--leading-normal); }.tp-proof-note strong { color: var(--ink-bright); }diff --git a/src/trader.js b/src/trader.jsindex 078c53abd..afc492e0b 100644--- a/src/trader.js+++ b/src/trader.js@@ -113,6 +113,15 @@ function metricsGrid(m) {const pf = m.profit_factor == null ? '∞' : m.profit_factor.toFixed(2);const unreal = m.open_count? `<span class="${pnlClass(m.unrealized_pnl_sol)}">${fmtSol(m.unrealized_pnl_sol)}</span>` : '<span class="lb-muted">—</span>';+ // Snipe hit-rate only renders when we can prove at least one entry against a+ // coin's on-chain birth — never a fabricated zero.+ const snipe = m.snipe_hit_rate != null+ ? metric(+ 'Snipe hit-rate',+ `<span class="${m.snipe_hit_rate >= 0.5 ? 'lb-pos' : 'lb-neg'}">${fmtPct(m.snipe_hit_rate * 100)}</span>`,+ `${m.snipe_wins}/${m.snipe_count} fresh-launch wins`,+ )+ : '';return `${metric('Realized P&L', pnl, pnlSub)}${metric('Win rate', fmtPct(m.win_rate * 100), `${m.wins}W · ${m.losses}L`)}@@ -121,6 +130,7 @@ function metricsGrid(m) {${metric('Max drawdown', `<span class="${m.max_drawdown_pct > 0 ? 'lb-neg' : 'lb-muted'}">${m.max_drawdown_pct > 0 ? '−' : ''}${m.max_drawdown_pct.toFixed(1)}%</span>`, fmtSol(m.max_drawdown_sol, { sign: false }))}${metric('Avg hold', holdTime(m.avg_hold_seconds), `median ${holdTime(m.median_hold_seconds)}`)}${metric('Coins traded', String(m.unique_coins), `${m.closed_count} closed trades`)}+ ${snipe}${metric('Open exposure', m.open_count ? fmtSol(m.open_exposure_sol, { sign: false }) : '<span class="lb-muted">none</span>', m.open_count ? `${m.open_count} open · ${unreal}` : 'flat')}`;}@@ -213,8 +223,16 @@ function closedRows(closed) {t.buy_url ? `<a class="tp-proof-link" href="${escapeHtml(t.buy_url)}" target="_blank" rel="noopener">buy ↗</a>` : '',t.sell_url ? `<a class="tp-proof-link" href="${escapeHtml(t.sell_url)}" target="_blank" rel="noopener">sell ↗</a>` : '',].filter(Boolean).join(' ');- return `<tr>- <td><div class="tp-coin"><span class="tp-coin-sym">${escapeHtml(t.symbol || t.name || '—')}</span><span class="tp-coin-mint">${escapeHtml(shortAddr(t.mint, 4, 4))}</span></div></td>+ const tags = [+ t.snipe+ ? `<span class="tp-tag tp-tag-snipe" title="Entered ${t.seconds_after_launch != null ? `${t.seconds_after_launch}s` : 'within minutes'} after this coin's on-chain launch">⚡ snipe</span>`+ : '',+ t.self_dealing+ ? '<span class="tp-tag tp-tag-self" title="Trade on a coin this account launched — excluded from the credited score">self-deal</span>'+ : '',+ ].filter(Boolean).join('');+ return `<tr${t.self_dealing ? ' class="tp-row-muted"' : ''}>+ <td><div class="tp-coin"><span class="tp-coin-sym">${escapeHtml(t.symbol || t.name || '—')}</span><span class="tp-coin-mint">${escapeHtml(shortAddr(t.mint, 4, 4))}</span>${tags}</div></td><td>${pnl}<div class="tp-metric-sub">${pct}</div></td><td><span class="tp-reason">${escapeHtml(t.exit_reason || '—')}</span></td><td>${held}</td>@@ -326,10 +344,23 @@ function render(data) {<div class="tp-panel" data-panel="proof"><div class="tp-proof-note">${SHIELD}+ <div class="tp-proof-text"><p><strong>This track record is verifiable, not trusted.</strong> Every closed trade above links to itson-chain buy and sell transaction on Solscan — the numbers are computed from those, nothing else. Theheadline score is additionally committed on-chain daily as a signed attestation against this trader'swallet${a.wallet ? ` (<a class="tp-proof-link" href="${solscanAddr(a.wallet)}" target="_blank" rel="noopener">${escapeHtml(shortAddr(a.wallet))} ↗</a>)` : ''}, so it can't be quietly edited after the fact.</p>+ ${m.self_dealing_count > 0+ ? `<p><strong>${m.self_dealing_count} self-dealing round-trip${m.self_dealing_count === 1 ? '' : 's'} excluded.</strong>+ Trades on coins this account launched (${fmtSol(m.self_dealing_excluded_pnl_sol, { sign: false })} of realized P&L) are+ not credited to the score — you can't pump a token you minted and call it a track record. They're tagged+ <span class="tp-tag tp-tag-self">self-deal</span> above for full transparency.</p>`+ : ''}+ ${m.snipe_hit_rate != null+ ? `<p><strong>Snipe hit-rate is chain-proven.</strong> ${m.snipe_count} of ${m.snipe_sample} entries with a verifiable+ launch slot landed within 5 minutes of the coin's on-chain birth; ${m.snipe_wins} were profitable. Launch times+ come from observed on-chain create transactions, not self-reported timestamps.</p>`+ : ''}+ </div></div><table class="tp-table"><thead><tr><th>Coin</th><th>P&L</th><th>Exit</th><th>Held</th><th>When</th><th>On-chain</th>diff --git a/tests/alpha-read.test.js b/tests/alpha-read.test.jsnew file mode 100644index 000000000..20657d427--- /dev/null+++ b/tests/alpha-read.test.js@@ -0,0 +1,185 @@+import { describe, it, expect } from 'vitest';+import {+ VERDICTS,+ buildReadPrompt,+ parseReadJson,+ extractNumbers,+ collectSignalNumbers,+ checkGrounding,+ clampSize,+ validateRead,+ deriveGate,+ templatedSpokenLine,+ SIZE_HEADROOM_SOL,+} from '../api/_lib/alpha-read.js';++const SIGNALS = {+ symbol: 'WIDGET',+ name: 'Widget',+ network: 'mainnet',+ age_minutes: 14,+ market_cap_usd: 23000,+ liquidity_sol: 8.4,+ bonding_curve_progress_pct: 41,+ reference_buy_price_impact_pct: 2.3,+ quality_score: 72,+ organic_score: 64,+ smart_money_score: 58,+ smart_money_wallets: 3,+ risk_flags: ['fresh_wallets'],+};++describe('parseReadJson', () => {+ it('parses clean JSON', () => {+ expect(parseReadJson('{"verdict":"watch","conviction":50}')).toEqual({ verdict: 'watch', conviction: 50 });+ });+ it('parses fenced JSON with prose around it', () => {+ const txt = 'Here is my read:\n```json\n{"verdict":"snipe","conviction":80}\n```\nthanks';+ expect(parseReadJson(txt)).toEqual({ verdict: 'snipe', conviction: 80 });+ });+ it('extracts the first balanced object from messy text', () => {+ expect(parseReadJson('blah {"a":1,"b":{"c":2}} trailing')).toEqual({ a: 1, b: { c: 2 } });+ });+ it('returns null on no JSON', () => {+ expect(parseReadJson('no json here')).toBeNull();+ expect(parseReadJson('')).toBeNull();+ });+});++describe('extractNumbers', () => {+ it('handles decimals, thousands separators, and k/m/b suffixes', () => {+ expect(extractNumbers('72.3')).toContain(72.3);+ expect(extractNumbers('$1,234 mcap')).toContain(1234);+ expect(extractNumbers('about 23k market cap')).toContain(23000);+ expect(extractNumbers('3m supply')).toContain(3000000);+ });+});++describe('grounding', () => {+ it('passes a line that only cites real signal numbers', () => {+ const allowed = collectSignalNumbers(SIGNALS, [58]);+ const res = checkGrounding(['Quality is 72 and smart money sits at 58.'], allowed);+ expect(res.ok).toBe(true);+ });+ it('flags a fabricated large figure not present in signals', () => {+ const allowed = collectSignalNumbers(SIGNALS, []);+ const res = checkGrounding(['It already pumped 340% and has $5,000,000 in liquidity.'], allowed);+ expect(res.ok).toBe(false);+ expect(res.suspicious).toContain(5000000);+ });+ it('allows small integer counts without a matching signal', () => {+ const allowed = collectSignalNumbers(SIGNALS, []);+ expect(checkGrounding(['Two risk flags worth noting.'], allowed).ok).toBe(true);+ });+});++describe('clampSize', () => {+ it('returns null for non-positive / missing input', () => {+ expect(clampSize(null, {})).toBeNull();+ expect(clampSize(0, {})).toBeNull();+ expect(clampSize(-1, {})).toBeNull();+ });+ it('clamps to the per-trade cap', () => {+ expect(clampSize(2, { perTradeSol: 0.5 })).toBe(0.5);+ });+ it('clamps to the remaining daily budget', () => {+ expect(clampSize(1, { dailyBudgetSol: 1, dailySpentSol: 0.8 })).toBeCloseTo(0.2, 6);+ });+ it('clamps to wallet balance minus fee headroom', () => {+ expect(clampSize(5, { balanceSol: 0.1 })).toBeCloseTo(0.1 - SIZE_HEADROOM_SOL, 6);+ });+ it('returns 0 when nothing fits', () => {+ expect(clampSize(1, { balanceSol: SIZE_HEADROOM_SOL })).toBe(0);+ });+});++describe('validateRead', () => {+ const owner = { balanceSol: 1, perTradeSol: 0.5, dailyBudgetSol: 2, dailySpentSol: 0, killSwitch: false, frozen: false };++ it('repairs an invalid verdict to watch and clamps conviction', () => {+ const { read } = validateRead({+ raw: { verdict: 'moon', conviction: 250, spoken_line: 'I like Widget here.' },+ signals: SIGNALS, agentName: 'Sage', owner: true, context: owner,+ });+ expect(read.verdict).toBe('watch');+ expect(read.conviction).toBe(100);+ });++ it('clamps a snipe size to policy for the owner', () => {+ const { read, gate } = validateRead({+ raw: { verdict: 'snipe', conviction: 75, suggested_size_sol: 10, risks: [], spoken_line: 'Clean enough — I take a small position.' },+ signals: SIGNALS, agentName: 'Sage', owner: true, context: owner,+ });+ expect(read.suggested_size_sol).toBe(0.5); // per-trade cap+ expect(gate.can_act).toBe(true);+ expect(gate.size_sol).toBe(0.5);+ });++ it('never suggests a size or action for a non-owner', () => {+ const { read, gate } = validateRead({+ raw: { verdict: 'snipe', conviction: 75, suggested_size_sol: 0.3, spoken_line: 'I would size in here.' },+ signals: SIGNALS, agentName: 'Sage', owner: false, context: {},+ });+ expect(read.suggested_size_sol).toBeNull();+ expect(gate.can_act).toBe(false);+ expect(gate.reason).toBe('not_owner');+ });++ it('replaces a spoken line that voices a fabricated number', () => {+ const { read } = validateRead({+ raw: { verdict: 'snipe', conviction: 70, suggested_size_sol: 0.2, risks: [], spoken_line: 'This already did 340% and has $5,000,000 locked — easy snipe.' },+ signals: SIGNALS, agentName: 'Sage', owner: true, context: owner,+ });+ expect(read.hallucination_guard.ok).toBe(false);+ expect(read.hallucination_guard.line_replaced).toBe(true);+ expect(read.spoken_line).not.toMatch(/5,000,000|340/);+ });++ it('keeps a grounded spoken line intact', () => {+ const line = 'Quality is 72 with 3 reputable wallets in — I take a small position.';+ const { read } = validateRead({+ raw: { verdict: 'snipe', conviction: 70, suggested_size_sol: 0.2, risks: [], spoken_line: line },+ signals: SIGNALS, agentName: 'Sage', owner: true, context: owner,+ });+ expect(read.hallucination_guard.ok).toBe(true);+ expect(read.spoken_line).toBe(line);+ });++ it('blocks the action when the kill switch is on', () => {+ const { gate } = validateRead({+ raw: { verdict: 'snipe', conviction: 80, suggested_size_sol: 0.2, spoken_line: 'Looks good.' },+ signals: SIGNALS, agentName: 'Sage', owner: true, context: { ...owner, killSwitch: true },+ });+ expect(gate.can_act).toBe(false);+ expect(gate.reason).toBe('kill_switch');+ });+});++describe('deriveGate', () => {+ it('is not actionable on watch/pass', () => {+ expect(deriveGate({ owner: true, verdict: 'watch', suggestedSize: null, signals: SIGNALS, context: {} }).can_act).toBe(false);+ expect(deriveGate({ owner: true, verdict: 'pass', suggestedSize: null, signals: SIGNALS, context: {} }).reason).toBe('not_actionable');+ });+});++describe('buildReadPrompt', () => {+ it('embeds the signals and forbids inventing numbers', () => {+ const { system, user } = buildReadPrompt({ agentName: 'Sage', persona: 'cautious', network: 'mainnet', signals: SIGNALS, owner: true });+ expect(system).toMatch(/ONLY use the numbers/i);+ expect(user).toContain('"quality_score": 72');+ });+ it('forbids size suggestions for a non-owner', () => {+ const { system } = buildReadPrompt({ agentName: 'Sage', persona: '', network: 'mainnet', signals: SIGNALS, owner: false });+ expect(system).toMatch(/suggested_size_sol" must be null/i);+ });+});++describe('VERDICTS / templatedSpokenLine', () => {+ it('exposes the three verdicts', () => {+ expect(VERDICTS).toEqual(['snipe', 'watch', 'pass']);+ });+ it('produces a grounded fallback line per verdict', () => {+ expect(templatedSpokenLine('snipe', 'Sage', SIGNALS)).toContain('$WIDGET');+ expect(templatedSpokenLine('pass', 'Sage', SIGNALS)).toMatch(/passing/i);+ });+});diff --git a/tests/trader-stats.test.js b/tests/trader-stats.test.jsindex 05ef23c15..79ab36184 100644--- a/tests/trader-stats.test.js+++ b/tests/trader-stats.test.js@@ -150,6 +150,104 @@ describe('computeTraderMetrics — degenerate inputs', () => {});});+describe('computeTraderMetrics — self-dealing exclusion (anti-gaming)', () => {+ // Two honest trades + two fat round-trips on the trader's OWN coins. A faker+ // would pump SELF1/SELF2 and post a 100% win rate; the credited record must not.+ const BOOK = [+ { status: 'closed', mint: 'AAAA', realized_pnl_lamports: String(2 * SOL), realized_pnl_pct: 200,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:00:00Z', closed_at: '2026-01-01T00:02:00Z' },+ { status: 'closed', mint: 'BBBB', realized_pnl_lamports: String(-0.5 * SOL), realized_pnl_pct: -50,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:03:00Z', closed_at: '2026-01-01T00:08:00Z' },+ { status: 'closed', mint: 'SELF1', realized_pnl_lamports: String(10 * SOL), realized_pnl_pct: 1000,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:09:00Z', closed_at: '2026-01-01T00:10:00Z' },+ { status: 'closed', mint: 'SELF2', realized_pnl_lamports: String(5 * SOL), realized_pnl_pct: 500,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:11:00Z', closed_at: '2026-01-01T00:12:00Z' },+ ];+ const selfDealMints = new Set(['SELF1', 'SELF2']);++ it('credits NOTHING from self-dealt coins — score reflects only honest trades', () => {+ const m = computeTraderMetrics(BOOK, { solUsd: 200, selfDealMints });+ expect(m.closed_count).toBe(2); // SELF1/SELF2 split out+ expect(m.wins).toBe(1);+ expect(m.losses).toBe(1);+ expect(m.win_rate).toBe(0.5); // NOT 1.0+ expect(m.realized_pnl_sol).toBeCloseTo(1.5, 6); // 2 − 0.5, the 15 SOL of self-deals excluded+ expect(m.unique_coins).toBe(2);+ });++ it('reports the excluded self-dealing total transparently', () => {+ const m = computeTraderMetrics(BOOK, { solUsd: 200, selfDealMints });+ expect(m.self_dealing_count).toBe(2);+ expect(m.self_dealing_excluded_pnl_sol).toBeCloseTo(15, 6);+ expect(m.self_dealing_excluded_pnl_usd).toBeCloseTo(3000, 2); // 15 × 200+ });++ it('accepts a plain object as well as a Set for selfDealMints', () => {+ const m = computeTraderMetrics(BOOK, { selfDealMints: { SELF1: true, SELF2: true } });+ expect(m.closed_count).toBe(2);+ expect(m.self_dealing_count).toBe(2);+ });++ it('credits every position when no self-deal evidence is supplied (legacy)', () => {+ const m = computeTraderMetrics(BOOK, { solUsd: 200 });+ expect(m.closed_count).toBe(4);+ expect(m.win_rate).toBe(0.75);+ expect(m.realized_pnl_sol).toBeCloseTo(16.5, 6);+ expect(m.self_dealing_count).toBe(0);+ expect(m.self_dealing_excluded_pnl_sol).toBe(0);+ });+});++describe('computeTraderMetrics — snipe hit-rate', () => {+ // Same launch time for A/B/C; D has no proven birth. A & C enter inside the+ // 5-min window (A wins, C loses); B enters 10 min later (not a snipe).+ const LAUNCH = '2026-01-01T00:00:00.000Z';+ const BOOK = [+ { status: 'closed', mint: 'A', realized_pnl_lamports: String(2 * SOL), realized_pnl_pct: 200,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:00:30Z', closed_at: '2026-01-01T00:02:00Z' },+ { status: 'closed', mint: 'B', realized_pnl_lamports: String(1 * SOL), realized_pnl_pct: 100,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:10:00Z', closed_at: '2026-01-01T00:12:00Z' },+ { status: 'closed', mint: 'C', realized_pnl_lamports: String(-0.5 * SOL), realized_pnl_pct: -50,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:01:00Z', closed_at: '2026-01-01T00:03:00Z' },+ { status: 'closed', mint: 'D', realized_pnl_lamports: String(0.3 * SOL), realized_pnl_pct: 30,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:00:10Z', closed_at: '2026-01-01T00:05:00Z' },+ ];+ const mintCreatedAt = { A: LAUNCH, B: LAUNCH, C: LAUNCH }; // D unknown on purpose++ it('counts only entries inside the snipe window, scoped to proven launches', () => {+ const m = computeTraderMetrics(BOOK, { mintCreatedAt });+ expect(m.snipe_sample).toBe(3); // A, B, C have a known birth; D does not+ expect(m.snipe_count).toBe(2); // A and C are inside 5 min; B is 10 min out+ expect(m.snipe_wins).toBe(1); // A won, C lost+ expect(m.snipe_hit_rate).toBe(0.5);+ });++ it('tolerates small negative clock skew between open time and block time', () => {+ const m = computeTraderMetrics(+ [{ status: 'closed', mint: 'A', realized_pnl_lamports: String(1 * SOL), realized_pnl_pct: 100,+ entry_quote_lamports: String(1 * SOL), opened_at: '2025-12-31T23:59:58Z', closed_at: '2026-01-01T00:01:00Z' }],+ { mintCreatedAt: { A: LAUNCH } }, // opened 2s "before" launch+ );+ expect(m.snipe_count).toBe(1);+ expect(m.snipe_hit_rate).toBe(1);+ });++ it('returns a null hit-rate (not a fake zero) when no launch times are known', () => {+ const m = computeTraderMetrics(BOOK, {});+ expect(m.snipe_sample).toBe(0);+ expect(m.snipe_count).toBe(0);+ expect(m.snipe_hit_rate).toBeNull();+ });++ it('excludes self-dealt coins from the snipe sample too', () => {+ const m = computeTraderMetrics(BOOK, { mintCreatedAt, selfDealMints: new Set(['A']) });+ expect(m.snipe_sample).toBe(2); // A removed before snipe accounting+ expect(m.snipe_count).toBe(1); // only C remains in-window+ expect(m.snipe_wins).toBe(0);+ expect(m.snipe_hit_rate).toBe(0);+ });+});+describe('windowStartIso', () => {const NOW = Date.parse('2026-06-15T12:00:00.000Z');diff --git a/tests/trading-compile.test.js b/tests/trading-compile.test.jsnew file mode 100644index 000000000..aac45f09e--- /dev/null+++ b/tests/trading-compile.test.js@@ -0,0 +1,126 @@+import { describe, it, expect } from 'vitest';+import {+ emptyRule,+ normalizeRule,+ validateRule,+ compileRuleToConfig,+ configToSniperStrategy,+ ruleToEnglish,+ LAMPORTS_PER_SOL,+} from '../src/studio/money/trading-compile.js';+import { normalizeStrategyConfig, validateStrategyConfig } from '../api/_lib/strategy-schema.js';++describe('trading-compile: normalizeRule', () => {+ it('fills every block from defaults given an empty input', () => {+ const r = normalizeRule({});+ expect(r.trigger.type).toBe('new_launch');+ expect(r.buy.amount_sol).toBeGreaterThan(0);+ expect(r.exits.stop_loss_pct).toBeGreaterThan(0);+ expect(r.network).toBe('mainnet');+ });++ it('coerces empty strings to null and keeps numbers', () => {+ const r = normalizeRule({ filters: { min_market_cap_usd: '', max_market_cap_usd: 50000 } });+ expect(r.filters.min_market_cap_usd).toBeNull();+ expect(r.filters.max_market_cap_usd).toBe(50000);+ });++ it('never mutates the frozen default template', () => {+ const a = emptyRule();+ a.buy.amount_sol = 99;+ const b = emptyRule();+ expect(b.buy.amount_sol).not.toBe(99);+ });++ it('clamps an unknown network to mainnet and honours devnet', () => {+ expect(normalizeRule({ network: 'bogus' }).network).toBe('mainnet');+ expect(normalizeRule({ network: 'devnet' }).network).toBe('devnet');+ });+});++describe('trading-compile: validateRule', () => {+ it('requires a stop loss', () => {+ const { valid, errors } = validateRule({ exits: { stop_loss_pct: 0, take_profit_pct: 100 } });+ expect(valid).toBe(false);+ expect(errors['exits.stop_loss_pct']).toBeTruthy();+ });++ it('requires at least one upside exit', () => {+ const { valid, errors } = validateRule({+ exits: { stop_loss_pct: 40, take_profit_pct: null, trailing_stop_pct: null, max_hold_minutes: null },+ });+ expect(valid).toBe(false);+ expect(errors.exits).toBeTruthy();+ });++ it('rejects an inverted market-cap range', () => {+ const { valid, errors } = validateRule({+ filters: { min_market_cap_usd: 100000, max_market_cap_usd: 1000 },+ exits: { stop_loss_pct: 40, take_profit_pct: 100 },+ });+ expect(valid).toBe(false);+ expect(errors['filters.max_market_cap_usd']).toBeTruthy();+ });++ it('accepts a sound rule', () => {+ expect(validateRule(emptyRule()).valid).toBe(true);+ });+});++describe('trading-compile: compileRuleToConfig matches the live server schema', () => {+ it('produces a config the server normalizer accepts unchanged in shape', () => {+ const config = compileRuleToConfig(emptyRule());+ // The compiled config must survive the SAME normalizer the live engine runs,+ // with no drift in the gate-relevant fields — so what the UI saves is exactly+ // what the runtime enforces.+ const norm = normalizeStrategyConfig(config);+ expect(norm.entry.trigger).toBe('new_launch');+ expect(norm.sizing.amount_sol).toBe(config.sizing.amount_sol);+ expect(norm.exits.stop_loss_pct).toBe(config.exits.stop_loss_pct);+ expect(norm.entry.max_market_cap_usd).toBe(config.entry.max_market_cap_usd);+ });++ it('compiles a valid config that passes the server validator', () => {+ const config = compileRuleToConfig(emptyRule());+ const { valid } = validateStrategyConfig(config);+ expect(valid).toBe(true);+ });++ it('carries filter values through to the entry block', () => {+ const config = compileRuleToConfig({+ filters: { max_market_cap_usd: 40000, require_socials: true },+ exits: { stop_loss_pct: 30, take_profit_pct: 200 },+ });+ expect(config.entry.max_market_cap_usd).toBe(40000);+ expect(config.entry.require_socials).toBe(true);+ });+});++describe('trading-compile: configToSniperStrategy', () => {+ it('converts SOL sizing to lamports and minutes to seconds', () => {+ const config = compileRuleToConfig({+ buy: { amount_sol: 0.25, max_slippage_bps: 700 },+ exits: { stop_loss_pct: 40, take_profit_pct: 150, max_hold_minutes: 10 },+ });+ const s = configToSniperStrategy(config, { maxPriceImpactPct: 12 });+ expect(s.per_trade_lamports).toBe(String(Math.floor(0.25 * LAMPORTS_PER_SOL)));+ expect(s.slippage_bps).toBe(700);+ expect(s.max_hold_seconds).toBe(600);+ expect(s.max_price_impact_pct).toBe(12);+ expect(s.trigger).toBe('new_mint');+ });++ it('leaves max_hold_seconds null when no max hold is set', () => {+ const s = configToSniperStrategy(compileRuleToConfig(emptyRule()));+ expect(s.max_hold_seconds).toBeNull();+ });+});++describe('trading-compile: ruleToEnglish', () => {+ it('renders a readable, non-hyperbolic sentence', () => {+ const text = ruleToEnglish(emptyRule());+ expect(text).toMatch(/When a new coin appears/);+ expect(text).toMatch(/buy/);+ expect(text).not.toMatch(/guarantee/i);+ });+});diff --git a/vercel.json b/vercel.jsonindex 48976bed3..f1fe722f1 100644--- a/vercel.json+++ b/vercel.json@@ -27,11 +27,7 @@"{api/agents/networth,api/avatars/from-forge}.js": {"maxDuration": 60},- "api/club/tips-stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },- "api/feed-stream.js": {+ "{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream}.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300},@@ -132,22 +128,10 @@"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 120},- "api/pump/trades-stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },"api/pump/launch-og.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 15},- "api/oracle/stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },- "api/oracle/action-stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },"api/oracle/trades.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 60@@ -168,14 +152,6 @@"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 60},- "api/sniper/stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },- "api/sniper/radar-stream.js": {- "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 300- },"api/sniper/history.js": {"maxDuration": 20},@@ -3680,6 +3656,14 @@"src": "/create/prompt/","dest": "/create-prompt.html"},+ {+ "src": "/genesis",+ "dest": "/genesis.html"+ },+ {+ "src": "/genesis/",+ "dest": "/genesis.html"+ },{"src": "/scan","dest": "/scan.html"diff --git a/vite.config.js b/vite.config.jsindex d1019410c..02ef20e57 100644--- a/vite.config.js+++ b/vite.config.js@@ -265,7 +265,8 @@ const appConfig = {chunk.name === 'walk-playground' ||chunk.name === 'feature-tour' ||chunk.name === 'notifications' ||- chunk.name === 'nav-tier-badge'+ chunk.name === 'nav-tier-badge' ||+ chunk.name === 'agent-bus'|| chunk.name === 'i18n'? `${chunk.name}.js`: 'assets/[name]-[hash].js',@@ -273,6 +274,7 @@ const appConfig = {input: {'footer-bot': resolve(__dirname, 'src/footer-bot.js'),'walk-companion': resolve(__dirname, 'src/walk-companion.js'),+ 'agent-bus': resolve(__dirname, 'src/agents/agent-bus.js'),'walk-playground': resolve(__dirname, 'src/walk-playground.js'),'feature-tour': resolve(__dirname, 'src/feature-tour.js'),notifications: resolve(__dirname, 'src/notifications.js'),@@ -318,6 +320,7 @@ const appConfig = {segment: resolve(__dirname, 'pages/segment.html'),'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),'create-prompt': resolve(__dirname, 'pages/create-prompt.html'),+ genesis: resolve(__dirname, 'pages/genesis.html'),'create-character': resolve(__dirname, 'pages/create-character.html'),scan: resolve(__dirname, 'pages/scan.html'),worlds: resolve(__dirname, 'pages/worlds.html'),@@ -530,6 +533,7 @@ const appConfig = {'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),aws: resolve(__dirname, 'pages/aws/index.html'),'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),+ 'autopilot-activity': resolve(__dirname, 'pages/autopilot-activity.html'),support: resolve(__dirname, 'pages/support.html'),// dashboard-next prototype — sub-pages auto-discovered so the parallel// agents that land new pages/dashboard-next/*.html files don't have to@@ -694,6 +698,8 @@ support: resolve(__dirname, 'pages/support.html'),'/create/selfie/': resolve(root, 'pages/create-selfie.html'),'/create/prompt': resolve(root, 'pages/create-prompt.html'),'/create/prompt/': resolve(root, 'pages/create-prompt.html'),+ '/genesis': resolve(root, 'pages/genesis.html'),+ '/genesis/': resolve(root, 'pages/genesis.html'),'/create/character': resolve(root, 'pages/create-character.html'),'/create/character/': resolve(root, 'pages/create-character.html'),'/create/video': resolve(root, 'pages/create/video.html'),@@ -1299,6 +1305,12 @@ support: resolve(__dirname, 'pages/support.html'),req.url = '/src/walk-companion.js';return next();}+ // /agent-bus.js — the Living-Agents nervous system at a stable URL so+ // nav.js can load it on any page for the ?agentbus=1 debug overlay.+ if (path === '/agent-bus.js') {+ req.url = '/src/agents/agent-bus.js';+ return next();+ }// /walk-playground.js — stable URL so any page (not just the nav// companion) can launch the full-page walk playground on demand.if (path === '/walk-playground.js') {