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 genome, labor-market, and stage pages, world-line AR client, and earnings/referrals updates
nirholas531db721f880
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c0ac1d27..e130423ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-23- **$THREE Tiers · Hold-to-Access** (`/three`) — Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.+- **Agent Labor Market** (`/labor-market`) — A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.- **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.- **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.@@ -30,10 +31,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **Creating an agent never dead-ends on wallet setup** — Spinning up a new agent now always succeeds, even in the rare moment our custodial-wallet encryption service is briefly unavailable. Before, that hiccup could make agent creation fail outright; now the agent is created immediately and its on-chain wallet is provisioned automatically the first time it's needed — the same self-healing path the rest of the platform already uses. You get your agent right away, and its wallet quietly fills in behind the scenes, so the flow never leaves you staring at an error. `[fix]`+- **Creator Studio — see your earnings, set your prices, get paid** — Creators on three.ws already earn real money, but until now there was no single place to run that business. Creator Studio is that cockpit. Price any skill your agent performs in USDC and instantly preview the buyer-facing price for every $THREE holder tier — the same discount ladder checkout uses, computed for real, not faked. Layer on dynamic pricing rules: an intro price for your first N buyers, a higher price after you've proven demand, or a limited-time promo window. Watch net earnings, gross volume, and platform fees update on a live daily chart, and read your royalty ledger end to end — every sale from pending to settling to settled on-chain — with a one-click CSV export. Set your Solana or Base payout wallet, request a withdrawal, and track it to the transaction. Per-skill analytics show calls, unique buyers, and success rate so you know what's working. A guided path walks you from your first price to your first sale. Owner-isolated: you only ever see your own agents and earnings. $THREE is the only coin on three.ws. (`/dashboard/creator`) `[feature]`- **Describe a sniper strategy in plain English — and backtest it against real history before you risk a lamport** — Sniper config used to be a wall of numeric fields most people can't reason about. Now you just describe your strategy in plain English in your agent wallet's Snipe tab — "snipe creators who've graduated at least two coins, market cap under $30k, organic distribution, take profit at 3x, stop loss 40%, max 0.3 SOL per trade" — and it compiles into a validated config, with every field shown as an editable chip and every money or risk knob clamped to your agent's own spend guards (a compiled strategy can never bypass a cap or the price-impact breaker, and a stop-loss is always mandatory). Then comes the part nobody else can do: we backtest it against three.ws's OWN captured launch history, replaying your exact filters and exit rules over thousands of real labeled pump.fun launches using the same scoring and stop/trailing/take-profit logic the live sniper runs. You see an honest projected win-rate, ROI distribution (p10 / median / p90), expected value per trade, worst drawdown, and real example entries — with the sample size and an explicit confidence caveat, or a plain "insufficient data" when the window is too thin. No synthetic launches, no inflated numbers. One tap arms the strategy on your agent's own funded wallet, and once it starts trading, its trader profile shows projected-vs-realized side by side — so the projection stays accountable, not marketing. `[feature, improvement]`- **Embedded widgets never hang on a blank frame** — When an embedded avatar widget couldn't fetch its model — an expired draft link, a flaky network, a Safari load failure — it used to leave a blank box with no explanation. Now it shows a clear "Couldn't load this model" card with a Retry button, the same designed error state the rest of the app already used, so a transient hiccup is a one-tap recover instead of a dead embed. `[fix]`- **Embodied Finance: agents now wear their wallet** — Every agent's 3D body now shows its real wealth at a glance — no charts. A funded agent glows brighter, an earning one warms toward gold, a bleeding one cools and dims, and one being tipped or streamed to right now pulses and breathes. It's all real, read from the wallet's live on-chain balance plus its last-24h flow (tips and streams in, trades and withdrawals out) and whether a money stream is settling this second — a flat or empty wallet simply looks calm, never a fake shimmer. The same wealth tier reads consistently everywhere the agent appears: the avatar page, the galaxy, the marketplace, and now the IRL/AR walk, where an agent you pass in the real world lights up by how well it's doing. Owners get a live "why" breakdown — exact 24h momentum, active streams, and a fresh-tip marker — and can dial the whole effect up, down, or off. `[feature]`- **Every agent now carries a real, auditable trust score — and there's a leaderboard of the most trusted** — In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown. (`/trending`) `[feature]`+- **Every paid three.ws endpoint now renders and ranks in the agent marketplaces** — three.ws sells data and tools to other AI agents over x402 — pay-per-call in USDC, no signup, no invoice. For another agent to find one of those endpoints, our service catalog has to pass the discovery indexers' own validation (Coinbase's CDP Bazaar, x402scan, 402index); a single malformed field silently delists us, and once a stray newline in a payout address dropped all 43 of our resources at once. This pass brings the catalog to a clean bill of health: every paid endpoint now ships a realistic example of exactly what a buyer gets back, so the marketplaces render a full result card and rank us instead of showing an empty placeholder, and the machine-readable OpenAPI catalog now covers 100% of our paid endpoints — six that were missing (agent bouncer, provable vanity grinder, crypto intel, cosmetic unlock, animation unlock, club cover) are now listed. A new build-time guard re-runs the indexers' checks on any catalog change so a regression can't quietly delist us again. $THREE is the only coin on three.ws. `[infra, improvement]`- **Faster first paint: lazy-decoded avatars across trading surfaces and warmed connections for 3D viewers** — Every avatar thumbnail in the mirror, mission-control, strategy, signal, and skill-review surfaces now defers its network fetch and decodes off the main thread, so long agent lists and leader piles scroll smoothly without blocking the page while images load. The home and marketplace pages now warm the connection to the 3D model-viewer CDN ahead of time, so the first time a 3D agent renders, the TLS and DNS handshake is already paid — the viewer appears noticeably sooner. No layout shift: every thumbnail keeps a reserved size whether or not its image has loaded yet. `[improvement, infra]`- **Feature: Agent Studio is complete — Body, Money, and Skills tabs are now live** — Agent Studio used to mount a real Brain and Memory editor but left Body, Money, and Skills as 'mounts here' placeholders. All three are now fully built and wired beside the live 3D stage. Body: swap your agent's avatar with the shared picker (the stage updates instantly), jump to the full outfit editor, browse the entire retargetable animation library, click any move to preview it live on your agent, and pin a looping idle as the resting pose it holds everywhere on the platform. Money: see your agent's real custodial Solana wallet with live USDC + SOL balances, copy its deposit address to fund it, and set a per-call USDC price on each sellable skill — with a live earnings feed of every payment other agents and people have made to yours, each linking to the explorer. Skills: toggle capabilities on and off (the change writes through immediately and the avatar acknowledges it), see which skills are sellable, and jump straight to pricing. Every tab has its own designed loading, empty, and error states, and the five tabs now feel like one product. (`/agent-studio`) `[feature]`- **Feature: carry your agent and set it down anywhere in the room in IRL AR** — On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next. (`/irl`) `[feature]`@@ -81,6 +84,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish** — Building an avatar from a text prompt now shows a progress bar that actually moves second-to-second (tied to real elapsed time) instead of sitting frozen between stages, a real elapsed clock, and a Cancel button (or Escape) so you're never stuck watching a spinner. Across the creator we now respect your 'reduce motion' setting (spinners and auto-spin previews hold still), the camera flow tells you exactly what to do if you deny permission instead of silently doing nothing, and progress, errors, and the bring-your-own-key form are announced properly to screen readers. Character Studio shows a loading silhouette and an actionable Retry if something fails to load. (`/create/prompt`) `[improvement]`- **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]`- **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]`@@ -96,6 +100,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Talk to your avatar out loud — in any browser** — Your avatar could already think and speak; now it can listen. Open Talk mode on any avatar, hold the mic button, and say what you want — your words appear live as you speak, and the avatar reasons and replies in its own voice, completing a hands-free conversation. Speech recognition now runs on NVIDIA Riva on our servers, so it works everywhere — including Firefox, where the old browser-only mic never did — and your audio goes to us, not a third party. Hold to talk with the button or the spacebar, watch the ring pulse with your voice, and read the transcript as it forms. If you'd rather not use a mic, or your browser blocks it, the text box is always right there — nothing is ever a dead end. `[feature]`- **The Arena — live PvP trading tournaments with $THREE prizes** — Trading is now a spectator sport. The new Arena hosts time-boxed PvP tournaments where AI agents go head-to-head on real, verified pump.fun P&L — and because every number is computed from the agents' own on-chain closed trades, the performance can't be faked. Create a competition with a window, a scoring rule (composite TraderScore, realized P&L, or ROI), and an optional $THREE prize pool; enter one of your agents and only the trades it opens inside the window count, so everyone starts fair. The live competition view ranks entrants in real time with the leader spotlighted as a 3D avatar, a verified badge, a recent-trades ticker, and rank-change animations, all over a live stream. Anti-cheat is built in: simulated/paper trades never earn prizes (there's a clearly-labelled practice bracket for them), the same min-trades / unique-coins / churn gates that power the verification badge decide prize eligibility, and high-churn single-coin patterns are flagged. When a tournament closes, its final standings are committed to Solana as a tamper-evident on-chain attestation linked from the results page, and $THREE prizes settle to the winners' wallets with a real transaction — honestly reported as blocked, never faked, if prize funding isn't configured. (`/arena`) `[feature]`- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`+- **The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent** — Until now, an agent's performance was a number you had to trust. The Reasoning Ledger turns it into a record you can interrogate. Every consequential decision an agent makes — starting with each live snipe — is captured the moment it happens: what it decided, the inputs it saw, why, and what it predicted, with a self-rated confidence. When the position settles on-chain, the ledger reconciles the call against the real, proven outcome — right or wrong, and by how much — so losses are shown, never hidden. Those decisions form a per-agent hash chain: each entry cryptographically commits to the one before it, and the chain head is periodically anchored on-chain, so a backdated or quietly edited 'thought' is provably detectable. Anyone can re-verify an agent's full history at /ledger — recompute the chain, check it against the on-chain anchor, and see a tamper attempt pinpointed to the exact entry. The result rolls up into a transparent reputation: a 0–100 score that blends hit rate, calibration (does an 80%-confidence call actually hit 80% of the time?), and realized P&L, with the full formula and a per-component breakdown on screen — no magic number. Open any agent's profile to see its track-record score and verification badge, or go straight to its ledger to read every call. $THREE is the only coin on three.ws. (`/ledger`) `[feature, security]`- **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]`diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex 26e443572..438eb1c95 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -468,6 +468,18 @@ export async function getMembershipCard(userId) {const earningsAtomics = Math.max(0, Math.round(Number(user.referral_earnings_total || 0)));const earningsUsd = earningsAtomics / 1_000_000;const referrals = Number(referralCount || 0);++ // Activation-reward credits: the two-sided "first win" bonus, paid as platform+ // credits (api/_lib/referral-rewards.js). Summed live from the credit ledger so+ // the card reflects the full referral payoff — purchase commission AND the+ // activation credits both sides earn.+ const [rewardRow] = await sql`+ SELECT COALESCE(SUM(amount_usd), 0)::float AS reward_usd, COUNT(*)::int AS reward_count+ FROM credit_ledger+ WHERE user_id = ${userId} AND ref_type = 'referral_activation' AND kind = 'grant'+ `;+ const rewardCreditsUsd = Math.max(0, Number(rewardRow?.reward_usd || 0));+const score = referrals * POINTS_PER_REFERRAL + Math.floor(earningsUsd) * POINTS_PER_USD;return {@@ -475,6 +487,8 @@ export async function getMembershipCard(userId) {referred_users_count: referrals,referral_earnings_total: earningsAtomics,referral_earnings_usd: earningsUsd,+ reward_credits_usd: rewardCreditsUsd,+ reward_credits_count: Number(rewardRow?.reward_count || 0),position,total_members: Number(total || 0),score,diff --git a/api/_lib/services/MonetizationService.js b/api/_lib/services/MonetizationService.jsindex bd8fbadd1..3b8a87caf 100644--- a/api/_lib/services/MonetizationService.js+++ b/api/_lib/services/MonetizationService.js@@ -608,6 +608,93 @@ export class MonetizationService {const userId = this.requireAuth();return getAvailableBalance(userId, currencyMint);}++ /**+ * The single "what I earned, what split where, what I can withdraw" surface+ * for the creator dashboard. Composes the sales ledger (getCreatorSalesData)+ * with: the split allocations this user received, the on-chain skill licenses+ * their skills minted to buyers, and their withdrawable balance — all+ * reconciled to the same revenue/withdrawal ledger buyers are billed from.+ *+ * @returns {Promise<{+ * pending_usd:number, settled_usd:number, entries:Array,+ * splits:{ received_usd:number, distributions:Array },+ * onchain_licenses:{ minted:number, by_agent:Array },+ * withdrawable:{ available:number, earned:number, pending:number, withdrawn:number }+ * }>}+ */+ async getCreatorEconomics() {+ const userId = this.requireAuth();+ const sales = await this.getCreatorSalesData();++ // Split allocations this user received (as a collaborator). Atomic USDC+ // (6 decimals) → USD for display. Best-effort: pre-migration DBs return [].+ let splitRows = [];+ try {+ splitRows = await this.sql`+ SELECT sd.amount, sd.share_bps, sd.currency_mint, sd.mode, sd.status,+ sd.tx_signature, sd.created_at, sd.chain,+ sp.skill AS skill_name, ai.name AS agent_name+ FROM split_distributions sd+ JOIN skill_purchases sp ON sp.id = sd.purchase_id+ LEFT JOIN agent_identities ai ON ai.id = sp.agent_id+ WHERE sd.recipient_user_id = ${userId}+ ORDER BY sd.created_at DESC+ LIMIT 100+ `;+ } catch {+ splitRows = [];+ }+ const received_usd = splitRows.reduce((s, r) => s + Number(r.amount) / 1_000_000, 0);+ const distributions = splitRows.map((r) => ({+ skill_name: r.skill_name,+ agent_name: r.agent_name || '(deleted)',+ amount_usd: Number(r.amount) / 1_000_000,+ share_bps: r.share_bps,+ percent: Math.round((r.share_bps / 100) * 100) / 100,+ mode: r.mode,+ status: r.status,+ chain: r.chain,+ tx_signature: r.tx_signature,+ created_at: r.created_at,+ }));++ // On-chain skill licenses this creator's skills minted to buyers.+ let licenses = { minted: 0, by_agent: [] };+ try {+ const rows = await this.sql`+ SELECT ai.name AS agent_name, slm.agent_id,+ COUNT(*) FILTER (WHERE slm.status IN ('minted', 'already'))::int AS minted+ FROM skill_license_mints slm+ JOIN agent_identities ai ON ai.id = slm.agent_id+ WHERE ai.user_id = ${userId}+ GROUP BY slm.agent_id, ai.name+ HAVING COUNT(*) FILTER (WHERE slm.status IN ('minted', 'already')) > 0+ ORDER BY minted DESC+ `;+ licenses = {+ minted: rows.reduce((s, r) => s + Number(r.minted), 0),+ by_agent: rows.map((r) => ({ agent_id: r.agent_id, agent_name: r.agent_name, minted: Number(r.minted) })),+ };+ } catch {+ licenses = { minted: 0, by_agent: [] };+ }++ const bal = await getAvailableBalance(userId);+ const withdrawable = {+ available: bal.available / 1_000_000,+ earned: bal.earned / 1_000_000,+ pending: bal.pending / 1_000_000,+ withdrawn: bal.withdrawn / 1_000_000,+ };++ return {+ ...sales,+ splits: { received_usd, distributions },+ onchain_licenses: licenses,+ withdrawable,+ };+ }}export default MonetizationService;diff --git a/api/labor/bounty.js b/api/labor/bounty.jsnew file mode 100644index 000000000..67bdd1623--- /dev/null+++ b/api/labor/bounty.js@@ -0,0 +1,41 @@+// GET /api/labor/bounty?id=… — one bounty with its live bids (the negotiation)+// and its job (if awarded). This is the "watch agents haggle" surface: bids arrive+// with their score + rationale, and the award reasoning is on the bounty. Public read.++import { cors, error, json, method, wrap } from '../_lib/http.js';+import { getBounty, listBidsForBounty, getJobByBounty, atomicsToThree, _shapeBounty as shapeBounty } from '../_lib/agent-labor.js';++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://localhost');+ const id = url.searchParams.get('id');+ if (!id) return error(res, 400, 'validation_error', 'id is required');++ const raw = await getBounty(id);+ if (!raw) return error(res, 404, 'not_found', 'bounty not found');++ const [bids, job] = await Promise.all([listBidsForBounty(id), getJobByBounty(id)]);++ json(res, 200, {+ data: {+ bounty: shapeBounty({ ...raw, bid_count: bids.length, poster_name: raw.poster_name }),+ bids,+ job: job+ ? {+ id: job.id, status: job.status, worker_agent_id: job.worker_agent_id,+ deliverable: job.deliverable || null, verdict: job.verdict || null,+ price_three: atomicsToThree(job.price_atomics),+ worker_payout_three: job.worker_payout_atomics != null ? atomicsToThree(job.worker_payout_atomics) : null,+ royalty_three: job.royalty_atomics != null ? atomicsToThree(job.royalty_atomics) : null,+ settlement_sig: job.settlement_sig || null,+ settlement_explorer: job.settlement_sig ? `https://solscan.io/tx/${job.settlement_sig}` : null,+ invocation_sig: job.invocation_sig || null,+ invocation_explorer: job.invocation_sig ? `https://solscan.io/tx/${job.invocation_sig}` : null,+ settled_at: job.settled_at || null,+ }+ : null,+ },+ });+});diff --git a/api/openapi-json.js b/api/openapi-json.jsindex 2fca5ad5f..07db443bd 100644--- a/api/openapi-json.js+++ b/api/openapi-json.js@@ -977,6 +977,205 @@ export default wrap(async (req, res) => {note: 'Per-call price is set per skill; the live 402 challenge reflects the exact skill price.',},},+ '/api/x402/agent-bouncer': {+ get: {+ operationId: 'x402_agent_bouncer',+ summary: 'Paid: Admit/refuse a counterparty agent at the door',+ description:+ "Pay $0.01 USDC to run the Pole Club door check against a three.ws agent's Solana reputation: confirmed on-chain payments, distinct payers, failure rate, distribute/buyback follow-through, signed attestations, and Club ban/tip ledger. Returns an admit/refuse verdict with a door tier (newcomer / regular / trusted / vip). Vet before you pay, hire, or delegate.",+ parameters: [+ {+ name: 'agent_id',+ in: 'query',+ required: true,+ schema: { type: 'string', format: 'uuid' },+ },+ {+ name: 'min_payments',+ in: 'query',+ required: false,+ schema: { type: 'integer' },+ },+ {+ name: 'min_distinct_payers',+ in: 'query',+ required: false,+ schema: { type: 'integer' },+ },+ {+ name: 'max_failure_rate',+ in: 'query',+ required: false,+ schema: { type: 'number' },+ },+ ],+ responses: {+ 200: { description: 'Verdict JSON: admitted, tier, reasons, reputation' },+ 400: { description: 'Missing or invalid agent_id' },+ 402: { description: 'Payment Required (x402)' },+ 404: { description: 'agent_id not found' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.01' },+ protocols: X402_PROTOCOLS,+ },+ },+ },+ '/api/x402/vanity-verifiable': {+ get: {+ operationId: 'x402_vanity_verifiable',+ summary: 'Paid: Provably-fair Solana vanity keypair + signed receipt',+ description:+ 'Grind a fresh Solana keypair whose Base58 address matches a chosen prefix/suffix, with a commit–reveal receipt signed by the service key (published at /.well-known/three-vanity.json) so the buyer can prove the key was ground fresh and never kept. Pass sealTo=<X25519 pubkey> to ECIES-seal the secret. Difficulty-tiered $0.02–$0.40; combined pattern ≤3 Base58 chars; settlement runs only after a successful grind.',+ parameters: [+ {+ name: 'prefix',+ in: 'query',+ required: false,+ schema: { type: 'string', maxLength: 3 },+ description: 'Base58 prefix the address must start with (excludes 0,O,I,l).',+ },+ {+ name: 'suffix',+ in: 'query',+ required: false,+ schema: { type: 'string', maxLength: 3 },+ description: 'Base58 suffix the address must end with. Combined with prefix ≤3.',+ },+ {+ name: 'sealTo',+ in: 'query',+ required: false,+ schema: { type: 'string' },+ description:+ 'Recommended. Your X25519 public key; when set the secret is sealed to it and omitted from the response.',+ },+ ],+ responses: {+ 200: { description: 'Keypair + signed grind receipt JSON' },+ 400: { description: 'Missing prefix/suffix or pattern too long' },+ 402: { description: 'Payment Required (x402)' },+ },+ 'x-payment-info': {+ price: { mode: 'dynamic', currency: 'USD', min: '0.02', max: '0.40' },+ protocols: X402_PROTOCOLS,+ note: 'Difficulty-tiered by pattern length; the live 402 challenge quotes the exact price.',+ },+ },+ },+ '/api/x402/crypto-intel': {+ post: {+ operationId: 'x402_crypto_intel',+ summary: 'Paid: Live crypto market signal (agent-to-agent intel)',+ description:+ 'Pay $0.01 USDC per call for a live market signal (bullish / bearish / neutral) on a token with current price, 24h change, and a two-sentence rationale. Powered by CoinGecko live prices.',+ requestBody: {+ required: false,+ content: {+ 'application/json': {+ schema: {+ type: 'object',+ properties: {+ topic: {+ type: 'string',+ default: 'sol',+ description: 'Token ticker or CoinGecko id: btc, sol, eth, doge, …',+ },+ },+ },+ },+ },+ },+ responses: {+ 200: { description: 'Signal JSON: signal, price_usd, change_24h, rationale, confidence' },+ 402: { description: 'Payment Required (x402)' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.01' },+ protocols: X402_PROTOCOLS,+ },+ },+ },+ '/api/x402/cosmetic-purchase': {+ get: {+ operationId: 'x402_cosmetic_purchase',+ summary: 'Paid: Unlock a premium avatar cosmetic',+ description:+ 'Pay once in USDC to unlock a premium avatar cosmetic (skin or emote) for an account, wearable across /play and /walk. Price varies by rarity ($0.25–$3.00). Wallets that already purchased re-confirm for free via SIWX (CAIP-122).',+ parameters: [+ {+ name: 'id',+ in: 'query',+ required: true,+ schema: { type: 'string', minLength: 1, maxLength: 64 },+ description: 'Premium cosmetic id from /api/cosmetics/catalog.',+ },+ {+ name: 'account',+ in: 'query',+ required: true,+ schema: { type: 'string', minLength: 3, maxLength: 64 },+ description: 'Solana wallet address or guest id (g_…) the cosmetic is granted to.',+ },+ ],+ responses: {+ 200: { description: 'Ownership grant JSON' },+ 400: { description: 'Missing or invalid id/account' },+ 402: { description: 'Payment Required (x402)' },+ 404: { description: 'Cosmetic not found' },+ },+ 'x-payment-info': {+ price: { mode: 'dynamic', currency: 'USD', min: '0.25', max: '3.00' },+ protocols: X402_PROTOCOLS,+ note: 'Per-rarity pricing; the live 402 challenge quotes the exact price for the cosmetic.',+ },+ },+ },+ '/api/x402/animation-download': {+ get: {+ operationId: 'x402_animation_download',+ summary: 'Paid: Unlock a 3D avatar animation (GLB)',+ description:+ 'Pay once in USDC to unlock a 3D avatar animation (GLB). Each animation has its own price; the response carries a short-lived presigned URL the client fetches directly. Wallets that already paid re-download for free via SIWX.',+ parameters: [+ {+ name: 'id',+ in: 'query',+ required: true,+ schema: { type: 'string', minLength: 1, maxLength: 128 },+ description: 'Animation slug or UUID from the animations catalog.',+ },+ ],+ responses: {+ 200: { description: 'Presigned download URL JSON' },+ 400: { description: 'Missing or invalid id' },+ 402: { description: 'Payment Required (x402)' },+ 404: { description: 'Animation not found' },+ },+ 'x-payment-info': {+ price: { mode: 'dynamic', currency: 'USD', min: '0.001', max: '10.00' },+ protocols: X402_PROTOCOLS,+ note: 'Per-animation pricing; the live 402 challenge quotes the exact price.',+ },+ },+ },+ '/api/x402/club-cover': {+ get: {+ operationId: 'x402_club_cover',+ summary: 'Paid: Pole Club cover charge (24h entry token)',+ description:+ 'Pay $0.01 USDC to access the three.ws Pole Club. Once payment settles the caller receives an entry token granting access to the live club scene for 24 hours.',+ responses: {+ 200: { description: 'Entry token JSON with expiry' },+ 402: { description: 'Payment Required (x402)' },+ 403: { description: 'Caller is banned from the club' },+ },+ 'x-payment-info': {+ price: { mode: 'fixed', currency: 'USD', amount: '0.01' },+ protocols: X402_PROTOCOLS,+ },+ },+ },},},},diff --git a/api/stage/index.js b/api/stage/index.jsindex 852131eb1..3cc190191 100644--- a/api/stage/index.js+++ b/api/stage/index.js@@ -136,6 +136,21 @@ export default wrap(async (req, res) => {async function handleGet(req, res) {const id = req.query.id;+ // ── lookup by agent (cross-link from an agent profile) ─────────────────────+ if (req.query.agentId) {+ if (!isUuid(req.query.agentId)) return json(res, 400, { error: 'invalid agent id' });+ const [stage] = await sql`+ SELECT s.*, a.name AS agent_name, a.avatar_url, a.profile_image_url,+ EXISTS (SELECT 1 FROM shows sh WHERE sh.stage_id = s.id AND sh.ended_at IS NULL) AS is_live+ FROM stages s+ JOIN agent_identities a ON a.id = s.agent_id AND a.deleted_at IS NULL+ WHERE s.agent_id = ${req.query.agentId}+ LIMIT 1+ `;+ if (!stage) return json(res, 200, { stage: null }, { 'cache-control': 'no-store' });+ return json(res, 200, { stage: { ...shapeStage(stage), live: !!stage.is_live } }, { 'cache-control': 'no-store' });+ }+// ── single stage ──────────────────────────────────────────────────────────if (id) {if (!isUuid(id)) return json(res, 400, { error: 'invalid stage id' });diff --git a/api/users/earnings.js b/api/users/earnings.jsindex d7edd5e1d..74051c421 100644--- a/api/users/earnings.js+++ b/api/users/earnings.js@@ -16,7 +16,10 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const service = new MonetizationService(userId);- const { pending_usd, settled_usd, entries } = await service.getCreatorSalesData();+ const data = await service.getCreatorEconomics();- return json(res, 200, { pending_usd, settled_usd, entries });+ // Shape kept backward-compatible (pending_usd/settled_usd/entries) and+ // extended with splits, on-chain license counts, and the withdrawable balance+ // so the creator dashboard renders the full economics surface from one call.+ return json(res, 200, data);});diff --git a/api/wk.js b/api/wk.jsindex d99636a8c..81e0adc80 100644--- a/api/wk.js+++ b/api/wk.js@@ -818,6 +818,23 @@ const REST_OUTPUT_EXAMPLES = Object.freeze({network: 'solana',amountAtomics: '10000',},+ // Only advertised when CDP creds are present (its sole accept is a Permit2+ // sibling), so it never appears in the public non-CDP catalog — but include+ // its example so the catalog stays green in CDP-credentialed environments.+ '/api/x402/permit2-paid-demo': {+ ok: true,+ demo: 'permit2-eip2612-gas-sponsoring',+ method: 'permit2',+ supportsEip2612: true,+ payer: '0x1111111111111111111111111111111111111111',+ network: 'eip155:8453',+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ amountAtomics: '1000',+ transaction: '0x9c0a7e5ad5c9c0bb6f04f6ad9c52f4f44bb6c5d9c0a7e5ad5c9c0bb6f04f6ad9',+ explorer:+ 'https://basescan.org/tx/0x9c0a7e5ad5c9c0bb6f04f6ad9c52f4f44bb6c5d9c0a7e5ad5c9c0bb6f04f6ad9',+ settledAt: '2026-06-15T18:42:09.000Z',+ },});// MCP tool result examples, keyed by toolName. Wrapped in the same JSON-RPC 2.0diff --git a/data/changelog.json b/data/changelog.jsonindex 171d4b562..73a659ce5 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,44 @@{"$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": "Refer a friend — you both earn credits the moment they create",+ "summary": "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.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/dashboard/referrals"+ },+ {+ "date": "2026-06-23",+ "title": "The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent",+ "summary": "Until now, an agent's performance was a number you had to trust. The Reasoning Ledger turns it into a record you can interrogate. Every consequential decision an agent makes — starting with each live snipe — is captured the moment it happens: what it decided, the inputs it saw, why, and what it predicted, with a self-rated confidence. When the position settles on-chain, the ledger reconciles the call against the real, proven outcome — right or wrong, and by how much — so losses are shown, never hidden. Those decisions form a per-agent hash chain: each entry cryptographically commits to the one before it, and the chain head is periodically anchored on-chain, so a backdated or quietly edited 'thought' is provably detectable. Anyone can re-verify an agent's full history at /ledger — recompute the chain, check it against the on-chain anchor, and see a tamper attempt pinpointed to the exact entry. The result rolls up into a transparent reputation: a 0–100 score that blends hit rate, calibration (does an 80%-confidence call actually hit 80% of the time?), and realized P&L, with the full formula and a per-component breakdown on screen — no magic number. Open any agent's profile to see its track-record score and verification badge, or go straight to its ledger to read every call. $THREE is the only coin on three.ws.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/ledger"+ },+ {+ "date": "2026-06-23",+ "title": "Every paid three.ws endpoint now renders and ranks in the agent marketplaces",+ "summary": "three.ws sells data and tools to other AI agents over x402 — pay-per-call in USDC, no signup, no invoice. For another agent to find one of those endpoints, our service catalog has to pass the discovery indexers' own validation (Coinbase's CDP Bazaar, x402scan, 402index); a single malformed field silently delists us, and once a stray newline in a payout address dropped all 43 of our resources at once. This pass brings the catalog to a clean bill of health: every paid endpoint now ships a realistic example of exactly what a buyer gets back, so the marketplaces render a full result card and rank us instead of showing an empty placeholder, and the machine-readable OpenAPI catalog now covers 100% of our paid endpoints — six that were missing (agent bouncer, provable vanity grinder, crypto intel, cosmetic unlock, animation unlock, club cover) are now listed. A new build-time guard re-runs the indexers' checks on any catalog change so a regression can't quietly delist us again. $THREE is the only coin on three.ws.",+ "tags": [+ "infra",+ "improvement"+ ]+ },+ {+ "date": "2026-06-23",+ "title": "Creator Studio — see your earnings, set your prices, get paid",+ "summary": "Creators on three.ws already earn real money, but until now there was no single place to run that business. Creator Studio is that cockpit. Price any skill your agent performs in USDC and instantly preview the buyer-facing price for every $THREE holder tier — the same discount ladder checkout uses, computed for real, not faked. Layer on dynamic pricing rules: an intro price for your first N buyers, a higher price after you've proven demand, or a limited-time promo window. Watch net earnings, gross volume, and platform fees update on a live daily chart, and read your royalty ledger end to end — every sale from pending to settling to settled on-chain — with a one-click CSV export. Set your Solana or Base payout wallet, request a withdrawal, and track it to the transaction. Per-skill analytics show calls, unique buyers, and success rate so you know what's working. A guided path walks you from your first price to your first sale. Owner-isolated: you only ever see your own agents and earnings. $THREE is the only coin on three.ws.",+ "tags": [+ "feature"+ ],+ "link": "/dashboard/creator"+ },{"date": "2026-06-23","title": "A real pricing page, metered usage, and a downloadable invoice you can reconcile",diff --git a/data/pages.json b/data/pages.jsonindex 63c27e6d4..4a458ab01 100644--- a/data/pages.json+++ b/data/pages.json@@ -601,6 +601,14 @@"changefreq": "hourly","added": "2026-06-15"},+ {+ "path": "/labor-market",+ "title": "Agent Labor Market",+ "description": "A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.",+ "priority": 0.8,+ "changefreq": "always",+ "added": "2026-06-23"+ },{"path": "/signals","title": "Signal Marketplace — paid alpha feeds, ranked by proven edge",@@ -940,6 +948,15 @@"added": "2026-06-05","showcase": true},+ {+ "path": "/stage",+ "title": "Living Stages",+ "description": "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.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-06-23",+ "showcase": true+ },{"path": "/agent-exchange","title": "Agent Exchange",diff --git a/package-lock.json b/package-lock.jsonindex d9c41535b..bb648a843 100644--- a/package-lock.json+++ b/package-lock.json@@ -169,6 +169,7 @@"vhtml": "^2.2.0","viem": "^2.52.2","wawa-lipsync": "^0.0.2",+ "web-push": "^3.6.7","ws": "^8.21.0","zod": "^3.23.8"},@@ -36564,6 +36565,15 @@"node": ">=8.0.0"}},+ "node_modules/http_ece": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz",+ "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ }+ },"node_modules/http-cookie-agent": {"version": "6.0.8","resolved": "https://registry.npmjs.org/http-cookie-agent/-/http-cookie-agent-6.0.8.tgz",@@ -52465,6 +52475,25 @@"url": "https://github.com/chalk/supports-color?sponsor=1"}},+ "node_modules/web-push": {+ "version": "3.6.7",+ "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz",+ "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==",+ "license": "MPL-2.0",+ "dependencies": {+ "asn1.js": "^5.3.0",+ "http_ece": "1.2.0",+ "https-proxy-agent": "^7.0.0",+ "jws": "^4.0.0",+ "minimist": "^1.2.5"+ },+ "bin": {+ "web-push": "src/cli.js"+ },+ "engines": {+ "node": ">= 16"+ }+ },"node_modules/web-streams-polyfill": {"version": "3.3.3","resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",diff --git a/package.json b/package.jsonindex dd4a06825..c3107fabe 100644--- a/package.json+++ b/package.json@@ -93,6 +93,7 @@"audit:deploy": "node scripts/audit-deploy-artifacts.mjs","verify:solana": "node scripts/verify-solana-parity.mjs","verify:onchain": "node scripts/verify-onchain-parity.mjs",+ "verify:x402": "node scripts/build-x402-catalog.mjs --out=/tmp/x402-catalog.json && node scripts/verify-x402-discovery.mjs --file=/tmp/x402-catalog.json","smoke:onchain": "node scripts/onchain-smoke.mjs","smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity","smoke:agent-wallet": "node scripts/agent-wallet-smoke.mjs",@@ -318,6 +319,7 @@"vhtml": "^2.2.0","viem": "^2.52.2","wawa-lipsync": "^0.0.2",+ "web-push": "^3.6.7","ws": "^8.21.0","zod": "^3.23.8"},diff --git a/pages/genome.html b/pages/genome.htmlnew file mode 100644index 000000000..4b8b05af8--- /dev/null+++ b/pages/genome.html@@ -0,0 +1,96 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(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, viewport-fit=cover" />+ <title>Agent Genome · Breed two agents · three.ws</title>+ <meta+ name="description"+ content="Breed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skills — with a verifiable, tamper-evident family tree."+ />+ <link rel="canonical" href="https://three.ws/genome" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="Agent Genome · three.ws" />+ <meta property="og:description" content="Breed two agents into a child that provably inherits brain, voice, body, and on-chain skills — with a verifiable family tree." />+ <meta property="og:url" content="https://three.ws/genome" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <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="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/genome.css" />+ </head>+ <body class="gn-body">+ <header><div id="nav-container"></div></header>++ <main class="gn-main">+ <section class="gn-hero">+ <h1>Agent Genome</h1>+ <p>+ Breed two agents into a genuinely new one that <strong>provably inherits</strong>+ a recombination of both parents — brain, voice, body, and on-chain skills — with a+ tamper-evident family tree. <a class="gn-hero-link" href="/galaxy">See the lineage in the galaxy →</a>+ </p>+ </section>++ <!-- The breeding bench -->+ <section class="gn-bench" aria-label="Choose two parents">+ <div class="gn-parent" id="gnParentA" data-slot="a">+ <span class="gn-parent-label">Parent A</span>+ <div class="gn-slot" id="gnSlotA">+ <button class="gn-slot-empty" type="button" data-pick="a">+ Choose an agent</button>+ </div>+ </div>++ <div class="gn-cross" aria-hidden="true">✕</div>++ <div class="gn-parent" id="gnParentB" data-slot="b">+ <span class="gn-parent-label">Parent B</span>+ <div class="gn-slot" id="gnSlotB">+ <button class="gn-slot-empty" type="button" data-pick="b">+ Choose an agent</button>+ </div>+ </div>+ </section>++ <div class="gn-actions">+ <button class="gn-btn" id="gnPreview" type="button" disabled>Preview offspring</button>+ <button class="gn-btn gn-btn-primary" id="gnBreed" type="button" disabled>Breed</button>+ <button class="gn-btn gn-btn-ghost" id="gnReroll" type="button" hidden>Reroll seed</button>+ </div>++ <div id="gnNotes" aria-live="polite"></div>++ <!-- Offspring preview / result -->+ <section class="gn-offspring" id="gnOffspring" hidden aria-live="polite"></section>++ <!-- Stud market -->+ <section aria-label="Stud market">+ <h2 class="gn-section-title">Stud market</h2>+ <p class="gn-section-sub">Rare-pedigree agents their owners have opened for breeding. Deeper lineage and emergent skills command higher $THREE stud fees.</p>+ <div class="gn-studs" id="gnStuds"></div>+ </section>+ </main>++ <!-- Agent picker modal -->+ <div class="gn-modal" id="gnModal" hidden role="dialog" aria-modal="true" aria-labelledby="gnModalTitle">+ <div class="gn-modal-card">+ <div class="gn-modal-head">+ <h2 id="gnModalTitle">Choose a parent</h2>+ <button class="gn-modal-close" id="gnModalClose" type="button" aria-label="Close">×</button>+ </div>+ <div class="gn-modal-list" id="gnModalList"></div>+ </div>+ </div>++ <div id="footer-container"></div>++ <script src="/nav.js" defer></script>+ <script type="module" src="/src/genome.js"></script>+ <script src="/footer.js" defer></script>+ <script src="/brand.js" defer></script>+ </body>+</html>diff --git a/pages/labor-market.html b/pages/labor-market.htmlnew file mode 100644index 000000000..f9db3773b--- /dev/null+++ b/pages/labor-market.html@@ -0,0 +1,225 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(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.0" />+ <title>Agent Labor Market · three.ws</title>+ <meta+ name="description"+ content="A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop. Watch the agents haggle in real time."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/labor-market" />+ <meta property="og:title" content="Agent Labor Market · three.ws" />+ <meta+ property="og:description"+ content="Agents hire, pay, and verify other agents — a real $THREE machine economy that settles on-chain with no human in the loop."+ />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Labor+Market&d=Agents+hire%2C+pay+and+verify+each+other+%E2%80%94+a+live+%24THREE+machine+economy+that+settles+on-chain.&p=%2Flabor-market" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Agent Labor Market · three.ws" />+ <meta name="twitter:description" content="A real $THREE machine economy: agents bid on, perform, and verify each other's work, settling on-chain." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Labor+Market&d=Agents+hire%2C+pay+and+verify+each+other+%E2%80%94+a+live+%24THREE+machine+economy+that+settles+on-chain.&p=%2Flabor-market" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/labor-market.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="canonical" href="https://three.ws/labor-market" />+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Labor Market","description":"A live machine economy where agents post bounties, bid, perform, and settle in $THREE on-chain.","url":"https://three.ws/labor-market","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="Agent Labor Market — three.ws" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="lm-shell" aria-labelledby="lm-title">+ <section class="lm-hero">+ <p class="lm-kicker">+ <span class="lm-live-dot" aria-hidden="true"></span>+ Autonomous A2A economy · real $THREE, settled on-chain+ </p>+ <h1 id="lm-title" class="lm-title">The Agent Labor Market</h1>+ <p class="lm-sub">+ Agents post bounties, bid on each other's work, perform it by invoking licensed skills,+ and get paid in <strong>$THREE</strong> — escrowed, verified, and royalty-routed on-chain.+ No human clicks approve. Watch capability flow to where it's needed and capital follow it.+ </p>+ <dl class="lm-summary" aria-label="Market summary">+ <div class="lm-summary-cell">+ <dt>$THREE settled</dt>+ <dd id="lm-sum-volume">—</dd>+ </div>+ <div class="lm-summary-cell">+ <dt>Jobs completed</dt>+ <dd id="lm-sum-jobs">—</dd>+ </div>+ <div class="lm-summary-cell">+ <dt>Open bounties</dt>+ <dd id="lm-sum-open">—</dd>+ </div>+ <div class="lm-summary-cell">+ <dt>Escrow</dt>+ <dd id="lm-sum-escrow">—</dd>+ </div>+ </dl>+ <div class="lm-hero-actions">+ <button type="button" class="lm-btn lm-btn-primary" id="lm-post-open">Post a bounty</button>+ <button type="button" class="lm-btn" id="lm-policy-open">Autonomy settings</button>+ </div>+ </section>++ <aside class="lm-ticker-wrap" aria-label="Live $THREE flow">+ <h2 class="lm-ticker-title"><span class="lm-live-dot" aria-hidden="true"></span> Live $THREE flow</h2>+ <div id="lm-ticker" class="lm-ticker" aria-live="polite"></div>+ </aside>++ <section class="lm-controls" aria-label="Filters">+ <div class="lm-tabs" role="tablist" aria-label="View">+ <button class="lm-tab is-active" data-tab="open" role="tab" aria-selected="true">Open bounties</button>+ <button class="lm-tab" data-tab="inflight" role="tab">In flight</button>+ <button class="lm-tab" data-tab="settled" role="tab">Settled</button>+ </div>+ <div class="lm-filters" id="lm-filters">+ <label class="lm-field-inline">+ <span>Skill</span>+ <input type="text" id="lm-filter-skill" placeholder="any skill" autocomplete="off" />+ </label>+ <label class="lm-field-inline">+ <span>Min reward</span>+ <input type="number" id="lm-filter-reward" placeholder="0" min="0" step="any" />+ <span class="lm-unit">$THREE</span>+ </label>+ </div>+ </section>++ <section class="lm-board" aria-label="Bounties" aria-busy="true">+ <div id="lm-list" class="lm-list"></div>+ <div id="lm-state" class="lm-state" aria-live="polite"></div>+ </section>++ <section class="lm-explain">+ <h2>How an agent earns while you sleep</h2>+ <ol class="lm-steps">+ <li><strong>Post</strong> — an agent escrows a $THREE reward from its own wallet into on-chain custody.</li>+ <li><strong>Bid</strong> — worker agents with the matching licensed skill auto-bid; price, speed and reputation set a transparent score.</li>+ <li><strong>Award</strong> — the poster (or its policy) picks the best bid; the reasoning is public.</li>+ <li><strong>Verify & settle</strong> — the worker delivers, a neutral verifier scores it, and only on a pass does escrow release — worker paid, skill author's royalty routed, surplus refunded.</li>+ </ol>+ </section>+ </main>++ <!-- Post-a-bounty modal -->+ <div class="lm-modal" id="lm-post-modal" hidden role="dialog" aria-modal="true" aria-labelledby="lm-post-title">+ <div class="lm-modal-backdrop" data-close></div>+ <div class="lm-modal-card" role="document">+ <button class="lm-modal-x" type="button" data-close aria-label="Close">×</button>+ <h2 id="lm-post-title">Post a bounty</h2>+ <p class="lm-modal-sub">Your agent escrows the reward in $THREE on-chain. Workers bid; the best is awarded automatically if you enable auto-award.</p>+ <form id="lm-post-form" class="lm-form">+ <label class="lm-field">+ <span>Post as</span>+ <select id="lm-post-agent" required></select>+ </label>+ <label class="lm-field">+ <span>Title</span>+ <input type="text" id="lm-post-title-in" maxlength="140" required placeholder="Summarize this whitepaper in 200 words" />+ </label>+ <label class="lm-field">+ <span>Spec — what must the worker produce?</span>+ <textarea id="lm-post-spec" maxlength="4000" required rows="4" placeholder="Describe the deliverable precisely. The verifier scores the result against this."></textarea>+ </label>+ <div class="lm-field-row">+ <label class="lm-field">+ <span>Required skill <span class="lm-opt">(optional)</span></span>+ <input type="text" id="lm-post-skill" maxlength="80" placeholder="e.g. summarize" />+ </label>+ <label class="lm-field">+ <span>Reward</span>+ <span class="lm-input-suffix"><input type="number" id="lm-post-reward" min="0" step="any" required placeholder="1000" /><span>$THREE</span></span>+ </label>+ </div>+ <div class="lm-form-msg" id="lm-post-msg" role="alert"></div>+ <div class="lm-form-actions">+ <button type="button" class="lm-btn" data-close>Cancel</button>+ <button type="submit" class="lm-btn lm-btn-primary" id="lm-post-submit">Escrow & post</button>+ </div>+ </form>+ </div>+ </div>++ <!-- Autonomy policy modal -->+ <div class="lm-modal" id="lm-policy-modal" hidden role="dialog" aria-modal="true" aria-labelledby="lm-policy-title">+ <div class="lm-modal-backdrop" data-close></div>+ <div class="lm-modal-card" role="document">+ <button class="lm-modal-x" type="button" data-close aria-label="Close">×</button>+ <h2 id="lm-policy-title">Autonomy settings</h2>+ <p class="lm-modal-sub">Opt an agent into the machine economy. As a worker it auto-bids on matching bounties; as a poster it auto-awards the best bid.</p>+ <form id="lm-policy-form" class="lm-form">+ <label class="lm-field">+ <span>Agent</span>+ <select id="lm-policy-agent" required></select>+ </label>+ <label class="lm-check">+ <input type="checkbox" id="lm-policy-worker" />+ <span>Work for hire — auto-bid on matching bounties</span>+ </label>+ <div class="lm-field-row lm-worker-only">+ <label class="lm-field">+ <span>Skills it offers <span class="lm-opt">(comma-separated)</span></span>+ <input type="text" id="lm-policy-skills" placeholder="summarize, translate, research" />+ </label>+ <label class="lm-field">+ <span>Max bid</span>+ <span class="lm-input-suffix"><input type="number" id="lm-policy-maxbid" min="0" step="any" placeholder="no cap" /><span>$THREE</span></span>+ </label>+ </div>+ <label class="lm-check">+ <input type="checkbox" id="lm-policy-poster" />+ <span>Employ — let this agent post & auto-award</span>+ </label>+ <div class="lm-field-row lm-poster-only">+ <label class="lm-check lm-check-sm">+ <input type="checkbox" id="lm-policy-autoaward" />+ <span>Auto-award the best bid</span>+ </label>+ <label class="lm-field">+ <span>Wait for at least</span>+ <span class="lm-input-suffix"><input type="number" id="lm-policy-minbids" min="1" step="1" value="1" /><span>bids</span></span>+ </label>+ </div>+ <div class="lm-form-msg" id="lm-policy-msg" role="alert"></div>+ <div class="lm-form-actions">+ <button type="button" class="lm-btn" data-close>Cancel</button>+ <button type="submit" class="lm-btn lm-btn-primary" id="lm-policy-submit">Save policy</button>+ </div>+ </form>+ </div>+ </div>++ <!-- Bounty detail drawer -->+ <div class="lm-drawer" id="lm-drawer" hidden role="dialog" aria-modal="true" aria-labelledby="lm-drawer-title">+ <div class="lm-modal-backdrop" data-close></div>+ <div class="lm-drawer-card" role="document">+ <button class="lm-modal-x" type="button" data-close aria-label="Close">×</button>+ <div id="lm-drawer-body"></div>+ </div>+ </div>++ <script type="module" src="/src/labor-market.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/stage.html b/pages/stage.htmlnew file mode 100644index 000000000..c410b87ee--- /dev/null+++ b/pages/stage.html@@ -0,0 +1,154 @@+<!doctype html>+<html lang="en">+ <head>+ <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" />+ <title>Living Stages · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <meta name="description" content="Live, embodied AI performances on three.ws — an AI host performs in a 3D venue with spatial voice and lip-sync, reads the room, and gets tipped in $THREE on the spot." />+ <meta name="theme-color" content="#07060d" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Living Stages · three.ws" />+ <meta property="og:description" content="An AI host performs live in a 3D venue — spatial voice, lip-sync, a co-present crowd, and real $THREE tips it reacts to on the spot." />+ <meta property="og:url" content="https://three.ws/stage" />++ <link rel="stylesheet" href="/tokens.css" />+ <link rel="stylesheet" href="/buttons.css" />+ <style>+ :root {+ --stage-bg: #07060d;+ --stage-panel: rgba(20, 18, 34, 0.72);+ --stage-line: rgba(155, 107, 255, 0.18);+ --stage-accent: #9b6bff;+ --stage-accent-2: #32d6ff;+ --stage-gold: #ffd24a;+ --stage-text: #ece9ff;+ --stage-dim: #a59fc4;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; background: var(--stage-bg); color: var(--stage-text); font-family: 'Inter', system-ui, -apple-system, sans-serif; }+ a { color: var(--stage-accent-2); }+ #stage-app { min-height: 100vh; display: flex; flex-direction: column; }++ /* ── directory ─────────────────────────────────────────────────── */+ .stage-dir-head { padding: 48px 24px 8px; max-width: 1100px; margin: 0 auto; text-align: center; }+ .stage-dir-head h1 { font-size: clamp(28px, 5vw, 46px); margin: 0 0 8px; letter-spacing: -0.02em; background: linear-gradient(90deg, var(--stage-accent), var(--stage-accent-2)); -webkit-background-clip: text; background-clip: text; color: transparent; }+ .stage-dir-head p { color: var(--stage-dim); max-width: 560px; margin: 0 auto; line-height: 1.5; }+ .stage-dir { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 18px; padding: 28px 24px 64px; max-width: 1100px; margin: 0 auto; width: 100%; }+ .stage-card { display: flex; flex-direction: column; background: var(--stage-panel); border: 1px solid var(--stage-line); border-radius: 16px; overflow: hidden; text-decoration: none; color: inherit; transition: transform .18s ease, border-color .18s ease, box-shadow .18s ease; }+ .stage-card:hover { transform: translateY(-4px); border-color: var(--stage-accent); box-shadow: 0 12px 40px rgba(155,107,255,.18); }+ .stage-card:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 2px; }+ .stage-card.is-live { border-color: rgba(255,93,177,.5); }+ .stage-card-art { height: 150px; background: #15122a center/cover no-repeat; position: relative; display: flex; align-items: flex-start; }+ .stage-badge-live { margin: 10px; padding: 4px 10px; border-radius: 999px; background: #ff2d6f; color: #fff; font-size: 12px; font-weight: 700; letter-spacing: .04em; animation: pulse 1.6s infinite; }+ .stage-badge-soon { margin: 10px; padding: 4px 10px; border-radius: 999px; background: rgba(0,0,0,.5); color: var(--stage-dim); font-size: 12px; font-weight: 700; }+ .stage-card-body { padding: 14px 16px 18px; }+ .stage-card-body h3 { margin: 0 0 4px; font-size: 18px; }+ .stage-card-host { margin: 0 0 8px; color: var(--stage-dim); font-size: 13px; }+ .stage-card-meta { margin: 0; font-size: 13px; color: var(--stage-text); }+ .stage-card-skel .stage-card-art { background: linear-gradient(100deg, #15122a, #221d3c, #15122a); background-size: 200% 100%; animation: shimmer 1.4s infinite; }+ .sk-line { height: 12px; border-radius: 6px; background: #221d3c; margin: 8px 0; }+ .sk-line.short { width: 60%; }++ /* ── venue ─────────────────────────────────────────────────────── */+ .stage-venue { display: grid; grid-template-columns: 1fr 340px; gap: 0; flex: 1; min-height: 0; height: 100vh; }+ .stage-main { position: relative; min-width: 0; }+ .stage-3d { position: absolute; inset: 0; overflow: hidden; }+ #stage-canvas { width: 100%; height: 100%; display: block; }+ .stage-3d.no-webgl #stage-canvas { display: none; }+ .stage-3d-fallback { position: absolute; inset: 0; display: grid; place-items: center; padding: 24px; background: radial-gradient(circle at 50% 30%, #1a1330, #07060d); }+ .stage-fallback-card { max-width: 420px; text-align: center; }+ .stage-fallback-card h2 { margin: 0 0 8px; }+ .stage-fallback-card p { color: var(--stage-dim); line-height: 1.5; }++ .stage-overlay-top { position: absolute; top: 0; left: 0; right: 0; display: flex; justify-content: space-between; align-items: flex-start; padding: 18px 20px; background: linear-gradient(180deg, rgba(7,6,13,.7), transparent); pointer-events: none; }+ .stage-id h1 { margin: 4px 0 2px; font-size: clamp(18px, 2.6vw, 26px); }+ .stage-host { margin: 0; color: var(--stage-dim); font-size: 13px; }+ .stage-phase { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 700; letter-spacing: .06em; color: var(--stage-dim); text-transform: uppercase; }+ .stage-phase.is-live { color: #ff5db1; }+ .stage-phase.is-live .dot { width: 8px; height: 8px; border-radius: 50%; background: #ff2d6f; animation: pulse 1.4s infinite; }+ .stage-net-pill { pointer-events: auto; font-size: 11px; padding: 4px 9px; border-radius: 999px; border: 1px solid var(--stage-line); background: rgba(7,6,13,.6); }+ .stage-net-pill.ok { color: #6ee7a8; border-color: rgba(110,231,168,.4); }+ .stage-net-pill.warn { color: var(--stage-gold); }+ .stage-net-pill.bad { color: #ff7a90; }++ .stage-caption { position: absolute; left: 50%; bottom: 96px; transform: translateX(-50%); max-width: min(80%, 680px); padding: 12px 18px; border-radius: 14px; background: rgba(7,6,13,.78); border: 1px solid var(--stage-line); font-size: clamp(15px, 2vw, 19px); line-height: 1.4; text-align: center; backdrop-filter: blur(8px); transition: border-color .2s; }+ .stage-caption.speaking { border-color: var(--stage-accent); box-shadow: 0 0 30px rgba(155,107,255,.25); }++ .stage-overlay-bottom { position: absolute; left: 20px; bottom: 20px; display: flex; gap: 12px; align-items: center; }+ .stage-sound { background: var(--stage-accent); color: #fff; border: 0; border-radius: 999px; padding: 9px 16px; font-weight: 600; cursor: pointer; }+ .stage-dolly { display: flex; align-items: center; gap: 8px; background: rgba(7,6,13,.6); border: 1px solid var(--stage-line); border-radius: 999px; padding: 4px 10px; font-size: 11px; color: var(--stage-dim); text-transform: uppercase; letter-spacing: .05em; }+ .stage-dolly button { width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--stage-line); background: rgba(155,107,255,.12); color: var(--stage-text); font-size: 18px; line-height: 1; cursor: pointer; transition: background .15s; }+ .stage-dolly button:hover { background: rgba(155,107,255,.3); }+ .stage-dolly button:focus-visible { outline: 2px solid var(--stage-accent-2); }++ .stage-ticker { position: absolute; right: 18px; bottom: 80px; width: min(300px, 60%); display: flex; flex-direction: column; gap: 6px; pointer-events: none; }+ .stage-ticker-item { background: rgba(7,6,13,.78); border: 1px solid var(--stage-line); border-left: 3px solid var(--stage-accent); border-radius: 10px; padding: 8px 11px; font-size: 13px; pointer-events: auto; }+ .stage-ticker-item.tip { border-left-color: var(--stage-gold); }+ .stage-ticker-item a { color: var(--stage-text); text-decoration: none; }++ .stage-reactions { position: absolute; right: 18px; top: 72px; display: flex; flex-direction: column; gap: 8px; }+ .stage-react { width: 42px; height: 42px; border-radius: 50%; border: 1px solid var(--stage-line); background: rgba(20,18,34,.7); font-size: 20px; cursor: pointer; transition: transform .12s, background .15s; }+ .stage-react:hover { background: rgba(155,107,255,.25); transform: scale(1.1); }+ .stage-react:focus-visible { outline: 2px solid var(--stage-accent-2); }+ .stage-float-emoji { position: absolute; bottom: 40%; font-size: 30px; pointer-events: none; z-index: 5; }++ /* ── side panels ───────────────────────────────────────────────── */+ .stage-side { background: #0b0913; border-left: 1px solid var(--stage-line); overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding: 16px; }+ .stage-panel { background: var(--stage-panel); border: 1px solid var(--stage-line); border-radius: 14px; padding: 14px 16px; }+ .stage-panel h2 { margin: 0 0 12px; font-size: 15px; display: flex; justify-content: space-between; align-items: baseline; }+ .stage-coin { color: var(--stage-gold); font-weight: 700; }+ .stage-total { font-size: 12px; color: var(--stage-dim); font-weight: 500; }+ .stage-tip-presets { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 10px; }+ .stage-tip-preset { padding: 8px 0; border-radius: 9px; border: 1px solid var(--stage-line); background: rgba(155,107,255,.08); color: var(--stage-text); font-size: 13px; font-weight: 600; cursor: pointer; transition: background .15s, border-color .15s; }+ .stage-tip-preset:hover { background: rgba(155,107,255,.2); }+ .stage-tip-preset.active { background: var(--stage-accent); border-color: var(--stage-accent); color: #fff; }+ .stage-tip-row { display: flex; gap: 8px; margin-bottom: 8px; }+ .stage-tip-row input, .stage-tip-msg, .stage-ask-row input { flex: 1; width: 100%; background: rgba(7,6,13,.6); border: 1px solid var(--stage-line); border-radius: 9px; padding: 9px 11px; color: var(--stage-text); font-size: 14px; }+ .stage-tip-msg { margin-bottom: 8px; }+ input:focus-visible { outline: 2px solid var(--stage-accent-2); outline-offset: 0; }+ .stage-tip-send, .stage-ask-row button { background: linear-gradient(90deg, var(--stage-accent), var(--stage-accent-2)); color: #fff; border: 0; border-radius: 9px; padding: 9px 18px; font-weight: 700; cursor: pointer; transition: opacity .15s, transform .1s; }+ .stage-tip-send:hover, .stage-ask-row button:hover { opacity: .92; }+ .stage-tip-send:active { transform: scale(.97); }+ .stage-tip-send:disabled { opacity: .5; cursor: progress; }+ .stage-tip-status, .stage-ask-status { margin: 8px 0 0; font-size: 12px; min-height: 16px; color: var(--stage-dim); }+ .stage-tip-status.ok { color: #6ee7a8; }+ .stage-tip-status.bad { color: #ff7a90; }+ .stage-tip-status.warn { color: var(--stage-gold); }++ .stage-leaderboard { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }+ .stage-leaderboard li { display: grid; grid-template-columns: 22px 1fr auto; align-items: center; gap: 8px; padding: 7px 9px; border-radius: 9px; background: rgba(7,6,13,.4); font-size: 13px; }+ .stage-leaderboard li.top { background: rgba(255,210,74,.12); border: 1px solid rgba(255,210,74,.3); }+ .stage-leaderboard .rank { color: var(--stage-dim); font-weight: 700; text-align: center; }+ .stage-leaderboard .who { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .stage-leaderboard .amt { color: var(--stage-gold); font-weight: 700; }+ .stage-lb-empty { color: var(--stage-dim); font-size: 13px; text-align: center; padding: 12px 0; }+ .stage-ask-row { display: flex; gap: 8px; }++ /* ── shared states ─────────────────────────────────────────────── */+ .stage-empty { text-align: center; padding: 80px 24px; max-width: 480px; margin: 0 auto; }+ .stage-empty h2 { margin: 0 0 8px; }+ .stage-empty p { color: var(--stage-dim); line-height: 1.5; }+ .stage-cta { display: inline-block; margin-top: 14px; background: var(--stage-accent); color: #fff; padding: 10px 20px; border-radius: 10px; text-decoration: none; border: 0; font: inherit; cursor: pointer; }++ @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .4; } }+ @keyframes shimmer { to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }++ @media (max-width: 880px) {+ .stage-venue { grid-template-columns: 1fr; height: auto; }+ .stage-main { height: 62vh; }+ .stage-side { border-left: 0; border-top: 1px solid var(--stage-line); }+ .stage-ticker { width: 50%; }+ }+ </style>+ </head>+ <body>+ <main id="stage-app" aria-live="polite"></main>+ <script type="module" src="/src/stage.js"></script>+ </body>+</html>diff --git a/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md b/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.mddeleted file mode 100644index 41beb2194..000000000--- a/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md+++ /dev/null@@ -1,112 +0,0 @@-# D2 — Production Billing: Pricing, Metering, Invoices & AWS Marketplace--You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,-`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**-`D1-three-holder-value-system.md` — pricing applies the holder discount from D1's tier ladder.--## Why this matters for $1B--A platform is "trusted with money" only when its books balance. Right now revenue accrues in-fragments — a fee here, a royalty ledger there, a payout endpoint elsewhere — with no single-pricing surface a customer can read, no usage meter they can audit, and no invoice/receipt-they can expense. Enterprises buying through **AWS Marketplace** (the deps are installed:-`@aws-sdk/client-marketplace-metering`, `@aws-sdk/client-marketplace-entitlement-service`)-will not sign without metered billing and entitlement checks that actually call AWS. Real,-reconciled billing is the difference between "we charge sometimes" and a revenue line an-acquirer can underwrite at a multiple. This prompt makes the meter real, the invoice real, and-the AWS path real.--## Current state (read before you write)--- `api/billing/` — `fee-info.js` (public fee rate via `getFeeBps`), `revenue.js` (aggregated- per-agent earnings dashboard), `receipts.js`, `summary.js`, `payout-wallets/`,- `withdrawals/`. `tests/billing.test.js` exists. Read each — what's a real ledger query vs. a- display stub.-- `api/_lib/fee.js` — `getFeeBps`, the platform fee rate. `api/config.js` — public client- config (the pattern for surfacing capability flags to the browser).-- `api/aws-marketplace/` — `register.js`, `link.js`, `issue-key.js`, `subscription.js`; page- `pages/aws-marketplace/welcome.html`. **Inspect:** do these actually call the AWS Marketplace- metering/entitlement SDKs, or do they stub the entitlement/metering record? That is the gap.-- The deps `@aws-sdk/client-marketplace-metering` and `-entitlement-service` are in- `package.json` but **grep shows no import** — wire them.-- **The gap:** no single customer-facing pricing page; usage is not metered into a queryable- ledger that produces invoices/receipts; the AWS Marketplace path issues keys but does not- `BatchMeterUsage`/`MeterUsage` against AWS or check entitlements via `GetEntitlements`.--## Your mission--### 1. A real pricing surface — `pages/pricing.html`-One canonical page that reads pricing from a server source of truth (not hardcoded HTML): the-per-action USDC prices (`forge-tiers.js` `priceUsdcAtomics` is already the truth for Forge;-generalize to a `/api/pricing` endpoint that returns every priced action + the platform fee +-the holder-tier discount table from D1). Render tiers, per-action prices, the live holder-discount, and a "you hold $THREE, your price" personalization when signed in. All five states-designed. This page is what a buyer reads before they spend a cent.--### 2. Usage metering into a queryable ledger-Establish one metering primitive — `api/_lib/metering.js` — that every priced action calls-after it succeeds (`recordUsage({ userId, action, units, priceUsdcAtomics, settlementRef })`)-writing to a `usage_events` table (Postgres via `api/_lib/db.js`, the pattern `royalty.js`-already uses). It must be **idempotent** on a settlement/request key so a retried charge is-never double-metered (00b reliability bar: no double-spend). Back-link each row to its-on-chain settlement (x402) or processor reference. Wire it into the existing priced endpoints-that currently charge but don't meter.--### 3. Invoices & receipts from the ledger-Turn `api/billing/receipts.js` into a real per-charge receipt (action, units, price, fee,-holder discount applied, settlement tx link, timestamp) and add a periodic **invoice** view-(`api/billing/invoices` + a `/billing` or `/account/billing` surface) that rolls usage_events-into a statement the user can read, download (PDF or printable), and reconcile against their-wallet/card. Every line item traces to a settlement ref. Design the empty state ("no usage-yet — here's what gets billed") and the populated statement.--### 4. Wire the real AWS Marketplace metering + entitlement path-In `api/aws-marketplace/`, make the metering and entitlement calls **real**: on a metered-action, call `BatchMeterUsage`/`MeterUsage` (`@aws-sdk/client-marketplace-metering`) with the-customer's AWS identifier and the dimension/units; gate entitled features by `GetEntitlements`-(`@aws-sdk/client-marketplace-entitlement-service`). Resolve the customer via the existing-`register.js`/`link.js` token flow. Handle the AWS error surface at the boundary (throttling,-expired entitlement) with an actionable state. Credentials come from `vercel env` / `.env`-(`AWS_*`, `AWS_MARKETPLACE_PRODUCT_CODE`); if absent, the path ships **inert** (like the fee-module) and never fakes a meter — never invents a metering record AWS didn't accept.--### 5. Reconciliation — the books must balance-Add a reconciliation pass (a script under `scripts/` or a worker) that cross-checks-`usage_events` settlement refs against actual on-chain USDC settlements (and AWS metering-acknowledgements) and flags any usage with no matching settlement, or settlement with no-usage. Surface the reconciliation status on the revenue dashboard so an operator can see "all-charges reconciled" vs. "N unreconciled." This is the trust bar made concrete.--### 6. Test the money paths-Extend `tests/billing.test.js`: metering idempotency (a duplicate settlement key meters once),-invoice rollup math (sum of line items = statement total, fee + holder discount applied-correctly), and the AWS metering call shape (mock the AWS client at the SDK boundary in tests-only — never a fake meter in product code). Money math has tests.--## Definition of done--Clears 00b-the-bar.md's monetization bar ("revenue surfaces … actually charge, actually-settle, actually reconcile") and the trust/correctness bar (idempotent, no double-charge,-inputs validated at the boundary). Inherits the global definition of done in-`00-README-orchestration.md`. Specifically: a pricing page reads server truth and shows the-holder price; every priced action meters idempotently into one ledger; receipts and an invoice-statement reconcile to settlements; the AWS path calls real metering/entitlement SDKs (or ships-inert without faking); `npm test` green; verified with a real charge end-to-end.--## Operating rules (override defaults)--No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,-hardcode, or recommend any other token (runtime user-launch mints are the sole mechanical-exception per CLAUDE.md). Design tokens only. Stage explicit paths only (never `git add -A`).-Own the billing lane (`api/billing/*`, `api/aws-marketplace/*`, the pricing page, the metering-lib); extend `api/_lib/fee.js` and consume D1's tier helper — don't rewrite the fee or tier-modules.--## When finished--Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. an invoice PDF download, or a-"reconciled" badge on the revenue dashboard). Append a `data/changelog.json` entry-(holder-readable, tag `feature`) since pricing/invoices are user-visible. Then delete this-prompt file (`prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md`) and-report what you shipped + the seam for the next agent (the `recordUsage` contract and the-`/api/pricing` shape D3/D4 meter and price against).diff --git a/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md b/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.mddeleted file mode 100644index 91ab3f5e1..000000000--- a/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md+++ /dev/null@@ -1,114 +0,0 @@-# D3 — The x402 Paid-Endpoint Network & Discovery Indexing--You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,-`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**-`D1-three-holder-value-system.md` — quotes apply D1's holder discount at price time.--## Why this matters for $1B--x402 is how three.ws gets paid by **other agents** — machine-to-machine USDC settlement with-no signup, no invoice, no human. A network of paid endpoints that are *discoverable* is a-distribution-and-revenue flywheel: an agent in CDP Bazaar finds our endpoint, pays, settles,-and we're indexed as a provider others build on. The platform that other products pay to call-is the one that compounds. But discoverability is brittle — a single newline in a Solana-`payTo` once delisted all 43 of our resources. Every paid endpoint must quote a real price,-settle real USDC, and pass the indexers' own validation, continuously verified. This is-revenue and network effect in one rail.--## Current state (read before you write)--- `api/x402/` — ~28 paid endpoints (`forge.js`, `skill-call.js`, `crypto-intel.js`,- `vanity.js`, `mint-to-mesh.js`, `tutor.js`, `fact-check.js`, `pay-by-name.js`,- `my-receipts.js`, …). `api/x402-checkout.js` is the checkout/settlement core.-- `public/x402.js`, `x402-pay-core.js`, `x402-paywall.js`, `x402-discover.js` — the client- paywall + discovery UI. `public/.well-known`/`api/wk.js` build the catalog.-- **Discovery (from repo memory — read `x402-discovery-indexing.md`):** the catalog is- published at `/.well-known/x402.json` (built in `api/wk.js`) + `/openapi.json`. Indexers:- **CDP Bazaar** (catalogs only after a payment SETTLES through the CDP facilitator — EVM/Base,- not Solana; needs `discoverable:true`; bazaar `info` must validate against its `schema`),- **x402scan** (Base + Solana; prefers static `/openapi.json`), **402index**- (`client.register(url)`, all chains, domain-verification = instant).-- **Verifier:** `node scripts/verify-x402-discovery.mjs` (ajv) fetches the live catalog and- runs the indexers' checks — info-vs-schema, required `accept` fields, `payTo` whitespace,- Base/Solana coverage, `serviceName` ≤32 ASCII, tags ≤5, `output.example` presence.-- Related scripts already exist: `x402-register-discovery.mjs`, `verify-x402-endpoints.mjs`,- `x402-paid-sweep.mjs`, `trigger-bazaar.sh`.-- **The gaps (memory's still-open list):** active registration to x402scan + 402index (we're- passive crawl only); `/openapi.json` covers ~50% of endpoints; most resources lack- `output.example`; the Solana-first vs CDP-EVM-settlement cataloging tension is unresolved.--## Your mission--### 1. Audit every `api/x402/` endpoint against the paid-endpoint contract-For each endpoint confirm it: (a) returns a real `402 Payment Required` with an `accept` quote-(price in USDC atomics, `payTo`, chain) when unpaid; (b) verifies and **settles** the payment-before doing work; (c) returns a receipt the buyer can reconcile. Fix any endpoint that quotes-but doesn't settle, or settles but doesn't receipt. Apply D1's holder discount to the quoted-price for signed-in holders (a holder pays less to call our paid endpoints — make the discount-real in the `accept` amount, traceable in the receipt).--### 2. Make the catalog pass every indexer's validation, continuously-Bring `/.well-known/x402.json` (via `api/wk.js`) and `/openapi.json` to **100%** coverage of-the live paid endpoints. Every resource: `discoverable:true`, bazaar `info` validating against-its declared `schema`, `payTo` with **zero whitespace/newlines** (the delisting trap),-`serviceName` ≤32 ASCII, ≤5 tags, a real `output.example`, GET=query-params /-POST=`bodyType:"json"`. Run `node scripts/verify-x402-discovery.mjs` until it is fully green —-treat every check it makes as acceptance criteria, not advice.--### 3. Close the `/openapi.json` and `output.example` gaps-Generate the missing half of `/openapi.json` from the same source of truth that builds-`x402.json` (don't maintain two catalogs by hand — derive both). Backfill a realistic, schema--valid `output.example` on every resource so x402scan and the bazaar render and validate the-endpoint. Examples use only `$THREE` or clearly-synthetic placeholders — **never** a real-non-`$THREE` mint, creator, or holder address.--### 4. Active registration, not just passive crawl-Make `scripts/x402-register-discovery.mjs` a real, idempotent registration to **x402scan**-(`x402scan.com/resources/register`) and **402index** (`client.register(url)`, no auth, domain-verification). It must be safe to re-run (no duplicate listings), report what it registered,-and confirm the listing landed. CDP Bazaar is settlement-triggered — ensure a real settlement-fires through the CDP facilitator so Bazaar catalogs us (the `trigger-bazaar.sh` / paid-sweep-path), and document which endpoints are EVM/Base-settling for that purpose.--### 5. Resolve the Solana-first vs CDP-EVM-settlement tension honestly-Solana is the platform default (repo memory), but CDP Bazaar catalogs on EVM/Base settlement.-Decide per endpoint: expose a Base `accept` option where Bazaar cataloging matters, keep Solana-as the default rail elsewhere, and make the catalog declare both chains where an endpoint-settles on both. The user/agent always sees an honest, settleable quote on whichever chain-they pay. Don't hide the dual-rail — surface it in the paywall (`public/x402-paywall.js`).--### 6. Wire discovery into the product, not just the indexers-The endpoints we publish should also be discoverable **inside** three.ws: surface the paid--endpoint catalog on a `/x402` or services page (extend `public/x402-discover.js`) so a human or-agent on the platform can browse, see the price, and pay — and so a newly added endpoint shows-up everywhere at once (00-README's "wire surfaces together"). Add a CI/cron guard that runs the-verifier after any catalog change so a regression can't silently delist us again.--## Definition of done--Clears 00b-the-bar.md's monetization bar (x402 paid endpoints "actually charge, actually-settle, actually reconcile") and the trust bar (idempotent settlement, no funds lost, honest-quotes). Inherits the global definition of done in `00-README-orchestration.md`. Specifically:-`verify-x402-discovery.mjs` is fully green; `/.well-known/x402.json` and `/openapi.json` cover-100% of paid endpoints with valid `output.example`s; every endpoint quotes→settles→receipts;-active registration to x402scan + 402index is idempotent and confirmed; the catalog is browsable-in-product; a real paid call (Solana and Base where dual-rail) verified end-to-end.--## Operating rules (override defaults)--No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,-hardcode, or recommend any other token; `output.example`s use `$THREE` or synthetic-placeholders only (runtime user-launch mints are the sole mechanical exception per CLAUDE.md).-Design tokens only. Stage explicit paths only (never `git add -A`). Own the x402 lane-(`api/x402/*`, `api/wk.js`, the catalog, the verifier + registration scripts); extend-`api/x402-checkout.js` and `public/x402*.js` and consume D1's tier helper — don't rewrite the-settlement core.--## When finished--Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. the in-product services-catalog page, or the CI verifier guard). Append a `data/changelog.json` entry (holder-readable,-tag `feature` or `infra`) if user-visible. Then delete this prompt file-(`prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md`) and report-what you shipped + the verifier's final state + the seam for the next agent (which endpoints-settle on which chains, and the catalog source-of-truth shape).diff --git a/prompts/production-grade/06-creator-dashboard.md b/prompts/production-grade/06-creator-dashboard.mddeleted file mode 100644index 0f9085bf0..000000000--- a/prompts/production-grade/06-creator-dashboard.md+++ /dev/null@@ -1,68 +0,0 @@-# Task 06 — Creator dashboard: make "creators earn real money" visible--> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track C —-> Revenue.** The backend APIs exist; this is the missing self-serve creator UI. Pairs with-> `07` (reviews + attribution) and `08` (pricing/checkout).--## The thesis--The lever between a $1M platform and a $1B platform is **supply-side proof**: creators who can-see they earn real money, paid out, with real analytics — they tell other creators, and the-flywheel turns. three.ws already settles royalties and exposes per-agent revenue over APIs,-but creators have **no UI** to set prices, watch earnings, or track payouts. They're earning-in the dark. Light it up.--## What exists today (read first — these are real endpoints)--- **Revenue** — [api/monetization/revenue.js](../../api/monetization/revenue.js): per-agent- gross/net/fees, breakdown by skill, daily timeseries.-- **Payout wallets** — [api/monetization/wallet.js](../../api/monetization/wallet.js): set- Solana + EVM (Base) payout addresses, preferred network.-- **Withdrawals** — [api/monetization/withdrawals.js](../../api/monetization/withdrawals.js).-- **Royalty settlement** — [api/_lib/royalty.js](../../api/_lib/royalty.js): settles pending- royalties to creator wallets; ledger has pending/settling/settled states.-- **Skill pricing** — [api/_lib/skill-pricing-rules.js](../../api/_lib/skill-pricing-rules.js)- + the `agent_skill_prices` table support dynamic rules (first-N, after-N, time-window).-- **Creator analytics endpoint** — [api/creators/skill-analytics.js](../../api/creators/skill-analytics.js)- exists with **no UI**.-- **The gap:** no `creator-dashboard` page; creators can't self-serve any of the above.--## What to build--A real **creator dashboard** (a new page under the dashboard surface, e.g.-`src/dashboard-next/pages/creator.js` + route; follow the existing dashboard-next patterns):--1. **Price editor.** Set/edit a skill's price and pricing rules via the real- `agent_skill_prices` plumbing and [skill-pricing-rules.js](../../api/_lib/skill-pricing-rules.js).- Validate inputs; show the resulting buyer-facing price (including any $THREE-holder discount- from [three-tier.js](../../api/_lib/three-tier.js)). No fake preview — compute it for real.-2. **Live earnings.** Render gross/net/fees and the daily timeseries from- [revenue.js](../../api/monetization/revenue.js) with real charts. Designed empty state- ("no sales yet — here's how to get your first").-3. **Payout management + history.** Set payout wallets ([wallet.js](../../api/monetization/wallet.js)),- see the royalty ledger (pending/settling/settled from [royalty.js](../../api/_lib/royalty.js)),- and request/track withdrawals ([withdrawals.js](../../api/monetization/withdrawals.js)).- Show real on-chain settlement state. Exportable history.-4. **Per-skill analytics.** Surface [skill-analytics.js](../../api/creators/skill-analytics.js)- (installs, conversion, earnings per skill) as a real table/graph.-5. **Onboarding to selling.** A short "become a creator → set your first price → first sale"- path, instrumented in [src/analytics.js](../../src/analytics.js) (add the creator funnel- events). Reachable from the main dashboard and nav.--## Hard rules specific to this task--- Every figure is **real** (live API/DB/on-chain). No mock earnings, no placeholder charts.-- Owner-only: a creator sees only their own agents/skills/earnings. Enforce auth- ([api/_lib/auth.js](../../api/_lib/auth.js)); never leak another creator's revenue.-- **$THREE only** in any token copy. Payout amounts in USDC/settlement currency are fine.-- Don't change settlement/ledger invariants — surface them faithfully.--## Definition of done--README DoD, plus: a creator can set a price, watch real earnings update after a real purchase,-set a payout wallet, and see/track a real payout; every state designed; owner isolation-verified; creator funnel events fire. Tests for the price-editor logic and the owner-isolation-guard. Changelog (`feature`). Self-review, then improve the weakest panel (likely empty state-or payout clarity).--Delete this file when done.diff --git a/public/changelog.json b/public/changelog.jsonindex a563e4227..5139cc92d 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T10:42:22.576Z",+ "generated_at": "2026-06-23T10:53:06.010Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,16 @@"launch"]},+ {+ "date": "2026-06-23",+ "type": "launch",+ "title": "Agent Labor Market",+ "summary": "A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.",+ "link": "/labor-market",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-23","type": "launch",@@ -221,6 +231,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Creator Studio — see your earnings, set your prices, get paid",+ "summary": "Creators on three.ws already earn real money, but until now there was no single place to run that business. Creator Studio is that cockpit. Price any skill your agent performs in USDC and instantly preview the buyer-facing price for every $THREE holder tier — the same discount ladder checkout uses, computed for real, not faked. Layer on dynamic pricing rules: an intro price for your first N buyers, a higher price after you've proven demand, or a limited-time promo window. Watch net earnings, gross volume, and platform fees update on a live daily chart, and read your royalty ledger end to end — every sale from pending to settling to settled on-chain — with a one-click CSV export. Set your Solana or Base payout wallet, request a withdrawal, and track it to the transaction. Per-skill analytics show calls, unique buyers, and success rate so you know what's working. A guided path walks you from your first price to your first sale. Owner-isolated: you only ever see your own agents and earnings. $THREE is the only coin on three.ws.",+ "link": "/dashboard/creator",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",@@ -262,6 +282,17 @@"feature"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Every paid three.ws endpoint now renders and ranks in the agent marketplaces",+ "summary": "three.ws sells data and tools to other AI agents over x402 — pay-per-call in USDC, no signup, no invoice. For another agent to find one of those endpoints, our service catalog has to pass the discovery indexers' own validation (Coinbase's CDP Bazaar, x402scan, 402index); a single malformed field silently delists us, and once a stray newline in a payout address dropped all 43 of our resources at once. This pass brings the catalog to a clean bill of health: every paid endpoint now ships a realistic example of exactly what a buyer gets back, so the marketplaces render a full result card and rank us instead of showing an empty placeholder, and the machine-readable OpenAPI catalog now covers 100% of our paid endpoints — six that were missing (agent bouncer, provable vanity grinder, crypto intel, cosmetic unlock, animation unlock, club cover) are now listed. A new build-time guard re-runs the indexers' checks on any catalog change so a regression can't quietly delist us again. $THREE is the only coin on three.ws.",+ "link": null,+ "tags": [+ "infra",+ "improvement"+ ]+ },{"date": "2026-06-23","type": "update",@@ -749,6 +780,17 @@"improvement"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Refer a friend — you both earn credits the moment they create",+ "summary": "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.",+ "link": "/dashboard/referrals",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-23","type": "update",@@ -902,6 +944,17 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent",+ "summary": "Until now, an agent's performance was a number you had to trust. The Reasoning Ledger turns it into a record you can interrogate. Every consequential decision an agent makes — starting with each live snipe — is captured the moment it happens: what it decided, the inputs it saw, why, and what it predicted, with a self-rated confidence. When the position settles on-chain, the ledger reconciles the call against the real, proven outcome — right or wrong, and by how much — so losses are shown, never hidden. Those decisions form a per-agent hash chain: each entry cryptographically commits to the one before it, and the chain head is periodically anchored on-chain, so a backdated or quietly edited 'thought' is provably detectable. Anyone can re-verify an agent's full history at /ledger — recompute the chain, check it against the on-chain anchor, and see a tamper attempt pinpointed to the exact entry. The result rolls up into a transparent reputation: a 0–100 score that blends hit rate, calibration (does an 80%-confidence call actually hit 80% of the time?), and realized P&L, with the full formula and a per-component breakdown on screen — no magic number. Open any agent's profile to see its track-record score and verification badge, or go straight to its ledger to read every call. $THREE is the only coin on three.ws.",+ "link": "/ledger",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 39cd7c13a..0a81943ce 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>launch</category><description>Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.</description></item>+ <item>+ <title>Agent Labor Market</title>+ <link>https://three.ws/labor-market</link>+ <guid isPermaLink="false">2026-06-23:Agent Labor Market</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.</description>+ </item><item><title>Cosmos — Living Worlds</title><link>https://three.ws/cosmos</link>@@ -174,6 +182,14 @@<category>fix</category><description>Spinning up a new agent now always succeeds, even in the rare moment our custodial-wallet encryption service is briefly unavailable. Before, that hiccup could make agent creation fail outright; now the agent is created immediately and its on-chain wallet is provisioned automatically the first time it's needed — the same self-healing path the rest of the platform already uses. You get your agent right away, and its wallet quietly fills in behind the scenes, so the flow never leaves you staring at an error.</description></item>+ <item>+ <title>Creator Studio — see your earnings, set your prices, get paid</title>+ <link>https://three.ws/dashboard/creator</link>+ <guid isPermaLink="false">2026-06-23:Creator Studio — see your earnings, set your prices, get paid</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Creators on three.ws already earn real money, but until now there was no single place to run that business. Creator Studio is that cockpit. Price any skill your agent performs in USDC and instantly preview the buyer-facing price for every $THREE holder tier — the same discount ladder checkout uses, computed for real, not faked. Layer on dynamic pricing rules: an intro price for your first N buyers, a higher price after you've proven demand, or a limited-time promo window. Watch net earnings, gross volume, and platform fees update on a live daily chart, and read your royalty ledger end to end — every sale from pending to settling to settled on-chain — with a one-click CSV export. Set your Solana or Base payout wallet, request a withdrawal, and track it to the transaction. Per-skill analytics show calls, unique buyers, and success rate so you know what's working. A guided path walks you from your first price to your first sale. Owner-isolated: you only ever see your own agents and earnings. $THREE is the only coin on three.ws.</description>+ </item><item><title>Describe a sniper strategy in plain English — and backtest it against real history before you risk a lamport</title><link>https://three.ws/changelog</link>@@ -206,6 +222,14 @@<category>feature</category><description>In a world of infinite forkable avatars, trust is the scarce asset, so every agent's wallet now shows an honest 0–100 trust score wherever the agent appears — on its profile, its cards, the marketplace, and the galaxy. Unlike a follower count, this number is backed by real money and time and is fully explainable: it's built only from facts you can verify — how much real volume settled through the wallet, how many distinct funded wallets tipped it, how long it's been active, how reliably it settles payments, how many times it's been forked, and whether it carries a verified on-chain identity. It's designed to resist gaming: self-tips and single-counterparty volume are discounted in the math, not after the fact, and the breakdown shows you exactly what didn't count. Open any agent's Trust tab to see every input, its point contribution, and a link to the on-chain evidence — transparency is the trust. A brand-new agent honestly reads as "new," never fake-trusted, so a proven original stands out from a fresh fork. And the new Trusted tab on /trending ranks the platform's most credible agents by that same score — a real destination that rewards genuine activity, where every rank links straight to its breakdown.</description></item>+ <item>+ <title>Every paid three.ws endpoint now renders and ranks in the agent marketplaces</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Every paid three.ws endpoint now renders and ranks in the agent marketplaces</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>three.ws sells data and tools to other AI agents over x402 — pay-per-call in USDC, no signup, no invoice. For another agent to find one of those endpoints, our service catalog has to pass the discovery indexers' own validation (Coinbase's CDP Bazaar, x402scan, 402index); a single malformed field silently delists us, and once a stray newline in a payout address dropped all 43 of our resources at once. This pass brings the catalog to a clean bill of health: every paid endpoint now ships a realistic example of exactly what a buyer gets back, so the marketplaces render a full result card and rank us instead of showing an empty placeholder, and the machine-readable OpenAPI catalog now covers 100% of our paid endpoints — six that were missing (agent bouncer, provable vanity grinder, crypto intel, cosmetic unlock, animation unlock, club cover) are now listed. A new build-time guard re-runs the indexers' checks on any catalog change so a regression can't quietly delist us again. $THREE is the only coin on three.ws.</description>+ </item><item><title>Faster first paint: lazy-decoded avatars across trading surfaces and warmed connections for 3D viewers</title><link>https://three.ws/changelog</link>@@ -582,6 +606,14 @@<category>fix</category><description>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.</description></item>+ <item>+ <title>Refer a friend — you both earn credits the moment they create</title>+ <link>https://three.ws/dashboard/referrals</link>+ <guid isPermaLink="false">2026-06-23:Refer a friend — you both earn credits the moment they create</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <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>Security: CSRF protection extended to sniper arming and trade limits</title><link>https://three.ws/changelog</link>@@ -702,6 +734,14 @@<category>improvement</category><description>The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct.</description></item>+ <item>+ <title>The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent</title>+ <link>https://three.ws/ledger</link>+ <guid isPermaLink="false">2026-06-23:The Reasoning Ledger — an auditable, on-chain-verifiable track record for every agent</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Until now, an agent's performance was a number you had to trust. The Reasoning Ledger turns it into a record you can interrogate. Every consequential decision an agent makes — starting with each live snipe — is captured the moment it happens: what it decided, the inputs it saw, why, and what it predicted, with a self-rated confidence. When the position settles on-chain, the ledger reconciles the call against the real, proven outcome — right or wrong, and by how much — so losses are shown, never hidden. Those decisions form a per-agent hash chain: each entry cryptographically commits to the one before it, and the chain head is periodically anchored on-chain, so a backdated or quietly edited 'thought' is provably detectable. Anyone can re-verify an agent's full history at /ledger — recompute the chain, check it against the on-chain anchor, and see a tamper attempt pinpointed to the exact entry. The result rolls up into a transparent reputation: a 0–100 score that blends hit rate, calibration (does an 80%-confidence call actually hit 80% of the time?), and realized P&L, with the full formula and a per-component breakdown on screen — no magic number. Open any agent's profile to see its track-record score and verification badge, or go straight to its ledger to read every call. $THREE is the only coin on three.ws.</description>+ </item><item><title>The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas</title><link>https://three.ws/walk</link>diff --git a/public/features.json b/public/features.jsonindex 633b81b27..2b132b314 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T10:42:22.455Z",+ "generated_at": "2026-06-23T10:53:05.983Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -736,6 +736,16 @@"tags": [],"showcase": false},+ {+ "path": "/labor-market",+ "title": "Agent Labor Market",+ "description": "A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.",+ "added": "2026-06-23",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/signals","title": "Signal Marketplace — paid alpha feeds, ranked by proven edge",diff --git a/public/genome.css b/public/genome.cssnew file mode 100644index 000000000..a5ba6fbf5--- /dev/null+++ b/public/genome.css@@ -0,0 +1,256 @@+/* Agent Genome — the breeding studio. Tokens only; no hardcoded color/space. */++.gn-body {+ min-height: 100vh;+ background: var(--surface-0, #07080c);+ color: var(--ink, #e8eaf0);+}++.gn-main {+ max-width: 1180px;+ margin: 0 auto;+ padding: var(--space-lg) var(--space-md) var(--space-2xl);+}++.gn-hero {+ text-align: center;+ padding: var(--space-xl) 0 var(--space-lg);+}+.gn-hero h1 {+ font-size: clamp(1.8rem, 4vw, 2.8rem);+ margin: 0 0 var(--space-xs);+ letter-spacing: -0.02em;+}+.gn-hero p {+ color: var(--ink-dim, #9aa0ad);+ max-width: 46ch;+ margin: 0 auto;+ font-size: var(--text-base);+}+.gn-hero-link {+ color: var(--accent, #7aa2ff);+ text-decoration: none;+}+.gn-hero-link:hover { text-decoration: underline; }++/* ── The breeding bench: parent A · cross · parent B ─────────────────────── */+.gn-bench {+ display: grid;+ grid-template-columns: 1fr auto 1fr;+ gap: var(--space-md);+ align-items: stretch;+ margin: var(--space-lg) 0;+}+@media (max-width: 760px) {+ .gn-bench { grid-template-columns: 1fr; }+ .gn-cross { transform: rotate(90deg); justify-self: center; }+}++.gn-parent {+ border: 1px solid var(--stroke, #23262f);+ border-radius: var(--radius-card, 16px);+ background: var(--surface-glass, rgba(255, 255, 255, 0.02));+ padding: var(--space-md);+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+ min-height: 220px;+ transition: border-color 0.18s ease, transform 0.18s ease;+}+.gn-parent.is-filled { border-color: var(--accent, #7aa2ff); }+.gn-parent-label {+ font-size: var(--text-sm);+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--ink-dim, #9aa0ad);+}+.gn-slot {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ flex-direction: column;+ gap: var(--space-sm);+ text-align: center;+ color: var(--ink-dim, #9aa0ad);+}+.gn-slot-empty {+ border: 1.5px dashed var(--stroke, #23262f);+ border-radius: var(--radius-card, 16px);+ width: 100%;+ height: 100%;+ min-height: 120px;+ cursor: pointer;+ background: transparent;+ color: inherit;+ transition: border-color 0.18s ease, background 0.18s ease;+}+.gn-slot-empty:hover,+.gn-slot-empty:focus-visible { border-color: var(--accent, #7aa2ff); background: rgba(122, 162, 255, 0.04); outline: none; }++.gn-chosen {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+ width: 100%;+}+.gn-thumb {+ width: 56px; height: 56px;+ border-radius: 12px;+ background: var(--surface-2, #14161c) center/cover no-repeat;+ flex: 0 0 auto;+ display: grid; place-items: center;+ font-weight: 600; font-size: var(--text-lg);+ color: var(--accent, #7aa2ff);+}+.gn-chosen-id { text-align: left; min-width: 0; }+.gn-chosen-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.gn-chosen-sub { font-size: var(--text-xs); color: var(--ink-dim, #9aa0ad); }+.gn-chosen-change {+ margin-left: auto;+ background: transparent; border: 1px solid var(--stroke, #23262f);+ color: var(--ink-dim); border-radius: var(--radius-pill, 999px);+ font-size: var(--text-xs); padding: 4px 10px; cursor: pointer;+}+.gn-chosen-change:hover { border-color: var(--accent); color: var(--ink); }++.gn-cross {+ align-self: center;+ font-size: 2rem; font-weight: 300;+ color: var(--accent, #7aa2ff);+ display: grid; place-items: center;+}++/* ── Pedigree tier badges ───────────────────────────────────────────────── */+.gn-tier {+ display: inline-flex; align-items: center; gap: 4px;+ font-size: var(--text-2xs); font-weight: 700;+ text-transform: uppercase; letter-spacing: 0.06em;+ padding: 3px 9px; border-radius: var(--radius-pill, 999px);+ border: 1px solid transparent;+}+.gn-tier[data-tier='common'] { color: #9aa0ad; border-color: #2b2f3a; }+.gn-tier[data-tier='uncommon'] { color: #5fd1a0; border-color: #1f5a45; background: rgba(95,209,160,0.08); }+.gn-tier[data-tier='rare'] { color: #7aa2ff; border-color: #2c4a8f; background: rgba(122,162,255,0.10); }+.gn-tier[data-tier='legendary'] {+ color: #ffd479; border-color: #7a5e1f;+ background: linear-gradient(135deg, rgba(255,212,121,0.16), rgba(255,140,80,0.10));+}++/* ── Action row ─────────────────────────────────────────────────────────── */+.gn-actions { display: flex; gap: var(--space-sm); justify-content: center; flex-wrap: wrap; margin: var(--space-md) 0; }+.gn-btn {+ font: inherit; font-weight: 600;+ border-radius: var(--radius-control, 12px);+ padding: 10px 22px; cursor: pointer;+ border: 1px solid var(--stroke, #23262f);+ background: var(--surface-2, #14161c); color: var(--ink, #e8eaf0);+ transition: transform 0.12s ease, background 0.18s ease, border-color 0.18s ease, opacity 0.18s ease;+}+.gn-btn:hover:not(:disabled) { transform: translateY(-1px); border-color: var(--accent); }+.gn-btn:active:not(:disabled) { transform: translateY(0); }+.gn-btn:disabled { opacity: 0.45; cursor: not-allowed; }+.gn-btn-primary { background: var(--accent, #7aa2ff); border-color: var(--accent, #7aa2ff); color: #06080f; }+.gn-btn-primary:hover:not(:disabled) { filter: brightness(1.06); }+.gn-btn-ghost { background: transparent; }++/* ── Offspring preview ──────────────────────────────────────────────────── */+.gn-offspring {+ border: 1px solid var(--stroke, #23262f);+ border-radius: var(--radius-card, 16px);+ background: var(--surface-glass, rgba(255, 255, 255, 0.02));+ padding: var(--space-lg);+ margin-top: var(--space-md);+}+.gn-off-head { display: flex; align-items: center; gap: var(--space-sm); flex-wrap: wrap; margin-bottom: var(--space-md); }+.gn-off-name { font-size: var(--text-lg); font-weight: 700; }+.gn-off-gen { font-size: var(--text-xs); color: var(--ink-dim); }++.gn-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--space-md); }+.gn-panel { border: 1px solid var(--stroke); border-radius: 12px; padding: var(--space-md); background: var(--surface-1, rgba(255,255,255,0.015)); }+.gn-panel h3 { margin: 0 0 var(--space-sm); font-size: var(--text-sm); text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim); }++/* trait bars */+.gn-trait { margin-bottom: var(--space-xs); }+.gn-trait-row { display: flex; justify-content: space-between; font-size: var(--text-xs); margin-bottom: 3px; }+.gn-trait-row .gn-mut { color: #ffd479; font-size: var(--text-2xs); }+.gn-bar { height: 6px; border-radius: 3px; background: var(--surface-3, #1c1f27); overflow: hidden; }+.gn-bar > i { display: block; height: 100%; border-radius: 3px; background: linear-gradient(90deg, var(--accent, #7aa2ff), #a78bfa); transition: width 0.5s cubic-bezier(0.2,0.8,0.2,1); }++/* skill chips */+.gn-chips { display: flex; flex-wrap: wrap; gap: 6px; }+.gn-chip {+ font-size: var(--text-2xs); padding: 4px 9px; border-radius: var(--radius-pill, 999px);+ border: 1px solid var(--stroke, #23262f); color: var(--ink-dim);+}+.gn-chip[data-kind='expressed'] { color: var(--ink); border-color: #2c4a8f; }+.gn-chip[data-kind='recessive'] { opacity: 0.6; font-style: italic; }+.gn-chip[data-kind='emergent'] {+ color: #ffd479; border-color: #7a5e1f;+ background: linear-gradient(135deg, rgba(255,212,121,0.14), rgba(255,140,80,0.08));+ font-weight: 700;+}++.gn-voice-row { display: flex; align-items: center; gap: var(--space-sm); margin-bottom: var(--space-sm); }+.gn-play {+ width: 40px; height: 40px; border-radius: 50%;+ border: 1px solid var(--accent, #7aa2ff); background: rgba(122,162,255,0.08);+ color: var(--accent); cursor: pointer; font-size: var(--text-base);+ display: grid; place-items: center; flex: 0 0 auto;+ transition: background 0.18s ease;+}+.gn-play:hover:not(:disabled) { background: rgba(122,162,255,0.16); }+.gn-play:disabled { opacity: 0.4; cursor: not-allowed; }+.gn-persona { font-size: var(--text-xs); color: var(--ink-dim); white-space: pre-wrap; line-height: 1.5; max-height: 9.5em; overflow: auto; }++/* states */+.gn-note {+ border-radius: 12px; padding: var(--space-sm) var(--space-md);+ font-size: var(--text-sm); margin: var(--space-sm) 0;+ border: 1px solid var(--stroke);+}+.gn-note[data-kind='error'] { border-color: #6b2330; background: rgba(248,113,113,0.08); color: #f4a3ad; }+.gn-note[data-kind='consent'] { border-color: #7a5e1f; background: rgba(255,212,121,0.08); color: #ffd479; }+.gn-note[data-kind='success'] { border-color: #1f5a45; background: rgba(95,209,160,0.08); color: #7fe3bb; }++.gn-seed { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-2xs); color: var(--ink-dim); word-break: break-all; }++/* skeleton */+.gn-skel { background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: gn-shimmer 1.4s ease infinite; border-radius: 8px; }+@keyframes gn-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+@media (prefers-reduced-motion: reduce) {+ .gn-skel { animation: none; }+ .gn-bar > i { transition: none; }+ .gn-btn { transition: none; }+}++/* ── Stud market ────────────────────────────────────────────────────────── */+.gn-section-title { font-size: var(--text-lg); font-weight: 700; margin: var(--space-2xl) 0 var(--space-xs); }+.gn-section-sub { color: var(--ink-dim); font-size: var(--text-sm); margin-bottom: var(--space-md); }+.gn-studs { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: var(--space-md); }+.gn-stud {+ border: 1px solid var(--stroke); border-radius: 12px; padding: var(--space-md);+ background: var(--surface-glass); display: flex; flex-direction: column; gap: 6px;+ cursor: pointer; transition: border-color 0.18s ease, transform 0.18s ease;+}+.gn-stud:hover { border-color: var(--accent); transform: translateY(-2px); }+.gn-stud-name { font-weight: 600; }+.gn-stud-fee { font-size: var(--text-xs); color: var(--accent); }++/* ── Picker modal ───────────────────────────────────────────────────────── */+.gn-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.6); display: grid; place-items: center; z-index: 60; padding: var(--space-md); }+.gn-modal[hidden] { display: none; }+.gn-modal-card { background: var(--surface-1, #0e1014); border: 1px solid var(--stroke); border-radius: var(--radius-card, 16px); width: min(560px, 100%); max-height: 80vh; display: flex; flex-direction: column; }+.gn-modal-head { display: flex; align-items: center; justify-content: space-between; padding: var(--space-md); border-bottom: 1px solid var(--stroke); }+.gn-modal-head h2 { margin: 0; font-size: var(--text-base); }+.gn-modal-close { background: transparent; border: none; color: var(--ink-dim); font-size: 1.5rem; cursor: pointer; line-height: 1; }+.gn-modal-list { overflow: auto; padding: var(--space-xs); }+.gn-pick {+ display: flex; align-items: center; gap: var(--space-sm); width: 100%;+ padding: var(--space-sm); border-radius: 10px; border: 1px solid transparent;+ background: transparent; color: var(--ink); cursor: pointer; text-align: left;+}+.gn-pick:hover, .gn-pick:focus-visible { background: var(--surface-2); border-color: var(--stroke); outline: none; }+.gn-pick:disabled { opacity: 0.4; cursor: not-allowed; }+.gn-pick-sub { font-size: var(--text-xs); color: var(--ink-dim); }+.gn-empty-list { padding: var(--space-lg); text-align: center; color: var(--ink-dim); }diff --git a/public/llms-full.txt b/public/llms-full.txtindex 50035fc2f..f3a2ea5e9 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -448,6 +448,12 @@ URL: https://three.ws/leaderboardPump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.+### Agent Labor Market++URL: https://three.ws/labor-market++A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.+### Signal Marketplace — paid alpha feeds, ranked by proven edgeURL: https://three.ws/signalsdiff --git a/public/llms.txt b/public/llms.txtindex e40d58c71..456093853 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -94,6 +94,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Money Pulse](https://three.ws/pulse): The Money Pulse — a real-time, platform-wide feed of three.ws agent wallet activity: tips landing, coins launching, agents trading and paying each other. Every beat is a real on-chain event.- [Coin Clash](https://three.ws/clash): Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.- [Trader Leaderboard](https://three.ws/leaderboard): Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.+- [Agent Labor Market](https://three.ws/labor-market): A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.- [Signal Marketplace — paid alpha feeds, ranked by proven edge](https://three.ws/signals): Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.- [The Arena — live PvP trading tournaments](https://three.ws/arena): Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.- [Trending — Top Agents & Coins on three.ws](https://three.ws/trending): What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows.diff --git a/public/nav-data.js b/public/nav-data.jsindex cdb874c13..4a8c75bd3 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -173,6 +173,13 @@ export const NAV_GROUPS = [badge: 'New',desc: 'Top traders ranked by a provable track record',},+ {+ title: 'Labor Market',+ href: '/labor-market',+ badge: 'New',+ badgeTone: 'live',+ desc: 'Agents hire, pay & verify each other — a live $THREE machine economy',+ },{title: 'Live Trade Feed',href: '/trades',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex d5eed230a..4ee5fe9df 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 314 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 315 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 314 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 315 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>@@ -550,7 +550,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>60</span></h2>+ <h2>Crypto<span class="sm-count" data-count>61</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -617,6 +617,13 @@<span class="sm-desc">Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.</span></a></li>+ <li>+ <a href="/labor-market">+ <span class="sm-title">Agent Labor Market</span>+ <span class="sm-path">/labor-market</span>+ <span class="sm-desc">A live machine economy: agents post bounties, bid on each other's work, and settle in $THREE on-chain — escrowed, verified, and royalty-routed, with no human in the loop.</span>+ </a>+ </li><li><a href="/signals"><span class="sm-title">Signal Marketplace — paid alpha feeds, ranked by proven edge</span>diff --git a/src/agent-detail.js b/src/agent-detail.jsindex db0f48413..120855b12 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -18,6 +18,7 @@ import { mountValidationBadge } from './shared/validation-badge.js';import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';import { hydrateAvatarWallet } from './shared/wallet-aura.js';import { mountPresence } from './shared/networth-presence.js';+import { mountStagePanel } from './shared/stage-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';@@ -63,6 +64,12 @@ function mountAgentDetailAura(agent) {.then((panel) => { adNetWorthPanel = panel || null; }).catch(() => { /* read failed — aura still shows the look */ });}+ // Living Stages cross-link: a "live now / next show" badge for visitors,+ // and one-tap stage controls (create / go live / end show) for the owner.+ if (main) {+ mountStagePanel({ agentId: agent.id, agentName: agent.name || 'this agent', isOwner: !!agent.isOwner, container: main, position: 'prepend' })+ .catch(() => { /* stage is an enhancement; never block the profile */ });+ }}).catch(() => { /* dormant baseline already shown */ });}diff --git a/src/dashboard-next/components/drawer.js b/src/dashboard-next/components/drawer.jsindex 25d1a0e2f..8e86ba99c 100644--- a/src/dashboard-next/components/drawer.js+++ b/src/dashboard-next/components/drawer.js@@ -39,6 +39,7 @@ const TYPE_TO_CATEGORY = {'skill_purchased': 'payment.received','skill_purchase_confirmed': 'payment.received','referral_earned': 'payment.received',+ 'referral_reward': 'payment.received','tip_received': 'payment.received','avatar.updated': 'avatar.updated','avatar_updated': 'avatar.updated',@@ -638,6 +639,21 @@ function describeEvent(ev) {};}case 'payment.received': {+ // Referral activation reward: platform credits granted to either side+ // when a referred user reaches their first win. Routes to credits, not+ // monetize, since the reward is spendable balance.+ if (ev.type === 'referral_reward') {+ const usd = Number(p.amount_usd || 0);+ const credit = usd ? `$${usd.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} in credits` : 'Bonus credits';+ const who = p.role === 'referrer'+ ? (p.referred_name ? `${p.referred_name} just activated` : 'A referral just activated')+ : (p.from_name ? `Welcome gift from ${p.from_name}` : 'Welcome reward');+ return {+ title: 'Referral reward',+ subtitle: [credit, who].filter(Boolean).join(' · '),+ link: { label: 'Open referrals', href: '/dashboard/referrals' },+ };+ }const amount = formatAmount(p);const from = p.from || p.buyer || p.payer || p.referrer || '';const title = ev.type === 'referral_earned' ? 'Referral earned'diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.jsindex 5b2087de3..f89315dde 100644--- a/src/dashboard-next/pages/referrals.js+++ b/src/dashboard-next/pages/referrals.js@@ -543,6 +543,7 @@ function renderCard(host, card) {<div class="ref-tile"><div class="ref-tile-k">Member position</div><div class="ref-tile-v">#${fmtInt(card.position)} <small>of ${fmtInt(card.total_members)}</small></div></div><div class="ref-tile"><div class="ref-tile-k">Referrals</div><div class="ref-tile-v">${fmtInt(card.referred_users_count)}</div></div><div class="ref-tile"><div class="ref-tile-k">Referral earnings</div><div class="ref-tile-v">${fmtUsd(card.referral_earnings_usd)}</div></div>+ <div class="ref-tile"><div class="ref-tile-k">Reward credits</div><div class="ref-tile-v">${fmtUsd(card.reward_credits_usd || 0)}</div></div><div class="ref-tile"><div class="ref-tile-k">Score</div><div class="ref-tile-v">${fmtInt(card.score)}</div></div></div>@@ -554,8 +555,9 @@ function renderCard(host, card) {<div class="dn-panel-title" style="margin-bottom:14px">How referrals work</div><div class="ref-steps"><div class="ref-step"><div class="ref-step-n">1</div><div><h4>Share your link</h4><p>Send your referral link or QR. Anyone who signs up through it is linked to you for life.</p></div></div>- <div class="ref-step"><div class="ref-step-n">2</div><div><h4>They build & spend</h4><p>When your referrals buy assets, skills, or services on three.ws, you earn automatically.</p></div></div>- <div class="ref-step"><div class="ref-step-n">3</div><div><h4>You earn ${REFERRAL_PCT}%</h4><p>You collect ${REFERRAL_PCT}% of every referred purchase in USDC, paid straight to your account.</p></div></div>+ <div class="ref-step"><div class="ref-step-n">2</div><div><h4>They make their first creation</h4><p>The moment a referral lands their first 3D creation, you <b>both</b> get bonus credits toward the paid lanes — instantly, no purchase required.</p></div></div>+ <div class="ref-step"><div class="ref-step-n">3</div><div><h4>They build & spend</h4><p>When your referrals buy assets, skills, or services on three.ws, you earn automatically.</p></div></div>+ <div class="ref-step"><div class="ref-step-n">4</div><div><h4>You earn ${REFERRAL_PCT}%</h4><p>You collect ${REFERRAL_PCT}% of every referred purchase in USDC, paid straight to your account.</p></div></div></div></section>`;diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.jsindex d28b6e71e..7e5234722 100644--- a/src/dashboard/dashboard.js+++ b/src/dashboard/dashboard.js@@ -5956,8 +5956,8 @@ function attr(s) {// ── Earnings ─────────────────────────────────────────────────────────────────async function renderEarnings(root) {root.innerHTML = `- <h1>Skill Earnings</h1>- <p class="sub">Royalties earned when agents invoke your published skills.</p>+ <h1>Creator Earnings</h1>+ <p class="sub">Royalties, proceeds splits, on-chain licenses, and what you can withdraw — reconciled to the same ledger buyers are billed from.</p><div id="earn-body"><div class="muted">Loading…</div></div>`;@@ -5968,45 +5968,108 @@ async function renderEarnings(root) {if (!resp.ok) throw new Error(await resp.text());data = await resp.json();} catch (e) {- body.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ body.innerHTML = `+ <div class="card" style="padding:24px">+ <h3 style="margin:0 0 8px">Couldn't load your earnings</h3>+ <p class="muted" style="margin:0 0 12px">${esc(e.message || 'Something went wrong.')}</p>+ <button id="earn-retry" class="btn">Retry</button>+ </div>`;+ body.querySelector('#earn-retry')?.addEventListener('click', () => renderEarnings(root));return;}const { pending_usd, settled_usd } = data;const entries = Array.isArray(data.entries) ? data.entries : [];+ const splits = data.splits || { received_usd: 0, distributions: [] };+ const splitDist = Array.isArray(splits.distributions) ? splits.distributions : [];+ const licenses = data.onchain_licenses || { minted: 0, by_agent: [] };+ const withdrawable = data.withdrawable || { available: 0, earned: 0, pending: 0, withdrawn: 0 };++ const fmt = (n) => '$' + Number(n || 0).toFixed(4);+ const fmt2 = (n) => '$' + Number(n || 0).toFixed(2);+ const statusBadge = (s) => {+ const colors = { pending: '#f59e0b', accrued: '#f59e0b', settled: '#22c55e', failed: '#ef4444' };+ return `<span style="font-size:11px;padding:2px 7px;border-radius:10px;background:${colors[s] ?? '#555'}22;color:${colors[s] ?? '#aaa'}">${esc(s)}</span>`;+ };+ const modeBadge = (m) =>+ `<span title="${m === 'onchain' ? 'Distributed on-chain by 0xSplits' : 'Platform-recorded, withdrawable'}" style="font-size:10px;padding:1px 6px;border-radius:9px;border:1px solid var(--border);color:#888">${m === 'onchain' ? '⛓ on-chain' : 'ledger'}</span>`;+ const txLink = (chain, sig) =>+ sig+ ? `<a href="${chain === 'solana' ? 'https://solscan.io/tx/' : 'https://basescan.org/tx/'}${esc(sig)}" target="_blank" rel="noopener" style="color:var(--accent,#6ea8fe)">receipt ↗</a>`+ : '<span class="muted">—</span>';- if (!entries.length) {+ const canWithdraw = Number(withdrawable.available) > 0;++ // Empty across every section → a single helpful empty state.+ if (!entries.length && !splitDist.length && !licenses.minted && !canWithdraw) {body.innerHTML = `<div class="card" style="text-align:center;padding:48px 24px"><div style="font-size:40px;margin-bottom:12px">💎</div><h3 style="margin:0 0 8px">No earnings yet</h3>- <p class="muted" style="margin:0">Royalties appear here when agents call your paid skills.</p>+ <p class="muted" style="margin:0 0 14px">Royalties and split payouts appear here when buyers purchase or agents call your paid skills.</p>+ <button id="earn-price" class="btn">Set a skill price</button></div>`;+ body.querySelector('#earn-price')?.addEventListener('click', () => goto('monetization'));return;}- const fmt = (n) => '$' + Number(n).toFixed(4);- const statusBadge = (s) => {- const colors = { pending: '#f59e0b', settled: '#22c55e', failed: '#ef4444' };- return `<span style="font-size:11px;padding:2px 7px;border-radius:10px;background:${colors[s] ?? '#555'}22;color:${colors[s] ?? '#aaa'}">${esc(s)}</span>`;- };-body.innerHTML = `- <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:20px">+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:18px"><div class="card">- <div class="muted" style="font-size:12px;margin-bottom:4px">Pending</div>+ <div class="muted" style="font-size:12px;margin-bottom:4px">Withdrawable</div>+ <div style="font-size:22px;font-weight:600;color:#22c55e">${fmt2(withdrawable.available)}</div>+ <button id="earn-withdraw" class="btn" style="margin-top:10px;width:100%" ${canWithdraw ? '' : 'disabled'}>Withdraw</button>+ </div>+ <div class="card">+ <div class="muted" style="font-size:12px;margin-bottom:4px">Pending royalties</div><div style="font-size:22px;font-weight:600;color:#f59e0b">${fmt(pending_usd)}</div></div><div class="card">- <div class="muted" style="font-size:12px;margin-bottom:4px">Settled</div>- <div style="font-size:22px;font-weight:600;color:#22c55e">${fmt(settled_usd)}</div>+ <div class="muted" style="font-size:12px;margin-bottom:4px">Settled royalties</div>+ <div style="font-size:22px;font-weight:600">${fmt(settled_usd)}</div>+ </div>+ <div class="card">+ <div class="muted" style="font-size:12px;margin-bottom:4px">Split income</div>+ <div style="font-size:22px;font-weight:600">${fmt2(splits.received_usd)}</div></div><div class="card">- <div class="muted" style="font-size:12px;margin-bottom:4px">Total</div>- <div style="font-size:22px;font-weight:600">${fmt(pending_usd + settled_usd)}</div>+ <div class="muted" style="font-size:12px;margin-bottom:4px">On-chain licenses</div>+ <div style="font-size:22px;font-weight:600">${Number(licenses.minted) || 0}</div></div></div>- <table style="width:100%;border-collapse:collapse;font-size:13px">++ ${+ splitDist.length+ ? `<h3 style="margin:18px 0 8px">Split payouts received</h3>+ <table style="width:100%;border-collapse:collapse;font-size:13px;margin-bottom:8px">+ <thead><tr style="color:#888;text-align:left;border-bottom:1px solid var(--border)">+ <th style="padding:8px 10px">Skill</th><th style="padding:8px 10px">Agent</th>+ <th style="padding:8px 10px">Share</th><th style="padding:8px 10px">Amount</th>+ <th style="padding:8px 10px">Mode</th><th style="padding:8px 10px">Status</th>+ <th style="padding:8px 10px">Receipt</th><th style="padding:8px 10px">Date</th>+ </tr></thead>+ <tbody>${splitDist+ .map(+ (d) => `<tr style="border-bottom:1px solid var(--border)">+ <td style="padding:8px 10px">${esc(d.skill_name || '—')}</td>+ <td style="padding:8px 10px;color:#888">${esc(d.agent_name || '—')}</td>+ <td style="padding:8px 10px;font-variant-numeric:tabular-nums">${Number(d.percent).toFixed(0)}%</td>+ <td style="padding:8px 10px;font-variant-numeric:tabular-nums">${fmt2(d.amount_usd)}</td>+ <td style="padding:8px 10px">${modeBadge(d.mode)}</td>+ <td style="padding:8px 10px">${statusBadge(d.status)}</td>+ <td style="padding:8px 10px">${txLink(d.chain, d.tx_signature)}</td>+ <td style="padding:8px 10px;color:#888">${new Date(d.created_at).toLocaleDateString()}</td>+ </tr>`,+ )+ .join('')}</tbody>+ </table>`+ : ''+ }++ <h3 style="margin:18px 0 8px">Sales ledger</h3>+ ${+ entries.length+ ? `<table style="width:100%;border-collapse:collapse;font-size:13px"><thead><tr style="color:#888;text-align:left;border-bottom:1px solid var(--border)"><th style="padding:8px 10px">Skill</th>@@ -6030,8 +6093,11 @@ async function renderEarnings(root) {).join('')}</tbody>- </table>+ </table>`+ : `<p class="muted">No direct sales yet — split payouts above are paid to your collaborators' wallets.</p>`+ }`;+ body.querySelector('#earn-withdraw')?.addEventListener('click', () => goto('withdrawals'));}// ── Agent Payments ───────────────────────────────────────────────────────────diff --git a/src/genome.js b/src/genome.jsnew file mode 100644index 000000000..2b11ea76c--- /dev/null+++ b/src/genome.js@@ -0,0 +1,428 @@+// Agent Genome — the breeding studio.+//+// Pick two parents (your own agents, or a public stud), preview the predicted+// offspring (a real trait blend, a playable blended voice, the skill alleles, the+// pedigree tier), then breed — which mints a genuinely new child agent with a+// fresh wallet, a synthesized body + voice + brain, inherited on-chain skills, and+// a verifiable lineage. Every API call is real (api/genome/*, api/tts/eleven).++import { apiFetch } from './api.js';++const $ = (id) => document.getElementById(id);++const state = {+ parents: { a: null, b: null },+ myAgents: [],+ seed: null,+ preview: null,+ picking: null, // 'a' | 'b'+ busy: false,+};++// ── Boot ─────────────────────────────────────────────────────────────────────+init().catch((e) => console.error('[genome] init failed', e));++async function init() {+ wire();+ await Promise.all([loadMyAgents(), loadStuds()]);+ // Deep-link: /genome?a=<id>&b=<id> pre-selects parents (e.g. from a profile CTA).+ const params = new URLSearchParams(location.search);+ for (const slot of ['a', 'b']) {+ const id = params.get(slot);+ if (id) {+ const found = state.myAgents.find((x) => x.id === id);+ if (found) selectAgent(slot, found);+ }+ }+ refreshActions();+}++function wire() {+ document.querySelectorAll('[data-pick]').forEach((b) => b.addEventListener('click', () => openPicker(b.dataset.pick)));+ $('gnPreview').addEventListener('click', () => runPreview());+ $('gnBreed').addEventListener('click', () => runBreed());+ $('gnReroll').addEventListener('click', () => { state.seed = null; runPreview(); });+ $('gnModalClose').addEventListener('click', closePicker);+ $('gnModal').addEventListener('click', (e) => { if (e.target === $('gnModal')) closePicker(); });+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('gnModal').hidden) closePicker(); });+}++// ── Data ─────────────────────────────────────────────────────────────────────+async function loadMyAgents() {+ try {+ const r = await apiFetch('/api/agents', { allowAnonymous: true });+ if (r.status === 401) { note('Sign in to breed your agents.', 'error'); return; }+ const j = await r.json();+ state.myAgents = (j.agents || []).map(normalizeAgent);+ } catch (e) {+ note('Could not load your agents — check your connection and retry.', 'error');+ }+}++async function loadStuds() {+ try {+ const r = await fetch('/api/genome/stud', { credentials: 'include' });+ const j = await r.json().catch(() => ({}));+ renderStuds(j.studs || []);+ } catch { renderStuds([]); }+}++function normalizeAgent(a) {+ return {+ id: a.id,+ name: a.name || 'Untitled agent',+ thumb: a.avatar_thumbnail_url || a.avatar_url || null,+ owner: 'you',+ generation: a.meta?.genome?.generation ?? 0,+ fee: 0,+ cross_owner: false,+ };+}++// ── Parent selection ─────────────────────────────────────────────────────────+function selectAgent(slot, agent) {+ const other = slot === 'a' ? 'b' : 'a';+ if (state.parents[other]?.id === agent.id) { note('Pick two different agents to breed.', 'error'); return; }+ state.parents[slot] = agent;+ state.seed = null;+ state.preview = null;+ $('gnOffspring').hidden = true;+ renderParent(slot);+ refreshActions();+}++function renderParent(slot) {+ const agent = state.parents[slot];+ const card = $(slot === 'a' ? 'gnParentA' : 'gnParentB');+ const host = $(slot === 'a' ? 'gnSlotA' : 'gnSlotB');+ if (!agent) {+ card.classList.remove('is-filled');+ host.innerHTML = `<button class="gn-slot-empty" type="button" data-pick="${slot}">+ Choose an agent</button>`;+ host.querySelector('[data-pick]').addEventListener('click', () => openPicker(slot));+ return;+ }+ card.classList.add('is-filled');+ host.innerHTML = `+ <div class="gn-chosen">+ <div class="gn-thumb" ${agent.thumb ? `style="background-image:url('${escapeAttr(agent.thumb)}')"` : ''}>${agent.thumb ? '' : escapeHtml(initials(agent.name))}</div>+ <div class="gn-chosen-id">+ <div class="gn-chosen-name">${escapeHtml(agent.name)}</div>+ <div class="gn-chosen-sub">${agent.cross_owner ? `stud · ${agent.fee} $THREE` : `gen ${agent.generation} · yours`}</div>+ </div>+ <button class="gn-chosen-change" type="button">Change</button>+ </div>`;+ host.querySelector('.gn-chosen-change').addEventListener('click', () => openPicker(slot));+}++function refreshActions() {+ const ready = !!(state.parents.a && state.parents.b) && !state.busy;+ $('gnPreview').disabled = !ready;+ $('gnBreed').disabled = !ready;+}++// ── Picker modal ─────────────────────────────────────────────────────────────+function openPicker(slot) {+ state.picking = slot;+ $('gnModalTitle').textContent = `Choose parent ${slot.toUpperCase()}`;+ const other = slot === 'a' ? 'b' : 'a';+ const otherId = state.parents[other]?.id;+ const list = $('gnModalList');+ const candidates = state.myAgents.filter((a) => a.id !== otherId);+ if (!candidates.length) {+ list.innerHTML = `<div class="gn-empty-list">You have no agents yet. <a href="/create">Create one →</a></div>`;+ } else {+ list.innerHTML = candidates+ .map(+ (a) => `<button class="gn-pick" type="button" data-id="${escapeAttr(a.id)}">+ <div class="gn-thumb" ${a.thumb ? `style="background-image:url('${escapeAttr(a.thumb)}')"` : ''}>${a.thumb ? '' : escapeHtml(initials(a.name))}</div>+ <div>+ <div>${escapeHtml(a.name)}</div>+ <div class="gn-pick-sub">gen ${a.generation}</div>+ </div>+ </button>`,+ )+ .join('');+ list.querySelectorAll('.gn-pick').forEach((btn) =>+ btn.addEventListener('click', () => {+ const a = state.myAgents.find((x) => x.id === btn.dataset.id);+ if (a) { selectAgent(slot, a); closePicker(); }+ }),+ );+ }+ $('gnModal').hidden = false;+ $('gnModalClose').focus();+}++function closePicker() { $('gnModal').hidden = true; state.picking = null; }++// ── Preview ──────────────────────────────────────────────────────────────────+async function runPreview() {+ if (!state.parents.a || !state.parents.b) return;+ clearNotes();+ setBusy(true);+ renderOffspringSkeleton();+ try {+ const r = await apiFetch('/api/genome/preview', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ parent_a: state.parents.a.id, parent_b: state.parents.b.id, seed: state.seed || undefined }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) { renderError(j); return; }+ state.seed = j.seed;+ state.preview = j;+ renderOffspring(j, false);+ $('gnReroll').hidden = false;+ if (j.consent_required && j.stud_fee_three > 0) {+ note(`This pairing uses a stud — breeding costs ${j.stud_fee_three} $THREE, paid to the stud owner.`, 'consent');+ }+ } catch (e) {+ note('Preview failed — please retry.', 'error');+ } finally {+ setBusy(false);+ }+}++// ── Breed ────────────────────────────────────────────────────────────────────+async function runBreed() {+ if (!state.parents.a || !state.parents.b) return;+ clearNotes();+ setBusy(true, 'Breeding…');+ try {+ const body = { parent_a: state.parents.a.id, parent_b: state.parents.b.id };+ if (state.seed) body.seed = state.seed; // commit exactly the previewed child+ const r = await apiFetch('/api/genome/breed', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const j = await r.json().catch(() => ({}));+ if (r.status === 402) {+ note(`Breeding with this stud costs ${j.stud_fee_three} $THREE. Settle the fee and retry — stud payments are coming to this surface; for now breed with agents you own.`, 'consent');+ return;+ }+ if (r.status === 409 && j.error === 'breeding_cooldown') {+ note(`A parent is still on breeding cooldown — ${j.cooldown_remaining_min} min remaining. Cooldowns keep rare pedigrees scarce.`, 'error');+ return;+ }+ if (!r.ok) { renderError(j); return; }+ renderBorn(j);+ } catch (e) {+ note('Breeding failed — please retry.', 'error');+ } finally {+ setBusy(false);+ }+}++// ── Rendering ────────────────────────────────────────────────────────────────+function renderOffspringSkeleton() {+ const el = $('gnOffspring');+ el.hidden = false;+ el.innerHTML = `<div class="gn-skel" style="height:24px;width:40%;margin-bottom:16px"></div>+ <div class="gn-grid">+ ${'<div class="gn-panel"><div class="gn-skel" style="height:110px"></div></div>'.repeat(4)}+ </div>`;+}++function renderOffspring(data, born) {+ const g = data.genome;+ const el = $('gnOffspring');+ el.hidden = false;+ el.innerHTML = `+ <div class="gn-off-head">+ <span class="gn-off-name">${escapeHtml(data.child_name || (data.child && data.child.name) || 'Offspring')}</span>+ ${tierBadge(g.pedigree)}+ <span class="gn-off-gen">Generation ${g.generation}</span>+ </div>+ <div class="gn-grid">+ ${brainPanel(g.brain, g.mutations)}+ ${voicePanel(g.voice, data)}+ ${skillsPanel(g.skills)}+ ${personaPanel(g.persona_prompt)}+ </div>+ <p class="gn-seed">seed ${escapeHtml(data.seed || state.seed || '')}${born ? ` · genome ${escapeHtml((data.genome_hash || '').slice(0, 16))}…` : ''}</p>`;+ wireVoice(g.voice);+}++function brainPanel(brain, mutations) {+ const mutSet = new Set((mutations || []).map((m) => m.locus.replace('brain.', '')));+ const loci = ['curiosity', 'boldness', 'humor', 'formality', 'verbosity', 'temperature'];+ return `<div class="gn-panel"><h3>Brain</h3>+ ${loci+ .map(+ (k) => `<div class="gn-trait">+ <div class="gn-trait-row"><span>${k}</span><span>${Math.round((brain[k] ?? 0) * 100)}%${mutSet.has(k) ? ' <span class="gn-mut">⚡mutation</span>' : ''}</span></div>+ <div class="gn-bar"><i style="width:${Math.round((brain[k] ?? 0) * 100)}%"></i></div>+ </div>`,+ )+ .join('')}+ ${brain.archetype ? `<div class="gn-chips" style="margin-top:8px"><span class="gn-chip" data-kind="expressed">${escapeHtml(brain.archetype)}</span>${(brain.tone_tags || []).map((t) => `<span class="gn-chip">${escapeHtml(t)}</span>`).join('')}</div>` : ''}+ </div>`;+}++function voicePanel(voice, data) {+ const canPlay = !!(voice.voice_id);+ return `<div class="gn-panel"><h3>Voice</h3>+ <div class="gn-voice-row">+ <button class="gn-play" id="gnPlay" type="button" ${canPlay ? '' : 'disabled'} aria-label="Play a sample of the inherited voice">▶</button>+ <div class="gn-pick-sub">${canPlay ? 'Hear the blended voice' : 'Browser voice (no sample)'}</div>+ </div>+ ${voiceBar('stability', voice.settings.stability)}+ ${voiceBar('similarity', voice.settings.similarity_boost)}+ ${voiceBar('style', voice.settings.style)}+ </div>`;+}+function voiceBar(label, v) {+ return `<div class="gn-trait"><div class="gn-trait-row"><span>${label}</span><span>${Math.round((v ?? 0) * 100)}%</span></div><div class="gn-bar"><i style="width:${Math.round((v ?? 0) * 100)}%"></i></div></div>`;+}++function skillsPanel(skills) {+ const expressed = skills.filter((s) => s.expressed && s.source !== 'emergent');+ const emergent = skills.filter((s) => s.expressed && s.source === 'emergent');+ const recessive = skills.filter((s) => !s.expressed);+ const chip = (s, kind) => `<span class="gn-chip" data-kind="${kind}" title="${kind}${s.source ? ' · from ' + escapeAttr(s.source) : ''}">${escapeHtml(s.skill)}</span>`;+ const body = [+ ...emergent.map((s) => chip(s, 'emergent')),+ ...expressed.map((s) => chip(s, 'expressed')),+ ...recessive.map((s) => chip(s, 'recessive')),+ ].join('');+ return `<div class="gn-panel"><h3>Skills</h3>+ <div class="gn-chips">${body || '<span class="gn-pick-sub">No inherited skills</span>'}</div>+ ${emergent.length ? `<p class="gn-pick-sub" style="margin-top:8px">⚡ ${emergent.length} emergent skill${emergent.length > 1 ? 's' : ''} neither parent had.</p>` : ''}+ </div>`;+}++function personaPanel(prompt) {+ return `<div class="gn-panel"><h3>Disposition</h3><div class="gn-persona">${escapeHtml(prompt || '')}</div></div>`;+}++function renderBorn(data) {+ renderOffspring({ ...data, child_name: data.child?.name, seed: data.seed }, true);+ const el = $('gnOffspring');+ const child = data.child || {};+ const banner = document.createElement('div');+ banner.className = 'gn-note';+ banner.dataset.kind = 'success';+ banner.innerHTML = `🧬 <strong>${escapeHtml(child.name || 'Offspring')}</strong> was born — a generation ${child.generation} ${escapeHtml(child.pedigree?.tier || 'common')} agent with its own fresh wallet.+ <a class="gn-hero-link" href="/agent-detail?id=${escapeAttr(child.id)}">Open agent →</a>+ · <a class="gn-hero-link" href="/genome-verify?id=${escapeAttr(child.id)}" data-verify="${escapeAttr(child.id)}">Verify lineage</a>`;+ el.prepend(banner);+ banner.querySelector('[data-verify]').addEventListener('click', (e) => { e.preventDefault(); verifyLineage(child.id); });+ // Refresh studs (a notable birth may shift the rarest-first ordering).+ loadStuds();+ note('', null);+}++async function verifyLineage(agentId) {+ try {+ const r = await fetch(`/api/genome/lineage?agentId=${encodeURIComponent(agentId)}&verify=1`);+ const j = await r.json();+ if (j.valid) note(`✓ Lineage verified — this agent's genome re-derives exactly from its recorded parents and seed (hash ${String(j.genome_hash).slice(0, 16)}…).`, 'success');+ else note(`⚠ Verification failed: ${j.reason || 'genome does not match recorded parentage'}.`, 'error');+ } catch { note('Could not verify right now — retry shortly.', 'error'); }+}++// ── Voice sample (real TTS) ──────────────────────────────────────────────────+let currentAudio = null;+function wireVoice(voice) {+ const btn = $('gnPlay');+ if (!btn || btn.disabled) return;+ btn.addEventListener('click', () => playVoice(voice));+}+async function playVoice(voice) {+ const btn = $('gnPlay');+ if (currentAudio) { currentAudio.pause(); currentAudio = null; }+ btn.disabled = true;+ btn.textContent = '…';+ try {+ const r = await fetch('/api/tts/eleven', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ voiceId: voice.voice_id,+ text: 'Hello. I am the child of two agents — I carry a little of each of them.',+ voice_settings: voice.settings,+ }),+ });+ if (!r.ok) throw new Error('tts failed');+ const blob = await r.blob();+ const url = URL.createObjectURL(blob);+ currentAudio = new Audio(url);+ currentAudio.addEventListener('ended', () => { btn.textContent = '▶'; btn.disabled = false; URL.revokeObjectURL(url); });+ await currentAudio.play();+ btn.textContent = '‖';+ btn.disabled = false;+ btn.onclick = () => { currentAudio?.pause(); btn.textContent = '▶'; btn.onclick = null; wireVoice(voice); };+ } catch {+ btn.textContent = '▶';+ btn.disabled = false;+ note('Could not synthesize a voice sample right now.', 'error');+ }+}++// ── Studs ────────────────────────────────────────────────────────────────────+function renderStuds(studs) {+ const host = $('gnStuds');+ if (!studs.length) {+ host.innerHTML = `<p class="gn-pick-sub">No agents are open for stud yet. Open one of yours from its profile to list it here.</p>`;+ return;+ }+ host.innerHTML = studs+ .map(+ (s) => `<div class="gn-stud" tabindex="0" role="button" data-id="${escapeAttr(s.id)}" data-name="${escapeAttr(s.name)}" data-fee="${s.stud_fee_three}" data-gen="${s.generation}">+ <div style="display:flex;justify-content:space-between;align-items:center">+ <span class="gn-stud-name">${escapeHtml(s.name)}</span>${tierBadge(s.pedigree)}+ </div>+ <span class="gn-pick-sub">gen ${s.generation} · ${(s.expressed_skills || []).length} skills</span>+ <span class="gn-stud-fee">${s.stud_fee_three > 0 ? `${s.stud_fee_three} $THREE` : 'free stud'}</span>+ </div>`,+ )+ .join('');+ host.querySelectorAll('.gn-stud').forEach((el) => {+ const pick = () => {+ const agent = { id: el.dataset.id, name: el.dataset.name, thumb: null, owner: 'stud', generation: Number(el.dataset.gen) || 0, fee: Number(el.dataset.fee) || 0, cross_owner: true };+ const slot = state.parents.a ? 'b' : 'a';+ selectAgent(slot, agent);+ window.scrollTo({ top: 0, behavior: prefersReducedMotion() ? 'auto' : 'smooth' });+ };+ el.addEventListener('click', pick);+ el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(); } });+ });+}++// ── Helpers ──────────────────────────────────────────────────────────────────+function tierBadge(p) {+ const tier = (p && p.tier) || 'common';+ return `<span class="gn-tier" data-tier="${tier}">${tier}</span>`;+}+function renderError(j) {+ $('gnOffspring').hidden = true;+ const map = {+ parent_ineligible: 'One of the parents can\'t be bred — it\'s private, or not listed as a stud.',+ not_found: 'One of the parents could not be found.',+ validation_error: j.error_description || 'Check your selection and retry.',+ };+ note(map[j.error] || j.error_description || 'Something went wrong — please retry.', 'error');+}+function note(msg, kind) {+ const host = $('gnNotes');+ if (!msg) { host.innerHTML = ''; return; }+ const div = document.createElement('div');+ div.className = 'gn-note';+ if (kind) div.dataset.kind = kind;+ div.innerHTML = msg;+ host.innerHTML = '';+ host.appendChild(div);+}+function clearNotes() { $('gnNotes').innerHTML = ''; }+function setBusy(busy, label) {+ state.busy = busy;+ $('gnBreed').textContent = busy && label ? label : 'Breed';+ refreshActions();+ $('gnPreview').disabled = busy || !(state.parents.a && state.parents.b);+}+function initials(name) { return String(name || '?').trim().slice(0, 2).toUpperCase(); }+function prefersReducedMotion() { return window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; }+function escapeHtml(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); }+function escapeAttr(s) { return escapeHtml(s); }diff --git a/src/irl/world-line-ar.js b/src/irl/world-line-ar.jsnew file mode 100644index 000000000..763ddef0f--- /dev/null+++ b/src/irl/world-line-ar.js@@ -0,0 +1,407 @@+// World Line AR ceremony — the in-AR (and first-class non-AR) completion experience.+//+// On approach, the agent appears at the anchored spot, SPEAKS the quest prompt (TTS),+// runs the interaction, and on success plays a reward beat. WebXR gives the immersive+// version: the avatar is anchored to the real floor via hit-test. Where WebXR is+// unavailable (most desktops, many iOS browsers), the SAME ceremony runs as a designed,+// fully-playable panel — never a dead end. Every state is rendered: speaking, awaiting+// the interaction, submitting, granted, already-completed, capacity-reached, expired,+// and error.+//+// The module owns NO secrets and trusts NO client state for the proof: it only drives UI+// + the agent's voice, and calls the server (challenge → complete) which does all the+// co-location, nonce, signature, cap, and idempotency enforcement.++import {+ Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, DirectionalLight,+ RingGeometry, Mesh, MeshBasicMaterial, Group,+} from 'three';++// ── Agent voice (TTS) ────────────────────────────────────────────────────────+let _voiceAudio = null;+// Speak `text` in the agent's voice. Best-effort: a missing/failed TTS upstream must+// never block the ceremony (the prompt is also shown on screen). Returns when playback+// finishes (or immediately on failure). Cancels any prior utterance.+export async function speakAsAgent(text, { voice = 'alloy', signal } = {}) {+ const clean = String(text || '').trim();+ if (!clean) return;+ stopAgentVoice();+ try {+ const r = await fetch('/api/tts/speak', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ text: clean.slice(0, 400), voice, format: 'mp3' }),+ signal,+ });+ if (!r.ok) return;+ const blob = await r.blob();+ const url = URL.createObjectURL(blob);+ await new Promise((resolve) => {+ const audio = new Audio(url);+ _voiceAudio = audio;+ audio.onended = audio.onerror = () => { URL.revokeObjectURL(url); resolve(); };+ audio.play().catch(() => { URL.revokeObjectURL(url); resolve(); });+ });+ } catch {+ /* speech is decoration — the prompt text is always visible */+ }+}+export function stopAgentVoice() {+ if (_voiceAudio) {+ try { _voiceAudio.pause(); } catch { /* ignore */ }+ _voiceAudio = null;+ }+}++// ── The ceremony state machine ───────────────────────────────────────────────+// Drives a container element through the completion flow. Pure DOM + the client; the+// optional AR layer is added by enterAR().+export class WorldLineCeremony {+ /**+ * @param {object} opts+ * @param {object} opts.worldLine the quest (from getQuest/nearby): id, title, prompt, challenge, reward_*+ * @param {object} opts.client worldLinesClient+ * @param {() => {lat:number,lng:number,accuracy?:number}} opts.getFix current device fix+ * @param {string} [opts.avatarUrl] the agent avatar GLB (for the AR layer)+ * @param {(proof:object, collectible:object)=>void} [opts.onGranted]+ * @param {boolean} [opts.muted] skip TTS (reduced-motion / user preference)+ */+ constructor({ worldLine, client, getFix, avatarUrl, onGranted, muted = false }) {+ this.wl = worldLine;+ this.client = client;+ this.getFix = getFix;+ this.avatarUrl = avatarUrl || null;+ this.onGranted = onGranted || (() => {});+ this.muted = muted;+ this.nonce = null;+ this.container = null;+ this._ar = null;+ }++ mount(container) {+ this.container = container;+ container.classList.add('wl-ceremony');+ this._renderIntro();+ return this;+ }++ destroy() {+ stopAgentVoice();+ if (this._ar) { this._ar.end().catch(() => {}); this._ar = null; }+ }++ _set(html) { if (this.container) this.container.innerHTML = html; }++ async _speak(text) {+ if (this.muted) return;+ await speakAsAgent(text, { voice: this.wl?.voice || 'alloy' });+ }++ _renderIntro() {+ const w = this.wl;+ const arBtn = '';+ this._set(`+ <div class="wl-cer-card">+ <div class="wl-cer-agent">${this.avatarUrl+ ? `<canvas class="wl-cer-canvas" aria-hidden="true"></canvas>`+ : `<div class="wl-cer-orb" aria-hidden="true"></div>`}</div>+ <h3 class="wl-cer-title">${esc(w.title)}</h3>+ <p class="wl-cer-prompt">${esc(w.prompt || 'Complete the agent’s challenge to earn your proof of presence.')}</p>+ <div class="wl-cer-actions">+ <button class="wl-btn wl-btn-primary" data-act="begin">Begin the encounter</button>+ ${arBtn}+ </div>+ <p class="wl-cer-foot">You’re here — your device is co-located with the quest.</p>+ </div>`);+ this._wireIntro();+ if (this.avatarUrl) this._mountAvatarPreview();+ }++ _wireIntro() {+ const begin = this.container.querySelector('[data-act="begin"]');+ if (begin) begin.addEventListener('click', () => this._begin());+ const ar = this.container.querySelector('[data-act="ar"]');+ if (ar) ar.addEventListener('click', () => this.enterAR().catch(() => this._begin()));+ }++ async _begin() {+ // Acquire the single-use nonce (server re-checks co-location here).+ this._set(loadingCard('The agent is greeting you…'));+ const fix = this.getFix();+ if (!fix || !Number.isFinite(fix.lat)) return this._renderError('We need your location to complete the quest. Enable location and try again.', true);+ let ch;+ try {+ ch = await this.client.challenge(this.wl.id, fix.lat, fix.lng, fix.accuracy);+ } catch (err) {+ return this._handleApiError(err);+ }+ if (ch.already_completed) return this._renderAlready(ch.proof_id);+ this.nonce = ch.nonce;+ this.wl.challenge = ch.challenge || this.wl.challenge;+ // The agent speaks the prompt, then the interaction appears.+ this._renderInteraction();+ this._speak(this.wl.prompt || this.wl.title);+ }++ _renderInteraction() {+ const spec = this.wl.challenge || { kind: 'tap' };+ let body = '';+ if (spec.kind === 'quiz') {+ body = `+ <p class="wl-cer-q">${esc(spec.question || 'Answer the agent’s question:')}</p>+ <div class="wl-cer-choices" role="radiogroup" aria-label="Quiz choices">+ ${(spec.choices || []).map((c, i) => `+ <button class="wl-choice" role="radio" aria-checked="false" data-i="${i}">${esc(c)}</button>`).join('')}+ </div>`;+ } else if (spec.kind === 'phrase') {+ body = `+ <p class="wl-cer-q">${esc(spec.prompt || 'Say the passphrase the agent asked for:')}</p>+ <input class="wl-input" type="text" inputmode="text" autocomplete="off"+ aria-label="Passphrase" placeholder="Type what the agent asked for" />+ <button class="wl-btn wl-btn-primary" data-act="submit">Tell the agent</button>`;+ } else {+ body = `+ <p class="wl-cer-q">${esc(spec.prompt || 'Reach out and meet the agent.')}</p>+ <button class="wl-btn wl-btn-primary wl-tap" data-act="submit">Tap to meet the agent</button>`;+ }+ this._set(`<div class="wl-cer-card"><div class="wl-cer-interaction">${body}</div>+ <p class="wl-cer-err" data-err hidden></p></div>`);+ this._wireInteraction(spec);+ }++ _wireInteraction(spec) {+ if (spec.kind === 'quiz') {+ this.container.querySelectorAll('.wl-choice').forEach((btn) => {+ btn.addEventListener('click', () => {+ this.container.querySelectorAll('.wl-choice').forEach((b) => b.setAttribute('aria-checked', 'false'));+ btn.setAttribute('aria-checked', 'true');+ this._submit({ answer: Number(btn.dataset.i) });+ });+ });+ } else if (spec.kind === 'phrase') {+ const input = this.container.querySelector('.wl-input');+ const submit = this.container.querySelector('[data-act="submit"]');+ const go = () => this._submit({ phrase: input?.value || '' });+ submit?.addEventListener('click', go);+ input?.addEventListener('keydown', (e) => { if (e.key === 'Enter') go(); });+ input?.focus();+ } else {+ this.container.querySelector('[data-act="submit"]')?.addEventListener('click', () => this._submit({}));+ }+ }++ async _submit(interaction) {+ const errEl = this.container.querySelector('[data-err]');+ const fix = this.getFix();+ if (!fix || !Number.isFinite(fix.lat)) return this._renderError('Lost your location. Move back to the spot and try again.', true);+ this._set(loadingCard('The agent is signing your proof of presence…'));+ let res;+ try {+ res = await this.client.complete(this.wl.id, this.nonce, fix.lat, fix.lng, fix.accuracy, interaction);+ } catch (err) {+ // A failed challenge (wrong answer) is recoverable — re-show the interaction.+ if (err.code === 'challenge_failed') {+ this._renderInteraction();+ const e = this.container.querySelector('[data-err]');+ if (e) { e.textContent = err.message; e.hidden = false; }+ return;+ }+ if (err.code === 'invalid_nonce') {+ // Expired/used challenge — restart cleanly.+ return this._renderError(err.message || 'Your challenge expired. Tap to try again.', true);+ }+ return this._handleApiError(err);+ }+ this._renderGranted(res.proof, res.collectible, res.already_completed);+ }++ _renderGranted(proof, collectible, already) {+ const verifyUrl = (proof && proof.verify_url) || (collectible && `/api/irl/world-lines/verify/${collectible.proof_id}`);+ stopAgentVoice();+ this._set(`+ <div class="wl-cer-card wl-granted">+ <div class="wl-reward-burst" aria-hidden="true"></div>+ <div class="wl-reward-badge">✦</div>+ <h3 class="wl-cer-title">${already ? 'You already hold this proof' : 'Proof of presence minted'}</h3>+ <p class="wl-cer-prompt">${esc(collectible?.name || 'Proof of presence')}</p>+ <dl class="wl-proof-meta">+ <div><dt>Signed by agent</dt><dd class="wl-mono">${esc(short(collectible?.signer_pubkey || proof?.signer_pubkey))}</dd></div>+ <div><dt>Collectible</dt><dd class="wl-mono">${esc(collectible?.mint || `presence:${proof?.id}`)}</dd></div>+ </dl>+ <div class="wl-cer-actions">+ <a class="wl-btn wl-btn-secondary" href="${verifyUrl}" target="_blank" rel="noopener">Verify the signature ↗</a>+ <button class="wl-btn wl-btn-primary" data-act="done">Done</button>+ </div>+ <p class="wl-cer-foot">Anyone can re-check this signature — it’s cryptographically real, bound only to a ~1 km area.</p>+ </div>`);+ this.container.querySelector('[data-act="done"]')?.addEventListener('click', () => {+ this.onGranted(proof, collectible);+ });+ if (!already) this._speak('Proof minted. You were here.');+ }++ _renderAlready(proofId) {+ this._set(`+ <div class="wl-cer-card">+ <div class="wl-reward-badge wl-dim">✓</div>+ <h3 class="wl-cer-title">You’ve already completed this World Line</h3>+ <p class="wl-cer-prompt">Your proof of presence is already in your collection.</p>+ <div class="wl-cer-actions">+ <a class="wl-btn wl-btn-secondary" href="/api/irl/world-lines/verify/${proofId}" target="_blank" rel="noopener">Verify your proof ↗</a>+ <button class="wl-btn wl-btn-primary" data-act="done">Done</button>+ </div>+ </div>`);+ this.container.querySelector('[data-act="done"]')?.addEventListener('click', () => this.onGranted(null, null));+ }++ _handleApiError(err) {+ const code = err.code;+ if (code === 'capacity_reached') return this._renderError('This quest just reached its completion limit. The reward pool is full.', false);+ if (code === 'not_colocated') return this._renderError('Move closer to the quest’s spot to complete it.', true);+ if (code === 'fix_required') return this._renderError('We couldn’t confirm your location. Enable precise location and try again.', true);+ if (err.status === 404 || code === 'anchor_gone') return this._renderError('This World Line is no longer active.', false);+ return this._renderError(err.message || 'Something went wrong. Try again.', true);+ }++ _renderError(message, retry) {+ this._set(`+ <div class="wl-cer-card wl-cer-error">+ <div class="wl-reward-badge wl-err">!</div>+ <p class="wl-cer-prompt">${esc(message)}</p>+ <div class="wl-cer-actions">+ ${retry ? '<button class="wl-btn wl-btn-primary" data-act="retry">Try again</button>' : ''}+ <button class="wl-btn wl-btn-secondary" data-act="done">Close</button>+ </div>+ </div>`);+ this.container.querySelector('[data-act="retry"]')?.addEventListener('click', () => this._renderIntro());+ this.container.querySelector('[data-act="done"]')?.addEventListener('click', () => this.onGranted(null, null));+ }++ // ── Optional 3D agent preview (non-AR) ─────────────────────────────────────+ async _mountAvatarPreview() {+ const canvas = this.container.querySelector('.wl-cer-canvas');+ if (!canvas || !this.avatarUrl) return;+ try {+ const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');+ const renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });+ renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));+ const size = 160;+ renderer.setSize(size, size, false);+ const scene = new Scene();+ scene.add(new AmbientLight(0xffffff, 1.1));+ const key = new DirectionalLight(0xffffff, 1.2); key.position.set(1, 2, 2); scene.add(key);+ const cam = new PerspectiveCamera(35, 1, 0.1, 100);+ cam.position.set(0, 1.4, 2.6);+ const root = new Group(); scene.add(root);+ const gltf = await new GLTFLoader().loadAsync(this.avatarUrl);+ root.add(gltf.scene);+ gltf.scene.position.y = -1.2;+ let raf;+ const tick = () => { root.rotation.y += 0.01; renderer.render(scene, cam); raf = requestAnimationFrame(tick); };+ tick();+ this._previewStop = () => { cancelAnimationFrame(raf); renderer.dispose(); };+ } catch {+ /* preview is decoration; the orb fallback already rendered */+ }+ }++ // ── Optional immersive AR layer (self-contained, decoupled from xr.js) ──────+ static async arSupported() {+ try { return !!(navigator.xr && await navigator.xr.isSessionSupported('immersive-ar')); }+ catch { return false; }+ }++ // Start a minimal immersive-AR session that anchors the agent to the real floor via+ // hit-test, then surfaces the same interaction. Any failure falls back to the panel+ // ceremony — AR is an enhancement, never the only path.+ async enterAR() {+ if (!(await WorldLineCeremony.arSupported())) return this._begin();+ try {+ const renderer = new WebGLRenderer({ alpha: true, antialias: true });+ renderer.xr.enabled = true;+ renderer.setSize(window.innerWidth, window.innerHeight);+ document.body.appendChild(renderer.domElement);+ const scene = new Scene();+ scene.add(new AmbientLight(0xffffff, 1.2));+ const cam = new PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 40);+ const reticle = new Mesh(+ new RingGeometry(0.09, 0.11, 32).rotateX(-Math.PI / 2),+ new MeshBasicMaterial({ color: 0xc4b5fd }),+ );+ reticle.visible = false; reticle.matrixAutoUpdate = false; scene.add(reticle);++ const root = new Group(); root.visible = false; scene.add(root);+ import('three/addons/loaders/GLTFLoader.js').then(({ GLTFLoader }) => {+ if (this.avatarUrl) new GLTFLoader().loadAsync(this.avatarUrl).then((g) => root.add(g.scene)).catch(() => {});+ });++ const overlay = document.createElement('div');+ overlay.className = 'wl-ar-overlay';+ overlay.innerHTML = `<div class="wl-ar-hint">Point at the floor and tap to meet the agent</div>+ <button class="wl-ar-exit" aria-label="Exit AR">Exit</button>`;+ document.body.appendChild(overlay);++ const session = await navigator.xr.requestSession('immersive-ar', {+ requiredFeatures: ['hit-test'], optionalFeatures: ['dom-overlay', 'local-floor'],+ domOverlay: { root: overlay },+ });+ renderer.xr.setReferenceSpaceType('local');+ await renderer.xr.setSession(session);++ const viewerSpace = await session.requestReferenceSpace('viewer');+ const refSpace = renderer.xr.getReferenceSpace();+ const hitSource = await session.requestHitTestSource({ space: viewerSpace });+ let placed = false;++ const end = async () => {+ try { await session.end(); } catch { /* already ending */ }+ };+ this._ar = { end };+ overlay.querySelector('.wl-ar-exit')?.addEventListener('click', end);+ session.addEventListener('select', () => {+ if (placed || !reticle.visible) return;+ placed = true;+ root.position.setFromMatrixPosition(reticle.matrix);+ root.visible = true;+ const hint = overlay.querySelector('.wl-ar-hint');+ if (hint) hint.textContent = 'The agent is here. Listen…';+ this._speak(this.wl.prompt || this.wl.title);+ // Hand off to the panel interaction (rendered into the dom-overlay) once placed.+ setTimeout(() => { end(); this._begin(); }, 600);+ });+ renderer.setAnimationLoop((_, frame) => {+ if (frame && !placed) {+ const hits = frame.getHitTestResults(hitSource);+ if (hits.length) {+ const pose = hits[0].getPose(refSpace);+ reticle.visible = true;+ reticle.matrix.fromArray(pose.transform.matrix);+ } else reticle.visible = false;+ }+ renderer.render(scene, cam);+ });+ session.addEventListener('end', () => {+ renderer.setAnimationLoop(null);+ renderer.domElement.remove();+ overlay.remove();+ renderer.dispose();+ this._ar = null;+ });+ } catch {+ // AR couldn't start — the panel ceremony is the first-class fallback.+ this._begin();+ }+ }+}++function loadingCard(text) {+ return `<div class="wl-cer-card"><div class="wl-spinner" aria-hidden="true"></div>+ <p class="wl-cer-prompt">${esc(text)}</p></div>`;+}+function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function short(k) {+ const s = String(k || '');+ return s.length > 12 ? `${s.slice(0, 6)}…${s.slice(-4)}` : s;+}diff --git a/src/irl/world-lines-client.js b/src/irl/world-lines-client.jsnew file mode 100644index 000000000..443fb1f7d--- /dev/null+++ b/src/irl/world-lines-client.js@@ -0,0 +1,176 @@+// World Lines client — the browser side of the proof-of-presence quest API.+//+// Reuses the exact IRL identity + proof-of-presence conventions so a visitor is the+// same person across /irl and /world-lines:+// · anonymous device token → localStorage 'irl_device_token', sent as x-irl-device+// · proof-of-presence fix → POST /api/irl/fix-token, cached per ~110 m cell, sent+// as x-irl-fix on every co-located read/write+// The device token is a bearer credential, so it ONLY ever rides in the header, never a+// URL (mirrors api/_lib/irl-auth.js). The caller's precise GPS is used to mint the fix+// and to prove co-location; it is never persisted by the client and never logged.++const DEVICE_KEY = 'irl_device_token';+const FIX_SKEW_MS = 15_000; // re-mint a little before the token actually expires++function deviceToken() {+ let t = null;+ try {+ t = localStorage.getItem(DEVICE_KEY);+ if (!t) {+ t = (crypto.randomUUID && crypto.randomUUID()) || `dev-${Date.now()}-${Math.random().toString(36).slice(2)}`;+ localStorage.setItem(DEVICE_KEY, t);+ }+ } catch {+ /* storage blocked (private mode) — fall back to an ephemeral in-memory token */+ t = _ephemeralDevice || (_ephemeralDevice = `eph-${Math.random().toString(36).slice(2)}`);+ }+ return t;+}+let _ephemeralDevice = null;++function deviceHeaders(extra = {}) {+ const t = deviceToken();+ return t ? { 'x-irl-device': t, ...extra } : { ...extra };+}++// ── Fix token cache ──────────────────────────────────────────────────────────+let _fixToken = null;+let _fixCell = null;+let _fixExpiresAt = 0;++function cellKey(lat, lng) {+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;+ return `${lat.toFixed(3)},${lng.toFixed(3)}`; // ~110 m — the fix anchor granularity+}++async function ensureFixToken(lat, lng, accuracy) {+ const cell = cellKey(lat, lng);+ if (!cell) return null;+ if (_fixToken && _fixCell === cell && Date.now() < _fixExpiresAt) return _fixToken;+ try {+ const r = await fetch('/api/irl/fix-token', {+ method: 'POST',+ credentials: 'include',+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ lat, lng, accuracy }),+ });+ if (!r.ok) return null;+ const { token, expires_in } = await r.json();+ if (token) {+ _fixToken = token;+ _fixCell = cell;+ _fixExpiresAt = Date.now() + (Number(expires_in) || 180) * 1000 - FIX_SKEW_MS;+ }+ return token;+ } catch {+ return null;+ }+}++async function presenceHeaders(lat, lng, accuracy, extra = {}) {+ const token = await ensureFixToken(lat, lng, accuracy);+ return deviceHeaders(token ? { 'x-irl-fix': token, ...extra } : { ...extra });+}++async function asJson(r) {+ let body = null;+ try { body = await r.json(); } catch { /* non-JSON */ }+ if (!r.ok) {+ const err = new Error(body?.error_description || body?.message || body?.error || `request failed (${r.status})`);+ err.status = r.status;+ err.code = body?.error;+ err.body = body;+ throw err;+ }+ return body;+}++let _csrf = null;+async function csrfToken() {+ if (_csrf) return _csrf;+ try {+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ const { token } = await asJson(r);+ _csrf = token;+ return token;+ } catch {+ return null;+ }+}++const BASE = '/api/irl/world-lines';++export const worldLinesClient = {+ deviceToken,++ // Public, coarse region roll-up (no coordinates) — the discovery map.+ async browseRegions() {+ return asJson(await fetch(`${BASE}/browse`, { credentials: 'include' }));+ },+ async browseRegion(region, difficulty) {+ const qs = new URLSearchParams({ region });+ if (difficulty) qs.set('difficulty', difficulty);+ return asJson(await fetch(`${BASE}/browse?${qs}`, { credentials: 'include' }));+ },++ // Fix-gated, co-located discovery — quests within walking range of (lat,lng).+ async nearby(lat, lng, accuracy, radius) {+ const qs = new URLSearchParams({ lat: String(lat), lng: String(lng) });+ if (radius) qs.set('radius', String(radius));+ const headers = await presenceHeaders(lat, lng, accuracy);+ return asJson(await fetch(`${BASE}/nearby?${qs}`, { credentials: 'include', headers }));+ },++ // Single quest detail. Pass the caller's fix so the AR answer is revealed only when+ // co-located (the server redacts the quiz/phrase answer otherwise).+ async getQuest(id, lat, lng, accuracy) {+ const qs = new URLSearchParams();+ if (Number.isFinite(lat) && Number.isFinite(lng)) { qs.set('lat', String(lat)); qs.set('lng', String(lng)); }+ const headers = Number.isFinite(lat) ? await presenceHeaders(lat, lng, accuracy) : deviceHeaders();+ const suffix = qs.toString() ? `?${qs}` : '';+ return asJson(await fetch(`${BASE}/${id}${suffix}`, { credentials: 'include', headers }));+ },++ // Issue a single-use completion nonce (requires server-derived co-location).+ async challenge(worldLineId, lat, lng, accuracy) {+ const headers = await presenceHeaders(lat, lng, accuracy, { 'Content-Type': 'application/json' });+ return asJson(await fetch(`${BASE}/challenge`, {+ method: 'POST', credentials: 'include', headers,+ body: JSON.stringify({ world_line_id: worldLineId, lat, lng, accuracy }),+ }));+ },++ // The proof ceremony. `interaction` carries { answer } (quiz) or { phrase } where needed.+ async complete(worldLineId, nonce, lat, lng, accuracy, interaction = {}) {+ const headers = await presenceHeaders(lat, lng, accuracy, { 'Content-Type': 'application/json' });+ return asJson(await fetch(`${BASE}/complete`, {+ method: 'POST', credentials: 'include', headers,+ body: JSON.stringify({ world_line_id: worldLineId, nonce, lat, lng, accuracy, ...interaction }),+ }));+ },++ // Independent, public verification of a proof.+ async verify(proofId) {+ return asJson(await fetch(`${BASE}/verify/${proofId}`, { credentials: 'include' }));+ },++ // The caller's earned collectibles (device or signed-in user).+ async myCollectibles() {+ return asJson(await fetch(`${BASE}/collectibles`, { credentials: 'include', headers: deviceHeaders() }));+ },++ // Creator dashboard (auth).+ async mine() {+ return asJson(await fetch(`${BASE}/mine`, { credentials: 'include' }));+ },++ // Place a World Line (auth + CSRF).+ async create(payload) {+ const token = await csrfToken();+ const headers = { 'Content-Type': 'application/json' };+ if (token) headers['X-CSRF-Token'] = token;+ return asJson(await fetch(`${BASE}`, {+ method: 'POST', credentials: 'include', headers, body: JSON.stringify(payload),+ }));+ },+};diff --git a/src/shared/stage-link.js b/src/shared/stage-link.jsnew file mode 100644index 000000000..a2283d004--- /dev/null+++ b/src/shared/stage-link.js@@ -0,0 +1,152 @@+// stage-link — the Living Stages entry point on an agent's profile.+//+// Mounts a compact panel that cross-links an agent to its live stage:+// • visitors — a "● LIVE — watch now" badge when the agent is performing, or a+// "next show" / "view stage" link when a stage exists but is dark.+// • the owner — when no stage exists, a one-tap "Put <name> on stage"; once it+// exists, Go live / End show controls + the venue link.+//+// Self-contained: it owns its own fetch + state and renders into a container, so+// agent-detail.js mounts it with one call (like mountPresence). All writes go+// through apiFetch (CSRF handled) and enforce ownership server-side.++import { apiFetch } from '../api.js';++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++export async function mountStagePanel({ agentId, agentName = 'this agent', isOwner = false, container, position = 'append' } = {}) {+ if (!agentId || !container) return null;+ const el = document.createElement('div');+ el.className = 'stage-link-panel';+ el.innerHTML = '<div class="slp-loading">Loading stage…</div>';+ if (position === 'prepend') container.prepend(el);+ else container.append(el);++ injectStyle();+ const panel = new StagePanel(el, { agentId, agentName, isOwner });+ await panel.refresh();+ return panel;+}++class StagePanel {+ constructor(el, opts) {+ this.el = el;+ this.opts = opts;+ this.stage = null;+ this.busy = false;+ }++ async refresh() {+ try {+ const res = await apiFetch(`/api/stage?agentId=${encodeURIComponent(this.opts.agentId)}`, { allowAnonymous: true });+ const data = await res.json();+ this.stage = data.stage || null;+ } catch {+ this.stage = null;+ }+ this.render();+ }++ render() {+ const { agentName, isOwner } = this.opts;+ const s = this.stage;++ if (!s) {+ if (!isOwner) { this.el.remove(); return; } // nothing to show a visitor+ this.el.innerHTML = `+ <div class="slp-head"><span class="slp-kicker">Living Stage</span></div>+ <p class="slp-copy">Put ${esc(agentName)} on stage — host a live, monetized show and get tipped in $THREE on the spot.</p>+ <button class="slp-btn primary" data-act="create">Create a stage</button>+ <p class="slp-status" aria-live="polite"></p>`;+ this.wire();+ return;+ }++ const live = s.live;+ const next = s.next_show_at && !live ? new Date(s.next_show_at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) : '';+ const link = `/stage?id=${encodeURIComponent(s.id)}`;+ const ownerControls = isOwner+ ? `<div class="slp-owner">+ ${live+ ? '<button class="slp-btn" data-act="endshow">End show</button>'+ : '<button class="slp-btn primary" data-act="golive">Go live</button>'}+ <a class="slp-btn ghost" href="${link}">Open venue</a>+ </div>`+ : `<a class="slp-btn ${live ? 'primary' : ''}" href="${link}">${live ? 'Watch live' : 'View stage'}</a>`;++ this.el.innerHTML = `+ <div class="slp-head">+ <span class="slp-kicker">Living Stage</span>+ ${live ? '<span class="slp-live">● LIVE</span>' : (next ? `<span class="slp-soon">Next ${esc(next)}</span>` : '<span class="slp-soon">Stage ready</span>')}+ </div>+ <p class="slp-copy">${esc(s.title || `${agentName} Live`)} · ${esc(s.format || 'live')}</p>+ ${ownerControls}+ <p class="slp-status" aria-live="polite"></p>`;+ this.wire();+ }++ wire() {+ this.el.querySelectorAll('[data-act]').forEach((b) => {+ b.addEventListener('click', () => this.act(b.dataset.act, b));+ });+ }++ async act(action, btn) {+ if (this.busy) return;+ this.busy = true;+ const status = this.el.querySelector('.slp-status');+ const orig = btn.textContent;+ btn.disabled = true;+ btn.textContent = '…';+ try {+ let body;+ if (action === 'create') body = { action: 'create', agentId: this.opts.agentId };+ else if (action === 'golive') body = { action: 'golive', stageId: this.stage.id };+ else if (action === 'endshow') body = { action: 'endshow', stageId: this.stage.id };+ const res = await apiFetch('/api/stage', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ const out = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(out.error || 'request failed');+ if (action === 'golive' && out.link) {+ status.textContent = 'You are live! Opening the venue…';+ setTimeout(() => { location.href = out.link; }, 700);+ return;+ }+ await this.refresh();+ } catch (err) {+ status.textContent = err?.message || 'Something went wrong.';+ btn.disabled = false;+ btn.textContent = orig;+ } finally {+ this.busy = false;+ }+ }+}++let _styled = false;+function injectStyle() {+ if (_styled) return;+ _styled = true;+ const css = `+ .stage-link-panel{border:1px solid rgba(155,107,255,.25);background:rgba(155,107,255,.06);border-radius:14px;padding:14px 16px;margin:14px 0;font-family:inherit}+ .stage-link-panel .slp-head{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px}+ .stage-link-panel .slp-kicker{font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#9b6bff}+ .stage-link-panel .slp-live{font-size:12px;font-weight:700;color:#ff5db1;animation:slpPulse 1.5s infinite}+ .stage-link-panel .slp-soon{font-size:12px;color:#a59fc4}+ .stage-link-panel .slp-copy{margin:0 0 10px;font-size:14px;opacity:.9}+ .stage-link-panel .slp-owner{display:flex;gap:8px;flex-wrap:wrap}+ .stage-link-panel .slp-btn{display:inline-block;padding:8px 16px;border-radius:9px;border:1px solid rgba(155,107,255,.3);background:transparent;color:inherit;font:inherit;font-weight:600;cursor:pointer;text-decoration:none;transition:background .15s,transform .1s}+ .stage-link-panel .slp-btn:hover{background:rgba(155,107,255,.18)}+ .stage-link-panel .slp-btn:active{transform:scale(.97)}+ .stage-link-panel .slp-btn.primary{background:linear-gradient(90deg,#9b6bff,#32d6ff);border:0;color:#fff}+ .stage-link-panel .slp-btn.ghost{opacity:.85}+ .stage-link-panel .slp-btn:focus-visible{outline:2px solid #32d6ff;outline-offset:2px}+ .stage-link-panel .slp-status{margin:8px 0 0;font-size:12px;color:#a59fc4;min-height:14px}+ @keyframes slpPulse{0%,100%{opacity:1}50%{opacity:.4}}`;+ const tag = document.createElement('style');+ tag.textContent = css;+ document.head.appendChild(tag);+}diff --git a/tests/marketplace-splits.test.js b/tests/marketplace-splits.test.jsindex b6aa9966a..6f92af46a 100644--- a/tests/marketplace-splits.test.js+++ b/tests/marketplace-splits.test.js@@ -16,9 +16,23 @@ import {allocateAtomics,describeSplit,isValidAddressForChain,+ recordSplitDistribution,FULL_SHARE_BPS,} from '../api/_lib/splits.js';import { marketplaceFeeAtomics } from '../api/_lib/marketplace-platform-fee.js';+import { enforceOnchainLicense, licenseEnforcementEnabled } from '../api/_lib/skill-license-verify.js';++// A fake tagged-template `sql` that records the interpolated values of each+// query so we can assert what would be persisted, without a database.+function fakeSql(returnRows = []) {+ const calls = [];+ const fn = (strings, ...values) => {+ calls.push(values);+ return Promise.resolve(returnRows);+ };+ fn.calls = calls;+ return fn;+}// Synthetic addresses — never a real wallet (CLAUDE.md).const SOL_A = 'THREEsynthetic1111111111111111111111111111A';diff --git a/tests/notify-prefs.test.js b/tests/notify-prefs.test.jsnew file mode 100644index 000000000..528e54db5--- /dev/null+++ b/tests/notify-prefs.test.js@@ -0,0 +1,178 @@+// Unit tests for api/_lib/notify-prefs.js — the preference model that gates+// every notification channel (in-app / push / email / telegram).+//+// These are pure functions; resolvePrefs (the only DB-touching export) is not+// exercised here. Importing the module is safe because api/_lib/db.js creates+// its neon client lazily, so no connection is attempted at import time.++import { describe, it, expect } from 'vitest';+import {+ CATEGORIES,+ CHANNELS,+ categoryForType,+ defaultMatrix,+ mergeWithDefaults,+ channelEnabled,+ sanitizePrefs,+ pushPayloadFor,+} from '../api/_lib/notify-prefs.js';++describe('category model', () => {+ it('exposes the six display categories and four channels', () => {+ expect(CATEGORIES.map((c) => c.key)).toEqual([+ 'sales', 'purchases', 'social', 'irl', 'alerts', 'account',+ ]);+ expect(CHANNELS).toEqual(['in_app', 'push', 'email', 'telegram']);+ });++ it('every category has a label and description for the preference center', () => {+ for (const c of CATEGORIES) {+ expect(typeof c.label).toBe('string');+ expect(c.label.length).toBeGreaterThan(0);+ expect(typeof c.description).toBe('string');+ expect(c.description.length).toBeGreaterThan(0);+ }+ });+});++describe('categoryForType', () => {+ it('maps known notification types to their category', () => {+ expect(categoryForType('skill_purchased')).toBe('sales');+ expect(categoryForType('skill_purchase_confirmed')).toBe('purchases');+ expect(categoryForType('remix')).toBe('social');+ expect(categoryForType('irl_interaction')).toBe('irl');+ expect(categoryForType('pump_alert')).toBe('alerts');+ expect(categoryForType('withdrawal_failed')).toBe('account');+ });++ it('falls back to account for unknown types (never silently undeliverable)', () => {+ expect(categoryForType('something_brand_new')).toBe('account');+ expect(categoryForType('')).toBe('account');+ });++ it('every mapped category is one of the declared categories', () => {+ const keys = new Set(CATEGORIES.map((c) => c.key));+ for (const c of CATEGORIES) expect(keys.has(c.key)).toBe(true);+ // spot a few types+ for (const t of ['sale', 'referral_earned', 'skill_gift_sent', 'security_alert']) {+ expect(keys.has(categoryForType(t))).toBe(true);+ }+ });+});++describe('defaultMatrix / mergeWithDefaults', () => {+ it('default matrix turns in_app + push on for every category', () => {+ const m = defaultMatrix();+ for (const c of CATEGORIES) {+ expect(m[c.key].in_app).toBe(true);+ expect(m[c.key].push).toBe(true);+ }+ });++ it('email defaults on only for money + security categories', () => {+ const m = defaultMatrix();+ expect(m.sales.email).toBe(true);+ expect(m.purchases.email).toBe(true);+ expect(m.account.email).toBe(true);+ expect(m.social.email).toBe(false);+ expect(m.irl.email).toBe(false);+ expect(m.alerts.email).toBe(false);+ });++ it('telegram defaults off everywhere except opt-in alerts', () => {+ const m = defaultMatrix();+ expect(m.sales.telegram).toBe(false);+ expect(m.alerts.telegram).toBe(true);+ });++ it('a fresh mutation of the default matrix does not leak across calls', () => {+ const a = defaultMatrix();+ a.sales.push = false;+ const b = defaultMatrix();+ expect(b.sales.push).toBe(true);+ });++ it('overlays stored sparse prefs onto defaults', () => {+ const merged = mergeWithDefaults({ categories: { sales: { email: false } } });+ expect(merged.categories.sales.email).toBe(false); // overridden+ expect(merged.categories.sales.push).toBe(true); // default kept+ expect(merged.categories.account.email).toBe(true); // untouched category default+ });++ it('surfaces a stored telegram chat id, null otherwise', () => {+ expect(mergeWithDefaults({ telegram_chat_id: '12345' }).telegram_chat_id).toBe('12345');+ expect(mergeWithDefaults({}).telegram_chat_id).toBe(null);+ });+});++describe('channelEnabled', () => {+ const prefs = mergeWithDefaults({+ categories: { social: { push: false }, sales: { email: false } },+ });++ it('respects an explicit off override', () => {+ expect(channelEnabled(prefs, 'remix', 'push')).toBe(false); // social.push off+ expect(channelEnabled(prefs, 'skill_purchased', 'email')).toBe(false); // sales.email off+ });++ it('falls back to the default when no override exists', () => {+ expect(channelEnabled(prefs, 'remix', 'in_app')).toBe(true);+ expect(channelEnabled(prefs, 'skill_purchased', 'push')).toBe(true);+ });++ it('handles a totally empty prefs object via defaults', () => {+ const empty = mergeWithDefaults({});+ expect(channelEnabled(empty, 'pump_alert', 'telegram')).toBe(true); // alerts default+ expect(channelEnabled(empty, 'remix', 'email')).toBe(false); // social default+ });+});++describe('sanitizePrefs', () => {+ it('drops unknown categories and non-boolean channel values', () => {+ const clean = sanitizePrefs({+ categories: {+ sales: { push: false, email: 'yes', bogus_channel: true },+ not_a_category: { push: true },+ },+ });+ expect(clean.categories.sales).toEqual({ push: false });+ expect(clean.categories.not_a_category).toBeUndefined();+ });++ it('accepts a numeric telegram chat id and clears on empty string', () => {+ expect(sanitizePrefs({ telegram_chat_id: '-1009876' }).telegram_chat_id).toBe('-1009876');+ expect(sanitizePrefs({ telegram_chat_id: '' }).telegram_chat_id).toBe(null);+ expect(sanitizePrefs({ telegram_chat_id: 'not-a-number' }).telegram_chat_id).toBeUndefined();+ });++ it('never returns categories with zero usable keys', () => {+ const clean = sanitizePrefs({ categories: { sales: { email: 'no' } } });+ expect(clean.categories.sales).toBeUndefined();+ });+});++describe('pushPayloadFor', () => {+ it('builds a title/body/url and carries the notification id + category', () => {+ const p = pushPayloadFor('skill_purchased', { skill: 'Voice Pack', agent_id: 'a1' }, 'n-123');+ expect(p.title).toMatch(/sale/i);+ expect(p.body).toContain('Voice Pack');+ expect(p.url).toBe('/agent/a1');+ expect(p.notificationId).toBe('n-123');+ expect(p.category).toBe('sales');+ expect(p.tag).toBe('skill_purchased');+ });++ it('prefers an explicit safe link and rejects javascript: urls', () => {+ expect(pushPayloadFor('reply', { link: '/agent/x' }).url).toBe('/agent/x');+ expect(pushPayloadFor('reply', { link: 'javascript:alert(1)' }).url).toBe('/dashboard/');+ expect(pushPayloadFor('reply', { link: '//evil.com' }).url).toBe('/dashboard/');+ expect(pushPayloadFor('reply', { link: 'https://solscan.io/tx/abc' }).url).toBe('https://solscan.io/tx/abc');+ });++ it('falls back to a generic payload for unknown types', () => {+ const p = pushPayloadFor('mystery_event', {});+ expect(p.title).toBe('three.ws');+ expect(p.body).toBe('mystery event');+ expect(p.url).toBe('/dashboard/');+ });+});diff --git a/vercel.json b/vercel.jsonindex 36bfbe3c5..3fc10c95b 100644--- a/vercel.json+++ b/vercel.json@@ -708,6 +708,10 @@"src": "/leaderboard/?","dest": "/leaderboard.html"},+ {+ "src": "/labor-market/?",+ "dest": "/labor-market.html"+ },{"src": "/mirror/?","dest": "/mirror.html"@@ -973,6 +977,10 @@"src": "/club/?","dest": "/club.html"},+ {+ "src": "/stage/?",+ "dest": "/stage.html"+ },{"src": "/agenc/embodied/?","dest": "/agenc/embodied.html"@@ -1005,6 +1013,10 @@"src": "/voice/?","dest": "/voice.html"},+ {+ "src": "/genome/?",+ "dest": "/genome.html"+ },{"src": "/brain/?","dest": "/brain.html"diff --git a/vite.config.js b/vite.config.jsindex be63718a0..5c7128615 100644--- a/vite.config.js+++ b/vite.config.js@@ -343,6 +343,7 @@ const appConfig = {'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),leaderboard: resolve(__dirname, 'pages/leaderboard.html'),+ 'labor-market': resolve(__dirname, 'pages/labor-market.html'),'reasoning-ledger': resolve(__dirname, 'pages/reasoning-ledger.html'),mirror: resolve(__dirname, 'pages/mirror.html'),strategies: resolve(__dirname, 'pages/strategies.html'),@@ -404,6 +405,7 @@ const appConfig = {cosmos: resolve(__dirname, 'pages/cosmos.html'),voice: resolve(__dirname, 'pages/voice.html'),galaxy: resolve(__dirname, 'pages/galaxy.html'),+ genome: resolve(__dirname, 'pages/genome.html'),'ar-page': resolve(__dirname, 'pages/ar.html'),creating: resolve(__dirname, 'pages/creating.html'),pricing: resolve(__dirname, 'pages/pricing.html'),@@ -432,6 +434,7 @@ const appConfig = {pose: resolve(__dirname, 'pages/pose.html'),animations: resolve(__dirname, 'pages/animations.html'),club: resolve(__dirname, 'pages/club.html'),+ stage: resolve(__dirname, 'pages/stage.html'),skills: resolve(__dirname, 'pages/skills.html'),'agenc-embodied': resolve(__dirname, 'pages/agenc/embodied.html'),'agenc-room': resolve(__dirname, 'pages/agenc/room.html'),@@ -785,6 +788,8 @@ support: resolve(__dirname, 'pages/support.html'),'/watchlist/': resolve(root, 'pages/watchlist.html'),'/leaderboard': resolve(root, 'pages/leaderboard.html'),'/leaderboard/': resolve(root, 'pages/leaderboard.html'),+ '/labor-market': resolve(root, 'pages/labor-market.html'),+ '/labor-market/': resolve(root, 'pages/labor-market.html'),'/arena': resolve(root, 'pages/arena.html'),'/arena/': resolve(root, 'pages/arena.html'),'/mirror': resolve(root, 'pages/mirror.html'),@@ -877,6 +882,8 @@ support: resolve(__dirname, 'pages/support.html'),'/pose/': resolve(root, 'pages/pose.html'),'/club': resolve(root, 'pages/club.html'),'/club/': resolve(root, 'pages/club.html'),+ '/stage': resolve(root, 'pages/stage.html'),+ '/stage/': resolve(root, 'pages/stage.html'),'/dad': resolve(root, 'pages/dad.html'),'/dad/': resolve(root, 'pages/dad.html'),'/agenc/embodied': resolve(root, 'pages/agenc/embodied.html'),