Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add agent labor market, reasoning ledger, genome preview, living stages, and newsletter flows
nirholascb422833e611
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 40139e108..6effbe9b8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,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.+- **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]`- **Auto-rigging now keeps your original avatar — the rigged model is a separate, attested, reversible version** — When you upload or generate a static avatar, three.ws automatically rigs it so your agent can walk, wave, and emote. Until now that upgrade overwrote your uploaded model in place. It no longer does: the animation-ready result is saved as a brand-new model linked to your original as its parent, your agent is moved onto it automatically, and the original static avatar is preserved untouched. Each rigged model carries its own content hash, so on-chain glTF attestations and IPFS pins stay honest — nothing ever claims a signature or a pinned CID for bytes that quietly changed underneath it. A version trail records the upgrade so rigging is reversible, and if rigging ever fails you still own your original avatar, which animates through the built-in fallback skeleton. Only coin referenced is $THREE. `[improvement, fix]`diff --git a/api/_lib/agent-labor.js b/api/_lib/agent-labor.jsnew file mode 100644index 000000000..b189e336c--- /dev/null+++ b/api/_lib/agent-labor.js@@ -0,0 +1,635 @@+// The Agent Labor Market (Moonshot 01) — data layer + pure economics.+//+// This module is the single place that reads/writes the bounty → bid → job+// ledger (agent_bounties / agent_bids / agent_jobs / agent_labor_policies) and+// the ONLY home for the market's pure math: the transparent award score and the+// exact-integer settlement split. Money never moves here — the endpoints+// (api/labor/*) reserve spend, hold escrow on-chain, and release it. This module+// records the business-level lifecycle so every stat the UI shows is a real+// aggregate over real bounties, and so the autonomy engine and tests can reuse+// 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)));+}++// ── Lazy schema (self-heals if the formal migration hasn't run) ─────────────++let _ensured = null;+export async function ensureLaborTables() {+ if (_ensured) return _ensured;+ _ensured = (async () => {+ await sql`+ create table if not exists agent_bounties (+ id uuid primary key default gen_random_uuid(),+ poster_agent_id uuid not null, poster_user_id uuid not null,+ title text not null, spec text not null, required_skill text,+ reward_atomics numeric(40,0) not null, reward_mint text not null,+ status text not null default 'open', deadline timestamptz,+ escrow_address text, escrow_fund_sig text, refund_sig text,+ awarded_bid_id uuid, awarded_agent_id uuid, awarded_at timestamptz, award_rationale text,+ auto boolean not null default false, meta jsonb not null default '{}',+ created_at timestamptz not null default now(), updated_at timestamptz not null default now()+ )`;+ await sql`create index if not exists agent_bounties_feed on agent_bounties (status, created_at desc)`;+ await sql`create index if not exists agent_bounties_skill_open on agent_bounties (required_skill) where status = 'open'`;+ await sql`create index if not exists agent_bounties_poster on agent_bounties (poster_agent_id, created_at desc)`;+ await sql`+ create table if not exists agent_bids (+ id uuid primary key default gen_random_uuid(),+ bounty_id uuid not null, worker_agent_id uuid not null, worker_user_id uuid not null,+ price_atomics numeric(40,0) not null, eta_seconds integer, pitch text,+ score double precision, rationale text, reputation double precision,+ auto boolean not null default false, status text not null default 'pending',+ created_at timestamptz not null default now(), updated_at timestamptz not null default now(),+ constraint agent_bids_unique_worker unique (bounty_id, worker_agent_id)+ )`;+ await sql`create index if not exists agent_bids_bounty on agent_bids (bounty_id, created_at desc)`;+ await sql`create index if not exists agent_bids_worker on agent_bids (worker_agent_id, created_at desc)`;+ await sql`+ create table if not exists agent_jobs (+ id uuid primary key default gen_random_uuid(),+ bounty_id uuid not null, bid_id uuid not null,+ worker_agent_id uuid not null, worker_user_id uuid not null, poster_agent_id uuid not null,+ required_skill text, price_atomics numeric(40,0) not null,+ status text not null default 'working', deliverable jsonb, delivered_at timestamptz,+ verdict jsonb, verified_at timestamptz,+ invocation_sig text, settlement_sig text, royalty_sig text,+ royalty_atomics numeric(40,0), worker_payout_atomics numeric(40,0), royalty_author_id uuid,+ settle_key text, settled_at timestamptz, refund_sig text, failure_reason text,+ meta jsonb not null default '{}',+ created_at timestamptz not null default now(), updated_at timestamptz not null default now(),+ constraint agent_jobs_bounty_unique unique (bounty_id)+ )`;+ await sql`create index if not exists agent_jobs_worker on agent_jobs (worker_agent_id, status)`;+ await sql`create index if not exists agent_jobs_poster on agent_jobs (poster_agent_id, created_at desc)`;+ await sql`create unique index if not exists agent_jobs_settle_key on agent_jobs (settle_key) where settle_key is not null`;+ await sql`create index if not exists agent_jobs_settled_at on agent_jobs (settled_at desc) where status = 'settled'`;+ await sql`+ create table if not exists agent_labor_policies (+ agent_id uuid primary key, user_id uuid not null,+ worker_enabled boolean not null default false, skills text[] not null default '{}',+ max_bid_atomics numeric(40,0), min_reward_atomics numeric(40,0),+ poster_enabled boolean not null default false, auto_award boolean not null default false,+ min_bids integer not null default 1,+ meta jsonb not null default '{}',+ created_at timestamptz not null default now(), updated_at timestamptz not null default now()+ )`;+ await sql`create index if not exists agent_labor_policies_worker on agent_labor_policies (worker_enabled) where worker_enabled = true`;+ return true;+ })().catch((err) => {+ console.error('[agent-labor] ensureLaborTables failed:', err?.message);+ _ensured = null;+ return false;+ });+ return _ensured;+}++// ── Bounty writes/reads ─────────────────────────────────────────────────────++export async function createBounty(input) {+ await ensureLaborTables();+ const {+ posterAgentId, posterUserId, title, spec, requiredSkill = null,+ rewardAtomics, deadline = null, auto = false, meta = {},+ } = input;+ const [row] = await sql`+ INSERT INTO agent_bounties+ (poster_agent_id, poster_user_id, title, spec, required_skill,+ reward_atomics, reward_mint, status, deadline, auto, meta)+ VALUES (${posterAgentId}, ${posterUserId}, ${title}, ${spec}, ${requiredSkill},+ ${String(toBig(rewardAtomics))}, ${TOKEN_MINT}, 'open',+ ${deadline}, ${!!auto}, ${JSON.stringify(meta || {})}::jsonb)+ RETURNING *`;+ return row;+}++export async function getBounty(id) {+ const [row] = await sql`SELECT * FROM agent_bounties WHERE id = ${id} LIMIT 1`;+ return row || null;+}++export async function setBountyEscrow(id, { escrowAddress, escrowFundSig }) {+ const [row] = await sql`+ UPDATE agent_bounties+ SET escrow_address = ${escrowAddress}, escrow_fund_sig = ${escrowFundSig}, updated_at = now()+ WHERE id = ${id} RETURNING *`;+ return row || null;+}++export async function setBountyStatus(id, status, patch = {}) {+ const [row] = await sql`+ UPDATE agent_bounties+ SET status = ${status},+ awarded_bid_id = COALESCE(${patch.awardedBidId ?? null}, awarded_bid_id),+ awarded_agent_id = COALESCE(${patch.awardedAgentId ?? null}, awarded_agent_id),+ awarded_at = COALESCE(${patch.awardedAt ?? null}::timestamptz, awarded_at),+ award_rationale = COALESCE(${patch.awardRationale ?? null}, award_rationale),+ refund_sig = COALESCE(${patch.refundSig ?? null}, refund_sig),+ updated_at = now()+ WHERE id = ${id} RETURNING *`;+ return row || null;+}++export async function listOpenBounties({ limit = 50, requiredSkill = null, minRewardAtomics = null } = {}) {+ await ensureLaborTables();+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));+ const skillFilter = requiredSkill ? sql`AND b.required_skill = ${requiredSkill}` : sql``;+ const rewardFilter = minRewardAtomics+ ? sql`AND b.reward_atomics >= ${String(toBig(minRewardAtomics))}`+ : sql``;+ const rows = await sql`+ SELECT b.*, pa.name AS poster_name,+ (SELECT COUNT(*) FROM agent_bids bd WHERE bd.bounty_id = b.id AND bd.status != 'withdrawn') AS bid_count+ FROM agent_bounties b+ LEFT JOIN agent_identities pa ON pa.id = b.poster_agent_id+ WHERE b.status = 'open' ${skillFilter} ${rewardFilter}+ ORDER BY b.created_at DESC+ LIMIT ${lim}`;+ return rows.map(shapeBounty);+}++export async function listBountiesForAgent(agentId, { limit = 40 } = {}) {+ await ensureLaborTables();+ const lim = Math.min(200, Math.max(1, Number(limit) || 40));+ const rows = await sql`+ SELECT b.*, pa.name AS poster_name,+ (SELECT COUNT(*) FROM agent_bids bd WHERE bd.bounty_id = b.id AND bd.status != 'withdrawn') AS bid_count+ FROM agent_bounties b+ LEFT JOIN agent_identities pa ON pa.id = b.poster_agent_id+ WHERE b.poster_agent_id = ${agentId}+ ORDER BY b.created_at DESC LIMIT ${lim}`;+ return rows.map(shapeBounty);+}++// ── Bids ────────────────────────────────────────────────────────────────────++/** Upsert a worker's bid (one per bounty); returns the row. */+export async function upsertBid(input) {+ await ensureLaborTables();+ const {+ bountyId, workerAgentId, workerUserId, priceAtomics, etaSeconds = null,+ pitch = null, score = null, rationale = null, reputation = null, auto = false,+ } = input;+ const [row] = await sql`+ INSERT INTO agent_bids+ (bounty_id, worker_agent_id, worker_user_id, price_atomics, eta_seconds,+ pitch, score, rationale, reputation, auto, status)+ VALUES (${bountyId}, ${workerAgentId}, ${workerUserId}, ${String(toBig(priceAtomics))},+ ${etaSeconds}, ${pitch}, ${score}, ${rationale}, ${reputation}, ${!!auto}, 'pending')+ ON CONFLICT (bounty_id, worker_agent_id) DO UPDATE SET+ price_atomics = EXCLUDED.price_atomics, eta_seconds = EXCLUDED.eta_seconds,+ pitch = EXCLUDED.pitch, score = EXCLUDED.score, rationale = EXCLUDED.rationale,+ reputation = EXCLUDED.reputation, auto = EXCLUDED.auto, status = 'pending', updated_at = now()+ RETURNING *`;+ return row;+}++export async function getBid(id) {+ const [row] = await sql`SELECT * FROM agent_bids WHERE id = ${id} LIMIT 1`;+ return row || null;+}++export async function listBidsForBounty(bountyId) {+ const rows = await sql`+ SELECT bd.*, wa.name AS worker_name+ FROM agent_bids bd+ LEFT JOIN agent_identities wa ON wa.id = bd.worker_agent_id+ WHERE bd.bounty_id = ${bountyId} AND bd.status != 'withdrawn'+ ORDER BY bd.score DESC NULLS LAST, bd.created_at ASC`;+ return rows.map(shapeBid);+}++export async function rejectOtherBids(bountyId, winningBidId) {+ await sql`+ UPDATE agent_bids SET status = 'rejected', updated_at = now()+ WHERE bounty_id = ${bountyId} AND id != ${winningBidId} AND status = 'pending'`;+}++export async function markBidAwarded(bidId) {+ await sql`UPDATE agent_bids SET status = 'awarded', updated_at = now() WHERE id = ${bidId}`;+}++// ── Jobs ────────────────────────────────────────────────────────────────────++export async function createJob(input) {+ await ensureLaborTables();+ const { bountyId, bidId, workerAgentId, workerUserId, posterAgentId, requiredSkill = null, priceAtomics } = input;+ const [row] = await sql`+ INSERT INTO agent_jobs+ (bounty_id, bid_id, worker_agent_id, worker_user_id, poster_agent_id, required_skill, price_atomics, status)+ VALUES (${bountyId}, ${bidId}, ${workerAgentId}, ${workerUserId}, ${posterAgentId},+ ${requiredSkill}, ${String(toBig(priceAtomics))}, 'working')+ ON CONFLICT (bounty_id) DO NOTHING+ RETURNING *`;+ return row || (await getJobByBounty(bountyId));+}++export async function getJob(id) {+ const [row] = await sql`SELECT * FROM agent_jobs WHERE id = ${id} LIMIT 1`;+ return row || null;+}+export async function getJobByBounty(bountyId) {+ const [row] = await sql`SELECT * FROM agent_jobs WHERE bounty_id = ${bountyId} LIMIT 1`;+ return row || null;+}++export async function markJobDelivered(id, deliverable) {+ const [row] = await sql`+ UPDATE agent_jobs SET status = 'delivered', deliverable = ${JSON.stringify(deliverable ?? {})}::jsonb,+ delivered_at = now(), updated_at = now()+ WHERE id = ${id} AND status = 'working' RETURNING *`;+ return row || null;+}++export async function markJobVerifying(id) {+ const [row] = await sql`+ UPDATE agent_jobs SET status = 'verifying', updated_at = now()+ WHERE id = ${id} AND status = 'delivered' RETURNING *`;+ return row || null;+}++export async function recordVerdict(id, verdict) {+ const [row] = await sql`+ UPDATE agent_jobs SET verdict = ${JSON.stringify(verdict ?? {})}::jsonb, verified_at = now(), updated_at = now()+ WHERE id = ${id} RETURNING *`;+ return row || null;+}++/** Claim the settle for a job idempotently. Returns the row if THIS caller won the+ * claim (settle_key was unset), or null if another settle already owns it. */+export async function claimSettle(id, settleKey) {+ const [row] = await sql`+ UPDATE agent_jobs SET settle_key = ${settleKey}, status = 'verifying', updated_at = now()+ WHERE id = ${id} AND settle_key IS NULL AND status IN ('delivered','verifying')+ RETURNING *`;+ return row || null;+}++export async function markJobSettled(id, patch) {+ const [row] = await sql`+ UPDATE agent_jobs SET status = 'settled',+ settlement_sig = ${patch.settlementSig ?? null},+ royalty_sig = ${patch.royaltySig ?? null},+ invocation_sig = ${patch.invocationSig ?? null},+ royalty_atomics = ${patch.royaltyAtomics != null ? String(patch.royaltyAtomics) : null},+ worker_payout_atomics = ${patch.workerPayoutAtomics != null ? String(patch.workerPayoutAtomics) : null},+ royalty_author_id = ${patch.royaltyAuthorId ?? null},+ refund_sig = COALESCE(${patch.refundSig ?? null}, refund_sig),+ settled_at = now(), updated_at = now()+ WHERE id = ${id} RETURNING *`;+ return row || null;+}++export async function markJobFailed(id, { reason, refundSig = null, status = 'failed' }) {+ const [row] = await sql`+ UPDATE agent_jobs SET status = ${status}, failure_reason = ${reason || null},+ refund_sig = COALESCE(${refundSig}, refund_sig),+ settle_key = NULL, updated_at = now()+ WHERE id = ${id} RETURNING *`;+ return row || null;+}++export async function listInflightJobs({ limit = 30 } = {}) {+ const lim = Math.min(100, Math.max(1, Number(limit) || 30));+ const rows = await sql`+ SELECT j.*, b.title, b.reward_atomics, wa.name AS worker_name, pa.name AS poster_name+ FROM agent_jobs j+ JOIN agent_bounties b ON b.id = j.bounty_id+ LEFT JOIN agent_identities wa ON wa.id = j.worker_agent_id+ LEFT JOIN agent_identities pa ON pa.id = j.poster_agent_id+ WHERE j.status IN ('working','delivered','verifying')+ ORDER BY j.created_at DESC LIMIT ${lim}`;+ return rows.map(shapeJob);+}++export async function recentSettlements({ limit = 20 } = {}) {+ await ensureLaborTables();+ const lim = Math.min(100, Math.max(1, Number(limit) || 20));+ const rows = await sql`+ SELECT j.id, j.bounty_id, j.worker_agent_id, j.poster_agent_id, j.required_skill,+ j.worker_payout_atomics, j.royalty_atomics, j.price_atomics, j.settlement_sig,+ j.royalty_sig, j.invocation_sig, j.settled_at, b.title,+ wa.name AS worker_name, pa.name AS poster_name+ FROM agent_jobs j+ JOIN agent_bounties b ON b.id = j.bounty_id+ LEFT JOIN agent_identities wa ON wa.id = j.worker_agent_id+ LEFT JOIN agent_identities pa ON pa.id = j.poster_agent_id+ WHERE j.status = 'settled'+ ORDER BY j.settled_at DESC LIMIT ${lim}`;+ return rows.map(shapeSettlement);+}++// ── Reputation + per-agent stats ────────────────────────────────────────────++export async function workerReputation(agentId) {+ await ensureLaborTables();+ const [row] = await sql`+ SELECT+ COUNT(*) FILTER (WHERE status = 'settled') AS settled,+ COUNT(*) FILTER (WHERE status IN ('failed')) AS failed,+ COALESCE(SUM(worker_payout_atomics) FILTER (WHERE status = 'settled'), 0) AS earned+ FROM agent_jobs WHERE worker_agent_id = ${agentId}`;+ const settled = Number(row?.settled || 0);+ const failed = Number(row?.failed || 0);+ return {+ reputation: reputationFromStats({ settled, failed }),+ settled, failed,+ earned_atomics: String(toBig(row?.earned || 0)),+ };+}++export async function agentLaborStats(agentId) {+ await ensureLaborTables();+ const [posted] = await sql`+ SELECT COUNT(*) AS n, COUNT(*) FILTER (WHERE status = 'settled') AS settled+ FROM agent_bounties WHERE poster_agent_id = ${agentId}`;+ const [work] = await sql`+ SELECT+ COUNT(*) FILTER (WHERE status = 'settled') AS jobs_done,+ COUNT(*) FILTER (WHERE status = 'failed') AS jobs_failed,+ COUNT(*) FILTER (WHERE status IN ('working','delivered','verifying')) AS jobs_active,+ COALESCE(SUM(worker_payout_atomics) FILTER (WHERE status = 'settled'), 0) AS earned,+ COALESCE(SUM(royalty_atomics) FILTER (WHERE status = 'settled' AND royalty_author_id = ${agentId}), 0) AS royalties+ FROM agent_jobs WHERE worker_agent_id = ${agentId}`;+ const [spent] = await sql`+ SELECT COALESCE(SUM(price_atomics) FILTER (WHERE status = 'settled'), 0) AS spent+ FROM agent_jobs WHERE poster_agent_id = ${agentId}`;+ const settled = Number(work?.jobs_done || 0);+ const failed = Number(work?.jobs_failed || 0);+ return {+ bounties_posted: Number(posted?.n || 0),+ bounties_settled: Number(posted?.settled || 0),+ jobs_done: settled,+ jobs_failed: failed,+ jobs_active: Number(work?.jobs_active || 0),+ earned_atomics: String(toBig(work?.earned || 0)),+ earned_three: atomicsToThree(work?.earned || 0),+ royalties_atomics: String(toBig(work?.royalties || 0)),+ spent_atomics: String(toBig(spent?.spent || 0)),+ spent_three: atomicsToThree(spent?.spent || 0),+ reputation: reputationFromStats({ settled, failed }),+ };+}++/** Total $THREE moved through the market, settled, for the live ticker header. */+export async function marketTotals() {+ await ensureLaborTables();+ const [row] = await sql`+ SELECT+ COUNT(*) FILTER (WHERE status = 'settled') AS settled_jobs,+ COALESCE(SUM(price_atomics) FILTER (WHERE status = 'settled'), 0) AS volume,+ (SELECT COUNT(*) FROM agent_bounties WHERE status = 'open') AS open_bounties+ FROM agent_jobs`;+ return {+ settled_jobs: Number(row?.settled_jobs || 0),+ volume_atomics: String(toBig(row?.volume || 0)),+ volume_three: atomicsToThree(row?.volume || 0),+ open_bounties: Number(row?.open_bounties || 0),+ };+}++// ── Labor policies (autonomy opt-in) ────────────────────────────────────────++export async function getLaborPolicy(agentId) {+ await ensureLaborTables();+ const [row] = await sql`SELECT * FROM agent_labor_policies WHERE agent_id = ${agentId} LIMIT 1`;+ return row ? shapePolicy(row) : null;+}++export async function upsertLaborPolicy(agentId, userId, patch) {+ await ensureLaborTables();+ const skills = Array.isArray(patch.skills) ? patch.skills.filter((s) => typeof s === 'string').slice(0, 40) : [];+ const [row] = await sql`+ INSERT INTO agent_labor_policies+ (agent_id, user_id, worker_enabled, skills, max_bid_atomics, min_reward_atomics,+ poster_enabled, auto_award, min_bids, meta)+ VALUES (${agentId}, ${userId}, ${!!patch.workerEnabled}, ${skills},+ ${patch.maxBidAtomics != null ? String(toBig(patch.maxBidAtomics)) : null},+ ${patch.minRewardAtomics != null ? String(toBig(patch.minRewardAtomics)) : null},+ ${!!patch.posterEnabled}, ${!!patch.autoAward}, ${Math.max(1, Number(patch.minBids) || 1)},+ ${JSON.stringify(patch.meta || {})}::jsonb)+ ON CONFLICT (agent_id) DO UPDATE SET+ worker_enabled = EXCLUDED.worker_enabled, skills = EXCLUDED.skills,+ max_bid_atomics = EXCLUDED.max_bid_atomics, min_reward_atomics = EXCLUDED.min_reward_atomics,+ poster_enabled = EXCLUDED.poster_enabled, auto_award = EXCLUDED.auto_award,+ min_bids = EXCLUDED.min_bids, meta = EXCLUDED.meta, updated_at = now()+ RETURNING *`;+ return shapePolicy(row);+}++/** Worker agents whose autonomous policy matches a bounty's skill + reward floor. */+export async function findAutoBidders({ requiredSkill, rewardAtomics, excludeAgentId }) {+ await ensureLaborTables();+ const reward = String(toBig(rewardAtomics));+ const rows = await sql`+ SELECT p.*, ai.name AS agent_name, ai.user_id AS owner_user_id,+ ai.meta->>'solana_address' AS solana_address+ FROM agent_labor_policies p+ JOIN agent_identities ai ON ai.id = p.agent_id AND ai.deleted_at IS NULL+ WHERE p.worker_enabled = true+ AND p.agent_id != ${excludeAgentId}+ AND (p.min_reward_atomics IS NULL OR p.min_reward_atomics <= ${reward})+ AND (${requiredSkill}::text IS NULL OR ${requiredSkill} = ANY(p.skills))+ LIMIT 25`;+ return rows;+}++// ── Shaping ─────────────────────────────────────────────────────────────────++function shapeBounty(r) {+ return {+ id: r.id,+ poster_agent_id: r.poster_agent_id,+ poster_name: r.poster_name || 'Agent',+ title: r.title,+ spec: r.spec,+ required_skill: r.required_skill || null,+ reward_atomics: String(toBig(r.reward_atomics)),+ reward_three: atomicsToThree(r.reward_atomics),+ reward_mint: r.reward_mint,+ status: r.status,+ deadline: r.deadline || null,+ escrow_address: r.escrow_address || null,+ escrow_fund_sig: r.escrow_fund_sig || null,+ escrow_explorer: r.escrow_fund_sig ? `https://solscan.io/tx/${r.escrow_fund_sig}` : null,+ awarded_agent_id: r.awarded_agent_id || null,+ award_rationale: r.award_rationale || null,+ auto: !!r.auto,+ bid_count: Number(r.bid_count || 0),+ created_at: r.created_at,+ };+}++function shapeBid(r) {+ return {+ id: r.id,+ bounty_id: r.bounty_id,+ worker_agent_id: r.worker_agent_id,+ worker_user_id: r.worker_user_id,+ worker_name: r.worker_name || 'Agent',+ price_atomics: String(toBig(r.price_atomics)),+ price_three: atomicsToThree(r.price_atomics),+ eta_seconds: r.eta_seconds != null ? Number(r.eta_seconds) : null,+ pitch: r.pitch || null,+ score: r.score != null ? Number(r.score) : null,+ rationale: r.rationale || null,+ reputation: r.reputation != null ? Number(r.reputation) : null,+ auto: !!r.auto,+ status: r.status,+ created_at: r.created_at,+ };+}++function shapeJob(r) {+ return {+ id: r.id,+ bounty_id: r.bounty_id,+ title: r.title || null,+ worker_agent_id: r.worker_agent_id,+ worker_name: r.worker_name || 'Agent',+ poster_agent_id: r.poster_agent_id,+ poster_name: r.poster_name || 'Agent',+ required_skill: r.required_skill || null,+ price_atomics: String(toBig(r.price_atomics)),+ price_three: atomicsToThree(r.price_atomics),+ reward_three: r.reward_atomics != null ? atomicsToThree(r.reward_atomics) : null,+ status: r.status,+ deliverable: r.deliverable || null,+ verdict: r.verdict || null,+ delivered_at: r.delivered_at || null,+ created_at: r.created_at,+ };+}++function shapeSettlement(r) {+ return {+ id: r.id,+ bounty_id: r.bounty_id,+ title: r.title || null,+ worker_agent_id: r.worker_agent_id,+ worker_name: r.worker_name || 'Agent',+ poster_agent_id: r.poster_agent_id,+ poster_name: r.poster_name || 'Agent',+ required_skill: r.required_skill || null,+ worker_payout_atomics: String(toBig(r.worker_payout_atomics || r.price_atomics)),+ worker_payout_three: atomicsToThree(r.worker_payout_atomics || r.price_atomics),+ royalty_atomics: String(toBig(r.royalty_atomics || 0)),+ royalty_three: atomicsToThree(r.royalty_atomics || 0),+ settlement_sig: r.settlement_sig || null,+ settlement_explorer: r.settlement_sig ? `https://solscan.io/tx/${r.settlement_sig}` : null,+ royalty_sig: r.royalty_sig || null,+ invocation_sig: r.invocation_sig || null,+ invocation_explorer: r.invocation_sig ? `https://solscan.io/tx/${r.invocation_sig}` : null,+ settled_at: r.settled_at,+ };+}++function shapePolicy(r) {+ return {+ agent_id: r.agent_id,+ worker_enabled: !!r.worker_enabled,+ skills: Array.isArray(r.skills) ? r.skills : [],+ max_bid_atomics: r.max_bid_atomics != null ? String(toBig(r.max_bid_atomics)) : null,+ max_bid_three: r.max_bid_atomics != null ? atomicsToThree(r.max_bid_atomics) : null,+ min_reward_atomics: r.min_reward_atomics != null ? String(toBig(r.min_reward_atomics)) : null,+ min_reward_three: r.min_reward_atomics != null ? atomicsToThree(r.min_reward_atomics) : null,+ poster_enabled: !!r.poster_enabled,+ auto_award: !!r.auto_award,+ min_bids: Number(r.min_bids || 1),+ updated_at: r.updated_at,+ };+}++export { toBig as _toBig, shapeBounty as _shapeBounty };diff --git a/api/_lib/email.js b/api/_lib/email.jsindex 0c515dd8f..ae368e75b 100644--- a/api/_lib/email.js+++ b/api/_lib/email.js@@ -142,6 +142,41 @@ export function sendReferralCommissionEmail({ to, amount, currency, fromHandle,return sendEmail({ to, ...renderReferralCommission({ amount, currency, fromHandle, skillName, date }) });}+// Double opt-in newsletter confirmation. Minimal localization (prompt 38) so a+// subscriber confirms in their own language; unknown locales fall back to en.+const NEWSLETTER_I18N = {+ en: { subject: 'Confirm your three.ws subscription', heading: 'Confirm your subscription', body: 'Tap below to confirm you want updates from three.ws — new features, launches, and changelog highlights.', cta: 'Confirm subscription', foot: "If you didn't request this, you can ignore this email." },+ es: { subject: 'Confirma tu suscripción a three.ws', heading: 'Confirma tu suscripción', body: 'Toca abajo para confirmar que quieres novedades de three.ws — nuevas funciones, lanzamientos y cambios destacados.', cta: 'Confirmar suscripción', foot: 'Si no lo solicitaste, puedes ignorar este correo.' },+ fr: { subject: 'Confirmez votre abonnement three.ws', heading: 'Confirmez votre abonnement', body: 'Appuyez ci-dessous pour confirmer que vous souhaitez recevoir les actualités de three.ws — nouvelles fonctionnalités, lancements et nouveautés.', cta: "Confirmer l'abonnement", foot: "Si vous n'êtes pas à l'origine de cette demande, ignorez cet e-mail." },+ pt: { subject: 'Confirme a sua inscrição na three.ws', heading: 'Confirme a sua inscrição', body: 'Toque abaixo para confirmar que deseja novidades da three.ws — novos recursos, lançamentos e destaques.', cta: 'Confirmar inscrição', foot: 'Se não foi você, pode ignorar este e-mail.' },+ de: { subject: 'Bestätige dein three.ws-Abo', heading: 'Abo bestätigen', body: 'Tippe unten, um zu bestätigen, dass du Updates von three.ws erhalten möchtest — neue Funktionen, Launches und Changelog-Highlights.', cta: 'Abo bestätigen', foot: 'Falls du das nicht angefordert hast, ignoriere diese E-Mail.' },+};++function newsletterCopy(locale) {+ const lang = String(locale || 'en').slice(0, 2).toLowerCase();+ return NEWSLETTER_I18N[lang] || NEWSLETTER_I18N.en;+}++export function renderNewsletterConfirm({ confirmUrl, locale }) {+ const t = newsletterCopy(locale);+ return {+ subject: t.subject,+ html: layout(t.subject, `+ <p class="brand">three.ws</p>+ <h1>${esc(t.heading)}</h1>+ <p>${esc(t.body)}</p>+ <a class="btn" href="${esc(confirmUrl)}">${esc(t.cta)}</a>+ <hr>+ <p class="muted">${esc(t.foot)}</p>+ `),+ text: `${t.heading}\n\n${t.body}\n\n${confirmUrl}\n\n${t.foot}`,+ };+}++export function sendNewsletterConfirmEmail({ to, confirmUrl, locale }) {+ return sendEmail({ to, ...renderNewsletterConfirm({ confirmUrl, locale }) });+}+// ─── HTML helpers ─────────────────────────────────────────────────────────────function layout(title, body) {diff --git a/api/_lib/genome-agent.js b/api/_lib/genome-agent.jsnew file mode 100644index 000000000..de79fa4d8--- /dev/null+++ b/api/_lib/genome-agent.js@@ -0,0 +1,132 @@+// Genome ⇆ agent glue. Loads the heritable slice of an agent (the fields+// api/_lib/genome.js reads), resolves an agent's genome (stored or founder-derived),+// and centralizes the breeding-eligibility + cooldown + stud-consent rules so the+// preview, breed, and lineage endpoints agree on one source of truth.++import { sql } from './db.js';+import {+ genomeFromAgent,+ normalizeGenome,+ GENOME_VERSION,+ pedigreeScore,+ voiceSettings,+ appearanceFromGenome,+ composePersonaPrompt,+ expressedSkills,+} from './genome.js';++// Client-safe projection of a genome — everything needed to render the predicted+// offspring (traits, voice settings + voice_id for a real TTS sample, bakeable+// appearance, skill alleles, mutations, pedigree). Carries no secret; a genome+// never holds one.+export function publicGenome(genome, name = 'Offspring') {+ const g = normalizeGenome(genome);+ return {+ version: g.version,+ generation: g.generation,+ brain: g.brain,+ voice: {+ provider: g.voice.provider,+ voice_id: g.voice.voice_id,+ model: g.voice.model,+ pitch: g.voice.pitch,+ settings: voiceSettings(g),+ },+ appearance: appearanceFromGenome(g),+ skills: g.skills,+ expressed_skills: expressedSkills(g),+ mutations: g.mutations,+ persona_prompt: composePersonaPrompt(g, name),+ pedigree: pedigreeScore(g),+ };+}++// A parent can breed at most once per cooldown window — keeps deep pedigrees+// scarce and blocks spam-minting offspring. Per agent, regardless of who breeds it.+export const BREED_COOLDOWN_MS = 6 * 60 * 60 * 1000; // 6 hours++// Load every column genome derivation needs, joined to the backing avatar so we+// have its GLB storage key + appearance for body synthesis.+export async function loadBreedingAgent(agentId) {+ const [row] = await sql`+ select i.id, i.user_id, i.name, i.meta, i.skills, i.is_public,+ i.persona_prompt, i.persona_tone_tags,+ i.voice_provider, i.voice_id, i.voice_model, i.voice_settings,+ i.avatar_id,+ a.storage_key as avatar_storage_key,+ a.appearance as avatar_appearance,+ a.visibility as avatar_visibility,+ a.name as avatar_name+ from agent_identities i+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where i.id = ${agentId} and i.deleted_at is null+ limit 1+ `;+ return row || null;+}++// Shape a DB row into the object genomeFromAgent() consumes. A stored genome on+// meta.genome wins; otherwise a stable founder genome is derived from real traits.+export function agentGenome(row) {+ const meta = row.meta || {};+ if (meta.genome && meta.genome.version === GENOME_VERSION) return normalizeGenome(meta.genome);+ return genomeFromAgent({+ id: row.id,+ meta,+ persona_tone_tags: row.persona_tone_tags || meta.persona_tone_tags || [],+ voice_provider: row.voice_provider,+ voice_id: row.voice_id,+ voice_model: row.voice_model,+ voice_settings: row.voice_settings,+ appearance: row.avatar_appearance || meta.appearance || {},+ skills: row.skills || [],+ avatar_id: row.avatar_id,+ });+}++// The owner-set breeding policy for an agent (defaults: own-use breedable, not a+// public stud, no fee). Lives on meta.genome_breeding.+export function breedingPolicy(row) {+ const p = (row.meta || {}).genome_breeding || {};+ return {+ breedable: p.breedable !== false,+ stud: p.stud === true,+ stud_fee_three: Math.max(0, Number(p.stud_fee_three) || 0),+ };+}++// Can `callerUserId` use `row` as a breeding parent?+// • own agent (breedable) → free, allowed+// • someone else's public stud → allowed, may carry a $THREE stud fee+// • anything else → denied+// Returns { allowed, reason, fee_three, cross_owner, owner_id }.+export function eligibilityFor(row, callerUserId) {+ const policy = breedingPolicy(row);+ const owned = row.user_id === callerUserId;+ if (owned) {+ if (!policy.breedable) return { allowed: false, reason: 'parent_not_breedable' };+ return { allowed: true, fee_three: 0, cross_owner: false, owner_id: row.user_id };+ }+ if (!row.is_public) return { allowed: false, reason: 'parent_private' };+ if (!policy.stud) return { allowed: false, reason: 'parent_not_listed_as_stud' };+ return { allowed: true, fee_three: policy.stud_fee_three, cross_owner: true, owner_id: row.user_id };+}++// Most-recent breeding timestamp for an agent as either parent. Null if never.+export async function lastBredAt(agentId) {+ const [row] = await sql`+ select max(created_at) as last+ from genome_breedings+ where (parent_a_agent_id = ${agentId} or parent_b_agent_id = ${agentId})+ and status <> 'failed'+ `;+ return row?.last ? new Date(row.last) : null;+}++// Cooldown check against an injected `now` (testable, no Date.now in genome core).+export async function cooldownRemainingMs(agentId, now = Date.now()) {+ const last = await lastBredAt(agentId);+ if (!last) return 0;+ const remaining = BREED_COOLDOWN_MS - (now - last.getTime());+ return remaining > 0 ? remaining : 0;+}diff --git a/api/_lib/genome.js b/api/_lib/genome.jsnew file mode 100644index 000000000..c54dabe31--- /dev/null+++ b/api/_lib/genome.js@@ -0,0 +1,578 @@+// Agent Genome — deterministic, seed-recorded, verifiable trait inheritance.+//+// This module is the provable heart of agent breeding. Given two parent genomes+// and a recorded seed it derives a child genome that is a bounded recombination+// of both parents — brain disposition, voice parameters, body/visual traits, and+// skill alleles — with every random choice drawn from the seed. The same+// (parentA, parentB, seed) ALWAYS produces a byte-identical child genome, so a+// breeding event is re-derivable and a forged "child" is detectable+// (`verifyGenome`). No randomness ever enters without flowing through the seed.+//+// Pure functions only — no DB, no network, no `Date.now()`. The breeding endpoint+// (api/genome/breed.js) wraps this with wallet provisioning, artifact synthesis+// (real TTS voice settings, baked GLB, persona prompt), on-chain skill grants, and+// lineage persistence. Keeping the genetics pure makes the invariants testable and+// the pedigree auditable.++import { createHash } from 'node:crypto';++export const GENOME_VERSION = 1;++// ── Deterministic PRNG ───────────────────────────────────────────────────────+// xmur3 string hash → mulberry32 stream. Each genetic locus draws from its OWN+// stream keyed by `${seed}::${locus}`, so loci are independent and order-free:+// adding a new locus never perturbs the draws of existing ones, which keeps old+// genomes verifiable as the schema grows.++function xmur3(str) {+ let h = 1779033703 ^ str.length;+ for (let i = 0; i < str.length; i++) {+ h = Math.imul(h ^ str.charCodeAt(i), 3432918353);+ h = (h << 13) | (h >>> 19);+ }+ return () => {+ h = Math.imul(h ^ (h >>> 16), 2246822507);+ h = Math.imul(h ^ (h >>> 13), 3266489909);+ return (h ^= h >>> 16) >>> 0;+ };+}++function mulberry32(a) {+ return () => {+ a |= 0;+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++// A reproducible draw in [0,1) for a (seed, locus) pair. Pull `n` to get the+// nth independent draw on the same locus stream.+export function draw(seed, locus, n = 0) {+ const seeded = mulberry32(xmur3(`${seed}::${locus}`)());+ let v = 0;+ for (let i = 0; i <= n; i++) v = seeded();+ return v;+}++// ── Tunable inheritance constants (the rules the feature rests on) ───────────++// Bounded mutation: a child trait may drift at most this far (in 0..1 space) from+// the parental blend. Pinned by tests so "mutation" can never silently become+// "random new agent". A drift larger than MUTATION_RECORD_THRESHOLD is logged in+// genome.mutations so every novelty is auditable.+export const MUTATION_MAX = 0.12;+export const MUTATION_RECORD_THRESHOLD = 0.04;++// Heterozygous expression: when only ONE parent expresses a skill, the child+// expresses it with this probability, else carries it recessively (unexpressed,+// but heritable — it can surface in a grandchild). Deep pedigrees therefore carry+// latent variety that only rarely expresses, which is what makes them scarce.+export const HETERO_EXPRESS_P = 0.72;++// Emergent skills: trait fusion that produces a skill NEITHER parent expressed.+// Auditable rule — both ingredient alleles must be carried by the child (from+// either parent, expressed or recessive) and the dice keyed on the emergent name+// must pass. Static table = no hidden behaviour.+export const FUSION_RULES = [+ { a: 'trading', b: 'sentiment', emergent: 'alpha-signal' },+ { a: 'memory', b: 'research', emergent: 'deep-recall' },+ { a: 'voice', b: 'performance', emergent: 'showmanship' },+ { a: 'vision', b: 'forge', emergent: 'concept-art' },+ { a: 'defi', b: 'risk', emergent: 'portfolio-guardian' },+];+export const FUSION_EXPRESS_P = 0.5;++const BRAIN_LOCI = ['temperature', 'verbosity', 'curiosity', 'formality', 'humor', 'boldness'];+const VOICE_NUM_LOCI = ['stability', 'similarity_boost', 'style'];++const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x);+const round3 = (x) => Math.round(x * 1000) / 1000;++// ── Founder genome: make ANY agent breedable ─────────────────────────────────+// An agent that has never been bred has no genome. We derive a stable "founder"+// genome from its real, owned traits (persona tone tags, voice settings,+// appearance, skills). Unknown numeric dispositions are filled deterministically+// from the agent's id so each founder has a distinctive-but-fixed nature. This is+// pure: the same agent record always yields the same founder genome.++export function genomeFromAgent(agent) {+ if (agent?.genome && agent.genome.version === GENOME_VERSION) return normalizeGenome(agent.genome);+ const id = String(agent?.id || agent?.agent_id || 'founder');+ const meta = agent?.meta || {};+ if (meta.genome && meta.genome.version === GENOME_VERSION) return normalizeGenome(meta.genome);++ const brain = {};+ for (const locus of BRAIN_LOCI) brain[locus] = round3(draw(id, `founder:brain:${locus}`));++ const vs = agent.voice_settings || meta.voice_settings || {};+ const voice = {+ provider: agent.voice_provider || meta.voice_provider || 'browser',+ voice_id: agent.voice_id || meta.voice_id || null,+ model: agent.voice_model || meta.voice_model || null,+ stability: numOr(vs.stability, () => round3(draw(id, 'founder:voice:stability'))),+ similarity_boost: numOr(vs.similarity_boost, () => round3(draw(id, 'founder:voice:sim'))),+ style: numOr(vs.style, () => round3(draw(id, 'founder:voice:style'))),+ use_speaker_boost: typeof vs.use_speaker_boost === 'boolean' ? vs.use_speaker_boost : true,+ pitch: round3((draw(id, 'founder:voice:pitch') - 0.5) * 0.4),+ };++ const appearance = (agent.appearance || meta.appearance || {}) || {};+ const body = {+ base_avatar_id: agent.avatar_id || meta.avatar_id || null,+ morphs: sanitizeMorphs(appearance.morphs),+ colors: sanitizeColors(appearance.colors),+ accessories: dedupeStrings(appearance.accessories),+ outfit: typeof appearance.outfit === 'string' ? appearance.outfit : null,+ hidden: dedupeStrings(appearance.hidden),+ };++ const toneTags = dedupeStrings(agent.persona_tone_tags || meta.persona_tone_tags || []);+ const skillNames = dedupeStrings(agent.skills || meta.skills || []);+ const skills = skillNames.map((skill) => ({ skill, source: id, expressed: true, dominant: true, depth: 0 }));++ return normalizeGenome({+ version: GENOME_VERSION,+ founder: id,+ generation: 0,+ brain: { ...brain, tone_tags: toneTags, archetype: meta.archetype || pickArchetype(toneTags, id) },+ voice,+ body,+ skills,+ mutations: [],+ });+}++function numOr(v, fallback) {+ return typeof v === 'number' && Number.isFinite(v) ? clamp01(v) : fallback();+}++function pickArchetype(tags, id) {+ const ARCH = ['analyst', 'trickster', 'sage', 'maverick', 'diplomat', 'builder'];+ if (tags.length) return tags[0];+ return ARCH[Math.floor(draw(id, 'founder:archetype') * ARCH.length)];+}++// ── Core: derive a child genome from two parents + a seed ────────────────────+// Parents are canonicalized (sorted by founder/id) so A×B and B×A yield the same+// child — lineage and verification are independent of who initiated the breed.++export function deriveGenome({ parentA, parentB, seed }) {+ if (!seed || typeof seed !== 'string') throw new Error('deriveGenome: a string seed is required');+ const gA0 = normalizeGenome(parentA);+ const gB0 = normalizeGenome(parentB);+ // Canonical order — smaller key is "A".+ const [gA, gB] = [gA0, gB0].sort((x, y) => keyOf(x).localeCompare(keyOf(y)));++ const mutations = [];+ const generation = Math.max(gA.generation || 0, gB.generation || 0) + 1;++ // Brain numeric loci: parental blend + bounded mutation.+ const brain = {};+ for (const locus of BRAIN_LOCI) {+ const w = draw(seed, `brain:w:${locus}`); // blend weight toward A+ const blend = gA.brain[locus] * w + gB.brain[locus] * (1 - w);+ const mut = (draw(seed, `brain:mut:${locus}`) - 0.5) * 2 * MUTATION_MAX;+ const value = round3(clamp01(blend + mut));+ brain[locus] = value;+ if (Math.abs(value - blend) >= MUTATION_RECORD_THRESHOLD) {+ mutations.push({ locus: `brain.${locus}`, blend: round3(blend), value, delta: round3(value - blend) });+ }+ }+ // Tone tags: union, each tag expressed by a seeded coin (dominant if both carry it).+ brain.tone_tags = inheritSet(gA.brain.tone_tags, gB.brain.tone_tags, seed, 'tone');+ // Archetype: dominant pick from one parent.+ brain.archetype = draw(seed, 'brain:archetype') < 0.5 ? gA.brain.archetype : gB.brain.archetype;++ // Voice: numeric blend + mutation; dominant voice_id from the parent that has a real cloned/eleven voice.+ const voiceDomA = draw(seed, 'voice:dominant') < voiceWeight(gA, gB);+ const dom = voiceDomA ? gA.voice : gB.voice;+ const rec = voiceDomA ? gB.voice : gA.voice;+ const voice = {+ provider: dom.provider || rec.provider || 'browser',+ voice_id: dom.voice_id || rec.voice_id || null,+ model: dom.model || rec.model || null,+ use_speaker_boost: draw(seed, 'voice:boost') < 0.5 ? gA.voice.use_speaker_boost : gB.voice.use_speaker_boost,+ };+ for (const locus of VOICE_NUM_LOCI) {+ const w = draw(seed, `voice:w:${locus}`);+ const blend = gA.voice[locus] * w + gB.voice[locus] * (1 - w);+ const mut = (draw(seed, `voice:mut:${locus}`) - 0.5) * 2 * MUTATION_MAX;+ const value = round3(clamp01(blend + mut));+ voice[locus] = value;+ if (Math.abs(value - blend) >= MUTATION_RECORD_THRESHOLD) {+ mutations.push({ locus: `voice.${locus}`, blend: round3(blend), value, delta: round3(value - blend) });+ }+ }+ // Pitch: blend in [-0.2,0.2], small mutation.+ {+ const w = draw(seed, 'voice:w:pitch');+ const blend = gA.voice.pitch * w + gB.voice.pitch * (1 - w);+ const mut = (draw(seed, 'voice:mut:pitch') - 0.5) * 2 * (MUTATION_MAX * 0.4);+ voice.pitch = round3(Math.max(-0.3, Math.min(0.3, blend + mut)));+ }++ // Body: dominant base GLB, blended morphs/colors, unioned accessories/hidden.+ const bodyDomA = draw(seed, 'body:dominant') < 0.5;+ const body = {+ base_avatar_id: (bodyDomA ? gA.body.base_avatar_id : gB.body.base_avatar_id) || gA.body.base_avatar_id || gB.body.base_avatar_id || null,+ outfit: (bodyDomA ? gA.body.outfit : gB.body.outfit) || gA.body.outfit || gB.body.outfit || null,+ morphs: blendMorphs(gA.body.morphs, gB.body.morphs, seed),+ colors: blendColors(gA.body.colors, gB.body.colors, seed),+ accessories: inheritSet(gA.body.accessories, gB.body.accessories, seed, 'acc'),+ hidden: inheritSet(gA.body.hidden, gB.body.hidden, seed, 'hidden'),+ };++ // Skills: allele recombination with dominance + recessive carry + emergent fusion.+ const skills = inheritSkills(gA.skills, gB.skills, seed, generation);++ const child = normalizeGenome({+ version: GENOME_VERSION,+ generation,+ brain,+ voice,+ body,+ skills,+ mutations,+ parents: [keyOf(gA), keyOf(gB)],+ seed,+ });+ child.genome_hash = hashGenome(child);+ return child;+}++// Re-derive the child from recorded inputs and confirm it matches — the+// anti-forgery check. A "child" whose stored genome doesn't equal the+// deterministic derivation from its recorded parents + seed is detectable.+export function verifyGenome(childGenome, { parentA, parentB, seed }) {+ try {+ const rederived = deriveGenome({ parentA, parentB, seed });+ const expected = hashGenome(rederived);+ // Recompute over the PRESENTED content — never trust the child's stored+ // genome_hash field, which a forger would have rewritten to match a tampered+ // trait. hashGenome excludes that field, so any altered locus changes `actual`.+ const actual = hashGenome(childGenome);+ if (expected !== actual) return { valid: false, reason: 'hash_mismatch', expected, actual };+ return { valid: true, hash: expected, genome: rederived };+ } catch (e) {+ return { valid: false, reason: e?.message || 'derivation_failed' };+ }+}++// Canonical SHA-256 over the heritable content (excludes the hash field itself+// and the volatile `seed`, which is recorded separately as provenance).+export function hashGenome(genome) {+ const g = normalizeGenome(genome);+ const canonical = canonicalize({+ version: g.version,+ generation: g.generation,+ brain: g.brain,+ voice: g.voice,+ body: g.body,+ skills: g.skills,+ mutations: g.mutations,+ parents: g.parents || null,+ });+ return createHash('sha256').update(canonical).digest('hex');+}++// Deterministic JSON: object keys sorted recursively so the hash is stable+// regardless of insertion order.+function canonicalize(value) {+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;+ if (value && typeof value === 'object') {+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;+ }+ return JSON.stringify(value);+}++// ── Inheritance helpers ──────────────────────────────────────────────────────++// Union of two string sets; an element present in BOTH is dominant (always+// expressed), present in ONE is expressed by a seeded coin. Returns the expressed+// set, sorted for determinism.+function inheritSet(a, b, seed, ns) {+ const A = new Set(dedupeStrings(a));+ const B = new Set(dedupeStrings(b));+ const out = [];+ for (const el of new Set([...A, ...B])) {+ const both = A.has(el) && B.has(el);+ if (both || draw(seed, `${ns}:${el}`) < HETERO_EXPRESS_P) out.push(el);+ }+ return out.sort();+}++function blendMorphs(a, b, seed) {+ const A = sanitizeMorphs(a);+ const B = sanitizeMorphs(b);+ const out = {};+ for (const key of new Set([...Object.keys(A), ...Object.keys(B)])) {+ const va = key in A ? A[key] : (key in B ? B[key] : 0);+ const vb = key in B ? B[key] : (key in A ? A[key] : 0);+ const w = draw(seed, `morph:${key}`);+ const mut = (draw(seed, `morph:mut:${key}`) - 0.5) * 2 * MUTATION_MAX;+ out[key] = round3(clamp01(va * w + vb * (1 - w) + mut));+ }+ return out;+}++function blendColors(a, b, seed) {+ const A = sanitizeColors(a);+ const B = sanitizeColors(b);+ const out = {};+ for (const slot of new Set([...Object.keys(A), ...Object.keys(B)])) {+ const ca = hexToRgb(A[slot] || B[slot]);+ const cb = hexToRgb(B[slot] || A[slot]);+ const w = draw(seed, `color:${slot}`);+ out[slot] = rgbToHex({+ r: Math.round(ca.r * w + cb.r * (1 - w)),+ g: Math.round(ca.g * w + cb.g * (1 - w)),+ b: Math.round(ca.b * w + cb.b * (1 - w)),+ });+ }+ return out;+}++// Allele recombination. Each parent contributes its full allele set (expressed ++// recessive carried). For each skill:+// • expressed by both → expressed, dominant+// • expressed by one → expressed w.p. HETERO_EXPRESS_P, else recessive+// • carried (recessive) by one → carried recessively+// • recessive in both → expressed (recessive pairing surfaces it!)+// Then apply emergent fusion rules. Every allele records its source + depth so the+// pedigree is fully auditable.+function inheritSkills(a, b, seed, generation) {+ const bySkill = new Map();+ const add = (allele, parent) => {+ const cur = bySkill.get(allele.skill) || { skill: allele.skill, fromA: false, fromB: false, expA: false, expB: false, depth: allele.depth || 0 };+ if (parent === 'A') { cur.fromA = true; cur.expA = !!allele.expressed; }+ else { cur.fromB = true; cur.expB = !!allele.expressed; }+ cur.depth = Math.max(cur.depth, allele.depth || 0);+ bySkill.set(allele.skill, cur);+ };+ for (const al of a || []) add(al, 'A');+ for (const al of b || []) add(al, 'B');++ const out = [];+ const carried = new Set();+ for (const [skill, st] of bySkill) {+ let expressed;+ let dominant = false;+ if (st.expA && st.expB) { expressed = true; dominant = true; }+ else if (st.expA || st.expB) { expressed = draw(seed, `skill:${skill}`) < HETERO_EXPRESS_P; }+ else { expressed = true; } // recessive-in-both pairing surfaces the trait+ const source = st.fromA && st.fromB ? 'both' : st.fromA ? 'A' : 'B';+ out.push({ skill, expressed, dominant, recessive: !expressed, source, depth: (st.depth || 0) + 1 });+ carried.add(skill);+ }++ // Emergent fusion: a skill NEITHER parent expressed, born from carrying both+ // ingredients. Deterministic and auditable.+ for (const rule of FUSION_RULES) {+ if (carried.has(rule.a) && carried.has(rule.b) && !carried.has(rule.emergent)) {+ if (draw(seed, `fusion:${rule.emergent}`) < FUSION_EXPRESS_P) {+ out.push({ skill: rule.emergent, expressed: true, dominant: false, recessive: false, source: 'emergent', emergent_from: [rule.a, rule.b], depth: 1 });+ }+ }+ }+ return out.sort((x, y) => x.skill.localeCompare(y.skill));+}++// A parent with a real ElevenLabs/cloned voice is more likely to pass its voice_id+// to the child — a label-only "browser" voice rarely dominates a real one.+function voiceWeight(gA, gB) {+ const real = (v) => (v.provider === 'elevenlabs' || v.voice_id ? 1 : 0);+ const ra = real(gA.voice);+ const rb = real(gB.voice);+ if (ra === rb) return 0.5;+ return ra > rb ? 0.8 : 0.2;+}++// ── Pedigree scoring (drives the rare-pedigree badge + scarcity) ─────────────++export function pedigreeScore(genome) {+ const g = normalizeGenome(genome);+ const expressedSkills = g.skills.filter((s) => s.expressed);+ const emergent = g.skills.filter((s) => s.source === 'emergent' && s.expressed).length;+ const recessive = g.skills.filter((s) => s.recessive).length;+ const generation = g.generation || 0;+ // Weighted: depth matters most, then emergent novelty + latent recessive variety.+ const score = generation * 10 + emergent * 8 + recessive * 2 + expressedSkills.length + g.mutations.length;+ let tier = 'common';+ if (score >= 60 || generation >= 4) tier = 'legendary';+ else if (score >= 35 || emergent >= 1) tier = 'rare';+ else if (score >= 18 || generation >= 2) tier = 'uncommon';+ return { score, tier, generation, emergent, recessive, expressed_skills: expressedSkills.length, mutations: g.mutations.length };+}++// ── Artifact projection (deterministic; consumed by the breed endpoint) ──────++// Compose a real, in-character system prompt from the child's heritable brain.+// Deterministic so the persona is itself part of the verifiable derivation.+export function composePersonaPrompt(genome, name = 'this agent') {+ const g = normalizeGenome(genome);+ const b = g.brain;+ const lvl = (x) => (x >= 0.66 ? 'high' : x >= 0.33 ? 'balanced' : 'low');+ const parts = [+ `You are ${name}, a bred AI agent with an inherited disposition. Stay in character.`,+ `Archetype: ${b.archetype}.`,+ `Temperament — curiosity: ${lvl(b.curiosity)}, boldness: ${lvl(b.boldness)}, humor: ${lvl(b.humor)}, formality: ${lvl(b.formality)}.`,+ `Verbosity: ${lvl(b.verbosity)} — ${b.verbosity >= 0.66 ? 'expand with detail and context' : b.verbosity <= 0.33 ? 'be terse and to the point' : 'be clear and moderately detailed'}.`,+ ];+ if (b.tone_tags.length) parts.push(`Voice and vocabulary lean: ${b.tone_tags.join(', ')}.`);+ const skills = g.skills.filter((s) => s.expressed).map((s) => s.skill);+ if (skills.length) parts.push(`Inherited competencies you can draw on: ${skills.join(', ')}.`);+ const emergent = g.skills.filter((s) => s.source === 'emergent' && s.expressed).map((s) => s.skill);+ if (emergent.length) parts.push(`Emergent talent neither parent had: ${emergent.join(', ')}.`);+ return parts.join('\n');+}++// Real ElevenLabs voice settings the child carries — passed verbatim to+// api/tts/eleven so the inherited voice is genuinely synthesized, not labelled.+export function voiceSettings(genome) {+ const v = normalizeGenome(genome).voice;+ return {+ stability: round3(clamp01(v.stability)),+ similarity_boost: round3(clamp01(v.similarity_boost)),+ style: round3(clamp01(v.style)),+ use_speaker_boost: !!v.use_speaker_boost,+ };+}++// Appearance object the child carries — fed straight into api/_lib/bake.js to+// composite a real child GLB.+export function appearanceFromGenome(genome) {+ const body = normalizeGenome(genome).body;+ const out = {};+ if (Object.keys(body.morphs).length) out.morphs = body.morphs;+ if (Object.keys(body.colors).length) out.colors = body.colors;+ if (body.accessories.length) out.accessories = body.accessories;+ if (body.outfit) out.outfit = body.outfit;+ if (body.hidden.length) out.hidden = body.hidden;+ return out;+}++// The skills a child should actually be granted on-chain (expressed only —+// recessive alleles are carried but not licensed).+export function expressedSkills(genome) {+ return normalizeGenome(genome).skills.filter((s) => s.expressed).map((s) => s.skill);+}++// ── Normalization / validation ───────────────────────────────────────────────++export function normalizeGenome(g) {+ g = g && typeof g === 'object' ? g : {};+ const brain = g.brain && typeof g.brain === 'object' ? g.brain : {};+ const voice = g.voice && typeof g.voice === 'object' ? g.voice : {};+ const body = g.body && typeof g.body === 'object' ? g.body : {};+ const nb = {};+ for (const locus of BRAIN_LOCI) nb[locus] = clamp01(numOr(brain[locus], () => 0.5));+ nb.tone_tags = dedupeStrings(brain.tone_tags);+ nb.archetype = typeof brain.archetype === 'string' && brain.archetype ? brain.archetype : 'analyst';+ const nv = {+ provider: typeof voice.provider === 'string' ? voice.provider : 'browser',+ voice_id: voice.voice_id || null,+ model: voice.model || null,+ stability: clamp01(numOr(voice.stability, () => 0.5)),+ similarity_boost: clamp01(numOr(voice.similarity_boost, () => 0.75)),+ style: clamp01(numOr(voice.style, () => 0.4)),+ use_speaker_boost: typeof voice.use_speaker_boost === 'boolean' ? voice.use_speaker_boost : true,+ pitch: typeof voice.pitch === 'number' && Number.isFinite(voice.pitch) ? Math.max(-0.3, Math.min(0.3, voice.pitch)) : 0,+ };+ const nbody = {+ base_avatar_id: body.base_avatar_id || null,+ outfit: typeof body.outfit === 'string' ? body.outfit : null,+ morphs: sanitizeMorphs(body.morphs),+ colors: sanitizeColors(body.colors),+ accessories: dedupeStrings(body.accessories),+ hidden: dedupeStrings(body.hidden),+ };+ const skills = Array.isArray(g.skills)+ ? g.skills+ .filter((s) => s && typeof s.skill === 'string' && s.skill)+ .map((s) => ({+ skill: s.skill,+ expressed: s.expressed !== false,+ dominant: !!s.dominant,+ recessive: !!s.recessive,+ source: s.source || 'A',+ ...(s.emergent_from ? { emergent_from: s.emergent_from } : {}),+ depth: Number.isFinite(s.depth) ? s.depth : 0,+ }))+ : [];+ const out = {+ version: GENOME_VERSION,+ generation: Number.isFinite(g.generation) ? g.generation : 0,+ brain: nb,+ voice: nv,+ body: nbody,+ skills,+ mutations: Array.isArray(g.mutations) ? g.mutations : [],+ };+ if (g.founder) out.founder = g.founder;+ if (g.parents) out.parents = g.parents;+ if (g.seed) out.seed = g.seed;+ if (g.genome_hash) out.genome_hash = g.genome_hash;+ return out;+}++function keyOf(g) {+ return String(g.founder || (g.parents ? g.parents.join('+') + ':' + (g.seed || '') : '') || g.genome_hash || hashGenome(g));+}++// ── Small pure utilities ─────────────────────────────────────────────────────++function dedupeStrings(arr) {+ if (!Array.isArray(arr)) return [];+ const seen = new Set();+ const out = [];+ for (const v of arr) {+ const s = typeof v === 'string' ? v.trim() : '';+ if (s && !seen.has(s)) { seen.add(s); out.push(s); }+ }+ return out;+}++function sanitizeMorphs(m) {+ if (!m || typeof m !== 'object') return {};+ const out = {};+ for (const [k, v] of Object.entries(m)) {+ if (typeof v === 'number' && Number.isFinite(v)) out[k] = round3(clamp01(v));+ }+ return out;+}++function sanitizeColors(c) {+ if (!c || typeof c !== 'object') return {};+ const out = {};+ for (const [k, v] of Object.entries(c)) {+ const hex = normalizeHex(v);+ if (hex) out[k] = hex;+ }+ return out;+}++function normalizeHex(v) {+ if (typeof v !== 'string') return null;+ const m = v.trim().match(/^#?([0-9a-fA-F]{6})$/);+ return m ? `#${m[1].toLowerCase()}` : null;+}++function hexToRgb(hex) {+ const h = normalizeHex(hex) || '#808080';+ return { r: parseInt(h.slice(1, 3), 16), g: parseInt(h.slice(3, 5), 16), b: parseInt(h.slice(5, 7), 16) };+}++function rgbToHex({ r, g, b }) {+ const c = (x) => Math.max(0, Math.min(255, x)).toString(16).padStart(2, '0');+ return `#${c(r)}${c(g)}${c(b)}`;+}++// A fresh, recorded breeding seed. Hex string; callers persist it so the breed is+// re-derivable. (Accepts an injected randomness source for tests.)+export function makeSeed(bytes) {+ const buf = bytes || createHash('sha256').update(`${process.hrtime.bigint()}:${Math.random()}`).digest();+ return Buffer.from(buf).subarray(0, 16).toString('hex');+}diff --git a/api/_lib/labor-auth.js b/api/_lib/labor-auth.jsnew file mode 100644index 000000000..60189bd5d--- /dev/null+++ b/api/_lib/labor-auth.js@@ -0,0 +1,48 @@+// Shared auth + ownership for the Agent Labor Market endpoints (api/labor/*).+// Mirrors the session-or-bearer + CSRF-on-session pattern used by a2a-hire.js so+// every money/mutation path enforces ownership server-side, never client-side.++import { authenticateBearer, extractBearer, getSessionUser } from './auth.js';+import { requireCsrf } from './csrf.js';+import { error } from './http.js';+import { sql } from './db.js';++/**+ * Authenticate a write. Returns { userId, session } or null. When it returns+ * null it has ALREADY written the 401/403 response (CSRF failures included), so+ * the caller must simply `return`.+ */+export async function authWrite(req, res) {+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) {+ error(res, 401, 'unauthorized', 'sign in required');+ return null;+ }+ const userId = session?.id ?? bearer?.userId;+ if (session && !(await requireCsrf(req, res, userId))) return null;+ return { userId, session: !!session };+}++/** Load an agent and assert the caller owns it. Throws typed 404/403 errors. */+export async function loadOwnedAgent(agentId, userId) {+ const [agent] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) {+ throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });+ }+ if (agent.user_id !== userId) {+ throw Object.assign(new Error('you do not own this agent'), { status: 403, code: 'forbidden' });+ }+ return agent;+}++export function requireSolanaWallet(agent) {+ if (!agent.meta?.solana_address || !agent.meta?.encrypted_solana_secret) {+ throw Object.assign(new Error('this agent has no Solana wallet provisioned'), {+ status: 409, code: 'no_wallet',+ });+ }+ return agent;+}diff --git a/api/_lib/labor-escrow.js b/api/_lib/labor-escrow.jsnew file mode 100644index 000000000..7f48b90c2--- /dev/null+++ b/api/_lib/labor-escrow.js@@ -0,0 +1,119 @@+// On-chain escrow for the Agent Labor Market (Moonshot 01).+//+// A bounty's reward is REAL custody, not a DB flag: when an agent posts a bounty,+// it transfers the reward in $THREE from its own custodial wallet into a dedicated+// platform escrow wallet, which actually holds the funds until the work is verified.+// On a pass the escrow releases the worker's payout and the skill author's royalty;+// on a failure it refunds the poster. Every move is a real SPL transfer over the+// same protected-send path the rest of the platform uses (data-driven priority+// fee + CU, rebroadcast until it lands, hard throw on revert).+//+// The escrow keypair is loaded from LABOR_ESCROW_SECRET_BASE58 (a base58-encoded+// 64-byte secret). Fund-routing fails CLOSED if it is unset in production — a paid+// market must never silently route real $THREE to an unset address — mirroring the+// treasuryWallet() guard in token/config.js.++import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';++import { transferSolanaUSDC } from './solana-transfer.js';+import { TOKEN_MINT } from './token/config.js';++let _escrowKp = null;+let _escrowWarned = false;++/** The base58 secret for the escrow wallet, or null (read paths). */+function escrowSecretOrNull() {+ const s = process.env.LABOR_ESCROW_SECRET_BASE58;+ return s && s.trim() ? s.trim() : null;+}++/** Escrow keypair (strict). Throws a typed 503 when unconfigured so callers render+ * a clean "temporarily unavailable" state instead of an opaque 500. */+export function escrowKeypair() {+ if (_escrowKp) return _escrowKp;+ const secret = escrowSecretOrNull();+ if (!secret) {+ const e = new Error(+ '[labor-escrow] LABOR_ESCROW_SECRET_BASE58 is required to hold/release bounty escrow — refusing to route $THREE through an unconfigured escrow wallet.',+ );+ e.status = 503;+ e.code = 'escrow_unavailable';+ throw e;+ }+ try {+ _escrowKp = Keypair.fromSecretKey(bs58.decode(secret));+ } catch {+ const e = new Error('[labor-escrow] LABOR_ESCROW_SECRET_BASE58 is not a valid base58 64-byte secret key');+ e.status = 503;+ e.code = 'escrow_misconfigured';+ throw e;+ }+ return _escrowKp;+}++/** Non-throwing escrow address for read/status paths (null when unconfigured). */+export function escrowAddressOrNull() {+ const secret = escrowSecretOrNull();+ if (!secret) {+ if (!_escrowWarned) {+ _escrowWarned = true;+ console.warn('[labor-escrow] LABOR_ESCROW_SECRET_BASE58 not set — bounty posting will be unavailable.');+ }+ return null;+ }+ try {+ return escrowKeypair().publicKey.toBase58();+ } catch {+ return null;+ }+}++export function escrowConfigured() {+ return escrowAddressOrNull() != null;+}++function requirePositive(amountAtomics) {+ const amt = BigInt(typeof amountAtomics === 'bigint' ? amountAtomics : String(amountAtomics).split('.')[0]);+ if (amt <= 0n) {+ const e = new Error('escrow amount must be > 0');+ e.status = 400;+ e.code = 'bad_amount';+ throw e;+ }+ return amt;+}++/**+ * Fund escrow: move `amountAtomics` of $THREE from the poster agent's custodial+ * wallet into the escrow wallet. Returns the real funding tx signature.+ * @param {{ fromKeypair: Keypair, amountAtomics: bigint|string }} args+ */+export async function fundEscrow({ fromKeypair, amountAtomics }) {+ if (!fromKeypair?.secretKey) throw new Error('fundEscrow: fromKeypair required');+ const amount = requirePositive(amountAtomics);+ const escrow = escrowKeypair();+ return transferSolanaUSDC({+ fromWallet: bs58.encode(fromKeypair.secretKey),+ toAddress: escrow.publicKey.toBase58(),+ amount,+ mint: TOKEN_MINT,+ });+}++/**+ * Release from escrow to a destination wallet (worker payout, author royalty, or+ * poster refund). Returns the real settlement tx signature.+ * @param {{ toAddress: string, amountAtomics: bigint|string }} args+ */+export async function payFromEscrow({ toAddress, amountAtomics }) {+ if (!toAddress) throw new Error('payFromEscrow: toAddress required');+ const amount = requirePositive(amountAtomics);+ const escrow = escrowKeypair();+ return transferSolanaUSDC({+ fromWallet: bs58.encode(escrow.secretKey),+ toAddress,+ amount,+ mint: TOKEN_MINT,+ });+}diff --git a/api/_lib/labor-match.js b/api/_lib/labor-match.jsnew file mode 100644index 000000000..7dad4a217--- /dev/null+++ b/api/_lib/labor-match.js@@ -0,0 +1,293 @@+// The autonomy engine of the Agent Labor Market (Moonshot 01).+//+// This is the part that makes it a *machine* economy: a worker agent's opt-in+// policy auto-bids on bounties matching its licensed skills (priced + paced by a+// transparent negotiation rule, pitched by the LLM router), and a poster agent's+// opt-in policy auto-awards the best bid by the published score. The worker then+// performs the task by invoking its skill, and a neutral verifier agent scores the+// deliverable against the spec before any escrow is released. Every autonomous+// action is recorded with its rationale (the bid/award rows + a reasoning event)+// so the haggling is fully auditable — and visible in the live UI.+//+// Money never moves in this module. Escrow release happens in labor-settle.js.++import { llmComplete, llmConfigured } from './llm.js';+import { sql } from './db.js';+import {+ scoreBid, workerReputation, findAutoBidders, upsertBid, getBounty,+ getLaborPolicy, listBidsForBounty, createJob, markBidAwarded, rejectOtherBids,+ setBountyStatus, getJobByBounty, markJobDelivered, atomicsToThree, _toBig as toBig,+} from './agent-labor.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);+}++// ── Reasoning ledger (best-effort; compatible with Moonshot 05) ─────────────++/** Record an autonomous decision with its rationale. Best-effort: the rationale+ * also lives on the bid/award rows, so a missing ledger table never blocks the+ * economy. Writes to agent_reasoning_events when present. */+export async function emitReasoning(event) {+ try {+ await sql`+ INSERT INTO agent_reasoning_events (agent_id, kind, summary, detail, created_at)+ VALUES (${event.agentId}, ${event.kind}, ${event.summary || null},+ ${JSON.stringify(event.detail || {})}::jsonb, now())`;+ } catch {+ // Table may not exist yet (Moonshot 05 not deployed) — the decision is still+ // captured on the bid/award row; log for local visibility and move on.+ console.log(`[reasoning] ${event.kind} agent=${event.agentId} ${event.summary || ''}`);+ }+}++// ── LLM-backed negotiation copy (graceful, never blocks) ────────────────────++async function llmText({ system, user, maxTokens = 220, userId = null, agentId = null, tool }) {+ if (!llmConfigured()) return null;+ try {+ const { text } = await llmComplete({+ system, user, maxTokens, timeoutMs: 12_000,+ track: { userId, agentId, tool },+ });+ return (text || '').trim() || null;+ } catch (e) {+ console.warn(`[labor-match] llm ${tool} failed:`, e?.message);+ return null;+ }+}++async function generateBidPitch({ agentName, bounty, priceThree, etaSeconds }) {+ const etaMin = Math.round(etaSeconds / 60);+ const fallback = `${agentName} can deliver "${bounty.title}" for ${priceThree.toLocaleString()} $THREE in ~${etaMin} min, using its ${bounty.required_skill || 'general'} skill.`;+ const txt = await llmText({+ system: 'You are an autonomous worker agent bidding on a task in an agent labor market. Write ONE punchy sentence (max 30 words) pitching why you should win. No preamble, no quotes.',+ user: `Task: ${bounty.title}\nSpec: ${String(bounty.spec).slice(0, 400)}\nYour skill: ${bounty.required_skill || 'general'}\nYour price: ${priceThree} $THREE\nYour ETA: ${etaMin} min\nYou are "${agentName}".`,+ tool: 'labor.bid_pitch',+ });+ return { pitch: txt || fallback, rationale: txt ? `LLM pitch @ ${priceThree} $THREE / ${etaMin}m` : `heuristic pitch @ ${priceThree} $THREE / ${etaMin}m` };+}++async function generateAwardRationale({ bounty, bids, winner }) {+ const fallback = `Awarded to ${winner.worker_name}: top score ${winner.score?.toFixed?.(3) ?? winner.score} (price ${winner.price_three} $THREE, reputation ${(winner.reputation ?? 0).toFixed(2)}) across ${bids.length} bid${bids.length === 1 ? '' : 's'}.`;+ const txt = await llmText({+ system: 'You are an autonomous employer agent awarding a bounty. Explain in ONE sentence (max 30 words) why this bid won over the others, citing price, speed, and reputation. No preamble.',+ user: `Bounty: ${bounty.title}\nWinner: ${winner.worker_name} — ${winner.price_three} $THREE, score ${winner.score}, reputation ${winner.reputation}\nOther bids: ${bids.filter((b) => b.id !== winner.id).map((b) => `${b.worker_name} ${b.price_three}$THREE score ${b.score}`).join('; ') || 'none'}`,+ tool: 'labor.award_rationale',+ });+ return txt || fallback;+}++// ── Auto-bid ────────────────────────────────────────────────────────────────++/**+ * Place autonomous bids on an open bounty from every opted-in worker whose policy+ * matches its skill + reward floor. Idempotent per worker (upsert). Returns the+ * number of bids placed/updated.+ */+export async function autoBidForBounty(bounty) {+ if (!bounty || bounty.status !== 'open') return 0;+ const rewardAtomics = toBig(bounty.reward_atomics);+ const bidders = await findAutoBidders({+ requiredSkill: bounty.required_skill || null,+ rewardAtomics,+ excludeAgentId: bounty.poster_agent_id,+ });+ let placed = 0;+ for (const w of bidders) {+ try {+ const { reputation } = await workerReputation(w.agent_id);+ const price = negotiationPrice({ rewardAtomics, maxBidAtomics: w.max_bid_atomics, reputation });+ const eta = etaForReputation(reputation);+ const priceThree = atomicsToThree(price);+ const { pitch, rationale } = await generateBidPitch({+ agentName: w.agent_name || 'Agent', bounty, priceThree, etaSeconds: eta,+ });+ const score = scoreBid({ priceAtomics: price, rewardAtomics, etaSeconds: eta, reputation });+ await upsertBid({+ bountyId: bounty.id, workerAgentId: w.agent_id, workerUserId: w.owner_user_id,+ priceAtomics: price, etaSeconds: eta, pitch, score, rationale, reputation, auto: true,+ });+ placed++;+ emitReasoning({+ agentId: w.agent_id, kind: 'labor.bid',+ summary: `Bid ${priceThree} $THREE on "${bounty.title}"`,+ detail: { bounty_id: bounty.id, price_atomics: String(price), eta_seconds: eta, score, reputation },+ });+ } catch (e) {+ console.warn('[labor-match] auto-bid failed for', w.agent_id, e?.message);+ }+ }+ return placed;+}++// ── Auto-award ───────────────────────────────────────────────────────────────++/**+ * If the poster's policy auto-awards and enough bids are in, award the highest-+ * scoring bid: create the job, mark the winning bid, reject the rest, and move the+ * bounty to 'working'. Returns { job, bounty, winner } or null when not ready.+ */+export async function autoAwardIfReady(bountyId) {+ const bounty = await getBounty(bountyId);+ if (!bounty || bounty.status !== 'open') return null;+ const policy = await getLaborPolicy(bounty.poster_agent_id);+ if (!policy?.poster_enabled || !policy?.auto_award) return null;+ const bids = await listBidsForBounty(bountyId);+ if (bids.length < (policy.min_bids || 1)) return null;++ const winner = bids.reduce((best, b) => (Number(b.score) > Number(best.score) ? b : best), bids[0]);+ const rationale = await generateAwardRationale({ bounty, bids, winner });+ const awarded = await applyAward({ bounty, winner, rationale, auto: true });+ return awarded;+}++/** Shared award transition used by both the manual /award endpoint and auto-award. */+export async function applyAward({ bounty, winner, rationale, auto = false }) {+ const job = await createJob({+ bountyId: bounty.id, bidId: winner.id, workerAgentId: winner.worker_agent_id,+ workerUserId: winner.worker_user_id || winner.worker_userId, posterAgentId: bounty.poster_agent_id,+ requiredSkill: bounty.required_skill || null, priceAtomics: winner.price_atomics,+ });+ await markBidAwarded(winner.id);+ await rejectOtherBids(bounty.id, winner.id);+ const updated = await setBountyStatus(bounty.id, 'working', {+ awardedBidId: winner.id, awardedAgentId: winner.worker_agent_id,+ awardedAt: new Date().toISOString(), awardRationale: rationale,+ });+ emitReasoning({+ agentId: bounty.poster_agent_id, kind: 'labor.award',+ summary: `Awarded "${bounty.title}" to ${winner.worker_name || winner.worker_agent_id}`,+ detail: { bounty_id: bounty.id, bid_id: winner.id, worker_agent_id: winner.worker_agent_id, score: winner.score, auto },+ });+ return { job, bounty: updated, winner, rationale };+}++// ── Perform (the worker invokes its skill to produce the deliverable) ───────++/**+ * The worker performs the task. This is real cognitive work routed through the+ * platform LLM router (the worker's licensed skill), bounded by the per-user+ * spend cap. Marks the job delivered with the produced artifact.+ */+export async function performJob({ job, bounty, workerUserId }) {+ const system = `You are an autonomous worker agent fulfilling a paid task in an agent labor market. Perform the task precisely and return only the finished deliverable — no preamble, no meta commentary. Skill: ${bounty.required_skill || 'general'}.`;+ const user = `Title: ${bounty.title}\n\nSpec:\n${String(bounty.spec).slice(0, 1500)}`;+ let output = await llmText({ system, user, maxTokens: 900, userId: workerUserId, agentId: job.worker_agent_id, tool: 'labor.perform' });+ if (!output) {+ // No LLM provider configured: deliver a structured acknowledgement so the+ // pipeline still completes honestly (verifier will judge it against the spec).+ output = `Deliverable for "${bounty.title}" (skill: ${bounty.required_skill || 'general'}): ${String(bounty.spec).slice(0, 400)}`;+ }+ const deliverable = {+ skill: bounty.required_skill || 'general',+ output,+ summary: output.slice(0, 200),+ produced_at: new Date().toISOString(),+ };+ const delivered = await markJobDelivered(job.id, deliverable);+ emitReasoning({+ agentId: job.worker_agent_id, kind: 'labor.deliver',+ summary: `Delivered work for "${bounty.title}"`,+ detail: { bounty_id: bounty.id, job_id: job.id, chars: output.length },+ });+ return { job: delivered || job, deliverable };+}++// ── Verify (a neutral verifier scores the deliverable vs the spec) ──────────++/**+ * Score a deliverable against the bounty spec. Returns a verdict the settler+ * trusts: { pass, score (0..1), reason, verifier }. For an empty/blank+ * deliverable the verdict fails deterministically; otherwise the LLM verifier+ * judges fitness, with a conservative heuristic fallback when no LLM is available.+ */+export async function verifyDeliverable({ bounty, deliverable }) {+ const output = String(deliverable?.output || '').trim();+ if (!output) {+ return { pass: false, score: 0, reason: 'empty deliverable', verifier: 'deterministic' };+ }+ if (llmConfigured()) {+ const txt = await llmText({+ system: 'You are a neutral verifier agent. Judge whether the deliverable satisfies the task spec. Respond with STRICT JSON: {"pass": boolean, "score": number 0..1, "reason": string (max 24 words)}. No other text.',+ user: `Spec:\n${String(bounty.spec).slice(0, 1200)}\n\nDeliverable:\n${output.slice(0, 1500)}`,+ maxTokens: 160, tool: 'labor.verify',+ });+ const parsed = safeJson(txt);+ if (parsed && typeof parsed.pass === 'boolean') {+ const score = Math.max(0, Math.min(1, Number(parsed.score) || 0));+ return { pass: parsed.pass && score >= 0.5, score, reason: String(parsed.reason || '').slice(0, 200) || 'verified', verifier: 'llm' };+ }+ }+ // Heuristic fallback: a substantive, on-topic deliverable passes. Conservative+ // — a one-word reply or pure echo of the spec does not.+ const substantive = output.length >= 40;+ return {+ pass: substantive,+ score: substantive ? 0.6 : 0.2,+ reason: substantive ? 'substantive deliverable (heuristic)' : 'deliverable too thin (heuristic)',+ verifier: 'heuristic',+ };+}++function safeJson(s) {+ if (!s) return null;+ try {+ const m = s.match(/\{[\s\S]*\}/);+ return m ? JSON.parse(m[0]) : null;+ } catch {+ return null;+ }+}++// ── Skill-author payout resolution (royalty routing) ────────────────────────++/**+ * Resolve where a skill's royalty should go: the author's agent wallet. Returns+ * null when the skill has no resolvable on-chain payout — in which case the+ * settler routes the full awarded amount to the worker (no fake address is ever+ * invented to receive a royalty).+ */+export async function resolveSkillAuthorPayout(requiredSkill, { excludeAgentId } = {}) {+ if (!requiredSkill) return null;+ try {+ const rows = await sql`+ SELECT ms.id AS skill_id, ms.author_id,+ ai.id AS author_agent_id, ai.meta->>'solana_address' AS payout_address+ FROM marketplace_skills ms+ JOIN agent_identities ai ON ai.user_id = ms.author_id AND ai.deleted_at IS NULL+ WHERE (ms.slug = ${requiredSkill} OR ms.name = ${requiredSkill})+ AND ai.meta->>'solana_address' IS NOT NULL+ AND ai.id != ${excludeAgentId || '00000000-0000-0000-0000-000000000000'}+ ORDER BY ai.created_at ASC+ LIMIT 1`;+ const r = rows[0];+ if (!r?.payout_address) return null;+ return { skillId: r.skill_id, authorUserId: r.author_id, authorAgentId: r.author_agent_id, payoutAddress: r.payout_address };+ } catch (e) {+ console.warn('[labor-match] resolveSkillAuthorPayout failed:', e?.message);+ return null;+ }+}diff --git a/api/_lib/labor-settle.js b/api/_lib/labor-settle.jsnew file mode 100644index 000000000..16859821a--- /dev/null+++ b/api/_lib/labor-settle.js@@ -0,0 +1,245 @@+// Settlement for the Agent Labor Market (Moonshot 01) — where the $THREE actually+// moves. Shared by the POST /api/labor/settle endpoint and the autonomy driver so+// there is exactly ONE place that verifies a deliverable and releases escrow.+//+// Flow (idempotent by job settle_key — a retry never double-pays):+// 1. Claim the settle atomically (settle_key). A second caller no-ops.+// 2. A neutral verifier scores the deliverable against the spec.+// 3. On a PASS: release escrow on-chain — worker payout + skill-author royalty ++// any unspent reward refunded to the poster — then record a real agent-+// invocation receipt (worker invoked the poster's skill) and mark settled.+// 4. On a FAIL: refund the poster in full and mark the job failed (bad work+// counts against the worker; an inability to perform is recorded as 'refunded'+// so a network fault never tarnishes a worker's reputation).++import { sql } from './db.js';+import {+ settlementSplit, defaultRoyaltyBps, claimSettle, recordVerdict,+ markJobSettled, markJobFailed, setBountyStatus, atomicsToThree, _toBig as toBig,+} from './agent-labor.js';+import {+ verifyDeliverable, resolveSkillAuthorPayout, emitReasoning,+ autoBidForBounty, autoAwardIfReady, performJob,+} from './labor-match.js';+import { getBounty, getJobByBounty } from './agent-labor.js';+import { payFromEscrow } from './labor-escrow.js';+import { recoverSolanaAgentKeypair } from './agent-wallet.js';+import { recordInvocationReceipt } from './agent-invocation-onchain.js';+import { recordCustodyEvent } from './agent-trade-guards.js';++async function loadAgentWallet(agentId) {+ const [row] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ return row || null;+}++/**+ * Verify + settle a delivered job. Returns a result describing the on-chain+ * outcome. Safe to call more than once for the same job: only the first call that+ * wins the settle_key claim moves funds.+ *+ * @param {{ job: object, bounty: object, verdict?: object }} args+ */+export async function runSettlement({ job, bounty, verdict: providedVerdict = null }) {+ if (!job || !bounty) throw new Error('runSettlement: job and bounty required');++ const settleKey = `settle:${job.id}`;+ const claimed = await claimSettle(job.id, settleKey);+ if (!claimed) {+ // Already owned by a prior settle. Return the current terminal state.+ const [cur] = await sql`SELECT * FROM agent_jobs WHERE id = ${job.id}`;+ return { idempotent: true, status: cur?.status || job.status, job: cur || job };+ }++ // ── Verify ───────────────────────────────────────────────────────────────+ const verdict = providedVerdict || (await verifyDeliverable({ bounty, deliverable: claimed.deliverable }));+ await recordVerdict(job.id, verdict);++ const reward = toBig(bounty.reward_atomics);+ const awarded = toBig(job.price_atomics);++ // ── Failure path: refund poster, mark failed (no release) ─────────────────+ if (!verdict.pass) {+ let refundSig = null;+ let refundError = null;+ try {+ const poster = await loadAgentWallet(bounty.poster_agent_id);+ if (poster?.meta?.solana_address) {+ refundSig = await payFromEscrow({ toAddress: poster.meta.solana_address, amountAtomics: reward });+ }+ } catch (e) {+ refundError = e?.message || String(e);+ console.error('[labor-settle] refund failed', refundError);+ }+ await markJobFailed(job.id, { reason: `verification failed: ${verdict.reason}`, refundSig, status: 'failed' });+ await setBountyStatus(bounty.id, 'failed', { refundSig });+ emitReasoning({+ agentId: bounty.poster_agent_id, kind: 'labor.refund',+ summary: `Refunded "${bounty.title}" — work rejected`,+ detail: { bounty_id: bounty.id, job_id: job.id, verdict, refund_sig: refundSig, refund_error: refundError },+ });+ return { settled: false, status: 'failed', verdict, refund_sig: refundSig, refund_error: refundError };+ }++ // ── Pass path: resolve royalty + split ───────────────────────────────────+ const author = await resolveSkillAuthorPayout(bounty.required_skill, { excludeAgentId: job.worker_agent_id });+ const split = settlementSplit({+ rewardAtomics: reward, awardedAtomics: awarded,+ royaltyBps: defaultRoyaltyBps(), hasAuthor: !!author,+ });++ const worker = await loadAgentWallet(job.worker_agent_id);+ const poster = await loadAgentWallet(bounty.poster_agent_id);+ if (!worker?.meta?.solana_address) {+ // Cannot pay a worker with no wallet — refund and fail without penalizing the+ // worker's reputation (provisioning issue, not bad work).+ let refundSig = null;+ try {+ if (poster?.meta?.solana_address) refundSig = await payFromEscrow({ toAddress: poster.meta.solana_address, amountAtomics: reward });+ } catch (e) { console.error('[labor-settle] refund (no worker wallet) failed', e?.message); }+ await markJobFailed(job.id, { reason: 'worker has no wallet to receive payout', refundSig, status: 'refunded' });+ await setBountyStatus(bounty.id, 'refunded', { refundSig });+ return { settled: false, status: 'refunded', reason: 'worker_no_wallet', refund_sig: refundSig };+ }++ // ── Release escrow on-chain (worker payout is the critical leg) ───────────+ const settlementSig = await payFromEscrow({ toAddress: worker.meta.solana_address, amountAtomics: split.workerAtomics });++ // Royalty + poster refund are best-effort: a failure here leaves the residue in+ // escrow (sweepable) but must not undo the worker's confirmed payout.+ let royaltySig = null;+ if (author && split.royaltyAtomics > 0n) {+ try {+ royaltySig = await payFromEscrow({ toAddress: author.payoutAddress, amountAtomics: split.royaltyAtomics });+ } catch (e) { console.error('[labor-settle] royalty payout failed', e?.message); }+ }+ let posterRefundSig = null;+ if (split.posterRefundAtomics > 0n && poster?.meta?.solana_address) {+ try {+ posterRefundSig = await payFromEscrow({ toAddress: poster.meta.solana_address, amountAtomics: split.posterRefundAtomics });+ } catch (e) { console.error('[labor-settle] poster refund (auction surplus) failed', e?.message); }+ }++ // ── Record the real on-chain invocation receipt (non-fatal) ──────────────+ let invocationSig = null;+ let invocationError = null;+ try {+ if (!worker.meta?.encrypted_solana_secret) throw new Error('worker wallet not recoverable for receipt');+ if (!poster?.meta?.solana_address) throw new Error('poster has no Solana authority to record against');+ const invokerKeypair = await recoverSolanaAgentKeypair(worker.meta.encrypted_solana_secret, {+ agentId: job.worker_agent_id, userId: worker.user_id, reason: 'labor_invocation_receipt',+ });+ const receipt = await recordInvocationReceipt({+ invokerKeypair,+ targetAuthority: poster.meta.solana_address,+ skillName: bounty.required_skill || bounty.title,+ parameters: JSON.stringify({ bounty: bounty.id, job: job.id, three: atomicsToThree(split.workerAtomics) }).slice(0, 480),+ });+ invocationSig = receipt.signature;+ } catch (e) {+ invocationError = e?.message || String(e);+ console.error('[labor-settle] invocation receipt failed', invocationError);+ }++ await markJobSettled(job.id, {+ settlementSig, royaltySig, invocationSig,+ royaltyAtomics: split.royaltyAtomics, workerPayoutAtomics: split.workerAtomics,+ royaltyAuthorId: author?.authorAgentId || null,+ refundSig: posterRefundSig,+ });+ await setBountyStatus(bounty.id, 'settled');++ // Cross-wire: surface the worker's income in the custody ledger so it shows up+ // on the wallet HUD / live money pulse as real earnings.+ recordCustodyEvent({+ agentId: job.worker_agent_id, userId: null, eventType: 'tip', category: null,+ network: 'mainnet', asset: 'THREE', amountRaw: split.workerAtomics,+ signature: settlementSig, status: 'confirmed',+ meta: { source: 'labor_market', bounty_id: bounty.id, job_id: job.id, skill: bounty.required_skill || null },+ }).catch((e) => console.error('[labor-settle] worker income record failed', e?.message));++ emitReasoning({+ agentId: job.worker_agent_id, kind: 'labor.settle',+ summary: `Settled "${bounty.title}" — earned ${atomicsToThree(split.workerAtomics)} $THREE`,+ detail: {+ bounty_id: bounty.id, job_id: job.id, settlement_sig: settlementSig,+ worker_atomics: String(split.workerAtomics), royalty_atomics: String(split.royaltyAtomics),+ royalty_sig: royaltySig, invocation_sig: invocationSig,+ },+ });++ return {+ settled: true, status: 'settled', verdict,+ settlement_sig: settlementSig, royalty_sig: royaltySig,+ poster_refund_sig: posterRefundSig, invocation_sig: invocationSig, invocation_error: invocationError,+ worker_payout_atomics: String(split.workerAtomics),+ worker_payout_three: atomicsToThree(split.workerAtomics),+ royalty_atomics: String(split.royaltyAtomics),+ royalty_three: atomicsToThree(split.royaltyAtomics),+ explorer: settlementSig ? `https://solscan.io/tx/${settlementSig}` : null,+ };+}++/**+ * Drive a bounty as far as its participants' policies allow, autonomously: collect+ * auto-bids, auto-award if the poster opted in, then have an autonomous worker+ * perform the task and settle it on-chain. Each step is guarded — a failure in one+ * never throws out of the driver (the bounty just stops at a resumable state that+ * the manual endpoints or the /tick cron can pick up). Safe to call repeatedly.+ *+ * @returns {Promise<{ bids: number, awarded: boolean, settled: string|null }>}+ */+export async function runAutopilot(bountyId) {+ const out = { bids: 0, awarded: false, settled: null };+ try {+ let bounty = await getBounty(bountyId);+ if (!bounty) return out;++ if (bounty.status === 'open') {+ out.bids = await autoBidForBounty(bounty).catch((e) => {+ console.warn('[labor-autopilot] auto-bid failed', e?.message);+ return 0;+ });+ const awarded = await autoAwardIfReady(bountyId).catch((e) => {+ console.warn('[labor-autopilot] auto-award failed', e?.message);+ return null;+ });+ if (!awarded) return out;+ out.awarded = true;+ bounty = awarded.bounty || (await getBounty(bountyId));+ }++ // Drive an awarded job to delivery + settlement only when the worker is+ // autonomous (its policy enabled it to bid). A manual worker delivers via the+ // /deliver endpoint instead, so we never act on their behalf without consent.+ if (bounty?.status === 'working') {+ const job = await getJobByBounty(bountyId);+ if (!job) return out;+ const { isAutonomousWorker } = await import('./agent-labor.js')+ .then((m) => m.getLaborPolicy(job.worker_agent_id))+ .then((p) => ({ isAutonomousWorker: !!p?.worker_enabled }))+ .catch(() => ({ isAutonomousWorker: false }));+ if (!isAutonomousWorker) return out;++ let working = job;+ if (job.status === 'working') {+ const performed = await performJob({ job, bounty, workerUserId: job.worker_user_id }).catch((e) => {+ console.warn('[labor-autopilot] perform failed', e?.message);+ return null;+ });+ if (!performed) return out;+ working = performed.job;+ }+ if (working.status === 'delivered' || working.status === 'verifying') {+ const result = await runSettlement({ job: working, bounty }).catch((e) => {+ console.error('[labor-autopilot] settle failed', e?.message);+ return null;+ });+ out.settled = result?.status || null;+ }+ }+ } catch (e) {+ console.error('[labor-autopilot] driver error', e?.message);+ }+ return out;+}diff --git a/api/_lib/ledger-anchor.js b/api/_lib/ledger-anchor.jsnew file mode 100644index 000000000..0c86d9cb8--- /dev/null+++ b/api/_lib/ledger-anchor.js@@ -0,0 +1,142 @@+/**+ * On-chain anchor for the Reasoning Ledger (server-side).+ *+ * Because each agent's ledger is a hash chain, the head entry_hash commits to the+ * ENTIRE prefix — so anchoring the head is a Merkle-root-equivalent tamper proof.+ * This writes a signed SPL-Memo (kind `threews.ledger.v1`) committing an agent's+ * chain head to Solana, and records it in `ledger_anchors`. Anyone can then prove+ * the history wasn't edited: GET /api/ledger/verify/:agentId recomputes the chain+ * and checks its head against this on-chain commitment.+ *+ * Best-effort by contract, exactly like trader-score-attest.js:+ * - No funded attester key (ATTEST_AGENT_SECRET_KEY) → the commitment is still+ * recorded locally with status 'pending' (no signature); the cron reports it+ * rather than failing. The cryptographic tamper-evidence of the chain holds+ * regardless; only the independent on-chain timestamp is deferred.+ * - Idempotent per (agent_id, head_hash): re-anchoring the same head returns the+ * existing row instead of broadcasting a duplicate.+ */++import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';++import { sql } from './db.js';+import { solanaConnection } from './solana/connection.js';+import { RPC } from './solana-attestations.js';+import { loadAttesterKeypair } from './attest-event.js';++const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const LEDGER_KIND = 'threews.ledger.v1';+const TX_TIMEOUT_MS = 15_000;++function withTimeout(promise, ms) {+ let timer;+ const timeout = new Promise((_, reject) => {+ timer = setTimeout(() => reject(Object.assign(new Error(`rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' })), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++/**+ * Anchor an agent's current chain head on-chain (best-effort).+ *+ * @param {object} p+ * @param {string} p.agentId+ * @param {'mainnet'|'devnet'} p.network+ * @param {string} p.headHash entry_hash of the chain head (commits the whole chain)+ * @param {number} p.throughSeq seq of the head entry+ * @param {number} p.entryCount total entries committed+ * @param {number} [p.now]+ * @returns {Promise<{status:'anchored'|'deduped'|'pending', signature:string|null, detail?:string}>}+ */+export async function anchorLedgerHead({ agentId, network = 'mainnet', headHash, throughSeq, entryCount, now = Date.now() }) {+ if (!agentId || !headHash) throw new Error('anchorLedgerHead: agentId and headHash required');++ // Idempotent: this exact head already committed?+ const [existing] = await sql`+ select status, signature from ledger_anchors+ where agent_id = ${agentId} and head_hash = ${headHash} limit 1+ `;+ if (existing && existing.status === 'anchored') {+ return { status: 'deduped', signature: existing.signature };+ }++ // Load the funded attester. Missing key → record the commitment locally as+ // pending; the chain's tamper-evidence does not depend on the on-chain write.+ let attester;+ try {+ attester = loadAttesterKeypair();+ } catch {+ await upsertAnchor({ agentId, network, throughSeq, headHash, entryCount, status: 'pending', detail: 'attester_key_not_configured', signature: null });+ return { status: 'pending', signature: null, detail: 'attester_key_not_configured' };+ }++ const payload = {+ v: 1,+ kind: LEDGER_KIND,+ agent_id: agentId,+ head_hash: headHash,+ through_seq: throughSeq,+ entry_count: entryCount,+ network,+ ts: Math.floor(now / 1000),+ source: 'threews.reasoning-ledger',+ };++ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });+ const ix = new TransactionInstruction({+ programId: MEMO_PROGRAM_ID,+ keys: [{ pubkey: attester.publicKey, isSigner: true, isWritable: false }],+ data: Buffer.from(JSON.stringify(payload), 'utf8'),+ });++ let signature;+ try {+ signature = await withTimeout(+ sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),+ TX_TIMEOUT_MS,+ );+ } catch (err) {+ await upsertAnchor({ agentId, network, throughSeq, headHash, entryCount, status: 'failed', detail: `record_failed: ${err.message}`.slice(0, 280), signature: null });+ return { status: 'pending', signature: null, detail: `record_failed: ${err.message}` };+ }++ await upsertAnchor({ agentId, network, throughSeq, headHash, entryCount, status: 'anchored', detail: null, signature });+ return { status: 'anchored', signature };+}++async function upsertAnchor({ agentId, network, throughSeq, headHash, entryCount, status, detail, signature }) {+ await sql`+ insert into ledger_anchors (agent_id, network, through_seq, head_hash, entry_count, signature, status, detail, anchored_at)+ values (${agentId}, ${network}, ${throughSeq}, ${headHash}, ${entryCount}, ${signature}, ${status}, ${detail},+ ${status === 'anchored' ? new Date().toISOString() : null})+ on conflict (agent_id, head_hash) do update set+ status = excluded.status,+ signature = coalesce(excluded.signature, ledger_anchors.signature),+ detail = excluded.detail,+ through_seq = excluded.through_seq,+ entry_count = excluded.entry_count,+ anchored_at = coalesce(excluded.anchored_at, ledger_anchors.anchored_at)+ `;+}++/** Latest anchor row for an agent (any status), newest by through_seq. */+export async function latestAnchor(agentId) {+ const [row] = await sql`+ select network, through_seq, head_hash, entry_count, signature, status, detail, anchored_at+ from ledger_anchors where agent_id = ${agentId}+ order by through_seq desc, created_at desc limit 1+ `;+ return row || null;+}++/** Latest successfully-anchored row for an agent. */+export async function latestAnchoredAnchor(agentId) {+ const [row] = await sql`+ select network, through_seq, head_hash, entry_count, signature, status, anchored_at+ from ledger_anchors where agent_id = ${agentId} and status = 'anchored'+ order by through_seq desc limit 1+ `;+ return row || null;+}++export { LEDGER_KIND };diff --git a/api/_lib/migrations/20260623120000_reasoning_ledger.sql b/api/_lib/migrations/20260623120000_reasoning_ledger.sqlnew file mode 100644index 000000000..373237eceBinary files /dev/null and b/api/_lib/migrations/20260623120000_reasoning_ledger.sql differdiff --git a/api/_lib/migrations/20260623180000_agent_labor_market.sql b/api/_lib/migrations/20260623180000_agent_labor_market.sqlnew file mode 100644index 000000000..3d091df13--- /dev/null+++ b/api/_lib/migrations/20260623180000_agent_labor_market.sql@@ -0,0 +1,177 @@+begin;++-- The Agent Labor Market (Moonshot 01) — a real, autonomous machine economy.+--+-- One agent posts a bounty (escrowing the reward in $THREE from its own custodial+-- wallet), other agents discover and bid on it, the poster (or its autonomous+-- policy) awards the best bid, the worker performs the task by invoking a licensed+-- skill, a neutral verifier scores the deliverable, and on a pass the escrow is+-- released ON-CHAIN to the worker's wallet with the skill royalty routed to the+-- author — recorded as a real agent-invocation receipt. No human in the loop.+--+-- Money columns are atomic-unit integers ($THREE has 6 decimals), stored as+-- numeric(40,0) so they are exact (never floats) AND summable for earnings rollups.+-- Escrow is REAL on-chain custody (agent_bounties.escrow_address / escrow_fund_sig),+-- not a DB flag: funds are actually held by the escrow wallet and actually released.++-- ── Bounties ────────────────────────────────────────────────────────────────+create table if not exists agent_bounties (+ id uuid primary key default gen_random_uuid(),++ -- The employer: an agent owned by the caller. poster_user_id is the ownership+ -- anchor enforced server-side on every mutation.+ poster_agent_id uuid not null,+ poster_user_id uuid not null,++ title text not null,+ spec text not null, -- what the worker must produce+ required_skill text, -- skill slug the worker must hold a license for++ -- Reward, escrowed in $THREE. reward_mint is always the $THREE mint (enforced+ -- in code); kept as a column so a hire stays auditable if config ever changes.+ reward_atomics numeric(40,0) not null check (reward_atomics > 0),+ reward_mint text not null,++ -- Lifecycle: open → awarded → working → verifying → settled+ -- \→ refunded | failed | cancelled+ status text not null default 'open',+ deadline timestamptz,++ -- Real on-chain escrow custody.+ escrow_address text, -- wallet that holds the reward+ escrow_fund_sig text, -- poster wallet → escrow funding tx+ refund_sig text, -- escrow → poster refund tx (failure path)++ -- Award.+ awarded_bid_id uuid,+ awarded_agent_id uuid,+ awarded_at timestamptz,+ award_rationale text, -- transparent reason the bid won (algo + LLM)++ auto boolean not null default false, -- posted by an autonomous policy+ meta jsonb not null default '{}',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ constraint agent_bounties_status_chk+ check (status in ('open','awarded','working','verifying','settled','refunded','failed','cancelled'))+);++-- Open-bounty feed (the discovery surface): newest open bounties first.+create index if not exists agent_bounties_feed+ on agent_bounties (status, created_at desc);+-- Per-skill matching for the autonomy engine.+create index if not exists agent_bounties_skill_open+ on agent_bounties (required_skill)+ where status = 'open';+-- Per-poster history (the profile "Work" tab).+create index if not exists agent_bounties_poster+ on agent_bounties (poster_agent_id, created_at desc);++-- ── Bids ────────────────────────────────────────────────────────────────────+create table if not exists agent_bids (+ id uuid primary key default gen_random_uuid(),+ bounty_id uuid not null,+ worker_agent_id uuid not null,+ worker_user_id uuid not null,++ price_atomics numeric(40,0) not null check (price_atomics > 0), -- $THREE the worker will accept+ eta_seconds integer, -- promised turnaround+ pitch text,++ -- Transparent award score (price × eta × reputation) captured at award time,+ -- plus the human/LLM rationale that fed the reasoning ledger.+ score double precision,+ rationale text,+ reputation double precision,++ auto boolean not null default false, -- placed by an autonomous policy+ status text not null default 'pending',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ constraint agent_bids_status_chk check (status in ('pending','awarded','rejected','withdrawn')),+ -- One live bid per worker per bounty; a re-bid upserts.+ constraint agent_bids_unique_worker unique (bounty_id, worker_agent_id)+);++create index if not exists agent_bids_bounty on agent_bids (bounty_id, created_at desc);+create index if not exists agent_bids_worker on agent_bids (worker_agent_id, created_at desc);++-- ── Jobs (the awarded → settled work record) ────────────────────────────────+create table if not exists agent_jobs (+ id uuid primary key default gen_random_uuid(),+ bounty_id uuid not null,+ bid_id uuid not null,+ worker_agent_id uuid not null,+ worker_user_id uuid not null,+ poster_agent_id uuid not null,+ required_skill text,+ price_atomics numeric(40,0) not null, -- the awarded reward ($THREE atomics)++ status text not null default 'working',+ deliverable jsonb,+ delivered_at timestamptz,++ -- Verification verdict { pass, score, reason, verifier }.+ verdict jsonb,+ verified_at timestamptz,++ -- Real on-chain artifacts.+ invocation_sig text, -- agent-invocation invoke_skill receipt+ settlement_sig text, -- escrow → worker payout tx+ royalty_sig text, -- escrow → skill author royalty tx+ royalty_atomics numeric(40,0),+ worker_payout_atomics numeric(40,0),+ royalty_author_id uuid,++ -- Idempotent settlement: a retry with the same key never double-pays.+ settle_key text,+ settled_at timestamptz,+ refund_sig text,+ failure_reason text,++ meta jsonb not null default '{}',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ constraint agent_jobs_status_chk+ check (status in ('working','delivered','verifying','settled','refunded','failed')),+ -- One job per bounty (a bounty is awarded once).+ constraint agent_jobs_bounty_unique unique (bounty_id)+);++create index if not exists agent_jobs_worker on agent_jobs (worker_agent_id, status);+create index if not exists agent_jobs_poster on agent_jobs (poster_agent_id, created_at desc);+-- Settlement idempotency guard.+create unique index if not exists agent_jobs_settle_key+ on agent_jobs (settle_key) where settle_key is not null;+-- Recent-settlement ticker (the live $THREE flow feed).+create index if not exists agent_jobs_settled_at+ on agent_jobs (settled_at desc) where status = 'settled';++-- ── Per-agent labor autonomy policy (opt-in) ────────────────────────────────+create table if not exists agent_labor_policies (+ agent_id uuid primary key,+ user_id uuid not null,++ -- Worker side: auto-bid on matching bounties within these limits.+ worker_enabled boolean not null default false,+ skills text[] not null default '{}', -- skills this agent will work for hire+ max_bid_atomics numeric(40,0), -- never bid above this+ min_reward_atomics numeric(40,0), -- ignore bounties cheaper than this++ -- Poster side: auto-award the best bid by the transparent score.+ poster_enabled boolean not null default false,+ auto_award boolean not null default false,+ min_bids integer not null default 1, -- wait for at least this many bids++ meta jsonb not null default '{}',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists agent_labor_policies_worker+ on agent_labor_policies (worker_enabled) where worker_enabled = true;++commit;diff --git a/api/_lib/migrations/20260628091000_skill_license_mints.sql b/api/_lib/migrations/20260628091000_skill_license_mints.sqlnew file mode 100644index 000000000..f3051b77e--- /dev/null+++ b/api/_lib/migrations/20260628091000_skill_license_mints.sql@@ -0,0 +1,30 @@+-- On-chain skill-license issuance log.+--+-- One row per confirmed purchase that attempted an on-chain license mint (the+-- `skill_license` Anchor program). Records the minted PDA / NFT / tx so the+-- creator dashboard can show a license count and the skill executor can read a+-- proof, and records `skipped` (with a reason) when the environment can't mint+-- — so a missing collection / minter key / wallet is observable, never silent.++CREATE TABLE IF NOT EXISTS skill_license_mints (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ purchase_id uuid NOT NULL REFERENCES skill_purchases(id) ON DELETE CASCADE,+ user_id uuid REFERENCES users(id) ON DELETE SET NULL,+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill text NOT NULL,+ owner_wallet text,+ agent_mint text,+ network text,+ program_id text,+ license_pda text,+ nft_mint text,+ tx_signature text,+ -- minted: newly minted; already: PDA existed; skipped: env can't mint (reason set).+ status text NOT NULL DEFAULT 'skipped' CHECK (status IN ('minted', 'already', 'skipped')),+ reason text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (purchase_id)+);+CREATE INDEX IF NOT EXISTS idx_skill_license_mints_agent ON skill_license_mints(agent_id, status);+CREATE INDEX IF NOT EXISTS idx_skill_license_mints_user ON skill_license_mints(user_id);diff --git a/api/_lib/newsletter.js b/api/_lib/newsletter.jsnew file mode 100644index 000000000..1b0c57bb0--- /dev/null+++ b/api/_lib/newsletter.js@@ -0,0 +1,71 @@+// Shared helpers for the double opt-in newsletter (confirm + unsubscribe).+// Resend audience sync is best-effort — the DB row is the source of truth for+// who is subscribed; Resend is the delivery list we keep in step with it.++import { Resend } from 'resend';+import { captureException } from './sentry.js';++let _client = null;+function client() {+ if (!process.env.RESEND_API_KEY) return null;+ if (!_client) _client = new Resend(process.env.RESEND_API_KEY);+ return _client;+}++/** Add (or un-unsubscribe) a confirmed contact in the Resend audience. */+export async function addToAudience(email, locale) {+ const c = client();+ const audienceId = process.env.RESEND_AUDIENCE_ID;+ if (!c || !audienceId) return; // not configured — DB row still holds state+ try {+ await c.contacts.create({ email, audienceId, unsubscribed: false });+ } catch (err) {+ const msg = String(err?.message || '').toLowerCase();+ if (msg.includes('already') || msg.includes('exists')) return; // idempotent+ captureException(err, { email, where: 'newsletter-add-audience' });+ }+}++/** Flag a contact unsubscribed in the Resend audience. */+export async function removeFromAudience(email) {+ const c = client();+ const audienceId = process.env.RESEND_AUDIENCE_ID;+ if (!c || !audienceId) return;+ try {+ await c.contacts.update({ email, audienceId, unsubscribed: true });+ } catch (err) {+ captureException(err, { email, where: 'newsletter-remove-audience' });+ }+}++// A self-contained, branded result page — no page dependency, works even if the+// click lands before the SPA shell is cached. Matches the email template look.+export function resultPage({ heading, body, ctaLabel = 'Back to three.ws', ctaHref = '/' }) {+ return `<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<meta name="robots" content="noindex">+<title>${esc(heading)} · three.ws</title>+<style>+ body{font-family:-apple-system,system-ui,'Segoe UI',sans-serif;background:#080814;color:#eee;margin:0;min-height:100vh;display:grid;place-items:center;padding:24px}+ .card{max-width:460px;width:100%;background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:36px 32px;text-align:center}+ .brand{font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:#6a5cff;margin:0 0 18px}+ h1{font-size:22px;margin:0 0 12px;letter-spacing:-.01em}+ p{color:#aaa;line-height:1.6;margin:0 0 24px;font-size:15px}+ .btn{display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#6a5cff,#ff5ca8);color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:15px}+</style>+</head>+<body><div class="card">+ <p class="brand">three.ws</p>+ <h1>${esc(heading)}</h1>+ <p>${esc(body)}</p>+ <a class="btn" href="${esc(ctaHref)}">${esc(ctaLabel)}</a>+</div></body>+</html>`;+}++function esc(s) {+ return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+}diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsindex 2272fe3a6..6feab5a4e 100644--- a/api/_lib/purchase-confirm.js+++ b/api/_lib/purchase-confirm.js@@ -22,10 +22,12 @@ import BigNumber from 'bignumber.js';import { sql } from './db.js';import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';-import { insertNotification } from './notify.js';+import { insertNotification, emailAllowedForType } from './notify.js';import { verifyEvmUsdcPayment, evmChainId } from './evm-payment-verify.js';import { sendPurchaseReceiptEmail, sendSaleNotificationEmail } from './email.js';import { creditReferralCommission } from './referrals.js';+import { resolveListingSplit, recordSplitDistribution } from './splits.js';+import { recordOnchainLicenseForPurchase } from './skill-license-issue.js';const APP_ORIGIN = process.env.APP_ORIGIN || 'https://three.ws';@@ -251,16 +253,27 @@ export async function confirmSkillPurchase(pur, opts = {}) {return { status: 'expired' };}- const payoutAddress = await resolvePayoutAddress(pur.agent_id, pur.chain);+ let payoutAddress = await resolvePayoutAddress(pur.agent_id, pur.chain);++ // Multi-collaborator routing: when this listing has an on-chain (0xSplits)+ // split, the creator's net must flow INTO the split contract so 0xSplits+ // distributes to each collaborator trustlessly. For EVM listings we verify+ // the payment reached the split address instead of the owner's wallet. Solana+ // splits stay ledger-mode (0xSplits is EVM-only) and pay the owner wallet,+ // with each collaborator's exact share recorded in split_distributions.+ const split = await resolveListingSplit(sql, pur.agent_id, pur.skill).catch(() => null);+ if (split?.split_mode === 'onchain' && split.split_address && evmChainId(pur.chain)) {+ payoutAddress = split.split_address;+ }if (!payoutAddress) throw new Error('payout wallet not configured');- if (pur.chain === 'solana') return confirmSolanaSkill(pur, payoutAddress);- if (evmChainId(pur.chain)) return confirmEvmSkill(pur, payoutAddress, opts.txHash);+ if (pur.chain === 'solana') return confirmSolanaSkill(pur, payoutAddress, split);+ if (evmChainId(pur.chain)) return confirmEvmSkill(pur, payoutAddress, opts.txHash, split);throw new Error(`chain '${pur.chain}' not supported`);}// Solana path: locate the tx via Solana-Pay reference, then validateTransfer.-async function confirmSolanaSkill(pur, payoutAddress) {+async function confirmSolanaSkill(pur, payoutAddress, split = null) {const refKey = new PublicKey(pur.reference);const recipient = new PublicKey(payoutAddress);const splToken = new PublicKey(pur.currency_mint);@@ -340,12 +353,12 @@ async function confirmSolanaSkill(pur, payoutAddress) {return markSkillMismatch(pur, txSignature, reason);}- return finalizeSkillConfirmation(pur, txSignature, payoutAddress, matched.feeTaken.toFixed(0));+ return finalizeSkillConfirmation(pur, txSignature, payoutAddress, matched.feeTaken.toFixed(0), split);}// EVM path: the buyer submits the settlement tx hash; verify a USDC transfer of// at least the price reached the seller's payout wallet on Base.-async function confirmEvmSkill(pur, payoutAddress, txHash) {+async function confirmEvmSkill(pur, payoutAddress, txHash, split = null) {if (!txHash) return { status: 'pending' }; // buyer hasn't broadcast / submitted yet// Idempotency pre-check: one settlement tx can confirm at most one purchase.@@ -446,7 +459,7 @@ async function confirmEvmSkill(pur, payoutAddress, txHash) {}return markSkillMismatch(pur, txHash, result.message || 'no matching transfer');}- return finalizeSkillConfirmation(pur, txHash, payoutAddress);+ return finalizeSkillConfirmation(pur, txHash, payoutAddress, '0', split);}// Seller received some funds against this purchase, but not the exact expected@@ -494,7 +507,7 @@ async function markSkillMismatch(pur, txSignature, reason) {// Atomic confirm + ledger writes. Identical for Solana and EVM once a valid// payment is proven, so both chains converge here. `txSignature` is the Solana// signature or the EVM tx hash.-async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platformFeeAtomics = '0') {+async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platformFeeAtomics = '0', split = null) {const intentId = `sp_${pur.id}`;const updated = await sql`UPDATE skill_purchases@@ -565,6 +578,41 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfo${netAmt.toString()}, ${pur.currency_mint}, ${pur.chain}, ${payoutAddress})ON CONFLICT (intent_id) DO NOTHING`;++ // 3a-bis. Multi-collaborator split: apportion the creator's net across the+ // listing's recipients and record each one's exact share. Idempotent per+ // (purchase, address). In on-chain mode the net already flowed into the+ // 0xSplits contract (rows are informational/settled); in ledger mode each+ // recipient withdraws their accrued share. Never blocks the confirmed+ // payment — a split ledger failure degrades to the seller-net record above.+ if (split?.recipients?.length) {+ try {+ await recordSplitDistribution(sql, {+ purchaseId: pur.id,+ split,+ netAtomics: netAmt,+ currencyMint: pur.currency_mint,+ chain: pur.chain,+ });+ await logEvent(pur.id, 'split_recorded', {+ split_id: split.id,+ mode: split.split_mode,+ recipients: split.recipients.length,+ net: netAmt.toString(),+ });+ } catch (e) {+ console.error('[purchase-confirm] split distribution failed', e?.message);+ }+ }++ // 3a-ter. Mint the trustless on-chain skill license to the beneficiary so+ // entitlement can be verified against Solana, not just our DB. Best-effort:+ // degrades cleanly when the minter key is unset or the program is undeployed+ // (recordOnchainLicenseForPurchase never throws into the confirm path).+ recordOnchainLicenseForPurchase(sql, pur).catch((e) =>+ console.error('[purchase-confirm] license mint failed', e?.message),+ );+if (pur.referrer_user_id && referralAmt > 0n) {// Credit the referrer's accrued earnings AND fire the commission email.// Real payout happens via the existing withdrawal flow keyed off the@@ -790,9 +838,10 @@ async function sendPurchaseEmails({ pur, txSignature, sellerId, grossAmt, netAmtconst agentUrl = pur.agent_id ? `${APP_ORIGIN}/agents/${encodeURIComponent(pur.agent_id)}` : null;// Buyer receipt → the payer (the recipient of a gift didn't pay, so the- // receipt always goes to whoever was charged).+ // receipt always goes to whoever was charged). Gated by the buyer's email+ // preference for the 'purchases' category — honours the off switch.const buyerEmail = await getUserEmail(pur.user_id);- if (buyerEmail) {+ if (buyerEmail && (await emailAllowedForType(pur.user_id, 'skill_purchase_confirmed'))) {await sendPurchaseReceiptEmail({to: buyerEmail,skillName: pur.skill,@@ -810,7 +859,8 @@ async function sendPurchaseEmails({ pur, txSignature, sellerId, grossAmt, netAmt// referral) earnings and the buyer's public handle (never their email).if (sellerId && sellerId !== pur.user_id) {const sellerEmail = await getUserEmail(sellerId);- if (sellerEmail) {+ // Gated by the seller's email preference for the 'sales' category.+ if (sellerEmail && (await emailAllowedForType(sellerId, 'skill_purchased'))) {const buyerHandle = await getUserDisplay(pur.user_id);await sendSaleNotificationEmail({to: sellerEmail,diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex b67c80862..eab4eb040 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -231,11 +231,25 @@ export const limits = {// · irlInteractIp — log a tap/view/message (lighter; legit viewing fans out)irlPinIp: (ip) => getLimiter('irl:pin:ip', { limit: 20, window: '10 m' }).limit(ip),irlInteractIp: (ip) => getLimiter('irl:interact:ip', { limit: 60, window: '1 m' }).limit(ip),+ // Living Stages tip recording (api/stage/tip.js). Each call carries a real+ // on-chain settlement signature and is deduped per signature, so the limiter+ // only blunts a forger spamming distinct fake signatures at the recorder — a+ // generous ceiling for a lively crowd that still caps that abuse surface.+ stageTipIp: (ip) => getLimiter('stage:tip:ip', { limit: 60, window: '1 m' }).limit(ip),// IRL proof-of-presence mint (H3) — a walking viewer re-mints a fix token only// when their coarse cell changes (every ~150 m of travel), so a generous 30/min// covers a brisk walk + a few re-tries while a token-banking sweep (mint many// distinct cells to scrape) trips fast. Keyed per IP.irlFixIp: (ip) => getLimiter('irl:fix:ip', { limit: 30, window: '1 m' }).limit(ip),+ // IRL World Lines (proof-of-presence AR quests). Three write buckets, per IP:+ // · create — placing a quest is heavier + accountable (auth-gated), the tightest.+ // · challenge — issuing a single-use completion nonce; a co-located visitor may+ // re-issue a few times (expiry, retries) while walking the spot.+ // · complete — settling the agent-signed proof. A real visitor completes once, so+ // this only absorbs retries; a low ceiling blunts grinding the mint path.+ worldLineCreateIp: (ip) => getLimiter('wl:create:ip', { limit: 15, window: '10 m' }).limit(ip),+ worldLineChallengeIp: (ip) => getLimiter('wl:challenge:ip', { limit: 30, window: '5 m' }).limit(ip),+ worldLineCompleteIp: (ip) => getLimiter('wl:complete:ip', { limit: 20, window: '5 m' }).limit(ip),// IRL placement token bucket (D4) — keyed per (device_token + IP), tighter than// the coarse per-IP `irlPinIp` so one device can't script a rapid placement flood// even from a rotating IP. Two windows: a 5/min burst guard and a 30/hour ceiling.@@ -295,6 +309,11 @@ export const limits = {// login/auth budget and lock out shared-IP users (offices, shared NAT).referralCodeCheckIp: (ip) =>getLimiter('referral:code:check:ip', { limit: 120, window: '5 m' }).limit(ip),+ // Referral-link visit beacons (public, unauthenticated). Generous — a real+ // visitor fires once per link per page-load — but bounded so the funnel+ // table can't be flooded from one IP.+ referralVisitIp: (ip) =>+ getLimiter('referral:visit:ip', { limit: 60, window: '5 m' }).limit(ip),vanityGalleryPublishIp: (ip) =>getLimiter('vanity:gallery:publish:ip', { limit: 12, window: '10 m' }).limit(ip),vanityGalleryReadIp: (ip) =>diff --git a/api/_lib/reasoning-ledger.js b/api/_lib/reasoning-ledger.jsnew file mode 100644index 000000000..14fa2a3e4Binary files /dev/null and b/api/_lib/reasoning-ledger.js differdiff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 9424b343a..23a59df8a 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1988,3 +1988,39 @@ create table if not exists newsletter_subscribers ();create index if not exists newsletter_subscribers_tokenon newsletter_subscribers (confirm_token);++-- ── genome_breedings — Agent Genome: provable breeding events + lineage ──────+-- Two agents breed into a child that provably inherits a recombination of both+-- parents' brain, voice, body, and skill alleles. Each row records the breeding+-- seed + derived genome so the descent is re-derivable and non-forgeable+-- (api/_lib/genome.js deriveGenome/verifyGenome). The child gets a fresh distinct+-- wallet (fork's ownership invariant, extended to two parents); the parents'+-- rows are never mutated by a breed. `breeding_key` is the idempotency key:+-- replaying the same key returns the same child instead of minting twins.+create table if not exists genome_breedings (+ id uuid primary key default gen_random_uuid(),+ breeding_key text not null unique,+ parent_a_agent_id uuid not null references agent_identities(id) on delete cascade,+ parent_b_agent_id uuid not null references agent_identities(id) on delete cascade,+ child_agent_id uuid references agent_identities(id) on delete set null,+ seed text not null,+ genome jsonb not null,+ genome_hash text not null,+ generation integer not null default 1,+ pedigree_tier text not null default 'common',+ bred_by uuid not null references users(id),+ stud_fee_lamports bigint not null default 0,+ stud_fee_signature text,+ consent_owner uuid references users(id),+ status text not null default 'born'+ check (status in ('pending','born','failed')),+ created_at timestamptz not null default now()+);+create index if not exists genome_breedings_parent_a+ on genome_breedings (parent_a_agent_id, created_at desc);+create index if not exists genome_breedings_parent_b+ on genome_breedings (parent_b_agent_id, created_at desc);+create index if not exists genome_breedings_child+ on genome_breedings (child_agent_id) where child_agent_id is not null;+create index if not exists genome_breedings_bred_by+ on genome_breedings (bred_by, created_at desc);diff --git a/api/_lib/skill-license-issue.js b/api/_lib/skill-license-issue.jsnew file mode 100644index 000000000..96140d1ba--- /dev/null+++ b/api/_lib/skill-license-issue.js@@ -0,0 +1,110 @@+// Issue + record the on-chain skill license for a confirmed purchase.+// ---------------------------------------------------------------------------+// After a skill purchase confirms, the buyer's entitlement is proven two ways:+// 1. the DB grant (skill_access_grants) — fast, always available;+// 2. a trustless on-chain license (the `skill_license` Anchor program) — a+// 1/1 SPL NFT + PDA the skill executor can verify without trusting our DB.+//+// This module bridges (1)→(2): it resolves the beneficiary's Solana wallet and+// the agent's on-chain skill-collection mint, mints the license server-side+// (minter-signed), and records the mint in `skill_license_mints` so the+// dashboard can show a license count and the executor can read back a proof.+//+// It DEGRADES, never fails the purchase: if the agent has no on-chain+// collection, the beneficiary has no Solana wallet, or the minter key / program+// isn't deployed, it records `status='skipped'` (with a reason) and returns —+// the purchase stays confirmed and access still works via the DB grant. It+// never fakes a license it did not actually mint (CLAUDE.md Rule 1 & 9).++import { isValidSolanaAddress } from './validate.js';+import { mintSkillLicenseOnchain, SKILL_LICENSE_PROGRAM_ID } from './skill-license-onchain.js';++/** Resolve a beneficiary's Solana (base58) wallet address, or null. */+async function resolveSolanaWallet(sql, userId) {+ if (!userId) return null;+ try {+ const rows = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${userId}+ ORDER BY is_primary DESC NULLS LAST, created_at ASC+ `;+ for (const r of rows) {+ if (isValidSolanaAddress(r.address)) return r.address;+ }+ } catch {+ /* table shape differs in some envs — fall through to null */+ }+ return null;+}++/**+ * Mint + record the on-chain license for a confirmed `skill_purchases` row.+ * Best-effort and self-contained: returns a small status object and never+ * throws into the confirm path.+ *+ * @param {Function} sql+ * @param {object} pur - confirmed purchase row (id, agent_id, skill, user_id, recipient_user_id, chain)+ * @returns {Promise<{ status:'minted'|'already'|'skipped', reason?:string, license?:string, signature?:string }>}+ */+export async function recordOnchainLicenseForPurchase(sql, pur) {+ const beneficiaryId = pur.recipient_user_id || pur.user_id;++ const [agent] = await sql`+ SELECT skill_collection_mint, skill_collection_network+ FROM agent_identities WHERE id = ${pur.agent_id}+ `;+ const agentMint = agent?.skill_collection_mint || null;+ if (!agentMint) return recordMint(sql, pur, beneficiaryId, { status: 'skipped', reason: 'agent_has_no_onchain_collection' });++ const ownerWallet = await resolveSolanaWallet(sql, beneficiaryId);+ if (!ownerWallet) return recordMint(sql, pur, beneficiaryId, { status: 'skipped', reason: 'beneficiary_has_no_solana_wallet' });++ const network = agent.skill_collection_network === 'devnet' ? 'devnet' : 'mainnet';++ try {+ const res = await mintSkillLicenseOnchain({ ownerWallet, agentMint, skill: pur.skill, network });+ return recordMint(sql, pur, beneficiaryId, {+ status: res.alreadyMinted ? 'already' : 'minted',+ ownerWallet,+ agentMint,+ network,+ license: res.license,+ nftMint: res.nftMint,+ signature: res.signature,+ });+ } catch (e) {+ // minter_unconfigured / program-not-deployed / RPC — record skip, keep the+ // purchase confirmed. The DB grant is the working entitlement meanwhile.+ const reason = e?.code === 'minter_unconfigured' ? 'minter_unconfigured' : e?.message?.slice(0, 200) || 'mint_failed';+ return recordMint(sql, pur, beneficiaryId, { status: 'skipped', reason, ownerWallet, agentMint, network });+ }+}++// Upsert the mint record (one per purchase). Tolerates a missing table so the+// confirm path is unaffected before the migration runs.+async function recordMint(sql, pur, beneficiaryId, fields) {+ try {+ await sql`+ INSERT INTO skill_license_mints+ (purchase_id, user_id, agent_id, skill, owner_wallet, agent_mint, network,+ program_id, license_pda, nft_mint, tx_signature, status, reason)+ VALUES+ (${pur.id}, ${beneficiaryId}, ${pur.agent_id}, ${pur.skill},+ ${fields.ownerWallet ?? null}, ${fields.agentMint ?? null}, ${fields.network ?? null},+ ${SKILL_LICENSE_PROGRAM_ID}, ${fields.license ?? null}, ${fields.nftMint ?? null},+ ${fields.signature ?? null}, ${fields.status}, ${fields.reason ?? null})+ ON CONFLICT (purchase_id) DO UPDATE SET+ status = EXCLUDED.status,+ reason = EXCLUDED.reason,+ license_pda = COALESCE(EXCLUDED.license_pda, skill_license_mints.license_pda),+ nft_mint = COALESCE(EXCLUDED.nft_mint, skill_license_mints.nft_mint),+ tx_signature = COALESCE(EXCLUDED.tx_signature, skill_license_mints.tx_signature),+ updated_at = now()+ `;+ } catch (e) {+ if (!e?.message?.includes('does not exist')) {+ console.error('[skill-license-issue] record failed', e?.message);+ }+ }+ return { status: fields.status, reason: fields.reason, license: fields.license, signature: fields.signature };+}diff --git a/api/_lib/stage-bridge.js b/api/_lib/stage-bridge.jsnew file mode 100644index 000000000..80e7c21a5--- /dev/null+++ b/api/_lib/stage-bridge.js@@ -0,0 +1,68 @@+// Living Stages — the Vercel half of the bridge to the standalone Colyseus server.+//+// Two directions, both HMAC-signed with the shared multiplayer secret bound to+// the exact body + a fresh timestamp (same discipline as presence-store.js'+// /internal/notify), so a captured tuple can't be replayed with attacker-chosen+// content or after the freshness window:+//+// API → server notifyStageRoom(): the instant a tip settles + is recorded, push+// it to the live StageRoom over /internal/stage so the host reacts+// in ~1s. Best-effort: the money already settled on-chain, so a+// missed push only loses the in-room flourish, never funds.+//+// server → API verifyStageRequest(): the room's host loop fetches its next beat+// from /api/stage/host; this verifies that call really came from+// the multiplayer server (not a public caller draining the brain).+//+// Keep byte-compatible with multiplayer/src/presence-token.js (verifyStageSignature+// / signStageRequest).++import { env } from './env.js';+import { hmacSha256, sha256Base64Url, constantTimeEquals } from './crypto.js';++const STAGE_MAX_AGE_S = 120;++// Push a stage event (today: a settled tip) to the live room. Returns+// { delivered, reason } and never throws into the request path.+export async function notifyStageRoom(stageId, event, payload = {}) {+ const base = env.MULTIPLAYER_INTERNAL_URL;+ if (!base) return { delivered: false, reason: 'unconfigured' };+ const body = { stageId, event, ...payload };+ try {+ const ts = Math.floor(Date.now() / 1000);+ const payloadHash = await sha256Base64Url(JSON.stringify(body ?? {}));+ const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, `stage:${ts}:${payloadHash}`);+ const res = await fetch(`${base}/internal/stage`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-stage-signature': sig,+ 'x-stage-timestamp': String(ts),+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(2500),+ });+ if (!res.ok) return { delivered: false, reason: `http_${res.status}` };+ const out = await res.json().catch(() => ({}));+ return { delivered: !!out?.delivered, reason: out?.reason };+ } catch (err) {+ return { delivered: false, reason: err?.name === 'TimeoutError' ? 'timeout' : 'error' };+ }+}++// Verify an inbound room → API request (the host loop fetching the next beat).+// `body` is the parsed JSON the handler will act on; recompute the hash over the+// same bytes the server signed. Returns true iff the signature + freshness check+// pass. Mirrors signStageRequest in multiplayer/src/presence-token.js.+export async function verifyStageRequest(req, body) {+ const sig = req.headers['x-stage-sig'] || req.headers['X-Stage-Sig'];+ const ts = req.headers['x-stage-ts'] || req.headers['X-Stage-Ts'];+ if (typeof sig !== 'string' || !sig) return false;+ const tsNum = Number(ts);+ if (!Number.isFinite(tsNum)) return false;+ const nowS = Math.floor(Date.now() / 1000);+ if (Math.abs(nowS - tsNum) > STAGE_MAX_AGE_S) return false;+ const payloadHash = await sha256Base64Url(JSON.stringify(body ?? {}));+ const expected = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, `stage-req:${tsNum}:${payloadHash}`);+ return constantTimeEquals(sig, expected);+}diff --git a/api/_lib/world-lines.js b/api/_lib/world-lines.jsnew file mode 100644index 000000000..0f3f86946--- /dev/null+++ b/api/_lib/world-lines.js@@ -0,0 +1,293 @@+// IRL World Lines — proof-of-presence cryptography + ceremony helpers.+//+// A World Line is a location-anchored AR quest left by an agent. To complete it a+// person must physically travel to the spot, prove co-location, and finish an+// agent-driven AR interaction. On success the agent's own wallet SIGNS a+// proof-of-presence — a tamper-evident attestation that "this visitor was in this+// coarse place at this time and did this thing" — which mints a verifiable+// collectible to the visitor.+//+// This module is the security core. It is deliberately PURE (no DB, no network) so+// every guarantee is unit-testable in isolation:+//+// · canonicalProofMessage() — the exact bytes the agent signs / a verifier checks.+// · signPresenceProof() — agent wallet (ed25519) signs the canonical message.+// · verifyPresenceProof() — anyone re-checks the signature against the agent+// public key. This is what GET /verify/:proofId runs,+// and what makes the collectible independently genuine.+// · mintPresenceNonce() — server issues a short-lived, HMAC-bound nonce tying a+// completion attempt to (world_line_id, coarse_cell,+// time-window). Stateless (no DB), like the fix token.+// · verifyPresenceNonce() — re-checks the nonce is unforged, unexpired, and bound+// to the world line + cell the completion claims.+//+// PRIVACY INVARIANT (inherited from api/irl/pins.js + multiplayer/src/geohash.js):+// nothing in a proof, a nonce, or any value this module produces is finer than the+// coarse (~1.1 km, precision-6) geocell. No precise lat/lng ever enters a signed+// payload, a nonce, or a log line. The completer is identified only by a salted hash,+// never a raw device token.++import { webcrypto } from 'node:crypto';+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58 from 'bs58';+import { hmacSha256, sha256, constantTimeEquals } from './crypto.js';+import { encodeGeohash } from './geohash.js';++// ── Coarse cell ──────────────────────────────────────────────────────────────+// The privacy unit for World Lines is the precision-6 geocell (~1.2 km × 0.6 km) —+// the SAME cell the realtime IrlRoom uses, deliberately coarser than the precision-7+// (~150 m) density cell pins use. A proof binds to this cell, never to a coordinate,+// so "where a completion happened" never resolves finer than "somewhere in this+// ~1 km cell." A precision-7 cell is a strict refinement of its precision-6 parent+// (geohash is hierarchical), so cell6 === cell7.slice(0, 6).+export const COARSE_CELL_PRECISION = 6;++export function coarseCell(lat, lng) {+ return encodeGeohash(lat, lng, COARSE_CELL_PRECISION);+}++// A coarse cell is a precision-6 geohash: 6 chars from the geohash base32 alphabet+// (no a/i/l/o). Validate before it reaches a query or a signed payload.+const COARSE_CELL_RE = /^[0-9bcdefghjkmnpqrstuvwxyz]{6}$/;+export function isCoarseCell(v) {+ return typeof v === 'string' && COARSE_CELL_RE.test(v);+}++// ── Challenge spec ───────────────────────────────────────────────────────────+// The agent-driven interaction the visitor completes in AR. Kept small and fully+// validated — it is creator-supplied free-ish content rendered to every visitor, so+// it is clamped the same way a pin caption is. The server never "grades" the AR+// interaction byte-for-byte (it cannot observe the AR session); co-location + the+// single-use nonce are the anti-cheat. The spec only shapes the client experience.+export const CHALLENGE_KINDS = new Set(['tap', 'phrase', 'quiz']);+export const PROMPT_MAX = 240; // the line the agent speaks in AR+export const PHRASE_MAX = 80; // a passphrase / quiz answer the visitor must give+export const TITLE_MAX = 80;+const QUIZ_CHOICE_MAX = 60;+const QUIZ_MAX_CHOICES = 4;++// Normalize + validate a challenge spec. Returns { ok, spec } or { ok:false, error }.+// `tap` — walk up, tap the agent (presence is the whole challenge).+// `phrase` — the agent asks the visitor to say/echo a passphrase the creator set.+// `quiz` — the agent poses a one-line question with up to 4 choices; one is correct.+export function normalizeChallengeSpec(raw) {+ const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const kind = CHALLENGE_KINDS.has(input.kind) ? input.kind : 'tap';+ const prompt = clampText(input.prompt, PROMPT_MAX);+ const spec = { kind, prompt: prompt || null };++ if (kind === 'phrase') {+ const phrase = clampText(input.phrase, PHRASE_MAX);+ if (!phrase) return { ok: false, error: 'a phrase challenge needs a passphrase' };+ // Store the answer ONLY as a normalized hash-friendly form; the client compares+ // the visitor's spoken/typed answer locally, so the answer travels to the device+ // that must satisfy it (the creator chose to gate on it). Case/space-insensitive.+ spec.phrase = normalizeAnswer(phrase);+ } else if (kind === 'quiz') {+ const question = clampText(input.question, PROMPT_MAX);+ if (!question) return { ok: false, error: 'a quiz challenge needs a question' };+ const choices = Array.isArray(input.choices)+ ? input.choices.map((c) => clampText(c, QUIZ_CHOICE_MAX)).filter(Boolean)+ : [];+ if (choices.length < 2) return { ok: false, error: 'a quiz needs at least two choices' };+ const trimmed = choices.slice(0, QUIZ_MAX_CHOICES);+ const answerIdx = Number.isInteger(input.answer) ? input.answer : -1;+ if (answerIdx < 0 || answerIdx >= trimmed.length) {+ return { ok: false, error: 'a quiz needs a valid correct-answer index' };+ }+ spec.question = question;+ spec.choices = trimmed;+ spec.answer = answerIdx;+ }+ return { ok: true, spec };+}++function clampText(v, max) {+ if (v == null) return '';+ return String(v).replace(/\s+/g, ' ').trim().slice(0, max);+}+function normalizeAnswer(v) {+ return String(v).toLowerCase().replace(/\s+/g, ' ').trim();+}++// ── Reward kinds ─────────────────────────────────────────────────────────────+// The collectible is the headline reward (the agent-signed proof itself, surfaced as+// an ownable "I was there" item). 'three_pool' funds a $THREE prize split among the+// first N completers — $THREE is the ONLY coin a value reward may ever reference.+export const REWARD_KINDS = new Set(['collectible', 'three_pool']);+export function normalizeRewardKind(v) {+ return REWARD_KINDS.has(v) ? v : 'collectible';+}++export const DIFFICULTIES = new Set(['easy', 'medium', 'hard']);+export function normalizeDifficulty(v) {+ return DIFFICULTIES.has(v) ? v : 'easy';+}++// ── The signed proof-of-presence message ─────────────────────────────────────+// The EXACT, canonical bytes the agent wallet signs and a verifier re-checks. Domain-+// separated and versioned so a signature can never be replayed as a different kind of+// attestation. Order is fixed; every field is coarse or a hash — never a coordinate,+// never a raw identifier.+//+// three.ws/world-line-presence:v1|wl=<id>|cell=<coarseCell>|nonce=<nonceId>|who=<completerHash>+//+// `completerHash` is a salted SHA-256 of the completer's stable id (device token or+// user id) — present so the proof is bound to ONE visitor (you can't lift another+// person's signed proof and claim it) without the signed bytes ever carrying the raw+// device token.+export const PROOF_DOMAIN = 'three.ws/world-line-presence:v1';++export function canonicalProofMessage({ worldLineId, coarseCell, nonceId, completerHash }) {+ return [+ PROOF_DOMAIN,+ `wl=${worldLineId}`,+ `cell=${coarseCell}`,+ `nonce=${nonceId}`,+ `who=${completerHash}`,+ ].join('|');+}++// Salted hash of a completer's stable id. The salt (a server secret) means the hash+// can't be reversed to the device token by dictionary attack, while staying stable so+// the same visitor maps to the same hash (for "you already completed this" + the+// visitor's own collectible list). Falls back to a fixed dev salt when unset so local+// testing works; production sets WORLD_LINE_SECRET.+export async function completerHash(stableId) {+ const salt = nonceSecret();+ return (await sha256(`wlc:${salt}:${String(stableId ?? '')}`)).slice(0, 32);+}++// Sign the canonical proof message with an agent's ed25519 key. `secretKey` is the+// 64-byte @solana/web3.js secret key (32-byte seed + 32-byte pubkey) recovered via+// recoverSolanaAgentKeypair; we sign with the 32-byte seed. Returns the detached+// signature + the signer public key, both base58 (the on-the-wire proof shape).+export function signPresenceProof({ secretKey, message }) {+ const sk = toBytes(secretKey);+ if (sk.length !== 64 && sk.length !== 32) {+ throw new Error('signPresenceProof: secretKey must be a 32- or 64-byte ed25519 key');+ }+ const seed = sk.length === 64 ? sk.slice(0, 32) : sk;+ const msgBytes = new TextEncoder().encode(message);+ const sig = ed25519.sign(msgBytes, seed);+ const pub = ed25519.getPublicKey(seed);+ return { signature: bs58.encode(sig), signerPubkey: bs58.encode(pub) };+}++// Independently verify a proof: does `signature` (base58) over the canonical message+// validate against `signerPubkey` (base58)? Never throws — a malformed signature or+// key returns false. This is the whole basis of GET /verify/:proofId: anyone holding+// the agent's public key can confirm the collectible is genuine.+export function verifyPresenceProof({ signerPubkey, message, signature }) {+ try {+ const pub = bs58.decode(String(signerPubkey));+ if (pub.length !== 32) return false;+ const sig = bs58.decode(String(signature));+ if (sig.length !== 64) return false;+ const msgBytes = new TextEncoder().encode(message);+ return ed25519.verify(sig, msgBytes, pub);+ } catch {+ return false;+ }+}++// ── The completion nonce (server-issued, stateless, HMAC-bound) ───────────────+// A nonce ties a completion attempt to a specific world line + coarse cell + time+// window. The server mints it only AFTER server-derived co-location succeeds, so+// holding a valid nonce is itself evidence the holder was at the spot. It carries a+// random component so each attempt is unique → the DB stores the nonce id under a+// UNIQUE constraint, making completion idempotent and replay-proof per nonce.+//+// Shape (compact, URL-safe, no DB): base64url(JSON) + '.' + base64url(HMAC).+// payload = { w: worldLineId, c: coarseCell, r: random16, iat: issuedAtSec }+export const NONCE_TTL_SEC = 300; // 5 min — long enough to finish the AR interaction.+const NONCE_FUTURE_SKEW_SEC = 60; // tolerate minor client/server clock skew.+const NONCE_SECRET_ENV = 'WORLD_LINE_SECRET';+// Stable, deliberately non-secret dev/preview key. Keeps mint+verify self-consistent+// without a configured secret so local testing isn't blocked. NOT a security boundary:+// production MUST set WORLD_LINE_SECRET (a token minted under the dev key won't verify+// once a real secret is configured). Never empty — a zero-length HMAC key throws.+const NONCE_DEV_SECRET = 'world-line:dev+preview-unsecured-key:not-for-production';++export function nonceEnforced() {+ const s = process.env[NONCE_SECRET_ENV];+ return typeof s === 'string' && s.length >= 16;+}+function nonceSecret() {+ return nonceEnforced() ? process.env[NONCE_SECRET_ENV] : NONCE_DEV_SECRET;+}++function b64urlEncode(str) {+ return Buffer.from(str, 'utf8').toString('base64')+ .replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');+}+function b64urlDecode(str) {+ const pad = str.length % 4 === 0 ? '' : '='.repeat(4 - (str.length % 4));+ return Buffer.from(String(str).replaceAll('-', '+').replaceAll('_', '/') + pad, 'base64').toString('utf8');+}+function randomHex(bytes = 12) {+ const b = new Uint8Array(bytes);+ (globalThis.crypto || webcrypto).getRandomValues(b);+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');+}++// The nonce id is the stable, storable identity of a nonce: the HMAC of its payload.+// Unique per mint (the random component guarantees it), short enough for a UNIQUE+// index, and what the signed proof + the DB idempotency key both key on.+export async function mintPresenceNonce(worldLineId, cell, nowSec = Math.floor(Date.now() / 1000)) {+ if (typeof worldLineId !== 'string' || !worldLineId) return null;+ if (!isCoarseCell(cell)) return null;+ const payload = { w: worldLineId, c: cell, r: randomHex(12), iat: nowSec };+ const json = JSON.stringify(payload);+ const sig = await hmacSha256(nonceSecret(), json);+ return {+ nonce: `${b64urlEncode(json)}.${sig}`,+ nonceId: sig.slice(0, 32),+ expires_in: NONCE_TTL_SEC,+ };+}++// Verify a nonce authorises a completion of `worldLineId` in `cell`. Returns+// { ok:true, nonceId } or { ok:false, reason }.+// reason: 'missing' | 'malformed' | 'forged' | 'expired' | 'mismatch'+export async function verifyPresenceNonce(nonce, worldLineId, cell, nowSec = Math.floor(Date.now() / 1000)) {+ if (typeof nonce !== 'string' || !nonce.length) return { ok: false, reason: 'missing' };+ const dot = nonce.indexOf('.');+ if (dot <= 0 || dot === nonce.length - 1) return { ok: false, reason: 'malformed' };+ const encPayload = nonce.slice(0, dot);+ const sig = nonce.slice(dot + 1);++ let json;+ try {+ json = b64urlDecode(encPayload);+ } catch {+ return { ok: false, reason: 'malformed' };+ }+ const expected = await hmacSha256(nonceSecret(), json);+ if (!constantTimeEquals(sig, expected)) return { ok: false, reason: 'forged' };++ let payload;+ try {+ payload = JSON.parse(json);+ } catch {+ return { ok: false, reason: 'malformed' };+ }+ const { w, c, iat } = payload || {};+ if (typeof w !== 'string' || !isCoarseCell(c) || !Number.isFinite(iat)) {+ return { ok: false, reason: 'malformed' };+ }+ if (nowSec - iat > NONCE_TTL_SEC || iat - nowSec > NONCE_FUTURE_SKEW_SEC) {+ return { ok: false, reason: 'expired' };+ }+ // Bind the nonce to the world line + cell the completion claims — a nonce minted+ // for one quest/cell can't be spent on another.+ if (w !== worldLineId || c !== cell) return { ok: false, reason: 'mismatch' };+ return { ok: true, nonceId: sig.slice(0, 32) };+}++function toBytes(v) {+ if (v instanceof Uint8Array) return v;+ if (Array.isArray(v)) return Uint8Array.from(v);+ if (v && typeof v === 'object' && typeof v.length === 'number') return Uint8Array.from(v);+ throw new Error('expected a byte array');+}diff --git a/api/admin/[resource].js b/api/admin/[resource].jsindex 3303ea3e9..0eb12438e 100644--- a/api/admin/[resource].js+++ b/api/admin/[resource].js@@ -1,6 +1,7 @@import { sql } from '../_lib/db.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { requireAdmin } from '../_lib/admin.js';+import { computeKFactor, conversionRate } from '../_lib/referral-rewards.js';export default wrap(async (req, res) => {const resource = req.query?.resource;@@ -199,5 +200,108 @@ export default wrap(async (req, res) => {return json(res, 200, { totals, byRoute, byDay });}+ if (resource === 'referrals') {+ // Viral loop health. Window is configurable (?days=, 1–365, default 30) so+ // the loop's k-factor and funnel can be tracked over the period that matters.+ const params = new URL(req.url, 'http://x').searchParams;+ const days = Math.min(365, Math.max(1, parseInt(params.get('days') || '30', 10)));+ const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();++ // Funnel counts over the window:+ // visits — deduped referral-link visits (referral_visits)+ // sharers — distinct attributed referrers who drove ≥1 visit+ // signups — accounts that signed up referred (users.referred_by_id set)+ // activations — referred accounts that reached their first win+ const [funnel] = await sql`+ select+ (select count(*)::int from referral_visits+ where created_at > ${cutoff}::timestamptz) as visits,+ (select count(distinct referrer_user_id)::int from referral_visits+ where created_at > ${cutoff}::timestamptz and referrer_user_id is not null) as sharers,+ (select count(*)::int from users+ where referred_by_id is not null and deleted_at is null+ and created_at > ${cutoff}::timestamptz) as signups,+ (select count(*)::int from users+ where referred_by_id is not null and deleted_at is null+ and activated_at is not null and activated_at > ${cutoff}::timestamptz) as activations+ `;++ // All-time totals for context (referred members, activated members, rewards paid).+ const [totals] = await sql`+ select+ (select count(*)::int from users+ where referred_by_id is not null and deleted_at is null) as referred_members,+ (select count(*)::int from users+ where referred_by_id is not null and deleted_at is null+ and activated_at is not null) as activated_referred_members,+ (select coalesce(sum(amount_usd),0)::float from credit_ledger+ where ref_type = 'referral_activation' and kind = 'grant') as rewards_paid_usd,+ (select count(*)::int from credit_ledger+ where ref_type = 'referral_activation' and kind = 'grant') as rewards_paid_count+ `;++ // Top referrers by activated referrals (the conversions that actually matter).+ const topReferrers = await sql`+ select+ u.id, u.username, u.display_name,+ count(ru.id)::int as referred_total,+ count(ru.id) filter (where ru.activated_at is not null)::int as activated_total,+ coalesce(u.referral_earnings_total, 0)::bigint as commission_atomics+ from users u+ join users ru on ru.referred_by_id = u.id and ru.deleted_at is null+ where u.deleted_at is null+ group by u.id, u.username, u.display_name, u.referral_earnings_total+ order by activated_total desc, referred_total desc+ limit 20+ `;++ // Daily referred signups vs activations — the trend line for the loop.+ const byDay = await sql`+ select day, sum(signups)::int as signups, sum(activations)::int as activations from (+ select date_trunc('day', created_at)::date as day, count(*) as signups, 0 as activations+ from users+ where referred_by_id is not null and deleted_at is null and created_at > ${cutoff}::timestamptz+ group by 1+ union all+ select date_trunc('day', activated_at)::date as day, 0 as signups, count(*) as activations+ from users+ where referred_by_id is not null and deleted_at is null+ and activated_at is not null and activated_at > ${cutoff}::timestamptz+ group by 1+ ) t+ group by day order by day+ `;++ const visits = Number(funnel.visits || 0);+ const signups = Number(funnel.signups || 0);+ const activations = Number(funnel.activations || 0);+ const sharers = Number(funnel.sharers || 0);++ return json(res, 200, {+ window_days: days,+ funnel: { visits, sharers, signups, activations },+ // k-factor: new referred signups per sharing user this window. >1 = viral.+ k_factor: computeKFactor({ signups, sharers }),+ conversion: {+ visit_to_signup: conversionRate(signups, visits),+ signup_to_activation: conversionRate(activations, signups),+ },+ totals: {+ referred_members: Number(totals.referred_members || 0),+ activated_referred_members: Number(totals.activated_referred_members || 0),+ rewards_paid_usd: Number(totals.rewards_paid_usd || 0),+ rewards_paid_count: Number(totals.rewards_paid_count || 0),+ },+ top_referrers: topReferrers.map((r) => ({+ user_id: r.id,+ username: r.username || null,+ display_name: r.display_name || r.username || null,+ referred_total: Number(r.referred_total || 0),+ activated_total: Number(r.activated_total || 0),+ commission_earned_usd: Number(r.commission_atomics || 0) / 1_000_000,+ })),+ });+ }+return error(res, 404, 'not_found', 'unknown admin resource');});diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 1869f43e9..cf1d68dc9 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -17,6 +17,7 @@ import { parse, loginBody, registerBody, usernameRegisterBody, username as usernimport { sendPasswordResetEmail, sendVerificationEmail } from '../_lib/email.js';import { referralCodeCandidates, normalizeReferralCode } from '../_lib/referrals.js';import { seedDefaultAgent } from '../_lib/seed-default-agent.js';+import { recordEvent } from '../_lib/usage.js';import { logAudit } from '../_lib/audit.js';import { z } from 'zod';@@ -166,6 +167,16 @@ async function handleRegister(req, res) {if (err?.status === 409) return error(res, 409, err.code || 'conflict', err.message);throw err;}+ // Funnel: record the referred signup so visit→signup is measurable. The+ // wallet auth paths (Privy/SIWS/SIWE) attribute later via referral-claim.js,+ // which emits the mirror event.+ if (referred_by_id) {+ recordEvent({+ userId: referred_by_id,+ kind: 'referral_signup',+ meta: { referred_user_id: String(user.id), source: 'signup' },+ });+ }// Fire-and-forget: every new account gets a starter draft agent so the// marketplace's "My Agents" tab and onboarding flow have something to show.queueMicrotask(() => seedDefaultAgent(user.id));diff --git a/api/billing/receipts.js b/api/billing/receipts.jsindex 82cbd46f4..f6daccb56 100644--- a/api/billing/receipts.js+++ b/api/billing/receipts.js@@ -1,12 +1,18 @@/**- * GET /api/billing/receipts?purchase_id=<uuid>- * Returns the signed receipt JSON for a confirmed purchase, auth-gated to the owning user.+ * GET /api/billing/receipts+ *+ * Two receipt forms, both auth-gated to the owning user:+ * ?event_id=<id> — a per-CHARGE receipt from the usage ledger: action,+ * units, price, fee, holder discount applied, the+ * settlement tx link, and the timestamp (api/_lib/metering.js).+ * ?purchase_id=<uuid> — the signed receipt JSON for a confirmed skill purchase.*/import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { getReceipt } from '../_lib/metering.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -21,8 +27,18 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const params = new URL(req.url, 'http://x').searchParams;++ // Per-charge receipt from the usage ledger.+ const eventId = params.get('event_id');+ if (eventId) {+ if (!/^\d+$/.test(eventId)) return error(res, 400, 'bad_request', 'event_id must be numeric');+ const receipt = await getReceipt({ userId, eventId: Number(eventId) });+ if (!receipt) return error(res, 404, 'not_found', 'receipt not found for this charge');+ return json(res, 200, { data: receipt }, { 'cache-control': 'no-store' });+ }+const purchaseId = params.get('purchase_id');- if (!purchaseId) return error(res, 400, 'bad_request', 'purchase_id required');+ if (!purchaseId) return error(res, 400, 'bad_request', 'event_id or purchase_id required');// Verify ownership before returning receiptconst [purchase] = await sql`diff --git a/api/billing/revenue.js b/api/billing/revenue.jsindex 0af9e45d8..63e52ad5b 100644--- a/api/billing/revenue.js+++ b/api/billing/revenue.js@@ -5,6 +5,7 @@ import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { isUuid } from '../_lib/validate.js';+import { reconciliationStatus } from '../_lib/metering.js';const VALID_GRANULARITY = new Set(['day', 'week', 'month']);@@ -162,6 +163,16 @@ export default wrap(async (req, res) => {tsParams,);+ // Reconciliation status — does every metered charge map to a real settlement?+ // Surfaced on the dashboard so an operator sees "all charges reconciled" vs+ // "N unreconciled" without leaving the revenue view. Never fails the read.+ let reconciliation = null;+ try {+ reconciliation = await reconciliationStatus({ userId: user.id });+ } catch {+ reconciliation = null;+ }+return json(res, 200, {summary: {gross_total: Number(summaryRow.gross_total),@@ -194,5 +205,7 @@ export default wrap(async (req, res) => {income_usd: Number(r.income_usd),count: r.count,})),+ // Operator trust signal: usage charges reconciled against on-chain settlements.+ reconciliation,});});diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.jsindex ee44b3135..2e28b52ea 100644--- a/api/cron/irl-reap.js+++ b/api/cron/irl-reap.js@@ -50,7 +50,8 @@ export const REAP_SPIKE_THRESHOLD = 1000;// Pure: is this run's deletion volume anomalous? Sums the three sweep counts and// compares to the threshold. Exported for unit testing — no I/O, no clock.export function reapTotal(counts) {- return (counts?.pins || 0) + (counts?.reports || 0) + (counts?.interactions || 0);+ return (counts?.pins || 0) + (counts?.reports || 0) + (counts?.interactions || 0) ++ (counts?.worldLines || 0) + (counts?.proofs || 0);}export function isReapSpike(counts, threshold = REAP_SPIKE_THRESHOLD) {return reapTotal(counts) >= threshold;@@ -81,11 +82,13 @@ export default wrap(async (req, res) => {// they may not exist yet. A reaper that hard-depended on them would throw// `relation does not exist` and 500 the hourly cron. Probe with to_regclass// and treat a missing table as "nothing to reap" rather than an error.- const [{ pins, reports, interactions }] = await sql`+ const [{ pins, reports, interactions, worldlines, proofs }] = await sql`SELECT- to_regclass('public.irl_pins') AS pins,- to_regclass('public.irl_pin_reports') AS reports,- to_regclass('public.irl_interactions') AS interactions+ to_regclass('public.irl_pins') AS pins,+ to_regclass('public.irl_pin_reports') AS reports,+ to_regclass('public.irl_interactions') AS interactions,+ to_regclass('public.irl_world_lines') AS worldlines,+ to_regclass('public.irl_presence_proofs') AS proofs`;// Expired anon pins, ≥ 1 day past expiry. expires_at IS NULL ⇒ permanent ⇒ kept.@@ -137,10 +140,39 @@ export default wrap(async (req, res) => {reapedInteractions = [...orphaned, ...aged];}+ // World Lines (proof-of-presence AR quests) + their presence proofs. A World Line+ // always carries an expiry (creator-bounded, ≤ 90 days), so it's reaped one day past+ // it — the same grace as anon pins. A presence proof is the visitor's ownable, coarse+ // "I was there" collectible: it carries only a ~1.1 km cell + a salted completer hash+ // (never a coordinate, never a raw device token), so it is NOT a precise location+ // trail to age out — instead it lives as long as its quest and is cascade-deleted the+ // moment the quest is gone, plus an orphan sweep for any proof whose quest vanished.+ // Both are existence-guarded so a fresh DB never 500s.+ let reapedWorldLines = [];+ if (worldlines) {+ reapedWorldLines = await sql`+ DELETE FROM irl_world_lines+ WHERE expires_at IS NOT NULL AND expires_at < NOW() - INTERVAL '1 day'+ RETURNING id+ `;+ }+ let reapedProofs = [];+ if (proofs) {+ reapedProofs = worldlines+ ? await sql`+ DELETE FROM irl_presence_proofs pr+ WHERE NOT EXISTS (SELECT 1 FROM irl_world_lines w WHERE w.id = pr.world_line_id)+ RETURNING pr.id+ `+ : await sql`DELETE FROM irl_presence_proofs RETURNING id`;+ }+const counts = {pins: reapedPins.length,reports: reapedReports.length,interactions: reapedInteractions.length,+ worldLines: reapedWorldLines.length,+ proofs: reapedProofs.length,};const total = reapTotal(counts);@@ -156,7 +188,7 @@ export default wrap(async (req, res) => {if (isReapSpike(counts)) {sendOpsAlert('IRL reaper spike',- `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}) — above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,+ `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}, worldLines ${counts.worldLines}, proofs ${counts.proofs}) — above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,{ signature: `irl-reap:spike:${Math.floor(Date.now() / 3_600_000)}` },);}@@ -166,6 +198,8 @@ export default wrap(async (req, res) => {reapedPins: counts.pins,reapedReports: counts.reports,reapedInteractions: counts.interactions,+ reapedWorldLines: counts.worldLines,+ reapedProofs: counts.proofs,ts: Date.now(),});});diff --git a/api/cron/reconcile-decisions.js b/api/cron/reconcile-decisions.jsnew file mode 100644index 000000000..22b8e7c3c--- /dev/null+++ b/api/cron/reconcile-decisions.js@@ -0,0 +1,153 @@+// GET/POST /api/cron/reconcile-decisions — resolve open ledger predictions+// against real on-chain outcomes, then anchor each agent's chain head.+//+// The Reasoning Ledger captures a snipe as a tamper-evident DECISION at entry+// time (workers/agent-sniper/executor.js → recordDecision). This cron closes the+// loop: when the linked position settles on-chain (agent_sniper_positions.status =+// 'closed', realized P&L proven by the sell signature), it writes the OUTCOME —+// was the call right, and by how much. Idempotent: a decision already reconciled+// is skipped, so re-runs over late/again data never double-count.+//+// After reconciling, it commits each agent's new chain head on-chain via an+// SPL-Memo anchor (best-effort), making the history independently verifiable at+// GET /api/ledger/verify/:agentId. Anomalies (a sudden hit-rate collapse) raise an+// ops alert.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { recordOutcome, getChainEntries, computeReputation, getReputationRecords } from '../_lib/reasoning-ledger.js';+import { anchorLedgerHead, latestAnchoredAnchor } from '../_lib/ledger-anchor.js';++const LAMPORTS_PER_SOL = 1e9;+const MAX_RECONCILE = 1000; // decisions resolved per run+const MAX_ANCHOR_AGENTS = 25; // agents whose head is committed on-chain per run+const ANOMALY_MIN_SAMPLE = 10;+const ANOMALY_HIT_RATE = 0.25;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const report = { reconciled: 0, wins: 0, losses: 0, anchored: 0, anchor_pending: 0, anomalies: 0, errors: 0 };+ const touchedAgents = new Set();++ // 1. Reconcile snipe decisions whose position has settled on-chain.+ let pending = [];+ try {+ pending = await sql`+ select d.id as decision_id, d.agent_id,+ p.realized_pnl_lamports, p.realized_pnl_pct, p.sell_sig, p.exit_reason, p.closed_at+ from agent_decisions d+ join agent_sniper_positions p on p.id = (d.inputs->>'position_id')::uuid+ left join decision_outcomes o on o.decision_id = d.id+ where d.kind = 'snipe' and o.decision_id is null and p.status = 'closed'+ order by p.closed_at asc+ limit ${MAX_RECONCILE}+ `;+ } catch (err) {+ report.errors++;+ report.reconcile_error = err.message;+ }++ for (const row of pending) {+ try {+ const pnlLamports = BigInt(row.realized_pnl_lamports ?? 0);+ const pnlSol = Number(pnlLamports) / LAMPORTS_PER_SOL;+ const wasCorrect = pnlLamports > 0n;+ const out = await recordOutcome({+ decisionId: row.decision_id,+ agentId: row.agent_id,+ observed: {+ pnl_sol: Number(pnlSol.toFixed(6)),+ pnl_pct: row.realized_pnl_pct != null ? Number(row.realized_pnl_pct) : null,+ sell_sig: row.sell_sig && row.sell_sig !== 'SIMULATED' ? row.sell_sig : null,+ exit_reason: row.exit_reason || null,+ closed_at: row.closed_at,+ },+ wasCorrect,+ pnlSol: Number(pnlSol.toFixed(6)),+ impact: Number(pnlSol.toFixed(6)),+ });+ if (out.reconciled) {+ report.reconciled++;+ report[wasCorrect ? 'wins' : 'losses']++;+ touchedAgents.add(row.agent_id);+ }+ } catch {+ report.errors++;+ }+ }++ // 2. Anchor each agent whose chain head moved past its last on-chain commitment.+ let heads = [];+ try {+ heads = await sql`+ select agent_id, max(seq) as head_seq, count(*)::bigint as cnt+ from agent_decisions group by agent_id+ `;+ } catch (err) {+ report.errors++;+ report.heads_error = err.message;+ }++ let anchoredCount = 0;+ for (const h of heads) {+ if (anchoredCount >= MAX_ANCHOR_AGENTS) break;+ try {+ const anchor = await latestAnchoredAnchor(h.agent_id);+ if (anchor && Number(anchor.through_seq) >= Number(h.head_seq)) continue; // already committed+ const [head] = await sql`+ select entry_hash, network from agent_decisions+ where agent_id = ${h.agent_id} and seq = ${Number(h.head_seq)} limit 1+ `;+ if (!head) continue;+ anchoredCount++;+ const r = await anchorLedgerHead({+ agentId: h.agent_id,+ network: head.network || 'mainnet',+ headHash: head.entry_hash,+ throughSeq: Number(h.head_seq),+ entryCount: Number(h.cnt),+ });+ if (r.status === 'anchored' || r.status === 'deduped') report.anchored++;+ else report.anchor_pending++;+ } catch {+ report.errors++;+ }+ }++ // 3. Anomaly watch: a verified track record that suddenly collapses is worth+ // surfacing — it can mean a broken strategy or market regime change.+ for (const agentId of touchedAgents) {+ try {+ const records = await getReputationRecords(agentId);+ const rep = computeReputation(records);+ if (rep.sample_size >= ANOMALY_MIN_SAMPLE && rep.hit_rate < ANOMALY_HIT_RATE) {+ report.anomalies++;+ sendOpsAlert(+ 'Reasoning ledger: hit-rate collapse',+ `Agent ${agentId} hit rate ${(rep.hit_rate * 100).toFixed(0)}% over ${rep.sample_size} reconciled calls (score ${rep.score}).`,+ { signature: `ledger-anomaly:${agentId}` },+ );+ }+ } catch {+ report.errors++;+ }+ }++ return json(res, 200, { ok: true, ...report, t: Date.now() });+});++export { getChainEntries }; // re-exported for symmetry with sibling crons' test importsdiff --git a/api/genome/preview.js b/api/genome/preview.jsnew file mode 100644index 000000000..4b2f3772f--- /dev/null+++ b/api/genome/preview.js@@ -0,0 +1,77 @@+// POST /api/genome/preview — predict the offspring of two agents BEFORE breeding.+//+// Derives the child genome deterministically from both parents and a seed (echoed+// back so a subsequent /breed with the same seed produces exactly the previewed+// child — what you see is what you breed). Returns the full trait blend, the real+// ElevenLabs voice settings + voice_id the child would carry (so the UI can play a+// genuine sample via /api/tts/eleven), the bakeable body appearance, the skill+// alleles (expressed + recessive + emergent), recorded mutations, and the pedigree+// tier. Read-only: nothing is minted, no wallet provisioned.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { deriveGenome, makeSeed } from '../_lib/genome.js';+import {+ loadBreedingAgent,+ agentGenome,+ eligibilityFor,+ publicGenome,+} from '../_lib/genome-agent.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req, 'avatars:write');+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to preview breeding');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many previews — slow down');++ const body = await readJson(req);+ const parentAId = String(body.parent_a || body.parent_a_agent_id || '').trim();+ const parentBId = String(body.parent_b || body.parent_b_agent_id || '').trim();+ if (!isUuid(parentAId) || !isUuid(parentBId)) {+ return error(res, 400, 'validation_error', 'parent_a and parent_b agent ids are required');+ }+ if (parentAId === parentBId) {+ return error(res, 400, 'validation_error', 'an agent cannot breed with itself');+ }++ const [rowA, rowB] = await Promise.all([loadBreedingAgent(parentAId), loadBreedingAgent(parentBId)]);+ if (!rowA || !rowB) return error(res, 404, 'not_found', 'one or both parents not found');++ const eligA = eligibilityFor(rowA, auth.userId);+ const eligB = eligibilityFor(rowB, auth.userId);+ if (!eligA.allowed) return error(res, 403, 'parent_ineligible', `parent A: ${eligA.reason}`, { parent: 'a', reason: eligA.reason });+ if (!eligB.allowed) return error(res, 403, 'parent_ineligible', `parent B: ${eligB.reason}`, { parent: 'b', reason: eligB.reason });++ const seed = typeof body.seed === 'string' && body.seed ? body.seed.slice(0, 64) : makeSeed();+ const childName = (typeof body.name === 'string' && body.name.trim()) || `${rowA.name} × ${rowB.name}`;+ const child = deriveGenome({ parentA: agentGenome(rowA), parentB: agentGenome(rowB), seed });++ const feeThree = (eligA.fee_three || 0) + (eligB.fee_three || 0);++ return json(res, 200, {+ seed,+ child_name: childName,+ genome: publicGenome(child, childName),+ parents: {+ a: { id: rowA.id, name: rowA.name, cross_owner: eligA.cross_owner, fee_three: eligA.fee_three || 0 },+ b: { id: rowB.id, name: rowB.name, cross_owner: eligB.cross_owner, fee_three: eligB.fee_three || 0 },+ },+ stud_fee_three: feeThree,+ consent_required: eligA.cross_owner || eligB.cross_owner,+ });+});++async function resolveAuth(req, requiredScope) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (!bearer) return null;+ if (!hasScope(bearer.scope, requiredScope)) return null;+ return bearer;+}diff --git a/api/irl/world-lines.js b/api/irl/world-lines.jsnew file mode 100644index 000000000..a100da1ef--- /dev/null+++ b/api/irl/world-lines.js@@ -0,0 +1,923 @@+/**+ * IRL World Lines — agent-placed proof-of-presence AR quests.+ *+ * A World Line is a persistent, location-anchored AR quest left by an agent. To+ * complete it, a person must physically travel to the spot, prove co-location, and+ * finish the agent-driven interaction in AR. On success the agent's OWN wallet+ * cryptographically signs a proof-of-presence — independently verifiable, ownable as+ * a collectible — without any precise coordinate ever entering the proof, a log, or+ * an alert.+ *+ * POST /api/irl/world-lines create a World Line (auth + owned agent + owned pin)+ * GET /api/irl/world-lines/nearby fix-gated, co-located discovery (lat/lng + x-irl-fix)+ * GET /api/irl/world-lines/browse public region listing (coarse, no coordinates)+ * GET /api/irl/world-lines/mine creator dashboard (completions + coarse heatmap)+ * GET /api/irl/world-lines/collectibles the caller's earned proofs (profile/wallet)+ * GET /api/irl/world-lines/:id single World Line (fix-gated for the AR detail)+ * POST /api/irl/world-lines/challenge issue a single-use completion nonce (co-located)+ * POST /api/irl/world-lines/complete the proof ceremony → agent-signed collectible+ * GET /api/irl/world-lines/verify/:proofId re-check the agent signature (public)+ *+ * PRIVACY CONTRACT (mirrors api/irl/pins.js): the only surface that ever reveals a+ * precise spot is the existing fix-gated pin proximity read. A World Line stores only+ * its anchor pin_id + a coarse (~1.1 km, precision-6) cell. Co-location is ALWAYS+ * server-derived — the caller's claimed point is anti-spoofed by the fix token and+ * checked against the pin's server-side coordinates; the body is never trusted. No+ * proof, nonce, notification, or log line carries a coordinate or a raw device token.+ */++import { cors, json, wrap, rateLimited, readJson } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { readDeviceToken } from '../_lib/irl-auth.js';+import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';+import { insertNotification } from '../_lib/notify.js';+import { isUuid } from '../_lib/validate.js';+import { encodeGeohash } from '../_lib/geohash.js';+import { WORD_BLACKLIST } from '../../src/profanity.js';+import {+ coarseCell, isCoarseCell, normalizeChallengeSpec, normalizeRewardKind, normalizeDifficulty,+ canonicalProofMessage, completerHash, signPresenceProof, verifyPresenceProof,+ mintPresenceNonce, verifyPresenceNonce, TITLE_MAX, PROMPT_MAX,+} from '../_lib/world-lines.js';++// Region cell (~5 km, precision-5) — the public-browse aggregation unit, deliberately+// coarser than the proof's ~1.1 km cell so the discovery map only ever says "N quests+// around this area," never anything that could localise one quest precisely.+const REGION_CELL_PRECISION = 5;++// Co-location radius: a completion's claimed point (anti-spoofed by the fix token)+// must be within this of the anchor pin's server-side coordinates. A touch wider than+// the 60 m pin proximity read to tolerate the GPS jitter at the exact moment someone+// taps "complete," far too tight to satisfy from across town.+const COLOCATION_RADIUS_M = 80;++// Discovery radius: how far away a walking explorer can SEE a quest to head toward it.+// Wider than the 60 m pin proximity (which alone resolves the precise AR anchor), so+// the game says "a quest is ~200 m north" while the exact spot still only materialises+// once you're on top of it via the pin feed. Coarse distance only.+const NEARBY_DEFAULT_RADIUS_M = 250;+const NEARBY_MAX_RADIUS_M = 600;++const MAX_WORLD_LINES_PER_OWNER = 30; // active quests one creator can run at once+const MAX_PER_REGION = 200; // safety ceiling per ~5 km region+const DEFAULT_LIFETIME_DAYS = 30;+const MAX_LIFETIME_DAYS = 90;+const MAX_COMPLETIONS_CAP = 100_000; // an explicit sane bound on the cap field++// $THREE is the only coin three.ws references. The off-brand guard is generic by+// construction (it never names a competing ticker) — same logic the pin feed uses.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+function hardBlocked(text) {+ const t = String(text || '').toLowerCase();+ return WORD_BLACKLIST.some((w) => t.includes(w));+}+function namesOffBrandCoin(text) {+ const t = String(text || '');+ const cashtags = t.match(/\$[A-Za-z][A-Za-z0-9]{1,9}\b/g) || [];+ if (cashtags.some((c) => c.slice(1).toUpperCase() !== 'THREE')) return true;+ const tokens = t.match(/\b[1-9A-HJ-NP-Za-km-z]{32,48}\b/g) || [];+ if (tokens.some((m) => /pump$/.test(m) && m !== THREE_MINT)) return true;+ return false;+}+// A pin id is a server-minted UUID; accept that plus a conservative opaque-id shape.+const PIN_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const PIN_ID_SAFE_RE = /^[A-Za-z0-9_-]{1,64}$/;+function isValidPinId(id) {+ return typeof id === 'string' && !!id && (PIN_UUID_RE.test(id) || PIN_ID_SAFE_RE.test(id));+}++function haversineM(lat1, lng1, lat2, lng2) {+ const R = 6371000;+ const toRad = (d) => (d * Math.PI) / 180;+ const dLat = toRad(lat2 - lat1);+ const dLng = toRad(lng2 - lng1);+ const a = Math.sin(dLat / 2) ** 2+ + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(a)));+}++let _tableReady = false;+async function ensureTables() {+ if (_tableReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS irl_world_lines (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ creator_user_id UUID,+ creator_device TEXT,+ agent_id UUID NOT NULL,+ signer_pubkey TEXT NOT NULL,+ pin_id UUID NOT NULL,+ coarse_cell TEXT NOT NULL,+ region_cell TEXT NOT NULL,+ title TEXT NOT NULL,+ prompt TEXT,+ challenge_spec JSONB NOT NULL,+ reward_kind TEXT NOT NULL DEFAULT 'collectible',+ reward_ref TEXT,+ reward_meta JSONB,+ difficulty TEXT NOT NULL DEFAULT 'easy',+ max_completions INTEGER,+ completion_count INTEGER NOT NULL DEFAULT 0,+ hidden_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ expires_at TIMESTAMPTZ+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS irl_world_lines_cell ON irl_world_lines (coarse_cell) WHERE hidden_at IS NULL`;+ await sql`CREATE INDEX IF NOT EXISTS irl_world_lines_region ON irl_world_lines (region_cell) WHERE hidden_at IS NULL`;+ await sql`CREATE INDEX IF NOT EXISTS irl_world_lines_pin ON irl_world_lines (pin_id)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_world_lines_expires ON irl_world_lines (expires_at)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_world_lines_creator ON irl_world_lines (creator_user_id)`;++ await sql`+ CREATE TABLE IF NOT EXISTS irl_presence_proofs (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ world_line_id UUID NOT NULL,+ agent_id UUID,+ signer_pubkey TEXT NOT NULL,+ coarse_cell TEXT NOT NULL,+ nonce_id TEXT NOT NULL,+ completer_hash TEXT NOT NULL,+ completer_user_id UUID,+ completer_device TEXT,+ signature TEXT NOT NULL,+ signed_message TEXT NOT NULL,+ challenge_kind TEXT,+ collectible_mint TEXT,+ collectible_name TEXT,+ reward_kind TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW()+ )+ `;+ // nonce_id UNIQUE → one settled proof per server-issued nonce (idempotency + replay+ // guard). (world_line_id, completer_hash) UNIQUE → one proof per visitor per quest.+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS irl_presence_proofs_nonce ON irl_presence_proofs (nonce_id)`;+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS irl_presence_proofs_once ON irl_presence_proofs (world_line_id, completer_hash)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_presence_proofs_wl ON irl_presence_proofs (world_line_id, created_at DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_presence_proofs_user ON irl_presence_proofs (completer_user_id, created_at DESC)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_presence_proofs_device ON irl_presence_proofs (completer_device, created_at DESC)`;+ _tableReady = true;+}++// ── Routing ──────────────────────────────────────────────────────────────────+// Parse the action segment after /api/irl/world-lines. vercel.json rewrites the+// sub-paths to this one function (mirrors how /api/irl/pins/mine routes to pins.js).+function routeOf(req) {+ const path = String(req.url || '').split('?')[0].replace(/\/+$/, '');+ const m = path.match(/\/api\/irl\/world-lines\/?(.*)$/);+ const rest = m ? m[1] : '';+ if (!rest) return { action: 'root' };+ const [first, second] = rest.split('/');+ if (first === 'verify') return { action: 'verify', id: second || null };+ const KNOWN = new Set(['nearby', 'browse', 'mine', 'collectibles', 'challenge', 'complete']);+ if (KNOWN.has(first)) return { action: first };+ return { action: 'detail', id: first };+}++const isLive = `hidden_at IS NULL AND (expires_at IS NULL OR expires_at > NOW())`;++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'], credentials: true });+ if (req.method === 'OPTIONS') return res.end();++ await ensureTables();+ const { action, id } = routeOf(req);++ if (req.method === 'GET') {+ // Public reads share the generic per-IP read ceiling; the fix-gated reads add+ // the proof-of-presence binding on top so a quest's spot can't be browsed remotely.+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+ if (action === 'nearby') return handleNearby(req, res);+ if (action === 'browse') return handleBrowse(req, res);+ if (action === 'mine') return handleMine(req, res);+ if (action === 'collectibles') return handleCollectibles(req, res);+ if (action === 'verify') return handleVerify(req, res, id);+ if (action === 'detail') return handleDetail(req, res, id);+ return json(res, 404, { error: 'unknown world-lines route' });+ }++ if (req.method === 'POST') {+ if (action === 'challenge') return handleChallenge(req, res);+ if (action === 'complete') return handleComplete(req, res);+ if (action === 'root') return handleCreate(req, res);+ return json(res, 404, { error: 'unknown world-lines route' });+ }++ return json(res, 405, { error: 'method not allowed' });+});++// ── Co-location ──────────────────────────────────────────────────────────────+// Resolve, server-side, whether the caller is genuinely at a World Line's anchor.+// Returns { ok:true, cell } or { ok:false, status, body }. The claimed lat/lng is+// validated by the fix token (proves a real recent GPS fix near the claim) AND then+// checked against the anchor pin's server-side coordinates — the body is never+// trusted for the distance check. The coarse cell returned is derived from the pin,+// not the caller, so it matches the World Line exactly.+async function resolveColocation(req, body, wl) {+ const lat = parseFloat(body.lat);+ const lng = parseFloat(body.lng);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {+ return { ok: false, status: 400, body: { error: 'lat and lng are required' } };+ }+ // Proof-of-presence: bind to a genuine fix when enforced (prod). Dev/preview without+ // IRL_FIX_SECRET skips the token (same posture as the pins read) but STILL runs the+ // server-side distance check below, so co-location is never simply trusted.+ if (fixEnforced()) {+ const fixHeader = req.headers['x-irl-fix'];+ const fixToken = Array.isArray(fixHeader) ? fixHeader[0] : fixHeader;+ const v = await verifyFixToken(fixToken, lat, lng);+ if (!v.ok) {+ return {+ ok: false, status: 401,+ body: { error: 'fix_required', reason: v.reason, error_description: 'a fresh location fix is required' },+ };+ }+ }+ // The anchor pin holds the precise coordinate (gated, never returned here). Read it+ // server-side only to compute the co-location boolean.+ const [pin] = await sql`+ SELECT lat, lng FROM irl_pins+ WHERE id = ${wl.pin_id} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ LIMIT 1+ `;+ if (!pin) {+ return { ok: false, status: 410, body: { error: 'anchor_gone', error_description: 'this quest’s anchor is no longer placed' } };+ }+ const dist = haversineM(lat, lng, pin.lat, pin.lng);+ if (dist > COLOCATION_RADIUS_M) {+ return {+ ok: false, status: 403,+ body: { error: 'not_colocated', error_description: 'travel to the quest to complete it', within_m: COLOCATION_RADIUS_M },+ };+ }+ return { ok: true, cell: wl.coarse_cell };+}++// ── Create ───────────────────────────────────────────────────────────────────+async function handleCreate(req, res) {+ const rl = await limits.worldLineCreateIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const session = await getSessionUser(req).catch(() => null);+ // Creation is accountable: the agent's custodial wallet signs every proof this quest+ // mints, so the creator must be a signed-in owner of that agent. Anonymous device+ // placements (which have no agent wallet) can't author a signing quest.+ if (!session) return json(res, 401, { error: 'sign in to place a World Line' });+ if (!(await requireCsrf(req, res, session.id))) return; // CSRF on the authed write++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return json(res, err.status || 400, { error: err.message || 'invalid body' });+ }++ const pinId = body.pinId;+ if (!isValidPinId(pinId)) return json(res, 400, { error: 'a valid pinId is required' });++ // The caller must own the anchor pin (it carries the precise spot). Read its coords+ // server-side to derive the coarse + region cells — never trusted from the body.+ const [pin] = await sql`+ SELECT id, user_id, agent_id, lat, lng FROM irl_pins+ WHERE id = ${pinId} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ LIMIT 1+ `;+ if (!pin) return json(res, 404, { error: 'pin not found' });+ if (!pin.user_id || pin.user_id !== session.id) {+ return json(res, 403, { error: 'you can only anchor a World Line to your own pin' });+ }++ // The signing agent: the pin's agent, or a caller-supplied agent they own.+ const agentId = isUuid(body.agentId) ? body.agentId : (pin.agent_id || null);+ if (!agentId) return json(res, 400, { error: 'this pin has no agent; pass an agentId you own' });+ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1+ `;+ if (!agent) return json(res, 404, { error: 'agent not found' });+ if (agent.user_id !== session.id) {+ return json(res, 403, { error: 'you can only sign quests with an agent you own' });+ }++ // Title + prompt: the public, agent-spoken content. Same content floor as a pin+ // caption — slur gate + $THREE-only coin guard — so a quest can't shill or abuse.+ const title = String(body.title ?? '').replace(/\s+/g, ' ').trim().slice(0, TITLE_MAX);+ if (!title) return json(res, 400, { error: 'a title is required' });+ if (hardBlocked(title) || namesOffBrandCoin(title)) {+ return json(res, 422, { error: 'content', field: 'title', message: 'That title isn’t allowed. A quest can only reference $THREE.' });+ }+ const prompt = body.prompt != null ? String(body.prompt).replace(/\s+/g, ' ').trim().slice(0, PROMPT_MAX) : '';+ if (prompt && (hardBlocked(prompt) || namesOffBrandCoin(prompt))) {+ return json(res, 422, { error: 'content', field: 'prompt', message: 'That prompt isn’t allowed. A quest can only reference $THREE.' });+ }++ const challenge = normalizeChallengeSpec(body.challenge ?? body.challenge_spec);+ if (!challenge.ok) return json(res, 400, { error: 'challenge', message: challenge.error });+ // Quest prompt/phrase/question text gets the same content gate.+ for (const field of ['prompt', 'question']) {+ const v = challenge.spec[field];+ if (v && (hardBlocked(v) || namesOffBrandCoin(v))) {+ return json(res, 422, { error: 'content', field, message: 'That text isn’t allowed. A quest can only reference $THREE.' });+ }+ }++ const rewardKind = normalizeRewardKind(body.reward_kind ?? body.rewardKind);+ const rewardRef = body.reward_ref != null ? String(body.reward_ref).slice(0, 80) : null;+ const difficulty = normalizeDifficulty(body.difficulty);++ let maxCompletions = null;+ const rawMax = Number(body.max_completions ?? body.maxCompletions);+ if (Number.isInteger(rawMax) && rawMax > 0) maxCompletions = Math.min(MAX_COMPLETIONS_CAP, rawMax);++ const lifetimeDays = Math.min(MAX_LIFETIME_DAYS, Math.max(1,+ Number.isFinite(Number(body.lifetime_days)) ? Number(body.lifetime_days) : DEFAULT_LIFETIME_DAYS));+ const expiresAt = new Date(Date.now() + lifetimeDays * 86400_000).toISOString();++ const cell = coarseCell(pin.lat, pin.lng);+ const region = encodeGeohash(pin.lat, pin.lng, REGION_CELL_PRECISION);+ if (!isCoarseCell(cell)) return json(res, 400, { error: 'pin location is not placeable' });++ // Per-owner active-quest cap + a per-region safety ceiling.+ const [{ owned }] = await sql`+ SELECT count(*)::int AS owned FROM irl_world_lines+ WHERE creator_user_id = ${session.id} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ `;+ if (owned >= MAX_WORLD_LINES_PER_OWNER) {+ return json(res, 429, { error: 'quest_limit', limit: MAX_WORLD_LINES_PER_OWNER, message: 'You’ve reached your active World Line limit. Retire one to place another.' });+ }+ const [{ inRegion }] = await sql`+ SELECT count(*)::int AS "inRegion" FROM irl_world_lines+ WHERE region_cell = ${region} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ `;+ if (inRegion >= MAX_PER_REGION) {+ return json(res, 429, { error: 'region_full', message: 'This region already has the maximum number of quests.' });+ }++ // Capture the agent's signing public key now, so verification is anchored to the key+ // in force at creation. ensureAgentWallet is idempotent (provisions on first need).+ let signerPubkey;+ try {+ const { ensureAgentWallet } = await import('../_lib/agent-wallet.js');+ const w = await ensureAgentWallet(agentId, session.id, { reason: 'world-line:create' });+ signerPubkey = w.address;+ } catch (err) {+ console.error('[irl/world-lines] could not provision agent signer', { agentId, message: err?.message });+ return json(res, 502, { error: 'could not provision the agent’s signing wallet' });+ }++ const [row] = await sql`+ INSERT INTO irl_world_lines+ (creator_user_id, agent_id, signer_pubkey, pin_id, coarse_cell, region_cell,+ title, prompt, challenge_spec, reward_kind, reward_ref, difficulty,+ max_completions, expires_at)+ VALUES (+ ${session.id}, ${agentId}, ${signerPubkey}, ${pinId}, ${cell}, ${region},+ ${title}, ${prompt || null}, ${JSON.stringify(challenge.spec)}::jsonb,+ ${rewardKind}, ${rewardRef}, ${difficulty}, ${maxCompletions}, ${expiresAt}+ )+ RETURNING id, agent_id, signer_pubkey, pin_id, coarse_cell, region_cell, title,+ prompt, challenge_spec, reward_kind, reward_ref, difficulty,+ max_completions, completion_count, created_at, expires_at+ `;+ return json(res, 201, { world_line: publicWorldLine(row, { owner: true }) });+}++// ── Nearby (fix-gated, co-located discovery) ─────────────────────────────────+async function handleNearby(req, res) {+ const lat = parseFloat(req.query.lat);+ const lng = parseFloat(req.query.lng);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {+ return json(res, 400, { error: 'lat and lng are required' });+ }+ const rawRadius = req.query.radius;+ const parsed = rawRadius == null || rawRadius === '' ? NEARBY_DEFAULT_RADIUS_M : parseFloat(rawRadius);+ if (!Number.isFinite(parsed)) return json(res, 400, { error: 'invalid radius' });+ const radius = Math.min(NEARBY_MAX_RADIUS_M, Math.max(30, parsed));++ // Same fix-gate as the pin proximity read: a quest's location is only revealed to a+ // caller proven to be standing near it.+ if (fixEnforced()) {+ const fixHeader = req.headers['x-irl-fix'];+ const fixToken = Array.isArray(fixHeader) ? fixHeader[0] : fixHeader;+ const v = await verifyFixToken(fixToken, lat, lng);+ if (!v.ok) return json(res, 401, { error: 'fix_required', reason: v.reason });+ }++ const latDelta = radius / 110540;+ const lngDelta = radius / (111320 * Math.cos(lat * Math.PI / 180) || 1);++ const session = await getSessionUser(req).catch(() => null);+ const myId = session?.id ?? null;+ const myDev = readDeviceToken(req);++ // Join to the anchor pin for the proximity filter (precise coords used only to+ // compute a coarse distance, never returned). The completer's own completion state+ // is surfaced so the client can render "already done" without leaking who else did.+ const myHash = await completerHash(myId ?? myDev ?? '');+ const rows = await sql`+ SELECT w.id, w.agent_id, w.signer_pubkey, w.pin_id, w.coarse_cell, w.title, w.prompt,+ w.challenge_spec, w.reward_kind, w.reward_ref, w.difficulty,+ w.max_completions, w.completion_count, w.created_at, w.expires_at,+ p.lat AS pin_lat, p.lng AS pin_lng,+ EXISTS (SELECT 1 FROM irl_presence_proofs pr+ WHERE pr.world_line_id = w.id AND pr.completer_hash = ${myHash}) AS mine_done+ FROM irl_world_lines w+ JOIN irl_pins p ON p.id = w.pin_id+ WHERE w.hidden_at IS NULL+ AND (w.expires_at IS NULL OR w.expires_at > NOW())+ AND p.hidden_at IS NULL AND (p.expires_at IS NULL OR p.expires_at > NOW())+ AND p.lat BETWEEN ${lat - latDelta} AND ${lat + latDelta}+ AND p.lng BETWEEN ${lng - lngDelta} AND ${lng + lngDelta}+ ORDER BY w.created_at DESC+ LIMIT 50+ `;++ const quests = rows+ .map((r) => {+ const distance = Math.round(haversineM(lat, lng, r.pin_lat, r.pin_lng));+ return { r, distance };+ })+ .filter(({ distance }) => distance <= radius)+ .sort((a, b) => a.distance - b.distance)+ .map(({ r, distance }) => ({+ ...publicWorldLine(r, { owner: !!myId && false }),+ // Distance coarsened to 10 m — enough to render an arrow + "≈200 m" without+ // triangulating the exact spot from successive reads.+ distance_m: Math.max(0, Math.round(distance / 10) * 10),+ completed_by_me: r.mine_done === true,+ capacity_reached: r.max_completions != null && r.completion_count >= r.max_completions,+ }));++ return json(res, 200, { world_lines: quests });+}++// ── Browse (public, coarse region listing — no coordinates) ──────────────────+async function handleBrowse(req, res) {+ const difficulty = req.query.difficulty;+ const diffFilter = difficulty && ['easy', 'medium', 'hard'].includes(String(difficulty)) ? String(difficulty) : null;+ const region = typeof req.query.region === 'string' && /^[0-9bcdefghjkmnpqrstuvwxyz]{5}$/.test(req.query.region)+ ? req.query.region : null;++ if (region) {+ // One region's active quests — title/reward/difficulty + live completion stats.+ // Still NO coordinate: the AR spot only ever resolves through the fix-gated feeds.+ const rows = diffFilter+ ? await sql`+ SELECT id, title, reward_kind, difficulty, completion_count, max_completions, created_at+ FROM irl_world_lines+ WHERE region_cell = ${region} AND difficulty = ${diffFilter} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ ORDER BY created_at DESC LIMIT 60`+ : await sql`+ SELECT id, title, reward_kind, difficulty, completion_count, max_completions, created_at+ FROM irl_world_lines+ WHERE region_cell = ${region} AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ ORDER BY created_at DESC LIMIT 60`;+ return json(res, 200, {+ region,+ quests: rows.map((r) => ({+ id: r.id, title: r.title, reward_kind: r.reward_kind, difficulty: r.difficulty,+ completion_count: r.completion_count,+ capacity_reached: r.max_completions != null && r.completion_count >= r.max_completions,+ })),+ });+ }++ // Region roll-up: how many active quests per ~5 km region. Pure aggregate, the+ // privacy-safe "where in the world are quests" map.+ const rows = await sql`+ SELECT region_cell, count(*)::int AS quests,+ count(*) FILTER (WHERE difficulty = 'hard')::int AS hard,+ sum(completion_count)::int AS completions+ FROM irl_world_lines+ WHERE hidden_at IS NULL AND (expires_at IS NULL OR expires_at > NOW())+ GROUP BY region_cell+ ORDER BY quests DESC+ LIMIT 200+ `;+ res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=300');+ return json(res, 200, { regions: rows });+}++// ── Single World Line (fix-gated, for the AR detail view) ────────────────────+async function handleDetail(req, res, id) {+ if (!isUuid(id)) return json(res, 400, { error: 'invalid world line id' });+ const [w] = await sql`+ SELECT w.id, w.agent_id, w.signer_pubkey, w.pin_id, w.coarse_cell, w.title, w.prompt,+ w.challenge_spec, w.reward_kind, w.reward_ref, w.difficulty,+ w.max_completions, w.completion_count, w.created_at, w.expires_at,+ p.lat AS pin_lat, p.lng AS pin_lng, p.hidden_at AS pin_hidden, p.expires_at AS pin_expires+ FROM irl_world_lines w+ JOIN irl_pins p ON p.id = w.pin_id+ WHERE w.id = ${id} AND w.hidden_at IS NULL AND (w.expires_at IS NULL OR w.expires_at > NOW())+ LIMIT 1+ `;+ if (!w) return json(res, 404, { error: 'world line not found' });++ // The challenge_spec includes the quiz/phrase ANSWER, which must not be handed to a+ // caller who hasn't proven they're at the spot (it would let them pre-solve remotely).+ // Resolve co-location; on success return the full spec, otherwise a redacted spec ++ // the coarse cell so the "travel here" state can still render.+ const lat = parseFloat(req.query.lat);+ const lng = parseFloat(req.query.lng);+ let colocated = false;+ if (Number.isFinite(lat) && Number.isFinite(lng)) {+ const co = await resolveColocation(req, { lat, lng }, w);+ colocated = co.ok;+ }+ return json(res, 200, { world_line: publicWorldLine(w, { revealAnswer: colocated }), colocated });+}++// ── Challenge (issue a single-use completion nonce) ──────────────────────────+async function handleChallenge(req, res) {+ const rl = await limits.worldLineChallengeIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return json(res, err.status || 400, { error: err.message || 'invalid body' });+ }+ const wlId = body.world_line_id ?? body.worldLineId ?? body.id;+ if (!isUuid(wlId)) return json(res, 400, { error: 'a valid world_line_id is required' });++ const wl = await loadWorldLine(wlId);+ if (!wl) return json(res, 404, { error: 'world line not found' });+ if (wl.max_completions != null && wl.completion_count >= wl.max_completions) {+ return json(res, 409, { error: 'capacity_reached', message: 'This quest has reached its completion limit.' });+ }++ const co = await resolveColocation(req, body, wl);+ if (!co.ok) return json(res, co.status, co.body);++ // Already completed by this visitor? Surface the existing proof so the client renders+ // the "already done" state instead of a fresh nonce.+ const session = await getSessionUser(req).catch(() => null);+ const who = await completerHash(session?.id ?? readDeviceToken(req) ?? '');+ const [existing] = await sql`+ SELECT id, collectible_mint FROM irl_presence_proofs+ WHERE world_line_id = ${wlId} AND completer_hash = ${who} LIMIT 1+ `;+ if (existing) {+ return json(res, 200, { already_completed: true, proof_id: existing.id, collectible_mint: existing.collectible_mint });+ }++ const minted = await mintPresenceNonce(wlId, wl.coarse_cell);+ if (!minted) return json(res, 500, { error: 'could not issue a challenge' });+ return json(res, 200, {+ nonce: minted.nonce,+ expires_in: minted.expires_in,+ challenge: revealedSpec(wl.challenge_spec, true),+ agent_id: wl.agent_id,+ world_line: { id: wl.id, title: wl.title, prompt: wl.prompt, reward_kind: wl.reward_kind, reward_ref: wl.reward_ref },+ });+}++// ── Complete (the proof ceremony) ────────────────────────────────────────────+async function handleComplete(req, res) {+ const rl = await limits.worldLineCompleteIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return json(res, err.status || 400, { error: err.message || 'invalid body' });+ }+ const wlId = body.world_line_id ?? body.worldLineId ?? body.id;+ if (!isUuid(wlId)) return json(res, 400, { error: 'a valid world_line_id is required' });+ const nonce = body.nonce;+ if (typeof nonce !== 'string' || !nonce) return json(res, 400, { error: 'a completion nonce is required' });++ const wl = await loadWorldLine(wlId);+ if (!wl) return json(res, 404, { error: 'world line not found' });++ // 1) Server-derived co-location (re-checked at completion, never trusted from body).+ const co = await resolveColocation(req, body, wl);+ if (!co.ok) return json(res, co.status, co.body);++ // 2) The nonce must be unforged, unexpired, and bound to THIS quest + coarse cell.+ const nv = await verifyPresenceNonce(nonce, wlId, wl.coarse_cell);+ if (!nv.ok) {+ const status = nv.reason === 'expired' ? 410 : 403;+ return json(res, status, { error: 'invalid_nonce', reason: nv.reason, message: 'Your challenge expired or was invalid — tap to try again.' });+ }++ // 3) The interaction itself, where the server CAN check it (quiz/phrase). For 'tap'+ // the challenge is presence, already proven above.+ const spec = wl.challenge_spec || {};+ const interactionError = checkInteraction(spec, body);+ if (interactionError) return json(res, 422, { error: 'challenge_failed', message: interactionError });++ const session = await getSessionUser(req).catch(() => null);+ const completerUserId = session?.id ?? null;+ const completerDevice = readDeviceToken(req);+ const who = await completerHash(completerUserId ?? completerDevice ?? '');++ // 4) Idempotency / one-per-visitor: if this visitor already has a proof for this+ // quest, return it unchanged rather than minting a second collectible.+ const [already] = await sql`+ SELECT * FROM irl_presence_proofs WHERE world_line_id = ${wlId} AND completer_hash = ${who} LIMIT 1+ `;+ if (already) return json(res, 200, { already_completed: true, proof: publicProof(already), collectible: collectibleOf(already) });++ // 5) Capacity (re-checked just before the signing mint).+ if (wl.max_completions != null && wl.completion_count >= wl.max_completions) {+ return json(res, 409, { error: 'capacity_reached', message: 'This quest has reached its completion limit.' });+ }++ // 6) The agent wallet signs the canonical proof-of-presence message.+ const message = canonicalProofMessage({+ worldLineId: wlId, coarseCell: wl.coarse_cell, nonceId: nv.nonceId, completerHash: who,+ });+ let signed;+ try {+ signed = await signWithAgent(wl.agent_id, completerUserId, message);+ } catch (err) {+ console.error('[irl/world-lines] agent signing failed', { agentId: wl.agent_id, message: err?.message });+ return json(res, 502, { error: 'the agent could not sign your proof — try again' });+ }+ // The signing key must match the key captured at creation, and the signature must+ // verify against it — we verify server-side BEFORE persisting, so a stored proof is+ // always genuine. (This is exactly what GET /verify re-runs for anyone.)+ if (signed.signerPubkey !== wl.signer_pubkey ||+ !verifyPresenceProof({ signerPubkey: signed.signerPubkey, message, signature: signed.signature })) {+ console.error('[irl/world-lines] self-verify failed', { wlId, agentId: wl.agent_id });+ return json(res, 502, { error: 'proof verification failed — try again' });+ }++ const collectibleName = wl.reward_ref || `${wl.title} — proof of presence`;++ // 7) Persist + count, guarded so capacity and one-per-visitor hold under concurrency.+ // The unique indexes (nonce_id; world_line_id+completer_hash) make a racing double+ // completion a clean conflict rather than a double mint. collectible_mint is the+ // deterministic, ownable id of the collectible; the verifiable signature is its body.+ let proof;+ try {+ [proof] = await sql`+ INSERT INTO irl_presence_proofs+ (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 (+ ${wlId}, ${wl.agent_id}, ${signed.signerPubkey}, ${wl.coarse_cell}, ${nv.nonceId}, ${who},+ ${completerUserId}, ${completerDevice}, ${signed.signature}, ${message}, ${spec.kind || 'tap'},+ ${collectibleName}, ${wl.reward_kind}+ )+ ON CONFLICT (nonce_id) DO NOTHING+ RETURNING *+ `;+ } catch (err) {+ // A (world_line_id, completer_hash) unique violation = this visitor already+ // completed via a different nonce in a race. Return their existing proof.+ const [dupe] = await sql`+ SELECT * FROM irl_presence_proofs WHERE world_line_id = ${wlId} AND completer_hash = ${who} LIMIT 1+ `;+ if (dupe) return json(res, 200, { already_completed: true, proof: publicProof(dupe), collectible: collectibleOf(dupe) });+ throw err;+ }+ if (!proof) {+ // nonce_id conflict (the same nonce was already spent) — idempotent replay.+ const [dupe] = await sql`SELECT * FROM irl_presence_proofs WHERE nonce_id = ${nv.nonceId} LIMIT 1`;+ if (dupe) return json(res, 200, { already_completed: true, proof: publicProof(dupe), collectible: collectibleOf(dupe) });+ return json(res, 409, { error: 'already_completed', message: 'This challenge was already used.' });+ }++ // The collectible id is derived from the proof row id (stable, ownable, verifiable).+ const collectibleMint = `presence:${proof.id}`;+ await sql`UPDATE irl_presence_proofs SET collectible_mint = ${collectibleMint} WHERE id = ${proof.id}`;+ proof.collectible_mint = collectibleMint;++ // Bump the completion count under the capacity guard (no over-fill past max).+ await sql`+ UPDATE irl_world_lines SET completion_count = completion_count + 1+ WHERE id = ${wlId} AND (max_completions IS NULL OR completion_count < max_completions)+ `;++ // 8) Tell the creator someone completed their World Line — coarse cell + count only,+ // never a coordinate or the completer's identity.+ if (wl.creator_user_id) {+ insertNotification(wl.creator_user_id, 'world_line_completed', {+ world_line_id: wlId,+ title: wl.title,+ coarse_cell: wl.coarse_cell,+ completion_count: (wl.completion_count || 0) + 1,+ link: '/world-lines/mine',+ });+ }++ return json(res, 201, { ok: true, proof: publicProof(proof), collectible: collectibleOf(proof) });+}++// Server-checkable part of a challenge. Presence ('tap') is already proven; quiz ++// phrase are graded against the stored spec so a completion can't be faked by skipping+// the interaction. Returns an error string or null.+function checkInteraction(spec, body) {+ if (!spec || spec.kind === 'tap') return null;+ if (spec.kind === 'quiz') {+ const ans = Number(body.answer);+ if (!Number.isInteger(ans) || ans !== spec.answer) return 'That’s not the right answer — try the quiz again.';+ return null;+ }+ if (spec.kind === 'phrase') {+ const said = String(body.phrase ?? body.answer ?? '').toLowerCase().replace(/\s+/g, ' ').trim();+ if (!said || said !== spec.phrase) return 'That passphrase didn’t match — ask the agent again.';+ return null;+ }+ return null;+}++// ── Verify (public, independent signature re-check) ──────────────────────────+async function handleVerify(req, res, proofId) {+ if (!isUuid(proofId)) return json(res, 400, { error: 'invalid proof id' });+ const [p] = await sql`+ SELECT pr.*, w.title FROM irl_presence_proofs pr+ LEFT JOIN irl_world_lines w ON w.id = pr.world_line_id+ WHERE pr.id = ${proofId} LIMIT 1+ `;+ if (!p) return json(res, 404, { error: 'proof not found' });++ // Re-run the exact check anyone could: does the agent signature validate over the+ // stored canonical message? Self-contained — needs only fields on the proof row.+ const verified = verifyPresenceProof({+ signerPubkey: p.signer_pubkey, message: p.signed_message, signature: p.signature,+ });+ return json(res, 200, {+ verified,+ proof: {+ id: p.id,+ world_line_id: p.world_line_id,+ world_line_title: p.title ?? null,+ agent_id: p.agent_id,+ signer_pubkey: p.signer_pubkey,+ coarse_cell: p.coarse_cell, // ~1.1 km — the only location the proof carries+ signed_message: p.signed_message,+ signature: p.signature,+ signature_scheme: 'ed25519',+ collectible_mint: p.collectible_mint,+ collectible_name: p.collectible_name,+ completed_at: p.created_at,+ },+ });+}++// ── Creator dashboard ────────────────────────────────────────────────────────+async function handleMine(req, res) {+ const session = await getSessionUser(req).catch(() => null);+ if (!session) return json(res, 401, { error: 'sign in to view your World Lines' });+ const rows = await sql`+ SELECT id, agent_id, signer_pubkey, pin_id, coarse_cell, region_cell, title, prompt,+ challenge_spec, reward_kind, reward_ref, difficulty, max_completions,+ completion_count, created_at, expires_at, hidden_at+ FROM irl_world_lines+ WHERE creator_user_id = ${session.id}+ ORDER BY created_at DESC LIMIT 100+ `;+ // Coarse heatmap: completions grouped by the proof's coarse cell — counts only, never+ // a precise point. (A quest has one anchor cell, so this is "completions per quest's+ // cell," the privacy-safe shape the dashboard renders.)+ const ids = rows.map((r) => r.id);+ let heat = [];+ if (ids.length) {+ heat = await sql`+ SELECT world_line_id, coarse_cell, count(*)::int AS completions+ FROM irl_presence_proofs+ WHERE world_line_id = ANY(${ids}::uuid[])+ GROUP BY world_line_id, coarse_cell+ `;+ }+ return json(res, 200, {+ world_lines: rows.map((r) => ({+ ...publicWorldLine(r, { owner: true }),+ expired: r.expires_at != null && new Date(r.expires_at).getTime() <= Date.now(),+ hidden: r.hidden_at != null,+ })),+ heatmap: heat,+ });+}++// ── Collectibles (the caller's earned proofs, for profile/wallet) ────────────+async function handleCollectibles(req, res) {+ const session = await getSessionUser(req).catch(() => null);+ const myDev = readDeviceToken(req);+ const myId = session?.id ?? null;+ if (!myId && !myDev) return json(res, 400, { error: 'sign in or present a device token' });++ // Strictly scoped to the caller's own id or device token — each arm null-guarded so a+ // missing identifier can never surface another visitor's collectibles.+ const rows = await sql`+ SELECT pr.id, pr.world_line_id, pr.agent_id, pr.signer_pubkey, pr.coarse_cell,+ pr.signature, pr.signed_message, pr.collectible_mint, pr.collectible_name,+ pr.reward_kind, pr.created_at, w.title, w.difficulty+ FROM irl_presence_proofs pr+ LEFT JOIN irl_world_lines w ON w.id = pr.world_line_id+ WHERE ((${myId}::uuid IS NOT NULL AND pr.completer_user_id = ${myId}::uuid)+ OR (${myDev}::text IS NOT NULL AND pr.completer_device = ${myDev}))+ ORDER BY pr.created_at DESC LIMIT 200+ `;+ return json(res, 200, {+ collectibles: rows.map((r) => ({+ ...collectibleOf(r),+ world_line_id: r.world_line_id,+ world_line_title: r.title ?? null,+ difficulty: r.difficulty ?? null,+ coarse_cell: r.coarse_cell,+ earned_at: r.created_at,+ verify_url: `/api/irl/world-lines/verify/${r.id}`,+ })),+ });+}++// ── Shared helpers ───────────────────────────────────────────────────────────+async function loadWorldLine(id) {+ const [w] = await sql`+ SELECT id, creator_user_id, agent_id, signer_pubkey, pin_id, coarse_cell, title, prompt,+ challenge_spec, reward_kind, reward_ref, difficulty, max_completions, completion_count+ FROM irl_world_lines+ WHERE id = ${id} AND hidden_at IS NULL AND (expires_at IS NULL OR expires_at > NOW())+ LIMIT 1+ `;+ return w || null;+}++// Recover the agent's custodial Solana key and sign the message. Isolated so it's the+// single seam tests mock — the rest of completion is pure DB + crypto already covered.+async function signWithAgent(agentId, userId, message) {+ const { ensureAgentWallet, recoverSolanaAgentKeypair } = await import('../_lib/agent-wallet.js');+ await ensureAgentWallet(agentId, userId, { reason: 'world-line:sign' });+ const [agent] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1`;+ const encrypted = agent?.meta?.encrypted_solana_secret;+ if (!encrypted) throw new Error('agent has no recoverable signing key');+ const kp = await recoverSolanaAgentKeypair(encrypted, { agentId, userId, reason: 'world-line:sign' });+ return signPresenceProof({ secretKey: kp.secretKey, message });+}++// Strip the secret answer from a challenge spec unless the caller is co-located.+function revealedSpec(spec, reveal) {+ if (!spec || typeof spec !== 'object') return { kind: 'tap', prompt: null };+ if (reveal) return spec;+ const { kind, prompt, question, choices } = spec;+ // For a quiz, the question + choices are needed to render; only the answer index is+ // hidden. For a phrase, the agent asks for it verbally — never echo the passphrase.+ const out = { kind, prompt: prompt ?? null };+ if (kind === 'quiz') { out.question = question; out.choices = choices; }+ return out;+}++function publicWorldLine(r, { owner = false, revealAnswer = false } = {}) {+ return {+ id: r.id,+ agent_id: r.agent_id,+ signer_pubkey: r.signer_pubkey,+ pin_id: r.pin_id,+ coarse_cell: r.coarse_cell,+ region_cell: r.region_cell,+ title: r.title,+ prompt: r.prompt,+ challenge: owner ? r.challenge_spec : revealedSpec(r.challenge_spec, revealAnswer),+ reward_kind: r.reward_kind,+ reward_ref: r.reward_ref,+ difficulty: r.difficulty,+ max_completions: r.max_completions,+ completion_count: r.completion_count,+ created_at: r.created_at,+ expires_at: r.expires_at,+ };+}++function publicProof(p) {+ return {+ id: p.id,+ world_line_id: p.world_line_id,+ agent_id: p.agent_id,+ signer_pubkey: p.signer_pubkey,+ coarse_cell: p.coarse_cell,+ signature: p.signature,+ signed_message: p.signed_message,+ signature_scheme: 'ed25519',+ completed_at: p.created_at,+ verify_url: `/api/irl/world-lines/verify/${p.id}`,+ };+}++function collectibleOf(p) {+ return {+ mint: p.collectible_mint || `presence:${p.id}`,+ name: p.collectible_name || 'Proof of presence',+ kind: 'proof-of-presence',+ reward_kind: p.reward_kind || 'collectible',+ signer_pubkey: p.signer_pubkey,+ signature: p.signature,+ proof_id: p.id,+ };+}diff --git a/api/labor/award.js b/api/labor/award.jsnew file mode 100644index 000000000..b175b0249--- /dev/null+++ b/api/labor/award.js@@ -0,0 +1,54 @@+// POST /api/labor/award — the poster (owner of the posting agent) awards a bid.+// Moves no money on its own (the reward is already escrowed): it transitions the+// bounty to 'working', creates the job, and rejects the other bids. If the worker+// is autonomous, the autopilot then performs + settles the job through to payout.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';+import { getBounty, getBid, listBidsForBounty, getJobByBounty } from '../_lib/agent-labor.js';+import { applyAward } from '../_lib/labor-match.js';+import { runAutopilot } from '../_lib/labor-settle.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const body = (await readJson(req)) || {};+ const { bountyId, bidId } = body;+ if (!bountyId || !bidId) return error(res, 400, 'validation_error', 'bountyId and bidId are required');++ const bounty = await getBounty(bountyId);+ if (!bounty) return error(res, 404, 'not_found', 'bounty not found');++ try {+ await loadOwnedAgent(bounty.poster_agent_id, userId); // caller must own the poster+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ if (bounty.status !== 'open') return error(res, 409, 'bounty_closed', `this bounty is ${bounty.status}, cannot be awarded`);++ const rawBid = await getBid(bidId);+ if (!rawBid || rawBid.bounty_id !== bountyId) return error(res, 404, 'bid_not_found', 'bid not found for this bounty');+ if (rawBid.status !== 'pending') return error(res, 409, 'bid_unavailable', `that bid is ${rawBid.status}`);++ const shaped = (await listBidsForBounty(bountyId)).find((b) => b.id === bidId);+ const winner = { ...shaped, worker_user_id: rawBid.worker_user_id, price_atomics: String(rawBid.price_atomics) };+ const rationale = `Awarded by owner to ${winner.worker_name} — ${winner.price_three} $THREE, score ${winner.score ?? 'n/a'}.`;++ const awarded = await applyAward({ bounty, winner, rationale, auto: false });++ // If the worker is autonomous, drive perform → verify → settle to completion.+ const autopilot = await runAutopilot(bountyId).catch(() => null);+ const job = (await getJobByBounty(bountyId)) || awarded.job;++ return json(res, 200, {+ ok: true,+ award: { bounty_id: bountyId, bid_id: bidId, worker_agent_id: winner.worker_agent_id, rationale, job_id: job?.id || null, status: job?.status || 'working' },+ autopilot: autopilot || { bids: 0, awarded: true, settled: null },+ });+});diff --git a/api/labor/bid.js b/api/labor/bid.jsnew file mode 100644index 000000000..c81cc9045--- /dev/null+++ b/api/labor/bid.js@@ -0,0 +1,73 @@+// POST /api/labor/bid — a worker agent (owned by the caller) bids on an open+// bounty. Bids move no money, so they aren't spend-gated; ownership IS enforced+// server-side. The bid's transparent score is computed and stored so the poster+// (or its auto-award policy) can rank it. If the poster auto-awards, placing the+// bid may immediately win — the autopilot runs after the bid lands.++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';+import {+ getBounty, getBid, scoreBid, workerReputation, upsertBid,+ threeToAtomics, _toBig as toBig, atomicsToThree,+} from '../_lib/agent-labor.js';+import { runAutopilot } from '../_lib/labor-settle.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const rl = await limits.mcpAgent(userId || 'anon');+ if (!rl.success) return rateLimited(res, rl, 'bid rate limit exceeded');++ const body = (await readJson(req)) || {};+ const { bountyId, workerAgentId, priceThree, priceAtomics, etaSeconds = null, pitch = null } = body;+ if (!bountyId || !workerAgentId) return error(res, 400, 'validation_error', 'bountyId and workerAgentId are required');++ let worker;+ try {+ worker = await loadOwnedAgent(workerAgentId, userId);+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ const bounty = await getBounty(bountyId);+ if (!bounty) return error(res, 404, 'not_found', 'bounty not found');+ if (bounty.status !== 'open') return error(res, 409, 'bounty_closed', `this bounty is ${bounty.status}, not open for bids`);+ if (bounty.poster_agent_id === workerAgentId) return error(res, 400, 'self_bid', 'an agent cannot bid on its own bounty');++ const reward = toBig(bounty.reward_atomics);+ const price = priceAtomics != null ? toBig(priceAtomics) : threeToAtomics(priceThree);+ if (price <= 0n) return error(res, 400, 'validation_error', 'bid price must be greater than zero');+ if (price > reward) {+ return error(res, 400, 'over_reward', `your bid (${atomicsToThree(price)} $THREE) exceeds the reward (${atomicsToThree(reward)} $THREE)`);+ }+ const eta = Number.isFinite(Number(etaSeconds)) && Number(etaSeconds) > 0 ? Math.round(Number(etaSeconds)) : null;++ const { reputation } = await workerReputation(workerAgentId);+ const score = scoreBid({ priceAtomics: price, rewardAtomics: reward, etaSeconds: eta, reputation });++ const bid = await upsertBid({+ bountyId, workerAgentId, workerUserId: userId, priceAtomics: price, etaSeconds: eta,+ pitch: pitch ? String(pitch).slice(0, 400) : `${worker.name || 'Agent'} bids ${atomicsToThree(price)} $THREE`,+ score, reputation, rationale: 'manual bid by owner', auto: false,+ });++ // A manual bid can still trigger the poster's auto-award. Drive the autopilot+ // (bounded; it only acts within the participants' opted-in policies).+ const autopilot = await runAutopilot(bountyId).catch(() => null);++ return json(res, 200, {+ ok: true,+ bid: {+ id: bid.id, bounty_id: bountyId, worker_agent_id: workerAgentId,+ price_atomics: String(toBig(bid.price_atomics)), price_three: atomicsToThree(bid.price_atomics),+ eta_seconds: eta, score, reputation, status: bid.status,+ },+ autopilot: autopilot || { bids: 0, awarded: false, settled: null },+ });+});diff --git a/api/labor/deliver.js b/api/labor/deliver.jsnew file mode 100644index 000000000..ae9574fb6--- /dev/null+++ b/api/labor/deliver.js@@ -0,0 +1,50 @@+// POST /api/labor/deliver — a worker agent (owned by the caller) submits the+// deliverable for its awarded job. Delivery immediately triggers verification ++// settlement: a neutral verifier scores the work against the spec and, ONLY on a+// pass, escrow is released on-chain to the worker with the skill royalty routed to+// the author. No human approves — the verdict gates the money.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';+import { getJob, getBounty, markJobDelivered } from '../_lib/agent-labor.js';+import { runSettlement } from '../_lib/labor-settle.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const body = (await readJson(req)) || {};+ const { jobId } = body;+ if (!jobId) return error(res, 400, 'validation_error', 'jobId is required');++ const job = await getJob(jobId);+ if (!job) return error(res, 404, 'not_found', 'job not found');++ try {+ await loadOwnedAgent(job.worker_agent_id, userId); // caller must own the worker+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }+ if (job.status !== 'working') return error(res, 409, 'not_deliverable', `job is ${job.status}, not awaiting delivery`);++ const raw = body.deliverable;+ const deliverable =+ typeof raw === 'string'+ ? { output: raw.slice(0, 8000), produced_at: new Date().toISOString() }+ : raw && typeof raw === 'object'+ ? { output: String(raw.output ?? '').slice(0, 8000), ...raw, produced_at: new Date().toISOString() }+ : null;+ if (!deliverable || !deliverable.output) return error(res, 400, 'validation_error', 'deliverable (string or { output }) is required');++ const delivered = await markJobDelivered(jobId, deliverable);+ if (!delivered) return error(res, 409, 'not_deliverable', 'job could not be marked delivered (already delivered?)');++ const bounty = await getBounty(job.bounty_id);+ const result = await runSettlement({ job: delivered, bounty });++ return json(res, 200, { ok: true, job_id: jobId, settlement: result });+});diff --git a/api/labor/feed.js b/api/labor/feed.jsnew file mode 100644index 000000000..88f2228e1--- /dev/null+++ b/api/labor/feed.js@@ -0,0 +1,38 @@+// GET /api/labor/feed — the live Agent Labor Market feed.+// Open bounties (filterable by skill + minimum reward), in-flight jobs, the most+// recent settlements (the $THREE-flow ticker), and market totals. Public read.++import { cors, json, method, wrap } from '../_lib/http.js';+import { TOKEN_MINT, TOKEN_DECIMALS, TOKEN_SYMBOL } from '../_lib/token/config.js';+import { escrowConfigured } from '../_lib/labor-escrow.js';+import {+ listOpenBounties, listInflightJobs, recentSettlements, marketTotals, threeToAtomics,+} from '../_lib/agent-labor.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://localhost');+ const skill = url.searchParams.get('skill')?.trim() || null;+ const minRewardThree = url.searchParams.get('minReward');+ const minRewardAtomics = minRewardThree ? threeToAtomics(minRewardThree) : null;++ const [open, inflight, settlements, totals] = await Promise.all([+ listOpenBounties({ requiredSkill: skill, minRewardAtomics, limit: 60 }),+ listInflightJobs({ limit: 30 }),+ recentSettlements({ limit: 24 }),+ marketTotals(),+ ]);++ json(res, 200, {+ data: {+ open,+ inflight,+ settlements,+ totals,+ escrow_configured: escrowConfigured(),+ token: { mint: TOKEN_MINT, symbol: TOKEN_SYMBOL, decimals: TOKEN_DECIMALS },+ },+ });+});diff --git a/api/labor/post.js b/api/labor/post.jsnew file mode 100644index 000000000..1d0c44ffa--- /dev/null+++ b/api/labor/post.js@@ -0,0 +1,136 @@+// POST /api/labor/post — an agent (owned by the caller) posts a bounty and+// escrows the reward in $THREE from its own custodial wallet into real on-chain+// escrow. Every guard is server-side: ownership, spend policy (per-tx + daily+// ceiling + kill switch), and a fail-closed price feed so the spend is valued in+// real USD before any $THREE moves. If escrow funding fails, NO money moved and+// the bounty is cancelled. On success the bounty is open and the autonomy engine+// immediately collects auto-bids (and auto-awards + runs the job if the poster+// opted in) so the market visibly comes alive.++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { authWrite, loadOwnedAgent, requireSolanaWallet } from '../_lib/labor-auth.js';+import { TOKEN_MINT } from '../_lib/token/config.js';+import { getTokenPriceUsd } from '../_lib/token/price.js';+import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';+import {+ SpendLimitError, reserveSpendUsd, releaseSpendReservation, updateCustodyEvent,+} from '../_lib/agent-trade-guards.js';+import { escrowConfigured, escrowAddressOrNull, fundEscrow } from '../_lib/labor-escrow.js';+import { createBounty, setBountyEscrow, setBountyStatus, threeToAtomics, atomicsToThree, _toBig as toBig } from '../_lib/agent-labor.js';+import { runAutopilot } from '../_lib/labor-settle.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const rl = await limits.mcpAgentPay(userId || 'anon');+ if (!rl.success) return rateLimited(res, rl, 'bounty rate limit exceeded');++ const body = (await readJson(req)) || {};+ const { posterAgentId, title, spec, requiredSkill = null, rewardThree, rewardAtomics, deadline = null } = body;++ if (!posterAgentId || typeof posterAgentId !== 'string') return error(res, 400, 'validation_error', 'posterAgentId is required');+ if (!title || typeof title !== 'string' || title.length > 140) return error(res, 400, 'validation_error', 'title is required (≤140 chars)');+ if (!spec || typeof spec !== 'string' || spec.length > 4000) return error(res, 400, 'validation_error', 'spec is required (≤4000 chars)');++ const reward = rewardAtomics != null ? toBig(rewardAtomics) : threeToAtomics(rewardThree);+ if (reward <= 0n) return error(res, 400, 'validation_error', 'reward must be greater than zero');++ if (!escrowConfigured()) {+ return error(res, 503, 'escrow_unavailable', 'the labor-market escrow wallet is not configured on this server');+ }++ let poster;+ try {+ poster = requireSolanaWallet(await loadOwnedAgent(posterAgentId, userId));+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ // Value the reward in real USD for the spend policy. Fail closed if no price+ // feed is live — a paid action must never proceed on a guessed price.+ let usd;+ try {+ const { priceUsd } = await getTokenPriceUsd();+ usd = atomicsToThree(reward) * priceUsd;+ } catch {+ return error(res, 503, 'price_unavailable', 'live $THREE price is unavailable — cannot value the escrow; try again shortly');+ }++ // Create the bounty row first so the reservation + escrow can reference it.+ const bounty = await createBounty({+ posterAgentId, posterUserId: userId, title: title.trim(), spec: spec.trim(),+ requiredSkill: requiredSkill ? String(requiredSkill).slice(0, 80) : null,+ rewardAtomics: reward, deadline, auto: false,+ meta: { reward_usd_at_post: usd },+ });++ // Reserve the spend against the poster's spend policy BEFORE moving funds.+ let reservationId = null;+ try {+ const r = await reserveSpendUsd({+ agentId: posterAgentId, userId, meta: poster.meta, category: 'x402',+ usdValue: usd, asset: 'THREE', network: 'mainnet',+ rowMeta: { kind: 'labor_bounty_escrow', bounty_id: bounty.id, reward_atomics: String(reward) },+ });+ reservationId = r.reservationId;+ } catch (e) {+ await setBountyStatus(bounty.id, 'cancelled');+ if (e instanceof SpendLimitError) return error(res, e.status || 403, e.code || 'spend_blocked', e.message, e.detail || {});+ console.error('[labor/post] reserve failed', e?.message);+ return error(res, 500, 'reserve_failed', 'could not reserve the escrow spend');+ }++ // Fund escrow on-chain: poster wallet → escrow wallet. A throw here means the+ // transfer did not land, so release the hold and cancel — no money moved.+ let fundSig;+ try {+ const posterKeypair = await recoverSolanaAgentKeypair(poster.meta.encrypted_solana_secret, {+ agentId: posterAgentId, userId, reason: 'labor_bounty_escrow_fund',+ });+ fundSig = await fundEscrow({ fromKeypair: posterKeypair, amountAtomics: reward });+ } catch (e) {+ await releaseSpendReservation(reservationId, 'labor_escrow_fund_failed');+ await setBountyStatus(bounty.id, 'cancelled');+ console.error('[labor/post] escrow funding failed', e?.message);+ return error(res, 502, 'escrow_fund_failed', `the bounty was not posted — no $THREE moved: ${e?.message || 'transfer failed'}`);+ }++ await updateCustodyEvent(reservationId, { status: 'confirmed', signature: fundSig, meta: { settled: true } })+ .catch((e) => console.error('[labor/post] finalize custody failed', e?.message));++ const escrowAddress = escrowAddressOrNull();+ const funded = await setBountyEscrow(bounty.id, { escrowAddress, escrowFundSig: fundSig });++ // Kick the autonomy engine: collect auto-bids and, if the poster auto-awards,+ // run the job through to settlement. Bounded; failures leave a resumable state.+ const autopilot = await runAutopilot(bounty.id).catch((e) => {+ console.warn('[labor/post] autopilot error', e?.message);+ return null;+ });++ const [final] = await sql`+ SELECT b.*, pa.name AS poster_name,+ (SELECT COUNT(*) FROM agent_bids bd WHERE bd.bounty_id = b.id AND bd.status != 'withdrawn') AS bid_count+ FROM agent_bounties b LEFT JOIN agent_identities pa ON pa.id = b.poster_agent_id+ WHERE b.id = ${bounty.id}`;++ return json(res, 200, {+ ok: true,+ bounty: {+ id: final.id, title: final.title, status: final.status,+ reward_atomics: String(toBig(final.reward_atomics)), reward_three: atomicsToThree(final.reward_atomics),+ required_skill: final.required_skill, escrow_address: final.escrow_address,+ escrow_fund_sig: final.escrow_fund_sig,+ escrow_explorer: final.escrow_fund_sig ? `https://solscan.io/tx/${final.escrow_fund_sig}` : null,+ bid_count: Number(final.bid_count || 0), award_rationale: final.award_rationale || null,+ },+ autopilot: autopilot || { bids: 0, awarded: false, settled: null },+ });+});diff --git a/api/ledger/[agentId].js b/api/ledger/[agentId].jsnew file mode 100644index 000000000..fe7528615--- /dev/null+++ b/api/ledger/[agentId].js@@ -0,0 +1,115 @@+// GET /api/ledger/:agentId — the Reasoning Ledger timeline + explainable+// reputation for one agent. Public read (a track record is meant to be audited).+//+// Query: ?limit=50&before=<seq>&kind=snipe&q=<text>&network=mainnet+//+// Returns the headline reputation (with its full formula + per-component+// breakdown + calibration curve), the latest on-chain anchor summary, and a+// paginated, filterable decision timeline where each entry carries its reasoning,+// prediction, and — once reconciled — the real outcome (right/wrong, by how much).++import { json, method, wrap, error } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import {+ getDecisionsWithOutcomes,+ getReputationRecords,+ computeReputation,+} from '../_lib/reasoning-ledger.js';+import { latestAnchor } from '../_lib/ledger-anchor.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function paramAgentId(req) {+ if (req.query?.agentId) return String(req.query.agentId);+ const m = String(req.url || '').match(/\/api\/ledger\/([^/?]+)/);+ return m ? decodeURIComponent(m[1]) : null;+}++function solscanUrl(sig, network) {+ if (!sig) return null;+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;+}++function shapeDecision(d) {+ const reconciled = d.outcome_status != null && d.was_correct != null;+ return {+ id: d.id,+ seq: Number(d.seq),+ kind: d.kind,+ subject_ref: d.subject_ref,+ action_ref: d.action_ref,+ inputs: d.inputs || {},+ rationale: d.rationale,+ prediction: d.prediction || {},+ confidence: d.confidence != null ? Number(d.confidence) : null,+ network: d.network,+ decided_at: d.decided_at,+ entry_hash: d.entry_hash,+ outcome: reconciled+ ? {+ status: 'reconciled',+ was_correct: d.was_correct,+ pnl_sol: d.pnl_sol != null ? Number(d.pnl_sol) : null,+ impact: d.impact != null ? Number(d.impact) : null,+ observed: d.observed || {},+ reconciled_at: d.reconciled_at,+ proof_url: solscanUrl(d.observed?.sell_sig, d.network),+ }+ : { status: 'pending' },+ };+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ const agentId = paramAgentId(req);+ if (!agentId || !UUID_RE.test(agentId)) {+ return error(res, 400, 'bad_request', 'a valid agent id is required');+ }++ const url = new URL(req.url, 'http://localhost');+ const limit = Number(url.searchParams.get('limit')) || 50;+ const before = url.searchParams.get('before');+ const kind = url.searchParams.get('kind');+ const q = url.searchParams.get('q');++ const [identity, repRecords, decisions, anchor] = await Promise.all([+ sql`select id, name, profile_image_url, avatar_url, is_public from agent_identities where id = ${agentId} limit 1`+ .then((r) => r[0] || null)+ .catch(() => null),+ getReputationRecords(agentId),+ getDecisionsWithOutcomes(agentId, {+ limit,+ beforeSeq: before ? Number(before) : null,+ kind: kind || null,+ q: q || null,+ }),+ latestAnchor(agentId).catch(() => null),+ ]);++ const reputation = computeReputation(repRecords);+ const shaped = decisions.map(shapeDecision);+ const nextBeforeSeq = shaped.length ? shaped[shaped.length - 1].seq : null;++ return json(res, 200, {+ agent: identity+ ? { id: identity.id, name: identity.name, image: identity.profile_image_url || identity.avatar_url || null }+ : { id: agentId, name: null, image: null },+ reputation,+ anchor: anchor+ ? {+ status: anchor.status,+ signature: anchor.signature,+ head_hash: anchor.head_hash,+ through_seq: Number(anchor.through_seq),+ entry_count: Number(anchor.entry_count),+ anchored_at: anchor.anchored_at,+ network: anchor.network,+ explorer_url: solscanUrl(anchor.signature, anchor.network),+ detail: anchor.detail || null,+ }+ : null,+ decisions: shaped,+ paging: { next_before_seq: shaped.length >= limit ? nextBeforeSeq : null },+ filters: { kind: kind || null, q: q || null },+ }, { 'cache-control': 'public, s-maxage=15, stale-while-revalidate=60' });+});diff --git a/api/ledger/verify/[agentId].js b/api/ledger/verify/[agentId].jsnew file mode 100644index 000000000..07ea8ce29--- /dev/null+++ b/api/ledger/verify/[agentId].js@@ -0,0 +1,89 @@+// GET /api/ledger/verify/:agentId — independently re-verify an agent's reasoning+// ledger. Public. This is the whole point of the feature: anyone can prove the+// history wasn't backdated or quietly edited.+//+// It recomputes the per-agent hash chain from each entry's committed contents+// (trusting NO stored hash), checks every link, then checks the recomputed head+// against the latest ON-CHAIN anchor. A tampered entry breaks its own hash and the+// next entry's prev_hash link; a full rewrite changes the head, which no longer+// matches the anchored commitment — so either way the alteration is detectable and+// pinpointed.+//+// status:+// empty — no decisions recorded yet+// verified — chain intact AND head matches the on-chain anchor+// verified_unanchored — chain intact, no on-chain anchor yet (commitment pending)+// verification_failed — a tamper / inconsistency was detected (see `chain` / `anchor`)++import { json, method, wrap, error } from '../../_lib/http.js';+import { getChainEntries, verifyChain } from '../../_lib/reasoning-ledger.js';+import { latestAnchoredAnchor } from '../../_lib/ledger-anchor.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function paramAgentId(req) {+ if (req.query?.agentId) return String(req.query.agentId);+ const m = String(req.url || '').match(/\/api\/ledger\/verify\/([^/?]+)/);+ return m ? decodeURIComponent(m[1]) : null;+}++function solscanUrl(sig, network) {+ if (!sig) return null;+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ const agentId = paramAgentId(req);+ if (!agentId || !UUID_RE.test(agentId)) {+ return error(res, 400, 'bad_request', 'a valid agent id is required');+ }++ const entries = await getChainEntries(agentId);+ const checkedAt = new Date().toISOString();++ if (!entries.length) {+ return json(res, 200, {+ agent_id: agentId,+ status: 'empty',+ chain: { ok: true, count: 0, head_hash: null, computed_head: null, broken_at: null, reason: null },+ anchor: null,+ checked_at: checkedAt,+ }, { 'cache-control': 'no-store' });+ }++ const chain = await verifyChain(agentId, entries);+ const anchorRow = await latestAnchoredAnchor(agentId).catch(() => null);++ let status;+ let anchor = null;+ if (!chain.ok) {+ status = 'verification_failed';+ } else if (anchorRow) {+ // The anchored head must equal the recomputed entry_hash at its seq.+ const atSeq = entries.find((e) => Number(e.seq) === Number(anchorRow.through_seq));+ const matches = !!atSeq && String(atSeq.entry_hash) === String(anchorRow.head_hash);+ status = matches ? 'verified' : 'verification_failed';+ anchor = {+ status: anchorRow.status,+ signature: anchorRow.signature,+ head_hash: anchorRow.head_hash,+ through_seq: Number(anchorRow.through_seq),+ entry_count: Number(anchorRow.entry_count),+ anchored_at: anchorRow.anchored_at,+ network: anchorRow.network,+ explorer_url: solscanUrl(anchorRow.signature, anchorRow.network),+ matches_chain: matches,+ };+ } else {+ status = 'verified_unanchored';+ }++ return json(res, 200, {+ agent_id: agentId,+ status,+ chain,+ anchor,+ checked_at: checkedAt,+ }, { 'cache-control': 'no-store' });+});diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsindex ec6ea529e..cc23c41b5 100644--- a/api/marketplace/set-skill-price.js+++ b/api/marketplace/set-skill-price.js@@ -10,14 +10,27 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { requireCsrf } from '../_lib/csrf.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { invalidateSkillPriceCache } from '../_lib/skill-price-cache.js';+import { persistListingSplit, clearListingSplit } from '../_lib/splits.js';import { z } from 'zod';+// Optional multi-collaborator proceeds split. Each recipient declares a payout+// address and a share (basis points OR percent); the app enforces Σ = 100%.+const splitRecipientSchema = z.object({+ address: z.string().trim().min(1).max(120),+ share_bps: z.number().int().positive().max(10000).optional(),+ percent: z.number().positive().max(100).optional(),+ recipient_user_id: z.string().uuid().nullable().optional(),+ label: z.string().trim().max(80).optional(),+});+const bodySchema = z.object({agent_id: z.string().uuid(),skill: z.string().trim().min(1).max(100),amount: z.number().int().min(0),currency_mint: z.string().trim().min(1).max(100),chain: z.string().trim().min(1).max(20).default('solana'),+ // Pass an array of 2+ recipients to split proceeds; null/[] clears the split.+ split: z.array(splitRecipientSchema).min(1).max(50).nullable().optional(),});async function resolveAuth(req) {@@ -49,7 +62,7 @@ export default wrap(async (req, res) => {return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');}- const { agent_id, skill, amount, currency_mint, chain } = parsed.data;+ const { agent_id, skill, amount, currency_mint, chain, split } = parsed.data;const [agent] = await sql`SELECT id, user_id FROM agent_identities@@ -58,6 +71,29 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');+ // Resolve the proceeds split first so a malformed split (shares not summing+ // to 100%, bad address) is rejected BEFORE we mutate the price row.+ let splitResult = null;+ if (amount === 0) {+ // Delisting clears any split too — no orphaned config.+ await clearListingSplit(sql, agent_id, skill).catch(() => {});+ } else if (split && split.length > 0) {+ try {+ splitResult = await persistListingSplit(sql, {+ agentId: agent_id,+ skill,+ chain,+ recipients: split,+ createdBy: auth.userId,+ });+ } catch (e) {+ if (e.status) return error(res, e.status, e.code, e.message);+ throw e;+ }+ } else if (split && split.length === 0) {+ await clearListingSplit(sql, agent_id, skill).catch(() => {});+ }+if (amount === 0) {await sql`UPDATE agent_skill_prices SET is_active = false, updated_at = now()@@ -77,5 +113,22 @@ export default wrap(async (req, res) => {}await invalidateSkillPriceCache(agent_id);- return json(res, 200, { data: { ok: true } });+ return json(res, 200, {+ data: {+ ok: true,+ ...(splitResult+ ? {+ split: {+ mode: splitResult.split_mode,+ address: splitResult.split_address,+ recipients: splitResult.recipients.map((r) => ({+ address: r.address,+ share_bps: r.share_bps,+ label: r.label,+ })),+ },+ }+ : {}),+ },+ });});diff --git a/api/newsletter-confirm.js b/api/newsletter-confirm.jsnew file mode 100644index 000000000..8b5b3ccda--- /dev/null+++ b/api/newsletter-confirm.js@@ -0,0 +1,67 @@+// GET /api/newsletter-confirm?token=... — step 2 of double opt-in.+//+// The confirm link from the signup email lands here. A valid token flips the+// subscriber to `confirmed`, adds them to the Resend audience, and shows a+// branded confirmation page. Tokens are single-purpose; an already-confirmed or+// unknown token shows a neutral page rather than leaking which is which.++import { sql } from './_lib/db.js';+import { cors, method, wrap, text, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { addToAudience, resultPage } from './_lib/newsletter.js';++const APP_URL = process.env.APP_ORIGIN || process.env.PUBLIC_APP_ORIGIN || 'https://three.ws';++function page(res, status, opts) {+ return text(res, status, resultPage(opts), { 'content-type': 'text/html; charset=utf-8' });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.newsletterConfirmIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const token = (new URL(req.url, 'http://x').searchParams.get('token') || '').trim();+ if (!token || token.length > 128) {+ return page(res, 400, {+ heading: 'Invalid link',+ body: 'This confirmation link is malformed. Try subscribing again from the site.',+ });+ }++ const [sub] = await sql`+ select email, status, locale from newsletter_subscribers where confirm_token = ${token}+ `;++ if (!sub) {+ return page(res, 404, {+ heading: 'Link expired',+ body: 'This confirmation link is no longer valid. You can subscribe again any time.',+ });+ }++ if (sub.status === 'confirmed') {+ return page(res, 200, {+ heading: "You're already subscribed",+ body: "Your email is confirmed — you'll get three.ws updates as they ship.",+ ctaHref: `${APP_URL}/changelog`,+ ctaLabel: 'See the changelog',+ });+ }++ await sql`+ update newsletter_subscribers+ set status = 'confirmed', confirmed_at = now(), unsubbed_at = null+ where confirm_token = ${token}+ `;+ await addToAudience(sub.email, sub.locale);++ return page(res, 200, {+ heading: "You're in",+ body: "Subscription confirmed. You'll get new features, launches, and changelog highlights — nothing else.",+ ctaHref: `${APP_URL}/changelog`,+ ctaLabel: 'See the changelog',+ });+});diff --git a/api/newsletter-subscribe.js b/api/newsletter-subscribe.jsindex 99bb91e37..9152c1927 100644--- a/api/newsletter-subscribe.js+++ b/api/newsletter-subscribe.js@@ -1,20 +1,31 @@-import { Resend } from 'resend';+// POST /api/newsletter-subscribe — double opt-in newsletter signup.+//+// Step 1 of 2: record a `pending` subscriber + a confirm token, then email a+// confirmation link. The contact is NOT added to the Resend audience until the+// link is clicked (api/newsletter-confirm.js) — so we never mail someone who+// didn't prove ownership of the address, and a typo'd/hostile email can't be+// used to subscribe a third party.+//+// Always returns a generic success so the endpoint can't be used to probe which+// addresses are already subscribed.+import { z } from 'zod';-import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';+import { sql } from './_lib/db.js';+import { cors, json, method, wrap, readJson, rateLimited } from './_lib/http.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';+import { randomToken } from './_lib/crypto.js';+import { sendNewsletterConfirmEmail } from './_lib/email.js';import { captureException } from './_lib/sentry.js';+const APP_URL = process.env.APP_ORIGIN || process.env.PUBLIC_APP_ORIGIN || 'https://three.ws';+const bodySchema = z.object({email: z.string().trim().toLowerCase().email().max(254),+ locale: z.string().trim().max(10).optional(),+ source: z.string().trim().max(40).optional(),});-let _client = null;-function client() {- if (!_client) _client = new Resend(process.env.RESEND_API_KEY);- return _client;-}-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;if (!method(req, res, ['POST'])) return;@@ -22,28 +33,36 @@ export default wrap(async (req, res) => {const rl = await limits.newsletterIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const { email } = parse(bodySchema, await readJson(req));+ const { email, locale, source } = parse(bodySchema, await readJson(req));- if (!process.env.RESEND_API_KEY || !process.env.RESEND_AUDIENCE_ID) {- // Endpoint not configured — accept silently so UI flow still works in dev.- return json(res, 200, { success: true });+ // Already confirmed → idempotent success, no second email.+ const [existing] = await sql`+ select status from newsletter_subscribers where email = ${email}+ `;+ if (existing?.status === 'confirmed') {+ return json(res, 200, { success: true, status: 'confirmed' });}+ // New or re-subscribing (pending/unsubscribed) → fresh token + confirm email.+ const token = randomToken(24);+ await sql`+ insert into newsletter_subscribers (email, status, confirm_token, locale, source)+ values (${email}, 'pending', ${token}, ${locale || null}, ${source || null})+ on conflict (email) do update set+ status = 'pending',+ confirm_token = excluded.confirm_token,+ locale = coalesce(excluded.locale, newsletter_subscribers.locale),+ source = coalesce(excluded.source, newsletter_subscribers.source),+ unsubbed_at = null+ `;++ const confirmUrl = `${APP_URL}/api/newsletter-confirm?token=${encodeURIComponent(token)}`;try {- await client().contacts.create({- email,- audienceId: process.env.RESEND_AUDIENCE_ID,- unsubscribed: false,- });+ await sendNewsletterConfirmEmail({ to: email, confirmUrl, locale });} catch (err) {- // Resend returns a non-2xx for duplicates — treat as success.- const msg = String(err?.message || '').toLowerCase();- if (msg.includes('already') || msg.includes('exists')) {- return json(res, 200, { success: true });- }- captureException(err, { email });- return error(res, 502, 'upstream_error', 'subscription failed');+ // Email transport failed — the row is saved, so a resend will reuse it.+ captureException(err, { email, where: 'newsletter-confirm-email' });}- return json(res, 200, { success: true });+ return json(res, 200, { success: true, status: 'pending' });});diff --git a/api/newsletter-unsubscribe.js b/api/newsletter-unsubscribe.jsnew file mode 100644index 000000000..ac2452e11--- /dev/null+++ b/api/newsletter-unsubscribe.js@@ -0,0 +1,56 @@+// GET /api/newsletter-unsubscribe?token=... — honoured one-click unsubscribe.+//+// Every newsletter email carries this link (also wired to the List-Unsubscribe+// header via Resend). A valid token flips the subscriber to `unsubscribed`,+// flags them unsubscribed in the Resend audience, and confirms with a branded+// page. Idempotent: re-clicking shows the same confirmation.++import { sql } from './_lib/db.js';+import { cors, method, wrap, text, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { removeFromAudience, resultPage } from './_lib/newsletter.js';++function page(res, status, opts) {+ return text(res, status, resultPage(opts), { 'content-type': 'text/html; charset=utf-8' });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.newsletterConfirmIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const token = (new URL(req.url, 'http://x').searchParams.get('token') || '').trim();+ if (!token || token.length > 128) {+ return page(res, 400, {+ heading: 'Invalid link',+ body: 'This unsubscribe link is malformed.',+ });+ }++ const [sub] = await sql`+ select email, status from newsletter_subscribers where confirm_token = ${token}+ `;++ if (!sub) {+ return page(res, 200, {+ heading: 'Unsubscribed',+ body: "You won't receive the three.ws newsletter.",+ });+ }++ if (sub.status !== 'unsubscribed') {+ await sql`+ update newsletter_subscribers+ set status = 'unsubscribed', unsubbed_at = now()+ where confirm_token = ${token}+ `;+ await removeFromAudience(sub.email);+ }++ return page(res, 200, {+ heading: 'Unsubscribed',+ body: "You're off the three.ws newsletter. Changed your mind? You can subscribe again any time.",+ });+});diff --git a/api/notifications/track.js b/api/notifications/track.jsnew file mode 100644index 000000000..ce51b684a--- /dev/null+++ b/api/notifications/track.js@@ -0,0 +1,58 @@+// POST /api/notifications/track — record a re-engagement funnel event.+//+// { notification_id, channel: 'push'|'in_app', event: 'opened'|'returned' }+//+// Closes the sent→opened→returned loop:+// • the service worker fires `opened` when a push notification is clicked,+// • the app fires `returned` when it boots from a push-sourced open+// (?source=push), proving the notification actually pulled the user back.+//+// Only `sent` is written server-side (by api/_lib/notify.js); the open/return+// signals can only come from the client, so this endpoint owns them. It's an+// idempotent analytics beacon (deduped by a partial unique index), so it auths+// on the session but is CSRF-exempt — there is no state a forged call could+// corrupt, only a funnel row for the caller's own notification.++import { z } from 'zod';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';++const body = z.object({+ notification_id: z.string().uuid().optional(),+ channel: z.enum(['push', 'in_app']),+ event: z.enum(['opened', 'returned']),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.notifTrack(user.id);+ if (!rl.success) return rateLimited(res, rl);++ const { notification_id, channel, event } = parse(body, await readJson(req));++ // If a notification id is given, confirm it belongs to the caller so the+ // funnel can't be poisoned with another user's notifications.+ if (notification_id) {+ const [row] = await sql`+ select 1 from user_notifications+ where id = ${notification_id} and user_id = ${user.id}+ `;+ if (!row) return error(res, 404, 'not_found', 'notification not found');+ }++ await sql`+ insert into notification_events (notification_id, user_id, channel, event)+ values (${notification_id ?? null}, ${user.id}, ${channel}, ${event})+ on conflict do nothing+ `;++ return json(res, 200, { ok: true });+});diff --git a/api/referral/visit.js b/api/referral/visit.jsnew file mode 100644index 000000000..6a901ba6d--- /dev/null+++ b/api/referral/visit.js@@ -0,0 +1,67 @@+// POST /api/referral/visit — record a referral-link visit (top of the viral funnel).+//+// A share link carries `?ref=CODE`. public/referral-capture.js parks the code for+// later signup attribution AND fires a beacon here so we can measure the FULL+// loop: visit → signup → activation, and from it the k-factor (signups per+// sharing user). Without this, only signups are visible and k is unknowable.+//+// Public + unauthenticated by design (the visitor has no account yet). Privacy-+// preserving: we store sha256(ip + ua + code), never the raw IP/UA, and dedup to+// one row per (code, visitor, UTC day) so refreshes don't inflate the funnel. An+// unknown code still records a visit (referrer_user_id NULL) so dead-link traffic+// is visible too.+//+// body: { code: string }+// → { ok: true } | { ok: false, error }++import { sql } from '../_lib/db.js';+import { cors, json, error, method, wrap, rateLimited, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { recordEvent } from '../_lib/usage.js';+import { normalizeReferralCode } from '../_lib/referrals.js';+import { referralVisitorHash } from '../_lib/referral-rewards.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.referralVisitIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req).catch(() => null);+ const code = normalizeReferralCode(body?.code);+ if (!code) return error(res, 400, 'invalid_code', 'malformed referral code');++ const ua = String(req.headers['user-agent'] || '').slice(0, 512);+ const visitorHash = referralVisitorHash({ ip, ua, code });+ // UTC day so the dedup window is stable regardless of server timezone.+ const day = new Date().toISOString().slice(0, 10);++ // Resolve the referrer at write time when the code is live — lets the funnel+ // roll up by referrer without re-joining on every read.+ const [referrer] = await sql`+ select id from users+ where upper(referral_code) = ${code} and deleted_at is null+ limit 1+ `;+ const referrerId = referrer?.id ?? null;++ // One visit per (code, visitor, day). A replay is a silent success.+ const [inserted] = await sql`+ insert into referral_visits (code, referrer_user_id, visitor_hash, day)+ values (${code}, ${referrerId}, ${visitorHash}, ${day}::date)+ on conflict (code, visitor_hash, day) do nothing+ returning id+ `;++ if (inserted) {+ recordEvent({+ userId: referrerId,+ kind: 'referral_visit',+ meta: { code, has_referrer: Boolean(referrerId) },+ });+ }++ return json(res, 200, { ok: true });+});diff --git a/api/stage/host.js b/api/stage/host.jsnew file mode 100644index 000000000..c3ce369d9--- /dev/null+++ b/api/stage/host.js@@ -0,0 +1,165 @@+/**+ * Living Stages — the host brain (Moonshot 04).+ *+ * The StageRoom's host loop calls this once per beat to get the embodied host's+ * next words. It reasons (latest Claude, via the platform LLM chain) over the+ * live show context the room hands it — the beat kind, the audience size, the tip+ * leaderboard, a fresh tip to shout out, or a queued audience question — plus the+ * agent's own persona and its memory of returning regulars, and returns a short,+ * speakable line + an animation cue. The room synthesizes it to spatial voice ++ * lip-sync and broadcasts it as live captions to every client.+ *+ * POST /api/stage/host { stageId, beat, context }+ * → { text, cue }+ *+ * Authenticated as the multiplayer server (HMAC over the body, verifyStageRequest)+ * so it is not a public LLM relay. Never canned: the words come from the brain;+ * only on a brain outage does the room fall back to its own minimal line.+ */++import { cors, json, wrap, readJson } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';+import { verifyStageRequest } from '../_lib/stage-bridge.js';+import { isUuid } from '../_lib/validate.js';++const BEAT_CUES = {+ opener: 'cheer',+ tip_shoutout: 'cheer',+ answer: 'point',+ banter: 'talk',+ game: 'dj',+};++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['POST', 'OPTIONS'] });+ if (req.method === 'OPTIONS') return res.end();+ if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });++ let body;+ try {+ body = await readJson(req, 20_000);+ } catch (e) {+ return json(res, e.status || 400, { error: e.message || 'bad_request' });+ }++ // Gate: only the multiplayer server (which signs with the shared secret) may+ // drive the host — otherwise this is a free LLM relay.+ if (!(await verifyStageRequest(req, body))) {+ return json(res, 401, { error: 'unauthorized' });+ }++ const stageId = body.stageId;+ const beat = String(body.beat || 'banter');+ const context = body.context || {};+ if (!isUuid(stageId)) return json(res, 400, { error: 'invalid stage id' });++ // Load the host agent's persona for voice/character. Best-effort: a missing+ // persona just yields a livelier-but-generic host, never a failure.+ const [stage] = await sql`+ SELECT s.agent_id, s.title, s.format, a.name AS agent_name, a.persona_prompt, a.description+ FROM stages s JOIN agent_identities a ON a.id = s.agent_id+ WHERE s.id = ${stageId} LIMIT 1+ `;+ if (!stage) return json(res, 404, { error: 'stage not found' });++ // Recall regulars: the top tippers across this stage's prior shows, so the host+ // can greet returning faces by name — the "remembers the regulars" behaviour.+ const regulars = await sql`+ SELECT tipper_label AS label, SUM(amount_atomic)::numeric AS total, COUNT(*)::int AS visits+ FROM show_tips WHERE stage_id = ${stageId} AND tipper_label IS NOT NULL+ GROUP BY tipper_label ORDER BY total DESC LIMIT 5+ `;++ const system = buildSystemPrompt(stage, regulars);+ const user = buildBeatPrompt(beat, context);++ let text = '';+ try {+ const out = await llmComplete({+ system,+ user,+ maxTokens: 160,+ timeoutMs: 18_000,+ track: { agentId: stage.agent_id, tool: 'stage_host' },+ });+ text = sanitizeLine(out.text);+ } catch (err) {+ if (err instanceof LlmUnavailableError) {+ return json(res, 503, { error: 'host_brain_unavailable' });+ }+ // A transient upstream failure: let the room use its failsafe line.+ return json(res, 502, { error: 'host_brain_error', detail: err?.message });+ }++ if (!text) return json(res, 502, { error: 'empty_completion' });+ return json(res, 200, { text, cue: BEAT_CUES[beat] || 'talk' }, { 'cache-control': 'no-store' });+});++function buildSystemPrompt(stage, regulars) {+ const persona = (stage.persona_prompt || stage.description || '').slice(0, 1200);+ const regularsLine = regulars.length+ ? `Returning regulars who have tipped this stage before (greet them warmly by name when they appear): ${regulars+ .map((r) => r.label)+ .join(', ')}.`+ : '';+ return [+ `You are ${stage.agent_name || 'the host'}, an embodied AI performer hosting a LIVE show "${stage.title || 'tonight’s set'}" — format: ${stage.format || 'open mic'} — in a 3D venue on three.ws.`,+ persona ? `Your persona: ${persona}` : '',+ `You speak OUT LOUD to a co-present crowd. Every line you return is spoken aloud and shown as live captions, so:`,+ `- Keep it to ONE or TWO short, punchy spoken sentences (never a paragraph, never a list, no stage directions, no emoji).`,+ `- Be lively, warm, quick-witted, and in-character. Read the room. Never sound canned.`,+ `- The crowd tips you in $THREE. $THREE is the only coin you ever mention — never name any other token.`,+ `- When someone tips, react with genuine, specific energy and thank them by name.`,+ regularsLine,+ `Return ONLY the words you say next — no quotes, no labels.`,+ ]+ .filter(Boolean)+ .join('\n');+}++function buildBeatPrompt(beat, ctx) {+ const audience = Number(ctx.audience) || 0;+ const crowd = audience <= 1 ? 'The room is just filling in.' : `There are ${audience} people in the crowd right now.`;+ const lb = Array.isArray(ctx.standings?.leaderboard) ? ctx.standings.leaderboard : [];+ const topLine = lb.length ? `Top tipper so far: ${lb[0].label}.` : '';++ switch (beat) {+ case 'opener':+ return `${crowd} Open the show. Welcome everyone in, set the vibe for a ${ctx.format || 'live'} set, and invite them to tip in $THREE to get your attention.`;+ case 'tip_shoutout': {+ const t = ctx.tip || {};+ const amt = formatThree(t.amount, t.mint);+ const msg = t.message ? ` They said: "${t.message}".` : '';+ return `${crowd} ${t.label || 'Someone'} just tipped you ${amt}!${msg} React on the spot — thank them by name with real energy.`;+ }+ case 'answer': {+ const q = ctx.question || {};+ return `${crowd} ${q.from || 'Someone'} in the crowd asks: "${q.text || ''}". Answer it live, in character, briefly.`;+ }+ case 'game':+ return `${crowd} ${topLine} Run the next quick beat of your ${ctx.format || 'show'} — a one-liner round, a dare, a quick bit. Keep the crowd's energy up.`;+ default:+ return `${crowd} ${topLine} Riff for a moment — read the room and keep it lively while you wait for the next tip or question.`;+ }+}++// Convert atomic units to a human "$THREE" amount for the prompt. We do NOT name+// any other token; a non-$THREE mint is described generically as "a tip".+function formatThree(amountAtomic, mint) {+ const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+ const n = Number(amountAtomic) || 0;+ const whole = Math.round(n / 1_000_000); // 6 decimals+ if (mint === THREE) return `${whole.toLocaleString('en-US')} $THREE`;+ return `a tip of ${whole.toLocaleString('en-US')}`;+}++// Collapse the model output to a single clean spoken line: strip surrounding+// quotes, control chars, and any leaked "Host:" label, bound the length.+function sanitizeLine(s) {+ if (typeof s !== 'string') return '';+ let t = s.replace(/[ -]+/g, ' ').replace(/\s+/g, ' ').trim();+ t = t.replace(/^["'“”]+|["'“”]+$/g, '').trim();+ t = t.replace(/^[A-Za-z .]{0,24}:\s*/, ''); // drop a leaked speaker label+ return t.slice(0, 400);+}diff --git a/api/stage/index.js b/api/stage/index.jsnew file mode 100644index 000000000..852131eb1--- /dev/null+++ b/api/stage/index.js@@ -0,0 +1,348 @@+/**+ * Living Stages — stage + show lifecycle (Moonshot 04).+ *+ * A "stage" is a venue where an embodied AI agent hosts live, monetized shows.+ * A "show" is one live session against that stage; "show_tips" is the per-show+ * ledger of real on-chain $THREE tips. This endpoint owns the read surface (the+ * stage directory + a single stage's live/between-show state) and the owner-only+ * writes (create/update a stage, go live, end a show).+ *+ * GET /api/stage → directory: live shows first, then upcoming+ * GET /api/stage?id=<id> → one stage: host, current show, leaderboard,+ * host wallet (tip target), between-show state+ * POST /api/stage { action:'create', agentId, title, format, voice, venue,+ * tipSplitBps, nextShowAt } → owner provisions a stage+ * POST /api/stage { action:'golive', stageId } → open a show + notify holders+ * POST /api/stage { action:'endshow', stageId } → close the current show+ *+ * Every write enforces ownership server-side (the agent's user_id must equal the+ * session user) + CSRF. Money is integer atomic units; $THREE is the only coin.+ */++import { cors, json, wrap, readJson } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';+import { ensureAgentWallet } from '../_lib/agent-wallet.js';+import { insertNotification } from '../_lib/notify.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { normalizeSplitBps } from '../_lib/stage-split.js';++const VENUES = new Set(['club', 'theater', 'plaza', 'arena']);+const MAX_TITLE = 120;+const MAX_FORMAT = 60;++let _tablesReady = false;+async function ensureTables() {+ if (_tablesReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS stages (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ agent_id UUID NOT NULL,+ owner_user_id UUID NOT NULL,+ venue TEXT NOT NULL DEFAULT 'club',+ title TEXT,+ format TEXT,+ voice TEXT NOT NULL DEFAULT 'nova',+ tip_split_bps INT NOT NULL DEFAULT 1000,+ status TEXT NOT NULL DEFAULT 'scheduled',+ next_show_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS stages_status ON stages (status, next_show_at)`;+ await sql`CREATE INDEX IF NOT EXISTS stages_agent ON stages (agent_id)`;+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS stages_agent_uniq ON stages (agent_id)`;+ await sql`+ CREATE TABLE IF NOT EXISTS shows (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ stage_id UUID NOT NULL,+ started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ ended_at TIMESTAMPTZ,+ peak_audience INT NOT NULL DEFAULT 0,+ total_tips_atomic NUMERIC NOT NULL DEFAULT 0,+ tip_count INT NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS shows_stage ON shows (stage_id, started_at DESC)`;+ // Exactly one open show per stage — a partial unique index makes "go live twice"+ // a no-op rather than a second open row the tips would split across.+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS shows_one_open ON shows (stage_id) WHERE ended_at IS NULL`;+ await sql`+ CREATE TABLE IF NOT EXISTS show_tips (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ show_id UUID,+ stage_id UUID NOT NULL,+ tipper_user_id UUID,+ tipper_label TEXT,+ amount_atomic NUMERIC NOT NULL,+ currency_mint TEXT NOT NULL,+ host_credit_atomic NUMERIC NOT NULL,+ venue_cut_atomic NUMERIC NOT NULL,+ settlement_sig TEXT NOT NULL,+ network TEXT,+ message TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )+ `;+ // One settlement → one tip row. The unique index is the idempotency guarantee+ // the tip endpoint leans on (ON CONFLICT DO NOTHING).+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS show_tips_sig ON show_tips (settlement_sig)`;+ await sql`CREATE INDEX IF NOT EXISTS show_tips_show ON show_tips (show_id, amount_atomic DESC)`;+ _tablesReady = true;+}++// Resolve the host agent's Solana wallet (the tip target) without provisioning on+// a public read — only return an address that already exists. Provisioning+// happens at stage creation, when the owner is authenticated.+async function readHostWallet(agentId) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1`;+ const addr = row?.meta?.solana_address;+ return typeof addr === 'string' && addr ? addr : null;+}++// Aggregate the per-tipper leaderboard for a show, highest total first.+async function showLeaderboard(showId, limit = 10) {+ if (!showId) return [];+ const rows = await sql`+ SELECT+ COALESCE(tipper_label, 'someone') AS label,+ SUM(amount_atomic)::numeric AS total,+ COUNT(*)::int AS count,+ MIN(created_at) AS first_at+ FROM show_tips+ WHERE show_id = ${showId}+ GROUP BY COALESCE(tipper_label, 'someone')+ ORDER BY total DESC, first_at ASC+ LIMIT ${limit}+ `;+ return rows.map((r) => ({ label: r.label, total: Number(r.total), count: r.count }));+}++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'] });+ if (req.method === 'OPTIONS') return res.end();++ await ensureTables();++ if (req.method === 'GET') return handleGet(req, res);+ if (req.method === 'POST') return handlePost(req, res);+ return json(res, 405, { error: 'method_not_allowed' });+});++async function handleGet(req, res) {+ const id = req.query.id;++ // ── single stage ──────────────────────────────────────────────────────────+ if (id) {+ if (!isUuid(id)) return json(res, 400, { error: 'invalid stage id' });+ const [stage] = await sql`+ SELECT s.*, a.name AS agent_name, a.avatar_url, a.profile_image_url, a.is_public+ FROM stages s+ JOIN agent_identities a ON a.id = s.agent_id AND a.deleted_at IS NULL+ WHERE s.id = ${id}+ LIMIT 1+ `;+ if (!stage) return json(res, 404, { error: 'stage not found' });++ const [openShow] = await sql`+ SELECT id, started_at, peak_audience, total_tips_atomic, tip_count+ FROM shows WHERE stage_id = ${id} AND ended_at IS NULL+ ORDER BY started_at DESC LIMIT 1+ `;+ const [lastShow] = openShow+ ? [null]+ : await sql`+ SELECT id, started_at, ended_at, peak_audience, total_tips_atomic, tip_count+ FROM shows WHERE stage_id = ${id} AND ended_at IS NOT NULL+ ORDER BY ended_at DESC LIMIT 1+ `;+ const leaderboardShow = openShow || lastShow;+ const leaderboard = await showLeaderboard(leaderboardShow?.id);+ const hostWallet = await readHostWallet(stage.agent_id);++ return json(res, 200, {+ stage: shapeStage(stage),+ live: !!openShow,+ currentShow: openShow ? shapeShow(openShow) : null,+ lastShow: lastShow ? shapeShow(lastShow) : null,+ leaderboard,+ hostWallet,+ }, { 'cache-control': 'no-store' });+ }++ // ── directory: live first, then upcoming, then recently-ended ──────────────+ const stages = await sql`+ SELECT s.*, a.name AS agent_name, a.avatar_url, a.profile_image_url,+ EXISTS (SELECT 1 FROM shows sh WHERE sh.stage_id = s.id AND sh.ended_at IS NULL) AS is_live,+ (SELECT total_tips_atomic FROM shows sh WHERE sh.stage_id = s.id ORDER BY started_at DESC LIMIT 1) AS recent_tips+ FROM stages s+ JOIN agent_identities a ON a.id = s.agent_id AND a.deleted_at IS NULL AND a.is_public IS TRUE+ WHERE s.status <> 'draft'+ ORDER BY is_live DESC, s.next_show_at ASC NULLS LAST, s.updated_at DESC+ LIMIT 60+ `;+ return json(res, 200, {+ stages: stages.map((s) => ({+ ...shapeStage(s),+ live: !!s.is_live,+ recentTipsAtomic: Number(s.recent_tips || 0),+ })),+ }, { 'cache-control': 'no-store' });+}++async function handlePost(req, res) {+ const session = await getSessionUser(req).catch(() => null);+ if (!session) return json(res, 401, { error: 'authentication_required' });+ if (!(await requireCsrf(req, res, session.id))) return;++ let body;+ try {+ body = await readJson(req, 20_000);+ } catch (e) {+ return json(res, e.status || 400, { error: e.message || 'bad_request' });+ }+ const action = String(body.action || '').toLowerCase();++ if (action === 'create') return createStage(req, res, session, body);+ if (action === 'golive') return goLive(req, res, session, body);+ if (action === 'endshow') return endShow(req, res, session, body);+ return json(res, 400, { error: 'unknown action' });+}++// Confirm the session user owns the agent (server-side ownership gate).+async function ownedAgent(agentId, userId) {+ if (!isUuid(agentId)) return null;+ const [a] = await sql`+ SELECT id, name, avatar_url FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL LIMIT 1+ `;+ return a || null;+}++async function createStage(req, res, session, body) {+ const agent = await ownedAgent(body.agentId, session.id);+ if (!agent) return json(res, 403, { error: 'you do not own this agent' });++ const venue = VENUES.has(body.venue) ? body.venue : 'club';+ const title = cleanStr(body.title, MAX_TITLE) || `${agent.name} Live`;+ const format = cleanStr(body.format, MAX_FORMAT) || 'open mic';+ const voice = cleanStr(body.voice, 40) || 'nova';+ const splitBps = normalizeSplitBps(body.tipSplitBps);+ const nextShowAt = parseFutureDate(body.nextShowAt);++ // Provision the host agent's wallet now (authenticated owner) so the tip target+ // exists before anyone can tip. Idempotent.+ let hostWallet = null;+ try {+ const w = await ensureAgentWallet(agent.id, session.id, { reason: 'stage_create' });+ hostWallet = w?.address || null;+ } catch (err) {+ return json(res, 502, { error: 'could not provision host wallet', detail: err?.message });+ }++ const [row] = await sql`+ INSERT INTO stages (agent_id, owner_user_id, venue, title, format, voice, tip_split_bps, status, next_show_at)+ VALUES (${agent.id}, ${session.id}, ${venue}, ${title}, ${format}, ${voice}, ${splitBps}, 'scheduled', ${nextShowAt})+ ON CONFLICT (agent_id) DO UPDATE SET+ venue = EXCLUDED.venue, title = EXCLUDED.title, format = EXCLUDED.format,+ voice = EXCLUDED.voice, tip_split_bps = EXCLUDED.tip_split_bps,+ next_show_at = EXCLUDED.next_show_at, status = 'scheduled', updated_at = NOW()+ RETURNING *+ `;+ return json(res, 201, { ok: true, stage: shapeStage(row), hostWallet });+}++async function goLive(req, res, session, body) {+ const stage = await ownedStage(body.stageId, session.id);+ if (!stage) return json(res, 403, { error: 'you do not own this stage' });++ // Open a show (idempotent via the partial unique index — a second go-live+ // returns the already-open show rather than a duplicate).+ const [show] = await sql`+ INSERT INTO shows (stage_id) VALUES (${stage.id})+ ON CONFLICT (stage_id) WHERE ended_at IS NULL DO UPDATE SET stage_id = EXCLUDED.stage_id+ RETURNING *+ `;+ await sql`UPDATE stages SET status = 'live', updated_at = NOW() WHERE id = ${stage.id}`;++ // Tell holders the show is starting — in-app bell + a best-effort Telegram ping.+ insertNotification(session.id, 'stage_live', {+ stage_id: stage.id,+ agent_id: stage.agent_id,+ title: stage.title,+ link: `/stage?id=${stage.id}`,+ });+ sendOpsAlert(+ 'Live stage started',+ `"${stage.title}" is live now. /stage?id=${stage.id}`,+ { signature: `stage-live:${show.id}` },+ );++ return json(res, 200, { ok: true, show: shapeShow(show), link: `/stage?id=${stage.id}` });+}++async function endShow(req, res, session, body) {+ const stage = await ownedStage(body.stageId, session.id);+ if (!stage) return json(res, 403, { error: 'you do not own this stage' });+ const [show] = await sql`+ UPDATE shows SET ended_at = NOW()+ WHERE stage_id = ${stage.id} AND ended_at IS NULL+ RETURNING *+ `;+ await sql`UPDATE stages SET status = 'offline', updated_at = NOW() WHERE id = ${stage.id}`;+ if (!show) return json(res, 200, { ok: true, ended: false, reason: 'no open show' });+ return json(res, 200, { ok: true, show: shapeShow(show) });+}++async function ownedStage(stageId, userId) {+ if (!isUuid(stageId)) return null;+ const [s] = await sql`+ SELECT * FROM stages WHERE id = ${stageId} AND owner_user_id = ${userId} LIMIT 1+ `;+ return s || null;+}++// ── shaping ──────────────────────────────────────────────────────────────────+function shapeStage(s) {+ return {+ id: s.id,+ agent_id: s.agent_id,+ venue: s.venue,+ title: s.title,+ format: s.format,+ voice: s.voice,+ tip_split_bps: s.tip_split_bps,+ status: s.status,+ next_show_at: s.next_show_at ? Date.parse(s.next_show_at) : null,+ host_name: s.agent_name,+ host_avatar: s.avatar_url || s.profile_image_url || null,+ };+}++function shapeShow(s) {+ return {+ id: s.id,+ started_at: s.started_at ? Date.parse(s.started_at) : null,+ ended_at: s.ended_at ? Date.parse(s.ended_at) : null,+ peak_audience: s.peak_audience ?? 0,+ total_tips_atomic: Number(s.total_tips_atomic || 0),+ tip_count: s.tip_count ?? 0,+ };+}++function cleanStr(v, max) {+ if (typeof v !== 'string') return '';+ return v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);+}++// Parse an epoch-ms or ISO date that must be in the future; otherwise null.+function parseFutureDate(v) {+ if (v == null) return null;+ const ms = typeof v === 'number' ? v : Date.parse(v);+ if (!Number.isFinite(ms) || ms < Date.now()) return null;+ return new Date(ms).toISOString();+}diff --git a/api/stage/tip.js b/api/stage/tip.jsnew file mode 100644index 000000000..9af8e3cbe--- /dev/null+++ b/api/stage/tip.js@@ -0,0 +1,220 @@+/**+ * Living Stages — record a real $THREE tip and make the host react (Moonshot 04).+ *+ * The audience member transfers $THREE (or USDC, where the platform's pay path+ * already allows it) directly to the host agent's wallet on-chain, then POSTs the+ * settlement signature here. This endpoint:+ * 1. validates the settlement signature + the $THREE/USDC mint + the atomic+ * amount (mirrors api/irl/interactions.js' pay discipline),+ * 2. is IDEMPOTENT per signature — one settlement records exactly one tip row+ * (a unique index + ON CONFLICT DO NOTHING is the guarantee, so a client+ * retry returns the existing row, never a double-credit),+ * 3. computes the host/venue accounting split (the full amount already landed+ * in the host wallet on-chain; the split records what is owed onward),+ * 4. rolls the show total, and+ * 5. pushes the tip to the live StageRoom over the signed /internal/stage+ * bridge so the host pre-empts its next beat and shouts the tipper out in ~1s.+ *+ * POST /api/stage/tip { stageId, signature, currencyMint, amount, message?,+ * network?, tipperName?, tipperSession? }+ * GET /api/stage/tip?stageId=<id> → current-show leaderboard + total+ *+ * Never trusts a client-asserted tip without a verifiable settlement. $THREE is+ * the only coin this platform promotes.+ */++import { cors, json, wrap, readJson, rateLimited } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { insertNotification } from '../_lib/notify.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { validateTipPayload, splitTip, tipExplorerUrl } from '../_lib/stage-split.js';+import { notifyStageRoom } from '../_lib/stage-bridge.js';++const MAX_MESSAGE = 140;+// A tip is "loud" when it clears 10k $THREE (6 decimals) — worth a Telegram ping.+const LOUD_TIP_ATOMIC = 10_000 * 1_000_000;++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['GET', 'POST', 'OPTIONS'] });+ if (req.method === 'OPTIONS') return res.end();++ if (req.method === 'GET') return handleGet(req, res);+ if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });++ const rl = await limits.stageTipIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req, 20_000);+ } catch (e) {+ return json(res, e.status || 400, { error: e.message || 'bad_request' });+ }++ const stageId = body.stageId;+ if (!isUuid(stageId)) return json(res, 400, { error: 'invalid stage id' });++ // A cookie-borne (session) request is a CSRF target; an anonymous,+ // settlement-proven tip has no ambient credential to abuse, so it is allowed+ // without CSRF (the on-chain signature is the proof) — same posture as the IRL+ // anonymous pay path. When signed in, enforce CSRF + attribute the tipper.+ const session = await getSessionUser(req).catch(() => null);+ if (session && !(await requireCsrf(req, res, session.id))) return;++ const valid = validateTipPayload({+ signature: body.signature,+ currencyMint: body.currencyMint,+ amount: body.amount,+ network: body.network,+ });+ if (!valid.ok) return json(res, 400, { error: valid.error });++ // Load the stage + its open show. A tip must land on a live show so it joins+ // the right ledger + reaches the room the host is performing in.+ const [stage] = await sql`+ SELECT s.id, s.agent_id, s.owner_user_id, s.tip_split_bps, s.title+ FROM stages s WHERE s.id = ${stageId} LIMIT 1+ `;+ if (!stage) return json(res, 404, { error: 'stage not found' });+ const [show] = await sql`+ SELECT id FROM shows WHERE stage_id = ${stageId} AND ended_at IS NULL+ ORDER BY started_at DESC LIMIT 1+ `;+ if (!show) return json(res, 409, { error: 'no live show — tips open when the host goes live' });++ const label = tipperLabel(session, body.tipperName);+ const { hostCredit, venueCut, splitBps } = splitTip(valid.amount, stage.tip_split_bps);+ const network = valid.network;+ const message = cleanMessage(body.message);++ // Idempotent insert: the unique index on settlement_sig makes a retry a no-op.+ // A returned row means this is the FIRST time we've seen this settlement.+ const [row] = await sql`+ INSERT INTO show_tips+ (show_id, stage_id, tipper_user_id, tipper_label, amount_atomic, currency_mint,+ host_credit_atomic, venue_cut_atomic, settlement_sig, network, message)+ VALUES (+ ${show.id}, ${stageId}, ${session?.id ?? null}, ${label},+ ${valid.amount}, ${valid.mint}, ${hostCredit}, ${venueCut},+ ${valid.signature}, ${network}, ${message}+ )+ ON CONFLICT (settlement_sig) DO NOTHING+ RETURNING id, amount_atomic, host_credit_atomic, venue_cut_atomic, created_at+ `;+ if (!row) {+ // Already recorded — hand back the original so the client is idempotent too.+ const [existing] = await sql`+ SELECT id, amount_atomic, host_credit_atomic, venue_cut_atomic+ FROM show_tips WHERE settlement_sig = ${valid.signature} LIMIT 1+ `;+ return json(res, 200, { ok: true, deduped: true, tip: shapeTip(existing) });+ }++ // Roll the show total (the row is already written, so a failed bump is logged,+ // never fatal — the per-tip rows remain the source of truth for the leaderboard).+ sql`+ UPDATE shows SET total_tips_atomic = total_tips_atomic + ${valid.amount}, tip_count = tip_count + 1+ WHERE id = ${show.id}+ `.catch((err) => console.warn('[stage/tip] show total bump failed', { showId: show.id, reason: err?.message }));++ const explorer = tipExplorerUrl(valid.signature, network);++ // Notify the owner (in-app bell always; Telegram for a loud one).+ if (stage.owner_user_id) {+ insertNotification(stage.owner_user_id, 'stage_tip', {+ stage_id: stageId,+ agent_id: stage.agent_id,+ amount: valid.amount,+ currency_mint: valid.mint,+ from: label,+ message,+ link: explorer || `/stage?id=${stageId}`,+ });+ }+ if (valid.amount >= LOUD_TIP_ATOMIC) {+ sendOpsAlert(+ 'Big stage tip',+ `${label} tipped ${valid.amount} (atomic) on "${stage.title}". /stage?id=${stageId}`,+ { signature: `stage-tip:${valid.signature}` },+ );+ }++ // Push to the live room so the host reacts within ~1s. Best-effort: the money+ // already settled on-chain + recorded here, so a missed push loses only the+ // in-room flourish, never funds.+ const pushed = await notifyStageRoom(stageId, 'tip', {+ tip: {+ tipperId: session?.id || label,+ tipperSession: typeof body.tipperSession === 'string' ? body.tipperSession.slice(0, 64) : null,+ label,+ amount: valid.amount,+ mint: valid.mint,+ message,+ signature: valid.signature,+ explorer,+ },+ });++ return json(res, 201, {+ ok: true,+ tip: shapeTip(row),+ split: { hostCredit, venueCut, splitBps },+ reacted: pushed?.delivered ?? false,+ explorer,+ });+});++async function handleGet(req, res) {+ const stageId = req.query.stageId;+ if (!isUuid(stageId)) return json(res, 400, { error: 'invalid stage id' });+ const [show] = await sql`+ SELECT id, total_tips_atomic, tip_count FROM shows+ WHERE stage_id = ${stageId}+ ORDER BY (ended_at IS NULL) DESC, started_at DESC LIMIT 1+ `;+ if (!show) return json(res, 200, { leaderboard: [], totalTipsAtomic: 0, tipCount: 0 });+ const rows = await sql`+ SELECT COALESCE(tipper_label, 'someone') AS label,+ SUM(amount_atomic)::numeric AS total, COUNT(*)::int AS count, MIN(created_at) AS first_at+ FROM show_tips WHERE show_id = ${show.id}+ GROUP BY COALESCE(tipper_label, 'someone')+ ORDER BY total DESC, first_at ASC LIMIT 10+ `;+ return json(res, 200, {+ leaderboard: rows.map((r) => ({ label: r.label, total: Number(r.total), count: r.count })),+ totalTipsAtomic: Number(show.total_tips_atomic || 0),+ tipCount: show.tip_count ?? 0,+ }, { 'cache-control': 'no-store' });+}++function tipperLabel(session, tipperName) {+ if (session?.display_name) return cleanLabel(session.display_name);+ if (session?.email) return cleanLabel(session.email.split('@')[0]);+ const n = cleanLabel(tipperName);+ return n || 'someone';+}++function cleanLabel(v) {+ if (typeof v !== 'string') return '';+ return v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 48);+}++function cleanMessage(v) {+ if (typeof v !== 'string') return null;+ const m = v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_MESSAGE);+ return m || null;+}++function shapeTip(r) {+ if (!r) return null;+ return {+ id: r.id,+ amount: Number(r.amount_atomic),+ hostCredit: Number(r.host_credit_atomic),+ venueCut: Number(r.venue_cut_atomic),+ };+}diff --git a/api/users/referral-claim.js b/api/users/referral-claim.jsindex 309aee57b..a539869e3 100644--- a/api/users/referral-claim.js+++ b/api/users/referral-claim.js@@ -21,6 +21,7 @@ import { requireCsrf } from '../_lib/csrf.js';import { cors, json, error, method, wrap, rateLimited, readJson } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { insertNotification } from '../_lib/notify.js';+import { recordEvent } from '../_lib/usage.js';// Canonical referral-code shape (api/_lib/referrals.js REFERRAL_CODE_RE): A–Z// and 0–9, 3–20 chars. Accepts vanity codes (the member's name), not just the@@ -90,6 +91,14 @@ export default wrap(async (req, res) => {referred_name: me.display_name || null,});+ // Funnel: a referred signup just landed. Mirrors the inline-attribution event+ // in api/auth/[action].js so visit→signup is measurable across every auth path.+ recordEvent({+ userId: referrer.id,+ kind: 'referral_signup',+ meta: { referred_user_id: String(me.id), source: 'claim' },+ });+const referrerName = referrer.display_name || referrer.username || null;return json(res, 200, { status: 'claimed', referrer: { name: referrerName } });});diff --git a/api/wk.js b/api/wk.jsindex d775494da..d99636a8c 100644--- a/api/wk.js+++ b/api/wk.js@@ -477,6 +477,405 @@ async function buildAgentServiceItems(origin) {return items;}+// ── output.example backfill ──────────────────────────────────────────────────+// Indexers (agentic.market / x402scan) render and rank a resource by its+// response example. A resource with no `bazaar.info.output.example` still+// catalogs, but ranks poorly and shows an empty result card — the verifier+// (`scripts/verify-x402-discovery.mjs`) flags every one as a warning. These maps+// are the single source of a realistic, schema-shaped success example for each+// paid endpoint so the catalog renders fully everywhere it's indexed.+//+// Every value here is SYNTHETIC: $THREE (the only coin) or an obviously-fake+// placeholder address — never a real third-party mint/creator/holder. Examples+// mirror the actual 200-response keys each handler emits (post-settlement).+const REST_OUTPUT_EXAMPLES = Object.freeze({+ '/api/x402/model-check': {+ url: 'https://three.ws/avatar/character-studio/sample.glb',+ fetchedBytes: 1572864,+ model: {+ container: 'glb',+ generator: 'three.ws CharacterStudio v1.5',+ version: '2.0',+ extensionsUsed: ['KHR_materials_unlit'],+ extensionsRequired: [],+ counts: {+ scenes: 1,+ nodes: 18,+ meshes: 6,+ materials: 4,+ textures: 3,+ animations: 1,+ skins: 1,+ totalVertices: 12480,+ totalTriangles: 24812,+ },+ },+ suggestions: [+ {+ id: 'texture_size',+ severity: 'info',+ message: 'All textures are within 1024x1024 — good for mobile.',+ },+ ],+ },+ '/api/x402/mint-to-mesh': {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ theme: { name: 'three', symbol: 'THREE', color: [0.92, 0.45, 0.18], hasImage: false },+ glb: { mimeType: 'model/gltf-binary', bytes: 50768, base64: 'Z2xURgIAAADQxAAA...' },+ },+ '/api/insights/revenue-vision': {+ power_mode: 'revenue-vision',+ insight:+ 'Builder teams of 10–50 convert 2.4× better than enterprise prospects on the current funnel.',+ recommended_move:+ 'Shift 30% of paid acquisition to builder-focused onboarding this sprint.',+ confidence: 'high',+ },+ '/api/x402/agent-reputation': {+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ name: 'Helios',+ wallet_address: 'AgEntWa11etExamp1eDoNotUse111111111111111111',+ deployed_mints: 2,+ payments: {+ confirmed_count: 142,+ confirmed_amount_atomics: '142000000',+ distinct_payers: 87,+ failed_count: 3,+ failure_rate: 0.021,+ },+ distributions: { confirmed: 12, failed: 1, success_rate: 0.923 },+ buybacks: { confirmed: 5, failed: 0, total_burn_atomics: '500000000' },+ attestations: { feedback_count: 14, validation_count: 8 },+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/agent-bouncer': {+ ok: true,+ admitted: true,+ banned: false,+ tier: 'trusted',+ reason: null,+ reasons: [],+ newcomer: false,+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ name: 'Helios',+ visits: 4,+ reputation: {+ deployed_mints: 2,+ payments: { confirmed_count: 142, distinct_payers: 87, failure_rate: 0.021 },+ distributions: { confirmed: 12, failed: 1, success_rate: 0.923 },+ },+ policy: {+ minPayments: 10,+ minDistinctPayers: 3,+ maxFailureRate: 0.2,+ allowNewcomers: true,+ },+ fetchedAt: '2026-06-22T17:00:00.000Z',+ },+ '/api/x402/onchain-identity-verify': {+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ chain: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ contract_or_mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ verified: true,+ evidence: {+ family: 'solana',+ tx_hash: '4kHTPp9ExampleSignatureDoNotUse...',+ wallet: 'AgEntWa11etExamp1eDoNotUse111111111111111111',+ confirmed_at: '2026-04-30T14:08:22Z',+ },+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/pump-agent-audit': {+ mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ network: 'mainnet',+ name: 'Helios',+ symbol: 'HELIO',+ payments: {+ total_in_atomics: '142000000',+ confirmed_count: 142,+ failed_count: 3,+ distinct_payers: 87,+ latest_payment_at: '2026-05-14T16:45:00Z',+ },+ distributions: { confirmed: 12, failed: 1, latest_status: 'confirmed', latest_error: null },+ buybacks: { confirmed: 5, failed: 0, total_burn_atomics: '500000000' },+ risk_flags: [],+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/pump-launch': {+ mint: 'HEL1oXyzABCDEFGHJKLMNopqrstuvwxyZ12345abcdef',+ signature: '5xYExampleTxSignatureDoNotUse...',+ creator: 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV',+ name: 'Helios',+ symbol: 'HELIO',+ metadataUri: 'https://ipfs.io/ipfs/QmExampleMetadataCid',+ network: 'mainnet',+ pumpfun_url: 'https://pump.fun/coin/HEL1oXyzABCDEFGHJKLMNopqrstuvwxyZ12345abcdef',+ vanity_prefix: 'HEL',+ vanity_iterations: 4821,+ },+ '/api/x402/forge': {+ job_id: 'f1.eyJwIjoiZXhhbXBsZSJ9.sig',+ status: 'queued',+ poll_url: '/api/forge?job=f1.eyJwIjoiZXhhbXBsZSJ9.sig',+ mode: 'text_to_3d',+ tier: 'standard',+ eta_seconds: 22,+ price_usdc: '0.15',+ },+ '/api/x402/skill-marketplace': {+ skill_filter: 'inspect_model',+ count: 1,+ cheapest: {+ agent_name: 'Helios',+ skill: 'inspect_model',+ amount_atomics: '10000',+ chain: 'solana',+ },+ listings: [+ {+ agent_id: '7b9a4f30-2d11-4e2d-9d12-1cdb1f6a3a55',+ agent_name: 'Helios',+ skill: 'inspect_model',+ amount_atomics: '10000',+ mint_decimals: 6,+ chain: 'solana',+ trial_uses: 1,+ time_pass_hours: 24,+ },+ ],+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/symbol-availability': {+ ticker: 'HELIO',+ network: 'mainnet',+ exact_collision: false,+ exact_matches: [],+ similar: [+ {+ ticker: 'HELIOS',+ mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ name: 'Helios',+ similarity: 0.71,+ },+ ],+ recommendation: 'available — one near-match exists at similarity 0.71',+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/vanity': {+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ prefix: 'So',+ suffix: null,+ ignoreCase: false,+ format: 'keypair',+ secretKeyBase58: 'Hy5pQqgExampleSecretDoNotUse...',+ attempts: 160,+ durationMs: 6,+ expectedAttempts: 58,+ network: 'solana',+ explorerUrl: 'https://solscan.io/account/SoEXAMPLEdoNotUse1111111111111111111111111111',+ },+ '/api/x402/vanity-verifiable': {+ protocol: 'three-vanity/v1',+ receiptType: 'grind-receipt',+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ pattern: { prefix: 'So', suffix: null, ignoreCase: false },+ commitment: 'sha256:0000000000000000000000000000000000000000000000000000000000000000',+ winningIndex: 3041,+ attempts: 3042,+ sealed: false,+ servicePublicKey: '3WzwpVSmSExamplePublicKeyDoNotUse',+ signature: 'ed25519:abcdef1234567890...',+ network: 'solana',+ verifyUrl: 'https://three.ws/vanity/verify',+ serviceKeyUrl: 'https://three.ws/.well-known/three-vanity.json',+ },+ '/api/x402/mint-to-mesh-batch': {+ count: 2,+ results: [+ {+ ok: true,+ mint: 'C3vQABCDEFGHJKLMNopqrstuvwxyZ12345abcdefghi',+ theme: { name: 'Helios', symbol: 'HELIO', hasImage: true },+ glb: { mimeType: 'model/gltf-binary', bytes: 18000, base64: 'Z2xUR...' },+ },+ { ok: false, mint: 'F7kXZExampleMintDoNotUse...', error: 'meta_fetch_failed' },+ ],+ indexed_at: '2026-05-14T17:00:00Z',+ },+ '/api/x402/dance-tip': {+ ok: true,+ ticketId: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',+ dancer: '1',+ dance: 'rumba',+ clip: 'rumba',+ durationSec: 10,+ startsAt: '2026-05-21T18:42:09.000Z',+ endsAt: '2026-05-21T18:42:19.000Z',+ network: 'solana',+ amountAtomics: '1000',+ },+ '/api/x402/asset-download': {+ ok: true,+ slug: 'pole-dancer-rumba',+ title: 'Pole Dancer (Rumba)',+ mimeType: 'model/gltf-binary',+ sizeBytes: 6492840,+ expiresAt: '2026-05-21T18:48:09.000Z',+ downloadUrl: 'https://three-ws-public.r2.dev/assets/pole-dancer-rumba.glb?X-Amz-Algorithm=...',+ },+ '/api/x402/skill-call': {+ ok: true,+ skill: { slug: 'wallet-balance', name: 'Wallet Balance', category: 'crypto' },+ tools: [{ type: 'function', function: { name: 'get_balance', description: 'Fetch balances.' } }],+ content: '# Wallet Balance\n\nUse get_balance to fetch token balances...',+ calledAt: '2026-05-31T18:48:09.000Z',+ },+ '/api/x402/fact-check': {+ verdict: 'supported',+ confidence: 0.91,+ claim: 'The Eiffel Tower is in Paris.',+ strictness: 'medium',+ sources: [+ {+ url: 'https://en.wikipedia.org/wiki/Eiffel_Tower',+ title: 'Eiffel Tower - Wikipedia',+ stance: 'supports',+ weight: 0.7,+ },+ ],+ costBreakdown: { searchCalls: 3, llmTokens: 1420, totalUsdc: '0.100355' },+ attestation: 'sha256:abcdef1234567890...',+ },+ '/api/x402/tutor': {+ sessionId: '8f1c0c2e-2a4d-4b6e-9b1a-3c5d7e9f0a1b',+ answer:+ 'The sky is blue because air scatters short-wavelength blue light from the sun more than other colors (Rayleigh scattering).',+ keyPoints: ['Sunlight contains all colors.', 'Air scatters blue more than red.'],+ example: 'At sunset light travels farther, so more blue scatters away and the sky reddens.',+ followUp: 'Why are sunsets red rather than blue?',+ level: 'intermediate',+ costThisChargeUsd: '0.010000',+ sessionTotalUsd: '0.030000',+ questionCount: 3,+ attestation: 'sha256:abcd1234...',+ },+ '/api/x402/crypto-intel': {+ topic: 'sol',+ headline: 'SOL up +7.2% in 24 h — momentum building',+ signal: 'bullish',+ price_usd: 148.32,+ change_24h: 7.18,+ rationale: 'SOL gained 7.18% in 24 h. Strong momentum suggests continued upside.',+ confidence: 0.86,+ ts: '2026-06-03T10:00:00Z',+ },+ '/api/x402/three-intel': {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ symbol: 'THREE',+ price_usd: 0.003685,+ change_24h: 12.4,+ market_cap_usd: 3685000,+ liquidity_usd: 412000,+ volume_24h_usd: 1268079,+ signal: 'bullish',+ headline: 'THREE climbs +12.40% — moderate upside',+ rationale: 'THREE gained +12.40% over 24 h at $0.003685; volume is healthy against liquidity.',+ confidence: 0.86,+ ts: '2026-06-12T10:00:00Z',+ },+ '/api/x402/cosmetic-purchase': {+ ok: true,+ id: 'skin-midnight',+ name: 'Midnight',+ slot: 'skin',+ rarity: 'legendary',+ account: 'g_5f3c9a21b8',+ owned: true,+ newlyOwned: true,+ network: 'solana',+ amountAtomics: '3000000',+ },+ '/api/x402/animation-download': {+ ok: true,+ id: '00000000-0000-0000-0000-000000000000',+ slug: 'spin-kick-combo',+ name: 'Spin Kick Combo',+ mimeType: 'model/gltf-binary',+ sizeBytes: 248400,+ expiresAt: '2026-06-15T18:48:09.000Z',+ downloadUrl: 'https://three.ws/cdn/u/spin-kick-combo.glb?X-Amz-Algorithm=...',+ },+ '/api/x402/club-cover': {+ ok: true,+ admitted: true,+ banned: false,+ tier: 'regular',+ visits: 4,+ passId: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',+ issuedAt: '2026-06-15T18:42:09.000Z',+ expiresAt: '2026-06-16T00:42:09.000Z',+ network: 'solana',+ amountAtomics: '10000',+ },+});++// MCP tool result examples, keyed by toolName. Wrapped in the same JSON-RPC 2.0+// CallToolResult envelope the live /api/mcp + /api/mcp-3d transports return, so+// the example mirrors exactly what a buyer's MCP client receives.+const MCP_TOOL_OUTPUT_SUMMARIES = Object.freeze({+ render_avatar: { ok: true, scene: 'avatar', format: 'glb', url: 'https://three.ws/cdn/avatar-preview.glb' },+ validate_model: { ok: true, warnings: [], errors: [], meta: { vertices: 12480, triangles: 24812 } },+ inspect_model: { container: 'glb', meshes: 6, materials: 4, animations: 1, vertices: 12480 },+ optimize_model: { ok: true, before: { bytes: 1572864 }, after: { bytes: 640000 }, savedPct: 59 },+ apply_animation: { ok: true, clip: 'walk', format: 'glb', url: 'https://three.ws/cdn/animated.glb' },+ text_to_3d: { job_id: 'f1.eyJwIjoiZXhhbXBsZSJ9.sig', status: 'queued', poll_url: '/api/forge?job=f1.eyJwIjoiZXhhbXBsZSJ9.sig' },+ image_to_3d: { job_id: 'f1.eyJpIjoiZXhhbXBsZSJ9.sig', status: 'queued', poll_url: '/api/forge?job=f1.eyJpIjoiZXhhbXBsZSJ9.sig' },+ remove_background: { ok: true, image_url: 'https://three.ws/cdn/cutout.png' },+ remesh_model: { ok: true, glb_url: 'https://three.ws/cdn/remeshed.glb', triangles: 20000 },+ stylize_model: { ok: true, glb_url: 'https://three.ws/cdn/stylized.glb', style: 'voxel' },+ segment_model: { ok: true, parts: ['head', 'torso', 'legs'], glb_url: 'https://three.ws/cdn/segmented.glb' },+ retexture_model: { ok: true, glb_url: 'https://three.ws/cdn/retextured.glb' },+ retexture_region: { ok: true, glb_url: 'https://three.ws/cdn/retextured-region.glb', region: 'face' },+ auto_rig_model: { ok: true, glb_url: 'https://three.ws/cdn/rigged.glb', bones: 52 },+ pose_model: { ok: true, glb_url: 'https://three.ws/cdn/posed.glb', pose: 't-pose' },+ direct_prompt: { job_id: 'f1.eyJkIjoiZXhhbXBsZSJ9.sig', status: 'queued', poll_url: '/api/forge?job=f1.eyJkIjoiZXhhbXBsZSJ9.sig' },+ generate_material: { ok: true, material_url: 'https://three.ws/cdn/material.glb' },+});++// Wrap a tool result summary in the JSON-RPC CallToolResult envelope.+function mcpResultExample(summary) {+ return {+ jsonrpc: '2.0',+ id: 1,+ result: { content: [{ type: 'text', text: JSON.stringify(summary) }] },+ };+}++// Backfill bazaar.info.output.example on one resource that lacks it, from the+// maps above. Mutates the already-built bazaar extension in place (the root info+// schema permits the extra `output` field — verified against both the REST and+// MCP meta-schemas) and returns the resource so it composes as an array .map().+// Resources that already carry an output example (the /api/mcp + /api/mcp-3d+// transport rows) are left untouched. Agent-published dynamic listings get a+// generic settled-result example so they catalog fully too.+function addOutputExample(r) {+ const info = r?.extensions?.bazaar?.info;+ if (!info || info.output?.example !== undefined) return r;+ let example;+ if (r.toolName && MCP_TOOL_OUTPUT_SUMMARIES[r.toolName]) {+ example = mcpResultExample(MCP_TOOL_OUTPUT_SUMMARIES[r.toolName]);+ } else if (REST_OUTPUT_EXAMPLES[r.path]) {+ example = REST_OUTPUT_EXAMPLES[r.path];+ } else if (typeof r.path === 'string' && r.path.startsWith('/api/x402/service/')) {+ // Agent-published listing: the response shape is the agent's own, so+ // advertise a generic settled envelope rather than a fabricated body.+ example = { ok: true, paid: true, result: {} };+ }+ if (example !== undefined) info.output = { type: 'json', example };+ return r;+}+async function handleX402Discovery(req, res) {const origin = env.APP_ORIGIN;const mcpUrl = `${origin}/api/mcp`;@@ -774,7 +1173,9 @@ async function handleX402Discovery(req, res) {// `.filter(Boolean)` drops any resource whose IIFE returned null —// e.g. permit2-paid-demo is omitted when CDP creds are missing,// matching the runtime 402 behavior so we don't catalog a route that- // would fail at first paid call.+ // would fail at first paid call. The trailing .map(addOutputExample)+ // backfills a realistic response example onto every entry so indexers+ // render and rank each one (no empty result cards, no verifier warnings).resources: [{path: '/api/x402/model-check',@@ -1739,7 +2140,9 @@ async function handleX402Discovery(req, res) {// Agent-published paid endpoints (monetize_endpoint). Dynamic —// one entry per active agent_paid_services listing....agentServiceItems,- ].filter(Boolean),+ ]+ .filter(Boolean)+ .map(addOutputExample),},{ 'cache-control': 'public, max-age=300' },);diff --git a/data/changelog.json b/data/changelog.jsonindex 7884d9086..a4a592aa4 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-23",+ "title": "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.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/three"+ },+ {+ "date": "2026-06-23",+ "title": "Agent profiles: a guided first run for brand-new agents, and one-click into the right studio",+ "summary": "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.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/agents"+ },{"date": "2026-06-23","title": "Avatar editor: a Walk tab to see your avatar in motion while you customize",diff --git a/data/pages.json b/data/pages.jsonindex 5a176c214..63c27e6d4 100644--- a/data/pages.json+++ b/data/pages.json@@ -868,6 +868,15 @@"changefreq": "hourly","added": "2026-05-25"},+ {+ "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.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-06-23",+ "showcase": true+ },{"path": "/three-live","title": "$THREE Live · Protocol Pulse",diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex c8e637bb3..e991ee8eb 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -22,11 +22,13 @@ import { monitor } from '@colyseus/monitor';import { WalkRoom } from './rooms/WalkRoom.js';import { IrlRoom } from './rooms/IrlRoom.js';import { ClashRoom } from './rooms/ClashRoom.js';+import { StageRoom } from './rooms/StageRoom.js';+import { getStageRoom } from './stage-registry.js';import { blockStore } from './block-store.js';import { worldPersistence } from './persistence.js';import { flushAllPlayers } from './playerStore.js';import { socialHub } from './social-hub.js';-import { verifyNotifySignature } from './presence-token.js';+import { verifyNotifySignature, verifyStageSignature } from './presence-token.js';const PORT = Number(process.env.PORT || 2567);const HOST = process.env.HOST || '0.0.0.0';@@ -93,6 +95,40 @@ app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {res.json({ delivered });});+// Living Stages tip/event bridge (Moonshot 04). The three.ws API calls this the+// instant a real $THREE tip settles on-chain (after it has verified the+// settlement signature + mint and deduped per signature) so the live StageRoom+// can react within ~1s — broadcast the tip ticker, update the leaderboard, and+// pre-empt the host's next beat with a shoutout. HMAC-signed with the shared+// secret bound to the exact body + a fresh timestamp, so only the API can inject+// a tip; an unsigned or stale request is rejected before it reaches a room. The+// money already settled to the host wallet on-chain — this only drives the live+// reaction, so a `not_found` (room not hosted on this instance) loses nothing but+// the in-room flourish.+app.post('/internal/stage', express.json({ limit: '16kb' }), (req, res) => {+ const { stageId, event, tip } = req.body || {};+ const sig = req.headers['x-stage-signature'];+ const ts = req.headers['x-stage-timestamp'];+ if (typeof stageId !== 'string' || !stageId) {+ return res.status(400).json({ error: 'bad_request' });+ }+ if (!verifyStageSignature(req.body || {}, ts, sig)) {+ return res.status(401).json({ error: 'bad_signature' });+ }+ const room = getStageRoom(stageId);+ if (!room) return res.json({ ok: true, delivered: false, reason: 'not_found' });+ try {+ if (event === 'tip' && tip) {+ const result = room.injectTip(tip);+ return res.json({ ok: true, delivered: !!result?.ok });+ }+ return res.status(400).json({ error: 'unknown_event' });+ } catch (err) {+ console.error('[multiplayer] /internal/stage error:', err?.message || err);+ return res.status(500).json({ error: 'inject_failed' });+ }+});+// The IRL world (irl_world) is a presence + reaction room only — it is NOT a pin// transport. Placed agents are private by location and reach a viewer solely via// the per-viewer /api/irl/pins proximity read when they are physically near one,@@ -207,12 +243,18 @@ gameServer.define('irl_world', IrlRoom).filterBy(['geocell']);// room. A fighter must hold the coin they fight for (ClashRoom.onAuth verifies a// holder pass for their declared faction). See rooms/ClashRoom.js + clash.js.gameServer.define('clash_arena', ClashRoom).filterBy(['matchKey']);+// Living Stages (Moonshot 04). One room instance per stageId, so every audience+// member who joins a given stage lands in the same live show — the host, the+// crowd, the tip ticker, and the leaderboard all live in that one room. The room+// loads its host/title/format from /api/stage and reacts to real $THREE tips the+// API injects over /internal/stage. See rooms/StageRoom.js + src/stage.js.+gameServer.define('stage_world', StageRoom).filterBy(['stageId']);gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);- console.log(`[multiplayer] rooms: walk_world, irl_world`);+ console.log(`[multiplayer] rooms: walk_world, irl_world, clash_arena, stage_world`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {diff --git a/multiplayer/src/presence-token.js b/multiplayer/src/presence-token.jsindex 8c76fc07e..424505955 100644--- a/multiplayer/src/presence-token.js+++ b/multiplayer/src/presence-token.js@@ -74,3 +74,44 @@ export function verifyNotifySignature(to, type, payload, ts, sig) {.digest('base64url');return timingSafeEqualStr(sig, expected);}++// ── Living Stages internal bridge ────────────────────────────────────────────+// The Vercel API and this server can't share code (separate packages), so the+// stage tip/event webhook reuses the same HMAC discipline as /internal/notify:+// the signature binds the exact body + a fresh timestamp to the shared secret, so+// a captured tuple can't be replayed with attacker-chosen content or after the+// freshness window. Keep byte-compatible with signStageEvent in+// api/_lib/stage-bridge.js.+const STAGE_MAX_AGE_S = 120;++export function verifyStageSignature(payload, ts, sig) {+ if (typeof sig !== 'string' || !sig) return false;+ const tsNum = Number(ts);+ if (!Number.isFinite(tsNum)) return false;+ const nowS = Math.floor(Date.now() / 1000);+ if (Math.abs(nowS - tsNum) > STAGE_MAX_AGE_S) return false;+ const payloadHash = crypto+ .createHash('sha256')+ .update(JSON.stringify(payload ?? {}))+ .digest('base64url');+ const expected = crypto+ .createHmac('sha256', secret())+ .update(`stage:${tsNum}:${payloadHash}`)+ .digest('base64url');+ return timingSafeEqualStr(sig, expected);+}++// Sign an outbound room → API request (the host loop fetching the next beat from+// /api/stage/host). Mirrored by verifyStageRequest in api/_lib/stage-bridge.js.+export function signStageRequest(payload) {+ const ts = Math.floor(Date.now() / 1000);+ const payloadHash = crypto+ .createHash('sha256')+ .update(JSON.stringify(payload ?? {}))+ .digest('base64url');+ const sig = crypto+ .createHmac('sha256', secret())+ .update(`stage-req:${ts}:${payloadHash}`)+ .digest('base64url');+ return { ts, sig };+}diff --git a/multiplayer/src/rooms/StageRoom.js b/multiplayer/src/rooms/StageRoom.jsnew file mode 100644index 000000000..a270436ee--- /dev/null+++ b/multiplayer/src/rooms/StageRoom.js@@ -0,0 +1,438 @@+// StageRoom — the live-performance world (stage_world) for three.ws Living Stages.+//+// An embodied AI agent hosts a real-time show in a 3D venue: it opens, riffs,+// runs its format, takes audience questions, and — the heart of the loop —+// reacts on the spot to real $THREE tips that settle on-chain to its wallet. The+// crowd is co-present (privacy-clean presence like IrlRoom), reactions ripple,+// and a live tip leaderboard drives who the host shouts out.+//+// What this room owns:+// • AUDIENCE presence — a session id + opt-in name/avatar + a server-assigned+// ring seat (never a client-reported coordinate), heartbeats + a reaper.+// • The HOST performance frame — each beat bumps `utteranceId` and broadcasts a+// timed `utterance` { id, text, voice, cue, beat, durationMs } that every+// client renders identically: spatial voice (client fetches /api/tts/speak),+// lip-sync, animation cue, and live captions. Captions are also written into+// synced state so a late joiner / no-WebGL client still reads the show.+// • The TIP TICKER + leaderboard — fed by the API over /internal/stage the+// instant a tip settles, so the host pre-empts its next beat to react in ~1s.+//+// The show's DECISIONS (which beat, who's top, which question) live in the pure+// ShowDirector (../stage-show.js); this room is the socket+schema shell. The+// host's WORDS come from the brain via /api/stage/host (latest Claude). Money is+// integer atomic units end to end; the room never trusts a client-asserted tip —+// only the API's verified, signature-deduped settlement reaches injectTip().++import { Room } from '@colyseus/core';++import { StageState, StageAudience, StageTipper } from '../stage-schemas.js';+import { ShowDirector, BEAT } from '../stage-show.js';+import { registerStage, unregisterStage } from '../stage-registry.js';+import { signStageRequest } from '../presence-token.js';++const PATCH_RATE_MS = 100; // 10 Hz — snappy enough for the tip ticker + captions+const MAX_CLIENTS = 200; // a busy venue; bound so a flood degrades gracefully+const BEAT_INTERVAL_MS = 13_000; // cadence between host beats when nothing pre-empts+const SPEAK_ESTIMATE_MS = 90; // per character, for the speaking → idle timer+const SPEAK_MIN_MS = 3_000;+const SPEAK_MAX_MS = 22_000;+const HEARTBEAT_STALE_MS = 45_000;+const REAPER_INTERVAL_MS = 15_000;+const REACTIONS_PER_SEC = 4; // anti-spam on the emoji channel+const QUESTIONS_PER_MIN = 6;+const VIP_TIP_THRESHOLD = 50_000 * 1_000_000; // ≥ 50k $THREE (6 decimals) → VIP front row+const RING_RADIUS = 6; // metres — audience seated on a ring around the stage++const API_BASE = (+ process.env.THREEWS_API_BASE ||+ process.env.MULTIPLAYER_API_BASE ||+ 'https://three.ws'+).replace(/\/$/, '');++const REACTIONS = new Set(['clap', 'fire', 'heart', 'laugh', 'wow', 'cheer']);++export class StageRoom extends Room {+ constructor() {+ super();+ this.maxClients = MAX_CLIENTS;+ this.stageId = '';+ this._director = null;+ this._beatTimer = null;+ this._speakTimer = null;+ this._beatRunning = false;+ this._rate = new Map(); // sessionId → { react:{ts,n}, ask:{ts,n} }+ this._configLoaded = false;+ }++ async onCreate(options) {+ this.stageId = String(options?.stageId || '').slice(0, 64);+ this.setState(new StageState());+ this.state.stageId = this.stageId;+ this.state.phase = 'preshow';+ this.setPatchRate(PATCH_RATE_MS);+ this.autoDispose = false; // a scheduled show outlives an empty crowd between beats++ this._director = new ShowDirector({ stageId: this.stageId });++ // Audience reactions ripple to the whole crowd; questions queue for the host+ // to pick; heartbeats keep the reaper from dropping a live viewer.+ this.onMessage('reaction', (client, payload) => this._guard('reaction', () => this._handleReaction(client, payload)));+ this.onMessage('question', (client, payload) => this._guard('question', () => this._handleQuestion(client, payload)));+ this.onMessage('heartbeat', (client) => this._guard('heartbeat', () => this._handleHeartbeat(client)));++ this.clock.setInterval(() => this._reap(), REAPER_INTERVAL_MS);++ // Register BEFORE the async config load so a tip arriving during boot finds+ // the room (it queues into the director regardless of config).+ registerStage(this.stageId, this);++ await this._loadConfig();++ // The performance heartbeat: pick + perform the next beat on a cadence. A+ // tip pre-empts this (see injectTip) so a shoutout never waits a full beat.+ this._beatTimer = this.clock.setInterval(() => this._runBeat('cadence'), BEAT_INTERVAL_MS);+ // Open the show immediately so the first client never lands on a dead stage.+ this._runBeat('open');++ console.log(`${this._tag()} created (host=${this.state.host.name || 'unknown'})`);+ }++ _tag() {+ return `[stage_world ${this.roomId} stage=${this.stageId || 'invalid'}]`;+ }++ _guard(label, fn) {+ try {+ fn();+ } catch (err) {+ console.error(`${this._tag()} ${label} handler error:`, err?.message || err);+ }+ }++ // Pull the stage's display config (host agent name/avatar/voice, title, format,+ // schedule, phase) from the API. The persona + memory the brain needs live+ // server-side in /api/stage/host — this room only needs what it renders.+ async _loadConfig() {+ try {+ const res = await fetch(`${API_BASE}/api/stage?id=${encodeURIComponent(this.stageId)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(6_000),+ });+ if (!res.ok) throw new Error(`config http ${res.status}`);+ const data = await res.json();+ const stage = data?.stage || data;+ if (stage) {+ this.state.title = clean(stage.title, 120);+ this.state.format = clean(stage.format, 60);+ this.state.nextShowAt = Number(stage.next_show_at) || 0;+ const h = this.state.host;+ h.agentId = clean(stage.agent_id, 64);+ h.name = clean(stage.host_name || stage.agent_name, 80) || 'The Host';+ h.avatar = clean(stage.host_avatar || stage.avatar_url, 512);+ h.voice = clean(stage.voice, 40) || 'nova';+ this._director.hostName = h.name;+ this._director.format = this.state.format || 'open mic';+ }+ this._configLoaded = true;+ } catch (err) {+ // A config miss must not silence the show — fall back to a generic host+ // identity so the room still runs (real beats, just an unstyled name).+ console.warn(`${this._tag()} config load failed: ${err?.message || err}`);+ const h = this.state.host;+ if (!h.name) h.name = 'The Host';+ if (!h.voice) h.voice = 'nova';+ }+ }++ // ── audience presence ─────────────────────────────────────────────────────+ onJoin(client, options) {+ const member = new StageAudience();+ member.id = client.sessionId;+ member.name = clean(options?.name, 40);+ member.avatar = clean(options?.avatar, 512);+ const seat = this._assignSeat();+ member.x = seat.x;+ member.z = seat.z;+ member.tsServer = Date.now();+ this.state.audience.set(client.sessionId, member);+ this._director.noteAudience(this.state.audience.size);+ console.log(`${this._tag()} +join (audience=${this.state.audience.size})`);+ }++ onLeave(client) {+ this._rate.delete(client.sessionId);+ const had = this.state.audience.delete(client.sessionId);+ if (had) console.log(`${this._tag()} -leave (audience=${this.state.audience.size})`);+ }++ // Seat each arrival on a ring around the stage, golden-angle spaced so the+ // crowd fans out evenly instead of stacking. Server-assigned (never a client+ // coordinate) so presence can't be used to probe or spoof a position.+ _assignSeat() {+ const i = this.state.audience.size;+ const angle = i * 2.399963; // golden angle (rad)+ const r = RING_RADIUS + (i % 3) * 1.6; // a few concentric rings as it fills+ return { x: Math.cos(angle) * r, z: Math.sin(angle) * r };+ }++ _handleReaction(client, payload) {+ if (!this.state.audience.has(client.sessionId)) return;+ if (!this._rateOk(client.sessionId, 'react', REACTIONS_PER_SEC, 1000)) return;+ const emoji = typeof payload?.emoji === 'string' ? payload.emoji : '';+ if (!REACTIONS.has(emoji)) return;+ const member = this.state.audience.get(client.sessionId);+ member.reaction = emoji;+ member.reactionTs = Date.now();+ // Broadcast so the whole crowd renders the ripple at once (sender included).+ this.broadcast('reaction', { id: client.sessionId, emoji, ts: member.reactionTs }, { afterNextPatch: false });+ }++ _handleQuestion(client, payload) {+ if (!this.state.audience.has(client.sessionId)) return;+ if (!this._rateOk(client.sessionId, 'ask', QUESTIONS_PER_MIN, 60_000)) {+ client.send('question_ack', { ok: false, reason: 'slow_down' });+ return;+ }+ const member = this.state.audience.get(client.sessionId);+ const ok = this._director.queueQuestion({+ id: `${client.sessionId}:${Date.now()}`,+ from: member.name || 'someone',+ text: typeof payload?.text === 'string' ? payload.text : '',+ ts: Date.now(),+ });+ client.send('question_ack', { ok, queued: this._director.pendingQuestionCount() });+ }++ _handleHeartbeat(client) {+ const member = this.state.audience.get(client.sessionId);+ if (member) member.tsServer = Date.now();+ }++ _reap() {+ const cutoff = Date.now() - HEARTBEAT_STALE_MS;+ for (const [id, m] of this.state.audience) {+ if (m.tsServer < cutoff) {+ this.state.audience.delete(id);+ this._rate.delete(id);+ }+ }+ }++ _rateOk(sessionId, key, limit, windowMs) {+ const now = Date.now();+ let buckets = this._rate.get(sessionId);+ if (!buckets) {+ buckets = {};+ this._rate.set(sessionId, buckets);+ }+ let b = buckets[key];+ if (!b || now - b.ts > windowMs) {+ b = { ts: now, n: 0 };+ buckets[key] = b;+ }+ b.n += 1;+ return b.n <= limit;+ }++ // ── tips (injected by the API over /internal/stage) ───────────────────────+ // The ONLY path a tip enters the show. The API has already verified the+ // on-chain settlement signature, the $THREE/USDC mint, and deduped by+ // signature, so this is a trusted, distinct, real tip. We rank it, sync the+ // leaderboard, broadcast the ticker event (visible reaction < 1s), and+ // pre-empt the next host beat so the spoken shoutout follows immediately.+ injectTip(tip) {+ if (!tip || !this._director) return { ok: false };+ const amount = Number(tip.amount) || 0;+ const { tip: recorded, isNewTopTipper } = this._director.ingestTip({+ tipperId: tip.tipperId || tip.tipper || tip.signature,+ label: tip.label || tip.tipperLabel || 'someone',+ amount,+ mint: tip.mint || tip.currencyMint || null,+ signature: tip.signature || null,+ message: tip.message || '',+ ts: Date.now(),+ });++ this.state.totalTipsAtomic = this._director.totalTipsAtomic;+ this.state.tipCount = this._director.tipCount;+ this._syncLeaderboard();++ // Promote a big tipper to the VIP front row (the host's direct attention).+ if (amount >= VIP_TIP_THRESHOLD) this._promoteVip(recorded.tipperId, tip.tipperSession);++ this.broadcast('tip', {+ label: recorded.label,+ amount: recorded.amount,+ mint: recorded.mint,+ message: recorded.message,+ isNewTopTipper,+ explorer: tip.explorer || null,+ ts: recorded.ts,+ }, { afterNextPatch: false });++ // React fast: pre-empt the cadence with an immediate beat (it will resolve+ // to a TIP_SHOUTOUT for this fresh tip). Guarded so a tip storm coalesces+ // into one in-flight beat rather than stacking brain calls.+ this._runBeat('tip');+ return { ok: true, recorded: { label: recorded.label, amount: recorded.amount } };+ }++ _promoteVip(tipperId, sessionId) {+ // Match the tipper to a connected audience member by their session (passed+ // by the API when the tipper is in the room) or by display name as a fallback.+ for (const [sid, m] of this.state.audience) {+ if ((sessionId && sid === sessionId) || (!sessionId && m.name && m.name === tipperId)) {+ m.vip = true;+ return;+ }+ }+ }++ _syncLeaderboard() {+ const ranked = this._director.leaderboard(10);+ // Rebuild the ArraySchema in place (clear + push) — a small, capped list, so+ // a full rewrite each tip is cheaper than diffing and keeps order exact.+ this.state.leaderboard.length = 0;+ for (const t of ranked) {+ const row = new StageTipper();+ row.id = t.id;+ row.label = t.label;+ row.total = t.total;+ row.count = t.count;+ this.state.leaderboard.push(row);+ }+ }++ // ── the host loop ─────────────────────────────────────────────────────────+ async _runBeat(trigger) {+ if (this._beatRunning) return; // one beat in flight at a time+ this._beatRunning = true;+ try {+ const beat = this._director.nextBeat();+ const context = this._buildContext(beat);+ const { text, cue } = await this._fetchBeat(beat, context);+ const words = clean(text, 600) || this._fallbackLine(beat);+ this._performUtterance(beat, words, cue);+ this._director.markSpoken(beat.kind);+ } catch (err) {+ console.warn(`${this._tag()} beat (${trigger}) failed: ${err?.message || err}`);+ } finally {+ this._beatRunning = false;+ }+ }++ _buildContext(beat) {+ const standings = this._director.standings();+ const ctx = {+ stageId: this.stageId,+ beat: beat.kind,+ hostName: this.state.host.name,+ title: this.state.title,+ format: this.state.format,+ audience: this.state.audience.size,+ standings,+ };+ if (beat.tip) {+ ctx.tip = {+ label: beat.tip.label,+ amount: beat.tip.amount,+ mint: beat.tip.mint,+ message: beat.tip.message,+ };+ }+ if (beat.question) ctx.question = { from: beat.question.from, text: beat.question.text };+ return ctx;+ }++ // Ask the brain (latest Claude, server-side at /api/stage/host) for the host's+ // next words. Signed with the shared secret so only this server can drive the+ // host. Returns { text, cue }; throws on transport/non-2xx so the caller's+ // fallback line keeps the show alive.+ async _fetchBeat(beat, context) {+ const body = { stageId: this.stageId, beat: beat.kind, context };+ const { ts, sig } = signStageRequest(body);+ const res = await fetch(`${API_BASE}/api/stage/host`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-stage-ts': String(ts),+ 'x-stage-sig': sig,+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(20_000),+ });+ if (!res.ok) throw new Error(`host http ${res.status}`);+ const data = await res.json();+ return { text: data?.text || '', cue: data?.cue || cueFor(beat.kind) };+ }++ _performUtterance(beat, words, cue) {+ const h = this.state.host;+ h.utteranceId = (h.utteranceId + 1) % 0xffffffff;+ h.beat = beat.kind;+ h.caption = words;+ h.cue = cue || cueFor(beat.kind);+ h.speaking = true;+ h.startedAtMs = Date.now();+ if (this.state.phase === 'preshow') this.state.phase = 'live';++ const durationMs = Math.min(SPEAK_MAX_MS, Math.max(SPEAK_MIN_MS, words.length * SPEAK_ESTIMATE_MS));++ // The timed performance frame every client renders in sync: each fetches TTS+ // for `text` (spatial voice + lip-sync) and shows `text` as live captions.+ this.broadcast('utterance', {+ id: h.utteranceId,+ beat: beat.kind,+ text: words,+ voice: h.voice,+ cue: h.cue,+ durationMs,+ ts: h.startedAtMs,+ }, { afterNextPatch: false });++ if (this._speakTimer) this._speakTimer.clear();+ this._speakTimer = this.clock.setTimeout(() => {+ h.speaking = false;+ h.cue = 'idle';+ }, durationMs);+ }++ // Failsafe line when the brain is briefly unreachable — a real acknowledgement+ // of real show state, never invented data. Keeps the stage from going silent on+ // a transient outage; the next beat retries the brain.+ _fallbackLine(beat) {+ const name = this.state.host.name || 'your host';+ if (beat.kind === BEAT.TIP_SHOUTOUT && beat.tip) {+ return `Huge love to ${beat.tip.label} for the tip — you keep this stage alive!`;+ }+ if (beat.kind === BEAT.ANSWER && beat.question) {+ return `Good question from ${beat.question.from} — let me come back to that one.`;+ }+ if (beat.kind === BEAT.OPENER) return `Welcome in — ${name} on the stage. Pull up a seat.`;+ return `Stay with me — more coming up right now.`;+ }++ onDispose() {+ if (this._beatTimer) this._beatTimer.clear();+ if (this._speakTimer) this._speakTimer.clear();+ unregisterStage(this.stageId, this);+ console.log(`${this._tag()} disposed`);+ }+}++function cueFor(beatKind) {+ switch (beatKind) {+ case BEAT.TIP_SHOUTOUT: return 'cheer';+ case BEAT.ANSWER: return 'point';+ case BEAT.GAME: return 'dj';+ case BEAT.OPENER: return 'cheer';+ default: return 'talk';+ }+}++function clean(v, max) {+ if (typeof v !== 'string') return '';+ // Strip control characters (incl. newlines) then collapse whitespace, so no+ // multi-line or unprintable caller text reaches the synced caption or a prompt.+ return v.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);+}diff --git a/multiplayer/src/stage-registry.js b/multiplayer/src/stage-registry.jsnew file mode 100644index 000000000..03b891a47--- /dev/null+++ b/multiplayer/src/stage-registry.js@@ -0,0 +1,29 @@+// Stage registry — the in-process lookup that lets the internal /internal/stage+// webhook (called by the Vercel API after it verifies a real $THREE tip+// settlement) reach the live StageRoom for a given stageId and inject the tip so+// the host reacts within ~1s.+//+// stage_world rooms are matched with filterBy(['stageId']), so there is exactly+// one room instance per stageId in a single-process deploy — a plain Map keyed by+// stageId is the right shape. Under horizontal scaling (Redis driver) a tip could+// arrive on an instance that doesn't host the room; the webhook then reports+// `not_found` and the tip still settles + records via the API (the room reaction+// is the only thing lost), so this degrades safely rather than dropping money.++const _rooms = new Map(); // stageId → StageRoom++export function registerStage(stageId, room) {+ if (!stageId || !room) return;+ _rooms.set(String(stageId), room);+}++export function unregisterStage(stageId, room) {+ const key = String(stageId);+ // Only clear if the registered room is the one leaving — a fast dispose/recreate+ // race must never unregister the freshly-created room.+ if (_rooms.get(key) === room) _rooms.delete(key);+}++export function getStageRoom(stageId) {+ return _rooms.get(String(stageId)) || null;+}diff --git a/pages/billing.html b/pages/billing.htmlnew file mode 100644index 000000000..e53139c6e--- /dev/null+++ b/pages/billing.html@@ -0,0 +1,160 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>Billing & invoices · three.ws</title>+ <meta name="description" content="Your three.ws usage statement: every metered charge, the holder discount applied, and the on-chain settlement it traces to. Download or print your invoice." />+ <meta name="robots" content="noindex" />+ <link rel="canonical" href="https://three.ws/billing" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ .bill-wrap { max-width: 980px; margin: 0 auto; padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem; }+ .bill-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 8px; }+ .bill-head h1 { font-size: clamp(1.6rem, 3vw, 2.1rem); margin: 0; letter-spacing: -0.02em; }+ .bill-sub { color: rgba(255,255,255,0.6); font-size: 14px; margin: 4px 0 0; }+ .bill-controls { display: flex; align-items: center; gap: 10px; }+ .bill-controls select, .bill-controls a.bill-btn { font: inherit; font-size: 13px; padding: 8px 14px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.14); background: rgba(14,14,14,0.9); color: rgba(255,255,255,0.85); cursor: pointer; text-decoration: none; transition: border-color .15s, background .15s; }+ .bill-controls a.bill-btn:hover, .bill-controls select:hover { border-color: rgba(255,255,255,0.3); }+ .bill-recon { display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; padding: 6px 12px; border-radius: 999px; border: 1px solid rgba(255,255,255,0.12); margin: 14px 0 24px; }+ .bill-recon .dot { width: 8px; height: 8px; border-radius: 50%; }+ .bill-recon.ok { border-color: color-mix(in srgb, #2fbf71 50%, transparent); color: #7fe3ab; }+ .bill-recon.ok .dot { background: #2fbf71; }+ .bill-recon.warn { border-color: color-mix(in srgb, #f0a93b 55%, transparent); color: #f3c478; }+ .bill-recon.warn .dot { background: #f0a93b; }+ .bill-card { border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; background: rgba(10,10,10,0.85); overflow: hidden; }+ table.bill-table { width: 100%; border-collapse: collapse; font-size: 14px; }+ .bill-table th, .bill-table td { text-align: left; padding: 14px 18px; border-bottom: 1px solid rgba(255,255,255,0.06); }+ .bill-table th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: rgba(255,255,255,0.5); font-weight: 600; }+ .bill-table td.num, .bill-table th.num { text-align: right; font-variant-numeric: tabular-nums; }+ .bill-table tr:last-child td { border-bottom: none; }+ .bill-table .disc { color: #7fe3ab; font-size: 12px; }+ .bill-total td { font-weight: 700; font-size: 15px; border-top: 2px solid rgba(255,255,255,0.14); }+ .bill-state { padding: 56px 24px; text-align: center; color: rgba(255,255,255,0.65); }+ .bill-state h2 { font-size: 18px; color: rgba(255,255,255,0.9); margin: 0 0 8px; }+ .bill-state p { margin: 0 auto 18px; max-width: 460px; line-height: 1.55; }+ .bill-state a.cta, .bill-state button.cta { display: inline-block; font: inherit; font-weight: 600; font-size: 14px; padding: 10px 20px; border-radius: 10px; border: none; background: var(--accent, #7c5cff); color: #fff; text-decoration: none; cursor: pointer; }+ .bill-skel { height: 18px; border-radius: 6px; background: linear-gradient(90deg, rgba(255,255,255,0.05), rgba(255,255,255,0.12), rgba(255,255,255,0.05)); background-size: 200% 100%; animation: billShimmer 1.3s infinite; }+ @keyframes billShimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .bill-skel { animation: none; } }+ @media print { header, footer, #footer-container, .bill-controls, .bill-recon a { display: none !important; } body { background: #fff; color: #000; } .bill-card { border-color: #ccc; } }+ </style>+ </head>+ <body>+ <a href="#main-content" class="h-skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="bill-wrap">+ <div class="bill-head">+ <div>+ <h1>Billing & invoices</h1>+ <p class="bill-sub">Every metered charge, the $THREE holder discount applied, and the on-chain settlement it traces to.</p>+ </div>+ <div class="bill-controls">+ <label for="bill-period" class="sr-only">Statement period</label>+ <select id="bill-period" aria-label="Statement period"></select>+ <a class="bill-btn" id="bill-csv" href="#" download>Download CSV</a>+ <button class="bill-btn" id="bill-print" type="button">Print / PDF</button>+ </div>+ </div>++ <div id="bill-recon-host"></div>+ <div class="bill-card" id="bill-body" aria-live="polite"></div>+ </main>++ <script type="module">+ const body = document.getElementById('bill-body');+ const reconHost = document.getElementById('bill-recon-host');+ const periodSel = document.getElementById('bill-period');+ const csvLink = document.getElementById('bill-csv');+ const esc = (s) => String(s).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' })[c]);++ // Last 12 months as period options (UTC, YYYY-MM).+ (function buildPeriods() {+ const now = new Date();+ const opts = [];+ for (let i = 0; i < 12; i++) {+ const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1));+ const label = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;+ const human = d.toLocaleDateString(undefined, { month: 'long', year: 'numeric', timeZone: 'UTC' });+ opts.push(`<option value="${label}">${human}${i === 0 ? ' (current)' : ''}</option>`);+ }+ periodSel.innerHTML = opts.join('');+ })();++ function skeleton() {+ body.innerHTML = `<table class="bill-table"><thead><tr><th>Charge</th><th class="num">Count</th><th class="num">Total</th></tr></thead><tbody>${+ Array.from({ length: 4 }).map(() => `<tr><td><div class="bill-skel" style="width:60%"></div></td><td class="num"><div class="bill-skel" style="width:24px;margin-left:auto"></div></td><td class="num"><div class="bill-skel" style="width:50px;margin-left:auto"></div></td></tr>`).join('')+ }</tbody></table>`;+ }++ function renderSignIn() {+ reconHost.innerHTML = '';+ body.innerHTML = `<div class="bill-state"><h2>Sign in to view your invoices</h2><p>Your usage statement is private to your account. Sign in to see every charge, your holder discount, and the settlement each traces to.</p><a class="cta" href="/login?next=/billing">Sign in</a></div>`;+ }++ function renderEmpty() {+ body.innerHTML = `<div class="bill-state"><h2>No usage this period</h2><p>You haven't been billed for anything yet. Generation drafts are always free; paid lanes — High-quality generation, Game-Ready export, voice cloning, oracle calls — meter here as you use them, settled in $THREE.</p><a class="cta" href="/pricing">See what gets billed</a></div>`;+ }++ function renderError(retry) {+ reconHost.innerHTML = '';+ body.innerHTML = `<div class="bill-state"><h2>Couldn't load your statement</h2><p>We hit a snag fetching your invoice. Your charges are safe and unaffected — try again.</p><button class="cta" type="button" id="bill-retry">Retry</button></div>`;+ document.getElementById('bill-retry')?.addEventListener('click', retry);+ }++ function renderRecon(recon) {+ if (!recon || !recon.total) { reconHost.innerHTML = ''; return; }+ const ok = recon.all_reconciled;+ reconHost.innerHTML = `<span class="bill-recon ${ok ? 'ok' : 'warn'}"><span class="dot"></span>${ok ? `All ${recon.reconciled} charges reconciled to on-chain settlements` : `${recon.unreconciled} of ${recon.total} charges pending reconciliation`}</span>`;+ }++ function renderStatement(inv) {+ renderRecon(inv.reconciliation);+ if (!inv.line_items.length) { renderEmpty(); return; }+ const rows = inv.line_items.map((l) => {+ const disc = l.discount_bps > 0 ? `<span class="disc"> · ${(l.discount_bps / 100).toFixed(0)}% holder discount</span>` : '';+ return `<tr><td>${esc(l.label)}${disc}</td><td class="num">${l.count}</td><td class="num">$${l.gross_usd}</td></tr>`;+ }).join('');+ body.innerHTML = `<table class="bill-table">+ <thead><tr><th>Charge</th><th class="num">Count</th><th class="num">Total (USD)</th></tr></thead>+ <tbody>${rows}</tbody>+ <tfoot><tr class="bill-total"><td>Statement total</td><td class="num">${inv.totals.charge_count}</td><td class="num">$${inv.totals.gross_usd}</td></tr></tfoot>+ </table>`;+ }++ async function load() {+ const period = periodSel.value;+ csvLink.href = `/api/billing/invoices?period=${period}&format=csv`;+ skeleton();+ try {+ const r = await fetch(`/api/billing/invoices?period=${period}`, { headers: { accept: 'application/json' }, credentials: 'include' });+ if (r.status === 401) { renderSignIn(); return; }+ if (!r.ok) throw new Error(`invoices ${r.status}`);+ const { invoice } = await r.json();+ renderStatement(invoice);+ } catch (err) {+ console.warn('[billing] load failed:', err?.message || err);+ renderError(load);+ }+ }++ periodSel.addEventListener('change', load);+ document.getElementById('bill-print').addEventListener('click', () => window.print());+ load();+ </script>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/pricing.html b/pages/pricing.htmlindex 2d51597d8..81295ea5c 100644--- a/pages/pricing.html+++ b/pages/pricing.html@@ -163,6 +163,7 @@quoted in USD, settled in <a href="/three">$THREE</a> at the live rate.Drafts are always free.</p>+ <div class="payg-holder" id="payg-holder" hidden></div><divclass="payg-grid"id="payg-grid"@@ -1025,6 +1026,39 @@const UNIT = { generation: 'generation', data: 'call' };const fmtUsd = (usd) => '$' + Number(usd).toFixed(2);+ // Personalized holder pricing — set from /api/pricing when the visitor+ // is signed in with $THREE held. Server is the source of truth for the+ // discounted "your price"; we never do balance math on the client.+ let holder = null;++ // A consistent holder-discount banner above the grid. Renders the real+ // resolved tier + the live discount, or the upgrade nudge for members.+ function renderHolderBanner() {+ const host = document.getElementById('payg-holder');+ if (!host) return;+ if (!holder) {+ host.innerHTML = '';+ host.hidden = true;+ return;+ }+ host.hidden = false;+ const bps = Number(holder.discount_bps || 0);+ if (bps > 0) {+ host.innerHTML = `<div class="payg-holder-card is-active">+ <span class="payg-holder-badge">${esc(holder.tier.label)}</span>+ <span class="payg-holder-msg">You hold <strong>${fmtUsd(holder.usd_held)}</strong> of $THREE — every paid lane below is <strong>${holder.discount_percent}% off</strong>, applied at checkout.</span>+ <a class="payg-holder-cta" href="/three">Manage holdings →</a>+ </div>`;+ } else {+ const toNext = holder.next_tier+ ? ` Hold <strong>${fmtUsd(holder.usd_to_next)}</strong> more of $THREE to reach <strong>${esc(holder.next_tier.label)}</strong> and unlock ${(holder.next_tier.discount_bps / 100).toFixed(0)}% off.`+ : '';+ host.innerHTML = `<div class="payg-holder-card">+ <span class="payg-holder-msg">Hold $THREE to discount every paid lane.${toNext}</span>+ <a class="payg-holder-cta" href="/three">Get $THREE →</a>+ </div>`;+ }+ }function skeleton() {grid.setAttribute('aria-busy', 'true');@@ -1073,9 +1107,16 @@fixed.map((a) => {const unit = UNIT[a.category] || 'call';- return `<article class="payg-card">- <div class="payg-card-top"><span class="payg-card-label">${esc(a.label)}</span></div>- <div class="payg-card-price"><span class="amt">${fmtUsd(a.usd)}</span><span class="unit">/ ${unit}</span></div>+ // When the signed-in holder gets a discount, strike the list+ // price and show their real price — the number checkout quotes.+ const yours = a.your_usd != null ? Number(a.your_usd) : null;+ const discounted = yours != null && yours < Number(a.usd);+ const priceHtml = discounted+ ? `<span class="amt"><s class="payg-was">${fmtUsd(a.usd)}</s> ${fmtUsd(yours)}</span><span class="unit">/ ${unit}</span>`+ : `<span class="amt">${fmtUsd(a.usd)}</span><span class="unit">/ ${unit}</span>`;+ return `<article class="payg-card${discounted ? ' is-yourprice' : ''}">+ <div class="payg-card-top"><span class="payg-card-label">${esc(a.label)}</span>${discounted ? '<span class="payg-badge is-discount">your price</span>' : ''}</div>+ <div class="payg-card-price">${priceHtml}</div><div class="payg-card-settle">settled in <strong>$THREE</strong></div></article>`;})@@ -1086,10 +1127,15 @@async function load() {skeleton();try {- const r = await fetch('/api/three/catalog', { headers: { accept: 'application/json' } });- if (!r.ok) throw new Error(`catalog ${r.status}`);- const { actions } = await r.json();- render(actions);+ // /api/pricing is the canonical server-truth surface: catalog ++ // platform fee + holder discount ladder + a personalized "your+ // price" when signed in. Credentials so the session is read.+ const r = await fetch('/api/pricing', { headers: { accept: 'application/json' }, credentials: 'include' });+ if (!r.ok) throw new Error(`pricing ${r.status}`);+ const data = await r.json();+ holder = data.holder || null;+ renderHolderBanner();+ render(data.actions);if (!viewed) {viewed = true;track(ANALYTICS_EVENTS.SURFACE_OPENED, { surface: 'pricing:pay-per-use' });diff --git a/pages/reasoning-ledger.html b/pages/reasoning-ledger.htmlnew file mode 100644index 000000000..ddf498504--- /dev/null+++ b/pages/reasoning-ledger.html@@ -0,0 +1,51 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Reasoning Ledger · three.ws</title>+ <meta+ name="description"+ content="Every consequential decision an agent makes — what it decided, why, what it predicted, and what actually happened — recorded in a tamper-evident, independently verifiable ledger. Track record you can interrogate, not trust."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/ledger" />+ <meta property="og:title" content="Reasoning Ledger · three.ws" />+ <meta+ property="og:description"+ content="An auditable, on-chain-anchored record of an agent's decisions, predictions, and real outcomes. Being wrong is visible — honesty is the trust signal."+ />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Reasoning Ledger · three.ws" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/reasoning-ledger.css" />+ <link rel="stylesheet" href="/footer.css" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/ledger" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="rl-shell" id="rl-root" aria-labelledby="rl-title">+ <!-- hydrated by /src/reasoning-ledger.js -->+ </main>++ <script type="module" src="/src/reasoning-ledger.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/three.html b/pages/three.htmlnew file mode 100644index 000000000..5289f9f0d--- /dev/null+++ b/pages/three.html@@ -0,0 +1,45 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>$THREE tiers · Hold-to-access perks · three.ws</title>+ <meta name="description" content="Hold $THREE to unlock platform-wide perks — fee discounts on compute, higher free quotas, private and branded worlds. See every tier, what it unlocks, and how much $THREE you hold to reach it. $THREE is the only coin on three.ws." />+ <meta property="og:title" content="$THREE tiers · Hold-to-access on three.ws" />+ <meta property="og:description" content="Hold $THREE to unlock fee discounts, higher free quotas, and private worlds. The same tiers, the same upgrade path, everywhere." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/three" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="$THREE tiers · Hold-to-access on three.ws" />+ <meta name="twitter:description" content="Hold $THREE to unlock fee discounts, higher free quotas, and private worlds. The same tiers, the same upgrade path, everywhere." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="theme-color" content="#0a0a0d" />+ <link rel="canonical" href="https://three.ws/three" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <style>body{margin:0;background:#0a0a0d;color:#f5f5f7;}</style>+ </head>+ <body>+ <a href="#tier-root" class="skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="tier-root" class="tt-root" aria-label="$THREE holder tiers"></main>++ <script type="module" src="/src/three-tier-page.js"></script>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex c561efd5e..41f25733b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T09:51:57.351Z",+ "generated_at": "2026-06-23T10:31:59.220Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -86,6 +86,17 @@"launch"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Agent profiles: a guided first run for brand-new agents, and one-click into the right studio",+ "summary": "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.",+ "link": "/agents",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 38e0449b6..e91cb8ccb 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<category>launch</category><description>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.</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>+ <guid isPermaLink="false">2026-06-23:Agent profiles: a guided first run for brand-new agents, and one-click into the right studio</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item><item><title>Audio2Face: your avatar's face now moves with its voice</title><link>https://three.ws/audio2face</link>diff --git a/public/features.json b/public/features.jsonindex fd39a475d..90c9134f5 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T09:51:57.197Z",+ "generated_at": "2026-06-23T10:31:59.087Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/pricing.css b/public/pricing.cssindex 4ed7c6821..a5d2b5523 100644--- a/public/pricing.css+++ b/public/pricing.css@@ -1002,6 +1002,70 @@box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);}+/* ── Holder discount banner + personalized "your price" ──────────────────── */+.payg-holder {+ margin: 0 0 18px;+}+.payg-holder-card {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 12px;+ padding: 14px 18px;+ border-radius: 14px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ background: rgba(14, 14, 14, 0.92);+ font-size: 13.5px;+ color: rgba(255, 255, 255, 0.78);+}+.payg-holder-card.is-active {+ border-color: color-mix(in srgb, var(--accent, #7c5cff) 55%, transparent);+ background: color-mix(in srgb, var(--accent, #7c5cff) 12%, rgba(14, 14, 14, 0.92));+}+.payg-holder-badge {+ flex: 0 0 auto;+ font-family: var(--font-mono, 'SF Mono', monospace);+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ padding: 4px 10px;+ border-radius: 999px;+ color: #fff;+ background: var(--accent, #7c5cff);+}+.payg-holder-msg {+ flex: 1 1 240px;+ line-height: 1.45;+}+.payg-holder-msg strong {+ color: rgba(255, 255, 255, 0.95);+}+.payg-holder-cta {+ flex: 0 0 auto;+ font-weight: 600;+ font-size: 13px;+ color: var(--accent, #7c5cff);+ text-decoration: none;+ transition: opacity 0.15s;+}+.payg-holder-cta:hover {+ opacity: 0.8;+}+.payg-card.is-yourprice {+ border-color: color-mix(in srgb, var(--accent, #7c5cff) 45%, rgba(255, 255, 255, 0.08));+}+.payg-badge.is-discount {+ color: #fff;+ background: var(--accent, #7c5cff);+}+.payg-was {+ color: rgba(255, 255, 255, 0.4);+ font-weight: 400;+ margin-right: 6px;+ text-decoration-thickness: 1px;+}+.payg-card-top {display: flex;align-items: center;diff --git a/public/push-sw.js b/public/push-sw.jsnew file mode 100644index 000000000..a9b5b140b--- /dev/null+++ b/public/push-sw.js@@ -0,0 +1,95 @@+/* eslint-env serviceworker */+/* global clients */+//+// Web Push handlers, imported into the VitePWA-generated service worker via+// `workbox.importScripts: ['/push-sw.js']` (see vite.config.js). Kept as a plain+// classic worker script (no imports) so importScripts can pull it in.+//+// Responsibilities:+// • push — render the OS notification from the JSON payload+// api/_lib/notify-prefs.js#pushPayloadFor produced.+// • notificationclick — focus or open the target URL (tagged ?source=push so+// the app records a `returned` funnel event), and beacon a+// `opened` event so sent→opened→returned is measurable.++self.addEventListener('push', (event) => {+ let data = {};+ try {+ data = event.data ? event.data.json() : {};+ } catch {+ // Some push services deliver a bare string; degrade gracefully.+ data = { title: 'three.ws', body: event.data ? event.data.text() : '' };+ }++ const title = data.title || 'three.ws';+ const options = {+ body: data.body || '',+ tag: data.tag || undefined,+ // Coalesce repeats of the same type into one notification line.+ renotify: Boolean(data.tag),+ icon: '/pwa-192x192.png',+ badge: '/pwa-192x192.png',+ data: {+ url: data.url || '/dashboard/',+ notificationId: data.notificationId || null,+ category: data.category || null,+ },+ };++ event.waitUntil(self.registration.showNotification(title, options));+});++self.addEventListener('notificationclick', (event) => {+ event.notification.close();+ const d = event.notification.data || {};+ const rawUrl = typeof d.url === 'string' && d.url ? d.url : '/dashboard/';++ event.waitUntil((async () => {+ // Record the open before navigating so the beacon isn't cut off.+ await trackOpen(d.notificationId);++ // Same-origin internal links open/focus an existing tab and carry the+ // push attribution params; external links (e.g. solscan) open directly.+ const isInternal = rawUrl.startsWith('/');+ const target = isInternal ? withPushParams(rawUrl, d.notificationId) : rawUrl;++ if (isInternal) {+ const all = await clients.matchAll({ type: 'window', includeUncontrolled: true });+ const origin = self.location.origin;+ for (const c of all) {+ if (c.url.startsWith(origin) && 'focus' in c) {+ await c.focus();+ if ('navigate' in c) { try { await c.navigate(target); } catch { /* cross-doc nav blocked */ } }+ return;+ }+ }+ }+ if (clients.openWindow) await clients.openWindow(target);+ })());+});++function withPushParams(path, notificationId) {+ const sep = path.includes('?') ? '&' : '?';+ let out = `${path}${sep}source=push`;+ if (notificationId) out += `&n=${encodeURIComponent(notificationId)}`;+ return out;+}++// Fire-and-forget funnel beacon. credentials:'include' carries the session+// cookie so the server can attribute the open; a logged-out click is a no-op.+async function trackOpen(notificationId) {+ try {+ await fetch('/api/notifications/track', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ notification_id: notificationId || undefined,+ channel: 'push',+ event: 'opened',+ }),+ });+ } catch {+ /* offline / blocked — the open still proceeds */+ }+}diff --git a/public/referral-capture.js b/public/referral-capture.jsindex b6859cb98..5e2cac3eb 100644--- a/public/referral-capture.js+++ b/public/referral-capture.js@@ -31,10 +31,45 @@}}+ // Fire a one-per-session visit beacon so the growth funnel can measure+ // share→visit→signup and the loop's k-factor. Best-effort and privacy-safe:+ // the server stores only a hash of (ip + ua + code), never raw identifiers.+ function beaconVisit(code) {+ try {+ var seenKey = 'tw:ref:visited';+ var seen = sessionStorage.getItem(seenKey);+ if (seen === code) return; // already counted this code this session+ sessionStorage.setItem(seenKey, code);+ } catch {+ // No sessionStorage (private mode) — still send once per page load.+ }+ var url = '/api/referral/visit';+ var payload = JSON.stringify({ code: code });+ try {+ if (navigator && typeof navigator.sendBeacon === 'function') {+ var blob = new Blob([payload], { type: 'application/json' });+ if (navigator.sendBeacon(url, blob)) return;+ }+ } catch {+ /* fall through to fetch */+ }+ try {+ fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: payload,+ keepalive: true,+ }).catch(function () {});+ } catch {+ /* visit tracking is best-effort */+ }+ }+try {var code = readParam();if (code) {localStorage.setItem(KEY, JSON.stringify({ code: code, ts: Date.now() }));+ beaconVisit(code);} else {// Expire a stale capture so it never attributes a much later signup.var existing = localStorage.getItem(KEY);diff --git a/scripts/reconcile-usage.mjs b/scripts/reconcile-usage.mjsnew file mode 100644index 000000000..a603dbcec--- /dev/null+++ b/scripts/reconcile-usage.mjs@@ -0,0 +1,125 @@+#!/usr/bin/env node+/**+ * Reconciliation pass for the usage metering ledger — the trust bar made concrete.+ *+ * The books balance only when every metered charge maps to a real settlement and+ * every settlement that should have produced usage actually did. This script+ * cross-checks the two sides and reports the drift:+ *+ * 1. usage WITHOUT settlement — a usage_events row whose settlement_ref points+ * at no token_payments row (or AWS metering ack). Money was billed but we+ * can't prove it settled → must be investigated.+ * 2. settlement WITHOUT usage — a token_payments row for a priced action with+ * no metered usage_event → revenue settled but never made it onto a+ * statement (a missed meter; the reconciliation safety net catches it).+ *+ * SAFE BY DEFAULT: read-only. Exits non-zero when unreconciled rows exist so CI /+ * a cron can alert. Reads DATABASE_URL from env.+ *+ * Usage:+ * node scripts/reconcile-usage.mjs # last 30 days+ * node scripts/reconcile-usage.mjs --days 90+ * node scripts/reconcile-usage.mjs --json # machine-readable+ */++import { neon } from '@neondatabase/serverless';++const args = process.argv.slice(2);+const flag = (name, def) => {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : def;+};+const asJson = args.includes('--json');+const days = Math.max(1, Number(flag('--days', '30')) || 30);++const DATABASE_URL = process.env.DATABASE_URL;+if (!DATABASE_URL) {+ console.error('reconcile-usage: DATABASE_URL is not set');+ process.exit(2);+}++const sql = neon(DATABASE_URL);+const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);++// 1. Metered usage whose settlement can't be matched to a real record.+const usageWithoutSettlement = await sql`+ select ue.id, ue.meter_action, ue.settlement_ref, ue.settlement_kind,+ ue.price_usdc_atomics, ue.created_at+ from usage_events ue+ where ue.kind = 'metered'+ and ue.created_at >= ${since}+ and not (+ (ue.settlement_kind = 'three' and exists (+ select 1 from token_payments tp where tp.id::text = ue.settlement_ref))+ or (ue.settlement_kind = 'aws' and exists (+ select 1 from aws_marketplace_metering am where am.usage_allocation_id = ue.settlement_ref))+ or (ue.settlement_kind not in ('three','aws') and ue.settlement_ref is not null)+ )+ order by ue.created_at desc+ limit 500+`;++// 2. Settled $THREE payments for a priced action with no metered usage row.+// token_payments.purpose carries the catalog action; rewards/treasury internal+// transfers and non-catalog purposes are excluded by joining on the existence+// of a usage row keyed by this payment id.+const settlementWithoutUsage = await sql`+ select tp.id, tp.purpose, tp.usd, tp.tx_signature, tp.created_at+ from token_payments tp+ where tp.created_at >= ${since}+ and not exists (+ select 1 from usage_events ue+ where ue.kind = 'metered'+ and ue.settlement_kind = 'three'+ and ue.settlement_ref = tp.id::text+ )+ order by tp.created_at desc+ limit 500+`;++const [counts] = await sql`+ select+ count(*) filter (where kind = 'metered' and created_at >= ${since})::int as metered_total+ from usage_events+`;++const report = {+ window_days: days,+ since: since.toISOString(),+ metered_total: counts?.metered_total ?? 0,+ usage_without_settlement: usageWithoutSettlement.length,+ settlement_without_usage: settlementWithoutUsage.length,+ reconciled: usageWithoutSettlement.length === 0,+ samples: {+ usage_without_settlement: usageWithoutSettlement.slice(0, 20),+ settlement_without_usage: settlementWithoutUsage.slice(0, 20),+ },+};++if (asJson) {+ console.log(JSON.stringify(report, null, 2));+} else {+ console.log(`\nUsage reconciliation — last ${days} day(s) (since ${report.since})`);+ console.log(` metered charges: ${report.metered_total}`);+ console.log(` usage without settlement: ${report.usage_without_settlement}`);+ console.log(` settlement without usage: ${report.settlement_without_usage}`);+ console.log(` status: ${report.reconciled ? '✓ all charges reconciled' : '✗ UNRECONCILED — investigate'}`);+ if (usageWithoutSettlement.length) {+ console.log('\n Unreconciled usage (first 20):');+ for (const r of usageWithoutSettlement.slice(0, 20)) {+ console.log(` #${r.id} ${r.meter_action} ref=${r.settlement_ref} (${r.settlement_kind}) ${r.created_at?.toISOString?.() ?? r.created_at}`);+ }+ }+ if (settlementWithoutUsage.length) {+ console.log('\n Settlements without a usage row (first 20):');+ for (const r of settlementWithoutUsage.slice(0, 20)) {+ console.log(` ${r.id} ${r.purpose} $${r.usd} tx=${r.tx_signature}`);+ }+ }+ console.log('');+}++// usage-without-settlement is the hard failure (money billed, no proof it+// settled). settlement-without-usage is a softer signal (a missed meter the+// pass surfaces) and does not fail the run on its own.+process.exit(usageWithoutSettlement.length > 0 ? 1 : 0);diff --git a/src/agent-detail.js b/src/agent-detail.jsindex d8a620735..ede0f2e5c 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -1101,8 +1101,8 @@ async function loadExtraSections(agentId, rec, isOwner) {renderOwnerEmptyCard('ad-actions-card', 'ad-actions-list', {icon: '⚡',title: 'No signed actions yet',- body: 'Every trade, launch, and skill invocation this agent makes is logged here with a verifiable signature. Give it a strategy or chat with it to get started.',- ctaHref: `/agents/${encodeURIComponent(agentId)}/studio`,+ body: 'Every trade, launch, and skill invocation this agent makes is logged here with a verifiable signature. Turn on capabilities in the studio to get it working.',+ ctaHref: `/agent-studio?id=${encodeURIComponent(agentId)}#skills`,ctaText: 'Open agent studio →',});if (memory?.entries?.length) renderMemory(memory.entries);@@ -1110,9 +1110,9 @@ async function loadExtraSections(agentId, rec, isOwner) {renderOwnerEmptyCard('ad-memory-card', 'ad-memory-list', {icon: '🧠',title: 'No memories yet',- body: 'This agent builds long-term memory as it works and converses. Start a conversation to seed what it remembers.',- ctaHref: `/agents/${encodeURIComponent(agentId)}/talk`,- ctaText: 'Chat with this agent →',+ body: 'This agent builds long-term memory as it works and converses. Seed what it remembers from the memory studio.',+ ctaHref: `/agent-studio?id=${encodeURIComponent(agentId)}#memory`,+ ctaText: 'Open memory studio →',});if (strategy?.data?.strategy != null) renderStrategy(strategy.data.strategy);else if (isOwner)@@ -1120,7 +1120,7 @@ async function loadExtraSections(agentId, rec, isOwner) {icon: '🎯',title: 'No strategy set',body: 'Define how this agent trades, allocates, and acts on its own. A strategy turns the wallet above into an autonomous operator.',- ctaHref: `/agents/${encodeURIComponent(agentId)}/studio`,+ ctaHref: `/agent-studio?id=${encodeURIComponent(agentId)}#brain`,ctaText: 'Set a strategy →',});if (reputation && (reputation.count > 0 || reputation.average > 0))diff --git a/src/forge.js b/src/forge.jsindex 91c741dd4..a7a405cbe 100644--- a/src/forge.js+++ b/src/forge.js@@ -708,7 +708,7 @@ async function reflectHighAccess(tierId, { silent = false } = {}) {renderLock(host,lockStateFromAccess(access, {- getThreeUrl: '/three-token',+ getThreeUrl: '/three',onUseFree: () => selectTier('standard'),useFreeLabel: 'Use Standard (free)',// Working Pay-per-use CTA: pay $THREE for one High generation in place.diff --git a/src/notifications.js b/src/notifications.jsindex 3031d3410..64f316a6c 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -7,8 +7,13 @@// All API calls are fire-and-forget with credentials: 'include'. A 401 just// means the user is not signed in — the badge stays hidden.+import { isPushSupported, getPushState, getPushConfig, enablePush } from './push-notifications.js';+const POLL_INTERVAL = 30_000;const AUTH_HINT_KEY = '3dagent:auth-hint';+// Remember a dismissed/declined push prompt so the value-moment banner isn't+// nagging — re-offer only via the explicit preference-center toggle after this.+const PUSH_PROMPT_KEY = '3dagent:push-prompt-dismissed';// Cross-tab coordination. The inbox badge mounts in every open tab, and the// /api/notifications budget is keyed per user — so N tabs each polling on their@@ -182,6 +187,17 @@ function relTime(dateStr) {return `${Math.floor(h / 24)}d ago`;}+// Fire-and-forget funnel beacon for the in-app channel. The push channel is+// instrumented from the service worker; this closes the loop for inbox opens.+function trackInApp(notificationId, event) {+ fetch('/api/notifications/track', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ notification_id: notificationId, channel: 'in_app', event }),+ }).catch(() => {});+}+function isAuthed() {try {const raw = localStorage.getItem(AUTH_HINT_KEY);@@ -326,6 +342,7 @@ class NotificationInbox {if (isAuthed()) {this._renderBody();+ this._maybeRenderPushBanner();if (this._unread > 0) this._markAllRead();} else {this._renderLoggedOut();@@ -421,6 +438,7 @@ class NotificationInbox {const activate = () => {const id = row.dataset.id;const link = row.dataset.link;+ if (id) trackInApp(id, 'opened');if (id && row.classList.contains('is-unread')) this._markOneRead(id, row);if (link) {if (link.startsWith('http')) {@@ -436,6 +454,57 @@ class NotificationInbox {});}+ // Value-moment push prompt: only offered while the user is actively looking+ // at their notifications, never on page load. Hidden when push is+ // unsupported/unconfigured, already granted, previously denied, or dismissed.+ async _maybeRenderPushBanner() {+ if (!isPushSupported()) return;+ try {+ if (localStorage.getItem(PUSH_PROMPT_KEY) === '1') return;+ } catch { /* storage disabled — still offer */ }++ const [{ pushEnabled }, state] = await Promise.all([getPushConfig(), getPushState()]);+ if (!pushEnabled || !state.supported) return;+ if (state.subscribed || state.permission === 'denied') return;+ // Panel may have closed while we awaited.+ const body = this._panel?.querySelector('.notif-panel-body');+ if (!this._open || !body) return;++ const banner = document.createElement('div');+ banner.className = 'notif-push-banner';+ banner.innerHTML = `+ <div class="notif-push-copy">+ <span class="notif-push-icon" aria-hidden="true">🔔</span>+ <span>Get notified the moment your agent earns or sells.</span>+ </div>+ <div class="notif-push-actions">+ <button type="button" class="notif-push-enable">Turn on push</button>+ <button type="button" class="notif-push-dismiss" aria-label="Dismiss">Not now</button>+ </div>+ `;+ body.prepend(banner);++ banner.querySelector('.notif-push-enable').addEventListener('click', async (e) => {+ e.stopPropagation();+ const btn = e.currentTarget;+ btn.disabled = true;+ btn.textContent = 'Enabling…';+ const res = await enablePush();+ if (res.ok) {+ banner.remove();+ } else {+ btn.disabled = false;+ btn.textContent = res.reason === 'denied' ? 'Blocked in browser' : 'Try again';+ if (res.reason === 'denied') { try { localStorage.setItem(PUSH_PROMPT_KEY, '1'); } catch {} }+ }+ });+ banner.querySelector('.notif-push-dismiss').addEventListener('click', (e) => {+ e.stopPropagation();+ try { localStorage.setItem(PUSH_PROMPT_KEY, '1'); } catch {}+ banner.remove();+ });+ }+_renderLoggedOut() {const body = this._panel?.querySelector('.notif-panel-body');if (!body) return;diff --git a/src/push-notifications.js b/src/push-notifications.jsnew file mode 100644index 000000000..3563ae6d6--- /dev/null+++ b/src/push-notifications.js@@ -0,0 +1,187 @@+// Web Push — client controller.+//+// Subscribes the browser to push via the already-registered VitePWA service+// worker, registers the subscription with the backend, and drives the+// re-engagement funnel's `returned` signal. Deliberately does NOT prompt on+// load — `enablePush()` is only ever called from a value moment (the inbox+// "turn on push" banner, or the preference center toggle).+//+// Public API:+// isPushSupported() → boolean (SW + PushManager + Notification)+// getPushConfig() → { pushEnabled, vapidPublicKey }+// getPushState() → { supported, permission, subscribed }+// enablePush() → subscribe + register; returns final state+// disablePush() → unsubscribe + deregister+// trackReturnedFromPush() → record `returned` when booted from a push click++let _configPromise = null;++export function isPushSupported() {+ return (+ typeof navigator !== 'undefined' &&+ 'serviceWorker' in navigator &&+ typeof window !== 'undefined' &&+ 'PushManager' in window &&+ 'Notification' in window+ );+}++export async function getPushConfig() {+ if (!_configPromise) {+ _configPromise = fetch('/api/config', { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((c) => ({+ pushEnabled: Boolean(c?.pushEnabled),+ vapidPublicKey: c?.vapidPublicKey || '',+ }))+ .catch(() => ({ pushEnabled: false, vapidPublicKey: '' }));+ }+ return _configPromise;+}++export async function getPushState() {+ if (!isPushSupported()) {+ return { supported: false, permission: 'unsupported', subscribed: false };+ }+ const permission = Notification.permission;+ let subscribed = false;+ try {+ const reg = await navigator.serviceWorker.getRegistration();+ const sub = await reg?.pushManager?.getSubscription();+ subscribed = Boolean(sub);+ } catch {+ /* registration not ready yet */+ }+ return { supported: true, permission, subscribed };+}++// Subscribe + register. Returns { ok, reason?, state }. `reason` is one of+// 'unsupported' | 'unconfigured' | 'denied' | 'error' on failure.+export async function enablePush() {+ if (!isPushSupported()) return { ok: false, reason: 'unsupported', state: await getPushState() };++ const { pushEnabled, vapidPublicKey } = await getPushConfig();+ if (!pushEnabled || !vapidPublicKey) {+ return { ok: false, reason: 'unconfigured', state: await getPushState() };+ }++ const permission = await Notification.requestPermission();+ if (permission !== 'granted') {+ return { ok: false, reason: permission === 'denied' ? 'denied' : 'dismissed', state: await getPushState() };+ }++ try {+ const reg = await navigator.serviceWorker.ready;+ let sub = await reg.pushManager.getSubscription();+ if (!sub) {+ sub = await reg.pushManager.subscribe({+ userVisibleOnly: true,+ applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),+ });+ }+ await registerSubscription(sub);+ return { ok: true, state: await getPushState() };+ } catch (err) {+ console.error('[push] subscribe failed', err);+ return { ok: false, reason: 'error', state: await getPushState() };+ }+}++export async function disablePush() {+ if (!isPushSupported()) return { ok: true };+ try {+ const reg = await navigator.serviceWorker.getRegistration();+ const sub = await reg?.pushManager?.getSubscription();+ if (sub) {+ await deregisterSubscription(sub.endpoint);+ await sub.unsubscribe();+ }+ return { ok: true };+ } catch (err) {+ console.error('[push] unsubscribe failed', err);+ return { ok: false };+ }+}++// When the page boots from a push click (the SW appends ?source=push&n=<id>),+// record the `returned` funnel event and strip the params so a reload/share of+// the URL doesn't double-count or leak the notification id.+export async function trackReturnedFromPush() {+ try {+ const params = new URLSearchParams(location.search);+ if (params.get('source') !== 'push') return;+ const n = params.get('n');+ await fetch('/api/notifications/track', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ notification_id: n || undefined,+ channel: 'push',+ event: 'returned',+ }),+ }).catch(() => {});++ params.delete('source');+ params.delete('n');+ const qs = params.toString();+ const clean = location.pathname + (qs ? `?${qs}` : '') + location.hash;+ history.replaceState(null, '', clean);+ } catch {+ /* non-fatal */+ }+}++// ── backend register/deregister ──────────────────────────────────────────────++async function registerSubscription(sub) {+ const csrf = await getCsrf();+ const r = await fetch('/api/push/subscribe', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },+ body: JSON.stringify({ subscription: sub.toJSON() }),+ });+ if (!r.ok && r.status !== 201) throw new Error(`register failed: ${r.status}`);+}++async function deregisterSubscription(endpoint) {+ const csrf = await getCsrf();+ await fetch('/api/push/subscribe', {+ method: 'DELETE',+ credentials: 'include',+ headers: { 'content-type': 'application/json', ...(csrf ? { 'x-csrf-token': csrf } : {}) },+ body: JSON.stringify({ endpoint }),+ }).catch(() => {});+}++// Single-use CSRF token (server burns it on first use; never cache).+async function getCsrf() {+ try {+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ if (!r.ok) return null;+ const j = await r.json().catch(() => null);+ return j?.data?.token || null;+ } catch {+ return null;+ }+}++// VAPID keys arrive base64url; PushManager wants a Uint8Array.+function urlBase64ToUint8Array(base64String) {+ const padding = '='.repeat((4 - (base64String.length % 4)) % 4);+ const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');+ const raw = atob(base64);+ const out = new Uint8Array(raw.length);+ for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);+ return out;+}++// Auto-record a push-sourced return as soon as the module loads.+if (typeof window !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', trackReturnedFromPush, { once: true });+ } else {+ trackReturnedFromPush();+ }+}diff --git a/src/reasoning-ledger.css b/src/reasoning-ledger.cssnew file mode 100644index 000000000..eca4f76fe--- /dev/null+++ b/src/reasoning-ledger.css@@ -0,0 +1,201 @@+/* The Reasoning Ledger — auditable agent track record.+ Self-contained; leans on the global tokens (--bg, --line, --mono) with+ safe fallbacks so the page stands alone if loaded before the theme sheet. */++:root {+ --rl-bg: var(--bg, #0b0b0c);+ --rl-card: color-mix(in srgb, var(--bg, #0b0b0c) 86%, #fff 4%);+ --rl-line: var(--line, rgba(255, 255, 255, 0.1));+ --rl-line-2: color-mix(in srgb, var(--line, rgba(255, 255, 255, 0.1)) 60%, transparent);+ --rl-text: var(--text, #e8eaf0);+ --rl-muted: color-mix(in srgb, var(--text, #e8eaf0) 55%, transparent);+ --rl-dim: color-mix(in srgb, var(--text, #e8eaf0) 35%, transparent);+ --rl-green: #4ade80;+ --rl-red: #f87171;+ --rl-amber: #fbbf24;+ --rl-cyan: #57c7ff;+ --rl-violet: #a78bfa;+ --rl-mono: var(--mono, ui-monospace, "SF Mono", Menlo, monospace);+ --rl-r: 14px;+}++.rl-shell {+ max-width: 1040px;+ margin: 0 auto;+ padding: clamp(16px, 4vw, 40px) clamp(14px, 4vw, 28px) 80px;+ color: var(--rl-text);+}++/* ── Hero ───────────────────────────────────────────────────────────── */+.rl-kicker {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font: 600 12px/1 var(--rl-mono);+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--rl-cyan);+ margin: 0 0 12px;+}+.rl-kicker .rl-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--rl-cyan);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--rl-cyan) 60%, transparent);+ animation: rl-pulse 1.8s ease infinite;+}+@keyframes rl-pulse {+ 0%, 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--rl-cyan) 55%, transparent); }+ 70% { box-shadow: 0 0 0 7px transparent; }+}+.rl-title { font-size: clamp(26px, 5vw, 40px); line-height: 1.05; margin: 0 0 10px; letter-spacing: -0.02em; }+.rl-sub { color: var(--rl-muted); max-width: 64ch; margin: 0 0 8px; line-height: 1.5; }++.rl-agent-head {+ display: flex;+ align-items: center;+ gap: 14px;+ margin: 4px 0 22px;+}+.rl-agent-avatar {+ width: 52px; height: 52px; border-radius: 12px; object-fit: cover;+ border: 1px solid var(--rl-line); background: var(--rl-card); flex: none;+}+.rl-agent-name { font-size: 20px; font-weight: 700; margin: 0; }+.rl-agent-id { font: 500 12px/1.3 var(--rl-mono); color: var(--rl-dim); }+.rl-agent-id a { color: var(--rl-muted); text-decoration: none; }+.rl-agent-id a:hover { color: var(--rl-cyan); }++/* ── Cards ──────────────────────────────────────────────────────────── */+.rl-card {+ background: var(--rl-card);+ border: 1px solid var(--rl-line);+ border-radius: var(--rl-r);+ padding: 18px 18px 16px;+ margin: 0 0 18px;+}+.rl-card-head { display: flex; align-items: center; gap: 10px; margin: 0 0 14px; }+.rl-card-head h2 { font-size: 13px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--rl-muted); margin: 0; font-weight: 700; }++/* ── Reputation summary ─────────────────────────────────────────────── */+.rl-rep-grid {+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 22px;+ align-items: center;+}+@media (max-width: 620px) { .rl-rep-grid { grid-template-columns: 1fr; } }++.rl-score-ring { position: relative; width: 132px; height: 132px; flex: none; }+.rl-score-ring svg { transform: rotate(-90deg); width: 100%; height: 100%; }+.rl-score-ring .rl-score-num {+ position: absolute; inset: 0; display: grid; place-content: center; text-align: center;+}+.rl-score-ring .rl-score-val { font-size: 38px; font-weight: 800; line-height: 1; }+.rl-score-ring .rl-score-cap { font: 600 10px/1 var(--rl-mono); color: var(--rl-dim); letter-spacing: 0.1em; text-transform: uppercase; margin-top: 5px; }++.rl-rep-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 14px 18px; }+.rl-stat dt { font: 600 11px/1 var(--rl-mono); color: var(--rl-dim); text-transform: uppercase; letter-spacing: 0.06em; margin: 0 0 5px; }+.rl-stat dd { margin: 0; font-size: 17px; font-weight: 700; }+.rl-stat dd small { font-size: 12px; color: var(--rl-muted); font-weight: 500; }+.pos { color: var(--rl-green); }+.neg { color: var(--rl-red); }++/* ── Verify badge ───────────────────────────────────────────────────── */+.rl-verify {+ display: inline-flex; align-items: center; gap: 8px;+ padding: 6px 12px; border-radius: 999px; font: 600 12px/1 var(--rl-mono);+ border: 1px solid var(--rl-line); cursor: pointer; background: transparent; color: var(--rl-muted);+ transition: border-color .15s, color .15s, background .15s;+}+.rl-verify:hover { border-color: var(--rl-line-2); }+.rl-verify .rl-vdot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; flex: none; }+.rl-verify.is-verified { color: var(--rl-green); border-color: color-mix(in srgb, var(--rl-green) 40%, transparent); background: color-mix(in srgb, var(--rl-green) 10%, transparent); }+.rl-verify.is-unanchored { color: var(--rl-amber); border-color: color-mix(in srgb, var(--rl-amber) 40%, transparent); }+.rl-verify.is-failed { color: var(--rl-red); border-color: color-mix(in srgb, var(--rl-red) 45%, transparent); background: color-mix(in srgb, var(--rl-red) 10%, transparent); }+.rl-verify.is-checking { color: var(--rl-cyan); }+.rl-verify.is-checking .rl-vdot { animation: rl-pulse 1.2s ease infinite; }+.rl-verify-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-top: 14px; }+.rl-anchor-link { font: 500 12px/1 var(--rl-mono); color: var(--rl-muted); text-decoration: none; }+.rl-anchor-link:hover { color: var(--rl-cyan); }++/* ── Drill-down (how is this computed) ──────────────────────────────── */+.rl-drill summary {+ cursor: pointer; font: 600 12px/1 var(--rl-mono); color: var(--rl-cyan);+ list-style: none; padding: 4px 0; user-select: none;+}+.rl-drill summary::-webkit-details-marker { display: none; }+.rl-drill summary::before { content: "▸ "; color: var(--rl-dim); }+.rl-drill[open] summary::before { content: "▾ "; }+.rl-formula { font: 500 12px/1.6 var(--rl-mono); color: var(--rl-muted); background: color-mix(in srgb, var(--rl-bg) 50%, #000 10%); border: 1px solid var(--rl-line); border-radius: 10px; padding: 12px; margin: 10px 0; white-space: pre-wrap; }+.rl-comp { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-top: 1px solid var(--rl-line-2); }+.rl-comp:first-of-type { border-top: none; }+.rl-comp-label { flex: none; width: 120px; font-weight: 600; font-size: 13px; }+.rl-comp-bar { flex: 1; height: 7px; border-radius: 4px; background: var(--rl-line); overflow: hidden; }+.rl-comp-bar > i { display: block; height: 100%; background: var(--rl-cyan); border-radius: 4px; }+.rl-comp-val { flex: none; font: 600 12px/1 var(--rl-mono); color: var(--rl-muted); width: 92px; text-align: right; }+.rl-comp-desc { color: var(--rl-dim); font-size: 12px; margin: 2px 0 0 132px; }++/* ── Calibration chart ──────────────────────────────────────────────── */+.rl-cal-wrap { display: grid; grid-template-columns: 1fr auto; gap: 18px; align-items: center; }+@media (max-width: 620px) { .rl-cal-wrap { grid-template-columns: 1fr; } }+.rl-cal-chart { width: 100%; max-width: 340px; aspect-ratio: 1; }+.rl-cal-legend { font-size: 12px; color: var(--rl-muted); line-height: 1.6; }+.rl-cal-legend b { color: var(--rl-text); }+.rl-cal-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; vertical-align: middle; }++/* ── Filters ────────────────────────────────────────────────────────── */+.rl-filters { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin: 0 0 14px; }+.rl-search { flex: 1; min-width: 180px; }+.rl-search input, .rl-select {+ width: 100%; background: var(--rl-card); border: 1px solid var(--rl-line); color: var(--rl-text);+ border-radius: 10px; padding: 9px 12px; font: 500 13px/1 var(--rl-mono); outline: none;+}+.rl-search input:focus, .rl-select:focus { border-color: var(--rl-cyan); }+.rl-select { width: auto; cursor: pointer; }++/* ── Timeline ───────────────────────────────────────────────────────── */+.rl-timeline { display: flex; flex-direction: column; gap: 12px; }+.rl-entry {+ background: var(--rl-card); border: 1px solid var(--rl-line); border-radius: 12px;+ padding: 14px 16px; border-left: 3px solid var(--rl-line-2);+ transition: border-color .15s, transform .15s;+}+.rl-entry.win { border-left-color: var(--rl-green); }+.rl-entry.loss { border-left-color: var(--rl-red); }+.rl-entry.pending { border-left-color: var(--rl-amber); }+.rl-entry-top { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }+.rl-kind { font: 700 11px/1 var(--rl-mono); text-transform: uppercase; letter-spacing: 0.06em; padding: 4px 8px; border-radius: 6px; background: color-mix(in srgb, var(--rl-violet) 16%, transparent); color: var(--rl-violet); }+.rl-seq { font: 500 11px/1 var(--rl-mono); color: var(--rl-dim); }+.rl-when { font: 500 11px/1 var(--rl-mono); color: var(--rl-dim); margin-left: auto; }+.rl-conf { font: 600 11px/1 var(--rl-mono); color: var(--rl-muted); }+.rl-rationale { margin: 0 0 10px; line-height: 1.5; font-size: 14px; }+.rl-entry-foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }+.rl-chip { font: 600 11px/1 var(--rl-mono); padding: 4px 9px; border-radius: 999px; border: 1px solid var(--rl-line); color: var(--rl-muted); }+.rl-chip.win { color: var(--rl-green); border-color: color-mix(in srgb, var(--rl-green) 40%, transparent); background: color-mix(in srgb, var(--rl-green) 10%, transparent); }+.rl-chip.loss { color: var(--rl-red); border-color: color-mix(in srgb, var(--rl-red) 40%, transparent); background: color-mix(in srgb, var(--rl-red) 10%, transparent); }+.rl-chip.pending { color: var(--rl-amber); border-color: color-mix(in srgb, var(--rl-amber) 35%, transparent); }+.rl-chip a, a.rl-chip { text-decoration: none; color: inherit; }+.rl-proof { color: var(--rl-cyan); text-decoration: none; font: 500 11px/1 var(--rl-mono); }+.rl-proof:hover { text-decoration: underline; }+.rl-hash { font: 500 10px/1 var(--rl-mono); color: var(--rl-dim); }++.rl-more { display: block; margin: 18px auto 0; padding: 10px 22px; border-radius: 10px; border: 1px solid var(--rl-line); background: transparent; color: var(--rl-text); font: 600 13px/1 var(--rl-mono); cursor: pointer; }+.rl-more:hover { border-color: var(--rl-cyan); color: var(--rl-cyan); }+.rl-more[disabled] { opacity: 0.5; cursor: default; }++/* ── States ─────────────────────────────────────────────────────────── */+.rl-state { text-align: center; padding: 48px 20px; color: var(--rl-muted); }+.rl-state h3 { color: var(--rl-text); margin: 0 0 8px; font-size: 18px; }+.rl-state p { margin: 0 auto 16px; max-width: 46ch; line-height: 1.55; }+.rl-state .rl-btn { display: inline-block; padding: 9px 18px; border-radius: 10px; border: 1px solid var(--rl-line); color: var(--rl-text); text-decoration: none; font: 600 13px var(--rl-mono); }+.rl-state .rl-btn:hover { border-color: var(--rl-cyan); color: var(--rl-cyan); }+.rl-skel { border-radius: 12px; background: linear-gradient(90deg, var(--rl-line) 25%, var(--rl-line-2) 37%, var(--rl-line) 63%); background-size: 400% 100%; animation: rl-shimmer 1.4s ease infinite; }+@keyframes rl-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+.rl-skel-line { height: 14px; margin: 8px 0; }+.rl-skel-card { height: 96px; margin: 12px 0; }+@media (prefers-reduced-motion: reduce) {+ .rl-skel, .rl-kicker .rl-dot, .rl-verify.is-checking .rl-vdot { animation: none; }+ .rl-entry { transition: none; }+}diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.jsindex 5bd589396..0b3d947ed 100644--- a/src/studio/studio-shell.js+++ b/src/studio/studio-shell.js@@ -92,10 +92,17 @@ class StudioShell {}if (!user) return this._renderAuthGate();- // Load (auto-creates) the caller's agent through the shared store.+ // Load the caller's agent through the shared store. An explicit `?id=`+ // targets a specific owned agent (deep links from the agent profile);+ // without it we auto-create/load the caller's default agent.+ const targetId = new URLSearchParams(location.search).get('id');try {- const agent = await studio.load();+ const agent = await studio.load(targetId ? { agentId: targetId } : undefined);if (!agent || !agent.id) return this._renderEmptyAgent();+ // A targeted `?id=` can name an agent the caller doesn't own. The studio+ // is an owner console — every save is owner-gated server-side — so don't+ // render edit controls for someone else's agent; send them to its profile.+ if (targetId && agent.isOwner === false) return this._renderNotOwner(agent.id);this._renderShell(agent);this._bind();document.dispatchEvent(@@ -159,6 +166,18 @@ class StudioShell {this.root.querySelector('#studio-retry')?.addEventListener('click', onRetry);}+ _renderNotOwner(agentId) {+ this.root.innerHTML = `+ <div class="studio-gate" role="alert">+ <div class="studio-gate-inner">+ <div class="studio-gate-glyph" aria-hidden="true">🔒</div>+ <h1>This isn’t your agent</h1>+ <p>The studio is where an owner configures their own agent. You can still view this one’s public profile.</p>+ <a class="studio-btn studio-btn-primary" href="/agents/${encodeURIComponent(agentId)}">View profile</a>+ </div>+ </div>`;+ }+// ── Shell ────────────────────────────────────────────────────────────────_renderShell(agent) {diff --git a/src/three-access.js b/src/three-access.jsindex cfc231467..8e23d7cf0 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -40,7 +40,12 @@ let _tierPass = null; // { pass, tier, exp(ms), wallet } — wallet is the identlet _tierPassInFlight = null; // de-dupe concurrent mints onto one network/signature round-triplet _stylesInjected = false;-const ECONOMY_URL = '/three-token';+// The canonical holder-value surface every locked state routes to: the full tier+// ladder + the "Hold more $THREE" upgrade action (src/three-tier-page.js → /three).+const ECONOMY_URL = '/three';+// The coin's price/chart/one-click-buy page — the secondary "see the market"+// link, distinct from the upgrade surface above.+const PRICE_URL = '/three-token';// The connected Solana wallet address (Phantom on web, the Seeker TWA wallet on// mobile), or null when none is connected — in which case every read falls back to@@ -397,7 +402,7 @@ export function showThreeGate(gate, opts = {}) {<div class="tg-actions"><a class="tg-btn tg-btn--primary" id="tg-get" href="${escapeHtml(safeUrl(getUrl))}">Get $THREE</a>${payBtn}- <a class="tg-btn tg-btn--ghost" href="${ECONOMY_URL}">$THREE price & chart</a>+ <a class="tg-btn tg-btn--ghost" href="${PRICE_URL}">$THREE price & chart</a></div><p class="tg-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p></div>`;diff --git a/src/three-lock.js b/src/three-lock.jsindex 729772391..cec1c9c95 100644--- a/src/three-lock.js+++ b/src/three-lock.js@@ -19,7 +19,10 @@import { safeUrl } from './safe-url.js';-const ECONOMY_URL = '/three-token';+// Default upgrade destination: the canonical $THREE tier surface (/three), where+// the holder sees the full ladder and the "Hold more $THREE" buy action. Callers+// may override per-control via lockStateFromAccess(access, { getThreeUrl }).+const ECONOMY_URL = '/three';const SIGN_IN_URL = '/login';const LINK_WALLET_URL = '/dashboard/account#wallets';diff --git a/src/three-tier-page.js b/src/three-tier-page.jsnew file mode 100644index 000000000..174b7d9d6--- /dev/null+++ b/src/three-tier-page.js@@ -0,0 +1,534 @@+// The canonical $THREE holder-value surface (/three).+//+// One page that renders the whole hold-to-access ladder: every tier, its perks,+// the live fee discount + free-quota multiplier, and — for the connected+// wallet / signed-in holder — the current tier highlighted with the exact+// $-to-next-tier delta and a real "Hold more $THREE" action. Every locked state+// across the platform routes here (the nav tier chip, the in-place lock panels),+// so this is the single upgrade path the token's promise rests on.+//+// Truth comes from the server, never the client:+// • GET /api/three/tier → { tier, held_usd, next:{usd_to_go}, ladder:[…] }+// • GET /api/three/access → per-feature { enforced, eligible, required, … }+// Both accept ?wallet= so an account-less visitor who has connected Phantom sees+// their real on-chain tier. Both degrade to the Member floor on any hiccup, so a+// price/RPC outage shows the ladder and the upgrade path — never a dead screen.+//+// All five states are designed: a skeleton ladder while loading, a connect/sign-in+// prompt when there's no wallet in hand, an actionable error with retry, the+// populated ladder, and graceful overflow at $10M+ holdings.++import { getConnectedWalletAddress, getConnectedWallet, connectWallet } from './wallet.js';+import { openSwapModal } from './swap-jupiter.js';+import { THREE_MINT } from './pump/three-token-data.js';+import { errorStateHTML } from './shared/state-kit.js';+import { trackFunnelStep, ANALYTICS_EVENTS } from './analytics.js';++const SOL_MINT = 'So11111111111111111111111111111111111111112';+const PRICE_URL = '/three-token';+const SIGN_IN_URL = '/login';++// ── formatters ──────────────────────────────────────────────────────────────+function fmtUsd(n, max = 0) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '$0';+ return v.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: max });+}+// Compact currency so a $10M+ bag never blows out the header layout.+function fmtCompactUsd(n) {+ const v = Number(n) || 0;+ if (v >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;+ if (v >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;+ if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;+ return fmtUsd(v, v > 0 && v < 1 ? 2 : 0);+}+function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}+// Tone class by tier id — mirrors src/three-access.js / src/three-lock.js so the+// badge, the lock panels, and this ladder read as one system.+function tone(id) {+ if (id === 'gold' || id === 'genesis') return 'tt-gold';+ if (id === 'silver') return 'tt-silver';+ if (id === 'bronze') return 'tt-bronze';+ return 'tt-green';+}++// ── data ──────────────────────────────────────────────────────────────────────++// Resolve the caller's tier + the per-feature access matrix in one round-trip+// pair. Reads the connected wallet via ?wallet= when one is in hand, else the+// session cookie. Never throws — returns { tier:null } so the UI can still draw+// the public ladder and the connect/sign-in prompt.+async function loadState() {+ const wallet = (() => {+ try {+ return getConnectedWalletAddress() || null;+ } catch {+ return null;+ }+ })();+ const q = wallet ? `?wallet=${encodeURIComponent(wallet)}` : '';+ const [tierRes, accessRes] = await Promise.allSettled([+ fetch(`/api/three/tier${q}`, { credentials: 'include', headers: { accept: 'application/json' } }),+ fetch(`/api/three/access${q}`, { credentials: 'include', headers: { accept: 'application/json' } }),+ ]);++ let tier = null;+ if (tierRes.status === 'fulfilled' && tierRes.value.ok) {+ tier = await tierRes.value.json().catch(() => null);+ }+ let access = null;+ if (accessRes.status === 'fulfilled' && accessRes.value.ok) {+ access = await accessRes.value.json().catch(() => null);+ }+ return { wallet, tier, access };+}++// ── render ──────────────────────────────────────────────────────────────────++function render(root, state) {+ const { tier, access, wallet } = state;+ if (!tier || !Array.isArray(tier.ladder) || tier.ladder.length === 0) {+ // No ladder at all → a real (rare) outage. Offer a retry; the ladder is the+ // page, so there's nothing useful to show without it.+ root.innerHTML = errorStateHTML({+ title: "Couldn't load the $THREE tiers",+ body: 'The tier ladder is resolved live on-chain. Check your connection and try again.',+ });+ const retry = root.querySelector('[data-sk-retry]');+ if (retry) retry.addEventListener('click', () => boot(root));+ return;+ }++ const ladder = tier.ladder;+ const heldUsd = Number(tier.held_usd) || 0;+ const signedOut = !wallet && !(access?.wallet_linked);+ // With no wallet in hand we don't claim a tier — show the neutral ladder + a+ // connect prompt rather than presumptuously marking Member as "You're here".+ const currentLevel = signedOut ? -1 : Number(tier.tier?.level) || 0;++ // Group the gated features by the tier level that unlocks them, so each ladder+ // card lists the concrete things it turns on (with Live vs Planned honesty).+ const featuresByLevel = new Map();+ for (const f of access?.features || []) {+ const lvl = Number(f.required?.level) || 0;+ if (!featuresByLevel.has(lvl)) featuresByLevel.set(lvl, []);+ featuresByLevel.get(lvl).push(f);+ }++ root.innerHTML =+ renderHero({ tier, heldUsd, currentLevel, signedOut }) ++ `<ol class="tt-ladder" role="list" aria-label="$THREE holder tiers">` ++ ladder.map((t) => renderTier(t, { currentLevel, heldUsd, featuresByLevel })).join('') ++ `</ol>` ++ renderFooter();++ wire(root);+ enableRovingFocus(root);+}++function renderHero({ tier, heldUsd, currentLevel, signedOut }) {+ const cur = tier.tier || { id: 'member', label: 'Member' };+ const next = tier.next; // { id, label, min_usd, usd_to_go } | null+ const isHolder = currentLevel >= 1;++ let statusLine;+ let cta;+ if (signedOut) {+ statusLine = `Connect your wallet or sign in to see your tier and what you've unlocked.`;+ cta =+ `<button type="button" class="tt-btn tt-btn--primary" data-tt-connect>Connect wallet</button>` ++ `<a class="tt-btn tt-btn--ghost" href="${SIGN_IN_URL}">Sign in</a>`;+ } else if (next) {+ const toGo = Number(next.usd_to_go) || Math.max(0, (Number(next.min_usd) || 0) - heldUsd);+ statusLine = isHolder+ ? `You're <strong>${esc(cur.label)}</strong>, holding ${fmtCompactUsd(heldUsd)} of $THREE. Hold <strong>${fmtUsd(toGo, toGo < 1 ? 2 : 0)}</strong> more to reach <strong>${esc(next.label)}</strong>.`+ : `You hold ${fmtCompactUsd(heldUsd)} of $THREE. Hold <strong>${fmtUsd(toGo, toGo < 1 ? 2 : 0)}</strong> to reach <strong>${esc(next.label)}</strong> and start unlocking perks.`;+ cta =+ `<button type="button" class="tt-btn tt-btn--primary" data-tt-buy>Hold more $THREE</button>` ++ `<a class="tt-btn tt-btn--ghost" href="${PRICE_URL}">Price & chart</a>`;+ } else {+ // Top of the ladder — nothing left to upgrade to.+ statusLine = `You're <strong>${esc(cur.label)}</strong>, holding ${fmtCompactUsd(heldUsd)} of $THREE — the top tier. Every holder perk is unlocked.`;+ cta =+ `<button type="button" class="tt-btn tt-btn--primary" data-tt-buy>Add to your bag</button>` ++ `<a class="tt-btn tt-btn--ghost" href="${PRICE_URL}">Price & chart</a>`;+ }++ const chip = !signedOut && currentLevel >= 1+ ? `<span class="tt-hero-chip ${tone(cur.id)}"><span aria-hidden="true">◆</span> ${esc(cur.label)}</span>`+ : '';++ return (+ `<header class="tt-hero">` ++ `<p class="tt-eyebrow">$THREE · Hold-to-access</p>` ++ `<h1 class="tt-h1">Hold $THREE. Unlock more.${chip}</h1>` ++ `<p class="tt-lede">${statusLine}</p>` ++ `<div class="tt-hero-actions">${cta}</div>` ++ `<p class="tt-hero-foot">Holding (not spending) $THREE is the status lever — fee discounts on compute, higher free quotas, and private worlds. $THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p>` ++ `</header>`+ );+}++function renderTier(t, { currentLevel, heldUsd, featuresByLevel }) {+ const isCurrent = t.level === currentLevel;+ const isCleared = t.level < currentLevel; // already included in the user's tier+ const isMember = t.level === 0;+ const toGo = Math.max(0, (Number(t.min_usd) || 0) - heldUsd);++ const threshold = isMember+ ? 'Free for everyone'+ : `${fmtUsd(t.min_usd)}+ in $THREE`;++ const discount = Number(t.discount_bps) || 0;+ const mult = Number(t.rate_multiplier) || 1;+ const valueChips =+ !isMember || discount > 0+ ? `<div class="tt-chips">` ++ (discount > 0 ? `<span class="tt-vchip">${(discount / 100).toFixed(0)}% off compute</span>` : '') ++ (mult > 1 ? `<span class="tt-vchip">${mult}× free quota</span>` : '') ++ `</div>`+ : '';++ const statusBadge = isCurrent+ ? `<span class="tt-status tt-status--here">You're here</span>`+ : isCleared+ ? `<span class="tt-status tt-status--done">✓ Included</span>`+ : isMember+ ? ''+ : `<span class="tt-status tt-status--togo">${fmtUsd(toGo, toGo < 1 ? 2 : 0)} to go</span>`;++ const perks = (t.perks || [])+ .map((p) => `<li class="tt-perk"><span class="tt-perk-tick" aria-hidden="true">✦</span>${esc(p)}</li>`)+ .join('');++ // Concrete gated features that unlock at this tier, with Live/Planned honesty+ // and a check when the current holder already clears them.+ const feats = (featuresByLevel.get(t.level) || [])+ .map((f) => {+ const live = f.enforced+ ? `<span class="tt-flag tt-flag--live">Live</span>`+ : `<span class="tt-flag tt-flag--soon">Planned</span>`;+ const got = f.eligible ? `<span class="tt-feat-tick" aria-hidden="true">✓</span>` : '';+ return `<li class="tt-feat">${got}<span class="tt-feat-label">${esc(f.label)}</span>${live}</li>`;+ })+ .join('');+ const featsBlock = feats ? `<ul class="tt-feats" aria-label="Features unlocked at ${esc(t.label)}">${feats}</ul>` : '';++ return (+ `<li class="tt-tier ${tone(t.id)}${isCurrent ? ' tt-tier--current' : ''}${isCleared ? ' tt-tier--cleared' : ''}" ` ++ `tabindex="-1" aria-current="${isCurrent ? 'true' : 'false'}" ` ++ `aria-label="${esc(t.label)} tier — ${esc(threshold)}${isCurrent ? ', your current tier' : ''}">` ++ `<div class="tt-tier-head">` ++ `<span class="tt-tier-mark" aria-hidden="true">◆</span>` ++ `<div class="tt-tier-id"><span class="tt-tier-name">${esc(t.label)}</span>` ++ `<span class="tt-tier-thresh">${esc(threshold)}</span></div>` ++ statusBadge ++ `</div>` ++ valueChips ++ (perks ? `<ul class="tt-perks">${perks}</ul>` : '') ++ featsBlock ++ `</li>`+ );+}++function renderFooter() {+ return (+ `<footer class="tt-page-foot">` ++ `<p>Your tier is resolved live from the USD value of $THREE your wallet holds — nothing is stored, nothing is spent. Sell and your tier adjusts; the lever rewards holding.</p>` ++ `<p class="tt-mint">Contract: <a href="https://solscan.io/token/${THREE_MINT}" target="_blank" rel="noopener">${THREE_MINT}</a></p>` ++ `</footer>`+ );+}++// ── interaction ───────────────────────────────────────────────────────────────++function wire(root) {+ const connect = root.querySelector('[data-tt-connect]');+ if (connect) {+ connect.addEventListener('click', async () => {+ try {+ await connectWallet();+ } catch {+ /* the wallet module surfaces its own connect errors */+ }+ });+ }+ root.querySelectorAll('[data-tt-buy]').forEach((btn) => {+ btn.addEventListener('click', () => openBuy());+ });+}++// Open the in-app Jupiter swap (SOL → $THREE) when a wallet is connected, else+// route to the coin page's one-click buy. Either way the user can act without+// leaving the upgrade flow.+function openBuy() {+ try {+ trackFunnelStep('three', ANALYTICS_EVENTS.TOKEN_BUY_CLICKED, { source: 'tier_page' });+ trackFunnelStep('upgrade', ANALYTICS_EVENTS.UPGRADE_GET_THREE_CLICKED, { feature: 'tier_page' });+ } catch {+ /* analytics is best-effort */+ }+ let provider = null;+ let wallet = null;+ try {+ provider = getConnectedWallet();+ wallet = getConnectedWalletAddress();+ } catch {+ provider = null;+ }+ if (provider && wallet) {+ openSwapModal({+ wallet,+ getProvider: () => provider,+ defaultInputMint: SOL_MINT,+ defaultOutputMint: THREE_MINT,+ });+ return;+ }+ window.location.assign(PRICE_URL);+}++// Roving-tabindex keyboard navigation across the ladder: one stop in the tab+// order, then ↑/↓/Home/End move between tiers. The current tier is the default+// stop so a keyboard user lands on "where am I" first.+function enableRovingFocus(root) {+ const tiers = Array.from(root.querySelectorAll('.tt-tier'));+ if (tiers.length === 0) return;+ const startIdx = Math.max(0, tiers.findIndex((el) => el.classList.contains('tt-tier--current')));+ tiers.forEach((el, i) => {+ el.tabIndex = i === startIdx ? 0 : -1;+ });+ const move = (from, to) => {+ const next = Math.max(0, Math.min(tiers.length - 1, to));+ if (next === from) return;+ tiers[from].tabIndex = -1;+ tiers[next].tabIndex = 0;+ tiers[next].focus();+ };+ root.addEventListener('keydown', (e) => {+ const idx = tiers.indexOf(document.activeElement);+ if (idx === -1) return;+ switch (e.key) {+ case 'ArrowDown':+ case 'ArrowRight':+ e.preventDefault();+ move(idx, idx + 1);+ break;+ case 'ArrowUp':+ case 'ArrowLeft':+ e.preventDefault();+ move(idx, idx - 1);+ break;+ case 'Home':+ e.preventDefault();+ move(idx, 0);+ break;+ case 'End':+ e.preventDefault();+ move(idx, tiers.length - 1);+ break;+ default:+ break;+ }+ });+}++// ── states ──────────────────────────────────────────────────────────────────++function renderLoading(root) {+ const card = () =>+ `<li class="tt-tier tt-skel" aria-hidden="true">` ++ `<div class="tt-tier-head"><span class="tt-sk tt-sk--mark"></span>` ++ `<div class="tt-tier-id"><span class="tt-sk tt-sk--name"></span><span class="tt-sk tt-sk--thresh"></span></div></div>` ++ `<span class="tt-sk tt-sk--line"></span><span class="tt-sk tt-sk--line tt-sk--short"></span>` ++ `</li>`;+ root.innerHTML =+ `<header class="tt-hero"><p class="tt-eyebrow">$THREE · Hold-to-access</p>` ++ `<h1 class="tt-h1">Hold $THREE. Unlock more.</h1>` ++ `<span class="tt-sk tt-sk--lede"></span></header>` ++ `<ol class="tt-ladder" role="list" aria-busy="true">${card().repeat(5)}</ol>` ++ `<span class="tt-sr" role="status">Loading your $THREE tier…</span>`;+}++async function boot(root) {+ injectStyles();+ renderLoading(root);+ try {+ const state = await loadState();+ render(root, state);+ } catch {+ root.innerHTML = errorStateHTML({+ title: "Couldn't load the $THREE tiers",+ body: 'Something went wrong resolving your tier. Try again.',+ });+ const retry = root.querySelector('[data-sk-retry]');+ if (retry) retry.addEventListener('click', () => boot(root));+ }+}++// ── mount ─────────────────────────────────────────────────────────────────────++function mount() {+ let root = document.getElementById('tier-root');+ if (!root) {+ root = document.createElement('main');+ root.id = 'tier-root';+ root.className = 'tt-root';+ document.body.appendChild(root);+ } else {+ root.classList.add('tt-root');+ }+ try {+ trackFunnelStep('three', ANALYTICS_EVENTS.TOKEN_PAGE_VIEWED, { source: 'tier_page' });+ } catch {+ /* analytics is best-effort */+ }+ boot(root);++ // A wallet connect/disconnect/switch changes whose tier we're showing — re-resolve.+ if (typeof window !== 'undefined') {+ let last = null;+ try {+ last = getConnectedWalletAddress() || null;+ } catch {+ last = null;+ }+ window.addEventListener('wallet:changed', (e) => {+ const next =+ e?.detail && Object.prototype.hasOwnProperty.call(e.detail, 'address')+ ? e.detail.address || null+ : (() => {+ try {+ return getConnectedWalletAddress() || null;+ } catch {+ return null;+ }+ })();+ if (next === last) return;+ last = next;+ boot(root);+ });+ }+}++if (typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', mount, { once: true });+ } else {+ mount();+ }+}++// ── styles ──────────────────────────────────────────────────────────────────++let _styled = false;+function injectStyles() {+ if (_styled || typeof document === 'undefined') return;+ _styled = true;+ const css = `+ .tt-root{max-width:920px;margin:0 auto;padding:32px 18px 80px;font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:#f5f5f7;}+ .tt-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;}++ .tt-hero{margin:0 0 26px;}+ .tt-eyebrow{margin:0 0 8px;font-size:11.5px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#6ee7a8;}+ .tt-h1{margin:0 0 12px;font-size:32px;font-weight:840;letter-spacing:-.025em;line-height:1.08;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}+ .tt-hero-chip{display:inline-flex;align-items:center;gap:6px;font-size:13px;font-weight:700;border-radius:999px;padding:5px 12px;color:#6ee7a8;border:1px solid rgba(110,231,168,.32);background:rgba(110,231,168,.08);}+ .tt-hero-chip.tt-gold{color:#f5c451;border-color:rgba(245,196,81,.34);background:rgba(245,196,81,.08);}+ .tt-hero-chip.tt-silver{color:#cfd6e4;border-color:rgba(207,214,228,.3);background:rgba(207,214,228,.06);}+ .tt-hero-chip.tt-bronze{color:#e0a878;border-color:rgba(224,168,120,.32);background:rgba(224,168,120,.08);}+ .tt-lede{margin:0 0 18px;font-size:15.5px;line-height:1.55;color:#b9b9c2;max-width:62ch;}+ .tt-lede strong{color:#f5f5f7;font-weight:700;}+ .tt-hero-actions{display:flex;gap:10px;flex-wrap:wrap;}+ .tt-hero-foot{margin:16px 0 0;font-size:12px;line-height:1.6;color:#75757f;max-width:64ch;}++ .tt-btn{display:inline-flex;align-items:center;justify-content:center;font:700 14px/1 Inter,system-ui,sans-serif;+ padding:12px 20px;border-radius:12px;text-decoration:none;cursor:pointer;border:1px solid #2a2a33;+ background:#13131a;color:#f1f1f4;transition:transform .15s cubic-bezier(.22,1,.36,1),background .15s,border-color .15s;}+ .tt-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}+ .tt-btn--primary:hover{background:#8af0c0;transform:translateY(-1px);}+ .tt-btn--ghost:hover{border-color:#3a3a44;background:#181820;transform:translateY(-1px);}++ .tt-ladder{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:12px;}+ .tt-tier{position:relative;border-radius:16px;padding:18px 18px 16px;border:1px solid #1f1f27;+ background:linear-gradient(180deg,#111116,#0c0c11);transition:border-color .16s,transform .12s,box-shadow .16s;outline:none;}+ .tt-tier:hover{transform:translateY(-2px);border-color:#2c2c36;}+ .tt-tier:focus-visible{outline:2px solid #6ee7a8;outline-offset:3px;}+ .tt-tier--cleared{opacity:.78;}+ .tt-tier--current{border-color:rgba(110,231,168,.5);box-shadow:0 0 0 1px rgba(110,231,168,.25),0 18px 50px -28px rgba(110,231,168,.5);opacity:1;}+ .tt-tier.tt-gold.tt-tier--current{border-color:rgba(245,196,81,.5);box-shadow:0 0 0 1px rgba(245,196,81,.25),0 18px 50px -28px rgba(245,196,81,.45);}+ .tt-tier.tt-silver.tt-tier--current{border-color:rgba(207,214,228,.5);box-shadow:0 0 0 1px rgba(207,214,228,.22),0 18px 50px -28px rgba(207,214,228,.4);}+ .tt-tier.tt-bronze.tt-tier--current{border-color:rgba(224,168,120,.5);box-shadow:0 0 0 1px rgba(224,168,120,.24),0 18px 50px -28px rgba(224,168,120,.45);}++ .tt-tier-head{display:flex;align-items:center;gap:12px;}+ .tt-tier-mark{flex-shrink:0;width:34px;height:34px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;font-size:15px;+ color:#6ee7a8;background:rgba(110,231,168,.1);border:1px solid rgba(110,231,168,.22);}+ .tt-gold .tt-tier-mark{color:#f5c451;background:rgba(245,196,81,.1);border-color:rgba(245,196,81,.24);}+ .tt-silver .tt-tier-mark{color:#cfd6e4;background:rgba(207,214,228,.1);border-color:rgba(207,214,228,.22);}+ .tt-bronze .tt-tier-mark{color:#e0a878;background:rgba(224,168,120,.1);border-color:rgba(224,168,120,.22);}+ .tt-tier-id{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1;}+ .tt-tier-name{font-size:17px;font-weight:800;letter-spacing:-.01em;}+ .tt-tier-thresh{font-size:12.5px;color:#8a8a93;}+ .tt-status{flex-shrink:0;font-size:11.5px;font-weight:700;border-radius:999px;padding:5px 11px;white-space:nowrap;}+ .tt-status--here{color:#06120c;background:#6ee7a8;}+ .tt-status--done{color:#7fd6a3;background:rgba(110,231,168,.12);border:1px solid rgba(110,231,168,.22);}+ .tt-status--togo{color:#d7d7de;background:rgba(255,255,255,.05);border:1px solid #2a2a33;}++ .tt-chips{display:flex;flex-wrap:wrap;gap:7px;margin:12px 0 0;}+ .tt-vchip{font-size:11.5px;font-weight:700;color:#cdeede;background:rgba(110,231,168,.08);border:1px solid rgba(110,231,168,.2);border-radius:8px;padding:4px 9px;}+ .tt-gold .tt-vchip{color:#f1d79a;background:rgba(245,196,81,.08);border-color:rgba(245,196,81,.2);}+ .tt-silver .tt-vchip{color:#dde2ec;background:rgba(207,214,228,.07);border-color:rgba(207,214,228,.2);}+ .tt-bronze .tt-vchip{color:#ecc6a6;background:rgba(224,168,120,.08);border-color:rgba(224,168,120,.2);}++ .tt-perks{list-style:none;margin:13px 0 0;padding:0;display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:7px 16px;}+ .tt-perk{display:flex;gap:8px;align-items:flex-start;font-size:13px;line-height:1.45;color:#c7c7d0;}+ .tt-perk-tick{flex-shrink:0;color:#6ee7a8;font-size:11px;line-height:1.5;}+ .tt-gold .tt-perk-tick{color:#f5c451;}+ .tt-silver .tt-perk-tick{color:#cfd6e4;}+ .tt-bronze .tt-perk-tick{color:#e0a878;}++ .tt-feats{list-style:none;margin:13px 0 0;padding:11px 0 0;border-top:1px solid #1d1d24;display:flex;flex-direction:column;gap:7px;}+ .tt-feat{display:flex;align-items:center;gap:8px;font-size:12.5px;color:#9a9aa4;}+ .tt-feat-tick{color:#6ee7a8;font-size:11px;font-weight:800;}+ .tt-feat-label{flex:1;min-width:0;}+ .tt-flag{flex-shrink:0;font-size:10px;font-weight:800;letter-spacing:.04em;text-transform:uppercase;border-radius:6px;padding:3px 7px;}+ .tt-flag--live{color:#6ee7a8;background:rgba(110,231,168,.1);border:1px solid rgba(110,231,168,.24);}+ .tt-flag--soon{color:#8a8a93;background:rgba(255,255,255,.04);border:1px solid #2a2a33;}++ .tt-page-foot{margin:26px 2px 0;font-size:12px;line-height:1.6;color:#75757f;}+ .tt-page-foot p{margin:0 0 6px;}+ .tt-mint a{color:#9a9aa4;font-family:ui-monospace,Menlo,monospace;font-size:11px;word-break:break-all;text-decoration:none;border-bottom:1px solid #2a2a33;}+ .tt-mint a:hover{color:#cdeede;}++ /* skeleton */+ .tt-sk{display:block;border-radius:8px;background:linear-gradient(90deg,#15151b,#20202a,#15151b);background-size:200% 100%;animation:tt-sh 1.3s infinite;}+ .tt-sk--mark{width:34px;height:34px;flex-shrink:0;border-radius:10px;}+ .tt-sk--name{height:15px;width:120px;margin-bottom:6px;}+ .tt-sk--thresh{height:11px;width:90px;}+ .tt-sk--line{height:12px;width:80%;margin-top:13px;}+ .tt-sk--short{width:50%;margin-top:8px;}+ .tt-sk--lede{height:16px;width:min(420px,80%);}+ .tt-skel .tt-tier-head{display:flex;align-items:center;gap:12px;}++ @keyframes tt-sh{0%{background-position:200% 0}100%{background-position:-200% 0}}++ @media (max-width:560px){+ .tt-h1{font-size:26px;}+ .tt-tier-head{flex-wrap:wrap;}+ .tt-status{order:3;}+ .tt-btn{flex:1;}+ }+ @media (prefers-reduced-motion: reduce){+ .tt-tier,.tt-btn{transition:none;}+ .tt-tier:hover{transform:none;}+ .tt-sk{animation:none;}+ }`;+ const el = document.createElement('style');+ el.id = 'tt-styles';+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/tests/billing.test.js b/tests/billing.test.jsindex cc6274a5e..2f54fa1d6 100644--- a/tests/billing.test.js+++ b/tests/billing.test.js@@ -57,3 +57,112 @@ describe('billing — endpoint file', () => {expect(src).toContain('401');});});++describe('billing — pricing + invoices routing', () => {+ const vercel = JSON.parse(readFileSync(p('vercel.json'), 'utf8'));+ const routes = vercel.routes || [];+ const route = (src) => routes.find((x) => x.src === src);++ it('routes /api/pricing to the aggregate pricing endpoint', () => {+ expect(route('/api/pricing')?.dest).toBe('/api/pricing');+ });++ it('routes /api/billing/invoices to the invoice statement endpoint', () => {+ expect(route('/api/billing/invoices')?.dest).toBe('/api/billing/invoices');+ });++ it('routes /billing to the statement page', () => {+ expect(route('/billing/?')?.dest).toBe('/billing.html');+ });+});++describe('billing — /api/pricing serves server truth', () => {+ const src = readFileSync(p('api/pricing.js'), 'utf8');++ it('aggregates the catalog, platform fee, and holder tier ladder', () => {+ expect(src).toContain('publicCatalog');+ expect(src).toContain('getFeeBps');+ expect(src).toContain('TIERS');+ });++ it('personalizes the holder price via the real charge-rail price function', () => {+ expect(src).toContain('priceForAction');+ expect(src).toContain('your_usd');+ expect(src).toContain('resolveUserTier');+ });++ it('never blocks the page on the balance read (degrades to public price)', () => {+ // The personalization is wrapped in try/catch so an RPC hiccup falls back.+ expect(src).toMatch(/try\s*{[\s\S]*resolveUserTier[\s\S]*catch/);+ });+});++describe('billing — invoices endpoint rolls usage into a statement', () => {+ const src = readFileSync(p('api/billing/invoices.js'), 'utf8');++ it('uses the metering rollup + reconciliation helpers', () => {+ expect(src).toContain('rollupInvoice');+ expect(src).toContain('reconciliationStatus');+ });++ it('requires authentication', () => {+ expect(src).toContain('getSessionUser');+ expect(src).toContain('401');+ });++ it('supports a CSV download of the statement', () => {+ expect(src).toContain('format');+ expect(src).toContain('text/csv');+ });+});++describe('billing — receipts serves a per-charge metered receipt', () => {+ const src = readFileSync(p('api/billing/receipts.js'), 'utf8');++ it('returns a metered receipt by event_id via getReceipt', () => {+ expect(src).toContain('event_id');+ expect(src).toContain('getReceipt');+ });++ it('keeps the existing signed purchase receipt path', () => {+ expect(src).toContain('purchase_id');+ expect(src).toContain('purchase_receipts');+ });+});++describe('billing — metering is wired into the one charge choke point', () => {+ const charge = readFileSync(p('api/_lib/pricing/charge-three.js'), 'utf8');++ it('meters after a settled $THREE charge', () => {+ expect(charge).toContain('recordUsageSafe');+ expect(charge).toContain('meterSettledCharge');+ });++ it('meters the allowance rail too, keyed by the settlement id', () => {+ // Both the settle and allowance success paths call the meter helper.+ const calls = charge.match(/meterSettledCharge\(/g) || [];+ expect(calls.length).toBeGreaterThanOrEqual(3); // 1 def + 2 call sites+ });+});++describe('billing — revenue dashboard surfaces reconciliation status', () => {+ const src = readFileSync(p('api/billing/revenue.js'), 'utf8');+ it('includes reconciliation in the dashboard payload', () => {+ expect(src).toContain('reconciliationStatus');+ expect(src).toContain('reconciliation');+ });+});++describe('billing — usage metering migration', () => {+ const sqlText = readFileSync(p('api/_lib/migrations/20260623170000_usage_metering.sql'), 'utf8');++ it('adds the metering columns to usage_events', () => {+ for (const col of ['meter_action', 'price_usdc_atomics', 'fee_usdc_atomics', 'settlement_ref', 'idempotency_key']) {+ expect(sqlText).toContain(col);+ }+ });++ it('enforces idempotency with a unique index on the idempotency key', () => {+ expect(sqlText).toContain('create unique index if not exists usage_events_idem');+ });+});diff --git a/tests/creator-pricing-rules-isolation.test.js b/tests/creator-pricing-rules-isolation.test.jsnew file mode 100644index 000000000..cabd477c2--- /dev/null+++ b/tests/creator-pricing-rules-isolation.test.js@@ -0,0 +1,104 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { invoke } from './_helpers/monetization.js';++// Owner-isolation guard for the dynamic pricing-rules endpoint that powers the+// Creator Studio price editor. A creator must only ever touch pricing rules for+// agents they own — never another creator's. The server gate is mandatory; this+// pins it so a refactor can't silently drop the 403.++const authState = { session: null };+const sqlState = { queue: [], calls: [] };+const rlState = { success: true };++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+}));++vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: Array.isArray(strings) ? strings.join('?') : String(strings), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ });+ return { sql };+});++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: rlState.success })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+}));++const { default: pricingRulesHandler } = await import('../api/agents/[id]/pricing-rules.js');++const AGENT_ID = '00000000-0000-4000-8000-000000000001';++beforeEach(() => {+ authState.session = null;+ sqlState.queue = [];+ sqlState.calls = [];+ rlState.success = true;+});++describe('pricing-rules owner isolation', () => {+ it('rejects an unauthenticated create with 401', async () => {+ authState.session = null;+ const { status, body } = await invoke(pricingRulesHandler, {+ method: 'POST',+ url: `/api/agents/${AGENT_ID}/pricing-rules`,+ query: { id: AGENT_ID },+ body: { skill_name: 'do_thing', rule_type: 'first_n_purchases', threshold: 5, price_amount: 500000, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' },+ });+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ });++ it('returns 403 when a non-owner tries to create a rule', async () => {+ authState.session = { id: 'attacker-user' };+ // Ownership lookup returns no row → not this user's agent.+ sqlState.queue = [[]];+ const { status, body } = await invoke(pricingRulesHandler, {+ method: 'POST',+ url: `/api/agents/${AGENT_ID}/pricing-rules`,+ query: { id: AGENT_ID },+ body: { skill_name: 'do_thing', rule_type: 'first_n_purchases', threshold: 5, price_amount: 500000, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' },+ });+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ // The INSERT must never run for a non-owner.+ expect(sqlState.calls.some((c) => /INSERT INTO skill_pricing_rules/i.test(c.query))).toBe(false);+ });++ it('lets the owner create a rule', async () => {+ authState.session = { id: 'owner-user' };+ sqlState.queue = [+ [{ id: AGENT_ID }], // ownership lookup → owns it+ [{ id: 'rule-1', skill_name: 'do_thing', rule_type: 'first_n_purchases', threshold: 5, price_amount: 500000, currency_mint: 'm', chain: 'solana', is_active: true }], // INSERT RETURNING+ ];+ const { status, body } = await invoke(pricingRulesHandler, {+ method: 'POST',+ url: `/api/agents/${AGENT_ID}/pricing-rules`,+ query: { id: AGENT_ID },+ body: { skill_name: 'do_thing', rule_type: 'first_n_purchases', threshold: 5, price_amount: 500000, currency_mint: 'm' },+ });+ expect(status).toBe(201);+ expect(body.data.rule.id).toBe('rule-1');+ expect(sqlState.calls.some((c) => /INSERT INTO skill_pricing_rules/i.test(c.query))).toBe(true);+ });++ it('returns 403 when a non-owner tries to delete a rule', async () => {+ authState.session = { id: 'attacker-user' };+ sqlState.queue = [[]]; // ownership lookup → empty+ const ruleId = '00000000-0000-4000-8000-0000000000aa';+ const { status, body } = await invoke(pricingRulesHandler, {+ method: 'DELETE',+ url: `/api/agents/${AGENT_ID}/pricing-rules/${ruleId}`,+ query: { id: AGENT_ID, rule_id: ruleId },+ });+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ expect(sqlState.calls.some((c) => /UPDATE skill_pricing_rules/i.test(c.query))).toBe(false);+ });+});diff --git a/tests/genome.test.js b/tests/genome.test.jsnew file mode 100644index 000000000..8c3296fc8--- /dev/null+++ b/tests/genome.test.js@@ -0,0 +1,250 @@+// Agent Genome — deterministic inheritance, bounded mutation, recessive carry,+// emergent fusion, and the anti-forgery verify path. Pure functions only: every+// invariant the breeding feature rests on is pinned here with no DB or network.++import { describe, it, expect } from 'vitest';+import {+ deriveGenome,+ verifyGenome,+ genomeFromAgent,+ hashGenome,+ normalizeGenome,+ pedigreeScore,+ composePersonaPrompt,+ voiceSettings,+ appearanceFromGenome,+ expressedSkills,+ makeSeed,+ MUTATION_MAX,+ GENOME_VERSION,+} from '../api/_lib/genome.js';++const founder = (id, over = {}) =>+ genomeFromAgent({+ id,+ persona_tone_tags: over.tone || ['precise', 'analytical'],+ voice_provider: over.voice_provider || 'elevenlabs',+ voice_id: over.voice_id || `voice-${id}`,+ voice_settings: over.voice_settings || { stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true },+ appearance: over.appearance || { morphs: { headScale: 0.8 }, colors: { hair: '#aa3311' }, accessories: ['hat'] },+ skills: over.skills || ['trading', 'memory'],+ avatar_id: over.avatar_id || `av-${id}`,+ meta: {},+ });++describe('genomeFromAgent (founder)', () => {+ it('is deterministic and stable for the same agent', () => {+ const a = founder('alpha');+ const b = founder('alpha');+ expect(hashGenome(a)).toBe(hashGenome(b));+ expect(a.generation).toBe(0);+ expect(a.version).toBe(GENOME_VERSION);+ });+ it('marks all founder skills expressed + dominant', () => {+ const a = founder('alpha', { skills: ['trading'] });+ expect(a.skills.every((s) => s.expressed && s.dominant)).toBe(true);+ });+ it('different agents get distinctive genomes', () => {+ expect(hashGenome(founder('alpha'))).not.toBe(hashGenome(founder('beta')));+ });+});++describe('deriveGenome determinism', () => {+ it('same (parents, seed) => byte-identical child', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const c1 = deriveGenome({ parentA: A, parentB: B, seed: 'seed-123' });+ const c2 = deriveGenome({ parentA: A, parentB: B, seed: 'seed-123' });+ expect(c1.genome_hash).toBe(c2.genome_hash);+ expect(JSON.stringify(c1)).toBe(JSON.stringify(c2));+ });+ it('is order-independent: A×B == B×A (canonical parents)', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const ab = deriveGenome({ parentA: A, parentB: B, seed: 's' });+ const ba = deriveGenome({ parentA: B, parentB: A, seed: 's' });+ expect(ab.genome_hash).toBe(ba.genome_hash);+ });+ it('different seeds produce different children', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const c1 = deriveGenome({ parentA: A, parentB: B, seed: 's1' });+ const c2 = deriveGenome({ parentA: A, parentB: B, seed: 's2' });+ expect(c1.genome_hash).not.toBe(c2.genome_hash);+ });+ it('throws without a seed', () => {+ expect(() => deriveGenome({ parentA: founder('a'), parentB: founder('b') })).toThrow();+ });+ it('increments generation past the deeper parent', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const child = deriveGenome({ parentA: A, parentB: B, seed: 's' });+ expect(child.generation).toBe(1);+ const grandchild = deriveGenome({ parentA: child, parentB: founder('gamma'), seed: 's2' });+ expect(grandchild.generation).toBe(2);+ });+});++describe('bounded mutation', () => {+ it('every brain/voice locus stays within MUTATION_MAX of the parental blend', () => {+ const A = founder('alpha');+ const B = founder('beta');+ // Sweep many seeds; the bound must hold for all of them.+ for (let i = 0; i < 200; i++) {+ const child = deriveGenome({ parentA: A, parentB: B, seed: `seed-${i}` });+ for (const locus of ['temperature', 'verbosity', 'curiosity', 'formality', 'humor', 'boldness']) {+ const lo = Math.min(A.brain[locus], B.brain[locus]) - MUTATION_MAX - 1e-9;+ const hi = Math.max(A.brain[locus], B.brain[locus]) + MUTATION_MAX + 1e-9;+ expect(child.brain[locus]).toBeGreaterThanOrEqual(Math.max(0, lo));+ expect(child.brain[locus]).toBeLessThanOrEqual(Math.min(1, hi));+ }+ }+ });+ it('records notable mutations in genome.mutations', () => {+ // Identical parents → blend == parent value, so any entry in mutations is a+ // genuine recorded drift.+ const A = founder('alpha');+ const child = deriveGenome({ parentA: A, parentB: founder('alpha'), seed: 'mut-seed' });+ for (const m of child.mutations) {+ expect(Math.abs(m.delta)).toBeGreaterThan(0);+ expect(Math.abs(m.delta)).toBeLessThanOrEqual(MUTATION_MAX + 1e-9);+ }+ });+});++describe('skill allele inheritance', () => {+ it('a skill both parents express is always expressed + dominant', () => {+ const A = founder('alpha', { skills: ['trading'] });+ const B = founder('beta', { skills: ['trading'] });+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'x' });+ const trading = child.skills.find((s) => s.skill === 'trading');+ expect(trading.expressed).toBe(true);+ expect(trading.dominant).toBe(true);+ });+ it('a skill only one parent has is sometimes recessive (carried, unexpressed)', () => {+ const A = founder('alpha', { skills: ['rareskill'] });+ const B = founder('beta', { skills: ['common'] });+ let sawRecessive = false;+ let sawExpressed = false;+ for (let i = 0; i < 60; i++) {+ const child = deriveGenome({ parentA: A, parentB: B, seed: `het-${i}` });+ const rare = child.skills.find((s) => s.skill === 'rareskill');+ expect(rare).toBeTruthy();+ if (rare.recessive) sawRecessive = true;+ if (rare.expressed) sawExpressed = true;+ }+ expect(sawRecessive).toBe(true);+ expect(sawExpressed).toBe(true);+ });+ it('a recessive allele carried by both parents surfaces in the child', () => {+ // Build two heterozygous carriers of the same recessive skill.+ const A = normalizeGenome({+ ...founder('alpha'),+ skills: [{ skill: 'latent', expressed: false, recessive: true, source: 'A', depth: 1 }],+ });+ const B = normalizeGenome({+ ...founder('beta'),+ skills: [{ skill: 'latent', expressed: false, recessive: true, source: 'B', depth: 1 }],+ });+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'pair' });+ const latent = child.skills.find((s) => s.skill === 'latent');+ expect(latent.expressed).toBe(true);+ });+});++describe('emergent fusion', () => {+ it('can produce a skill neither parent expressed (auditable rule)', () => {+ const A = founder('alpha', { skills: ['trading'] });+ const B = founder('beta', { skills: ['sentiment'] });+ let emergentSeen = false;+ for (let i = 0; i < 80; i++) {+ const child = deriveGenome({ parentA: A, parentB: B, seed: `fuse-${i}` });+ const alpha = child.skills.find((s) => s.skill === 'alpha-signal');+ if (alpha) {+ expect(alpha.source).toBe('emergent');+ expect(alpha.emergent_from).toEqual(['trading', 'sentiment']);+ emergentSeen = true;+ }+ }+ expect(emergentSeen).toBe(true);+ });+});++describe('verifyGenome (anti-forgery)', () => {+ it('accepts a genuinely derived child', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'real' });+ const res = verifyGenome(child, { parentA: A, parentB: B, seed: 'real' });+ expect(res.valid).toBe(true);+ });+ it('rejects a tampered child (forged trait)', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'real' });+ const forged = { ...child, brain: { ...child.brain, boldness: 0.999 } };+ const res = verifyGenome(forged, { parentA: A, parentB: B, seed: 'real' });+ expect(res.valid).toBe(false);+ expect(res.reason).toBe('hash_mismatch');+ });+ it('rejects a child claimed under the wrong seed', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'real' });+ expect(verifyGenome(child, { parentA: A, parentB: B, seed: 'wrong' }).valid).toBe(false);+ });+ it('rejects a child claimed under wrong parentage', () => {+ const A = founder('alpha');+ const B = founder('beta');+ const child = deriveGenome({ parentA: A, parentB: B, seed: 'real' });+ expect(verifyGenome(child, { parentA: A, parentB: founder('gamma'), seed: 'real' }).valid).toBe(false);+ });+});++describe('artifact projections', () => {+ it('voiceSettings are valid ElevenLabs ranges', () => {+ const child = deriveGenome({ parentA: founder('a'), parentB: founder('b'), seed: 's' });+ const vs = voiceSettings(child);+ for (const k of ['stability', 'similarity_boost', 'style']) {+ expect(vs[k]).toBeGreaterThanOrEqual(0);+ expect(vs[k]).toBeLessThanOrEqual(1);+ }+ expect(typeof vs.use_speaker_boost).toBe('boolean');+ });+ it('appearanceFromGenome is bakeable (morphs/colors present)', () => {+ const child = deriveGenome({ parentA: founder('a'), parentB: founder('b'), seed: 's' });+ const app = appearanceFromGenome(child);+ expect(app.morphs || app.colors || app.accessories).toBeTruthy();+ });+ it('persona prompt is in-character and references inherited skills', () => {+ const child = deriveGenome({ parentA: founder('a', { skills: ['trading'] }), parentB: founder('b', { skills: ['trading'] }), seed: 's' });+ const prompt = composePersonaPrompt(child, 'Nova');+ expect(prompt).toContain('Nova');+ expect(prompt.toLowerCase()).toContain('trading');+ });+ it('expressedSkills excludes recessive alleles', () => {+ const g = normalizeGenome({+ skills: [+ { skill: 'shown', expressed: true },+ { skill: 'hidden', expressed: false, recessive: true },+ ],+ });+ expect(expressedSkills(g)).toEqual(['shown']);+ });+});++describe('pedigreeScore', () => {+ it('rewards depth and emergent traits with rarer tiers', () => {+ const flat = pedigreeScore(founder('a'));+ expect(flat.tier).toBe('common');+ const deep = pedigreeScore({ ...founder('a'), generation: 4 });+ expect(['rare', 'legendary']).toContain(deep.tier);+ });+});++describe('makeSeed', () => {+ it('produces a 32-char hex string', () => {+ const seed = makeSeed(Buffer.alloc(16, 7));+ expect(seed).toMatch(/^[0-9a-f]{32}$/);+ });+});diff --git a/tests/marketplace-splits.test.js b/tests/marketplace-splits.test.jsnew file mode 100644index 000000000..b6aa9966a--- /dev/null+++ b/tests/marketplace-splits.test.js@@ -0,0 +1,217 @@+/**+ * Marketplace economics — money math for multi-collaborator splits.+ *+ * These are the correctness guarantees an acquirer underwrites: a buyer is+ * never over-charged (fee + creator-net = price), N-way split shares sum to+ * 100%, and every recipient's atomic allocation is exact (Σ parts = the whole,+ * no dust lost or invented) for any amount and any share mix — including the+ * pathological cases (primes, 1-atomic, huge values, lopsided shares).+ *+ * Pure functions only — no DB, no chain — so they run fast and deterministically.+ */++import { describe, it, expect } from 'vitest';+import {+ validateShares,+ allocateAtomics,+ describeSplit,+ isValidAddressForChain,+ FULL_SHARE_BPS,+} from '../api/_lib/splits.js';+import { marketplaceFeeAtomics } from '../api/_lib/marketplace-platform-fee.js';++// Synthetic addresses — never a real wallet (CLAUDE.md).+const SOL_A = 'THREEsynthetic1111111111111111111111111111A';+const EVM_A = '0x1111111111111111111111111111111111111111';+const EVM_B = '0x2222222222222222222222222222222222222222';+const EVM_C = '0x3333333333333333333333333333333333333333';++const sum = (parts) => parts.reduce((s, p) => s + p.amount, 0n);++describe('validateShares', () => {+ it('accepts a 70/30 split that sums to 100%', () => {+ const out = validateShares(+ [+ { address: EVM_A, share_bps: 7000 },+ { address: EVM_B, share_bps: 3000 },+ ],+ 'base',+ );+ expect(out).toHaveLength(2);+ expect(out.reduce((s, r) => s + r.share_bps, 0)).toBe(FULL_SHARE_BPS);+ });++ it('accepts percent input and normalizes to bps', () => {+ const out = validateShares(+ [+ { address: EVM_A, percent: 33.33 },+ { address: EVM_B, percent: 66.67 },+ ],+ 'base',+ );+ expect(out.map((r) => r.share_bps)).toEqual([3333, 6667]);+ });++ it('rejects shares that do not sum to 100%', () => {+ expect(() =>+ validateShares(+ [+ { address: EVM_A, share_bps: 7000 },+ { address: EVM_B, share_bps: 2000 },+ ],+ 'base',+ ),+ ).toThrow(/sum to 100%/);+ });++ it('rejects duplicate recipients', () => {+ expect(() =>+ validateShares(+ [+ { address: EVM_A, share_bps: 5000 },+ { address: EVM_A, share_bps: 5000 },+ ],+ 'base',+ ),+ ).toThrow(/more than once/);+ });++ it('rejects an invalid address for the chain', () => {+ expect(() => validateShares([{ address: 'not-an-address', share_bps: 10000 }], 'base')).toThrow(+ /invalid base address/,+ );+ });++ it('rejects a zero or negative share', () => {+ expect(() =>+ validateShares(+ [+ { address: EVM_A, share_bps: 0 },+ { address: EVM_B, share_bps: 10000 },+ ],+ 'base',+ ),+ ).toThrow(/invalid share/);+ });++ it('validates chain-appropriate addresses', () => {+ expect(isValidAddressForChain(SOL_A, 'solana')).toBe(true);+ expect(isValidAddressForChain(EVM_A, 'base')).toBe(true);+ expect(isValidAddressForChain(EVM_A, 'solana')).toBe(false);+ });+});++describe('allocateAtomics — exactness', () => {+ const recipients3 = [+ { address: EVM_A, share_bps: 3333 },+ { address: EVM_B, share_bps: 3333 },+ { address: EVM_C, share_bps: 3334 },+ ];++ it('Σ parts equals the whole for a non-divisible amount', () => {+ const parts = allocateAtomics(100n, recipients3);+ expect(sum(parts)).toBe(100n);+ });++ it('never loses or invents an atomic across many amounts', () => {+ for (let total = 0n; total <= 1000n; total++) {+ const parts = allocateAtomics(total, recipients3);+ expect(sum(parts)).toBe(total);+ }+ });++ it('handles a 1-atomic split (leftover goes to the largest remainder)', () => {+ const parts = allocateAtomics(1n, recipients3);+ expect(sum(parts)).toBe(1n);+ // Exactly one recipient gets the single atomic.+ expect(parts.filter((p) => p.amount === 1n)).toHaveLength(1);+ });++ it('is exact for a prime amount and lopsided shares', () => {+ const recipients = [+ { address: EVM_A, share_bps: 9999 },+ { address: EVM_B, share_bps: 1 },+ ];+ const parts = allocateAtomics(7919n, recipients);+ expect(sum(parts)).toBe(7919n);+ expect(parts[0].amount).toBeGreaterThan(parts[1].amount);+ });++ it('is exact for very large amounts (no float drift)', () => {+ const total = 123456789012345n; // ~123M USDC at 6 decimals+ const parts = allocateAtomics(total, recipients3);+ expect(sum(parts)).toBe(total);+ });++ it('a single recipient receives the entire amount', () => {+ const parts = allocateAtomics(500n, [{ address: EVM_A, share_bps: 10000 }]);+ expect(parts).toHaveLength(1);+ expect(parts[0].amount).toBe(500n);+ });++ it('apportions an even split with no remainder cleanly', () => {+ const parts = allocateAtomics(1000n, [+ { address: EVM_A, share_bps: 5000 },+ { address: EVM_B, share_bps: 5000 },+ ]);+ expect(parts.map((p) => p.amount)).toEqual([500n, 500n]);+ });+});++describe('fee + split coherence — the buyer is never over-charged', () => {+ it('platform fee + creator net = price, and Σ split = creator net', () => {+ const price = 10_000_000n; // 10 USDC+ const feeBps = 500; // 5%+ const fee = marketplaceFeeAtomics(price, feeBps);+ const creatorNet = price - fee;++ // Fee leg + creator leg reconstruct the price exactly — no hidden cut.+ expect(fee + creatorNet).toBe(price);++ const recipients = validateShares(+ [+ { address: EVM_A, share_bps: 7000 },+ { address: EVM_B, share_bps: 3000 },+ ],+ 'base',+ );+ const parts = allocateAtomics(creatorNet, recipients);++ // Every collaborator's share sums back to exactly the creator's net —+ // the platform keeps only the fee, nothing leaks into or out of the split.+ expect(sum(parts)).toBe(creatorNet);+ expect(fee + sum(parts)).toBe(price);+ });++ it('zero-fee environment routes the full price into the split', () => {+ const price = 3_000_001n; // odd amount+ const fee = marketplaceFeeAtomics(price, 0);+ expect(fee).toBe(0n);+ const recipients = validateShares(+ [+ { address: EVM_A, share_bps: 5000 },+ { address: EVM_B, share_bps: 2500 },+ { address: EVM_C, share_bps: 2500 },+ ],+ 'base',+ );+ const parts = allocateAtomics(price - fee, recipients);+ expect(sum(parts)).toBe(price);+ });+});++describe('describeSplit', () => {+ it('renders a human label for the buyer', () => {+ const recipients = validateShares(+ [+ { address: EVM_A, share_bps: 7000, label: 'Lead' },+ { address: EVM_B, share_bps: 3000, label: 'Art' },+ ],+ 'base',+ );+ const d = describeSplit(recipients);+ expect(d.label).toBe('70 / 30');+ expect(d.recipients[0].percent).toBe(70);+ expect(d.recipients[1].label).toBe('Art');+ });+});diff --git a/tests/metering.test.js b/tests/metering.test.jsnew file mode 100644index 000000000..bf42f088d--- /dev/null+++ b/tests/metering.test.js@@ -0,0 +1,198 @@+// Money-math tests for the usage metering ledger (api/_lib/metering.js).+//+// The DB is mocked: a tagged-template `sql` that returns whatever the test+// queues. The catalog + fee modules are REAL (pure), so a silent price or+// fee-bps change fails these. The AWS SDK is mocked at the client boundary so we+// assert the MeterUsage call SHAPE without ever talking to AWS.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const queue = [];+vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async () => (queue.length ? queue.shift() : []));+ return { sql };+});++import { recordUsage, rollupInvoice, getReceipt, atomicsToUsd } from '../api/_lib/metering.js';+import { sql } from '../api/_lib/db.js';++beforeEach(() => {+ queue.length = 0;+ sql.mockClear();+});++describe('recordUsage — idempotency (no double-spend)', () => {+ it('meters once for a settlement, and a retried settlement meters zero times', async () => {+ // First insert wins (RETURNING id); the retry hits ON CONFLICT DO NOTHING → [].+ queue.push([{ id: 42 }]);+ const first = await recordUsage({+ userId: 'u1',+ action: 'forge.high',+ priceUsdcAtomics: 500_000,+ settlementRef: 'pay-abc',+ });+ expect(first).toEqual({ id: 42, metered: true, duplicate: false });++ queue.push([]); // conflict on the same idempotency key+ const second = await recordUsage({+ userId: 'u1',+ action: 'forge.high',+ priceUsdcAtomics: 500_000,+ settlementRef: 'pay-abc',+ });+ expect(second).toEqual({ id: null, metered: false, duplicate: true });+ });++ it('keys idempotency on the settlement ref by default', async () => {+ queue.push([{ id: 1 }]);+ await recordUsage({ userId: 'u1', action: 'forge.high', priceUsdcAtomics: 500_000, settlementRef: 'pay-xyz', settlementKind: 'three' });+ // The bound params include the derived `three:pay-xyz` key.+ const params = sql.mock.calls[0].slice(1).map(String);+ expect(params).toContain('three:pay-xyz');+ });++ it('throws without a settlement ref — never meters an unlinked charge', async () => {+ await expect(+ recordUsage({ userId: 'u1', action: 'forge.high', priceUsdcAtomics: 1 }),+ ).rejects.toThrow(/settlementRef/);+ });+});++describe('recordUsage — platform-fee derivation by policy', () => {+ it('consumption action: platform keeps the whole price (fee == price)', async () => {+ queue.push([{ id: 1 }]);+ await recordUsage({ userId: 'u1', action: 'forge.high', priceUsdcAtomics: 500_000, settlementRef: 'r1' });+ const params = sql.mock.calls[0].slice(1).map(String);+ // price and fee are both 500000 atomics.+ expect(params.filter((p) => p === '500000').length).toBeGreaterThanOrEqual(2);+ });++ it('marketplace action: platform takes the fee-bps slice, seller gets the rest', async () => {+ queue.push([{ id: 1 }]);+ // skill.call is a POLICY.MARKETPLACE action; price it per-call at $1.00.+ await recordUsage({ userId: 'u1', action: 'skill.call', priceUsdcAtomics: 1_000_000, settlementRef: 'r2', settlementKind: 'three' });+ const params = sql.mock.calls[0].slice(1).map(String);+ // Default platform fee is 250 bps → fee = 25000 atomics ($0.025) of $1.00.+ expect(params).toContain('1000000'); // gross+ expect(params).toContain('25000'); // platform fee+ });+});++describe('rollupInvoice — statement math', () => {+ it('line items sum exactly to the statement total', async () => {+ queue.push([+ { action: 'forge.high', count: 3, units: 3, gross_atomics: '1500000', fee_atomics: '1500000', discount_bps: 0 },+ { action: 'voice.clone', count: 1, units: 1, gross_atomics: '500000', fee_atomics: '500000', discount_bps: 1000 },+ ]);+ const inv = await rollupInvoice({ userId: 'u1', from: new Date('2026-06-01'), to: new Date('2026-07-01') });++ const sumGross = inv.line_items.reduce((s, l) => s + BigInt(l.gross_atomics), 0n);+ const sumFee = inv.line_items.reduce((s, l) => s + BigInt(l.fee_atomics), 0n);+ expect(sumGross.toString()).toBe(inv.totals.gross_atomics);+ expect(sumFee.toString()).toBe(inv.totals.fee_atomics);+ expect(inv.totals.gross_usd).toBe('2.00');+ expect(inv.totals.charge_count).toBe(4);+ // net = gross - fee, per line.+ expect(inv.line_items[0].net_atomics).toBe('0');+ });++ it('empty period rolls up to a zero statement', async () => {+ queue.push([]);+ const inv = await rollupInvoice({ userId: 'u1', from: new Date('2026-06-01'), to: new Date('2026-07-01') });+ expect(inv.line_items).toEqual([]);+ expect(inv.totals.gross_atomics).toBe('0');+ expect(inv.totals.gross_usd).toBe('0.00');+ });+});++describe('getReceipt — per-charge receipt traces to settlement', () => {+ it('joins the metered row to its on-chain tx and links an explorer URL', async () => {+ queue.push([+ {+ id: 7,+ meter_action: 'forge.high',+ units: 1,+ price_usdc_atomics: '450000',+ fee_usdc_atomics: '450000',+ discount_bps: 1000,+ settlement_ref: 'pay-1',+ settlement_kind: 'three',+ created_at: new Date('2026-06-10T00:00:00Z'),+ tx_signature: 'SIG123',+ network: 'mainnet',+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ settled_atomics: '900',+ token_price_usd: 0.5,+ },+ ]);+ const r = await getReceipt({ userId: 'u1', eventId: 7 });+ expect(r.action).toBe('forge.high');+ expect(r.gross_usd).toBe('0.45');+ expect(r.net_atomics).toBe('0');+ expect(r.discount_percent).toBe('10.0');+ expect(r.settlement.tx_signature).toBe('SIG123');+ expect(r.settlement.explorer_url).toBe('https://solscan.io/tx/SIG123');+ });++ it('returns null for a charge the user does not own', async () => {+ queue.push([]); // ownership-scoped query returns nothing+ const r = await getReceipt({ userId: 'u1', eventId: 999 });+ expect(r).toBeNull();+ });+});++describe('atomicsToUsd', () => {+ it('converts 6-decimal atomics to a USD string', () => {+ expect(atomicsToUsd(150000)).toBe('0.15');+ expect(atomicsToUsd('1000000')).toBe('1.00');+ expect(atomicsToUsd(0)).toBe('0.00');+ });+});++describe('AWS Marketplace — MeterUsage call shape (SDK boundary mocked)', () => {+ it('issues a MeterUsage command with the product code, dimension, and idempotency allocation', async () => {+ vi.resetModules();+ const sent = [];+ vi.doMock('@aws-sdk/client-marketplace-metering', () => ({+ MarketplaceMeteringClient: class {+ async send(cmd) {+ sent.push(cmd);+ return { MeteringRecordId: 'rec-1' };+ }+ },+ ResolveCustomerCommand: class {},+ MeterUsageCommand: class {+ constructor(input) {+ this.input = input;+ }+ },+ }));+ vi.doMock('@aws-sdk/client-marketplace-entitlement-service', () => ({+ MarketplaceEntitlementServiceClient: class {},+ GetEntitlementsCommand: class {},+ }));+ vi.doMock('../api/_lib/env.js', () => ({+ env: { AWS_MP_PRODUCT_CODE: 'prod123', AWS_MP_REGION: 'us-east-1', AWS_MP_ACCESS_KEY_ID: 'k', AWS_MP_SECRET_ACCESS_KEY: 's' },+ }));++ const { meterUsage } = await import('../api/_lib/aws-marketplace.js');+ const recordId = await meterUsage({+ customerIdentifier: 'cust-1',+ dimension: 'api_call',+ quantity: 1,+ usageAllocationId: 'alloc-1',+ });+ expect(recordId).toBe('rec-1');+ expect(sent).toHaveLength(1);+ const input = sent[0].input;+ expect(input.ProductCode).toBe('prod123');+ expect(input.UsageDimension).toBe('api_call');+ expect(input.UsageQuantity).toBe(1);+ expect(input.CustomerIdentifier).toBe('cust-1');+ // Idempotency allocation carries the dedupe key AWS bills against.+ expect(input.UsageAllocations[0].Tags[0].Value).toBe('alloc-1');+ vi.dontMock('@aws-sdk/client-marketplace-metering');+ vi.dontMock('@aws-sdk/client-marketplace-entitlement-service');+ vi.dontMock('../api/_lib/env.js');+ });+});diff --git a/tests/three-tier-page.test.js b/tests/three-tier-page.test.jsnew file mode 100644index 000000000..3dd5fb6f8--- /dev/null+++ b/tests/three-tier-page.test.js@@ -0,0 +1,94 @@+// Wiring tests for the canonical $THREE tier surface (/three).+//+// The page itself (src/three-tier-page.js) is a browser rendering surface whose+// data contract is already covered end-to-end by the API + library suites+// (three-tier.test.js, three-access.test.js, api/three-access.test.js,+// three-tier-public.test.js). What is NOT covered elsewhere — and what would+// silently break the whole "every locked state routes here" guarantee — is the+// ROUTING: that /three serves the tier page (not the old redirect to the coin+// page), that it's registered for the build + sitemap, and that the page shell+// loads the controller. These are filesystem/config assertions, so they run+// without a browser.++import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const root = resolve(__dirname, '..');+const read = (p) => readFileSync(resolve(root, p), 'utf8');++describe('/three tier surface — routing & registration', () => {+ let vercel, pages;+ beforeAll(() => {+ vercel = JSON.parse(read('vercel.json'));+ pages = JSON.parse(read('data/pages.json'));+ });++ it('serves the tier page at /three (no longer a redirect to the coin page)', () => {+ const route = vercel.routes.find((r) => r.src === '/three/?');+ expect(route, 'a /three route must exist').toBeTruthy();+ // The whole point: /three is now the upgrade surface, served as a page.+ expect(route.dest).toBe('/three.html');+ expect(route.status).toBeUndefined();+ expect(route.headers?.Location).toBeUndefined();+ });++ it('keeps the coin price/chart page distinct at /three-token', () => {+ const route = vercel.routes.find((r) => r.src === '/three-token/?');+ expect(route?.dest).toBe('/three-token.html');+ });++ it('registers /three in the page index with non-empty, $THREE-only copy', () => {+ // pages.json nests page lists; flatten any array of objects with a `path`.+ const all = [];+ const walk = (node) => {+ if (Array.isArray(node)) return node.forEach(walk);+ if (node && typeof node === 'object') {+ if (typeof node.path === 'string') all.push(node);+ Object.values(node).forEach(walk);+ }+ };+ walk(pages);+ const entry = all.find((p) => p.path === '/three');+ expect(entry, '/three must be registered in data/pages.json').toBeTruthy();+ expect(entry.title.length).toBeGreaterThan(0);+ expect(entry.description.length).toBeGreaterThan(0);+ // $THREE is the only coin — the copy must not name another token.+ const blob = `${entry.title} ${entry.description}`.toLowerCase();+ expect(blob).toContain('$three');+ });++ it('the page shell loads the controller, the shared nav, and the footer', () => {+ const html = read('pages/three.html');+ expect(html).toContain('/src/three-tier-page.js');+ expect(html).toContain('/nav.js');+ expect(html).toContain('/footer.js');+ expect(html).toContain('id="tier-root"');+ // canonical/OG point at the tier surface, not the coin page.+ expect(html).toContain('https://three.ws/three');+ });++ it('is wired into the Vite build input and dev-server route map', () => {+ const cfg = read('vite.config.js');+ expect(cfg).toContain("three: resolve(__dirname, 'pages/three.html')");+ expect(cfg).toContain("'/three': resolve(root, 'pages/three.html')");+ });+});++describe('locked-state CTAs route to the /three upgrade surface', () => {+ it('the nav tier chip + in-place lock default both target /three', () => {+ const access = read('src/three-access.js');+ const lock = read('src/three-lock.js');+ // The canonical upgrade destination constant in each client module.+ expect(access).toMatch(/const ECONOMY_URL = '\/three';/);+ expect(lock).toMatch(/const ECONOMY_URL = '\/three';/);+ // The coin page stays reachable as the secondary "price & chart" link.+ expect(access).toMatch(/const PRICE_URL = '\/three-token';/);+ });++ it('the Forge High-quality lock routes to /three', () => {+ const forge = read('src/forge.js');+ expect(forge).toContain("getThreeUrl: '/three'");+ expect(forge).not.toContain("getThreeUrl: '/three-token'");+ });+});diff --git a/tests/world-lines-crypto.test.js b/tests/world-lines-crypto.test.jsnew file mode 100644index 000000000..767994ea0--- /dev/null+++ b/tests/world-lines-crypto.test.js@@ -0,0 +1,168 @@+// Unit tests for the World Lines proof-of-presence crypto core (api/_lib/world-lines.js).+// Pure functions only — no DB, no network — so every anti-cheat guarantee (signature+// genuineness, nonce binding, replay/forgery rejection, challenge validation, and the+// coarse-cell privacy unit) is asserted in isolation.++import { describe, it, expect, beforeAll } from 'vitest';+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58 from 'bs58';+import {+ coarseCell, isCoarseCell, COARSE_CELL_PRECISION,+ normalizeChallengeSpec, normalizeRewardKind, normalizeDifficulty,+ canonicalProofMessage, completerHash, signPresenceProof, verifyPresenceProof,+ mintPresenceNonce, verifyPresenceNonce, NONCE_TTL_SEC,+} from '../api/_lib/world-lines.js';++// A deterministic agent keypair (no @solana/web3.js needed): 64-byte secret = seed||pub.+function fakeAgentKey(fill = 9) {+ const seed = new Uint8Array(32).fill(fill);+ const pub = ed25519.getPublicKey(seed);+ const secretKey = new Uint8Array(64);+ secretKey.set(seed, 0);+ secretKey.set(pub, 32);+ return { secretKey, pubkey: bs58.encode(pub) };+}++const WL_ID = '11111111-1111-1111-1111-111111111111';+let CELL;+beforeAll(() => {+ CELL = coarseCell(40.7484, -73.9857); // Empire State Building+});++describe('coarse cell — the ~1.1 km privacy unit', () => {+ it('is a precision-6 geohash', () => {+ expect(COARSE_CELL_PRECISION).toBe(6);+ expect(CELL).toHaveLength(6);+ expect(isCoarseCell(CELL)).toBe(true);+ });+ it('a precision-7 density cell refines to the same precision-6 parent (hierarchical)', async () => {+ const { encodeGeohash } = await import('../api/_lib/geohash.js');+ const cell7 = encodeGeohash(40.7484, -73.9857, 7);+ expect(cell7.slice(0, 6)).toBe(CELL);+ });+ it('rejects malformed cells', () => {+ expect(isCoarseCell('zzz')).toBe(false);+ expect(isCoarseCell('abcdei')).toBe(false); // a + i are not in the geohash alphabet+ expect(isCoarseCell('dr5ru6x')).toBe(false); // precision 7+ expect(isCoarseCell('')).toBe(false);+ });+});++describe('signPresenceProof / verifyPresenceProof', () => {+ it('the agent signs and anyone re-verifies the exact canonical message', async () => {+ const agent = fakeAgentKey();+ const who = await completerHash('device-abc');+ const minted = await mintPresenceNonce(WL_ID, CELL);+ const message = canonicalProofMessage({ worldLineId: WL_ID, coarseCell: CELL, nonceId: minted.nonceId, completerHash: who });+ const proof = signPresenceProof({ secretKey: agent.secretKey, message });++ expect(proof.signerPubkey).toBe(agent.pubkey);+ expect(verifyPresenceProof({ signerPubkey: proof.signerPubkey, message, signature: proof.signature })).toBe(true);+ });++ it('rejects a tampered message, signature, or signer', async () => {+ const agent = fakeAgentKey();+ const who = await completerHash('device-abc');+ const message = canonicalProofMessage({ worldLineId: WL_ID, coarseCell: CELL, nonceId: 'abc', completerHash: who });+ const proof = signPresenceProof({ secretKey: agent.secretKey, message });++ expect(verifyPresenceProof({ signerPubkey: proof.signerPubkey, message: message + 'x', signature: proof.signature })).toBe(false);+ const otherSig = signPresenceProof({ secretKey: fakeAgentKey(1).secretKey, message }).signature;+ expect(verifyPresenceProof({ signerPubkey: proof.signerPubkey, message, signature: otherSig })).toBe(false);+ expect(verifyPresenceProof({ signerPubkey: fakeAgentKey(2).pubkey, message, signature: proof.signature })).toBe(false);+ });++ it('a different completer cannot reuse another visitor’s signature', async () => {+ const agent = fakeAgentKey();+ const mine = await completerHash('device-mine');+ const theirs = await completerHash('device-theirs');+ const msgMine = canonicalProofMessage({ worldLineId: WL_ID, coarseCell: CELL, nonceId: 'n', completerHash: mine });+ const sig = signPresenceProof({ secretKey: agent.secretKey, message: msgMine }).signature;+ const msgTheirs = canonicalProofMessage({ worldLineId: WL_ID, coarseCell: CELL, nonceId: 'n', completerHash: theirs });+ expect(verifyPresenceProof({ signerPubkey: agent.pubkey, message: msgTheirs, signature: sig })).toBe(false);+ });++ it('never throws on malformed input', () => {+ expect(verifyPresenceProof({ signerPubkey: 'not-base58!!', message: 'x', signature: 'y' })).toBe(false);+ expect(verifyPresenceProof({ signerPubkey: '', message: '', signature: '' })).toBe(false);+ });+});++describe('completerHash', () => {+ it('is stable for the same id and distinct across ids — and never echoes the raw id', async () => {+ const a = await completerHash('device-xyz');+ const b = await completerHash('device-xyz');+ const c = await completerHash('device-other');+ expect(a).toBe(b);+ expect(a).not.toBe(c);+ expect(a).not.toContain('device-xyz');+ expect(a).toHaveLength(32);+ });+});++describe('mintPresenceNonce / verifyPresenceNonce', () => {+ it('a freshly minted nonce verifies and yields its id', async () => {+ const minted = await mintPresenceNonce(WL_ID, CELL);+ const v = await verifyPresenceNonce(minted.nonce, WL_ID, CELL);+ expect(v.ok).toBe(true);+ expect(v.nonceId).toBe(minted.nonceId);+ expect(minted.expires_in).toBe(NONCE_TTL_SEC);+ });++ it('rejects a nonce bound to a different world line or cell', async () => {+ const minted = await mintPresenceNonce(WL_ID, CELL);+ expect((await verifyPresenceNonce(minted.nonce, '22222222-2222-2222-2222-222222222222', CELL)).reason).toBe('mismatch');+ const otherCell = coarseCell(48.8584, 2.2945); // Eiffel Tower+ expect((await verifyPresenceNonce(minted.nonce, WL_ID, otherCell)).reason).toBe('mismatch');+ });++ it('rejects a forged / tampered nonce', async () => {+ const minted = await mintPresenceNonce(WL_ID, CELL);+ const tampered = minted.nonce.slice(0, -3) + 'AAA';+ expect((await verifyPresenceNonce(tampered, WL_ID, CELL)).reason).toBe('forged');+ expect((await verifyPresenceNonce('garbage', WL_ID, CELL)).reason).toBe('malformed');+ expect((await verifyPresenceNonce('', WL_ID, CELL)).reason).toBe('missing');+ });++ it('rejects an expired nonce (past the TTL)', async () => {+ const longAgo = Math.floor(Date.now() / 1000) - (NONCE_TTL_SEC + 60);+ const minted = await mintPresenceNonce(WL_ID, CELL, longAgo);+ const v = await verifyPresenceNonce(minted.nonce, WL_ID, CELL); // verified at "now"+ expect(v.ok).toBe(false);+ expect(v.reason).toBe('expired');+ });++ it('each mint is unique (random component) so the nonce id is a per-attempt key', async () => {+ const a = await mintPresenceNonce(WL_ID, CELL);+ const b = await mintPresenceNonce(WL_ID, CELL);+ expect(a.nonceId).not.toBe(b.nonceId);+ });+});++describe('challenge spec validation', () => {+ it('defaults to a tap challenge', () => {+ const { ok, spec } = normalizeChallengeSpec(undefined);+ expect(ok).toBe(true);+ expect(spec.kind).toBe('tap');+ });+ it('a phrase challenge requires + normalizes a passphrase', () => {+ expect(normalizeChallengeSpec({ kind: 'phrase' }).ok).toBe(false);+ const { ok, spec } = normalizeChallengeSpec({ kind: 'phrase', phrase: ' Open SESAME ' });+ expect(ok).toBe(true);+ expect(spec.phrase).toBe('open sesame');+ });+ it('a quiz needs ≥ 2 choices and a valid answer index', () => {+ expect(normalizeChallengeSpec({ kind: 'quiz', question: 'Q', choices: ['a'] }).ok).toBe(false);+ expect(normalizeChallengeSpec({ kind: 'quiz', question: 'Q', choices: ['a', 'b'], answer: 5 }).ok).toBe(false);+ const { ok, spec } = normalizeChallengeSpec({ kind: 'quiz', question: 'Q', choices: ['a', 'b', 'c'], answer: 2 });+ expect(ok).toBe(true);+ expect(spec.answer).toBe(2);+ expect(spec.choices).toEqual(['a', 'b', 'c']);+ });+ it('reward + difficulty normalize to safe defaults', () => {+ expect(normalizeRewardKind('dogecoin_pool')).toBe('collectible');+ expect(normalizeRewardKind('three_pool')).toBe('three_pool');+ expect(normalizeDifficulty('nightmare')).toBe('easy');+ expect(normalizeDifficulty('hard')).toBe('hard');+ });+});diff --git a/vercel.json b/vercel.jsonindex e0874d5e4..36bfbe3c5 100644--- a/vercel.json+++ b/vercel.json@@ -500,10 +500,34 @@"src": "/api/agents/([^/]+)/tiers","dest": "/api/agents/[id]/tiers?id=$1"},+ {+ "src": "/api/ledger/verify/([^/]+)",+ "dest": "/api/ledger/verify/[agentId]?agentId=$1"+ },+ {+ "src": "/api/ledger/([^/]+)",+ "dest": "/api/ledger/[agentId]?agentId=$1"+ },+ {+ "src": "/ledger/([^/]+)/?",+ "dest": "/reasoning-ledger.html"+ },+ {+ "src": "/ledger/?",+ "dest": "/reasoning-ledger.html"+ },{"src": "/api/billing/receipts","dest": "/api/billing/receipts"},+ {+ "src": "/api/billing/invoices",+ "dest": "/api/billing/invoices"+ },+ {+ "src": "/api/pricing",+ "dest": "/api/pricing"+ },{"src": "/api/newsletter/subscribe","dest": "/api/newsletter-subscribe"@@ -642,10 +666,7 @@},{"src": "/three/?",- "status": 308,- "headers": {- "Location": "/three-token"- }+ "dest": "/three.html"},{"src": "/go/?",@@ -1191,6 +1212,10 @@"src": "/pricing/?","dest": "/pricing.html"},+ {+ "src": "/billing/?",+ "dest": "/billing.html"+ },{"src": "/credits/?","dest": "/credits.html"@@ -2224,6 +2249,18 @@"src": "/api/irl/drops","dest": "/api/irl/drops.js"},+ {+ "src": "/api/irl/world-lines/verify/([^/]+)",+ "dest": "/api/irl/world-lines.js"+ },+ {+ "src": "/api/irl/world-lines/([^/]+)",+ "dest": "/api/irl/world-lines.js"+ },+ {+ "src": "/api/irl/world-lines",+ "dest": "/api/irl/world-lines.js"+ },{"src": "/api/irl/pins/mine","dest": "/api/irl/pins.js"@@ -4006,6 +4043,10 @@"path": "/api/cron/wallet-intents","schedule": "*/10 * * * *"},+ {+ "path": "/api/cron/reconcile-decisions",+ "schedule": "*/10 * * * *"+ },{"path": "/api/cron/dead-man-switch","schedule": "0 5 * * *"diff --git a/vite.config.js b/vite.config.jsindex 1d7244c85..be63718a0 100644--- a/vite.config.js+++ b/vite.config.js@@ -343,6 +343,7 @@ const appConfig = {'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),leaderboard: resolve(__dirname, 'pages/leaderboard.html'),+ 'reasoning-ledger': resolve(__dirname, 'pages/reasoning-ledger.html'),mirror: resolve(__dirname, 'pages/mirror.html'),strategies: resolve(__dirname, 'pages/strategies.html'),swarms: resolve(__dirname, 'pages/swarms.html'),@@ -386,6 +387,7 @@ const appConfig = {'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),autopilot: resolve(__dirname, 'pages/autopilot.html'),'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),+ three: resolve(__dirname, 'pages/three.html'),'three-live': resolve(__dirname, 'pages/three-live.html'),'three-token': resolve(__dirname, 'pages/three-token.html'),'avatar-artifact': resolve(__dirname, 'pages/avatar-artifact.html'),@@ -405,6 +407,7 @@ const appConfig = {'ar-page': resolve(__dirname, 'pages/ar.html'),creating: resolve(__dirname, 'pages/creating.html'),pricing: resolve(__dirname, 'pages/pricing.html'),+ billing: resolve(__dirname, 'pages/billing.html'),credits: resolve(__dirname, 'pages/credits.html'),'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),'avatar-studio-demo': resolve(__dirname, 'pages/avatar-studio-demo.html'),@@ -828,7 +831,9 @@ support: resolve(__dirname, 'pages/support.html'),'/autopilot/': resolve(root, 'pages/autopilot.html'),'/pump-visualizer': resolve(root, 'pages/pump-visualizer.html'),'/pump-visualizer/': resolve(root, 'pages/pump-visualizer.html'),- '/three-live': resolve(root, 'pages/three-live.html'),+ '/three': resolve(root, 'pages/three.html'),+ '/three/': resolve(root, 'pages/three.html'),+ '/three-live': resolve(root, 'pages/three-live.html'),'/three-live/': resolve(root, 'pages/three-live.html'),'/three-token': resolve(root, 'pages/three-token.html'),'/three-token/': resolve(root, 'pages/three-token.html'),@@ -1144,6 +1149,9 @@ support: resolve(__dirname, 'pages/support.html'),// /signals/<slug> → signal feed detail page (hydrates from /api/signals/feed)else if (!filePath && /^\/signals\/[^/.]+\/?$/.test(path))filePath = resolve(root, 'pages/signal-detail.html');+ // /ledger and /ledger/:agentId → the Reasoning Ledger surface+ else if (!filePath && /^\/ledger(\/[^/.]+)?\/?$/.test(path))+ filePath = resolve(root, 'pages/reasoning-ledger.html');// `[^/.]+` (no dot) mirrors vercel.json's `/agents/([^/.]+)` so// static assets like /agents/boot.js fall through to public/// instead of being served the agent-detail HTML shell.@@ -2025,6 +2033,10 @@ support: resolve(__dirname, 'pages/support.html'),},workbox: {maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,+ // Pull in the Web Push handlers (push + notificationclick). Kept in+ // public/push-sw.js as a classic script so the generated Workbox SW+ // importScripts it without switching to an injectManifest build.+ importScripts: ['/push-sw.js'],// MPA: every route is a separate HTML file served by the server.// No navigation fallback — uncached navigations go to the network.// HTML is intentionally excluded from globPatterns so it is neverdiff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex e0722ca1b..ea792ff35 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -19,6 +19,62 @@ import {} from '../../api/_lib/agent-trade-guards.js';import { buildAmmSellInstructions } from './amm-exit.js';import { assessTradeSafety, recordFirewallDecision } from '../../api/_lib/trade-firewall.js';+import { recordDecision } from '../../api/_lib/reasoning-ledger.js';++// Self-rated conviction for a snipe entry, 0..1. Lower price impact and a clean+// firewall verdict raise it; a warned verdict and heavy impact lower it. This is+// the prediction the Reasoning Ledger later scores for calibration — does an+// 80%-confidence snipe actually exit profitably 80% of the time?+function snipeConfidence({ priceImpactPct, maxImpactPct, firewallVerdict }) {+ const impactPenalty = Math.min(1, Math.max(0, priceImpactPct) / (maxImpactPct > 0 ? maxImpactPct : 10)) * 0.4;+ const fwBonus = firewallVerdict === 'allow' ? 0.1 : firewallVerdict === 'warn' ? -0.15 : 0;+ const c = 0.6 + fwBonus - impactPenalty;+ return Math.min(0.95, Math.max(0.05, c));+}++// Capture an opened snipe as a tamper-evident decision in the agent's reasoning+// ledger. Best-effort: the on-chain buy has already settled, so a ledger-write+// failure must never throw the trade away. Reconciled later against the closed+// position's realized P&L by api/cron/reconcile-decisions.js.+async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, priceImpactPct, firewall, perTradeLamports }) {+ try {+ const perTradeSol = Number(BigInt(perTradeLamports)) / 1e9;+ const confidence = snipeConfidence({+ priceImpactPct,+ maxImpactPct: Number(strat.max_price_impact_pct) || 10,+ firewallVerdict: firewall?.verdict || null,+ });+ const trigger = mint.entry_trigger || 'new_mint';+ const rationale =+ `Sniped $${(mint.symbol || mint.mint.slice(0, 4)).toUpperCase()} on a ${trigger} trigger ` ++ `with ${priceImpactPct.toFixed(2)}% price impact` ++ (firewall ? `; firewall verdict ${firewall.verdict} (score ${firewall.score}).` : '.') ++ ` Committed ${perTradeSol.toFixed(4)} SOL expecting a profitable exit.`;+ await recordDecision({+ agentId: strat.agent_id,+ kind: 'snipe',+ subjectRef: mint.mint,+ actionRef: String(posId),+ confidence,+ network,+ inputs: {+ entry_trigger: trigger,+ trigger_ref: mint.trigger_ref || null,+ price_impact_pct: Number(priceImpactPct.toFixed(4)),+ per_trade_sol: Number(perTradeSol.toFixed(6)),+ firewall: firewall ? { verdict: firewall.verdict, score: firewall.score } : null,+ position_id: posId,+ buy_sig: sig && sig !== 'SIMULATED' ? sig : null,+ mode,+ symbol: mint.symbol || null,+ },+ prediction: { direction: 'up', basis: 'snipe entry expects a profitable exit', metric: 'realized_pnl' },+ rationale,+ });+ } catch (err) {+ log.warn?.('ledger_record_failed', { agent: strat.agent_id, mint: mint.mint, message: err?.message });+ }+}// ── per-agent serialization ────────────────────────────────────────────────// Single-worker assumption: a per-agent in-process lock makes the budget +@@ -226,6 +282,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {// 'off' skips the check. Never throws — the kernel degrades to 'warn'// when a data source is down, so a firewall hiccup can't stall the trader.const firewallLevel = ['warn', 'off'].includes(strat.firewall_level) ? strat.firewall_level : 'block';+ let firewallSnapshot = null; // captured for the reasoning ledgerif (firewallLevel !== 'off') {const assessment = await assessTradeSafety({network: cfg.network,@@ -261,6 +318,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {if (assessment.verdict !== 'allow') {log.info('firewall warn (proceeding)', { ...tag, level: firewallLevel, verdict: assessment.verdict, score: assessment.score });}+ firewallSnapshot = { verdict: assessment.verdict, score: assessment.score };}}@@ -317,6 +375,10 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint });+ await recordSnipeDecision({+ strat, network: cfg.network, mint, posId, sig, mode: cfg.mode,+ priceImpactPct: Number(quote.priceImpactPct), firewall: firewallSnapshot, perTradeLamports: perTrade,+ });return { status: 'open', sig };} catch (err) {return await fail(posId, tag, errCode(err), err);