Skip to content

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.

Add labor economics, x402 catalog build, AWS marketplace updates, and agent-detail polish

nirholase166e3510ffd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6effbe9b8..2c0ac1d27 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-23
+- **$THREE Tiers · Hold-to-Access** (`/three`) — Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.
- **Cosmos — Living Worlds** (`/cosmos`) — Bring your avatar to life: type a world and NVIDIA Cosmos renders a living, photoreal scene that plays behind your 3D avatar. Generate, preview, and download a short cinematic clip.
- **Guardian console — recover & inherit agent wallets** (`/guardian`) — The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.
- **Mission Control** (`/terminal`) — The real-time pump.fun trading terminal: the live launch firehose fused with intel scores, firewall verdicts, and smart-money flow, your streaming positions with live PnL, and one-keystroke firewall + MEV-gated trading from your agent wallet — a keyboard-driven cockpit with filters and saved views.
@@ -17,6 +18,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Signal Marketplace — paid alpha feeds, ranked by proven edge** (`/signals`) — Verified traders publish their live entry/exit signals as x402-metered feeds. Your agent pays per signal or per epoch in USDC and auto-mirrors the trade through the firewall + MEV engine — every spend guarded, every fill audited. Each signal binds to a real on-chain fill and accrues a realized outcome, so feeds rank by proven accuracy, never follower count.
- **Strategy Objects** (`/strategies`) — A marketplace of how agents trade: ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy.
- **The Arena — live PvP trading tournaments** (`/arena`) — Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.
+- **A real pricing page, metered usage, and a downloadable invoice you can reconcile** — Billing on three.ws is now a closed loop you can read end to end. The new /pricing page reads its numbers from one server source of truth — every paid action, the platform fee, and the full $THREE holder discount ladder — so the price you see is the price checkout quotes, never a hardcoded copy. Connect a wallet that holds $THREE and the page personalizes: each paid lane shows your discounted price with the list price struck through, plus how much more $THREE reaches the next tier. Behind that, every paid action now meters into one ledger the moment it settles, linked to the on-chain transaction that paid for it — and it's idempotent, so a retried charge is recorded exactly once and you're never billed twice. The new /billing page rolls that ledger into a monthly invoice statement: every charge, the holder discount applied, the count and total, with CSV download and print-to-PDF. Each charge also yields a per-line receipt that traces to its settlement transaction. An operator reconciliation pass cross-checks every metered charge against the real on-chain settlement and surfaces an "all charges reconciled" badge on the revenue dashboard. The AWS Marketplace path meters real usage and checks entitlements against AWS, or ships inert when uncredentialed — it never invents a charge. $THREE is the only coin on three.ws. (`/pricing`) `[feature, improvement]`
- **Agent profiles: a guided first run for brand-new agents, and one-click into the right studio** — A freshly created agent used to show blank space where its Recent Actions, Memory, and Strategy panels live — nothing to tell its owner what those panels are for or how to fill them. Now, when you own an agent that hasn't done anything yet, each of those panels shows a clear, friendly empty state instead: what the panel tracks, why it matters, and a button that takes you straight to the exact place to act. “No signed actions yet” sends you to the Skills studio to switch on capabilities; “No memories yet” opens the Memory studio to seed what it remembers; “No strategy set” drops you into the Brain studio to define how it trades and acts on its own. Those buttons now deep-link to the specific agent you were viewing — the studio opens that agent on the right tab, instead of defaulting to your first one — so the path from profile to configured agent is a single click. Visitors who don't own the agent see none of this; the panels stay owner-only. Only coin referenced is $THREE. (`/agents`) `[feature, improvement]`
- **Audio2Face: your avatar's face now moves with its voice** — When your avatar talks, its mouth and face now animate in real time, in sync with the actual words. The voice is NVIDIA Magpie (as before), and that exact spoken audio is sent to NVIDIA Audio2Face-3D, which returns a per-frame facial-animation track — jaw, lips, cheeks, brows, and blinks — that drives the 3D model frame for frame. Two named NVIDIA models on one face: the lips track the real audio, not a generic talking loop. It works across avatar types automatically: whether your model uses ARKit / Ready Player Me blendshapes, VRM vowel shapes, or Oculus visemes, the animation is mapped onto whatever your rig exposes — no per-avatar setup. And it never gets in the way of speech: if Audio2Face is ever unavailable, your avatar still speaks and falls back to mouth movement driven by the audio's volume, so the face is never frozen. Try it live at /audio2face — type a line, pick a voice and an avatar, and watch it talk. (`/audio2face`) `[feature]`
- **Auto-rig now respects privacy, plan limits, and humanoid eligibility** — The background step that upgrades a new avatar so it can walk, wave, and emote now has real guardrails before it spends anything. Private avatars are never sent to a third-party rigging service unless you explicitly opt in — and when you do, the handoff uses a short-lived signed link that expires within the hour, not a permanent public URL, with a record kept that the mesh left the platform. Rigging is now rate-limited per account (hourly burst plus a hard daily ceiling) and across the whole platform, so nobody can script avatar creates to burn the shared GPU budget. And if your prompt clearly describes something that isn't a humanoid — a chair, a car, a dog — auto-rig skips the paid job instead of producing a broken skeleton, and tells you why. Only coin referenced is $THREE. `[security, improvement]`
@@ -67,6 +69,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **New: the Money Pulse — a live, platform-wide feed of real wallet activity** — Money moving through three.ws agents used to be invisible to everyone but the owner. The new Money Pulse turns it into a living, public layer: a real-time feed of tips landing, coins launching, agents trading, and agents paying each other — every beat a real on-chain event you can open on an explorer. Visit /pulse for the full feed with filters (tips, launches, trades, payments), a live-updating ticker, and money intelligence: 24-hour tip volume, the top-earning agents this week, and the busiest wallets right now. A compact ticker rides along the launches page, and each agent's profile and Wallet hub now carry that wallet's own story — tips received, biggest tip, public outflow, and launches, all from the real ledger. Privacy is strict by construction: private withdrawals, spend-limit changes and security events never appear, only already-public activity does, and owners get a one-tap toggle to include or hide their wallet from the global feed (enforced server-side). When you tip an agent, the transfer is independently verified on-chain before it ever shows up — so there is never a fake event. The feed pauses when it's off-screen or the tab is hidden, animates new beats as they land, and offers an opt-in money sound. (`/pulse`) `[feature]`
- **New: your agent's avatar now physically wears its wallet** — Funded agents now visibly look funded. Every avatar carries a live aura whose glow, palette, and energy are driven entirely by its real on-chain net worth — dormant wallets sit as a clean, quiet baseline, and the body brightens through honest tiers (Spark, Ember, Glow, Radiant, Luminous) as real value grows. The accent colour shifts with your real asset mix, with $THREE earning its own warm tint, and the same agent looks identical wherever it appears: the 3D viewer, its profile, the marketplace stage, and the character page. When a real tip, trade fill, or deposit confirms on-chain, the model plays a one-shot flourish — never on a timer, only on a real balance change. In the galaxy star-map, wealthier agents now burn brighter and bias toward wallet-violet, so a single glance tells you who's funded. It's all real chain data, capped tastefully for whales, runs at 60fps with off-screen avatars paused, and respects reduced-motion (a richer static treatment instead of animation). (`/galaxy`) `[feature, improvement]`
- **New: your avatar comes alive in iOS AR — it breathes and idles in your room** — Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker. `[feature, improvement]`
+- **One $THREE tier page, and every locked perk now routes to it** — Holding $THREE unlocks perks across three.ws — fee discounts on compute, higher free generation quotas, private and branded worlds. Until now you could see a perk was locked but had no single place that explained the whole ladder. The new /three page is that place: it shows every tier (Member → Bronze → Silver → Gold → Genesis), exactly what each one unlocks, the fee discount and free-quota multiplier it carries, and — once your wallet is connected — your current tier highlighted with the precise dollar amount of $THREE you'd need to reach the next one. Each tier lists the concrete features it turns on, honestly marked Live or Planned, with a check beside the ones you already have. Every locked control on the platform — the Forge High-quality gate, the holder chip in the top nav, the in-place lock panels — now sends you to this one page, with a one-click “Hold more $THREE” buy built in. The same tiers, the same upgrade path, everywhere. Your tier is read live from the value your wallet holds; nothing is stored and nothing is spent. $THREE is the only coin on three.ws. (`/three`) `[feature, improvement]`
- **Patronage: tips that build a real relationship with an agent** — Supporting an agent is no longer a dead-end transaction — it builds a relationship the agent actually remembers. Every agent now has a Support surface on its profile: a perk ladder ("tip to unlock"), your own live patron level and progress, and a public patron wall of its real top supporters with on-chain amounts and .sol names. Your level is computed purely from your real on-chain support (tips and streams), with documented tiers — Supporter, Patron, Champion, Benefactor — and when you cross a tier the agent writes a genuine memory of you, so in chat it greets you by name and thanks you for your support. Owners define their own perks and thresholds (an exclusive greeting, hidden lore, a free premium skill, early launch access, or a patron badge), and every perk is enforced server-side against your verified on-chain support — nobody can unlock something they haven't earned. Unlocking gated content takes a wallet signature, your support level is never spoofable, and you can hide yourself from the wall at any time. There's a fresh monthly season to compete for the top of the wall, and owners get a patron CRM to thank their champions. `[feature]`
- **Pin a 3D world's look when you embed it** — Play worlds embedded on another site can now choose their backdrop with a single setting, so the live 3D world sits cleanly inside the host page instead of clashing with it. Add ?biome=<id> to a /play embed URL — for example ?biome=noir for a neutral dark world. The IBM partnership demo uses this so its Play world renders on the same dark stage as the other 3D demos on that page, instead of dropping into a brightly-lit landscape. Default play and every coin's own world are unchanged. (`/play`) `[improvement]`
- **Pinch-zoom works everywhere again, and 3D runs lighter on phones** — Eighteen pages — including the camera capture, scan, IRL, city, play, and immersive app surfaces — were silently blocking pinch-zoom and browser zoom, which made them hard to read for anyone who needs larger text. Zoom is now enabled across every page on the platform, with no loss of the edge-to-edge fullscreen layout. Separately, several 3D viewers (voice/talk scenes, the artifact viewer, and the OS studio demos) were rendering at the phone's full native pixel density, which can be three times sharper than a screen can show and burns battery and GPU for nothing. They now cap at 2x like the rest of the platform, so 3D stays crisp while mobile devices stay cool and smooth. Only coin referenced is $THREE. `[improvement, fix]`
diff --git a/api/_lib/agent-labor.js b/api/_lib/agent-labor.js
index b189e336c..a6760c9be 100644
--- a/api/_lib/agent-labor.js
+++ b/api/_lib/agent-labor.js
@@ -10,99 +10,17 @@
// one source of truth for scoring and splitting.
import { sql } from './db.js';
-import { TOKEN_MINT, ATOMICS_PER_TOKEN } from './token/config.js';
-
-// ── Pure economics (unit-tested; no DB) ─────────────────────────────────────
-
-// Transparent award-score weights. Published in the API so posters can see why a
-// bid won. Lower price (deeper discount vs the escrowed reward), faster ETA, and
-// higher worker reputation all raise the score.
-export const SCORE_WEIGHTS = Object.freeze({ price: 0.45, eta: 0.2, reputation: 0.35 });
-// ETA at which the speed term is worth half its max — one hour. A same-second
-// promise scores ~1, a one-hour promise ~0.5, a one-day promise ~0.04.
-export const ETA_HALF_LIFE_S = 3600;
-
-const clamp01 = (n) => (n < 0 ? 0 : n > 1 ? 1 : n);
-const round4 = (n) => Math.round(n * 1e4) / 1e4;
-
-function toBig(v) {
- if (typeof v === 'bigint') return v;
- if (v == null) return 0n;
- // numeric(40,0) arrives as a string; never parse atomics through Number().
- return BigInt(String(v).split('.')[0]);
-}
-
-/**
- * Transparent award score in [0,1]. Deterministic and explainable — the same
- * formula the autonomy engine uses to auto-award and the UI renders next to each
- * bid. A bid priced at or above the full reward earns no price credit; a free,
- * instant bid from a perfect-reputation worker approaches 1.
- *
- * @param {{ priceAtomics: bigint|string|number, rewardAtomics: bigint|string|number,
- * etaSeconds?: number|null, reputation?: number }} bid
- */
-export function scoreBid({ priceAtomics, rewardAtomics, etaSeconds, reputation = 0.5 }) {
- const reward = toBig(rewardAtomics);
- const price = toBig(priceAtomics);
- if (reward <= 0n) return 0;
- // Price term: how deep the discount is vs the escrowed reward.
- const ratio = Number(price) / Number(reward);
- const priceScore = clamp01(1 - ratio);
- // ETA term: a smooth decay so faster always beats slower without a cliff.
- const eta = Number.isFinite(etaSeconds) && etaSeconds > 0 ? etaSeconds : ETA_HALF_LIFE_S;
- const etaScore = ETA_HALF_LIFE_S / (ETA_HALF_LIFE_S + eta);
- const repScore = clamp01(Number(reputation) || 0);
- const score =
- SCORE_WEIGHTS.price * priceScore +
- SCORE_WEIGHTS.eta * etaScore +
- SCORE_WEIGHTS.reputation * repScore;
- return round4(score);
-}
-
-/** Reputation in [0,1] from an agent's settled/failed job counts. New agents get
- * a neutral 0.5 prior so they can still win on price + speed (no cold-start lockout). */
-export function reputationFromStats({ settled = 0, failed = 0 } = {}) {
- const done = Number(settled) + Number(failed);
- const successRate = done > 0 ? Number(settled) / done : 0.5;
- const volume = Math.min(1, Number(settled) / 10); // saturates at 10 settled jobs
- return round4(0.7 * successRate + 0.3 * volume);
-}
-
-/** Default skill royalty (bps of the awarded amount) routed to the skill author. */
-export function defaultRoyaltyBps() {
- const raw = Number(process.env.LABOR_SKILL_ROYALTY_BPS);
- if (Number.isFinite(raw) && raw >= 0 && raw <= 5000) return Math.round(raw);
- return 1000; // 10%
-}
-
-/**
- * Exact-integer settlement split. The worker is paid its awarded bid; the skill
- * author takes a royalty out of that; any difference between the escrowed reward
- * and the (lower) awarded bid refunds to the poster. The three legs always sum to
- * exactly the escrowed reward — no $THREE dust is created or lost.
- *
- * @returns {{ workerAtomics: bigint, royaltyAtomics: bigint, posterRefundAtomics: bigint }}
- */
-export function settlementSplit({ rewardAtomics, awardedAtomics, royaltyBps = defaultRoyaltyBps(), hasAuthor = false }) {
- const reward = toBig(rewardAtomics);
- let awarded = toBig(awardedAtomics);
- if (awarded > reward) awarded = reward; // never pay out more than is escrowed
- if (awarded < 0n) awarded = 0n;
- const bps = BigInt(Math.max(0, Math.min(5000, Math.round(royaltyBps))));
- const royalty = hasAuthor ? (awarded * bps) / 10_000n : 0n;
- const worker = awarded - royalty;
- const posterRefund = reward - awarded;
- return { workerAtomics: worker, royaltyAtomics: royalty, posterRefundAtomics: posterRefund };
-}
-
-export function atomicsToThree(atomics) {
- return Number(toBig(atomics)) / Number(ATOMICS_PER_TOKEN);
-}
-export function threeToAtomics(three) {
- const n = Number(three);
- if (!Number.isFinite(n) || n < 0) return 0n;
- return BigInt(Math.round(n * Number(ATOMICS_PER_TOKEN)));
-}
+import { TOKEN_MINT } from './token/config.js';
+import {
+ scoreBid, reputationFromStats, defaultRoyaltyBps, settlementSplit,
+ atomicsToThree, threeToAtomics, toBig, SCORE_WEIGHTS, ETA_HALF_LIFE_S,
+} from './labor-economics.js';
+
+// Re-export the pure economics so existing call sites keep importing from here.
+export {
+ scoreBid, reputationFromStats, defaultRoyaltyBps, settlementSplit,
+ atomicsToThree, threeToAtomics, SCORE_WEIGHTS, ETA_HALF_LIFE_S,
+};
// ── Lazy schema (self-heals if the formal migration hasn't run) ─────────────
diff --git a/api/_lib/aws-marketplace.js b/api/_lib/aws-marketplace.js
index bbef8d651..bae9fb500 100644
--- a/api/_lib/aws-marketplace.js
+++ b/api/_lib/aws-marketplace.js
@@ -98,6 +98,46 @@ export async function getEntitlements(customerIdentifier) {
return result.Entitlements ?? [];
}
+/**
+ * True when the AWS Marketplace integration has the credentials + product code
+ * it needs to call AWS. Read directly from process.env so it never throws the
+ * way the `req()`-backed env getters do when unconfigured — that's what lets the
+ * whole path ship INERT (like the fee module) instead of erroring.
+ */
+export function awsMarketplaceConfigured() {
+ return Boolean(
+ process.env.AWS_MP_ACCESS_KEY_ID &&
+ process.env.AWS_MP_SECRET_ACCESS_KEY &&
+ process.env.AWS_MP_PRODUCT_CODE,
+ );
+}
+
+/**
+ * Resolve whether a customer is currently ENTITLED, via a real GetEntitlements
+ * call — filtering out expired entitlements. Inert (entitled:null) when AWS is
+ * not configured, so a deployment without AWS creds degrades open and never
+ * fakes an entitlement AWS didn't grant. Throttling / network errors surface as
+ * a typed, retryable error the caller turns into an actionable boundary state.
+ *
+ * @returns {Promise<{ configured: boolean, entitled: boolean|null, entitlements: object[] }>}
+ */
+export async function customerEntitlement(customerIdentifier) {
+ if (!awsMarketplaceConfigured()) return { configured: false, entitled: null, entitlements: [] };
+ try {
+ const entitlements = await getEntitlements(customerIdentifier);
+ const now = Date.now();
+ const active = entitlements.filter(
+ (e) => !e.ExpirationDate || new Date(e.ExpirationDate).getTime() > now,
+ );
+ return { configured: true, entitled: active.length > 0, entitlements: active };
+ } catch (err) {
+ const e = new Error(`aws_entitlement_check_failed: ${err?.name || ''} ${err?.message || ''}`.trim());
+ e.code = 'aws_entitlement_unavailable';
+ e.retryable = err?.name === 'ThrottlingException' || err?.name === 'InternalServiceErrorException';
+ throw e;
+ }
+}
+
// ── SNS signature verification ────────────────────────────────────────────────
// AWS signs every SNS message with a private key and includes the cert URL.
// We download the cert once (cached per URL), build the canonical string, and
diff --git a/api/_lib/env.js b/api/_lib/env.js
index fd597f12c..11d92df15 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -677,6 +677,13 @@ export const env = {
return opt('AWS_MP_METERING_DIMENSION');
},
+ // Contract (entitlement-based) products only: when 'true', key issuance is
+ // gated on a live GetEntitlements check against AWS. Leave unset for
+ // usage-based products (which have no entitlements; metering is the billing).
+ get AWS_MP_ENTITLEMENT_REQUIRED() {
+ return /^(1|true|yes)$/i.test(String(opt('AWS_MP_ENTITLEMENT_REQUIRED', '') || ''));
+ },
+
// Optional operator EOA private key for scripts/erc8004-mint-bsc.mjs.
// Used to register marketplace agents on the BSC IdentityRegistry. Never
// referenced by request handlers — keep it out of the serverless surface.
diff --git a/api/_lib/labor-economics.js b/api/_lib/labor-economics.js
new file mode 100644
index 000000000..3175be076
--- /dev/null
+++ b/api/_lib/labor-economics.js
@@ -0,0 +1,113 @@
+// Pure economics for the Agent Labor Market (Moonshot 01) — zero imports, so the
+// scoring, reputation, negotiation, and settlement-split math can be unit-tested
+// in isolation and reused identically by the data layer, the autonomy engine, and
+// the settler. No floats touch atomic amounts: every $THREE quantity is a BigInt.
+
+// $THREE decimals (6). Read from env so a non-default deployment stays exact;
+// kept import-free on purpose (this module must not pull the DB/config graph).
+const TOKEN_DECIMALS = (() => {
+ const n = Number(process.env.THREE_TOKEN_DECIMALS);
+ return Number.isInteger(n) && n >= 0 && n <= 18 ? n : 6;
+})();
+export const ATOMICS_PER_TOKEN = 10n ** BigInt(TOKEN_DECIMALS);
+
+// Transparent award-score weights, published in the API so posters see why a bid
+// won: deeper discount vs the escrowed reward, faster ETA, higher reputation.
+export const SCORE_WEIGHTS = Object.freeze({ price: 0.45, eta: 0.2, reputation: 0.35 });
+// ETA worth half its max — one hour.
+export const ETA_HALF_LIFE_S = 3600;
+
+const clamp01 = (n) => (n < 0 ? 0 : n > 1 ? 1 : n);
+const round4 = (n) => Math.round(n * 1e4) / 1e4;
+
+export function toBig(v) {
+ if (typeof v === 'bigint') return v;
+ if (v == null) return 0n;
+ return BigInt(String(v).split('.')[0]); // numeric(40,0) arrives as a string
+}
+
+export function atomicsToThree(atomics) {
+ return Number(toBig(atomics)) / Number(ATOMICS_PER_TOKEN);
+}
+export function threeToAtomics(three) {
+ const n = Number(three);
+ if (!Number.isFinite(n) || n < 0) return 0n;
+ return BigInt(Math.round(n * Number(ATOMICS_PER_TOKEN)));
+}
+
+/**
+ * Transparent award score in [0,1]. Deterministic and explainable. A bid at or
+ * above the full reward earns no price credit; a free, instant bid from a
+ * perfect-reputation worker approaches 1.
+ */
+export function scoreBid({ priceAtomics, rewardAtomics, etaSeconds, reputation = 0.5 }) {
+ const reward = toBig(rewardAtomics);
+ const price = toBig(priceAtomics);
+ if (reward <= 0n) return 0;
+ const ratio = Number(price) / Number(reward);
+ const priceScore = clamp01(1 - ratio);
+ const eta = Number.isFinite(etaSeconds) && etaSeconds > 0 ? etaSeconds : ETA_HALF_LIFE_S;
+ const etaScore = ETA_HALF_LIFE_S / (ETA_HALF_LIFE_S + eta);
+ const repScore = clamp01(Number(reputation) || 0);
+ const score =
+ SCORE_WEIGHTS.price * priceScore +
+ SCORE_WEIGHTS.eta * etaScore +
+ SCORE_WEIGHTS.reputation * repScore;
+ return round4(score);
+}
+
+/** Reputation in [0,1] from settled/failed counts. New agents get a neutral 0.5
+ * prior so they can still win on price + speed (no cold-start lockout). */
+export function reputationFromStats({ settled = 0, failed = 0 } = {}) {
+ const done = Number(settled) + Number(failed);
+ const successRate = done > 0 ? Number(settled) / done : 0.5;
+ const volume = Math.min(1, Number(settled) / 10);
+ return round4(0.7 * successRate + 0.3 * volume);
+}
+
+/** Default skill royalty (bps of the awarded amount) routed to the skill author. */
+export function defaultRoyaltyBps() {
+ const raw = Number(process.env.LABOR_SKILL_ROYALTY_BPS);
+ if (Number.isFinite(raw) && raw >= 0 && raw <= 5000) return Math.round(raw);
+ return 1000; // 10%
+}
+
+/**
+ * Exact-integer settlement split. The worker is paid its awarded bid; the author
+ * takes a royalty out of that; the difference between the escrowed reward and the
+ * (lower) awarded bid refunds to the poster. The three legs ALWAYS sum to exactly
+ * the escrowed reward — no $THREE dust is created or lost.
+ */
+export function settlementSplit({ rewardAtomics, awardedAtomics, royaltyBps = defaultRoyaltyBps(), hasAuthor = false }) {
+ const reward = toBig(rewardAtomics);
+ let awarded = toBig(awardedAtomics);
+ if (awarded > reward) awarded = reward;
+ if (awarded < 0n) awarded = 0n;
+ const bps = BigInt(Math.max(0, Math.min(5000, Math.round(royaltyBps))));
+ const royalty = hasAuthor ? (awarded * bps) / 10_000n : 0n;
+ const worker = awarded - royalty;
+ const posterRefund = reward - awarded;
+ return { workerAtomics: worker, royaltyAtomics: royalty, posterRefundAtomics: posterRefund };
+}
+
+/**
+ * The price an autonomous worker bids: never above the escrowed reward or its own
+ * max-bid ceiling, discounted off that ceiling by reputation (proven workers hold
+ * nearer the ceiling at 0.98×, new workers discount to 0.80× to win on price).
+ */
+export function negotiationPrice({ rewardAtomics, maxBidAtomics = null, reputation = 0.5 }) {
+ const reward = toBig(rewardAtomics);
+ const ceiling = maxBidAtomics != null && toBig(maxBidAtomics) < reward ? toBig(maxBidAtomics) : reward;
+ const rep = clamp01(Number(reputation) || 0);
+ const factorBps = BigInt(Math.round((0.8 + 0.18 * rep) * 10_000)); // 8000..9800
+ let price = (ceiling * factorBps) / 10_000n;
+ if (price < 1n) price = 1n;
+ if (price > reward) price = reward;
+ return price;
+}
+
+/** Promised turnaround: faster the higher the reputation (2h → 30m). */
+export function etaForReputation(reputation = 0.5) {
+ const rep = clamp01(Number(reputation) || 0);
+ return Math.round(7200 - 5400 * rep);
+}
diff --git a/api/_lib/labor-match.js b/api/_lib/labor-match.js
index 7dad4a217..b011721d9 100644
--- a/api/_lib/labor-match.js
+++ b/api/_lib/labor-match.js
@@ -16,34 +16,12 @@ import { sql } from './db.js';
import {
scoreBid, workerReputation, findAutoBidders, upsertBid, getBounty,
getLaborPolicy, listBidsForBounty, createJob, markBidAwarded, rejectOtherBids,
- setBountyStatus, getJobByBounty, markJobDelivered, atomicsToThree, _toBig as toBig,
+ setBountyStatus, getJobByBounty, markJobDelivered,
} from './agent-labor.js';
+import { negotiationPrice, etaForReputation, atomicsToThree, toBig } from './labor-economics.js';
-// ── Pure negotiation rules (unit-tested) ────────────────────────────────────
-
-/**
- * The price an autonomous worker bids. It never exceeds the escrowed reward or
- * the worker's own max-bid ceiling, and it discounts off that ceiling by the
- * worker's reputation: a proven worker can hold closer to the ceiling (0.98×),
- * a new worker discounts harder (0.80×) to win on price. Deterministic, so the
- * UI can explain exactly why a bid came in where it did.
- */
-export function negotiationPrice({ rewardAtomics, maxBidAtomics = null, reputation = 0.5 }) {
- const reward = toBig(rewardAtomics);
- const ceiling = maxBidAtomics != null && toBig(maxBidAtomics) < reward ? toBig(maxBidAtomics) : reward;
- const rep = Math.max(0, Math.min(1, Number(reputation) || 0));
- const factorBps = BigInt(Math.round((0.8 + 0.18 * rep) * 10_000)); // 8000..9800
- let price = (ceiling * factorBps) / 10_000n;
- if (price < 1n) price = 1n;
- if (price > reward) price = reward;
- return price;
-}
-
-/** Promised turnaround: faster the higher the reputation (2h → 30m). */
-export function etaForReputation(reputation = 0.5) {
- const rep = Math.max(0, Math.min(1, Number(reputation) || 0));
- return Math.round(7200 - 5400 * rep);
-}
+// Re-export the negotiation rules from the pure economics module.
+export { negotiationPrice, etaForReputation };
// ── Reasoning ledger (best-effort; compatible with Moonshot 05) ─────────────
diff --git a/api/_lib/monetization.js b/api/_lib/monetization.js
index 41c19cc55..d90bee415 100644
--- a/api/_lib/monetization.js
+++ b/api/_lib/monetization.js
@@ -119,7 +119,50 @@ export async function getAvailableBalance(userId, currencyMint = null) {
WHERE user_id = ${userId}
`;
- const earned = Number(result.earned);
+ // Split-aware adjustment. For a multi-collaborator listing the creator's net
+ // is apportioned across recipients (split_distributions), not kept whole by
+ // the agent owner. So we SUBTRACT the owner's revenue on split listings and
+ // ADD this user's ledger-mode split allocations (their exact share). On-chain
+ // (0xSplits) distributions are excluded — those settle on chain, not via our
+ // payout. Guarded: pre-migration DBs without the split tables degrade to the
+ // original owner-keeps-net behaviour, never erroring on a hot money path.
+ let splitOut = 0;
+ let splitIn = 0;
+ try {
+ const [outRow] = currencyMint
+ ? await sql`
+ SELECT COALESCE(SUM(re.net_amount), 0)::bigint AS amt
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ JOIN listing_splits ls ON ls.agent_id = re.agent_id AND ls.skill = re.skill
+ WHERE ai.user_id = ${userId} AND re.currency_mint = ${currencyMint}
+ `
+ : await sql`
+ SELECT COALESCE(SUM(re.net_amount), 0)::bigint AS amt
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ JOIN listing_splits ls ON ls.agent_id = re.agent_id AND ls.skill = re.skill
+ WHERE ai.user_id = ${userId}
+ `;
+ const [inRow] = currencyMint
+ ? await sql`
+ SELECT COALESCE(SUM(amount), 0)::bigint AS amt
+ FROM split_distributions
+ WHERE recipient_user_id = ${userId} AND mode = 'ledger' AND currency_mint = ${currencyMint}
+ `
+ : await sql`
+ SELECT COALESCE(SUM(amount), 0)::bigint AS amt
+ FROM split_distributions
+ WHERE recipient_user_id = ${userId} AND mode = 'ledger'
+ `;
+ splitOut = Number(outRow.amt);
+ splitIn = Number(inRow.amt);
+ } catch {
+ splitOut = 0;
+ splitIn = 0;
+ }
+
+ const earned = Number(result.earned) - splitOut + splitIn;
const pending = Number(wResult.pending);
const withdrawn = Number(wResult.withdrawn);
const available = earned - pending - withdrawn;
diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.js
index 3243227e5..ff901e0e0 100644
--- a/api/_lib/notify-prefs.js
+++ b/api/_lib/notify-prefs.js
@@ -61,6 +61,8 @@ const TYPE_CATEGORY = {
'payment-earned': 'sales',
payment_received: 'sales',
referral_earned: 'sales',
+ referral_signup: 'sales',
+ referral_reward: 'sales',
pump_launch_filled: 'sales',
skill_purchase_confirmed: 'purchases',
diff --git a/api/aws-marketplace/issue-key.js b/api/aws-marketplace/issue-key.js
index 1cf9dccbc..82b93df89 100644
--- a/api/aws-marketplace/issue-key.js
+++ b/api/aws-marketplace/issue-key.js
@@ -15,6 +15,8 @@ import { cors, json, readJson, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { issueSubscriptionForCustomer } from '../_lib/aws-marketplace-bridge.js';
+import { customerEntitlement } from '../_lib/aws-marketplace.js';
+import { env } from '../_lib/env.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -61,6 +63,30 @@ export default wrap(async (req, res) => {
return json(res, 409, { error: 'subscription_inactive', status: row.subscription_status });
}
+ // Contract (entitlement-based) products: gate key issuance on a REAL
+ // GetEntitlements check against AWS. Usage-based products have no entitlements
+ // (metering is the billing), so this is opt-in via AWS_MP_ENTITLEMENT_REQUIRED
+ // and a no-op otherwise. Degrades open when AWS is unconfigured (inert path);
+ // a throttled/unavailable AWS surfaces an actionable 503 instead of a 500.
+ if (env.AWS_MP_ENTITLEMENT_REQUIRED) {
+ try {
+ const ent = await customerEntitlement(row.customer_identifier);
+ if (ent.configured && ent.entitled === false) {
+ return json(res, 403, {
+ error: 'not_entitled',
+ message: 'Your AWS Marketplace entitlement is not active. Renew or re-subscribe in AWS Marketplace, then try again.',
+ });
+ }
+ } catch (err) {
+ console.error('[aws-marketplace/issue-key] entitlement check failed', { customerId, error: err?.message });
+ return json(res, 503, {
+ error: 'entitlement_unavailable',
+ retryable: Boolean(err?.retryable),
+ message: 'We could not verify your AWS Marketplace entitlement just now. Please retry in a moment.',
+ });
+ }
+ }
+
let issued;
try {
issued = await issueSubscriptionForCustomer({
diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.js
index 01cdd873a..c0aff989f 100644
--- a/api/billing/withdrawals/index.js
+++ b/api/billing/withdrawals/index.js
@@ -148,8 +148,17 @@ export default wrap(async (req, res) => {
select coalesce(sum(re.net_amount), 0)::bigint
from agent_revenue_events re
join agent_identities ai on ai.id = re.agent_id
+ left join listing_splits ls
+ on ls.agent_id = re.agent_id and ls.skill = re.skill
where ai.user_id = ${user.id}
and re.currency_mint = ${currency_mint}
+ and ls.id is null
+ ) + (
+ select coalesce(sum(sd.amount), 0)::bigint
+ from split_distributions sd
+ where sd.recipient_user_id = ${user.id}
+ and sd.mode = 'ledger'
+ and sd.currency_mint = ${currency_mint}
) - (
select coalesce(sum(w2.amount), 0)::bigint
from agent_withdrawals w2
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 8ddd35a2f..4f6f6eb4d 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -725,7 +725,7 @@
<section class="ad-card" id="ad-ledger-card" style="display: none">
<div class="ad-card-head">
- <span class="ad-bullet ad-bullet-cyan"></span>
+ <span class="ad-bullet"></span>
<h2>REASONING LEDGER</h2>
<span class="ad-pill ad-pill-muted" id="ad-ledger-verify">verifying…</span>
</div>
diff --git a/prompts/production-campaign/D-monetization/D1-three-holder-value-system.md b/prompts/production-campaign/D-monetization/D1-three-holder-value-system.md
deleted file mode 100644
index cf2c64f20..000000000
--- a/prompts/production-campaign/D-monetization/D1-three-holder-value-system.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# D1 — One $THREE-Holder Value System, Everywhere
-
-You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,
-`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none
-— this is the foundation D2/D3/D4 price and gate against.
-
-## Why this matters for $1B
-
-Holding $THREE is the platform's deflation-free status lever: hold (don't spend) to unlock
-perks. That promise is only worth a multiple if it is **consistent** — the same balance must
-mean the same tier, the same perks, the same discount, on every surface that gates on it.
-Today Forge gates "High quality" on holders but the tier ladder, the perk copy, the upgrade
-path, and the balance check live in separate places and are wired into exactly one surface.
-A holder who sees a "Silver perk" on one page and a dead "for holders only" string on another
-does not believe the token has value — and a token nobody believes in has no market cap to
-multiply. One helper, one UX, everywhere is what makes the economy legible.
-
-## Current state (read before you write)
-
-- `api/_lib/three-tier.js` — the **source of truth**: the `TIERS` ladder (Member → Bronze →
- Silver → …), `minUsd` thresholds, `discountBps`, `rateMultiplier`, perks, and the signed
- tier pass (`signTierPass`/`verifyTierPass`) the multiplayer server verifies. Resolves a
- tier from the live USD value of $THREE held; degrades to Member on a price/RPC hiccup.
-- `api/_lib/three-access.js` — `featureId → { minLevel, enforced, label, why, payPerUse }`
- registry + `resolveAccess(user, featureId)` (async, for display) and `accessFromTierLevel`
- (pure, for enforcement). This is the platform-wide access table — but inventory it: how many
- real `featureId`s are registered vs. how many surfaces actually gate?
-- `api/_lib/three-gate.js` — raw on-chain balance check (`checkThreeBalance`), fails **open**.
-- `api/_lib/holder-pass.js` — the per-coin world-entry pass; `balances.js` — wallet balances.
-- `api/_lib/forge-tiers.js` — Forge's quality tiers; the one surface that gates today.
-- **The gap:** the ladder and access table exist server-side, but there is no single **client**
- module that every page imports to (1) read the user's tier, (2) render the same tier badge +
- perk list, (3) gate an affordance with a consistent locked state, and (4) route to one
- upgrade path. Each surface that wants to gate re-implements the check and the copy.
-
-## Your mission
-
-### 1. Lock the tier ladder + access registry as the single source of truth
-Audit `TIERS` in `three-tier.js` for completeness (every tier has perks, a `discountBps`, a
-`rateMultiplier`, and reachable, sensible `minUsd` thresholds). Inventory `three-access.js`:
-register a `featureId` for **every** surface that should gate on holding — Forge high quality
-(exists), private/branded worlds, priority MCP routing, higher free quotas, early-access pages.
-Each entry needs honest `label`/`why` copy a holder reads in the UI. No invented perks that
-aren't wired — if you register it, the gating surface honors it in this PR or a sibling prompt.
-
-### 2. Ship ONE client holder-value module — `public/three-tier-client.js`
-A single ES module every gating surface imports. It must:
-- Resolve the signed-in user's tier from a real endpoint (extend/confirm an
- `api/account/tier` or `api/three/access` endpoint that returns `{ tier, usdHeld, nextTier,
- usdToNext, perks }` from `resolveUserTier`). No client-side balance math — server is truth.
-- Export `renderTierBadge(el, tier)`, `gateAffordance(el, { featureId, onUnlock })`, and
- `requireTier(featureId)` returning `{ allowed, tier, upgradeUrl }`.
-- A consistent **locked state**: disabled affordance + a tooltip/popover stating the exact
- requirement ("Hold $25 of $THREE to unlock — you hold $8") and a single upgrade CTA.
-- Cache the tier for the session; refresh on wallet/auth change. Never block paint on the fetch.
-
-### 3. Build the canonical upgrade path — one `/account` (or `/three`) tier surface
-One page renders the full ladder: current tier highlighted, every tier's perks, the live
-$-to-next-tier delta, and a real "Hold more $THREE" action that links to the $THREE acquisition
-flow (the existing $THREE token/buy surface — `$THREE` CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
-Every locked state across the platform routes here. Design all five states (loading skeleton
-of the ladder, empty/not-signed-in with a connect CTA, error, populated, overflow at $10M+).
-
-### 4. Replace the per-page reinventions with the shared module
-Migrate the Forge "High quality" gate to consume `three-tier-client.js` + `three-access.js`
-instead of its bespoke check. Then wire the shared gate into the other registered surfaces
-(private worlds, priority routing) so they show the same badge, locked state, and upgrade
-route. Delete any duplicated tier copy/threshold literals you find — one ladder, referenced.
-
-### 5. Make holding *visibly* pay off where the user already is
-Surface the holder discount and quota multiplier inline at the point of value: a tier badge in
-the nav/account menu, the holder discount line on any priced action (a seam D2/D3 consume),
-and the perk the user just unlocked called out on the relevant surface. Holding must feel like
-it did something, not just change a number on a settings page.
-
-### 6. Test the ladder and the gate
-Extend tests so the tier resolution, the fail-open balance behavior, the pure
-`accessFromTierLevel` enforcement, and the signed tier-pass round-trip are covered. Add a test
-asserting every `three-access.js` `featureId` maps to a real tier level and has non-empty copy.
-
-## Definition of done
-
-Clears 00b-the-bar.md's monetization bar ("$THREE holding unlocks visible, consistent value
-across every surface that gates on it — same tiering, same upgrade path, everywhere") and the
-polish bar (all five states designed on the tier surface and the locked state). Inherits the
-global definition of done in `00-README-orchestration.md`. Specifically: one client module is
-the only holder gate in the codebase; Forge and ≥2 more surfaces consume it; the upgrade page
-is reachable from every locked state; tier resolution degrades gracefully and is tested;
-`npm test` green; verified in a browser with a real wallet at a real and a zero balance.
-
-## Operating rules (override defaults)
-
-No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,
-hardcode, or recommend any other token (runtime user-launch mints are the sole mechanical
-exception per CLAUDE.md). Design tokens only. Stage explicit paths only (never `git add -A`).
-Own the holder-value lane (`three-tier.js`, `three-access.js`, `three-gate.js`, the client
-module, the tier surface); extend `balances.js`/`holder-pass.js`/`forge-tiers.js`, don't
-rewrite them.
-
-## When finished
-
-Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. an empty-state illustration
-on the tier surface, or a keyboard-navigable ladder). Append a `data/changelog.json` entry
-(holder-readable, tag `feature` or `improvement`) since this is user-visible. Then delete this
-prompt file (`prompts/production-campaign/D-monetization/D1-three-holder-value-system.md`) and
-report what you shipped + the seam D2/D3/D4 consume (the tier-resolution endpoint shape and the
-`discountBps`/`rateMultiplier` contract they price against).
diff --git a/public/admin/index.html b/public/admin/index.html
index a6887c6d3..0031f9626 100644
--- a/public/admin/index.html
+++ b/public/admin/index.html
@@ -206,11 +206,11 @@ async function boot() {
// ── Tab routing ─────────────────────────────────────────────────────────────
-const TAB_TITLES = { overview: 'Overview', users: 'Users', revenue: 'Revenue', llm: 'LLM Spend', usage: 'Usage' };
+const TAB_TITLES = { overview: 'Overview', users: 'Users', revenue: 'Revenue', llm: 'LLM Spend', usage: 'Usage', growth: 'Growth & Virality' };
function switchTab(tab) {
state.tab = tab;
document.querySelectorAll('.nav-item[data-tab]').forEach((el) => el.classList.toggle('active', el.dataset.tab === tab));
- ['overview', 'users', 'revenue', 'llm', 'usage'].forEach((t) => {
+ ['overview', 'users', 'revenue', 'llm', 'usage', 'growth'].forEach((t) => {
document.getElementById('tab-' + t).style.display = t === tab ? '' : 'none';
});
document.getElementById('page-title').textContent = TAB_TITLES[tab] || 'Overview';
@@ -219,6 +219,7 @@ function switchTab(tab) {
if (tab === 'revenue') loadRevenue();
if (tab === 'llm') loadLlmSpend();
if (tab === 'usage') loadFeatures();
+ if (tab === 'growth') loadGrowth();
}
// ── Overview tab ─────────────────────────────────────────────────────────────
@@ -572,6 +573,67 @@ async function loadFeatures() {
document.getElementById('feat-tool').innerHTML = rankBars(data.byTool || [], (r) => r.tool, (r) => r.events, (v) => fmtNum(v));
}
+// ── Growth tab (referral loop & k-factor) ──────────────────────────────────────
+
+async function loadGrowth() {
+ const el = document.getElementById('tab-growth');
+ el.innerHTML = '<div class="empty"><span class="spinner"></span></div>';
+ const data = await api.get('/api/admin/referrals');
+ if (data.error) { el.innerHTML = `<div class="empty">Error: ${esc(data.error_description || data.error)}</div>`; return; }
+
+ const f = data.funnel || {};
+ const c = data.conversion || {};
+ const t = data.totals || {};
+ const k = Number(data.k_factor) || 0;
+ // k-factor headline tints green when the loop is self-sustaining (>1).
+ const kColor = k >= 1 ? '#22c55e' : k >= 0.5 ? '#eab308' : '#888';
+ const pct = (v) => (Number(v) * 100).toFixed(1) + '%';
+
+ el.innerHTML = `
+ <div class="kpi-grid">
+ <div class="stat-card">
+ <div class="stat-label">k-factor · ${esc(data.window_days)}d</div>
+ <div class="stat-value" style="color:${kColor}">${k.toFixed(3)}</div>
+ <div class="stat-sub">signups per sharing user${k >= 1 ? ' · viral 🚀' : ''}</div>
+ </div>
+ ${kpi('Link visits', fmtNum(f.visits), `${fmtNum(f.sharers)} sharers`)}
+ ${kpi('Referred signups', fmtNum(f.signups), `${pct(c.visit_to_signup)} of visits`)}
+ ${kpi('Activations', fmtNum(f.activations), `${pct(c.signup_to_activation)} of signups`)}
+ ${kpi('Rewards paid', fmtUsdShort(t.rewards_paid_usd), `${fmtNum(t.rewards_paid_count)} grants`)}
+ ${kpi('Referred members', fmtNum(t.referred_members), `${fmtNum(t.activated_referred_members)} activated`)}
+ </div>
+ <div class="section">
+ <div class="section-head"><span class="section-title">Referred signups vs activations · last ${esc(data.window_days)} days</span></div>
+ <div class="chart-wrap" id="growth-day"></div>
+ </div>
+ <div class="section">
+ <div class="section-head"><span class="section-title">Top referrers · by activated referrals</span></div>
+ <div class="section-body">
+ <table><thead><tr><th>Referrer</th><th>Referred</th><th>Activated</th><th>Commission</th></tr></thead><tbody>
+ ${(data.top_referrers || []).map((r) => `<tr>
+ <td style="color:#ddd">${esc(r.display_name || r.username || r.user_id)}</td>
+ <td>${fmtNum(r.referred_total)}</td>
+ <td>${fmtNum(r.activated_total)}</td>
+ <td>$${(Number(r.commission_earned_usd) || 0).toLocaleString('en-US', { maximumFractionDigits: 2 })}</td>
+ </tr>`).join('') || '<tr><td colspan="4" class="empty">No referrals yet.</td></tr>'}
+ </tbody></table>
+ </div>
+ </div>
+ `;
+ // Stacked-ish two-series trend: render signups as the column height with
+ // activations annotated in the tooltip (colChart is single-series).
+ const byDay = data.byDay || [];
+ document.getElementById('growth-day').innerHTML = colChart(
+ byDay.map((r) => ({ day: r.day, value: Number(r.signups) || 0 })),
+ (v) => v + ' signups',
+ );
+}
+
+function fmtUsdShort(usd) {
+ const v = Number(usd) || 0;
+ return '$' + v.toLocaleString('en-US', { minimumFractionDigits: v < 100 ? 2 : 0, maximumFractionDigits: 2 });
+}
+
// ── Utils ─────────────────────────────────────────────────────────────────────
function fmtUsd(micro) { const v = (Number(micro) || 0) / 1e6; return '$' + v.toLocaleString('en-US', { minimumFractionDigits: v < 100 ? 2 : 0, maximumFractionDigits: v < 1 ? 4 : 2 }); }
diff --git a/public/changelog.json b/public/changelog.json
index 41f25733b..a563e4227 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T10:31:59.220Z",
+ "generated_at": "2026-06-23T10:42:22.576Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "launch",
+ "title": "$THREE Tiers · Hold-to-Access",
+ "summary": "Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.",
+ "link": "/three",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-23",
"type": "launch",
@@ -86,6 +96,17 @@
"launch"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "A real pricing page, metered usage, and a downloadable invoice you can reconcile",
+ "summary": "Billing on three.ws is now a closed loop you can read end to end. The new /pricing page reads its numbers from one server source of truth — every paid action, the platform fee, and the full $THREE holder discount ladder — so the price you see is the price checkout quotes, never a hardcoded copy. Connect a wallet that holds $THREE and the page personalizes: each paid lane shows your discounted price with the list price struck through, plus how much more $THREE reaches the next tier. Behind that, every paid action now meters into one ledger the moment it settles, linked to the on-chain transaction that paid for it — and it's idempotent, so a retried charge is recorded exactly once and you're never billed twice. The new /billing page rolls that ledger into a monthly invoice statement: every charge, the holder discount applied, the count and total, with CSV download and print-to-PDF. Each charge also yields a per-line receipt that traces to its settlement transaction. An operator reconciliation pass cross-checks every metered charge against the real on-chain settlement and surfaces an \"all charges reconciled\" badge on the revenue dashboard. The AWS Marketplace path meters real usage and checks entitlements against AWS, or ships inert when uncredentialed — it never invents a charge. $THREE is the only coin on three.ws.",
+ "link": "/pricing",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -602,6 +623,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "One $THREE tier page, and every locked perk now routes to it",
+ "summary": "Holding $THREE unlocks perks across three.ws — fee discounts on compute, higher free generation quotas, private and branded worlds. Until now you could see a perk was locked but had no single place that explained the whole ladder. The new /three page is that place: it shows every tier (Member → Bronze → Silver → Gold → Genesis), exactly what each one unlocks, the fee discount and free-quota multiplier it carries, and — once your wallet is connected — your current tier highlighted with the precise dollar amount of $THREE you'd need to reach the next one. Each tier lists the concrete features it turns on, honestly marked Live or Planned, with a check beside the ones you already have. Every locked control on the platform — the Forge High-quality gate, the holder chip in the top nav, the in-place lock panels — now sends you to this one page, with a one-click “Hold more $THREE” buy built in. The same tiers, the same upgrade path, everywhere. Your tier is read live from the value your wallet holds; nothing is stored and nothing is spent. $THREE is the only coin on three.ws.",
+ "link": "/three",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index e91cb8ccb..39cd7c13a 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>feature</category>
<description>A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms.</description>
</item>
+ <item>
+ <title>$THREE Tiers · Hold-to-Access</title>
+ <link>https://three.ws/three</link>
+ <guid isPermaLink="false">2026-06-23:$THREE Tiers · Hold-to-Access</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.</description>
+ </item>
<item>
<title>Cosmos — Living Worlds</title>
<link>https://three.ws/cosmos</link>
@@ -70,6 +78,14 @@
<category>launch</category>
<description>Time-boxed PvP tournaments where AI agents compete on real, verified pump.fun P&amp;L. Live rankings, on-chain attested standings, and $THREE prizes for the winners.</description>
</item>
+ <item>
+ <title>A real pricing page, metered usage, and a downloadable invoice you can reconcile</title>
+ <link>https://three.ws/pricing</link>
+ <guid isPermaLink="false">2026-06-23:A real pricing page, metered usage, and a downloadable invoice you can reconcile</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Billing on three.ws is now a closed loop you can read end to end. The new /pricing page reads its numbers from one server source of truth — every paid action, the platform fee, and the full $THREE holder discount ladder — so the price you see is the price checkout quotes, never a hardcoded copy. Connect a wallet that holds $THREE and the page personalizes: each paid lane shows your discounted price with the list price struck through, plus how much more $THREE reaches the next tier. Behind that, every paid action now meters into one ledger the moment it settles, linked to the on-chain transaction that paid for it — and it's idempotent, so a retried charge is recorded exactly once and you're never billed twice. The new /billing page rolls that ledger into a monthly invoice statement: every charge, the holder discount applied, the count and total, with CSV download and print-to-PDF. Each charge also yields a per-line receipt that traces to its settlement transaction. An operator reconciliation pass cross-checks every metered charge against the real on-chain settlement and surfaces an &quot;all charges reconciled&quot; badge on the revenue dashboard. The AWS Marketplace path meters real usage and checks entitlements against AWS, or ships inert when uncredentialed — it never invents a charge. $THREE is the only coin on three.ws.</description>
+ </item>
<item>
<title>Agent profiles: a guided first run for brand-new agents, and one-click into the right studio</title>
<link>https://three.ws/agents</link>
@@ -470,6 +486,14 @@
<category>feature</category>
<description>Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker.</description>
</item>
+ <item>
+ <title>One $THREE tier page, and every locked perk now routes to it</title>
+ <link>https://three.ws/three</link>
+ <guid isPermaLink="false">2026-06-23:One $THREE tier page, and every locked perk now routes to it</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Holding $THREE unlocks perks across three.ws — fee discounts on compute, higher free generation quotas, private and branded worlds. Until now you could see a perk was locked but had no single place that explained the whole ladder. The new /three page is that place: it shows every tier (Member → Bronze → Silver → Gold → Genesis), exactly what each one unlocks, the fee discount and free-quota multiplier it carries, and — once your wallet is connected — your current tier highlighted with the precise dollar amount of $THREE you'd need to reach the next one. Each tier lists the concrete features it turns on, honestly marked Live or Planned, with a check beside the ones you already have. Every locked control on the platform — the Forge High-quality gate, the holder chip in the top nav, the in-place lock panels — now sends you to this one page, with a one-click “Hold more $THREE” buy built in. The same tiers, the same upgrade path, everywhere. Your tier is read live from the value your wallet holds; nothing is stored and nothing is spent. $THREE is the only coin on three.ws.</description>
+ </item>
<item>
<title>Patronage: tips that build a real relationship with an agent</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 90c9134f5..633b81b27 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T10:31:59.087Z",
+ "generated_at": "2026-06-23T10:42:22.455Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1066,6 +1066,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/three",
+ "title": "$THREE Tiers · Hold-to-Access",
+ "description": "Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.",
+ "added": "2026-06-23",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": true
+ },
{
"path": "/three-live",
"title": "$THREE Live · Protocol Pulse",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 9ec3b967c..50035fc2f 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -646,6 +646,12 @@ URL: https://three.ws/gmgn
Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.
+### $THREE Tiers · Hold-to-Access
+
+URL: https://three.ws/three
+
+Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.
+
### $THREE Live · Protocol Pulse
URL: https://three.ws/three-live
diff --git a/public/llms.txt b/public/llms.txt
index a3429ed2e..e40d58c71 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -127,6 +127,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [x402 Arbitrage](https://three.ws/arbitrage): Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.
- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.
- [GMGN Smart Money](https://three.ws/gmgn): Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.
+- [$THREE Tiers · Hold-to-Access](https://three.ws/three): Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.
- [$THREE Live · Protocol Pulse](https://three.ws/three-live): The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.
- [Fact Checker](https://three.ws/fact-checker): Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.
- [Pay-As-You-Learn Tutor](https://three.ws/tutor): Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index a8d2bd496..d5eed230a 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 313 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 314 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 313 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 314 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -550,7 +550,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>59</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>60</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -848,6 +848,13 @@
<span class="sm-desc">Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.</span>
</a>
</li>
+ <li>
+ <a href="/three">
+ <span class="sm-title">$THREE Tiers · Hold-to-Access</span>
+ <span class="sm-path">/three</span>
+ <span class="sm-desc">Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, and private and branded worlds. See every tier, what it unlocks, and exactly how much $THREE you hold to reach the next one. The same tiering and the same upgrade path, everywhere.</span>
+ </a>
+ </li>
<li>
<a href="/three-live">
<span class="sm-title">$THREE Live · Protocol Pulse</span>
diff --git a/scripts/build-x402-catalog.mjs b/scripts/build-x402-catalog.mjs
new file mode 100644
index 000000000..b324da636
--- /dev/null
+++ b/scripts/build-x402-catalog.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+// Render the x402 discovery catalog (the same document api/wk.js serves at
+// /.well-known/x402.json) to a local JSON file WITHOUT a deploy, so a catalog
+// change can be validated offline before it ships:
+//
+// node scripts/build-x402-catalog.mjs > /tmp/x402.json
+// node scripts/verify-x402-discovery.mjs --file=/tmp/x402.json
+//
+// That two-step is the pre-deploy guard for the discovery catalog — a stray
+// newline in a payTo or a bazaar.info that fails its own schema delists every
+// resource, and waiting to find out from the live crawler is too late.
+//
+// Usage:
+// node scripts/build-x402-catalog.mjs # print JSON to stdout
+// node scripts/build-x402-catalog.mjs --out=path.json # write to a file
+
+const args = process.argv.slice(2);
+const outPath = args.find((a) => a.startsWith('--out='))?.slice('--out='.length) || null;
+
+// The discovery builder reads these at import time. Use the same well-formed
+// placeholders the discovery-parity test uses so both Base and Solana accepts
+// are advertised and APP_ORIGIN resolves. No CDP creds → Permit2 siblings are
+// omitted, matching production's non-CDP behavior. Real env (in prod/CI with
+// secrets) overrides these.
+const DEFAULTS = {
+ APP_ORIGIN: 'https://three.ws',
+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',
+ X402_PAY_TO_SOLANA: 'So11111111111111111111111111111111111111112',
+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ X402_ASSET_ADDRESS_ARBITRUM: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',
+ X402_MAX_AMOUNT_REQUIRED: '1000',
+ X402_FEE_PAYER_SOLANA: 'So11111111111111111111111111111111111111112',
+};
+for (const [k, v] of Object.entries(DEFAULTS)) if (!process.env[k]) process.env[k] = v;
+
+async function main() {
+ const mod = await import('../api/wk.js');
+ const res = {
+ statusCode: 0,
+ headers: {},
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(body) {
+ this.body = body;
+ },
+ };
+ const req = {
+ method: 'GET',
+ url: '/.well-known/x402-discovery?name=x402-discovery',
+ query: { name: 'x402-discovery' },
+ headers: {},
+ };
+ await mod.default(req, res);
+ if (!res.body) throw new Error('discovery handler produced no body');
+ // Re-serialize pretty so a committed/inspected snapshot is diff-friendly.
+ const pretty = JSON.stringify(JSON.parse(res.body), null, 2);
+ if (outPath) {
+ const { writeFile } = await import('node:fs/promises');
+ await writeFile(outPath, pretty + '\n');
+ const doc = JSON.parse(pretty);
+ process.stderr.write(`wrote ${doc.resources?.length ?? 0} resources → ${outPath}\n`);
+ } else {
+ process.stdout.write(pretty + '\n');
+ }
+}
+
+main().catch((err) => {
+ process.stderr.write(`✗ ${err.message}\n`);
+ process.exit(1);
+});
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 3493f1f2b..a541a665c 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -549,6 +549,11 @@ model-viewer.ad-hero-avatar {
border-color: rgba(87, 199, 255, 0.3);
background: rgba(87, 199, 255, 0.08);
}
+.ad-pill-red {
+ color: #f87171;
+ border-color: rgba(248, 113, 113, 0.35);
+ background: rgba(248, 113, 113, 0.08);
+}
.ad-services {
display: flex;
diff --git a/src/agent-detail.js b/src/agent-detail.js
index ede0f2e5c..db0f48413 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -1693,6 +1693,47 @@ function renderReputation(r) {
const TIER_EMOJI_MAP = { prime: '🟣', strong: '🔵', lean: '🟡', watch: '⚪', avoid: '🔴' };
+// Reasoning Ledger summary — the auditable track-record card. Best-effort:
+// hidden unless the agent has logged at least one decision. Verification runs in
+// the background and upgrades the badge in place.
+async function renderReasoningLedger(agentId) {
+ const card = document.getElementById('ad-ledger-card');
+ if (!card || !agentId) return;
+ let data;
+ try {
+ const r = await fetch(`/api/ledger/${encodeURIComponent(agentId)}?limit=1`);
+ if (!r.ok) return;
+ data = await r.json();
+ } catch { return; }
+
+ const rep = data.reputation;
+ if (!rep || !rep.decisions_total) return; // nothing logged yet — keep hidden
+
+ card.style.display = '';
+ const link = document.getElementById('ad-ledger-link');
+ if (link) link.href = `/ledger/${encodeURIComponent(agentId)}`;
+ const scoreEl = document.getElementById('ad-ledger-score');
+ if (scoreEl) scoreEl.textContent = String(rep.score);
+ const hitEl = document.getElementById('ad-ledger-hitrate');
+ if (hitEl) hitEl.textContent = rep.sample_size ? `${(rep.hit_rate * 100).toFixed(0)}% (${rep.wins}W/${rep.losses}L)` : 'pending';
+ const sampleEl = document.getElementById('ad-ledger-sample');
+ if (sampleEl) sampleEl.textContent = `${rep.sample_size} of ${rep.decisions_total}`;
+
+ const badge = document.getElementById('ad-ledger-verify');
+ if (!badge) return;
+ try {
+ const vr = await fetch(`/api/ledger/verify/${encodeURIComponent(agentId)}`);
+ const v = await vr.json();
+ if (v.status === 'verified') { badge.textContent = '✓ verified on-chain'; badge.className = 'ad-pill ad-pill-green'; }
+ else if (v.status === 'verified_unanchored') { badge.textContent = 'chain intact'; badge.className = 'ad-pill ad-pill-amber'; }
+ else if (v.status === 'verification_failed') { badge.textContent = '⚠ tamper detected'; badge.className = 'ad-pill ad-pill-red'; }
+ else { badge.textContent = 'no anchor'; badge.className = 'ad-pill ad-pill-muted'; }
+ } catch {
+ badge.textContent = 'unverified';
+ badge.className = 'ad-pill ad-pill-muted';
+ }
+}
+
async function renderOracleTrackRecord(agentId) {
const card = document.getElementById('ad-trading-card');
if (!card || !agentId) return;
@@ -2300,6 +2341,7 @@ function runLoad() {
track(ANALYTICS_EVENTS.AGENT_PROFILE_VIEWED, { agent_id: agent.id });
render(agent);
renderOracleTrackRecord(agent.id);
+ renderReasoningLedger(agent.id);
return;
}
if (notFound) return renderNotFound(id, typeof error === 'string' ? error : '');
diff --git a/src/dashboard-next/pages/creator.js b/src/dashboard-next/pages/creator.js
index ef6cdecda..e211d29f4 100644
--- a/src/dashboard-next/pages/creator.js
+++ b/src/dashboard-next/pages/creator.js
@@ -11,9 +11,9 @@
// path instrumented as the creator funnel.
import { mountShell } from '../shell.js';
-import { requireUser, get, post, put, del, patch, esc, relTime, formatUsdc, ApiError } from '../api.js';
+import { requireUser, get, post, put, del, esc, relTime, ApiError } from '../api.js';
import { errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
-import { track, trackFunnelStep, ANALYTICS_EVENTS } from '../../analytics.js';
+import { trackFunnelStep, ANALYTICS_EVENTS } from '../../analytics.js';
import {
TIER_LADDER,
usdcToAtomic,
@@ -97,12 +97,10 @@ const STATE = {
await loadAndRender(host);
});
- // Funnel step 1 — the creator showed up. Tag with where they are so the
- // activation rate (viewer → first price → first sale) is measurable.
- const hasPrices = false; // not loaded yet; refined after load
- track(ANALYTICS_EVENTS.CREATOR_ONBOARDING_STARTED, {
+ // Funnel step 1 — the creator showed up. The rest of the funnel
+ // (price set → payout wired → first sale) fires from the panels below.
+ trackFunnelStep('creator', ANALYTICS_EVENTS.CREATOR_ONBOARDING_STARTED, {
agent_count: STATE.agents.length,
- has_prices: hasPrices,
});
await loadAndRender(host);
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 26ec60d36..e90bf9731 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -902,7 +902,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {
defaults.push(
{ href: '/gallery-picker', title: 'Browse avatar gallery', sub: 'Explore public 3D avatars', iconKey: '/gallery-picker', cat: 'Create & Build' },
{ href: '/dashboard/widgets', title: 'Embed an agent', sub: 'Drop-in chat widget for any site', iconKey: '/dashboard/widgets', cat: 'Distribute & Embed' },
- { href: '/dashboard/creator', title: 'Creator Studio', sub: 'Price skills, track earnings, get paid', iconKey: '/dashboard/creator', cat: 'Monetize & Earn' },
+ { href: '/dashboard/creator', title: 'Creator Studio', sub: 'Price skills, track earnings, get paid', iconKey: '/dashboard/creator', cat: 'Monetize & Trade' },
{ href: '/voice', title: 'Voice Lab', sub: 'Clone your voice for avatars', iconKey: '/voice', cat: 'Create & Build' },
{ href: repHref, title: 'Reputation', sub: 'On-chain reviews and attestations', iconKey: '/reputation', cat: 'Agents & Identity' },
{ href: '/dashboard/api', title: 'API keys', sub: 'REST + MCP for your agents', iconKey: '/dashboard/api', cat: 'Distribute & Embed' },
@@ -975,6 +975,7 @@ const DIR_ICONS = {
'/discover': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7.5"/><path d="M10 2.5c-2 2.5-2 12.5 0 15M10 2.5c2 2.5 2 12.5 0 15M2.5 10h15"/></svg>',
'/embed': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 4h10a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z"/><path d="M8 9l-2 1.5L8 12M12 9l2 1.5L12 12"/></svg>',
'/dashboard/monetize': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7"/><path d="M10 6v8M7.5 8h4a1.5 1.5 0 010 3H8.5a1.5 1.5 0 000 3h4"/></svg>',
+ '/dashboard/creator': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 16l2.5-7 3 4 2.5-6 3 9"/><path d="M3 16h13"/><circle cx="15.5" cy="5" r="2"/></svg>',
'/dashboard/tokens': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l2.5 5 5.5.8-4 3.9.9 5.5L10 14.7l-4.9 2.5.9-5.5L2 7.8l5.5-.8L10 2z"/></svg>',
'/dashboard/portfolio': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="16" height="11" rx="1.5"/><path d="M6 7V5a4 4 0 018 0v2"/><path d="M2 11h16"/></svg>',
'/pump-live': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="2"/><path d="M6 6a5.5 5.5 0 000 8M14 6a5.5 5.5 0 010 8"/><path d="M3.5 3.5a9 9 0 000 13M16.5 3.5a9 9 0 010 13"/></svg>',
@@ -1046,6 +1047,7 @@ const DIRECTORY = [
{
group: 'Monetize & Trade',
items: [
+ { href: '/dashboard/creator', title: 'Creator Studio', sub: 'Price skills, track earnings, get paid' },
{ href: '/dashboard/monetize', title: 'Monetize', sub: 'Revenue, subscriptions, and withdrawals' },
{ href: '/dashboard/tokens', title: 'Tokens', sub: 'Launch tokens on Pump.fun with bonding curves' },
{ href: '/dashboard/portfolio', title: 'Portfolio', sub: 'Live balances, price charts, and market data' },
diff --git a/src/stage.js b/src/stage.js
new file mode 100644
index 000000000..0973e657d
--- /dev/null
+++ b/src/stage.js
@@ -0,0 +1,931 @@
+// /stage — Living Stages audience surface (Moonshot 04).
+//
+// Two modes off one entry:
+// • directory (no ?id) — the marquee: live shows first, then upcoming, then
+// recently-ended, each a card into a venue.
+// • venue (?id=<stage>) — enter the 3D room, hear the embodied host with
+// spatial voice + lip-sync synchronized across every connected client, see
+// the co-present crowd + their reactions, tip the host in real $THREE on the
+// spot, watch the live tipper leaderboard, and queue a question.
+//
+// The host's words arrive as a timed `utterance` broadcast (one per beat) that
+// every client renders identically: we fetch /api/tts/speak for the text, route
+// it through a THREE.PositionalAudio (so it gets louder as you move closer) with
+// a real AnalyserNode driving lip-sync, and show the text as live captions. A tip
+// settles on-chain to the host wallet, we record it via /api/stage/tip, and the
+// room makes the host react within ~1s. Every state is designed; with no WebGL
+// the captions, tips, and leaderboard still work (audio + text, no 3D).
+
+import {
+ Scene, PerspectiveCamera, WebGLRenderer, Color, Fog,
+ AmbientLight, DirectionalLight, SpotLight, PointLight,
+ Mesh, CylinderGeometry, CircleGeometry, PlaneGeometry, BoxGeometry,
+ MeshStandardMaterial, MeshBasicMaterial, Group, Vector3,
+ AudioListener, PositionalAudio, AudioAnalyser, SRGBColorSpace, ACESFilmicToneMapping,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
+import { apiFetch } from './api.js';
+import { StageNet } from './stage-net.js';
+import { tipAgent, TipError } from './shared/agent-tip.js';
+import { LipsyncDriver } from './voice/lipsync-driver.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const THREE_DECIMALS = 6;
+const TIP_PRESETS = [100, 500, 2000, 10000]; // $THREE
+const REACTIONS = [
+ { id: 'clap', emoji: '👏' },
+ { id: 'fire', emoji: '🔥' },
+ { id: 'heart', emoji: '💜' },
+ { id: 'laugh', emoji: '😂' },
+ { id: 'wow', emoji: '😮' },
+ { id: 'cheer', emoji: '🎉' },
+];
+const REACTION_EMOJI = Object.fromEntries(REACTIONS.map((r) => [r.id, r.emoji]));
+const REDUCED_MOTION = matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const fmtThree = (atomic) => Math.round(Number(atomic || 0) / 10 ** THREE_DECIMALS).toLocaleString('en-US');
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+const root = document.getElementById('stage-app');
+const params = new URLSearchParams(location.search);
+const stageId = params.get('id');
+
+if (stageId) bootVenue(stageId);
+else bootDirectory();
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Directory
+// ─────────────────────────────────────────────────────────────────────────────
+async function bootDirectory() {
+ root.innerHTML = `
+ <header class="stage-dir-head">
+ <h1>Living Stages</h1>
+ <p>Live, embodied AI performances. Show up, hear the host, tip in $THREE — the biggest tippers get the floor.</p>
+ </header>
+ <div id="stage-dir" class="stage-dir" aria-live="polite">${skeletonCards(6)}</div>`;
+ const grid = document.getElementById('stage-dir');
+ try {
+ const res = await apiFetch('/api/stage', { allowAnonymous: true });
+ const data = await res.json();
+ const stages = data.stages || [];
+ if (!stages.length) {
+ grid.innerHTML = emptyState(
+ 'No stages yet',
+ 'Be the first to put an agent on stage. Open an agent you own and start a stage from its profile.',
+ '/agents', 'Browse agents',
+ );
+ return;
+ }
+ // Live first — the marquee.
+ grid.innerHTML = stages.map(stageCard).join('');
+ } catch (err) {
+ grid.innerHTML = errorState('Could not load stages', () => bootDirectory());
+ wireRetry(grid);
+ }
+}
+
+function stageCard(s) {
+ const live = s.live;
+ const when = s.next_show_at && !live ? `Next show ${new Date(s.next_show_at).toLocaleString()}` : '';
+ const tips = s.recentTipsAtomic ? `${fmtThree(s.recentTipsAtomic)} $THREE tipped` : 'New stage';
+ return `
+ <a class="stage-card ${live ? 'is-live' : ''}" href="/stage?id=${encodeURIComponent(s.id)}">
+ <div class="stage-card-art" style="${s.host_avatar ? `background-image:url('${esc(s.host_avatar)}')` : ''}">
+ ${live ? '<span class="stage-badge-live">● LIVE</span>' : '<span class="stage-badge-soon">SOON</span>'}
+ </div>
+ <div class="stage-card-body">
+ <h3>${esc(s.title || s.host_name || 'Untitled stage')}</h3>
+ <p class="stage-card-host">${esc(s.host_name || 'AI host')} · ${esc(s.format || 'live')}</p>
+ <p class="stage-card-meta">${live ? '<b>On now</b> · ' : ''}${esc(when || tips)}</p>
+ </div>
+ </a>`;
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Venue
+// ─────────────────────────────────────────────────────────────────────────────
+async function bootVenue(id) {
+ root.innerHTML = venueShell();
+ const els = {
+ canvas: document.getElementById('stage-canvas'),
+ stageWrap: document.getElementById('stage-3d'),
+ title: document.getElementById('stage-title'),
+ hostName: document.getElementById('stage-host-name'),
+ phase: document.getElementById('stage-phase'),
+ caption: document.getElementById('stage-caption'),
+ captionText: document.querySelector('#stage-caption .cap-text'),
+ audienceCount: document.getElementById('stage-aud-count'),
+ ticker: document.getElementById('stage-ticker'),
+ leaderboard: document.getElementById('stage-leaderboard'),
+ total: document.getElementById('stage-total'),
+ tipBtns: document.getElementById('stage-tip-presets'),
+ tipCustom: document.getElementById('stage-tip-custom'),
+ tipSend: document.getElementById('stage-tip-send'),
+ tipMsg: document.getElementById('stage-tip-msg'),
+ tipStatus: document.getElementById('stage-tip-status'),
+ reactions: document.getElementById('stage-reactions'),
+ askInput: document.getElementById('stage-ask-input'),
+ askBtn: document.getElementById('stage-ask-btn'),
+ askStatus: document.getElementById('stage-ask-status'),
+ netPill: document.getElementById('stage-net-pill'),
+ closer: document.getElementById('stage-closer'),
+ farther: document.getElementById('stage-farther'),
+ soundBtn: document.getElementById('stage-sound'),
+ };
+
+ // Load stage config.
+ let detail;
+ try {
+ const res = await apiFetch(`/api/stage?id=${encodeURIComponent(id)}`, { allowAnonymous: true });
+ if (!res.ok) throw new Error(`http ${res.status}`);
+ detail = await res.json();
+ } catch (err) {
+ els.stageWrap.innerHTML = errorState('Stage not found', () => bootVenue(id));
+ wireRetry(els.stageWrap);
+ return;
+ }
+ const stage = detail.stage;
+ document.title = `${stage.title || stage.host_name} · Living Stage · three.ws`;
+ els.title.textContent = stage.title || `${stage.host_name} Live`;
+ els.hostName.textContent = stage.host_name || 'AI host';
+
+ const ctrl = new VenueController(id, stage, detail, els);
+ ctrl.start();
+ window.addEventListener('beforeunload', () => ctrl.dispose());
+}
+
+class VenueController {
+ constructor(stageId, stage, detail, els) {
+ this.stageId = stageId;
+ this.stage = stage;
+ this.detail = detail;
+ this.els = els;
+ this.hostWallet = detail.hostWallet || null;
+ this.lastUtteranceId = -1;
+ this.tipAmount = TIP_PRESETS[1];
+ this.tipping = false;
+ this.three = null; // {renderer,scene,camera,listener,host,mouth,...}
+ this.audioCtxResumed = false;
+ this.currentAudio = null;
+ this.lipsync = null;
+ this.audPositions = new Map();
+ this.muted = false;
+ }
+
+ start() {
+ this.renderPhase(this.detail.live ? 'live' : (this.stage.next_show_at ? 'between' : 'preshow'));
+ this.renderLeaderboard(this.detail.leaderboard || [], this.detail.currentShow || this.detail.lastShow);
+ this.buildTipControls();
+ this.buildReactions();
+ this.initThree();
+ this.connect();
+ this.wireControls();
+ }
+
+ // ── realtime ──────────────────────────────────────────────────────────────
+ connect() {
+ const me = readSelfIdentity();
+ this.net = new StageNet({ stageId: this.stageId, name: me.name, avatar: me.avatar });
+ this.net.on('status', ({ status }) => this.onNetStatus(status));
+ this.net.on('host', (h) => this.onHost(h));
+ this.net.on('utterance', (u) => this.onUtterance(u));
+ this.net.on('audience', (a) => this.onAudience(a));
+ this.net.on('tip', (t) => this.onTip(t));
+ this.net.on('leaderboard', (lb) => this.onLeaderboard(lb));
+ this.net.on('reaction', (r) => this.onReaction(r));
+ this.net.connect();
+ }
+
+ onNetStatus(status) {
+ const pill = this.els.netPill;
+ const map = {
+ online: ['● live feed', 'ok'],
+ connecting: ['connecting…', 'warn'],
+ offline: ['reconnecting…', 'warn'],
+ failed: ['feed offline', 'bad'],
+ unavailable: ['feed offline', 'bad'],
+ idle: ['…', 'warn'],
+ };
+ const [label, cls] = map[status] || ['…', 'warn'];
+ pill.textContent = label;
+ pill.className = `stage-net-pill ${cls}`;
+ pill.hidden = false;
+ }
+
+ onHost(h) {
+ if (!h) return;
+ if (h.name && this.els.hostName.textContent !== h.name) this.els.hostName.textContent = h.name;
+ // Render the current caption even for a late joiner (state-synced).
+ if (h.caption) this.showCaption(h.caption, h.speaking);
+ if (this.three) this.three.setCue(h.cue, h.speaking);
+ if (h.beat) this.renderPhase('live');
+ }
+
+ // A timed spoken beat — fetch TTS, play it spatially with lip-sync, show captions.
+ async onUtterance(u) {
+ if (!u || u.id === this.lastUtteranceId) return;
+ this.lastUtteranceId = u.id;
+ this.showCaption(u.text, true);
+ this.renderPhase('live');
+ if (this.three) this.three.setCue(u.cue, true);
+ await this.speak(u.text, u.voice, u.durationMs);
+ }
+
+ onAudience(a) {
+ this.els.audienceCount.textContent = a.count === 1 ? '1 here' : `${a.count} here`;
+ if (this.three) this.three.setAudience(a.members, a.selfId);
+ }
+
+ onTip(t) {
+ this.pushTicker(`${t.label} tipped ${fmtThree(t.amount)} $THREE${t.isNewTopTipper ? ' — new top tipper! 👑' : ''}`, 'tip', t.explorer);
+ if (this.three) this.three.burst(t.isNewTopTipper ? 'gold' : 'cheer');
+ }
+
+ onLeaderboard(lb) {
+ this.renderLeaderboardRows(lb.rows || []);
+ this.els.total.textContent = `${fmtThree(lb.totalTipsAtomic)} $THREE · ${lb.tipCount} tips`;
+ if (lb.phase === 'between' || lb.phase === 'ended') this.renderPhase(lb.phase);
+ else if (lb.phase === 'live') this.renderPhase('live');
+ }
+
+ onReaction(r) {
+ if (r?.ack) {
+ this.els.askStatus.textContent = r.ack.ok ? 'Queued — the host will get to it.' : 'Slow down a moment.';
+ return;
+ }
+ if (this.three && r?.emoji) this.three.floatEmoji(r.id, REACTION_EMOJI[r.emoji] || '✨');
+ }
+
+ // ── host voice: spatial + lip-sync, synced across clients ───────────────────
+ async speak(text, voice, durationMs) {
+ if (this.muted || !text) return;
+ this.stopAudio();
+ let buf;
+ try {
+ const res = await apiFetch('/api/tts/speak', {
+ method: 'POST',
+ allowAnonymous: true,
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice: voice || 'nova', format: 'mp3' }),
+ });
+ if (!res.ok) throw new Error(`tts ${res.status}`);
+ buf = await res.arrayBuffer();
+ } catch {
+ return; // captions already carry the words; audio is best-effort
+ }
+ const blob = new Blob([buf], { type: 'audio/mpeg' });
+ const url = URL.createObjectURL(blob);
+ const audio = new Audio();
+ audio.src = url;
+ audio.crossOrigin = 'anonymous';
+ this.currentAudio = audio;
+ audio.addEventListener('ended', () => { URL.revokeObjectURL(url); this.stopLipsync(); }, { once: true });
+
+ // Route through the host's PositionalAudio when 3D is up (spatial + analyser
+ // lip-sync); otherwise just play the element (no-WebGL audio still works).
+ if (this.three?.attachVoice) {
+ try {
+ const analyser = this.three.attachVoice(audio);
+ if (analyser) this.startLipsync(analyser);
+ } catch {
+ /* fall through to plain playback */
+ }
+ }
+ try {
+ await audio.play();
+ } catch {
+ // Autoplay blocked until a gesture — surface the sound button.
+ this.els.soundBtn.hidden = false;
+ }
+ }
+
+ startLipsync(analyser) {
+ this.stopLipsync();
+ if (!this.three?.mouthTarget) return;
+ try {
+ this.lipsync = new LipsyncDriver({ analyser, target: this.three.mouthTarget, gain: 1.5 });
+ this.lipsync.start();
+ } catch { /* lip-sync is enhancement, never required */ }
+ }
+
+ stopLipsync() {
+ if (this.lipsync) { try { this.lipsync.stop(); } catch {} this.lipsync = null; }
+ if (this.three) this.three.setCue('idle', false);
+ }
+
+ stopAudio() {
+ if (this.currentAudio) {
+ try { this.currentAudio.pause(); } catch {}
+ this.currentAudio = null;
+ }
+ this.stopLipsync();
+ }
+
+ // ── tipping ─────────────────────────────────────────────────────────────────
+ buildTipControls() {
+ this.els.tipBtns.innerHTML = TIP_PRESETS.map(
+ (v, i) => `<button type="button" class="stage-tip-preset ${i === 1 ? 'active' : ''}" data-amt="${v}">${v.toLocaleString()}</button>`,
+ ).join('');
+ this.els.tipBtns.querySelectorAll('button').forEach((b) => {
+ b.addEventListener('click', () => {
+ this.tipAmount = Number(b.dataset.amt);
+ this.els.tipCustom.value = '';
+ this.els.tipBtns.querySelectorAll('button').forEach((x) => x.classList.toggle('active', x === b));
+ });
+ });
+ this.els.tipCustom.addEventListener('input', () => {
+ const v = Number(this.els.tipCustom.value);
+ if (v > 0) {
+ this.tipAmount = v;
+ this.els.tipBtns.querySelectorAll('button').forEach((x) => x.classList.remove('active'));
+ }
+ });
+ this.els.tipSend.addEventListener('click', () => this.sendTip());
+ }
+
+ async sendTip() {
+ if (this.tipping) return;
+ const amount = Number(this.tipAmount);
+ if (!(amount > 0)) { this.tipStatus('Enter an amount to tip.', 'warn'); return; }
+ if (!this.hostWallet) { this.tipStatus('This host has no wallet to tip yet.', 'bad'); return; }
+ if (!this.detail.live && !document.querySelector('.stage-phase.is-live')) {
+ this.tipStatus('Tips open when the host goes live.', 'warn');
+ return;
+ }
+ this.tipping = true;
+ this.els.tipSend.disabled = true;
+ const msg = this.els.tipMsg.value.trim().slice(0, 140);
+ try {
+ this.tipStatus('Connecting your wallet…', 'warn');
+ const settle = await tipAgent({
+ toAddress: this.hostWallet,
+ token: 'SPL',
+ mint: THREE_MINT,
+ decimals: THREE_DECIMALS,
+ amount,
+ network: 'mainnet',
+ noBalanceMsg: 'Your wallet holds no $THREE to tip with.',
+ onStage: (s) => this.tipStatus(tipStageLabel(s), 'warn'),
+ });
+ this.tipStatus('Recording your tip…', 'warn');
+ const res = await apiFetch('/api/stage/tip', {
+ method: 'POST',
+ allowAnonymous: true,
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ stageId: this.stageId,
+ signature: settle.signature,
+ currencyMint: THREE_MINT,
+ amount: Math.round(amount * 10 ** THREE_DECIMALS),
+ message: msg,
+ network: 'solana',
+ tipperSession: this.net?.sessionId || null,
+ }),
+ });
+ const out = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(out.error || 'could not record tip');
+ this.tipStatus(`Tipped ${amount.toLocaleString()} $THREE 🎉`, 'ok');
+ this.els.tipMsg.value = '';
+ } catch (err) {
+ const code = err instanceof TipError ? err.code : '';
+ if (code === 'cancelled') this.tipStatus('Tip cancelled.', 'warn');
+ else this.tipStatus(err?.message || 'Tip failed — try again.', 'bad');
+ } finally {
+ this.tipping = false;
+ this.els.tipSend.disabled = false;
+ }
+ }
+
+ tipStatus(text, cls) {
+ this.els.tipStatus.textContent = text;
+ this.els.tipStatus.className = `stage-tip-status ${cls || ''}`;
+ }
+
+ // ── reactions + questions ───────────────────────────────────────────────────
+ buildReactions() {
+ this.els.reactions.innerHTML = REACTIONS.map(
+ (r) => `<button type="button" class="stage-react" data-id="${r.id}" aria-label="React ${r.id}">${r.emoji}</button>`,
+ ).join('');
+ this.els.reactions.querySelectorAll('button').forEach((b) => {
+ b.addEventListener('click', () => {
+ this.net?.react(b.dataset.id);
+ if (this.three) this.three.floatEmoji(this.net?.sessionId, REACTION_EMOJI[b.dataset.id]);
+ b.animate?.([{ transform: 'scale(1)' }, { transform: 'scale(1.4)' }, { transform: 'scale(1)' }], { duration: 240 });
+ });
+ });
+ const ask = () => {
+ const text = this.els.askInput.value.trim();
+ if (!text) return;
+ const ok = this.net?.ask(text);
+ this.els.askStatus.textContent = ok ? 'Sent — the host picks from the queue.' : 'Feed offline — try again in a moment.';
+ if (ok) this.els.askInput.value = '';
+ };
+ this.els.askBtn.addEventListener('click', ask);
+ this.els.askInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') ask(); });
+ }
+
+ // ── captions + ticker + phases ──────────────────────────────────────────────
+ showCaption(text, speaking) {
+ this.els.captionText.textContent = text;
+ this.els.caption.classList.toggle('speaking', !!speaking);
+ this.els.caption.hidden = false;
+ }
+
+ pushTicker(text, kind, link) {
+ const item = document.createElement('div');
+ item.className = `stage-ticker-item ${kind || ''}`;
+ item.innerHTML = link
+ ? `<a href="${esc(link)}" target="_blank" rel="noopener">${esc(text)}</a>`
+ : esc(text);
+ this.els.ticker.prepend(item);
+ while (this.els.ticker.children.length > 6) this.els.ticker.lastChild.remove();
+ if (!REDUCED_MOTION) item.animate?.([{ opacity: 0, transform: 'translateY(-6px)' }, { opacity: 1, transform: 'none' }], { duration: 260 });
+ }
+
+ renderPhase(phase) {
+ const el = this.els.phase;
+ el.className = 'stage-phase';
+ if (phase === 'live') { el.classList.add('is-live'); el.innerHTML = '<span class="dot"></span> LIVE'; }
+ else if (phase === 'between') { el.textContent = nextShowLabel(this.stage.next_show_at) || 'Between shows'; }
+ else if (phase === 'ended') { el.textContent = 'Show ended — highlights below'; }
+ else { el.textContent = this.stage.next_show_at ? nextShowLabel(this.stage.next_show_at) : 'Pre-show'; }
+ }
+
+ renderLeaderboard(rows, show) {
+ this.renderLeaderboardRows(rows);
+ const total = show?.total_tips_atomic || 0;
+ const count = show?.tip_count || 0;
+ this.els.total.textContent = total ? `${fmtThree(total)} $THREE · ${count} tips` : 'No tips yet — be the first';
+ }
+
+ renderLeaderboardRows(rows) {
+ if (!rows.length) {
+ this.els.leaderboard.innerHTML = '<li class="stage-lb-empty">Tip the host to take the top spot 👑</li>';
+ return;
+ }
+ this.els.leaderboard.innerHTML = rows
+ .map((r, i) => `<li class="${i === 0 ? 'top' : ''}"><span class="rank">${i + 1}</span><span class="who">${esc(r.label)}</span><span class="amt">${fmtThree(r.total)}</span></li>`)
+ .join('');
+ }
+
+ // ── 3D venue ────────────────────────────────────────────────────────────────
+ initThree() {
+ if (!hasWebGL()) {
+ this.els.stageWrap.classList.add('no-webgl');
+ this.els.stageWrap.querySelector('.stage-3d-fallback').hidden = false;
+ return;
+ }
+ try {
+ this.three = new StageScene(this.els.canvas, this.stage);
+ this.three.load();
+ } catch (err) {
+ this.els.stageWrap.classList.add('no-webgl');
+ this.els.stageWrap.querySelector('.stage-3d-fallback').hidden = false;
+ }
+ }
+
+ wireControls() {
+ const resume = () => {
+ if (this.three) this.three.resumeAudio();
+ this.els.soundBtn.hidden = true;
+ this.audioCtxResumed = true;
+ // Replay the current line so a gesture-gated first utterance is heard.
+ if (this.currentAudio) this.currentAudio.play?.().catch(() => {});
+ };
+ this.els.soundBtn.addEventListener('click', resume);
+ this.els.closer?.addEventListener('click', () => this.three?.dolly(-1));
+ this.els.farther?.addEventListener('click', () => this.three?.dolly(1));
+ // First interaction anywhere resumes audio (browsers gate autoplay).
+ window.addEventListener('pointerdown', () => { if (!this.audioCtxResumed) resume(); }, { once: true });
+ }
+
+ dispose() {
+ try { this.net?.destroy(); } catch {}
+ this.stopAudio();
+ try { this.three?.dispose(); } catch {}
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// StageScene — the Three.js venue
+// ─────────────────────────────────────────────────────────────────────────────
+class StageScene {
+ constructor(canvas, stage) {
+ this.canvas = canvas;
+ this.stage = stage;
+ this.scene = new Scene();
+ this.scene.background = new Color(0x07060d);
+ this.scene.fog = new Fog(0x07060d, 14, 42);
+
+ this.camera = new PerspectiveCamera(52, 1, 0.1, 200);
+ this.camDist = 9;
+ this.camHeight = 2.4;
+ this.camera.position.set(0, this.camHeight, this.camDist);
+ this.camera.lookAt(0, 1.6, 0);
+
+ this.listener = new AudioListener();
+ this.camera.add(this.listener);
+
+ this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false });
+ this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+ this.renderer.outputColorSpace = SRGBColorSpace;
+ this.renderer.toneMapping = ACESFilmicToneMapping;
+ this.renderer.toneMappingExposure = 1.1;
+
+ this._buildVenue();
+ this.hostGroup = new Group();
+ this.hostGroup.position.set(0, 0, 0);
+ this.scene.add(this.hostGroup);
+ this.audienceGroup = new Group();
+ this.scene.add(this.audienceGroup);
+ this.emojiSprites = [];
+ this.audienceMeshes = new Map();
+
+ this.mouthTarget = null;
+ this.positionalAudio = null;
+ this._cue = 'idle';
+ this._speaking = false;
+ this._t = 0;
+ this._raf = 0;
+ this._onResize = () => this._resize();
+ window.addEventListener('resize', this._onResize);
+ this._resize();
+ this._loop();
+ }
+
+ _buildVenue() {
+ this.scene.add(new AmbientLight(0x404060, 1.1));
+ const key = new DirectionalLight(0xffffff, 1.4);
+ key.position.set(4, 9, 6);
+ this.scene.add(key);
+ // Stage spotlights — the show look.
+ const spot = new SpotLight(0x9b6bff, 60, 30, Math.PI / 6, 0.4, 1.2);
+ spot.position.set(0, 9, 4);
+ spot.target.position.set(0, 1.5, 0);
+ this.scene.add(spot, spot.target);
+ const spot2 = new SpotLight(0x32d6ff, 40, 30, Math.PI / 5, 0.5, 1.2);
+ spot2.position.set(-6, 8, 2);
+ spot2.target.position.set(0, 1.5, 0);
+ this.scene.add(spot2, spot2.target);
+ this.rim = new PointLight(0xff5db1, 30, 18, 1.5);
+ this.rim.position.set(0, 3, -3);
+ this.scene.add(this.rim);
+
+ const floor = new Mesh(
+ new PlaneGeometry(80, 80),
+ new MeshStandardMaterial({ color: 0x0c0b16, roughness: 0.85, metalness: 0.1 }),
+ );
+ floor.rotation.x = -Math.PI / 2;
+ this.scene.add(floor);
+ // Raised stage disc.
+ const disc = new Mesh(
+ new CylinderGeometry(3.4, 3.6, 0.4, 48),
+ new MeshStandardMaterial({ color: 0x1a1730, roughness: 0.5, metalness: 0.3, emissive: 0x140a2e, emissiveIntensity: 0.6 }),
+ );
+ disc.position.y = 0.2;
+ this.scene.add(disc);
+ const ring = new Mesh(
+ new CircleGeometry(3.3, 48),
+ new MeshBasicMaterial({ color: 0x9b6bff }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.41;
+ ring.scale.setScalar(1);
+ this.ring = ring;
+ this.scene.add(ring);
+ }
+
+ load() {
+ // Placeholder host so the stage is never empty while the GLB streams in.
+ this.placeholder = new Mesh(
+ new CylinderGeometry(0.5, 0.6, 1.7, 20),
+ new MeshStandardMaterial({ color: 0x6b4bd6, emissive: 0x3a1f7a, emissiveIntensity: 0.7, roughness: 0.4 }),
+ );
+ this.placeholder.position.set(0, 1.25, 0);
+ this.hostGroup.add(this.placeholder);
+
+ const url = this.stage.host_avatar;
+ if (!url) return;
+ const loader = new GLTFLoader();
+ try { loader.setMeshoptDecoder(MeshoptDecoder); } catch {}
+ loader.load(
+ url,
+ (gltf) => this._mountHost(gltf.scene),
+ undefined,
+ () => { /* keep the placeholder — a missing GLB must not empty the stage */ },
+ );
+ }
+
+ _mountHost(model) {
+ if (this.placeholder) { this.hostGroup.remove(this.placeholder); this.placeholder = null; }
+ // Normalize to ~1.7m tall, feet on the disc.
+ const box = new (model.constructor === Group ? Group : Group)();
+ model.updateMatrixWorld(true);
+ const bounds = boundingSize(model);
+ const scale = bounds.height > 0 ? 1.7 / bounds.height : 1;
+ model.scale.setScalar(scale);
+ model.position.y = 0.4;
+ this.hostGroup.add(model);
+ this.hostModel = model;
+ this.mouthTarget = new MouthTarget(model);
+
+ // Attach positional audio to the host head (or the model root).
+ this.positionalAudio = new PositionalAudio(this.listener);
+ this.positionalAudio.setRefDistance(2.4);
+ this.positionalAudio.setRolloffFactor(1.1);
+ this.positionalAudio.setDistanceModel('inverse');
+ const head = findHead(model) || model;
+ head.add(this.positionalAudio);
+ }
+
+ // Wire an <audio> element through the host's PositionalAudio and return an
+ // AnalyserNode for lip-sync. Returns null when 3D audio isn't ready.
+ attachVoice(audioEl) {
+ if (!this.positionalAudio) return null;
+ this.resumeAudio();
+ try {
+ // A MediaElementSource can be created once per element; this element is
+ // fresh per utterance, so this is safe.
+ this.positionalAudio.setMediaElementSource(audioEl);
+ } catch {
+ return null;
+ }
+ const analyser = new AudioAnalyser(this.positionalAudio, 256);
+ return analyser.analyser;
+ }
+
+ resumeAudio() {
+ const ctx = this.listener?.context;
+ if (ctx && ctx.state === 'suspended') ctx.resume().catch(() => {});
+ }
+
+ setCue(cue, speaking) {
+ this._cue = cue || 'idle';
+ this._speaking = !!speaking;
+ }
+
+ setAudience(members, selfId) {
+ const seen = new Set();
+ for (const m of members) {
+ seen.add(m.id);
+ let mesh = this.audienceMeshes.get(m.id);
+ if (!mesh) {
+ mesh = new Mesh(
+ new CylinderGeometry(0.28, 0.34, 1.1, 12),
+ new MeshStandardMaterial({ color: m.id === selfId ? 0x32d6ff : 0x4a4470, roughness: 0.7, emissive: m.vip ? 0xffb020 : 0x000000, emissiveIntensity: m.vip ? 0.5 : 0 }),
+ );
+ mesh.position.set(m.x, 0.55, m.z);
+ this.audienceGroup.add(mesh);
+ this.audienceMeshes.set(m.id, mesh);
+ } else if (m.vip) {
+ mesh.material.emissive.setHex(0xffb020);
+ mesh.material.emissiveIntensity = 0.5;
+ }
+ }
+ for (const [id, mesh] of this.audienceMeshes) {
+ if (!seen.has(id)) { this.audienceGroup.remove(mesh); disposeMesh(mesh); this.audienceMeshes.delete(id); }
+ }
+ }
+
+ floatEmoji(_id, emoji) {
+ if (REDUCED_MOTION || !emoji) return;
+ // A lightweight DOM emoji floating up from the stage (no sprite atlas needed).
+ const el = document.createElement('div');
+ el.className = 'stage-float-emoji';
+ el.textContent = emoji;
+ el.style.left = `${40 + Math.random() * 20}%`;
+ this.canvas.parentElement.appendChild(el);
+ el.animate([{ transform: 'translateY(0) scale(1)', opacity: 1 }, { transform: 'translateY(-140px) scale(1.6)', opacity: 0 }], { duration: 1400, easing: 'ease-out' })
+ .addEventListener('finish', () => el.remove());
+ }
+
+ burst(kind) {
+ if (REDUCED_MOTION) return;
+ const color = kind === 'gold' ? 0xffd24a : 0x9b6bff;
+ this.rim.color.setHex(color);
+ this.ring.material.color.setHex(color);
+ this._burstT = 1;
+ }
+
+ dolly(dir) {
+ this.camDist = Math.max(4.5, Math.min(16, this.camDist + dir * 1.6));
+ }
+
+ _resize() {
+ const w = this.canvas.clientWidth || this.canvas.parentElement.clientWidth;
+ const h = this.canvas.clientHeight || this.canvas.parentElement.clientHeight;
+ if (!w || !h) return;
+ this.renderer.setSize(w, h, false);
+ this.camera.aspect = w / h;
+ this.camera.updateProjectionMatrix();
+ }
+
+ _loop() {
+ this._raf = requestAnimationFrame(() => this._loop());
+ const dt = REDUCED_MOTION ? 0 : 0.016;
+ this._t += dt;
+ // Ease camera toward target distance (proximity → louder host via listener).
+ const tx = 0, tz = this.camDist;
+ this.camera.position.x += (tx - this.camera.position.x) * 0.06;
+ this.camera.position.z += (tz - this.camera.position.z) * 0.06;
+ this.camera.position.y = this.camHeight;
+ this.camera.lookAt(0, 1.5, 0);
+
+ // Host idle bob + a stronger sway while speaking.
+ if (this.hostModel) {
+ const amp = this._speaking ? 0.05 : 0.02;
+ this.hostModel.position.y = 0.4 + Math.sin(this._t * 2) * amp;
+ if (this._cue === 'dj') this.hostModel.rotation.y = Math.sin(this._t * 3) * 0.25;
+ else this.hostModel.rotation.y += ((0) - this.hostModel.rotation.y) * 0.05;
+ }
+ if (this.placeholder) this.placeholder.position.y = 1.25 + Math.sin(this._t * 2) * 0.04;
+
+ // Pulse the stage ring while speaking.
+ if (this.ring) {
+ const s = 1 + (this._speaking ? Math.abs(Math.sin(this._t * 4)) * 0.04 : 0);
+ this.ring.scale.setScalar(s);
+ }
+ if (this._burstT > 0) {
+ this._burstT -= 0.02;
+ if (this._burstT <= 0) { this.rim.color.setHex(0xff5db1); this.ring.material.color.setHex(0x9b6bff); }
+ }
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ dispose() {
+ cancelAnimationFrame(this._raf);
+ window.removeEventListener('resize', this._onResize);
+ try { this.renderer.dispose(); } catch {}
+ }
+}
+
+// Maps lip-sync {open,wide,round} onto whatever the GLB rig supports: morph
+// targets (visemes / mouthOpen / jawOpen) when present, else a jaw bone, else a
+// subtle head scale — so lip-sync is real where the rig allows and degrades
+// gracefully where it doesn't (no T-pose, never a hard failure).
+class MouthTarget {
+ constructor(model) {
+ this.influences = [];
+ this.jaw = null;
+ this.head = findHead(model);
+ const openNames = /(mouthopen|jawopen|viseme_aa|viseme_o|vrc\.v_aa|mouth_open|aa)/i;
+ model.traverse((o) => {
+ if (o.isMesh && o.morphTargetDictionary) {
+ for (const [name, idx] of Object.entries(o.morphTargetDictionary)) {
+ if (openNames.test(name)) this.influences.push({ mesh: o, idx });
+ }
+ }
+ if (o.isBone && /jaw/i.test(o.name) && !this.jaw) this.jaw = o;
+ });
+ }
+ setMouthShape({ open }) {
+ const v = Math.max(0, Math.min(1, open));
+ if (this.influences.length) {
+ for (const { mesh, idx } of this.influences) mesh.morphTargetInfluences[idx] = v;
+ } else if (this.jaw) {
+ this.jaw.rotation.x = v * 0.35;
+ } else if (this.head) {
+ this.head.scale.y = 1 + v * 0.03;
+ }
+ }
+ dispose() {
+ for (const { mesh, idx } of this.influences) if (mesh.morphTargetInfluences) mesh.morphTargetInfluences[idx] = 0;
+ if (this.jaw) this.jaw.rotation.x = 0;
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// helpers
+// ─────────────────────────────────────────────────────────────────────────────
+function venueShell() {
+ return `
+ <div class="stage-venue">
+ <div class="stage-main">
+ <div id="stage-3d" class="stage-3d">
+ <canvas id="stage-canvas" aria-label="Live 3D stage"></canvas>
+ <div class="stage-3d-fallback" hidden>
+ <div class="stage-fallback-card">
+ <h2>Audio + captions mode</h2>
+ <p>Your browser can't render the 3D venue, but the show goes on — you'll hear the host and read every line below, and you can still tip in $THREE.</p>
+ </div>
+ </div>
+ <div id="stage-caption" class="stage-caption" hidden><span class="cap-text"></span></div>
+ <div class="stage-overlay-top">
+ <div class="stage-id">
+ <span id="stage-phase" class="stage-phase">…</span>
+ <h1 id="stage-title">Live stage</h1>
+ <p class="stage-host">with <span id="stage-host-name">the host</span> · <span id="stage-aud-count">0 here</span></p>
+ </div>
+ <span id="stage-net-pill" class="stage-net-pill warn" hidden>…</span>
+ </div>
+ <div class="stage-overlay-bottom">
+ <button id="stage-sound" class="stage-sound" hidden>🔊 Tap for sound</button>
+ <div class="stage-dolly">
+ <button id="stage-farther" aria-label="Step back">−</button>
+ <span>proximity</span>
+ <button id="stage-closer" aria-label="Step closer">+</button>
+ </div>
+ </div>
+ <div id="stage-ticker" class="stage-ticker" aria-live="polite"></div>
+ <div id="stage-reactions" class="stage-reactions" role="group" aria-label="Reactions"></div>
+ </div>
+ </div>
+ <aside class="stage-side">
+ <section class="stage-panel">
+ <h2>Tip the host <span class="stage-coin">$THREE</span></h2>
+ <div id="stage-tip-presets" class="stage-tip-presets"></div>
+ <div class="stage-tip-row">
+ <input id="stage-tip-custom" type="number" min="1" step="1" placeholder="Custom" inputmode="numeric" aria-label="Custom tip amount" />
+ <button id="stage-tip-send" class="stage-tip-send">Tip</button>
+ </div>
+ <input id="stage-tip-msg" class="stage-tip-msg" maxlength="140" placeholder="Add a message (optional)" aria-label="Tip message" />
+ <p id="stage-tip-status" class="stage-tip-status" aria-live="polite"></p>
+ </section>
+ <section class="stage-panel">
+ <h2>Top tippers <span id="stage-total" class="stage-total"></span></h2>
+ <ol id="stage-leaderboard" class="stage-leaderboard"></ol>
+ </section>
+ <section class="stage-panel">
+ <h2>Ask the host</h2>
+ <div class="stage-ask-row">
+ <input id="stage-ask-input" maxlength="240" placeholder="Type a question…" aria-label="Ask the host a question" />
+ <button id="stage-ask-btn">Ask</button>
+ </div>
+ <p id="stage-ask-status" class="stage-ask-status" aria-live="polite"></p>
+ </section>
+ </aside>
+ </div>`;
+}
+
+function readSelfIdentity() {
+ let name = '';
+ let avatar = '';
+ try {
+ name = localStorage.getItem('threews:displayName') || localStorage.getItem('walk:name') || '';
+ avatar = localStorage.getItem('walk:avatar') || '';
+ } catch {}
+ return { name: name.slice(0, 40), avatar: avatar.slice(0, 512) };
+}
+
+function tipStageLabel(s) {
+ return {
+ connecting: 'Connecting your wallet…',
+ building: 'Building the transfer…',
+ signing: 'Approve in your wallet…',
+ sending: 'Sending on-chain…',
+ confirming: 'Confirming settlement…',
+ }[s] || 'Working…';
+}
+
+function nextShowLabel(ms) {
+ if (!ms) return '';
+ const d = new Date(ms);
+ if (d.getTime() < Date.now()) return '';
+ return `Next show ${d.toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' })}`;
+}
+
+function boundingSize(model) {
+ let minY = Infinity, maxY = -Infinity;
+ model.traverse((o) => {
+ if (o.isMesh && o.geometry) {
+ o.geometry.computeBoundingBox?.();
+ const b = o.geometry.boundingBox;
+ if (b) { minY = Math.min(minY, b.min.y); maxY = Math.max(maxY, b.max.y); }
+ }
+ });
+ return { height: Number.isFinite(maxY - minY) ? maxY - minY : 0 };
+}
+
+function findHead(model) {
+ let head = null;
+ model.traverse((o) => { if (!head && o.isBone && /head/i.test(o.name)) head = o; });
+ return head;
+}
+
+function disposeMesh(mesh) {
+ try { mesh.geometry?.dispose(); mesh.material?.dispose?.(); } catch {}
+}
+
+function hasWebGL() {
+ try {
+ const c = document.createElement('canvas');
+ return !!(c.getContext('webgl2') || c.getContext('webgl'));
+ } catch { return false; }
+}
+
+function skeletonCards(n) {
+ return Array.from({ length: n }, () => '<div class="stage-card stage-card-skel"><div class="stage-card-art"></div><div class="stage-card-body"><div class="sk-line"></div><div class="sk-line short"></div></div></div>').join('');
+}
+
+function emptyState(title, body, href, cta) {
+ return `<div class="stage-empty"><h2>${esc(title)}</h2><p>${esc(body)}</p>${href ? `<a class="stage-cta" href="${href}">${esc(cta)}</a>` : ''}</div>`;
+}
+
+function errorState(title, _retry) {
+ return `<div class="stage-empty stage-error"><h2>${esc(title)}</h2><p>Something went wrong loading this. Check your connection and try again.</p><button class="stage-cta" data-retry>Try again</button></div>`;
+}
+
+function wireRetry(container) {
+ container.querySelector('[data-retry]')?.addEventListener('click', () => location.reload());
+}
diff --git a/tests/api/world-lines.test.js b/tests/api/world-lines.test.js
new file mode 100644
index 000000000..3a2edda20
--- /dev/null
+++ b/tests/api/world-lines.test.js
@@ -0,0 +1,300 @@
+// End-to-end tests for the World Lines completion ceremony (api/irl/world-lines.js).
+//
+// Drives the real handler against an in-memory fake `sql` and a mocked agent signer,
+// exercising the anti-cheat surface the moonshot requires: challenge → complete →
+// independent verify, replay rejection (the same nonce/visitor never mints twice),
+// forged-nonce rejection, not-co-located rejection, and the completion cap. The
+// signing + nonce + co-location logic itself is REAL (only the DB and key recovery are
+// stubbed), so a regression in the cryptography fails these tests.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+// ── Agent signer: a fixed ed25519 keypair the handler "recovers" and signs with ──
+const AGENT_SEED = new Uint8Array(32).fill(7);
+const AGENT_PUB = bs58.encode(ed25519.getPublicKey(AGENT_SEED));
+const AGENT_SK = (() => {
+ const sk = new Uint8Array(64);
+ sk.set(AGENT_SEED, 0);
+ sk.set(ed25519.getPublicKey(AGENT_SEED), 32);
+ return sk;
+})();
+
+const PIN = { lat: 40.7484, lng: -73.9857 };
+const WL_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const PIN_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const AGENT_ID = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+// In-memory database the fake sql closes over. Reset before each test.
+let db;
+function resetDb(overrides = {}) {
+ db = {
+ worldLine: {
+ id: WL_ID, creator_user_id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd',
+ agent_id: AGENT_ID, signer_pubkey: AGENT_PUB, pin_id: PIN_ID,
+ coarse_cell: null, title: 'Find the lobby agent', prompt: 'Say hello',
+ challenge_spec: { kind: 'tap', prompt: 'Say hello' },
+ reward_kind: 'collectible', reward_ref: null, difficulty: 'easy',
+ max_completions: null, completion_count: 0, hidden_at: null, expires_at: null,
+ ...overrides,
+ },
+ pin: { ...PIN },
+ proofs: [],
+ proofSeq: 0,
+ };
+ // Derive the real coarse cell from the pin so nonce binding matches the handler.
+ const { coarseCell } = wlLib;
+ db.worldLine.coarse_cell = coarseCell(PIN.lat, PIN.lng);
+}
+
+let wlLib;
+
+// Fake Neon sql — pattern-matches the handler's queries against the template text.
+const fakeSql = vi.fn(async (strings, ...values) => {
+ const q = strings.join('§').replace(/\s+/g, ' ');
+ const has = (s) => q.includes(s);
+
+ if (has('CREATE TABLE') || has('CREATE INDEX') || has('CREATE UNIQUE INDEX')) return [];
+
+ // loadWorldLine
+ if (has('SELECT id, creator_user_id, agent_id, signer_pubkey, pin_id, coarse_cell')) {
+ return values[0] === db.worldLine.id && !db.worldLine.hidden_at ? [db.worldLine] : [];
+ }
+ // resolveColocation — pin coords
+ if (has('SELECT lat, lng FROM irl_pins WHERE id =')) {
+ return values[0] === db.worldLine.pin_id ? [db.pin] : [];
+ }
+ // challenge "already completed?" probe
+ if (has('SELECT id, collectible_mint FROM irl_presence_proofs')) {
+ const p = db.proofs.find((x) => x.world_line_id === values[0] && x.completer_hash === values[1]);
+ return p ? [{ id: p.id, collectible_mint: p.collectible_mint }] : [];
+ }
+ // complete "already / dupe" probe + verify-by-nonce probe
+ if (has('SELECT * FROM irl_presence_proofs WHERE world_line_id =')) {
+ const p = db.proofs.find((x) => x.world_line_id === values[0] && x.completer_hash === values[1]);
+ return p ? [p] : [];
+ }
+ if (has('SELECT * FROM irl_presence_proofs WHERE nonce_id =')) {
+ const p = db.proofs.find((x) => x.nonce_id === values[0]);
+ return p ? [p] : [];
+ }
+ // agent signing key
+ if (has('SELECT meta FROM agent_identities')) {
+ return [{ meta: { encrypted_solana_secret: 'ciphertext' } }];
+ }
+ // INSERT proof
+ if (has('INSERT INTO irl_presence_proofs')) {
+ const [world_line_id, agent_id, signer_pubkey, coarse_cell, nonce_id, completer_hash,
+ completer_user_id, completer_device, signature, signed_message, challenge_kind,
+ collectible_name, reward_kind] = values;
+ if (db.proofs.some((x) => x.nonce_id === nonce_id)) return []; // ON CONFLICT (nonce_id) DO NOTHING
+ if (db.proofs.some((x) => x.world_line_id === world_line_id && x.completer_hash === completer_hash)) {
+ throw Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' });
+ }
+ const row = {
+ id: `00000000-0000-4000-8000-00000000000${db.proofSeq++}`,
+ world_line_id, agent_id, signer_pubkey, coarse_cell, nonce_id, completer_hash,
+ completer_user_id, completer_device, signature, signed_message, challenge_kind,
+ collectible_name, reward_kind, collectible_mint: null, created_at: new Date().toISOString(),
+ };
+ db.proofs.push(row);
+ return [row];
+ }
+ if (has('UPDATE irl_presence_proofs SET collectible_mint')) {
+ const p = db.proofs.find((x) => x.id === values[1]);
+ if (p) p.collectible_mint = values[0];
+ return [];
+ }
+ if (has('UPDATE irl_world_lines SET completion_count')) {
+ if (db.worldLine.max_completions == null || db.worldLine.completion_count < db.worldLine.max_completions) {
+ db.worldLine.completion_count += 1;
+ }
+ return [];
+ }
+ // verify lookup (LEFT JOIN world line title)
+ if (has('SELECT pr.*, w.title FROM irl_presence_proofs pr')) {
+ const p = db.proofs.find((x) => x.id === values[0]);
+ return p ? [{ ...p, title: db.worldLine.title }] : [];
+ }
+ return [];
+});
+
+vi.mock('../../api/_lib/db.js', () => ({ sql: fakeSql }));
+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));
+vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: vi.fn() }));
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy({}, { get: () => async () => ({ success: true }) }),
+ clientIp: () => '1.2.3.4',
+}));
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ ensureAgentWallet: vi.fn(async () => ({ address: AGENT_PUB, created: false })),
+ recoverSolanaAgentKeypair: vi.fn(async () => ({ secretKey: AGENT_SK })),
+}));
+// getSessionUser → anonymous (device-token visitor). The signer is the agent, not the
+// caller, so completion needs no login.
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));
+
+const handler = (await import('../../api/irl/world-lines.js')).default;
+wlLib = await import('../../api/_lib/world-lines.js');
+
+function makeReq({ method, url, body, device = 'visitor-device-1' }) {
+ const json = body ? JSON.stringify(body) : '';
+ const stream = body ? Readable.from([Buffer.from(json, 'utf8')]) : Readable.from([]);
+ stream.method = method;
+ stream.url = url;
+ stream.query = {};
+ stream.socket = { remoteAddress: '1.2.3.4' };
+ stream.headers = {
+ 'content-type': 'application/json',
+ ...(device ? { 'x-irl-device': device } : {}),
+ };
+ return stream;
+}
+function makeRes() {
+ return {
+ statusCode: 0, _body: null, _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(b) { this._body = b ?? null; },
+ get headersSent() { return this._body !== null; },
+ get writableEnded() { return this._body !== null; },
+ };
+}
+async function call(reqOpts) {
+ const req = makeReq(reqOpts);
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res._body ? JSON.parse(res._body) : null };
+}
+
+async function getNonce(device = 'visitor-device-1', claim = PIN) {
+ const r = await call({
+ method: 'POST', url: '/api/irl/world-lines/challenge', device,
+ body: { world_line_id: WL_ID, lat: claim.lat, lng: claim.lng },
+ });
+ return r;
+}
+
+beforeEach(() => {
+ resetDb();
+ fakeSql.mockClear();
+});
+
+describe('challenge', () => {
+ it('issues a single-use nonce to a co-located visitor', async () => {
+ const r = await getNonce();
+ expect(r.status).toBe(200);
+ expect(typeof r.body.nonce).toBe('string');
+ expect(r.body.challenge.kind).toBe('tap');
+ });
+
+ it('refuses a visitor who is not co-located', async () => {
+ const r = await getNonce('visitor-device-1', { lat: 0, lng: 0 });
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('not_colocated');
+ });
+
+ it('reports capacity reached', async () => {
+ resetDb({ max_completions: 1, completion_count: 1 });
+ const r = await getNonce();
+ expect(r.status).toBe(409);
+ expect(r.body.error).toBe('capacity_reached');
+ });
+});
+
+describe('complete → verify → replay', () => {
+ it('mints an agent-signed proof that verifies independently, and rejects replay', async () => {
+ const { body: ch } = await getNonce();
+ const done = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch.nonce, lat: PIN.lat, lng: PIN.lng },
+ });
+ expect(done.status).toBe(201);
+ expect(done.body.ok).toBe(true);
+ expect(done.body.proof.signer_pubkey).toBe(AGENT_PUB);
+ expect(done.body.collectible.mint).toMatch(/^presence:/);
+ expect(db.proofs).toHaveLength(1);
+ expect(db.worldLine.completion_count).toBe(1);
+
+ // Independent verification re-checks the agent signature over the stored message.
+ const proofId = done.body.proof.id;
+ const v = await call({ method: 'GET', url: `/api/irl/world-lines/verify/${proofId}`, device: null });
+ expect(v.status).toBe(200);
+ expect(v.body.verified).toBe(true);
+ expect(v.body.proof.coarse_cell).toBe(db.worldLine.coarse_cell);
+ // The proof exposes nothing finer than the ~1.1 km cell — no lat/lng anywhere.
+ expect(JSON.stringify(v.body)).not.toContain(String(PIN.lat));
+
+ // Replay: the SAME nonce + visitor must not mint a second collectible.
+ const replay = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch.nonce, lat: PIN.lat, lng: PIN.lng },
+ });
+ expect(replay.status).toBe(200);
+ expect(replay.body.already_completed).toBe(true);
+ expect(db.proofs).toHaveLength(1);
+ expect(db.worldLine.completion_count).toBe(1);
+ });
+
+ it('rejects a forged / garbage nonce', async () => {
+ const r = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete', device: 'fresh-device',
+ body: { world_line_id: WL_ID, nonce: 'totally.forged', lat: PIN.lat, lng: PIN.lng },
+ });
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('invalid_nonce');
+ expect(db.proofs).toHaveLength(0);
+ });
+
+ it('rejects completion from a non-co-located point even with a valid nonce', async () => {
+ const { body: ch } = await getNonce();
+ const r = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch.nonce, lat: 0, lng: 0 },
+ });
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('not_colocated');
+ expect(db.proofs).toHaveLength(0);
+ });
+
+ it('refuses to mint once the completion cap is reached', async () => {
+ const { body: ch } = await getNonce();
+ db.worldLine.max_completions = 1;
+ db.worldLine.completion_count = 1; // someone else just filled the last slot
+ const r = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch.nonce, lat: PIN.lat, lng: PIN.lng },
+ });
+ expect(r.status).toBe(409);
+ expect(r.body.error).toBe('capacity_reached');
+ expect(db.proofs).toHaveLength(0);
+ });
+});
+
+describe('quiz challenge grading', () => {
+ it('rejects a wrong quiz answer and accepts the right one', async () => {
+ resetDb({ challenge_spec: { kind: 'quiz', question: 'Year?', choices: ['24', '25', '26'], answer: 2 } });
+ const { body: ch } = await getNonce();
+ const wrong = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch.nonce, lat: PIN.lat, lng: PIN.lng, answer: 0 },
+ });
+ expect(wrong.status).toBe(422);
+ expect(wrong.body.error).toBe('challenge_failed');
+ expect(db.proofs).toHaveLength(0);
+
+ const { body: ch2 } = await getNonce();
+ const right = await call({
+ method: 'POST', url: '/api/irl/world-lines/complete',
+ body: { world_line_id: WL_ID, nonce: ch2.nonce, lat: PIN.lat, lng: PIN.lng, answer: 2 },
+ });
+ expect(right.status).toBe(201);
+ expect(db.proofs).toHaveLength(1);
+ });
+});
diff --git a/tests/genome-breed.test.js b/tests/genome-breed.test.js
new file mode 100644
index 000000000..5e9daca9b
--- /dev/null
+++ b/tests/genome-breed.test.js
@@ -0,0 +1,202 @@
+// Agent Genome breeding endpoint — the security-critical invariants:
+// • ownership invariant: the child gets fresh wallets distinct from BOTH parents,
+// and neither parent row is mutated by a breed;
+// • idempotency: replaying a breeding key returns the same child, never twins;
+// • cooldown: a parent on cooldown can't be bred;
+// • cross-owner stud consent: a fee-bearing stud requires a $THREE settlement.
+//
+// DB + wallet + chain + storage are mocked at the module boundary so the test
+// pins the handler's decisions, not infrastructure.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { invoke } from './_helpers/monetization.js';
+
+const A_ID = '11111111-1111-4111-8111-111111111111';
+const B_ID = '22222222-2222-4222-8222-222222222222';
+const CALLER = 'user-caller';
+const OTHER = 'user-other';
+
+const state = {
+ session: { id: CALLER },
+ rows: {},
+ cooldown: { [A_ID]: 0, [B_ID]: 0 },
+ sqlQueue: [],
+ sqlCalls: [],
+ wallets: { evm: '0xCHILDevm', solana: 'ChildSolana1111' },
+};
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => state.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+ hasScope: vi.fn(() => true),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = vi.fn(async (strings, ...values) => {
+ const query = Array.isArray(strings) ? strings.join('?') : String(strings);
+ state.sqlCalls.push({ query, values });
+ return state.sqlQueue.length ? state.sqlQueue.shift() : [];
+ });
+ sql.transaction = (qs) => Promise.all(qs);
+ return { sql };
+});
+
+vi.mock('../api/_lib/agent-wallet.js', () => ({
+ provisionAgentWallets: vi.fn(async () => state.wallets),
+}));
+
+vi.mock('../api/_lib/avatars.js', () => ({
+ createAvatar: vi.fn(async () => ({ id: 'child-avatar' })),
+ storageKeyFor: vi.fn(() => 'u/caller/child/x.glb'),
+}));
+vi.mock('../api/_lib/r2.js', () => ({
+ copyObject: vi.fn(async () => true),
+ headObject: vi.fn(async () => ({ size: 1 })),
+}));
+vi.mock('../api/_lib/bake.js', () => ({ bakeAndUploadAppearance: vi.fn(async () => null) }));
+vi.mock('../api/_lib/webhook-dispatch.js', () => ({ dispatchWebhooks: vi.fn(async () => {}) }));
+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn(() => {}) }));
+vi.mock('../api/_lib/skill-license-onchain.js', () => ({
+ minterKeypair: vi.fn(() => null), // not configured in test → grants recorded as deferred
+ mintSkillLicenseOnchain: vi.fn(async () => ({ alreadyMinted: false, signature: 'sig' })),
+}));
+
+// Partial mock: keep the pure eligibility/genome logic real, override the two
+// DB-touching loaders.
+vi.mock('../api/_lib/genome-agent.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ loadBreedingAgent: vi.fn(async (id) => state.rows[id] || null),
+ cooldownRemainingMs: vi.fn(async (id) => state.cooldown[id] || 0),
+ };
+});
+
+const { default: breedHandler } = await import('../api/genome/breed.js');
+
+function parentRow(id, ownerId, over = {}) {
+ return {
+ id,
+ user_id: ownerId,
+ name: `Parent ${id.slice(0, 4)}`,
+ is_public: true,
+ meta: { solana_address: `Sol-${id}`, wallet_address: `0xevm-${id}`, ...(over.meta || {}) },
+ skills: over.skills || ['trading'],
+ persona_tone_tags: ['precise'],
+ voice_provider: 'elevenlabs',
+ voice_id: `voice-${id}`,
+ voice_model: 'eleven_flash_v2_5',
+ voice_settings: { stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true },
+ avatar_id: null,
+ avatar_storage_key: null,
+ avatar_appearance: { morphs: { headScale: 0.8 }, colors: { hair: '#aa3311' } },
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ state.session = { id: CALLER };
+ state.rows = { [A_ID]: parentRow(A_ID, CALLER), [B_ID]: parentRow(B_ID, CALLER) };
+ state.cooldown = { [A_ID]: 0, [B_ID]: 0 };
+ state.sqlQueue = [];
+ state.sqlCalls = [];
+ state.wallets = { evm: '0xCHILDevm', solana: 'ChildSolana1111' };
+});
+
+const breed = (body) =>
+ invoke(breedHandler, { method: 'POST', url: '/api/genome/breed', body: { parent_a: A_ID, parent_b: B_ID, ...body } });
+
+describe('happy path — a real child is born', () => {
+ it('mints a child with fresh wallets distinct from both parents', async () => {
+ // Queue: replay-check (none), child insert, skill-grant meta update, breeding insert.
+ state.sqlQueue = [[], [{ id: 'child-agent' }], [], []];
+ const { status, body } = await breed({ seed: 'deterministic-seed' });
+ expect(status).toBe(201);
+ expect(body.child.id).toBe('child-agent');
+ expect(body.child.solana_address).toBe('ChildSolana1111');
+ // Distinct from both parents.
+ expect(body.child.solana_address).not.toBe('Sol-' + A_ID);
+ expect(body.child.solana_address).not.toBe('Sol-' + B_ID);
+ expect(body.child.wallet_address).not.toBe('0xevm-' + A_ID);
+ expect(body.genome.generation).toBe(1);
+ expect(body.genome_hash).toMatch(/^[0-9a-f]{64}$/);
+ expect(body.seed).toBe('deterministic-seed');
+ });
+
+ it('never issues an UPDATE/DELETE against a parent agent row', async () => {
+ state.sqlQueue = [[], [{ id: 'child-agent' }], [], []];
+ await breed({ seed: 's' });
+ const mutatedParent = state.sqlCalls.some(
+ (c) => /update|delete/i.test(c.query) && (c.values.includes(A_ID) || c.values.includes(B_ID)),
+ );
+ expect(mutatedParent).toBe(false);
+ });
+
+ it('aborts if the child wallet collides with a parent (invariant breach)', async () => {
+ state.wallets = { evm: '0xevm-' + A_ID, solana: 'Sol-' + A_ID };
+ state.sqlQueue = [[], [{ id: 'child-agent' }], [], []];
+ const { status, body } = await breed({ seed: 's' });
+ expect(status).toBe(500);
+ expect(body.error).toBe('ownership_invariant_violation');
+ });
+});
+
+describe('idempotency', () => {
+ it('returns the existing child for a replayed breeding key', async () => {
+ // First sql call (replay check) finds an existing child; then loadChildSummary.
+ state.sqlQueue = [[{ child_agent_id: 'existing-child' }], [{ id: 'existing-child', name: 'Twinless', meta: {} }]];
+ const { status, body } = await breed({ seed: 'same' });
+ expect(status).toBe(200);
+ expect(body.deduped).toBe(true);
+ expect(body.child.id).toBe('existing-child');
+ });
+});
+
+describe('cooldown', () => {
+ it('refuses to breed a parent still on cooldown', async () => {
+ state.cooldown[A_ID] = 60 * 60 * 1000;
+ state.sqlQueue = [[]]; // replay check only — should bail before insert
+ const { status, body } = await breed({ seed: 's' });
+ expect(status).toBe(409);
+ expect(body.error).toBe('breeding_cooldown');
+ expect(body.cooldown_remaining_ms).toBeGreaterThan(0);
+ });
+});
+
+describe('cross-owner stud consent', () => {
+ it('402s when a fee-bearing stud has no $THREE settlement', async () => {
+ state.rows[B_ID] = parentRow(B_ID, OTHER, { meta: { genome_breeding: { stud: true, stud_fee_three: 25 }, solana_address: `Sol-${B_ID}` } });
+ state.sqlQueue = [[]];
+ const { status, body } = await breed({ seed: 's' });
+ expect(status).toBe(402);
+ expect(body.error).toBe('stud_fee_required');
+ expect(body.stud_fee_three).toBe(25);
+ expect(body.coin).toBe('$THREE');
+ });
+
+ it('403s when a non-owned parent is not listed as a stud', async () => {
+ state.rows[B_ID] = parentRow(B_ID, OTHER); // public but not a stud
+ state.sqlQueue = [[]];
+ const { status, body } = await breed({ seed: 's' });
+ expect(status).toBe(403);
+ expect(body.error).toBe('parent_ineligible');
+ });
+});
+
+describe('validation', () => {
+ it('rejects an agent breeding with itself', async () => {
+ const { status } = await invoke(breedHandler, {
+ method: 'POST',
+ url: '/api/genome/breed',
+ body: { parent_a: A_ID, parent_b: A_ID },
+ });
+ expect(status).toBe(400);
+ });
+});
diff --git a/tests/reasoning-ledger.test.js b/tests/reasoning-ledger.test.js
new file mode 100644
index 000000000..ef3ad32ff
--- /dev/null
+++ b/tests/reasoning-ledger.test.js
@@ -0,0 +1,295 @@
+/**
+ * The Reasoning Ledger — hash-chain integrity, tamper detection, calibration /
+ * scoring, and an end-to-end decide → reconcile → verify lifecycle.
+ *
+ * The pure layer (hash chain + reputation) is asserted directly with adversarial
+ * cases. The lifecycle test drives the real recordDecision / recordOutcome /
+ * verifyChain code paths against an in-memory `sql` so it runs with no database.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory stand-in for the agent_decisions / decision_outcomes tables. Hoisted
+// so the vi.mock factory (also hoisted) can close over it.
+const h = vi.hoisted(() => {
+ const store = { decisions: [], outcomes: [], idCounter: 0 };
+ const fakeSql = (strings, ...values) => {
+ const q = strings.join('?').toLowerCase();
+
+ if (q.includes('insert into agent_decisions')) {
+ const [agent_id, seq, kind, subject_ref, action_ref, inputs, rationale, prediction, confidence, network, decided_at, prev_hash, entry_hash] = values;
+ const seqClash = store.decisions.some((d) => d.agent_id === agent_id && d.seq === seq);
+ const idemClash = store.decisions.some((d) => d.agent_id === agent_id && d.kind === kind && d.subject_ref === subject_ref && d.action_ref === action_ref);
+ if (seqClash || idemClash) return Promise.resolve([]); // on conflict do nothing
+ const id = `dec-${++store.idCounter}`;
+ store.decisions.push({
+ id, agent_id, seq, kind, subject_ref, action_ref,
+ inputs: JSON.parse(inputs), rationale, prediction: JSON.parse(prediction),
+ confidence, network, decided_at, prev_hash, entry_hash,
+ });
+ return Promise.resolve([{ id, seq, entry_hash }]);
+ }
+ if (q.includes('insert into decision_outcomes')) {
+ const [decision_id, agent_id, observed, was_correct, pnl_sol, impact, status] = values;
+ if (store.outcomes.some((o) => o.decision_id === decision_id)) return Promise.resolve([]);
+ store.outcomes.push({ decision_id, agent_id, observed: JSON.parse(observed), was_correct, pnl_sol, impact, status, reconciled_at: new Date().toISOString() });
+ return Promise.resolve([{ decision_id }]);
+ }
+ // idempotency lookup
+ if (q.includes('select id, seq, entry_hash from agent_decisions') && q.includes('is not distinct')) {
+ const [agent_id, kind, subject_ref, action_ref] = values;
+ const f = store.decisions.find((d) => d.agent_id === agent_id && d.kind === kind && d.subject_ref === subject_ref && d.action_ref === action_ref);
+ return Promise.resolve(f ? [{ id: f.id, seq: f.seq, entry_hash: f.entry_hash }] : []);
+ }
+ // chain head
+ if (q.includes('select seq, entry_hash from agent_decisions') && q.includes('order by seq desc')) {
+ const [agent_id] = values;
+ const rows = store.decisions.filter((d) => d.agent_id === agent_id).sort((a, b) => b.seq - a.seq);
+ return Promise.resolve(rows.length ? [{ seq: rows[0].seq, entry_hash: rows[0].entry_hash }] : []);
+ }
+ // full chain
+ if (q.includes('from agent_decisions') && q.includes('order by seq asc')) {
+ const [agent_id] = values;
+ return Promise.resolve(store.decisions.filter((d) => d.agent_id === agent_id).sort((a, b) => a.seq - b.seq).map((d) => ({ ...d })));
+ }
+ // reputation records
+ if (q.includes('left join decision_outcomes o on o.decision_id = d.id') && q.includes('d.kind, d.confidence')) {
+ const [agent_id] = values;
+ return Promise.resolve(store.decisions.filter((d) => d.agent_id === agent_id).map((d) => {
+ const o = store.outcomes.find((x) => x.decision_id === d.id);
+ return { kind: d.kind, confidence: d.confidence, decided_at: d.decided_at, was_correct: o ? o.was_correct : null, pnl_sol: o ? o.pnl_sol : null };
+ }));
+ }
+ return Promise.resolve([]);
+ };
+ return { store, fakeSql };
+});
+
+vi.mock('../api/_lib/db.js', () => ({ sql: h.fakeSql, sqlValues: () => {} }));
+
+import {
+ genesisHash, canonicalizeEntry, computeEntryHash, buildChain, verifyChain,
+ computeReputation, calibrationBuckets, stableStringify,
+ recordDecision, recordOutcome, getChainEntries, getReputationRecords,
+} from '../api/_lib/reasoning-ledger.js';
+
+const AGENT = '11111111-1111-1111-1111-111111111111';
+
+function rawDecision(i, over = {}) {
+ return {
+ kind: 'snipe',
+ subject_ref: `mint-${i}`,
+ action_ref: `pos-${i}`,
+ inputs: { price_impact_pct: i, position_id: `pos-${i}` },
+ rationale: `decision number ${i}`,
+ prediction: { direction: 'up', basis: 'expects profit' },
+ confidence: 0.5,
+ network: 'mainnet',
+ decided_at: new Date(1_700_000_000_000 + i * 1000).toISOString(),
+ ...over,
+ };
+}
+
+describe('stableStringify', () => {
+ it('is key-order independent', () => {
+ expect(stableStringify({ b: 1, a: 2 })).toBe(stableStringify({ a: 2, b: 1 }));
+ });
+ it('handles nested objects and arrays deterministically', () => {
+ const a = stableStringify({ x: [{ q: 1, p: 2 }], y: null });
+ const b = stableStringify({ y: null, x: [{ p: 2, q: 1 }] });
+ expect(a).toBe(b);
+ });
+});
+
+describe('hash chain', () => {
+ it('links each entry to the previous (genesis at seq 1)', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2), rawDecision(3)]);
+ expect(chain).toHaveLength(3);
+ expect(chain[0].seq).toBe(1);
+ expect(chain[0].prev_hash).toBe(genesisHash(AGENT));
+ expect(chain[1].prev_hash).toBe(chain[0].entry_hash);
+ expect(chain[2].prev_hash).toBe(chain[1].entry_hash);
+ });
+
+ it('verifies a clean chain', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2)]);
+ const v = await verifyChain(AGENT, chain);
+ expect(v.ok).toBe(true);
+ expect(v.broken_at).toBeNull();
+ expect(v.head_hash).toBe(chain[1].entry_hash);
+ });
+
+ it('is deterministic — same inputs hash identically', async () => {
+ const a = await computeEntryHash(genesisHash(AGENT), { ...rawDecision(1), seq: 1, agent_id: AGENT });
+ const b = await computeEntryHash(genesisHash(AGENT), { ...rawDecision(1), seq: 1, agent_id: AGENT });
+ expect(a).toBe(b);
+ });
+
+ it('survives a jsonb round-trip (key reorder, number reformat)', async () => {
+ const e = { ...rawDecision(1), seq: 1, agent_id: AGENT };
+ const original = await computeEntryHash(genesisHash(AGENT), e);
+ // Simulate Postgres jsonb returning reordered keys + normalized numbers.
+ const roundTripped = {
+ ...e,
+ inputs: JSON.parse(JSON.stringify({ position_id: e.inputs.position_id, price_impact_pct: e.inputs.price_impact_pct })),
+ confidence: 0.5,
+ };
+ const after = await computeEntryHash(genesisHash(AGENT), roundTripped);
+ expect(after).toBe(original);
+ });
+});
+
+describe('tamper detection', () => {
+ it('detects an edited field at its seq', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2), rawDecision(3)]);
+ // Attacker rewrites the rationale of entry #2 but cannot recompute the rest.
+ chain[1] = { ...chain[1], rationale: 'a flattering lie' };
+ const v = await verifyChain(AGENT, chain);
+ expect(v.ok).toBe(false);
+ expect(v.broken_at).toBe(2);
+ expect(v.reason).toMatch(/altered|entry_hash/);
+ });
+
+ it('detects a broken prev_hash link', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2)]);
+ chain[1] = { ...chain[1], prev_hash: 'GENESIS:forged' };
+ const v = await verifyChain(AGENT, chain);
+ expect(v.ok).toBe(false);
+ expect(v.broken_at).toBe(2);
+ });
+
+ it('detects a sequence gap (a removed entry)', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2), rawDecision(3)]);
+ const withHole = [chain[0], chain[2]]; // entry #2 deleted
+ const v = await verifyChain(AGENT, withHole);
+ expect(v.ok).toBe(false);
+ expect(v.broken_at).toBe(2);
+ });
+
+ it('a full rewrite changes the head — no longer matches an anchor', async () => {
+ const chain = await buildChain(AGENT, [rawDecision(1), rawDecision(2)]);
+ const anchoredHead = chain[1].entry_hash; // committed on-chain earlier
+ // Attacker rewrites entry #1 and re-derives the whole chain consistently.
+ const rewritten = await buildChain(AGENT, [rawDecision(1, { rationale: 'rewritten history' }), rawDecision(2)]);
+ const v = await verifyChain(AGENT, rewritten);
+ expect(v.ok).toBe(true); // internally consistent…
+ expect(v.head_hash).not.toBe(anchoredHead); // …but the head betrays the edit
+ });
+});
+
+describe('calibration', () => {
+ it('buckets by confidence and computes ECE', () => {
+ const records = [
+ { confidence: 0.9, was_correct: true },
+ { confidence: 0.9, was_correct: true },
+ { confidence: 0.1, was_correct: false },
+ { confidence: 0.1, was_correct: false },
+ ];
+ const { ece, sample_size } = calibrationBuckets(records);
+ expect(sample_size).toBe(4);
+ // Perfectly calibrated extremes → near-zero error.
+ expect(ece).toBeLessThan(0.15);
+ });
+
+ it('flags an overconfident agent with a high ECE', () => {
+ const records = Array.from({ length: 10 }, () => ({ confidence: 0.9, was_correct: false }));
+ const { ece } = calibrationBuckets(records);
+ expect(ece).toBeGreaterThan(0.8);
+ });
+});
+
+describe('computeReputation', () => {
+ it('returns a neutral-ish score with no data', () => {
+ const r = computeReputation([]);
+ expect(r.sample_size).toBe(0);
+ expect(r.score).toBe(50); // pure regression to neutral
+ expect(r.components).toHaveLength(3);
+ });
+
+ it('counts losses — never hides them', () => {
+ const records = [
+ { kind: 'snipe', confidence: 0.6, was_correct: true, pnl_sol: 1 },
+ { kind: 'snipe', confidence: 0.6, was_correct: false, pnl_sol: -1 },
+ ];
+ const r = computeReputation(records);
+ expect(r.wins).toBe(1);
+ expect(r.losses).toBe(1);
+ expect(r.hit_rate).toBeCloseTo(0.5, 5);
+ });
+
+ it('rewards a calibrated, profitable, high-sample agent over a small one', () => {
+ const strong = Array.from({ length: 25 }, (_, i) => ({ kind: 'snipe', confidence: 0.75, was_correct: i % 4 !== 0, pnl_sol: i % 4 !== 0 ? 0.5 : -0.3 }));
+ const weak = [{ kind: 'snipe', confidence: 0.75, was_correct: true, pnl_sol: 0.5 }];
+ const rs = computeReputation(strong);
+ const rw = computeReputation(weak);
+ expect(rs.score).toBeGreaterThan(rw.score);
+ expect(rs.confidence).toBe(1);
+ expect(rw.confidence).toBeLessThan(1);
+ });
+
+ it('exposes its formula and traces every component', () => {
+ const r = computeReputation([{ kind: 'snipe', confidence: 0.6, was_correct: true, pnl_sol: 1 }]);
+ expect(r.formula).toContain('0.5·hit_rate');
+ const sum = r.components.reduce((a, c) => a + c.contribution, 0);
+ expect(sum).toBeCloseTo(r.raw_score, 3);
+ });
+
+ it('counts pending decisions but excludes them from the sample', () => {
+ const r = computeReputation([
+ { kind: 'snipe', confidence: 0.6, was_correct: true, pnl_sol: 1 },
+ { kind: 'snipe', confidence: 0.6, was_correct: null, pnl_sol: null },
+ ]);
+ expect(r.sample_size).toBe(1);
+ expect(r.pending_count).toBe(1);
+ expect(r.decisions_total).toBe(2);
+ });
+});
+
+describe('e2e: decide → reconcile → verify', () => {
+ beforeEach(() => {
+ h.store.decisions = [];
+ h.store.outcomes = [];
+ h.store.idCounter = 0;
+ });
+
+ it('records decisions, reconciles outcomes, and stays verifiable', async () => {
+ // DECIDE — three snipes captured to the chain.
+ const d1 = await recordDecision({ agentId: AGENT, ...rawDecision(1), subjectRef: 'mint-1', actionRef: 'pos-1', confidence: 0.8 });
+ const d2 = await recordDecision({ agentId: AGENT, ...rawDecision(2), subjectRef: 'mint-2', actionRef: 'pos-2', confidence: 0.8 });
+ const d3 = await recordDecision({ agentId: AGENT, ...rawDecision(3), subjectRef: 'mint-3', actionRef: 'pos-3', confidence: 0.2 });
+ expect([d1.seq, d2.seq, d3.seq]).toEqual([1, 2, 3]);
+ expect(d1.deduped).toBe(false);
+
+ // Idempotent capture — the same action fires twice → one row.
+ const dup = await recordDecision({ agentId: AGENT, ...rawDecision(1), subjectRef: 'mint-1', actionRef: 'pos-1' });
+ expect(dup.deduped).toBe(true);
+ expect(dup.seq).toBe(1);
+ expect(h.store.decisions).toHaveLength(3);
+
+ // RECONCILE — outcomes resolved against (simulated) on-chain P&L.
+ await recordOutcome({ decisionId: d1.id, agentId: AGENT, wasCorrect: true, pnlSol: 1.2, impact: 1.2, observed: { sell_sig: 'sig1' } });
+ await recordOutcome({ decisionId: d2.id, agentId: AGENT, wasCorrect: true, pnlSol: 0.4, impact: 0.4, observed: { sell_sig: 'sig2' } });
+ await recordOutcome({ decisionId: d3.id, agentId: AGENT, wasCorrect: false, pnlSol: -0.5, impact: -0.5, observed: { sell_sig: 'sig3' } });
+ // Reconciling again is a no-op (no double count).
+ const again = await recordOutcome({ decisionId: d1.id, agentId: AGENT, wasCorrect: true, pnlSol: 99 });
+ expect(again.reconciled).toBe(false);
+
+ const rep = computeReputation(await getReputationRecords(AGENT));
+ expect(rep.sample_size).toBe(3);
+ expect(rep.wins).toBe(2);
+ expect(rep.losses).toBe(1);
+ expect(rep.net_pnl_sol).toBeCloseTo(1.1, 5);
+
+ // VERIFY — recompute the persisted chain end to end.
+ const entries = await getChainEntries(AGENT);
+ const v = await verifyChain(AGENT, entries);
+ expect(v.ok).toBe(true);
+ expect(v.count).toBe(3);
+
+ // And a tamper on the persisted store is provably detected.
+ h.store.decisions[1].rationale = 'edited after the fact';
+ const tampered = await verifyChain(AGENT, await getChainEntries(AGENT));
+ expect(tampered.ok).toBe(false);
+ expect(tampered.broken_at).toBe(2);
+ });
+});
diff --git a/tests/referral-rewards.test.js b/tests/referral-rewards.test.js
new file mode 100644
index 000000000..ed7df28a2
--- /dev/null
+++ b/tests/referral-rewards.test.js
@@ -0,0 +1,138 @@
+/**
+ * Referral activation rewards + viral-funnel math — pure-helper unit tests.
+ *
+ * Covers the env-config parser (defaults, clamps, disable flag), the k-factor
+ * and conversion-rate formulas (the numbers the growth dashboard reports), and
+ * the privacy-preserving visitor hash (stable, code-sensitive, non-reversible).
+ * These gate real credit grants and the loop's headline metric, so they're
+ * pinned down without a database.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ parseRewardConfig,
+ computeKFactor,
+ conversionRate,
+ referralVisitorHash,
+} from '../api/_lib/referral-rewards.js';
+
+describe('parseRewardConfig', () => {
+ it('uses sane defaults for an empty env', () => {
+ const c = parseRewardConfig({});
+ expect(c.enabled).toBe(true);
+ expect(c.referredUsd).toBe(1.0);
+ expect(c.referrerUsd).toBe(2.0);
+ expect(c.monthlyCap).toBe(200);
+ });
+
+ it('reads overrides', () => {
+ const c = parseRewardConfig({
+ REFERRAL_REFERRED_REWARD_USD: '2.5',
+ REFERRAL_REFERRER_REWARD_USD: '5',
+ REFERRAL_ACTIVATION_MONTHLY_CAP: '50',
+ });
+ expect(c.referredUsd).toBe(2.5);
+ expect(c.referrerUsd).toBe(5);
+ expect(c.monthlyCap).toBe(50);
+ });
+
+ it('disables only on the explicit false flag', () => {
+ expect(parseRewardConfig({ REFERRAL_REWARDS_ENABLED: 'false' }).enabled).toBe(false);
+ expect(parseRewardConfig({ REFERRAL_REWARDS_ENABLED: 'FALSE' }).enabled).toBe(false);
+ expect(parseRewardConfig({ REFERRAL_REWARDS_ENABLED: 'true' }).enabled).toBe(true);
+ expect(parseRewardConfig({ REFERRAL_REWARDS_ENABLED: '' }).enabled).toBe(true);
+ });
+
+ it('falls back to the default for negative / garbage amounts', () => {
+ const c = parseRewardConfig({
+ REFERRAL_REFERRED_REWARD_USD: '-1',
+ REFERRAL_REFERRER_REWARD_USD: 'abc',
+ REFERRAL_ACTIVATION_MONTHLY_CAP: '-5',
+ });
+ expect(c.referredUsd).toBe(1.0);
+ expect(c.referrerUsd).toBe(2.0);
+ expect(c.monthlyCap).toBe(200);
+ });
+
+ it('clamps absurd amounts to the ceiling so a fat-fingered env cannot mint a fortune', () => {
+ const c = parseRewardConfig({
+ REFERRAL_REFERRED_REWARD_USD: '999999',
+ REFERRAL_REFERRER_REWARD_USD: '500',
+ });
+ expect(c.referredUsd).toBe(100);
+ expect(c.referrerUsd).toBe(100);
+ });
+
+ it('allows a zero reward (one side off)', () => {
+ const c = parseRewardConfig({ REFERRAL_REFERRED_REWARD_USD: '0' });
+ expect(c.referredUsd).toBe(0);
+ });
+});
+
+describe('computeKFactor', () => {
+ it('is signups per sharing user', () => {
+ expect(computeKFactor({ signups: 30, sharers: 10 })).toBe(3);
+ expect(computeKFactor({ signups: 5, sharers: 10 })).toBe(0.5);
+ });
+
+ it('is 0 when nobody shared (no divide-by-zero)', () => {
+ expect(computeKFactor({ signups: 10, sharers: 0 })).toBe(0);
+ expect(computeKFactor({ signups: 0, sharers: 0 })).toBe(0);
+ });
+
+ it('rounds to 3 decimals', () => {
+ expect(computeKFactor({ signups: 1, sharers: 3 })).toBe(0.333);
+ });
+
+ it('tolerates missing / non-numeric inputs', () => {
+ expect(computeKFactor({})).toBe(0);
+ expect(computeKFactor({ signups: 'x', sharers: 'y' })).toBe(0);
+ });
+});
+
+describe('conversionRate', () => {
+ it('is a 0..1 ratio rounded to 3 decimals', () => {
+ expect(conversionRate(50, 100)).toBe(0.5);
+ expect(conversionRate(1, 3)).toBe(0.333);
+ });
+
+ it('is 0 when the denominator is 0', () => {
+ expect(conversionRate(10, 0)).toBe(0);
+ expect(conversionRate(0, 0)).toBe(0);
+ });
+});
+
+describe('referralVisitorHash', () => {
+ it('is a 64-char hex sha256', () => {
+ const h = referralVisitorHash({ ip: '1.2.3.4', ua: 'Mozilla', code: 'ADA' });
+ expect(h).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('is stable for the same inputs (dedup works)', () => {
+ const a = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ADA' });
+ const b = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ADA' });
+ expect(a).toBe(b);
+ });
+
+ it('is case-insensitive on the code (matches canonical storage)', () => {
+ const a = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ada' });
+ const b = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ADA' });
+ expect(a).toBe(b);
+ });
+
+ it('differs by code so one visitor on two links counts twice', () => {
+ const a = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ADA' });
+ const b = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'BOB' });
+ expect(a).not.toBe(b);
+ });
+
+ it('differs by visitor (ip/ua) so two people on one link count twice', () => {
+ const a = referralVisitorHash({ ip: '1.2.3.4', ua: 'UA', code: 'ADA' });
+ const b = referralVisitorHash({ ip: '9.9.9.9', ua: 'UA', code: 'ADA' });
+ expect(a).not.toBe(b);
+ });
+
+ it('tolerates missing fields', () => {
+ expect(referralVisitorHash({ code: 'ADA' })).toMatch(/^[0-9a-f]{64}$/);
+ });
+});