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
feat: transactional emails, skill reviews, affiliate breakdown
miniaturization1148e88e0dee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13deba61c..a12db286f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,8 +12,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Walk Leaderboard** (`/walk-leaderboard`) — Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`+- **Affiliate dashboard now shows who you referred** — The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals. (`/dashboard/referrals`) `[improvement]`+- **Agent payments now produce a signed receipt of exactly what was bought** — Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement. `[feature, sdk]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`+- **Avatar Studio: full-spectrum color picker and one-tap Looks** — The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast. (`/avatar-studio`) `[feature, improvement]`- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Coin pages stay fast when pump.fun is having a moment** — The /launches coin page pulls creator fee-sharing earnings live from pump.fun. We put that call behind a circuit breaker (built on the well-tested cockatiel library rather than home-grown code): if pump.fun slows down or errors, the breaker trips after a few failures and the page instantly skips that one enrichment instead of every visitor waiting out the timeout. The earnings simply show as unavailable until pump.fun recovers, and the rest of the page — registry, intel, outcome, trader record — was never affected. Same approach is now available platform-wide for other third-party data sources. (`/launches`) `[infra, improvement]`- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`@@ -33,6 +36,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, improvement]`- **Imported avatars now animate with correct arm and leg orientation** — Animations are authored on one reference rig and retargeted onto whatever avatar you bring — Mixamo, Ready Player Me, VRoid, and more. We found that limbs on those rigs could play roughly 30° off from where they should be, because the retarget replayed each joint's motion in the wrong frame when a rig's rest pose differed from ours. The retarget now preserves each joint's true world-space motion, so idle, walk, and every other clip drive a foreign rig's arms and legs the way they were animated. Avatars matching the reference rig are byte-for-byte unchanged. `[fix, improvement]`- **Live market feed stays up through provider blips** — The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups. `[infra, improvement]`+- **More reliable on-chain transactions across the platform** — Every on-chain action that moves funds — agent transfers, token launches, buys and sells, creator-fee claims, club and lottery payouts, buybacks, and skill purchases — now goes through one hardened sender. It estimates the right priority fee, automatically re-broadcasts your transaction with a fresh blockhash until it actually lands instead of giving up after one try, and treats a transaction that reverts on-chain as a clear failure rather than a silent success. In practice that means far fewer 'stuck' or dropped transactions when the network is busy, and an honest error (with your funds untouched) when something genuinely can't go through. Nothing to do on your end. `[improvement, fix, infra]`- **My Collection page now loads** — The /collection page — where your unlocked skills and active subscriptions live — was returning a 404 because its route pointed at the wrong build path, and its subscriptions list was calling an endpoint that rejected the request. Both are fixed: the page loads, your purchased skills and NFT receipts render, and the Subscriptions tab now shows your active creator subscriptions with plan, price, renewal date, and a link to each creator. The marketplace analytics page had the same routing fault and now loads too. (`/collection`) `[fix]`- **Our paid services are properly discoverable by AI agents again** — Every three.ws paid endpoint and MCP tool is published to the x402 discovery indexes (Coinbase's Bazaar, x402scan, agentic.market) so AI agents can find and pay for them automatically. A stray invisible character in the published Solana receiving address was making indexers reject the entire catalog, and our MCP tools weren't flagged as discoverable — both are fixed, service names were tidied to meet listing limits, and we added a checker that catches these issues before they ship. Result: agents can discover and call our services across the ecosystem. `[improvement]`- **Pay-per-call endpoints accept Solana USDC payments again** — Paying for any x402 endpoint with Solana USDC was failing the moment the wallet tried to build the payment — the platform's receiving address was being published with a stray invisible character, so a correctly-built payment got rejected as going to the wrong recipient. Payment addresses are now cleaned before they're ever advertised, so Solana USDC payments to paid endpoints go through and settle as expected. `[fix]`diff --git a/api/_lib/email.js b/api/_lib/email.jsindex a4a8c1a05..0c515dd8f 100644--- a/api/_lib/email.js+++ b/api/_lib/email.js@@ -88,6 +88,30 @@ export function renderSubscriptionConfirm({ plan, chain, txId }) {};}+export function renderPurchaseReceipt({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }) {+ return {+ subject: `Your three.ws receipt — ${skillName}`,+ html: purchaseReceiptHtml({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }),+ text: purchaseReceiptText({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }),+ };+}++export function renderSaleNotification({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }) {+ return {+ subject: `You made a sale — ${skillName}`,+ html: saleNotificationHtml({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }),+ text: saleNotificationText({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }),+ };+}++export function renderReferralCommission({ amount, currency, fromHandle, skillName, date }) {+ return {+ subject: `You earned a referral commission`,+ html: referralCommissionHtml({ amount, currency, fromHandle, skillName, date }),+ text: referralCommissionText({ amount, currency, fromHandle, skillName, date }),+ };+}+// ─── Template wrappers ────────────────────────────────────────────────────────export function sendWelcomeEmail({ to, displayName }) {@@ -106,6 +130,18 @@ export function sendSubscriptionConfirmEmail({ to, plan, chain, txId }) {return sendEmail({ to, ...renderSubscriptionConfirm({ plan, chain, txId }) });}+export function sendPurchaseReceiptEmail({ to, skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }) {+ return sendEmail({ to, ...renderPurchaseReceipt({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }) });+}++export function sendSaleNotificationEmail({ to, skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }) {+ return sendEmail({ to, ...renderSaleNotification({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }) });+}++export function sendReferralCommissionEmail({ to, amount, currency, fromHandle, skillName, date }) {+ return sendEmail({ to, ...renderReferralCommission({ amount, currency, fromHandle, skillName, date }) });+}+// ─── HTML helpers ─────────────────────────────────────────────────────────────function layout(title, body) {@@ -188,6 +224,120 @@ function subscriptionText(plan, chain, txId) {return `Your three.ws ${plan} plan is now active on ${chain}.\n${txId ? `Transaction: ${txId}\n` : ''}Open dashboard: ${APP_URL}/dashboard/`;}+// Renders a label/value row used by the receipt + sale templates.+function row(label, value) {+ if (value === null || value === undefined || value === '') return '';+ return `<tr><td style="padding:6px 0;color:#777;font-size:13px">${esc(label)}</td><td style="padding:6px 0;color:#eee;font-size:14px;text-align:right;font-weight:600">${value}</td></tr>`;+}++function purchaseReceiptHtml({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }) {+ const txCell = txUrl+ ? `<a href="${esc(txUrl)}" style="color:#6a5cff;text-decoration:none">${esc(shortTx(txId))}</a>`+ : (txId ? `<code>${esc(shortTx(txId))}</code>` : '');+ return layout(`Receipt — ${skillName}`, `+ <p class="brand">three.ws</p>+ <h1>Purchase confirmed</h1>+ <p>Thanks for your purchase. Here's your receipt for <strong>${esc(skillName)}</strong>${agentName ? ` from <strong>${esc(agentName)}</strong>` : ''}.</p>+ <table style="width:100%;border-collapse:collapse;margin:8px 0 20px">+ ${row('Skill', esc(skillName))}+ ${agentName ? row('Agent', esc(agentName)) : ''}+ ${row('Amount', `${esc(amount)} ${esc(currency)}`)}+ ${date ? row('Date', esc(date)) : ''}+ ${txCell ? row('Transaction', txCell) : ''}+ </table>+ ${agentUrl ? `<a class="btn" href="${esc(agentUrl)}">View agent</a>` : ''}+ <hr>+ <p class="muted">Keep this email as proof of purchase. Questions? Reply and we'll help.</p>+ `);+}++function purchaseReceiptText({ skillName, agentName, agentUrl, amount, currency, date, txUrl, txId }) {+ return [+ `Purchase confirmed — three.ws`,+ ``,+ `Skill: ${skillName}`,+ agentName ? `Agent: ${agentName}` : null,+ `Amount: ${amount} ${currency}`,+ date ? `Date: ${date}` : null,+ txId ? `Transaction: ${txUrl || txId}` : null,+ agentUrl ? `\nView agent: ${agentUrl}` : null,+ ``,+ `Keep this email as proof of purchase.`,+ ].filter(Boolean).join('\n');+}++function saleNotificationHtml({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }) {+ const txCell = txUrl+ ? `<a href="${esc(txUrl)}" style="color:#6a5cff;text-decoration:none">${esc(shortTx(txId))}</a>`+ : (txId ? `<code>${esc(shortTx(txId))}</code>` : '');+ return layout(`You made a sale`, `+ <p class="brand">three.ws</p>+ <h1>You made a sale</h1>+ <p>Someone purchased <strong>${esc(skillName)}</strong>${agentName ? ` on <strong>${esc(agentName)}</strong>` : ''}. Your net earnings have been recorded.</p>+ <table style="width:100%;border-collapse:collapse;margin:8px 0 20px">+ ${row('Skill', esc(skillName))}+ ${agentName ? row('Agent', esc(agentName)) : ''}+ ${row('Net earnings', `${esc(netAmount)} ${esc(currency)}`)}+ ${buyerHandle ? row('Buyer', esc(buyerHandle)) : ''}+ ${date ? row('Date', esc(date)) : ''}+ ${txCell ? row('Transaction', txCell) : ''}+ </table>+ <a class="btn" href="${APP_URL}/dashboard/">View earnings</a>+ ${agentUrl ? `<hr><p class="muted">Manage this agent: <a href="${esc(agentUrl)}" style="color:#6a5cff">${esc(agentUrl)}</a></p>` : ''}+ `);+}++function saleNotificationText({ skillName, agentName, agentUrl, netAmount, currency, buyerHandle, date, txUrl, txId }) {+ return [+ `You made a sale — three.ws`,+ ``,+ `Skill: ${skillName}`,+ agentName ? `Agent: ${agentName}` : null,+ `Net earnings: ${netAmount} ${currency}`,+ buyerHandle ? `Buyer: ${buyerHandle}` : null,+ date ? `Date: ${date}` : null,+ txId ? `Transaction: ${txUrl || txId}` : null,+ ``,+ `View earnings: ${APP_URL}/dashboard/`,+ agentUrl ? `Manage agent: ${agentUrl}` : null,+ ].filter(Boolean).join('\n');+}++function referralCommissionHtml({ amount, currency, fromHandle, skillName, date }) {+ return layout(`Referral commission earned`, `+ <p class="brand">three.ws</p>+ <h1>You earned a commission</h1>+ <p>A purchase by ${fromHandle ? `<strong>${esc(fromHandle)}</strong>` : 'someone you referred'} earned you a referral commission.</p>+ <table style="width:100%;border-collapse:collapse;margin:8px 0 20px">+ ${row('Commission', `${esc(amount)} ${esc(currency)}`)}+ ${fromHandle ? row('From', esc(fromHandle)) : ''}+ ${skillName ? row('Skill', esc(skillName)) : ''}+ ${date ? row('Date', esc(date)) : ''}+ </table>+ <a class="btn" href="${APP_URL}/dashboard/">View earnings</a>+ <hr>+ <p class="muted">Keep sharing your referral link to keep earning.</p>+ `);+}++function referralCommissionText({ amount, currency, fromHandle, skillName, date }) {+ return [+ `You earned a referral commission — three.ws`,+ ``,+ `Commission: ${amount} ${currency}`,+ fromHandle ? `From: ${fromHandle}` : null,+ skillName ? `Skill: ${skillName}` : null,+ date ? `Date: ${date}` : null,+ ``,+ `View earnings: ${APP_URL}/dashboard/`,+ ].filter(Boolean).join('\n');+}++function shortTx(tx) {+ const s = String(tx || '');+ return s.length > 16 ? `${s.slice(0, 8)}…${s.slice(-6)}` : s;+}+function esc(s) {return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');}diff --git a/api/_lib/migrations/20260621180000_skill_reviews.sql b/api/_lib/migrations/20260621180000_skill_reviews.sqlnew file mode 100644index 000000000..94bfb9d92--- /dev/null+++ b/api/_lib/migrations/20260621180000_skill_reviews.sql@@ -0,0 +1,48 @@+-- Per-skill ratings & reviews for paid skills sold on an agent.+--+-- Distinct from:+-- • agent_reviews — one rating per (agent, user) for the agent as a whole.+-- • skill_ratings — ratings for installable marketplace_skills templates.+--+-- skill_reviews captures social proof for an *individual paid skill* on a+-- specific agent (the (agent_id, skill) pair that agent_skill_prices /+-- skill_purchases are keyed on). Only a user who has actually obtained access+-- to that skill — a confirmed purchase, time-pass, subscription or trial — may+-- leave a review; the API enforces that with hasSkillAccess before insert.+--+-- One review per (agent_id, skill, reviewer); POST upserts in place. Indexes+-- support the two hot paths: per-skill aggregation (avg + count + recent list)+-- and "has this reviewer already reviewed this skill?".+--+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260621180000_skill_reviews.sql+-- Idempotent.++BEGIN;++CREATE TABLE IF NOT EXISTS skill_reviews (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill text NOT NULL,+ reviewer_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),+ body text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (agent_id, skill, reviewer_id)+);++-- Per-skill aggregation (AVG(rating), COUNT(*), recent-first list).+CREATE INDEX IF NOT EXISTS skill_reviews_agent_skill+ ON skill_reviews (agent_id, skill, created_at DESC);++-- "Which skills has this user reviewed?" / fast reviewer lookups.+CREATE INDEX IF NOT EXISTS skill_reviews_reviewer+ ON skill_reviews (reviewer_id);++-- Auto-bump updated_at on upsert/edit; reuse the standard trigger function.+DO $$ BEGIN+ CREATE TRIGGER skill_reviews_set_updated_at BEFORE UPDATE ON skill_reviews+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+EXCEPTION WHEN duplicate_object THEN NULL; END $$;++COMMIT;diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsindex c81450ec4..2272fe3a6 100644--- a/api/_lib/purchase-confirm.js+++ b/api/_lib/purchase-confirm.js@@ -24,6 +24,63 @@ import { sql } from './db.js';import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';import { insertNotification } from './notify.js';import { verifyEvmUsdcPayment, evmChainId } from './evm-payment-verify.js';+import { sendPurchaseReceiptEmail, sendSaleNotificationEmail } from './email.js';+import { creditReferralCommission } from './referrals.js';++const APP_ORIGIN = process.env.APP_ORIGIN || 'https://three.ws';++// USDC and most SPL skill prices use 6 decimals. Render atomic units as a human+// amount (e.g. 1500000 → "1.50") for receipts/notifications.+function formatAmount(atomics, decimals = 6) {+ try {+ const n = Number(BigInt(atomics)) / 10 ** decimals;+ return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 6 });+ } catch {+ return String(atomics);+ }+}++// Best-effort symbol for the currency shown in emails. The platform's only+// settlement asset is USDC; fall back to a short mint label otherwise.+function currencyLabel(mint) {+ if (!mint) return 'USDC';+ const m = String(mint);+ if (/usdc/i.test(m)) return 'USDC';+ return m.length > 10 ? `${m.slice(0, 4)}…${m.slice(-4)}` : m;+}++// Explorer URL for a confirmed payment, by chain.+function txExplorerUrl(chain, txSignature) {+ if (!txSignature) return null;+ if (chain === 'solana') return `https://solscan.io/tx/${txSignature}`;+ if (evmChainId(chain) && /^base/i.test(String(chain))) return `https://basescan.org/tx/${txSignature}`;+ if (evmChainId(chain)) return `https://basescan.org/tx/${txSignature}`;+ return null;+}++// Real, sendable email for a user. Skips missing addresses and the synthetic+// `…@privy.local` placeholders minted for wallet-only Privy accounts — those are+// not deliverable mailboxes.+async function getUserEmail(userId) {+ if (!userId) return null;+ try {+ const [row] = await sql`SELECT email FROM users WHERE id = ${userId} AND deleted_at IS NULL`;+ const email = row?.email;+ if (!email || /@privy\.local$/i.test(email)) return null;+ return email;+ } catch {+ return null;+ }+}++async function getAgentName(agentId) {+ try {+ const [row] = await sql`SELECT name FROM agent_identities WHERE id = ${agentId}`;+ return row?.name || null;+ } catch {+ return null;+ }+}let _rpc;function rpc() {@@ -509,13 +566,21 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfoON CONFLICT (intent_id) DO NOTHING`;if (pur.referrer_user_id && referralAmt > 0n) {- // Track the referrer's accrued earnings. Real payout happens via the- // existing withdrawal flow keyed off this column.- await sql`- UPDATE users- SET referral_earnings_total = COALESCE(referral_earnings_total, 0) + ${Number(referralAmt)}- WHERE id = ${pur.referrer_user_id}- `;+ // Credit the referrer's accrued earnings AND fire the commission email.+ // Real payout happens via the existing withdrawal flow keyed off the+ // referral_earnings_total column. Best-effort; never blocks confirm.+ try {+ const buyerHandle = await getUserDisplay(pur.user_id);+ await creditReferralCommission({+ referrerUserId: pur.referrer_user_id,+ amountAtomics: referralAmt,+ currency: currencyLabel(pur.currency_mint),+ fromHandle: buyerHandle,+ skillName: pur.skill,+ });+ } catch (e) {+ console.error('[purchase-confirm] referral commission credit failed', e?.message);+ }}await emitReceipt(pur, txSignature, payoutAddress, 'purchase');@@ -581,6 +646,18 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfopurchase_id: pur.id,});}++ // 3c. Transactional emails — best-effort, fully isolated from the critical+ // path. A send failure (or missing creds) must never affect the confirmed+ // payment, the access grant, or the response. These complement the in-app+ // notifications above; they do not replace them.+ await sendPurchaseEmails({+ pur,+ txSignature,+ sellerId,+ grossAmt,+ netAmt,+ }).catch((e) => console.error('[purchase-confirm] email dispatch failed', e?.message));}return { status: 'confirmed', tx_signature: txSignature };@@ -698,6 +775,59 @@ async function getSellerUserId(agentId) {return row?.user_id ?? null;}+// Send the buyer receipt + seller sale-notification for a confirmed purchase.+// Best-effort: each send is independently guarded so one failure never blocks+// the other, and the whole function is awaited under a .catch() at the call site+// so nothing here can break the confirmed payment. Skips users without a real,+// deliverable email (wallet-only / Privy accounts). sendEmail itself no-ops when+// RESEND_API_KEY is unset (dev/preview), so these are safe everywhere.+async function sendPurchaseEmails({ pur, txSignature, sellerId, grossAmt, netAmt }) {+ const decimals = pur.mint_decimals ?? 6;+ const currency = currencyLabel(pur.currency_mint);+ const date = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });+ const txUrl = txExplorerUrl(pur.chain, txSignature);+ const agentName = await getAgentName(pur.agent_id);+ const agentUrl = pur.agent_id ? `${APP_ORIGIN}/agents/${encodeURIComponent(pur.agent_id)}` : null;++ // Buyer receipt → the payer (the recipient of a gift didn't pay, so the+ // receipt always goes to whoever was charged).+ const buyerEmail = await getUserEmail(pur.user_id);+ if (buyerEmail) {+ await sendPurchaseReceiptEmail({+ to: buyerEmail,+ skillName: pur.skill,+ agentName,+ agentUrl,+ amount: formatAmount(grossAmt.toString(), decimals),+ currency,+ date,+ txUrl,+ txId: txSignature,+ }).catch((e) => console.error('[purchase-confirm] receipt email failed', e?.message));+ }++ // Seller sale-notification → the agent's owner, with net (post-fee, post-+ // referral) earnings and the buyer's public handle (never their email).+ if (sellerId && sellerId !== pur.user_id) {+ const sellerEmail = await getUserEmail(sellerId);+ if (sellerEmail) {+ const buyerHandle = await getUserDisplay(pur.user_id);+ await sendSaleNotificationEmail({+ to: sellerEmail,+ skillName: pur.skill,+ agentName,+ agentUrl,+ netAmount: formatAmount(netAmt.toString(), decimals),+ currency,+ buyerHandle,+ date,+ txUrl,+ txId: txSignature,+ }).catch((e) => console.error('[purchase-confirm] sale email failed', e?.message));+ }+ }+}+// Best-effort friendly label for a user (gift notifications). Username first,// then display name, then a short id — never the email.async function getUserDisplay(userId) {diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex ab857774a..bbbc53fb2 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -1,6 +1,7 @@import { randomBytes } from 'crypto';import { sql } from './db.js';import { cacheWrap } from './cache.js';+import { sendReferralCommissionEmail } from './email.js';/*** Generates a random, human-readable referral code.@@ -54,11 +55,194 @@ export async function ensureReferralCode(userId) {throw new Error('referral_code_generation_exhausted');}+/**+ * Credit a confirmed referral commission to the referrer and notify them by+ * email. This is the single write-side home for accruing referral earnings:+ * purchase-confirm.js computes the atomic amount on a confirmed sale and calls+ * here so the ledger write and the "you earned a commission" email live+ * together.+ *+ * `referral_earnings_total` accumulates atomic USDC units (6 decimals), the same+ * unit getMembershipCard / getReferredUsers read back.+ *+ * The DB credit is awaited (it's part of recording the sale); the email is+ * strictly best-effort — a send failure (or missing RESEND_API_KEY) is logged,+ * never thrown, so it can never roll back or block the commission credit.+ *+ * @param {object} args+ * @param {string|number} args.referrerUserId who earned the commission+ * @param {bigint|number|string} args.amountAtomics commission in atomic USDC units+ * @param {string} [args.currency] display currency label (default 'USDC')+ * @param {string|null} [args.fromHandle] public handle of the buyer who triggered it+ * @param {string|null} [args.skillName] the skill that was sold+ * @returns {Promise<void>}+ */+export async function creditReferralCommission({+ referrerUserId,+ amountAtomics,+ currency = 'USDC',+ fromHandle = null,+ skillName = null,+}) {+ const amount = BigInt(amountAtomics);+ if (!referrerUserId || amount <= 0n) return;++ await sql`+ UPDATE users+ SET referral_earnings_total = COALESCE(referral_earnings_total, 0) + ${Number(amount)}+ WHERE id = ${referrerUserId}+ `;++ // Email is best-effort and never deliverable to synthetic Privy mailboxes.+ try {+ const [row] = await sql`+ SELECT email FROM users WHERE id = ${referrerUserId} AND deleted_at IS NULL+ `;+ const email = row?.email;+ if (email && !/@privy\.local$/i.test(email)) {+ const usd = (Number(amount) / 1_000_000).toLocaleString('en-US', {+ minimumFractionDigits: 2,+ maximumFractionDigits: 6,+ });+ const date = new Date().toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'short',+ day: 'numeric',+ });+ await sendReferralCommissionEmail({+ to: email,+ amount: usd,+ currency,+ fromHandle,+ skillName,+ date,+ }).catch((e) => console.error('[referrals] commission email failed', e?.message));+ }+ } catch (e) {+ console.error('[referrals] commission email lookup failed', e?.message);+ }+}+// Points awarded per confirmed referral and per whole USD of referral earnings.// Kept here (not inlined) so the score formula has a single, documented home.const POINTS_PER_REFERRAL = 100;const POINTS_PER_USD = 1;+// Referral commission, in basis points, applied to a referred user's confirmed+// purchase total to derive what the referrer earned. Mirrors the server default+// in api/_lib/purchase-confirm.js (REFERRAL_COMMISSION_BPS, default 500 = 5%) so+// the dashboard's per-user "commission" column matches what was actually accrued.+function referralBps() {+ const v = parseInt(process.env.REFERRAL_COMMISSION_BPS || '500', 10);+ return Number.isFinite(v) && v >= 0 ? v : 500;+}++// Pagination bounds for the per-referred-user list. Keeps the join cheap and+// the payload small while letting the UI page through large referral networks.+const REFERRALS_PAGE_DEFAULT = 20;+const REFERRALS_PAGE_MAX = 100;++function clampLimit(limit) {+ const n = Number.parseInt(limit, 10);+ if (!Number.isFinite(n) || n <= 0) return REFERRALS_PAGE_DEFAULT;+ return Math.min(n, REFERRALS_PAGE_MAX);+}++function clampOffset(offset) {+ const n = Number.parseInt(offset, 10);+ if (!Number.isFinite(n) || n < 0) return 0;+ return n;+}++/**+ * Real per-referred-user breakdown for an affiliate dashboard: who signed up+ * with this referrer, when, how much confirmed revenue they generated, and the+ * commission the referrer earned on it.+ *+ * Revenue is the sum of every CONFIRMED purchase a referred user made where this+ * user was the attributed referrer — across both monetization tables:+ * • skill_purchases (referrer_user_id, user_id, amount, status)+ * • asset_purchases (referrer_user_id, buyer_user_id, amount, status)+ * Amounts are atomic USDC units (6 decimals), the same unit purchase-confirm.js+ * accrues into users.referral_earnings_total. Commission is derived from the+ * configured referral BPS so the column matches what was actually credited.+ *+ * Sorted by revenue generated (desc), then most recent signup — the most+ * valuable referrals surface first. Paginated via limit/offset.+ *+ * @param {string|number} userId the referrer+ * @param {{ limit?: number, offset?: number }} [opts]+ * @returns {Promise<{ items: object[], total: number, limit: number, offset: number, referral_commission_bps: number }>}+ */+export async function getReferredUsers(userId, opts = {}) {+ const limit = clampLimit(opts.limit);+ const offset = clampOffset(opts.offset);+ const bps = referralBps();++ // Total referred-user count drives pagination in the UI. Counts every active+ // account attributed to this referrer, regardless of whether they've spent.+ const [{ total }] = await sql`+ SELECT COUNT(*)::int AS total FROM users+ WHERE referred_by_id = ${userId} AND deleted_at IS NULL+ `;++ if (total === 0) {+ return { items: [], total: 0, limit, offset, referral_commission_bps: bps };+ }++ // Per-referred-user revenue, summed from both purchase tables. Each subquery+ // is correlated on the referred user's id AND keyed to this referrer so a+ // buyer's spend only counts toward the referrer who actually owns it. Only+ // confirmed sales count — pending/expired/failed rows are excluded.+ const rows = await sql`+ SELECT+ ru.id,+ ru.username,+ ru.display_name,+ ru.created_at AS signup_date,+ (+ COALESCE((+ SELECT SUM(sp.amount)::bigint+ FROM skill_purchases sp+ WHERE sp.user_id = ru.id+ AND sp.referrer_user_id = ${userId}+ AND sp.status = 'confirmed'+ ), 0)+ ++ COALESCE((+ SELECT SUM(ap.amount)::bigint+ FROM asset_purchases ap+ WHERE ap.buyer_user_id = ru.id+ AND ap.referrer_user_id = ${userId}+ AND ap.status = 'confirmed'+ ), 0)+ )::bigint AS revenue_generated+ FROM users ru+ WHERE ru.referred_by_id = ${userId} AND ru.deleted_at IS NULL+ ORDER BY revenue_generated DESC, ru.created_at DESC, ru.id+ LIMIT ${limit} OFFSET ${offset}+ `;++ const items = rows.map((r) => {+ const revenueAtomics = Math.max(0, Math.round(Number(r.revenue_generated || 0)));+ // Commission credited to the referrer = revenue * bps / 10000, floored to a+ // whole atomic unit to match the integer math in purchase-confirm.js.+ const commissionAtomics = Math.floor((revenueAtomics * bps) / 10000);+ return {+ user_id: r.id,+ username: r.username || null,+ display_name: r.display_name || r.username || null,+ signup_date: r.signup_date,+ revenue_generated: revenueAtomics,+ revenue_generated_usd: revenueAtomics / 1_000_000,+ commission_earned: commissionAtomics,+ commission_earned_usd: commissionAtomics / 1_000_000,+ };+ });++ return { items, total: Number(total || 0), limit, offset, referral_commission_bps: bps };+}+/*** Assemble the full membership-card payload for a user: signup position,* referral code + count, lifetime referral earnings, and a derived score.diff --git a/api/skills/[id].js b/api/skills/[id].jsindex d34226af2..ab0ccb356 100644--- a/api/skills/[id].js+++ b/api/skills/[id].js@@ -4,6 +4,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { cors, json, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse, isUuid } from '../_lib/validate.js';+import skillReviewHandler from './review.js';const updateSchema = z.object({name: z.string().trim().min(2).max(80).optional(),@@ -26,6 +27,10 @@ const updateSchema = z.object({});export default wrap(async (req, res) => {+ // vercel.json routes /api/skills/review → /api/skills/[id]?id=review. Hand the+ // per-skill ratings & reviews path off to its own handler before the UUID gate.+ if (req.query?.id === 'review') return skillReviewHandler(req, res);+if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;diff --git a/api/skills/review.js b/api/skills/review.jsnew file mode 100644index 000000000..bafcdc1b2--- /dev/null+++ b/api/skills/review.js@@ -0,0 +1,248 @@+/**+ * Per-skill ratings & reviews — paid skills sold on an agent.+ * ──────────────────────────────────────────────────────────+ * GET /api/skills/review?agent_id=<uuid>&skill=<name>&page=<n>&page_size=<n>+ * → { data: { summary: { rating_avg, rating_count, breakdown }, reviews, page,+ * page_size, total, has_more, my_review } }+ *+ * POST /api/skills/review+ * body: { agent_id: <uuid>, skill: <name>, rating: 1..5, body?: string<=2000 }+ * → { data: { review, summary: { rating_avg, rating_count } } }+ * 201 on first review, 200 on edit. 403 if the caller has not obtained+ * access to the skill (must own a confirmed purchase / time-pass / sub /+ * active trial); 422 on reviewing your own agent's skill.+ *+ * Reachability: vercel.json routes `/api/skills/<x>` → `/api/skills/[id]?id=<x>`,+ * so `[id].js` delegates `id === 'review'` here (see the early hand-off there).+ * One review per (agent_id, skill, reviewer); POST upserts in place.+ *+ * Schema: api/_lib/migrations/20260621180000_skill_reviews.sql.+ * Ownership is verified with the canonical hasSkillAccess() helper — the same+ * gate the paid-skill execution path uses — so a review can only follow real,+ * on-chain-confirmed access.+ */++import { z } from 'zod';++import { sql } from '../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';+import { hasSkillAccess } from '../_lib/skill-access.js';+import { publishUserEvent } from '../_lib/feed.js';++const SKILL_MAX = 200;++const reviewSchema = z.object({+ agent_id: z.string().trim().uuid(),+ skill: z.string().trim().min(1).max(SKILL_MAX),+ rating: z.number().int().min(1).max(5),+ body: z.string().trim().max(2000).optional().nullable(),+});++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (req.method === 'GET' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'GET')) {+ return handleList(req, res);+ }+ if (req.method === 'POST' || (req.method === 'OPTIONS' && req.headers['access-control-request-method'] === 'POST')) {+ return handleUpsert(req, res);+ }+ return error(res, 405, 'method_not_allowed', 'GET/POST only');+});++// ── list + aggregate (paginated) ──────────────────────────────────────────────++async function handleList(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agent_id');+ const skill = (url.searchParams.get('skill') || '').trim();++ if (!agentId || !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id required');+ if (!skill || skill.length > SKILL_MAX) return error(res, 400, 'validation_error', 'skill required');++ const page = Math.max(1, Number.parseInt(url.searchParams.get('page') || '1', 10) || 1);+ const pageSize = Math.min(50, Math.max(1, Number.parseInt(url.searchParams.get('page_size') || '10', 10) || 10));+ const offset = (page - 1) * pageSize;++ const [agent] = await sql`+ SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ const auth = await resolveAuth(req).catch(() => null);++ const [summary] = await sql`+ SELECT+ COALESCE(AVG(rating)::numeric(3,2), 0) AS rating_avg,+ COUNT(*)::int AS rating_count,+ SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END)::int AS r5,+ SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END)::int AS r4,+ SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END)::int AS r3,+ SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END)::int AS r2,+ SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END)::int AS r1+ FROM skill_reviews+ WHERE agent_id = ${agentId} AND skill = ${skill}+ `;++ const rows = await sql`+ SELECT r.id, r.rating, r.body, r.created_at, r.updated_at,+ r.reviewer_id, u.display_name, u.username, u.avatar_url+ FROM skill_reviews r+ LEFT JOIN users u ON u.id = r.reviewer_id AND u.deleted_at IS NULL+ WHERE r.agent_id = ${agentId} AND r.skill = ${skill}+ ORDER BY r.created_at DESC+ LIMIT ${pageSize} OFFSET ${offset}+ `;++ let myReview = null;+ if (auth) {+ const [mine] = await sql`+ SELECT id, rating, body, created_at, updated_at+ FROM skill_reviews+ WHERE agent_id = ${agentId} AND skill = ${skill} AND reviewer_id = ${auth.userId}+ `;+ if (mine) myReview = mine;+ }++ const total = summary?.rating_count || 0;+ const reviews = rows.map((r) => ({+ id: r.id,+ rating: r.rating,+ body: r.body,+ created_at: r.created_at,+ updated_at: r.updated_at,+ author_name: r.display_name || r.username || 'Anonymous',+ author_avatar: r.avatar_url || null,+ is_mine: !!(auth && r.reviewer_id === auth.userId),+ }));++ return json(+ res,+ 200,+ {+ data: {+ summary: {+ rating_avg: Number(summary?.rating_avg || 0),+ rating_count: total,+ breakdown: {+ 5: summary?.r5 || 0,+ 4: summary?.r4 || 0,+ 3: summary?.r3 || 0,+ 2: summary?.r2 || 0,+ 1: summary?.r1 || 0,+ },+ },+ reviews,+ page,+ page_size: pageSize,+ total,+ has_more: offset + reviews.length < total,+ my_review: myReview,+ },+ },+ { 'cache-control': 'no-store' },+ );+}++// ── upsert (create/update) ────────────────────────────────────────────────────++async function handleUpsert(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const parsed = reviewSchema.safeParse(await readJson(req).catch(() => null));+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'invalid review');+ }+ const { agent_id: agentId, skill, rating } = parsed.data;+ const reviewBody = (parsed.data.body || '').trim() || null;++ const [agent] = await sql`+ SELECT id, user_id, name FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id === auth.userId) {+ return error(res, 422, 'self_review_forbidden', 'you cannot review your own skill');+ }++ // Ownership gate: the reviewer must have real access to this paid skill —+ // a confirmed purchase, time-pass, agent/creator subscription, or active+ // trial. hasSkillAccess is the canonical gate used by the execution path.+ const access = await hasSkillAccess(auth.userId, agentId, skill);+ if (!access.paid) {+ // Free skills aren't sold, so there's no purchase to anchor a review to.+ return error(res, 403, 'not_purchasable', 'only paid skills can be reviewed');+ }+ if (!access.owned) {+ return error(res, 403, 'not_purchased', 'purchase this skill before reviewing it');+ }++ const [row] = await sql`+ INSERT INTO skill_reviews (agent_id, skill, reviewer_id, rating, body)+ VALUES (${agentId}, ${skill}, ${auth.userId}, ${rating}, ${reviewBody})+ ON CONFLICT (agent_id, skill, reviewer_id)+ DO UPDATE SET rating = EXCLUDED.rating, body = EXCLUDED.body, updated_at = now()+ RETURNING id, rating, body, created_at, updated_at+ `;++ const [summary] = await sql`+ SELECT+ COALESCE(AVG(rating)::numeric(3,2), 0) AS rating_avg,+ COUNT(*)::int AS rating_count+ FROM skill_reviews WHERE agent_id = ${agentId} AND skill = ${skill}+ `;++ // Notify the agent owner of a genuinely NEW review (not an edit). On a fresh+ // insert created_at === updated_at; an upsert-update bumps updated_at via the+ // trigger, so this gates out edit spam. Fire-and-forget.+ const isNew = +new Date(row.created_at) === +new Date(row.updated_at);+ if (isNew) {+ const [reviewer] = await sql`+ SELECT display_name, username FROM users WHERE id = ${auth.userId} AND deleted_at IS NULL+ `;+ publishUserEvent(agent.user_id, {+ type: 'skill_review',+ actor: reviewer?.display_name || reviewer?.username || 'Someone',+ agent_id: agentId,+ agent_name: agent.name || null,+ skill,+ rating,+ link: `/agent/${agentId}`,+ });+ }++ return json(res, isNew ? 201 : 200, {+ data: {+ review: row,+ summary: {+ rating_avg: Number(summary?.rating_avg || 0),+ rating_count: summary?.rating_count || 0,+ },+ },+ });+}diff --git a/api/users/referrals.js b/api/users/referrals.jsindex 12fb6c8b1..ad719dba5 100644--- a/api/users/referrals.js+++ b/api/users/referrals.js@@ -1,12 +1,17 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { getMembershipCard } from '../_lib/referrals.js';+import { getMembershipCard, getReferredUsers } from '../_lib/referrals.js';// GET /api/users/referrals — the signed-in user's membership card payload:// referral code (lazily minted if absent), referral count + lifetime earnings,-// signup position ("member #N"), and a derived score. Powers the 3D referral-// card on /dashboard/referrals.+// signup position ("member #N"), and a derived score. Also returns a real,+// paginated per-referred-user breakdown (who signed up, when, revenue they+// generated, and the commission earned) so the affiliate dashboard can show an+// actionable referral table — not just a counter. Powers /dashboard/referrals.+//+// Query params (optional): ?limit (1–100, default 20) & ?offset (>=0) page the+// referred-user list, sorted by revenue generated (desc).export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;@@ -22,5 +27,11 @@ export default wrap(async (req, res) => {const card = await getMembershipCard(userId);if (!card) return error(res, 404, 'not_found', 'user not found');- return json(res, 200, card);+ const url = new URL(req.url, 'http://localhost');+ const referredUsers = await getReferredUsers(userId, {+ limit: url.searchParams.get('limit'),+ offset: url.searchParams.get('offset'),+ });++ return json(res, 200, { ...card, referred_users: referredUsers });});diff --git a/data/changelog.json b/data/changelog.jsonindex 71277605d..4eea15bd3 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,35 @@{"$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-21",+ "title": "Affiliate dashboard now shows who you referred",+ "summary": "The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals.",+ "tags": [+ "improvement"+ ],+ "link": "/dashboard/referrals"+ },+ {+ "date": "2026-06-21",+ "title": "More reliable on-chain transactions across the platform",+ "summary": "Every on-chain action that moves funds — agent transfers, token launches, buys and sells, creator-fee claims, club and lottery payouts, buybacks, and skill purchases — now goes through one hardened sender. It estimates the right priority fee, automatically re-broadcasts your transaction with a fresh blockhash until it actually lands instead of giving up after one try, and treats a transaction that reverts on-chain as a clear failure rather than a silent success. In practice that means far fewer 'stuck' or dropped transactions when the network is busy, and an honest error (with your funds untouched) when something genuinely can't go through. Nothing to do on your end.",+ "tags": [+ "improvement",+ "fix",+ "infra"+ ]+ },+ {+ "date": "2026-06-21",+ "title": "Avatar Studio: full-spectrum color picker and one-tap Looks",+ "summary": "The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/avatar-studio"+ },{"date": "2026-06-21","title": "My Collection page now loads",@@ -20,6 +49,15 @@],"link": "/tour"},+ {+ "date": "2026-06-21",+ "title": "Agent payments now produce a signed receipt of exactly what was bought",+ "summary": "Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement.",+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-21","title": "Free neural voice for agents — high-quality speech, no API key",diff --git a/public/changelog.json b/public/changelog.jsonindex 309547cd4..aa2cdd00b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:55:33.519Z",+ "generated_at": "2026-06-21T08:14:13.200Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -67,6 +67,27 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Affiliate dashboard now shows who you referred",+ "summary": "The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals.",+ "link": "/dashboard/referrals",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Agent payments now produce a signed receipt of exactly what was bought",+ "summary": "Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement.",+ "link": null,+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-21","type": "update",@@ -87,6 +108,17 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Avatar Studio: full-spectrum color picker and one-tap Looks",+ "summary": "The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast.",+ "link": "/avatar-studio",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -294,6 +326,18 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "More reliable on-chain transactions across the platform",+ "summary": "Every on-chain action that moves funds — agent transfers, token launches, buys and sells, creator-fee claims, club and lottery payouts, buybacks, and skill purchases — now goes through one hardened sender. It estimates the right priority fee, automatically re-broadcasts your transaction with a fresh blockhash until it actually lands instead of giving up after one try, and treats a transaction that reverts on-chain as a clear failure rather than a silent success. In practice that means far fewer 'stuck' or dropped transactions when the network is busy, and an honest error (with your funds untouched) when something genuinely can't go through. Nothing to do on your end.",+ "link": null,+ "tags": [+ "improvement",+ "fix",+ "infra"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex f8e4c946d..0a6ac58bb 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -54,6 +54,22 @@<category>improvement</category><description>The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.</description></item>+ <item>+ <title>Affiliate dashboard now shows who you referred</title>+ <link>https://three.ws/dashboard/referrals</link>+ <guid isPermaLink="false">2026-06-21:Affiliate dashboard now shows who you referred</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals.</description>+ </item>+ <item>+ <title>Agent payments now produce a signed receipt of exactly what was bought</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Agent payments now produce a signed receipt of exactly what was bought</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement.</description>+ </item><item><title>Authorize $THREE once, then pay with no wallet popups</title><link>https://three.ws/three-token</link>@@ -70,6 +86,14 @@<category>feature</category><description>The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.</description></item>+ <item>+ <title>Avatar Studio: full-spectrum color picker and one-tap Looks</title>+ <link>https://three.ws/avatar-studio</link>+ <guid isPermaLink="false">2026-06-21:Avatar Studio: full-spectrum color picker and one-tap Looks</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast.</description>+ </item><item><title>Clearer empty state on the $THREE live-trades feed</title><link>https://three.ws/three-token</link>@@ -222,6 +246,14 @@<category>infra</category><description>The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.</description></item>+ <item>+ <title>More reliable on-chain transactions across the platform</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:More reliable on-chain transactions across the platform</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Every on-chain action that moves funds — agent transfers, token launches, buys and sells, creator-fee claims, club and lottery payouts, buybacks, and skill purchases — now goes through one hardened sender. It estimates the right priority fee, automatically re-broadcasts your transaction with a fresh blockhash until it actually lands instead of giving up after one try, and treats a transaction that reverts on-chain as a clear failure rather than a silent success. In practice that means far fewer 'stuck' or dropped transactions when the network is busy, and an honest error (with your funds untouched) when something genuinely can't go through. Nothing to do on your end.</description>+ </item><item><title>My Collection page now loads</title><link>https://three.ws/collection</link>diff --git a/public/features.json b/public/features.jsonindex 9d41f5b20..d60f165e3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:55:33.454Z",+ "generated_at": "2026-06-21T08:14:13.146Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-detail-market.js b/src/agent-detail-market.jsindex b3eb4e3a7..f13bd2752 100644--- a/src/agent-detail-market.js+++ b/src/agent-detail-market.js@@ -38,6 +38,7 @@ import {} from './shared/skill-purchase.js';import { log } from './shared/log.js';import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';+import { mountSkillReviews } from './skill-reviews.js';const API = '/api';const $ = (id) => document.getElementById(id);@@ -55,6 +56,10 @@ function escapeHtml(s) {(ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch],);}+// Safe DOM-id fragment from an arbitrary skill name (used for ARIA panel ids).+function cssId(s) {+ return String(s ?? '').replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 64) || 'x';+}function initial(name) {const s = String(name || '?').trim();return s ? s[0].toUpperCase() : '?';@@ -143,6 +148,10 @@ async function reloadPurchases(agentId) {marketAgent = fresh;purchasedSkills.clear();(fresh.purchased_skills || []).forEach((s) => purchasedSkills.add(s));+ // renderPricing rebuilds the body HTML, detaching any open review panels —+ // tear their handles down first so aborters/listeners don't leak.+ for (const handle of reviewHandles.values()) handle.destroy();+ reviewHandles.clear();renderPricing(fresh);renderSubscriptionTiers(fresh).catch(() => {});} catch (e) {@@ -518,10 +527,27 @@ function renderPricing(a) {} else {badge = `<span class="ad-price-badge free">Free</span>`;}- return `<div class="ad-skill-row"><span class="ad-skill-name">${escapeHtml(name)}</span><span class="ad-skill-actions">${badge}</span></div>`;+ // Per-skill ratings & reviews — paid skills only (a review must anchor to+ // a real purchase). The surface mounts lazily on first expand.+ const isPaid = !!(price && Number(price.amount) > 0);+ let reviewsBlock = '';+ if (isPaid) {+ const safeName = escapeHtml(name);+ const panelId = `ad-skill-reviews-${cssId(name)}`;+ reviewsBlock =+ `<div class="ad-skill-row ad-skill-reviews-row">` ++ `<button type="button" class="ad-skill-reviews-toggle" aria-expanded="false" aria-controls="${panelId}" data-reviews-skill="${safeName}" data-reviews-agent="${escapeHtml(a.id)}">` ++ `<span class="ad-skill-reviews-caret" aria-hidden="true">▸</span> Ratings & reviews` ++ `</button>` ++ `<div class="ad-skill-reviews-panel" id="${panelId}" hidden></div>` ++ `</div>`;+ }+ return `<div class="ad-skill-row"><span class="ad-skill-name">${escapeHtml(name)}</span><span class="ad-skill-actions">${badge}</span></div>${reviewsBlock}`;}).join('');+ bindReviewsDelegation(a);+const lib = $('ad-pricing-library');if (libraryArr.length) {lib.innerHTML =@@ -557,6 +583,75 @@ function bindPurchaseDelegation() {});}+// ── Per-skill reviews (lazy-mounted surface) ──────────────────────────────────++// Live review-surface handles keyed by skill name, so a purchase that completes+// while a panel is open can flip its compose form on without a full re-render.+const reviewHandles = new Map();+let reviewsDelegationBound = false;+let reviewsChromeInjected = false;++// One-time chrome for the per-skill reviews expander. The reviews surface itself+// injects its own `.skr-*` styles; this only styles the toggle row on this page.+function injectReviewsChrome() {+ if (reviewsChromeInjected || typeof document === 'undefined') return;+ reviewsChromeInjected = true;+ const el = document.createElement('style');+ el.id = 'ad-skill-reviews-chrome';+ el.textContent = `+.ad-skill-reviews-row{display:block;padding:0 0 6px}+.ad-skill-reviews-toggle{display:inline-flex;align-items:center;gap:6px;background:none;border:none;padding:4px 0;margin:0;color:var(--ad-muted,rgba(231,233,238,.55));font:inherit;font-size:12px;cursor:pointer;transition:color .12s ease}+.ad-skill-reviews-toggle:hover{color:var(--ad-text,#e7e9ee)}+.ad-skill-reviews-toggle:focus-visible{outline:2px solid var(--ad-cyan,#57c7ff);outline-offset:2px;border-radius:4px}+.ad-skill-reviews-caret{display:inline-block;font-size:10px;transition:transform .12s ease}+.ad-skill-reviews-toggle[aria-expanded="true"]{color:var(--ad-text,#e7e9ee)}+.ad-skill-reviews-panel:not([hidden]){display:block}`;+ document.head.appendChild(el);+}++function bindReviewsDelegation(agent) {+ injectReviewsChrome();+ if (reviewsDelegationBound) return;+ reviewsDelegationBound = true;+ const body = $('ad-pricing-body');+ if (!body) return;+ body.addEventListener('click', (e) => {+ const toggle = e.target.closest?.('.ad-skill-reviews-toggle');+ if (!toggle || !body.contains(toggle)) return;+ const skillName = toggle.dataset.reviewsSkill;+ const agentId = toggle.dataset.reviewsAgent || agent?.id;+ if (!skillName || !agentId) return;++ const panel = toggle.parentElement?.querySelector('.ad-skill-reviews-panel');+ if (!panel) return;+ const expanded = toggle.getAttribute('aria-expanded') === 'true';+ const caret = toggle.querySelector('.ad-skill-reviews-caret');++ if (expanded) {+ toggle.setAttribute('aria-expanded', 'false');+ if (caret) caret.textContent = '▸';+ panel.hidden = true;+ reviewHandles.get(skillName)?.destroy();+ reviewHandles.delete(skillName);+ panel.replaceChildren();+ return;+ }++ toggle.setAttribute('aria-expanded', 'true');+ if (caret) caret.textContent = '▾';+ panel.hidden = false;+ if (!reviewHandles.has(skillName)) {+ const handle = mountSkillReviews(panel, {+ agentId,+ skill: skillName,+ canReview: purchasedSkills.has(skillName),+ isOwner: !!(agent && agent.is_owner),+ });+ reviewHandles.set(skillName, handle);+ }+ });+}+// ── Subscription tiers ─────────────────────────────────────────────────────────let marketTiers = [];diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.jsindex 613e7f869..880054e53 100644--- a/src/dashboard-next/pages/referrals.js+++ b/src/dashboard-next/pages/referrals.js@@ -88,6 +88,25 @@ function memberSinceLabel(memberSince) {return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });}+/** "Jun 21, 2026" — full signup date for the referrals table. */+function fmtDate(value) {+ if (!value) return '—';+ const d = new Date(value);+ if (Number.isNaN(d.getTime())) return '—';+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });+}++/** Privacy-preserving display for a referred user with no public username. */+function maskedHandle(item) {+ if (item.display_name) return item.display_name;+ if (item.username) return `@${item.username}`;+ return 'Anonymous member';+}++// Referred-user list pagination size. Matches the server default so the first+// page is a single request with no over-fetch.+const REF_PAGE_SIZE = 20;+// ── styles (scoped, injected once) ──────────────────────────────────────────function injectStyles() {@@ -193,6 +212,51 @@ function injectStyles() {.ref-rail{flex-direction:row;flex-wrap:wrap;justify-content:center}.ref-tip{display:none}}++ /* ── referred-users table ───────────────────────────────────────────── */+ .ref-list-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px}+ .ref-list-count{font-size:12.5px;color:var(--nxt-ink-fade);font-family:${MONO}}+ .ref-tablewrap{overflow-x:auto;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm,12px);background:rgba(255,255,255,.012)}+ .ref-table{width:100%;border-collapse:collapse;font-size:13.5px;min-width:520px}+ .ref-table thead th{+ text-align:left;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;+ color:var(--nxt-ink-fade);font-weight:600;padding:11px 16px;+ border-bottom:1px solid var(--nxt-stroke);white-space:nowrap;background:rgba(255,255,255,.02)}+ .ref-table thead th.num,.ref-table tbody td.num{text-align:right;font-family:${MONO}}+ .ref-table tbody td{padding:13px 16px;border-bottom:1px solid var(--nxt-stroke);color:var(--nxt-ink);vertical-align:middle}+ .ref-table tbody tr:last-child td{border-bottom:none}+ .ref-table tbody tr{transition:background .12s ease}+ .ref-table tbody tr:hover{background:rgba(167,139,250,.06)}+ .ref-table tbody tr:focus-within{background:rgba(167,139,250,.08)}+ .ref-user{display:flex;align-items:center;gap:10px;min-width:0}+ .ref-avatar{flex:0 0 auto;width:28px;height:28px;border-radius:50%;display:grid;place-items:center;+ background:linear-gradient(135deg,#3a2680,#241a4d);color:#c4b5fd;font-size:12px;font-weight:700;font-family:${MONO};+ border:1px solid rgba(167,139,250,.3)}+ .ref-user-name{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:200px}+ .ref-table .ref-commission{color:#86efac;font-weight:600}+ .ref-table .ref-zero{color:var(--nxt-ink-fade)}+ .ref-pager{display:flex;align-items:center;justify-content:flex-end;gap:10px;margin-top:14px}+ .ref-pager-info{font-size:12.5px;color:var(--nxt-ink-fade);font-family:${MONO};margin-right:auto}+ .ref-pgbtn{display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,.04);+ border:1px solid var(--nxt-stroke-strong);border-radius:9px;padding:7px 13px;color:var(--nxt-ink);+ font-size:13px;cursor:pointer;transition:background .12s ease,border-color .12s ease,transform .1s ease}+ .ref-pgbtn:hover:not(:disabled){background:rgba(167,139,250,.16);border-color:rgba(167,139,250,.5)}+ .ref-pgbtn:active:not(:disabled){transform:translateY(1px)}+ .ref-pgbtn:focus-visible{outline:none;box-shadow:0 0 0 3px rgba(167,139,250,.4)}+ .ref-pgbtn:disabled{opacity:.4;cursor:not-allowed}+ .ref-empty{padding:36px 24px;text-align:center}+ .ref-empty svg{opacity:.5;margin-bottom:12px}+ .ref-empty h4{margin:0 0 6px;font-size:15px;color:var(--nxt-ink)}+ .ref-empty p{margin:0 0 16px;font-size:13px;color:var(--nxt-ink-dim);line-height:1.5;max-width:340px;margin-left:auto;margin-right:auto}+ .ref-skel-row td{padding:13px 16px;border-bottom:1px solid var(--nxt-stroke)}+ .ref-skel-bar{height:12px;border-radius:6px;background:linear-gradient(90deg,rgba(255,255,255,.05),rgba(255,255,255,.1),rgba(255,255,255,.05));+ background-size:200% 100%;animation:ref-shim2 1.4s infinite}+ @keyframes ref-shim2{0%{background-position:200% 0}100%{background-position:-200% 0}}+ @media (prefers-reduced-motion: reduce){.ref-skel-bar{animation:none}}+ @media (max-width:560px){+ .ref-pager{flex-wrap:wrap}+ .ref-pager-info{width:100%;margin-bottom:6px}+ }`;document.head.appendChild(s);}@@ -401,6 +465,8 @@ function renderCard(host, card) {<div class="ref-tile"><div class="ref-tile-k">Score</div><div class="ref-tile-v">${fmtInt(card.score)}</div></div></div>+ <section class="dn-panel" style="margin-top:20px" data-slot="referrals-list" aria-label="Your referrals"></section>+<section class="dn-panel" style="margin-top:20px"><div class="dn-panel-title" style="margin-bottom:14px">How referrals work</div><div class="ref-steps">@@ -412,6 +478,7 @@ function renderCard(host, card) {`;wireCard(host, card, refUrl);+ mountReferralsList(host.querySelector('[data-slot="referrals-list"]'), refUrl, card.referred_users);}function wireCard(host, card, refUrl) {@@ -480,6 +547,173 @@ function wireCard(host, card, refUrl) {});}+// ── referred-users table ──────────────────────────────────────────────────────++const PEOPLE_ICON = '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M16 19v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 19v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>';++function initials(item) {+ const src = item.display_name || item.username || '';+ const letters = src.replace(/[^a-zA-Z0-9]/g, '').slice(0, 2).toUpperCase();+ return letters || '?';+}++function referralRow(item) {+ const name = maskedHandle(item);+ const rev = Number(item.revenue_generated_usd || 0);+ const comm = Number(item.commission_earned_usd || 0);+ return `+ <tr tabindex="0">+ <td>+ <div class="ref-user">+ <span class="ref-avatar" aria-hidden="true">${esc(initials(item))}</span>+ <span class="ref-user-name" title="${esc(name)}">${esc(name)}</span>+ </div>+ </td>+ <td>${esc(fmtDate(item.signup_date))}</td>+ <td class="num ${rev > 0 ? '' : 'ref-zero'}">${esc(fmtUsd(rev))}</td>+ <td class="num ${comm > 0 ? 'ref-commission' : 'ref-zero'}">${esc(fmtUsd(comm))}</td>+ </tr>`;+}++function referralsTableShell(rowsHtml) {+ return `+ <div class="ref-tablewrap">+ <table class="ref-table">+ <thead>+ <tr>+ <th scope="col">Referred user</th>+ <th scope="col">Signup date</th>+ <th scope="col" class="num">Revenue generated</th>+ <th scope="col" class="num">Your commission</th>+ </tr>+ </thead>+ <tbody data-ref-tbody>${rowsHtml}</tbody>+ </table>+ </div>`;+}++function skeletonRows(n = 5) {+ let html = '';+ for (let i = 0; i < n; i++) {+ html += `<tr class="ref-skel-row">+ <td><div class="ref-user"><span class="ref-skel-bar" style="width:28px;height:28px;border-radius:50%"></span><span class="ref-skel-bar" style="width:120px"></span></div></td>+ <td><span class="ref-skel-bar" style="width:88px;display:inline-block"></span></td>+ <td class="num"><span class="ref-skel-bar" style="width:64px;display:inline-block"></span></td>+ <td class="num"><span class="ref-skel-bar" style="width:52px;display:inline-block"></span></td>+ </tr>`;+ }+ return html;+}++function renderReferralsEmpty(host) {+ host.innerHTML = `+ <div class="ref-empty">+ ${PEOPLE_ICON}+ <h4>No referrals yet</h4>+ <p>Share your link above — when someone signs up through it and starts spending, they'll show up here with the revenue they generate and your commission.</p>+ <button class="dn-btn primary" data-action="copy-from-empty" style="padding:0 18px;height:38px">Copy referral link</button>+ </div>`;+}++function renderReferralsError(host, message, onRetry) {+ host.innerHTML = `+ <div class="ref-empty">+ <h4>Couldn't load your referrals</h4>+ <p>${esc(message || 'Try again in a moment.')}</p>+ <button class="dn-btn" data-action="retry-list" style="padding:0 18px;height:38px">Retry</button>+ </div>`;+ host.querySelector('[data-action="retry-list"]').addEventListener('click', onRetry);+}++// Stateful, paginated referrals list. Renders into `host` and refetches per page+// without touching the membership card. First page may be hydrated from the+// initial card payload to avoid a duplicate request.+function mountReferralsList(host, refUrl, seed) {+ const state = {+ offset: 0,+ limit: seed?.limit || REF_PAGE_SIZE,+ total: typeof seed?.total === 'number' ? seed.total : null,+ loading: false,+ };++ function renderPage(payload) {+ state.total = payload.total;+ state.limit = payload.limit || state.limit;+ state.offset = payload.offset || 0;++ const totalLabel = `${fmtInt(state.total)} ${state.total === 1 ? 'referral' : 'referrals'}`;+ if (!payload.items || payload.items.length === 0) {+ if (state.total === 0) {+ host.innerHTML = `<div class="ref-list-head"><h3 class="dn-panel-title" style="margin:0">Your referrals</h3></div>`;+ const slot = document.createElement('div');+ host.appendChild(slot);+ renderReferralsEmpty(slot);+ const copyBtn = slot.querySelector('[data-action="copy-from-empty"]');+ if (copyBtn) copyBtn.addEventListener('click', () => copyToClipboard(refUrl));+ return;+ }+ // Past the last page (e.g. data shrank) — step back.+ if (state.offset > 0) { go(Math.max(0, state.offset - state.limit)); return; }+ }++ const start = state.offset + 1;+ const end = state.offset + payload.items.length;+ const pages = Math.max(1, Math.ceil(state.total / state.limit));+ const currentPage = Math.floor(state.offset / state.limit) + 1;+ const hasPrev = state.offset > 0;+ const hasNext = state.offset + state.limit < state.total;++ host.innerHTML = `+ <div class="ref-list-head">+ <h3 class="dn-panel-title" style="margin:0">Your referrals</h3>+ <span class="ref-list-count">${esc(totalLabel)}</span>+ </div>+ ${referralsTableShell(payload.items.map(referralRow).join(''))}+ ${state.total > state.limit ? `+ <div class="ref-pager">+ <span class="ref-pager-info">Showing ${fmtInt(start)}–${fmtInt(end)} of ${fmtInt(state.total)} · page ${fmtInt(currentPage)}/${fmtInt(pages)}</span>+ <button class="ref-pgbtn" data-action="prev" ${hasPrev ? '' : 'disabled'} aria-label="Previous page">‹ Prev</button>+ <button class="ref-pgbtn" data-action="next" ${hasNext ? '' : 'disabled'} aria-label="Next page">Next ›</button>+ </div>` : ''}+ `;+ const prev = host.querySelector('[data-action="prev"]');+ const next = host.querySelector('[data-action="next"]');+ if (prev) prev.addEventListener('click', () => go(Math.max(0, state.offset - state.limit)));+ if (next) next.addEventListener('click', () => go(state.offset + state.limit));+ }++ function renderLoading() {+ host.innerHTML = `+ <div class="ref-list-head">+ <h3 class="dn-panel-title" style="margin:0">Your referrals</h3>+ <span class="ref-list-count">Loading…</span>+ </div>+ ${referralsTableShell(skeletonRows(Math.min(5, state.limit)))}`;+ }++ async function go(offset) {+ if (state.loading) return;+ state.loading = true;+ state.offset = offset;+ renderLoading();+ try {+ const data = await get(`/api/users/referrals?limit=${state.limit}&offset=${offset}`);+ renderPage(data?.referred_users || { items: [], total: 0, limit: state.limit, offset });+ } catch (err) {+ renderReferralsError(host, err?.message, () => go(offset));+ } finally {+ state.loading = false;+ }+ }++ // Hydrate from the seed (the membership-card request already fetched page 0).+ if (seed && seed.items) {+ renderPage(seed);+ } else {+ go(0);+ }+}+function renderError(host, message) {host.innerHTML = `<div class="dn-empty" style="padding:40px 24px">diff --git a/src/skill-reviews.js b/src/skill-reviews.jsnew file mode 100644index 000000000..7b65a83f9--- /dev/null+++ b/src/skill-reviews.js@@ -0,0 +1,376 @@+/**+ * Per-skill ratings & reviews surface.+ * ────────────────────────────────────+ * A small, self-contained module that renders the average rating, an+ * accessible star-rating widget, and the review list for a single paid skill+ * on an agent. It talks to /api/skills/review (GET list/aggregate, POST upsert).+ *+ * Designed states: loading skeleton · empty ("be the first") · error (with+ * retry) · populated. The compose form only appears when the caller signals+ * the viewer owns the skill (canReview); everyone can read.+ *+ * Usage:+ * import { mountSkillReviews } from './skill-reviews.js';+ * const handle = mountSkillReviews(container, { agentId, skill, canReview, isOwner });+ * handle.setCanReview(true); // re-render the form after a purchase completes+ * handle.destroy(); // detach listeners+ *+ * The widget is keyboard-operable (radiogroup of stars, arrow keys + 1–5) and+ * ARIA-labelled. Styles are injected once, scoped under `.skr-*`, mirroring the+ * agent-detail token vocabulary (--ad-*) so it blends into that page without+ * touching its stylesheet.+ */++import { apiPostWithCsrf } from './shared/skill-purchase.js';+import { log } from './shared/log.js';++const API = '/api';+const PAGE_SIZE = 5;++function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch],+ );+}++function relativeTime(iso) {+ if (!iso) return '';+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return '';+ const secs = Math.round((Date.now() - then) / 1000);+ const units = [+ ['year', 31536000], ['month', 2592000], ['week', 604800],+ ['day', 86400], ['hour', 3600], ['minute', 60],+ ];+ for (const [name, span] of units) {+ const n = Math.floor(secs / span);+ if (n >= 1) return `${n} ${name}${n === 1 ? '' : 's'} ago`;+ }+ return 'just now';+}++// Static (display-only) star row. `value` may be fractional for averages.+function starsStatic(value, { size = 16 } = {}) {+ const v = Math.max(0, Math.min(5, Number(value) || 0));+ let html = `<span class="skr-stars-static" aria-hidden="true" style="--skr-star-size:${size}px">`;+ for (let i = 1; i <= 5; i += 1) {+ const fill = Math.max(0, Math.min(1, v - (i - 1)));+ html += `<span class="skr-star"><span class="skr-star-fill" style="width:${Math.round(fill * 100)}%">★</span><span class="skr-star-empty">★</span></span>`;+ }+ html += '</span>';+ return html;+}++let stylesInjected = false;+function injectStyles() {+ if (stylesInjected || typeof document === 'undefined') return;+ stylesInjected = true;+ const css = `+.skr-root{margin-top:14px;border-top:1px solid var(--ad-line,rgba(255,255,255,.07));padding-top:14px;font:inherit;color:var(--ad-text,#e7e9ee)}+.skr-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:10px}+.skr-head-avg{display:flex;align-items:baseline;gap:6px}+.skr-avg-num{font-size:22px;font-weight:700;line-height:1}+.skr-avg-count{font-size:12px;color:var(--ad-muted,rgba(231,233,238,.55))}+.skr-stars-static{display:inline-flex;gap:2px;line-height:1}+.skr-star{position:relative;display:inline-block;width:var(--skr-star-size,16px);height:var(--skr-star-size,16px);font-size:var(--skr-star-size,16px)}+.skr-star-empty{color:var(--ad-line-2,rgba(255,255,255,.12))}+.skr-star-fill{position:absolute;left:0;top:0;overflow:hidden;color:var(--ad-amber,#f5a524);white-space:nowrap}+.skr-list{display:flex;flex-direction:column;gap:10px}+.skr-item{background:var(--ad-bg-2,#141414);border:1px solid var(--ad-line,rgba(255,255,255,.07));border-radius:10px;padding:10px 12px;animation:skr-in .25s ease}+.skr-item.is-mine{border-color:var(--ad-cyan,#57c7ff)}+.skr-item-top{display:flex;align-items:center;gap:8px;margin-bottom:4px}+.skr-ava{width:24px;height:24px;border-radius:50%;background:var(--ad-card,#181818);display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;color:var(--ad-muted,rgba(231,233,238,.55));overflow:hidden;flex:0 0 auto}+.skr-ava img{width:100%;height:100%;object-fit:cover}+.skr-author{font-size:13px;font-weight:600}+.skr-mine-tag{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--ad-cyan,#57c7ff);border:1px solid var(--ad-cyan,#57c7ff);border-radius:999px;padding:1px 6px}+.skr-time{font-size:11px;color:var(--ad-dim,rgba(231,233,238,.35));margin-left:auto}+.skr-body{font-size:13px;line-height:1.5;color:var(--ad-text,#e7e9ee);white-space:pre-wrap;word-break:break-word;margin:4px 0 0}+.skr-empty,.skr-error{font-size:13px;color:var(--ad-muted,rgba(231,233,238,.55));padding:14px;text-align:center;background:var(--ad-bg-2,#141414);border:1px dashed var(--ad-line-2,rgba(255,255,255,.12));border-radius:10px}+.skr-error{border-style:solid;color:var(--ad-amber,#f5a524)}+.skr-retry{margin-top:8px;display:inline-block;background:none;border:1px solid var(--ad-line-2,rgba(255,255,255,.12));color:var(--ad-text,#e7e9ee);border-radius:8px;padding:5px 12px;font-size:12px;cursor:pointer}+.skr-retry:hover{border-color:var(--ad-text,#e7e9ee)}+.skr-more{margin:6px auto 0;display:block;background:none;border:1px solid var(--ad-line-2,rgba(255,255,255,.12));color:var(--ad-muted,rgba(231,233,238,.55));border-radius:8px;padding:6px 14px;font-size:12px;cursor:pointer}+.skr-more:hover{border-color:var(--ad-text,#e7e9ee);color:var(--ad-text,#e7e9ee)}+.skr-more:disabled{opacity:.5;cursor:default}+.skr-form{margin-top:12px;background:var(--ad-bg-2,#141414);border:1px solid var(--ad-line,rgba(255,255,255,.07));border-radius:10px;padding:12px}+.skr-form-label{font-size:12px;text-transform:uppercase;letter-spacing:.04em;color:var(--ad-muted,rgba(231,233,238,.55));display:block;margin-bottom:6px}+.skr-rate{display:inline-flex;gap:4px;margin-bottom:10px}+.skr-rate-star{background:none;border:none;padding:0;margin:0;cursor:pointer;font-size:26px;line-height:1;color:var(--ad-line-2,rgba(255,255,255,.12));transition:color .12s ease,transform .12s ease}+.skr-rate-star[aria-checked="true"],.skr-rate-star.is-lit{color:var(--ad-amber,#f5a524)}+.skr-rate-star:hover{transform:scale(1.12)}+.skr-rate:focus-within{outline:none}+.skr-rate-star:focus-visible{outline:2px solid var(--ad-cyan,#57c7ff);outline-offset:2px;border-radius:4px}+.skr-textarea{width:100%;box-sizing:border-box;background:var(--ad-bg,#0d0d0d);border:1px solid var(--ad-line,rgba(255,255,255,.07));border-radius:8px;color:var(--ad-text,#e7e9ee);font:inherit;font-size:13px;padding:8px 10px;resize:vertical;min-height:60px}+.skr-textarea:focus{outline:none;border-color:var(--ad-cyan,#57c7ff)}+.skr-form-row{display:flex;align-items:center;gap:10px;margin-top:8px}+.skr-count{font-size:11px;color:var(--ad-dim,rgba(231,233,238,.35));margin-left:auto}+.skr-submit{background:var(--ad-text,#e7e9ee);color:var(--ad-bg,#0d0d0d);border:none;border-radius:8px;padding:7px 16px;font-size:13px;font-weight:600;cursor:pointer;transition:opacity .12s ease}+.skr-submit:hover{opacity:.85}+.skr-submit:disabled{opacity:.4;cursor:default}+.skr-form-msg{font-size:12px;margin-top:8px}+.skr-form-msg.err{color:var(--ad-amber,#f5a524)}+.skr-form-msg.ok{color:var(--ad-green,#4ade80)}+.skr-skel{display:flex;flex-direction:column;gap:10px}+.skr-skel-row{height:48px;border-radius:10px;background:linear-gradient(100deg,var(--skeleton-base,rgba(255,255,255,.04)) 30%,var(--skeleton-sheen,rgba(255,255,255,.08)) 50%,var(--skeleton-base,rgba(255,255,255,.04)) 70%);background-size:200% 100%;animation:skr-shimmer 1.4s ease-in-out infinite}+@keyframes skr-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}+@keyframes skr-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}+@media (max-width:480px){.skr-avg-num{font-size:18px}.skr-rate-star{font-size:22px}}+@media (prefers-reduced-motion:reduce){.skr-item,.skr-skel-row{animation:none}.skr-rate-star:hover{transform:none}}+`;+ const el = document.createElement('style');+ el.id = 'skr-styles';+ el.textContent = css;+ document.head.appendChild(el);+}++/**+ * Mount the reviews surface inside `container` for one (agentId, skill).+ * Returns a handle with { setCanReview, refresh, destroy }.+ */+export function mountSkillReviews(container, { agentId, skill, canReview = false, isOwner = false } = {}) {+ if (!container || !agentId || !skill) {+ return { setCanReview() {}, refresh() {}, destroy() {} };+ }+ injectStyles();++ const state = {+ summary: { rating_avg: 0, rating_count: 0 },+ reviews: [],+ page: 1,+ hasMore: false,+ total: 0,+ myReview: null,+ status: 'loading', // loading | error | ready+ canReview,+ isOwner,+ formRating: 0,+ submitting: false,+ };++ const root = document.createElement('div');+ root.className = 'skr-root';+ root.setAttribute('aria-label', `Reviews for ${skill}`);+ container.appendChild(root);++ function reviewItemHtml(r) {+ const ava = r.author_avatar+ ? `<span class="skr-ava"><img src="${esc(r.author_avatar)}" alt=""></span>`+ : `<span class="skr-ava">${esc((r.author_name || '?').trim().charAt(0).toUpperCase() || '?')}</span>`;+ return `+ <li class="skr-item${r.is_mine ? ' is-mine' : ''}">+ <div class="skr-item-top">+ ${ava}+ <span class="skr-author">${esc(r.author_name || 'Anonymous')}</span>+ ${r.is_mine ? '<span class="skr-mine-tag">You</span>' : ''}+ ${starsStatic(r.rating, { size: 13 })}+ <span class="skr-time">${esc(relativeTime(r.created_at))}</span>+ </div>+ ${r.body ? `<p class="skr-body">${esc(r.body)}</p>` : ''}+ </li>`;+ }++ function formHtml() {+ if (state.isOwner) return '';+ if (!state.canReview) return '';+ const editing = !!state.myReview;+ const rating = state.formRating || state.myReview?.rating || 0;+ const bodyVal = state.myReview?.body || '';+ const starBtns = [1, 2, 3, 4, 5].map((n) => `+ <button type="button" role="radio" class="skr-rate-star${n <= rating ? ' is-lit' : ''}"+ aria-checked="${n === rating}" aria-label="${n} star${n === 1 ? '' : 's'}"+ tabindex="${n === (rating || 1) ? '0' : '-1'}" data-val="${n}">★</button>`).join('');+ return `+ <form class="skr-form" novalidate>+ <span class="skr-form-label" id="skr-rate-label-${esc(agentId)}">${editing ? 'Update your rating' : 'Rate this skill'}</span>+ <div class="skr-rate" role="radiogroup" aria-labelledby="skr-rate-label-${esc(agentId)}">${starBtns}</div>+ <textarea class="skr-textarea" maxlength="2000" placeholder="Share what worked (optional)…" aria-label="Review comment">${esc(bodyVal)}</textarea>+ <div class="skr-form-row">+ <span class="skr-count">0 / 2000</span>+ <button type="submit" class="skr-submit" disabled>${editing ? 'Update review' : 'Submit review'}</button>+ </div>+ <div class="skr-form-msg" role="status" aria-live="polite"></div>+ </form>`;+ }++ function listHtml() {+ if (!state.reviews.length) {+ const prompt = state.canReview && !state.isOwner+ ? 'Be the first to review this skill.'+ : state.isOwner+ ? 'No reviews yet for this skill.'+ : 'No reviews yet — purchase this skill to leave the first one.';+ return `<div class="skr-empty">${esc(prompt)}</div>`;+ }+ const items = state.reviews.map(reviewItemHtml).join('');+ const more = state.hasMore+ ? `<button type="button" class="skr-more">Show more reviews</button>`+ : '';+ return `<ul class="skr-list" style="list-style:none;margin:0;padding:0">${items}</ul>${more}`;+ }++ function render() {+ if (state.status === 'loading') {+ root.innerHTML = `<div class="skr-skel">${'<div class="skr-skel-row"></div>'.repeat(3)}</div>`;+ return;+ }+ if (state.status === 'error') {+ root.innerHTML = `<div class="skr-error">Couldn't load reviews.<br><button type="button" class="skr-retry">Retry</button></div>`;+ root.querySelector('.skr-retry')?.addEventListener('click', () => load(1));+ return;+ }+ const count = state.summary.rating_count;+ const head = count+ ? `<div class="skr-head">+ <div class="skr-head-avg">+ <span class="skr-avg-num">${state.summary.rating_avg.toFixed(1)}</span>+ ${starsStatic(state.summary.rating_avg, { size: 18 })}+ </div>+ <span class="skr-avg-count">${count} review${count === 1 ? '' : 's'}</span>+ </div>`+ : '';+ root.innerHTML = head + listHtml() + formHtml();+ bindAfterRender();+ }++ function bindAfterRender() {+ root.querySelector('.skr-more')?.addEventListener('click', () => load(state.page + 1, true));++ const form = root.querySelector('.skr-form');+ if (!form) return;+ const radiogroup = form.querySelector('.skr-rate');+ const stars = Array.from(form.querySelectorAll('.skr-rate-star'));+ const textarea = form.querySelector('.skr-textarea');+ const counter = form.querySelector('.skr-count');+ const submit = form.querySelector('.skr-submit');+ const msg = form.querySelector('.skr-form-msg');++ function syncCounter() {+ const len = textarea.value.length;+ counter.textContent = `${len} / 2000`;+ submit.disabled = state.submitting || !(state.formRating || state.myReview?.rating);+ }++ function paint(rating, hover) {+ stars.forEach((s) => {+ const v = Number(s.dataset.val);+ const lit = v <= (hover || rating);+ s.classList.toggle('is-lit', lit);+ s.setAttribute('aria-checked', String(v === rating));+ s.tabIndex = v === (rating || 1) ? 0 : -1;+ });+ }++ function setRating(n) {+ state.formRating = n;+ paint(n);+ syncCounter();+ }++ stars.forEach((s) => {+ const v = Number(s.dataset.val);+ s.addEventListener('click', () => { setRating(v); s.focus(); });+ s.addEventListener('mouseenter', () => paint(state.formRating || state.myReview?.rating || 0, v));+ s.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {+ e.preventDefault(); setRating(Math.min(5, v + 1));+ stars[Math.min(4, v)].focus();+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {+ e.preventDefault(); setRating(Math.max(1, v - 1));+ stars[Math.max(0, v - 2)].focus();+ } else if (e.key === ' ' || e.key === 'Enter') {+ e.preventDefault(); setRating(v);+ } else if (/^[1-5]$/.test(e.key)) {+ e.preventDefault(); const n = Number(e.key); setRating(n); stars[n - 1].focus();+ }+ });+ });+ radiogroup.addEventListener('mouseleave', () => paint(state.formRating || state.myReview?.rating || 0));++ textarea.addEventListener('input', syncCounter);+ // Seed counter/submit from any pre-filled (editing) values.+ state.formRating = state.formRating || state.myReview?.rating || 0;+ paint(state.formRating);+ syncCounter();++ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ const rating = state.formRating || state.myReview?.rating || 0;+ if (!rating || state.submitting) return;+ state.submitting = true;+ submit.disabled = true;+ msg.className = 'skr-form-msg';+ msg.textContent = 'Saving…';+ try {+ const resp = await apiPostWithCsrf(`${API}/skills/review`, {+ agent_id: agentId,+ skill,+ rating,+ body: textarea.value.trim() || null,+ });+ const data = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ const code = data?.error || data?.code;+ const human = code === 'unauthorized'+ ? 'Sign in to leave a review.'+ : code === 'not_purchased' || code === 'not_purchasable'+ ? 'Purchase this skill before reviewing it.'+ : data?.error_description || data?.message || 'Could not save your review.';+ throw new Error(human);+ }+ msg.className = 'skr-form-msg ok';+ msg.textContent = state.myReview ? 'Review updated.' : 'Thanks for your review!';+ await load(1);+ } catch (err) {+ log.warn('[skill-reviews] submit failed:', err?.message);+ state.submitting = false;+ msg.className = 'skr-form-msg err';+ msg.textContent = err?.message || 'Could not save your review.';+ submit.disabled = false;+ }+ });+ }++ let aborter = null;+ async function load(page = 1, append = false) {+ if (aborter) aborter.abort();+ aborter = new AbortController();+ if (!append) { state.status = 'loading'; render(); }+ try {+ const url = `${API}/skills/review?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(skill)}&page=${page}&page_size=${PAGE_SIZE}`;+ const resp = await fetch(url, { credentials: 'include', signal: aborter.signal });+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);+ const { data } = await resp.json();+ state.summary = data.summary || state.summary;+ state.total = data.total || 0;+ state.hasMore = !!data.has_more;+ state.page = data.page || page;+ state.myReview = data.my_review || null;+ state.formRating = state.myReview?.rating || 0;+ state.submitting = false;+ state.reviews = append ? state.reviews.concat(data.reviews || []) : (data.reviews || []);+ state.status = 'ready';+ render();+ } catch (err) {+ if (err?.name === 'AbortError') return;+ log.warn('[skill-reviews] load failed:', err?.message);+ state.status = 'error';+ render();+ }+ }++ load(1);++ return {+ setCanReview(v) {+ if (state.canReview === !!v) return;+ state.canReview = !!v;+ if (state.status === 'ready') render();+ },+ refresh() { load(1); },+ destroy() {+ if (aborter) aborter.abort();+ root.remove();+ },+ };+}diff --git a/tasks/CLEANUP-MANIFEST.md b/tasks/CLEANUP-MANIFEST.mdindex 078c15201..b9e2754d1 100644--- a/tasks/CLEANUP-MANIFEST.md+++ b/tasks/CLEANUP-MANIFEST.md@@ -193,3 +193,11 @@ Retired (feature verified shipped):|---|---|---|| tasks/walk/19-walk-npc-companions.md | DELETE | Built: src/walk-npcs.js (greeter/wanderer/guide FSM, real GLBs michelle/xbot/realistic-female, AnimationManager clips, disposal, cap 4) + per-env public/environments/*/dialogue.json + src/walk.js spawn/update/toggle. || tasks/walk/34-section-narration-as-avatar-walks.md | DELETE | Built: src/walk-companion-narrator.js (data-walk-narrate + heading fallback, IntersectionObserver, caption aria-live + optional real /api/tts/speak voice, off/caption/voice toggle) wired into src/walk-companion.js. |++## 2026-06-21 built-and-shipped (monetization batch A)++| spec file | decision | evidence |+|---|---|---|+| tasks/monetization-feature/17-transactional-emails.md | DELETE | Built: sendPurchaseReceiptEmail/sendSaleNotificationEmail/sendReferralCommissionEmail in api/_lib/email.js, triggered in api/_lib/purchase-confirm.js + api/_lib/referrals.js (creditReferralCommission), best-effort. |+| tasks/monetization-feature/21-user-ratings-and-reviews.md | DELETE | Built: skill_reviews migration + api/skills/review.js (purchase-verified via hasSkillAccess) + src/skill-reviews.js mounted on src/agent-detail-market.js; route via api/skills/[id].js delegation. |+| tasks/monetization-feature/19-affiliate-dashboard-improvements.md | DELETE | Built: getReferredUsers in api/_lib/referrals.js + per-user list in GET /api/users/referrals + table in src/dashboard-next/pages/referrals.js (real joins over skill_purchases/asset_purchases). |diff --git a/tasks/monetization-feature/17-transactional-emails.md b/tasks/monetization-feature/17-transactional-emails.mddeleted file mode 100644index 35ac000f3..000000000--- a/tasks/monetization-feature/17-transactional-emails.md+++ /dev/null@@ -1,80 +0,0 @@-----status: not-started------# Prompt 17: Backend - Transactional Emails--## Objective-Implement automated transactional emails for key monetization events to keep users informed and engaged.--## Explanation-Transactional emails are a crucial part of a professional product. They confirm actions, build trust, and can bring users back to the platform. Events like a successful purchase, a new referral, or a monthly earnings summary all warrant a clear and timely email notification.--## Instructions-1. **Choose and Integrate an Email Service Provider (ESP):**- * Select an ESP like SendGrid, Postmark, or AWS SES.- * Sign up and get your API keys.- * Install their Node.js SDK (e.g., `npm install @sendgrid/mail`).- * Create a helper module (e.g., `/api/_lib/email.js`) to centralize your email-sending logic.--2. **Create Email Templates:**- * Design simple, clean HTML templates for each email type. You can create these in your ESP's dashboard or as local files.- * Required templates:- * **Skill Purchase Receipt:** Sent to the buyer. Details the skill purchased, price, and a link back to the agent.- * **New Sale Notification:** Sent to the creator. Informs them they've made a sale.- * **New Referral Signup:** Sent to the referrer. Lets them know someone signed up with their code.- * **Referral Commission Earned:** Sent to the referrer. Informs them they've earned a commission from a sale.- * **API Subscription Confirmation:** Sent to a new API subscriber.--3. **Trigger Emails from Backend Logic:**- * **Purchase Receipt:** In your payment verification logic, after successfully recording a purchase, call your email helper to send the receipt to the buyer.- * **Sale Notification:** At the same time, trigger the notification to the skill's creator.- * **Referral Emails:** In the registration and commission logic, call the email helper to notify the referrer.- * **Subscription Email:** In your Stripe webhook handler for `checkout.session.completed`, trigger the subscription confirmation email.--## Email Helper Example (`/api/_lib/email.js`)--```javascript-import sgMail from '@sendgrid/mail';--sgMail.setApiKey(process.env.SENDGRID_API_KEY);--async function sendEmail({ to, subject, html, text }) {- const msg = {- to,- from: '[email protected]', // Use a verified sender- subject,- text,- html,- };-- try {- await sgMail.send(msg);- } catch (error) {- console.error('Email sending failed:', error);- // Add more robust error handling/logging- }-}--export async function sendPurchaseReceiptEmail({ buyerEmail, skillName, price }) {- const subject = 'Your 3D-Agent Skill Purchase';- const html = `<p>Thank you for purchasing the skill: <strong>${skillName}</strong> for ${price}.</p>`;- await sendEmail({ to: buyerEmail, subject, html });-}--// ... other email functions-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/17-transactional-emails.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/19-affiliate-dashboard-improvements.md b/tasks/monetization-feature/19-affiliate-dashboard-improvements.mddeleted file mode 100644index 10ee7ea3d..000000000--- a/tasks/monetization-feature/19-affiliate-dashboard-improvements.md+++ /dev/null@@ -1,65 +0,0 @@-----status: not-started------# Prompt 19: Frontend - Affiliate Dashboard Improvements--## Objective-Enhance the referral dashboard with more detailed analytics to empower affiliates and motivate them to refer more users.--## Explanation-A basic referral dashboard shows the number of signups. A great affiliate dashboard provides actionable insights. By showing affiliates a list of the users they've referred and the revenue generated from them, you turn it from a simple counter into a tool they can use to track the effectiveness of their promotional efforts.--## Instructions-1. **Update the Backend Endpoint:**- * Modify the `/api/users/referrals` endpoint.- * In addition to the summary counts, the endpoint should also return an array of the users who have signed up with the referrer's code.- * The SQL query should join the `users` table with itself (`u1` and `u2`) to find users where `u2.referred_by_id` matches `u1.id`.- * For each referred user, return their `username` (or a masked version), their `created_at` (signup date), and the total revenue they have generated (which might require another join or a subquery on your sales table).--2. **Enhance the Frontend HTML:**- * Open `profile.html` or your dedicated referral page.- * Below the summary stats, add a new section titled "Your Referrals".- * Add a table with columns for "Username", "Signup Date", and "Revenue Generated".--3. **Update the Frontend JavaScript:**- * In the JavaScript file managing this page, when you fetch data from `/api/users/referrals`, look for the new array of referred users.- * Dynamically create and insert table rows (`<tr>`) for each referred user into the new table.- * Format the `signup_date` and `revenue_generated` for display.- * If there are no referred users, display a message like "You haven't referred any users yet. Share your code to get started!".--## Backend SQL Query Example--```sql-// In /api/users/referrals, for the detailed list-const referrals = await sql`- SELECT- u.username,- u.created_at AS signup_date,- (- SELECT COALESCE(SUM(price_usd), 0)- FROM royalty_ledger- WHERE author_user_id = ${userId}- AND source_user_id = u.id -- Assuming you link sales to the user who paid- ) AS revenue_generated- FROM users u- WHERE u.referred_by_id = ${userId}- ORDER BY u.created_at DESC;-`;--// Return this 'referrals' array along with the summary stats-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/19-affiliate-dashboard-improvements.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/monetization-feature/21-user-ratings-and-reviews.md b/tasks/monetization-feature/21-user-ratings-and-reviews.mddeleted file mode 100644index 31d2761da..000000000--- a/tasks/monetization-feature/21-user-ratings-and-reviews.md+++ /dev/null@@ -1,37 +0,0 @@-----status: not-started------# Prompt 21: User Ratings and Reviews for Skills--**Status:** Not Started--## Objective-Allow users who have purchased a skill to leave a rating and a written review.--## Explanation-Social proof is a powerful driver of sales. Ratings and reviews help users make informed decisions and reward high-quality work from creators.--## Instructions-- [ ] **Create a `skill_reviews` table:**- - `id`, `user_id`, `agent_id`, `skill_name`, `rating` (1-5), `comment` (text), `created_at`.-- [ ] **On the agent detail page, after a user has purchased a skill, allow them to submit a review.**-- [ ] **Create API endpoints for submitting and fetching reviews.**- - `POST /api/skills/review`: to submit a new review. The backend should verify that the user actually owns the skill.- - `GET /api/agents/:id/reviews`: to fetch all reviews for an agent's skills.-- [ ] **Display the average rating and the number of reviews** next to each skill in the marketplace.-- [ ] **Create a "Reviews" tab** on the agent detail page where users can read all the reviews for that agent's skills.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/monetization-feature/21-user-ratings-and-reviews.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.