Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: cross-surface leaderboard, streaks, and badges at /rankings
fudjiabacd1220e5d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f3a9fb40..6524f2bb3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,10 +7,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-12- **Docs · The autonomous economy** (`/docs/autonomous-economy`) — How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.+- **Rankings** (`/rankings`) — The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.- **Robinhood Chain** (`/markets/robinhood`) — The 24/7 tokenized-equity board for Robinhood Chain (4663): live Chainlink NAV vs DEX premium for every Stock Token, a memecoin screener across NOXA and The Odyssey launchpads, recent launches, and chain TVL — plus a real wallet-connect buy flow for its coins.- **Search** (`/search`) — One search across every creation type on three.ws — avatars, agents, 3D models, worlds, and coins — with remixable models remixable straight from the results.- **Your creator portfolio** (`/profile`) — Your public three.ws portfolio: every avatar, agent, forged 3D model, world, coin, skill, and plugin you've made, in one place. Signed out, this redirects to sign-in; every user's own page also lives at /u/:username.- **/feed and /community are now real, live pages** — /feed used to only show activity from people you follow — it now defaults to a live, platform-wide feed of every new avatar, agent, forged 3D model, saved world, coin launch, and follow, with a toggle to switch to just the people you follow. Scroll for more and it loads the next page automatically; a "New activity" pill appears when something fresh lands so the list never jumps under you mid-read. /community, previously a static grid of links, now leads with that same live activity feed alongside the existing links to X, GitHub, docs, and tutorials. (`/feed`) `[feature]`+- **A cross-surface leaderboard, streaks, and badges** — A new Rankings board at /rankings ranks creators across every surface at once — creations forged, remixes received, coins launched, followers, and distance walked while signed in — with your own rank pinned even if you're off the visible page. Showing up daily (a login, a finished creation, or a walk session) now builds a real streak, shown on your profile and on the Rankings page. Four badges are genuinely earnable and persist once unlocked: First Creation, Remixed, 7-Day Streak, and a daily-refreshed Top 10 placement per metric. (`/rankings`) `[feature]`- **Agent discovery fixed: six paid endpoints were invisible to x402 scanners** — The machine-readable catalog at /openapi.json — what AI agents and x402 scanners like x402scan and AgentCash read to find and pay for three.ws APIs — had six paid endpoints (agent bouncer, verifiable vanity keys, crypto intel, cosmetic purchase, animation download, club cover) accidentally buried inside another entry, making them undiscoverable. All 61 payable routes now list correctly and the document passes the AgentCash discovery validator. The Permit2 gasless-payment demo is now only advertised when its settlement lane is actually live, so agents are never quoted a payment path that can't settle. (`/openapi.json`) `[fix, improvement]`- **Agent profiles, redesigned** — Agent profile pages got a ground-up redesign. Instead of one endless column of cards, everything is now organized into clear sections — Overview, Capabilities, Economy, Activity, Trust & Identity, Reviews, and Developers — with a sticky navigation bar that follows you as you scroll and hides sections that have nothing to show. The hero is a compact identity band with the live 3D avatar beside the agent's name, description, and actions, and secondary view modes now live in a tidy menu instead of a wall of buttons. Pages are roughly 40% shorter and much easier to scan. Prefer the old look? Every profile keeps a “Classic layout” link that serves the previous design unchanged. The companion panels (live presence, stages, work-for-hire, alpha co-pilot) now sit in a compact strip beside the profile instead of stacking above it — on mobile the agent's name and avatar are the first thing you see — and the live watch view (screen, avatar cam, action log) has a proper home in the Activity section. Signed-out visitors get a clear “sign in to see the action log” state instead of an endless loading spinner, and stats with nothing to report simply don't render. (`/agents`) `[improvement, feature]`- **AI features can no longer go down when one provider does** — Every AI-powered feature on three.ws (fact checks, agent chat, persona extraction, scene composing) routes through one shared brain that tries free providers first and falls back automatically. That chain just got much deeper: Groq now has a second lane with its own separate quota, OpenRouter gets a zero-credit free lane so an empty account no longer kills it, optional Cerebras and Google AI Studio lanes activate the moment a key is added, and — the anchor — Gemini on the platform's own Google Cloud now backs the whole chain with no third-party quota to exhaust. Previously a rare bad hour where every free tier was exhausted at once could surface an error; now the request rides through. The fact-checker was also corrected to stop favoring a paid key ahead of the free lanes. (`/changelog`) `[improvement, fix, infra]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 755f40642..2bb4777c9 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -27,6 +27,7 @@ bottom.| Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12) a **Creations** tab merging forged 3D models + Scene Studio worlds — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge` and `/diorama` stay anonymous by default (no login required); a signed-in creator's `user_id` is now attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. || Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category || Cross-entity search | [pages/search.html](pages/search.html) `→ /search`, backend [api/search.js](api/search.js) + query layer [api/_lib/cross-search.js](api/_lib/cross-search.js) | Live | The one search across every creation type — avatars, on-chain/Solana agents, forged 3D models, worlds, and coins. Federates (not one SQL UNION — the stores are genuinely heterogeneous, two of five aren't even in the same database) five parallel queries, normalizes into one card shape, and ranks by recency plus real signals (follower count via `user_follows`, remix count, view count) — see the file header in `api/search.js` for the full unify-vs-federate writeup. Model results carry a working "Remix — $0.25" action against the existing paid rail ([api/x402/remix-asset.js](api/x402/remix-asset.js)), reused from [pages/creations.html](pages/creations.html) rather than re-derived. Coin search checks three.ws's own launch directory (`pump_agent_mints`) first, then falls back to market-wide pump.fun/Birdeye search for broader coverage (those external matches carry no verified timestamp or creator profile, and are ranked/labelled accordingly). Linked from the Discover nav menu. |+| Cross-surface rankings, streaks & badges | [pages/rankings.html](pages/rankings.html) `→ /rankings`, backend [api/leaderboard/unified.js](api/leaderboard/unified.js), streak/badge engine [api/_lib/streaks.js](api/_lib/streaks.js) (migration [api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql](api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql)), daily Top-10 badge sweep [api/cron/leaderboard-rollup.js](api/cron/leaderboard-rollup.js) | Live | Five real, queried leaderboard metrics — creations (forge models + worlds), remixes received, coin launches, followers, and walk distance (signed-in walkers, all-time) — ranked live with the viewer's own rank pinned even off-page. Every signed-in qualifying action (login, a finished forge model, a saved world, a `/walk` session) rolls a per-user daily streak in `user_streaks` via `recordDailyActivity()`, called from [api/_lib/auth.js](api/_lib/auth.js), [api/_lib/forge-store.js](api/_lib/forge-store.js), [api/_lib/diorama-store.js](api/_lib/diorama-store.js), and [api/walk/metrics.js](api/walk/metrics.js). Four real earned badges persist in `user_badges`: First Creation, Remixed (awarded in [api/x402/remix-asset.js](api/x402/remix-asset.js) when a remix lands on your creation), 7-Day Streak, and a daily-refreshed `top10_<metric>` per leaderboard. Streak + badges surface on the profile ([pages/profile.html](pages/profile.html)) and the Rankings page itself. Rejected metrics (documented in `api/leaderboard/unified.js`'s header): royalties earned in USD (the settlement record is a single overwritten JSONB column, not a cumulative ledger) and `/play` activity (no per-human-user session table exists). || OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632): Agent Identity Studio flagship + decomposed studio services. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities`; docs: [docs/okx-marketplace.md](docs/okx-marketplace.md) || Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*` — token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) || Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) merges `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `bonding`, `launches`, `symbol`, `token`, `trending`, `wallet`, `whales`) via a static import barrel — the production source of truth, since Vercel's bundler only ships what static imports reach — plus an additive dev-time directory glob; skips malformed/throwing entries, never throws, valid-empty when zero. New descriptor = drop the file AND add its import line to the barrel. OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Endpoint handlers live in `api/crypto/*.js`. Spec: [prompts/x402-overhaul/](prompts/x402-overhaul) |diff --git a/api/_lib/auth.js b/api/_lib/auth.jsindex 0e79bd1f0..b3ae0381a 100644--- a/api/_lib/auth.js+++ b/api/_lib/auth.js@@ -6,6 +6,7 @@ import { env } from './env.js';import { sql } from './db.js';import { logAudit } from './audit.js';import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';+import { recordDailyActivity } from './streaks.js';const ACCESS_TTL_SEC = 60 * 60; // 1h access tokensconst REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens@@ -153,6 +154,10 @@ export async function createSession({ userId, userAgent, ip }) {insert into sessions (user_id, token_hash, user_agent, ip, expires_at)values (${userId}, ${hash}, ${userAgent ?? null}, ${ip ?? null}, now() + ${`${SESSION_TTL_SEC} seconds`}::interval)`;+ // A login (or the once-a-day silent session rotation in getSessionUser)+ // is a qualifying activity for the cross-surface streak. Fire-and-forget —+ // a streak-tracking hiccup must never block sign-in.+ recordDailyActivity(userId).catch(() => {});return secret;}diff --git a/api/_lib/diorama-store.js b/api/_lib/diorama-store.jsindex 1a47effd6..df0329171 100644--- a/api/_lib/diorama-store.js+++ b/api/_lib/diorama-store.js@@ -16,6 +16,7 @@ import { randomUUID } from 'node:crypto';import { sql } from './db.js';import { databaseConfigured } from './env.js';import { normalizeDiorama } from '../../src/diorama/schema.js';+import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';export function dioramaStoreEnabled() {return databaseConfigured();@@ -76,6 +77,12 @@ export async function saveDiorama({ diorama, clientKey = null, userId = null })${clientKey}, ${userId}, 0, false, ${createdAt})`;+ // A saved world is a qualifying streak action + the trigger for the+ // "first creation" badge. Fire-and-forget — never blocks the save.+ if (userId) {+ recordDailyActivity(userId).catch(() => {});+ maybeAwardFirstCreation(userId).catch(() => {});+ }return { id, createdAt };} catch (err) {console.error('[diorama-store] saveDiorama failed:', err?.message);diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 318cbf268..ecbb35a5d 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -18,10 +18,10 @@ import { randomUUID } from 'node:crypto';import { sql, isDbUnavailableError } from './db.js';import { databaseConfigured } from './env.js';import { putObject, publicUrl } from './r2.js';+import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';import { recordGenerationEvent } from './forge-events.js';import { scoreGlbQuality } from './glb-quality.js';import { compressGlb } from './glb-compress.js';-import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the// raw browser-local id. The id is anonymous to begin with; this is hygiene, not@@ -122,7 +122,7 @@ export async function findByJob({ replicateJobId, clientKey }) {const rows = await sql`select id, status, glb_url, glb_key, prompt, preview_image_url,views_requested, views_used, multiview, backend, tier, path, model_category,- created_at+ user_id, created_atfrom forge_creationswhere replicate_job_id = ${replicateJobId} and client_key = ${clientKey}limit 1@@ -322,6 +322,13 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, qlatencyMs,source: 'materialize',});+ // A finished, signed-in creation is a qualifying streak action + the+ // trigger for the "first creation" badge. Fire-and-forget — never blocks+ // delivery of the model itself.+ if (existing.user_id) {+ recordDailyActivity(existing.user_id).catch(() => {});+ maybeAwardFirstCreation(existing.user_id).catch(() => {});+ }return {id: existing.id,glbUrl: glb.publicUrl,diff --git a/api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql b/api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sqlnew file mode 100644index 000000000..970e4640c--- /dev/null+++ b/api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql@@ -0,0 +1,39 @@+-- Cross-surface leaderboard: daily-activity streaks + earned badges.+--+-- Powers GET /api/leaderboard/unified (creations, remixes received, launches,+-- followers, walk distance — each a real query over existing tables) and the+-- streak/badge widgets on /u/:username (see api/_lib/streaks.js).+--+-- A "qualifying action" that extends a streak is any of: a session+-- login/refresh (api/_lib/auth.js createSession), a finished forge model or+-- saved world (api/_lib/forge-store.js materializeCreation,+-- api/_lib/diorama-store.js saveDiorama), or a /walk activity batch+-- (api/walk/metrics.js) — all funnel through recordDailyActivity(userId) in+-- api/_lib/streaks.js so the streak logic lives in exactly one place.+--+-- Fully idempotent — safe to re-run. Mirrored into api/_lib/schema.sql.++-- ── user_streaks — one row per user, the running daily-activity streak ──────+create table if not exists user_streaks (+ user_id uuid primary key references users(id) on delete cascade,+ current_streak integer not null default 0,+ longest_streak integer not null default 0,+ last_active_day date,+ updated_at timestamptz not null default now(),+ created_at timestamptz not null default now()+);++-- ── user_badges — unlocked achievement records, one row per (user, code) ────+-- Mirrors the walk_achievements pattern (api/_lib/migrations/+-- 20260621140000_walk_metrics.sql): server-persisted, awarded once, never+-- computed fresh on every read.+create table if not exists user_badges (+ id bigserial primary key,+ user_id uuid not null references users(id) on delete cascade,+ code text not null, -- first_creation | first_remix_received | streak_7 | top10_<metric>+ context jsonb, -- optional detail (e.g. { "metric": "creations", "rank": 4 })+ unlocked_at timestamptz not null default now()+);++create unique index if not exists user_badges_uniq on user_badges (user_id, code);+create index if not exists user_badges_user on user_badges (user_id, unlocked_at desc);diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex f83bf3c99..7a983a6d6 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -2251,3 +2251,25 @@ create index if not exists agent_brain_anchors_hashon agent_brain_anchors(agent_id, brain_hash);create index if not exists agent_brain_anchors_statuson agent_brain_anchors(agent_id, status, created_at desc);++-- ── user_streaks / user_badges — cross-surface leaderboard streaks + badges ──+-- See api/_lib/migrations/20260712020000_leaderboard_streaks_badges.sql for the+-- full rationale.+create table if not exists user_streaks (+ user_id uuid primary key references users(id) on delete cascade,+ current_streak integer not null default 0,+ longest_streak integer not null default 0,+ last_active_day date,+ updated_at timestamptz not null default now(),+ created_at timestamptz not null default now()+);++create table if not exists user_badges (+ id bigserial primary key,+ user_id uuid not null references users(id) on delete cascade,+ code text not null,+ context jsonb,+ unlocked_at timestamptz not null default now()+);+create unique index if not exists user_badges_uniq on user_badges (user_id, code);+create index if not exists user_badges_user on user_badges (user_id, unlocked_at desc);diff --git a/api/_lib/streaks.js b/api/_lib/streaks.jsnew file mode 100644index 000000000..a531b7223--- /dev/null+++ b/api/_lib/streaks.js@@ -0,0 +1,211 @@+/**+ * Cross-surface streaks + badges — the retention layer for the unified+ * leaderboard (prompt 06 of the user-value pack).+ *+ * A "qualifying action" is any of:+ * · a session login/refresh (api/_lib/auth.js createSession)+ * · a finished forge model (api/_lib/forge-store.js materializeCreation)+ * · a saved world (api/_lib/diorama-store.js saveDiorama)+ * · a /walk activity batch (api/walk/metrics.js, signed-in walkers only)+ *+ * Each of those call sites calls recordDailyActivity(userId) after its own+ * write succeeds. The upsert here is idempotent per UTC day — calling it+ * five times in one day (five creations, a login, a walk) only ever counts+ * once toward the streak, so instrumenting multiple call sites is safe and+ * cannot inflate a streak beyond one increment per real day.+ *+ * Badges are earned records, not computed-on-the-fly trophies: once unlocked+ * a row in user_badges never disappears, even if the underlying stat that+ * earned it later changes (e.g. a creation is later deleted).+ */++import { sql, isDbUnavailableError } from './db.js';++export const BADGES = Object.freeze({+ FIRST_CREATION: 'first_creation',+ FIRST_REMIX_RECEIVED: 'first_remix_received',+ STREAK_7: 'streak_7',+ TOP10: (metric) => `top10_${metric}`,+});++export const BADGE_META = {+ first_creation: {+ label: 'First Creation',+ description: 'Forged your first 3D model or built your first world.',+ icon: '✨',+ },+ first_remix_received: {+ label: 'Remixed',+ description: 'Another creator built on top of one of your creations.',+ icon: '🔀',+ },+ streak_7: {+ label: '7-Day Streak',+ description: 'Showed up on three.ws seven days running.',+ icon: '🔥',+ },+};++function top10Meta(metric) {+ const labels = {+ creations: 'Creations',+ remixes_received: 'Remixes Received',+ launches: 'Launches',+ followers: 'Followers',+ walk_distance: 'Walk Distance',+ };+ return {+ label: `Top 10 · ${labels[metric] || metric}`,+ description: `Ranked in the top 10 platform-wide for ${labels[metric] || metric}.`,+ icon: '🏆',+ };+}++/** Static or computed metadata for a badge code — used to render it anywhere. */+export function badgeMeta(code) {+ if (BADGE_META[code]) return BADGE_META[code];+ const m = /^top10_(.+)$/.exec(code);+ if (m) return top10Meta(m[1]);+ return { label: code, description: '', icon: '★' };+}++/**+ * Award a badge once. Idempotent (unique on user_id+code) — safe to call+ * every time the qualifying condition is checked, not just on the crossing.+ * @returns {Promise<boolean>} true if this call newly unlocked it.+ */+export async function unlockBadge(userId, code, context = null) {+ if (!userId || !code) return false;+ try {+ const rows = await sql`+ insert into user_badges (user_id, code, context)+ values (${userId}, ${code}, ${context ? JSON.stringify(context) : null}::jsonb)+ on conflict (user_id, code) do nothing+ returning id+ `;+ return rows.length > 0;+ } catch (err) {+ if (isDbUnavailableError(err)) console.warn('[streaks] unlockBadge skipped (db unavailable):', err?.message);+ else console.error('[streaks] unlockBadge failed:', err?.message);+ return false;+ }+}++/** All badges a user has earned, newest first. */+export async function listBadges(userId) {+ if (!userId) return [];+ try {+ const rows = await sql`+ select code, context, unlocked_at+ from user_badges+ where user_id = ${userId}+ order by unlocked_at desc+ `;+ return rows.map((r) => ({ code: r.code, context: r.context ?? null, unlockedAt: r.unlocked_at, ...badgeMeta(r.code) }));+ } catch (err) {+ if (isDbUnavailableError(err)) console.warn('[streaks] listBadges skipped (db unavailable):', err?.message);+ else console.error('[streaks] listBadges failed:', err?.message);+ return [];+ }+}++function todayUTC() {+ return new Date().toISOString().slice(0, 10);+}++/**+ * Record today as an active day for a user and roll the streak forward.+ * Same-day repeats are a no-op (idempotent). A gap of 1+ missed UTC days+ * resets current_streak to 1. Awards the streak_7 badge on crossing.+ *+ * @returns {Promise<{currentStreak:number, longestStreak:number, lastActiveDay:string}|null>}+ */+export async function recordDailyActivity(userId) {+ if (!userId) return null;+ const today = todayUTC();+ try {+ const [row] = await sql`+ insert into user_streaks (user_id, current_streak, longest_streak, last_active_day)+ values (${userId}, 1, 1, ${today})+ on conflict (user_id) do update set+ current_streak = case+ when user_streaks.last_active_day = ${today}::date then user_streaks.current_streak+ when user_streaks.last_active_day = ${today}::date - 1 then user_streaks.current_streak + 1+ else 1+ end,+ longest_streak = greatest(+ user_streaks.longest_streak,+ case+ when user_streaks.last_active_day = ${today}::date then user_streaks.current_streak+ when user_streaks.last_active_day = ${today}::date - 1 then user_streaks.current_streak + 1+ else 1+ end+ ),+ last_active_day = ${today}::date,+ updated_at = now()+ returning current_streak, longest_streak, last_active_day+ `;+ if (!row) return null;+ if (row.current_streak >= 7) await unlockBadge(userId, BADGES.STREAK_7);+ return {+ currentStreak: row.current_streak,+ longestStreak: row.longest_streak,+ lastActiveDay: row.last_active_day,+ };+ } catch (err) {+ if (isDbUnavailableError(err)) console.warn('[streaks] recordDailyActivity skipped (db unavailable):', err?.message);+ else console.error('[streaks] recordDailyActivity failed:', err?.message);+ return null;+ }+}++/**+ * Award the "first creation" badge the moment a user's combined forge-model ++ * world count reaches 1. Reads forge_creations/dioramas directly (not through+ * forge-store.js/diorama-store.js) so this module has no dependency on either+ * store — both of them depend on streaks.js, not the other way around.+ */+export async function maybeAwardFirstCreation(userId) {+ if (!userId) return false;+ try {+ const [row] = await sql`+ select+ (select count(*)::int from forge_creations where user_id = ${userId} and status = 'done' and glb_url is not null)+ + (select count(*)::int from dioramas where user_id = ${userId}) as total+ `;+ if ((row?.total ?? 0) >= 1) return await unlockBadge(userId, BADGES.FIRST_CREATION);+ return false;+ } catch (err) {+ if (isDbUnavailableError(err)) console.warn('[streaks] maybeAwardFirstCreation skipped (db unavailable):', err?.message);+ else console.error('[streaks] maybeAwardFirstCreation failed:', err?.message);+ return false;+ }+}++/** Read a user's current streak without recording activity. */+export async function getStreak(userId) {+ if (!userId) return null;+ try {+ const [row] = await sql`+ select current_streak, longest_streak, last_active_day+ from user_streaks+ where user_id = ${userId}+ `;+ if (!row) return { currentStreak: 0, longestStreak: 0, lastActiveDay: null };+ // A streak "expires" the moment two UTC days have passed with no activity —+ // reflect that on read even before the next recordDailyActivity() rolls it+ // over, so a stale streak never displays as still-alive.+ const today = todayUTC();+ const last = row.last_active_day ? String(row.last_active_day) : null;+ const isBroken = last && last !== today && new Date(today) - new Date(last) > 86400000;+ return {+ currentStreak: isBroken ? 0 : row.current_streak,+ longestStreak: row.longest_streak,+ lastActiveDay: last,+ };+ } catch (err) {+ if (isDbUnavailableError(err)) console.warn('[streaks] getStreak skipped (db unavailable):', err?.message);+ else console.error('[streaks] getStreak failed:', err?.message);+ return null;+ }+}diff --git a/api/cron/leaderboard-rollup.js b/api/cron/leaderboard-rollup.jsnew file mode 100644index 000000000..422ed2db5--- /dev/null+++ b/api/cron/leaderboard-rollup.js@@ -0,0 +1,132 @@+// GET /api/cron/leaderboard-rollup — daily top-10 badge sweep for the+// cross-surface leaderboard (prompt 06 of the user-value pack).+//+// The leaderboard itself (GET /api/leaderboard/unified) is read live — none of+// its five metrics need a rollup table, the underlying queries are cheap+// aggregates the same way /api/walk/leaderboard's all-time window already is.+// The ONE thing that genuinely needs a daily cadence is the "top10_<metric>"+// badge: a placement earned today shouldn't quietly stop being true if the+// user's rank slips tomorrow, so it has to be captured at a point in time+// rather than recomputed live. This cron is that point in time — once daily,+// walk the top 10 of each metric and award the badge to whoever is there right+// now. Idempotent (user_badges is unique on user_id+code), so a user who holds+// top-10 for a week earns the badge once, on day one.++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { unlockBadge, BADGES } from '../_lib/streaks.js';++const METRICS = ['creations', 'remixes_received', 'launches', 'followers', 'walk_distance'];++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;+}++async function top10UserIds(metric) {+ if (metric === 'creations') {+ const rows = await sql`+ with per_user as (+ select user_id, count(*) as n+ from forge_creations+ where user_id is not null and status = 'done' and glb_url is not null+ group by user_id+ union all+ select user_id, count(*) as n+ from dioramas+ where user_id is not null+ group by user_id+ )+ select user_id, sum(n)::bigint as value+ from per_user+ group by user_id+ having sum(n) > 0+ order by value desc+ limit 10+ `;+ return rows.map((r) => r.user_id);+ }+ if (metric === 'remixes_received') {+ const rows = await sql`+ with mine as (+ select id, user_id from forge_creations where user_id is not null and status = 'done'+ ),+ children as (+ select parent_creation_id, count(*) as n from forge_creations+ where parent_creation_id is not null group by parent_creation_id+ )+ select m.user_id, sum(c.n)::bigint as value+ from mine m join children c on c.parent_creation_id = m.id+ group by m.user_id+ order by value desc+ limit 10+ `;+ return rows.map((r) => r.user_id);+ }+ if (metric === 'launches') {+ const rows = await sql`+ select user_id, count(*)::bigint as value+ from agent_identities+ where user_id is not null and is_public = true and deleted_at is null+ and meta->'token'->>'mint' is not null+ group by user_id+ order by value desc+ limit 10+ `;+ return rows.map((r) => r.user_id);+ }+ if (metric === 'followers') {+ const rows = await sql`+ select following_id as user_id, count(*)::bigint as value+ from user_follows+ group by following_id+ order by value desc+ limit 10+ `;+ return rows.map((r) => r.user_id);+ }+ // walk_distance+ const rows = await sql`+ select user_id, sum(distance_meters)::float8 as value+ from walk_metrics+ where user_id is not null+ group by user_id+ having sum(distance_meters) > 0+ order by value desc+ limit 10+ `;+ return rows.map((r) => r.user_id);+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ const awarded = {};+ for (const metric of METRICS) {+ const userIds = await top10UserIds(metric).catch((err) => {+ console.error(`[leaderboard-rollup] ${metric} ranking failed:`, err?.message);+ return [];+ });+ let count = 0;+ for (const userId of userIds) {+ const newlyAwarded = await unlockBadge(userId, BADGES.TOP10(metric), { metric });+ if (newlyAwarded) count += 1;+ }+ awarded[metric] = { checked: userIds.length, newlyAwarded: count };+ }++ return json(res, 200, { ok: true, awarded, ranAt: new Date().toISOString() });+});diff --git a/api/leaderboard/unified.js b/api/leaderboard/unified.jsnew file mode 100644index 000000000..81f0e3282--- /dev/null+++ b/api/leaderboard/unified.js@@ -0,0 +1,229 @@+// GET /api/leaderboard/unified — the cross-surface leaderboard (prompt 06 of+// the user-value pack).+//+// ?metric = creations | remixes_received | launches | followers | walk_distance+// (default creations)+// ?limit = 1..100 (default 50)+// ?offset = 0..+//+// Five real, queried rankings — every column here is a COUNT/SUM over an+// existing table, never a synthetic score:+// · creations — finished forge models (forge_creations, status=done)+// + saved worlds (dioramas), per signed-in creator.+// · remixes_received — count of OTHER creators' forge_creations rows whose+// parent_creation_id points at one of this user's+// finished creations (a real derivative count, not a+// view/like count).+// · launches — pump.fun coins minted from this user's agents+// (agent_identities.meta->'token'->>'mint').+// · followers — user_follows platform-wide follower count.+// · walk_distance — total metres walked while signed in (walk_metrics,+// all-time, signed-in walkers only — the anonymous+// half of walking already has its own board at+// /walk-leaderboard).+//+// Two metrics considered and REJECTED for lacking real data (see prompt+// report): "royalties earned" (forge_creations.remix_settlement_ref is a+// single JSONB column overwritten on every settlement, not an append-only+// ledger, so a cumulative sum across multiple remixes of the same source is+// not reliably computable without a schema change) and "/play activity" (no+// per-human-user session/quest-completion table exists — /play's own tables+// track wallet auth and agent-level Agora activity, not human play sessions).+//+// Every row is a real signed-in user (anonymous activity has no cross-surface+// identity to rank). The requester's own row is always resolved and pinned,+// even off-page, mirroring /api/walk/leaderboard's "you're #142" pattern.++import { cors, method, json, wrap, rateLimited, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';+import { thumbnailUrl } from '../_lib/r2.js';++export const maxDuration = 10;++const METRICS = new Set(['creations', 'remixes_received', 'launches', 'followers', 'walk_distance']);++const METRIC_LABEL = {+ creations: 'Creations',+ remixes_received: 'Remixes Received',+ launches: 'Launches',+ followers: 'Followers',+ walk_distance: 'Walk Distance',+};++// Per-metric ranking query — returns { user_id, value } rows, unsorted (the+// caller sorts once after merging in profile data isn't needed for sorting).+async function rankingRows(metric) {+ if (metric === 'creations') {+ return sql`+ with per_user as (+ select user_id, count(*) as n+ from forge_creations+ where user_id is not null and status = 'done' and glb_url is not null+ group by user_id+ union all+ select user_id, count(*) as n+ from dioramas+ where user_id is not null+ group by user_id+ )+ select user_id, sum(n)::bigint as value+ from per_user+ group by user_id+ `;+ }+ if (metric === 'remixes_received') {+ return sql`+ with mine as (+ select id, user_id+ from forge_creations+ where user_id is not null and status = 'done'+ ),+ children as (+ select parent_creation_id, count(*) as n+ from forge_creations+ where parent_creation_id is not null+ group by parent_creation_id+ )+ select m.user_id, sum(c.n)::bigint as value+ from mine m+ join children c on c.parent_creation_id = m.id+ group by m.user_id+ `;+ }+ if (metric === 'launches') {+ return sql`+ select user_id, count(*)::bigint as value+ from agent_identities+ where user_id is not null+ and is_public = true+ and deleted_at is null+ and meta->'token'->>'mint' is not null+ group by user_id+ `;+ }+ if (metric === 'followers') {+ return sql`+ select following_id as user_id, count(*)::bigint as value+ from user_follows+ group by following_id+ `;+ }+ // walk_distance+ return sql`+ select user_id, sum(distance_meters)::float8 as value+ from walk_metrics+ where user_id is not null+ group by user_id+ having sum(distance_meters) > 0+ `;+}++async function resolveViewerId(req) {+ try {+ const bearer = extractBearer(req);+ const user = bearer ? await authenticateBearer(bearer) : await getSessionUser(req);+ return user?.userId || user?.id || user?.sub || null;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const metric = url.searchParams.get('metric') || 'creations';+ if (!METRICS.has(metric)) {+ return error(res, 400, 'bad_metric', 'metric must be one of: ' + [...METRICS].join(', '));+ }+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 100);+ const offset = Math.max(Number(url.searchParams.get('offset')) || 0, 0);++ const rows = await rankingRows(metric);++ const ranked = rows+ .map((r) => ({ userId: r.user_id, value: Number(r.value) || 0 }))+ .filter((r) => r.value > 0)+ .sort((a, b) => (b.value !== a.value ? b.value - a.value : a.userId < b.userId ? -1 : 1));++ const total = ranked.length;+ const rankByUser = new Map();+ ranked.forEach((r, i) => rankByUser.set(r.userId, i + 1));++ const page = ranked.slice(offset, offset + limit);++ const viewerId = await resolveViewerId(req);+ const idsNeeded = new Set(page.map((r) => r.userId));+ if (viewerId) idsNeeded.add(viewerId);++ const profiles = new Map();+ const idList = [...idsNeeded];+ if (idList.length) {+ const profRows = await sql`+ select u.id, u.username, u.display_name,+ (select thumbnail_key from avatars+ where owner_id = u.id and deleted_at is null and thumbnail_key is not null+ order by created_at desc limit 1) as thumbnail_key+ from users u+ where u.id = any(${idList}) and u.deleted_at is null+ `;+ for (const p of profRows) profiles.set(p.id, p);+ }++ function toRow(r) {+ const prof = profiles.get(r.userId);+ const handle = prof?.username ? `@${prof.username}` : prof?.display_name || 'three.ws creator';+ return {+ rank: rankByUser.get(r.userId),+ userId: r.userId,+ username: prof?.username || null,+ handle,+ profileUrl: prof?.username ? `/u/${prof.username}` : null,+ avatar: thumbnailUrl(prof?.thumbnail_key),+ value: metric === 'walk_distance' ? Math.round(r.value * 100) / 100 : Math.round(r.value),+ };+ }++ const pageRows = page.map(toRow);++ let me = null;+ if (viewerId) {+ if (rankByUser.has(viewerId)) {+ const entry = ranked.find((r) => r.userId === viewerId);+ me = toRow(entry);+ me.onPage = pageRows.some((r) => r.userId === viewerId);+ } else {+ const prof = profiles.get(viewerId);+ me = {+ rank: null,+ userId: viewerId,+ username: prof?.username || null,+ handle: prof?.username ? `@${prof.username}` : prof?.display_name || 'you',+ profileUrl: prof?.username ? `/u/${prof.username}` : null,+ avatar: thumbnailUrl(prof?.thumbnail_key),+ value: 0,+ onPage: false,+ unranked: true,+ };+ }+ }++ res.setHeader('cache-control', 'public, max-age=15, s-maxage=30, stale-while-revalidate=60');++ return json(res, 200, {+ metric,+ metricLabel: METRIC_LABEL[metric],+ total,+ limit,+ offset,+ hasMore: offset + limit < total,+ rows: pageRows,+ me,+ });+});diff --git a/api/users/[username].js b/api/users/[username].jsindex 821b67d48..eeffe3578 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -4,6 +4,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { publicUrl, thumbnailUrl } from '../_lib/r2.js';import { listCreationsByUser, countCreationsByUser } from '../_lib/forge-store.js';import { listDioramasByUser, countDioramasByUser } from '../_lib/diorama-store.js';+import { getStreak, listBadges } from '../_lib/streaks.js';const CREATIONS_PAGE_SIZE = 24;const SITE = 'https://three.ws';@@ -219,6 +220,14 @@ export default wrap(async (req, res) => {countDioramasByUser({ userId: user.id }),]);+ // Streak + badges — the retention layer for the cross-surface leaderboard.+ // Both fail soft to an empty/zero state so a streak-tracking hiccup never+ // 500s a profile.+ const [streak, badges] = await Promise.all([+ getStreak(user.id).catch(() => ({ currentStreak: 0, longestStreak: 0, lastActiveDay: null })),+ listBadges(user.id).catch(() => []),+ ]);+const avatars = avatarRows.map((a) => ({id: a.id,slug: a.slug,@@ -429,6 +438,8 @@ export default wrap(async (req, res) => {banner_url: user.banner_url || null,},stats,+ streak: streak || { currentStreak: 0, longestStreak: 0, lastActiveDay: null },+ badges,social,avatars,agents,diff --git a/api/walk/metrics.js b/api/walk/metrics.jsindex 27f9978ee..f6803fcb2 100644--- a/api/walk/metrics.js+++ b/api/walk/metrics.js@@ -31,6 +31,7 @@ import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';+import { recordDailyActivity } from '../_lib/streaks.js';export const maxDuration = 10;@@ -171,5 +172,9 @@ export default wrap(async (req, res) => {}}+ // A signed-in walker's session is a qualifying streak action. Anonymous+ // walkers have no user_id to attach a cross-surface streak to.+ if (userId && hasMetrics) recordDailyActivity(userId).catch(() => {});+return json(res, 200, { ok: true, recorded: hasMetrics || !!body.eventName || codes.length > 0 });});diff --git a/api/x402/remix-asset.js b/api/x402/remix-asset.jsindex a057c9386..8fde67bc4 100644--- a/api/x402/remix-asset.js+++ b/api/x402/remix-asset.js@@ -28,6 +28,7 @@ import { atomicsToUsd } from '../_lib/remix-royalty.js';import { composeRefinement } from '../../mcp-server/src/tools/_lineage.js';import { generate, originFromReq, viewerUrl } from '../_mcp-studio/forge-client.js';import remixAssetListing from '../_lib/service-catalog/services/remix-asset.js';+import { unlockBadge, BADGES } from '../_lib/streaks.js';import { publishUserEvent } from '../_lib/feed.js';// $0.25 — the cost of a generation. The creator royalty comes OUT of this fee@@ -161,6 +162,8 @@ async function handleRemix({ req, requirement }) {royaltyPaid: royalty.paid,royaltyUsd: royalty.creatorUsd ?? 0,});+ // First-remix-received badge — a real earned record, awarded once.+ unlockBadge(source.userId, BADGES.FIRST_REMIX_RECEIVED).catch(() => {});}return {diff --git a/data/changelog.json b/data/changelog.jsonindex cd26fd2c4..95ef4372e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -13458,6 +13458,15 @@"improvement"],"link": "/docs/market-data-api"+ },+ {+ "date": "2026-07-12",+ "title": "A cross-surface leaderboard, streaks, and badges",+ "summary": "A new Rankings board at /rankings ranks creators across every surface at once — creations forged, remixes received, coins launched, followers, and distance walked while signed in — with your own rank pinned even if you're off the visible page. Showing up daily (a login, a finished creation, or a walk session) now builds a real streak, shown on your profile and on the Rankings page. Four badges are genuinely earnable and persist once unlocked: First Creation, Remixed, 7-Day Streak, and a daily-refreshed Top 10 placement per metric.",+ "tags": [+ "feature"+ ],+ "link": "/rankings"}]}diff --git a/data/pages.json b/data/pages.jsonindex 043f2f6c9..d88368c83 100644--- a/data/pages.json+++ b/data/pages.json@@ -721,6 +721,14 @@"changefreq": "weekly","added": "2026-06-05"},+ {+ "path": "/rankings",+ "title": "Rankings",+ "description": "The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-07-12"+ },{"path": "/walk-leaderboard","title": "Walk Leaderboard",diff --git a/pages/community.html b/pages/community.htmlindex a2f447679..97d1e3461 100644--- a/pages/community.html+++ b/pages/community.html@@ -237,6 +237,12 @@<p>Step-by-step guides for creating your first agent, embedding on your site, minting on Solana, and adding paid skills.</p><a class="card-link" href="/tutorials">Browse tutorials →</a></div>+ <div class="card">+ <span class="icon">🏆</span>+ <h2>Rankings</h2>+ <p>The cross-surface leaderboard — creations, remixes, launches, followers, and walk distance. Build a daily streak and earn badges.</p>+ <a class="card-link" href="/rankings">See who's ranked →</a>+ </div></div><div class="section">diff --git a/pages/profile.html b/pages/profile.htmlindex 8cf8e8d8a..f3c612fd5 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -466,6 +466,53 @@color: rgba(255, 255, 255, 0.35);}+ /* ── Streak + badges ─────────────────────────────────────────────── */+ .up-streak-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+ margin: -1.1rem 0 2rem;+ }++ .up-streak-pill {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ padding: 0.4rem 0.75rem;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.02);+ font-size: 0.72rem;+ font-weight: 500;+ color: rgba(255, 255, 255, 0.75);+ }++ .up-streak-pill .up-streak-flame {+ font-size: 0.85rem;+ line-height: 1;+ }++ .up-badge-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ padding: 0.4rem 0.7rem;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.02);+ font-size: 0.72rem;+ font-weight: 500;+ color: rgba(255, 255, 255, 0.75);+ cursor: default;+ transition: border-color 0.15s, background 0.15s;+ }++ .up-badge-chip:hover {+ border-color: rgba(255, 255, 255, 0.2);+ background: rgba(255, 255, 255, 0.04);+ }+/* ── Tabs ────────────────────────────────────────────────────────── */.up-tabs {display: flex;@@ -1451,6 +1498,8 @@const {user,stats = {},+ streak = { currentStreak: 0, longestStreak: 0, lastActiveDay: null },+ badges = [],social = {},avatars = [],agents = [],@@ -1747,6 +1796,27 @@).join('');+ // Streak + earned badges — a real earned-record row, never a+ // synthetic trophy. Hidden entirely for a user with no streak and no+ // badges yet, rather than showing an empty "0-day streak" ghost.+ const streakHtml = (() => {+ const days = streak.currentStreak || 0;+ const badgeChips = badges+ .map(+ (b) => `+ <span class="up-badge-chip" title="${attr(b.description || '')}">+ <span aria-hidden="true">${esc(b.icon || '★')}</span> ${esc(b.label || b.code)}+ </span>+ `,+ )+ .join('');+ if (!days && !badgeChips) return '';+ const streakPill = days+ ? `<span class="up-streak-pill"><span class="up-streak-flame" aria-hidden="true">🔥</span> ${days}-day streak</span>`+ : '';+ return `<div class="up-streak-row">${streakPill}${badgeChips}</div>`;+ })();+// Tabs: only show those with content; default to first non-emptyconst tabs = [{ key: 'creations', label: 'Creations', count: stats.creations || creations.length },@@ -1828,6 +1898,7 @@</div><div id="up-walk-hero"></div><div class="up-stats">${statsHtml}</div>+ ${streakHtml}${tabBar}<section class="up-section" data-section="creations"${defaultTab === 'creations' ? '' : ' hidden'}>${renderCreationsGrid(creations)}diff --git a/pages/rankings.html b/pages/rankings.htmlnew file mode 100644index 000000000..7d7459b0d--- /dev/null+++ b/pages/rankings.html@@ -0,0 +1,384 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>Rankings · three.ws</title>+ <meta name="description" content="The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up." />+ <link rel="canonical" href="https://three.ws/rankings" />+ <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="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/rankings" />+ <meta property="og:title" content="Rankings · three.ws" />+ <meta property="og:description" content="Creators ranked by real creations, remixes received, coin launches, followers, and distance walked — one board across every surface." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=labs&t=Rankings&d=The+cross-surface+leaderboard+%E2%80%94+creations%2C+remixes%2C+launches%2C+followers%2C+and+walk+distance%2C+ranked.&p=%2Frankings" />+ <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="Rankings · three.ws" />+ <meta name="twitter:description" content="Creators ranked by real creations, remixes, launches, followers, and walk distance — one board across every surface." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&t=Rankings&d=The+cross-surface+leaderboard+%E2%80%94+creations%2C+remixes%2C+launches%2C+followers%2C+and+walk+distance%2C+ranked.&p=%2Frankings" />+ <meta name="theme-color" content="#0a0a0a" />+ <style>+ .rk-shell { max-width: 980px; margin: 0 auto; padding: var(--space-lg) var(--space-md) var(--space-2xl); }++ .rk-hero { padding: var(--space-xl) 0 var(--space-md); }+ .rk-kicker {+ display: inline-flex; align-items: center; gap: var(--space-xs);+ font: var(--weight-semibold) var(--text-2xs)/1.2 var(--font-mono);+ letter-spacing: 0.06em; text-transform: uppercase; color: var(--color-text-dim);+ margin: 0 0 var(--space-sm);+ }+ .rk-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--color-success); box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-success) 60%, transparent); animation: rk-pulse 1.8s ease infinite; }+ @keyframes rk-pulse { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--color-success) 55%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } }+ .rk-title { font: var(--weight-bold) var(--text-2xl)/1.05 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-sm); letter-spacing: -0.02em; }+ .rk-sub { font: var(--weight-regular) var(--text-base)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0; max-width: 62ch; }++ /* Your streak card */+ .rk-streak-card {+ display: none;+ align-items: center; gap: var(--space-md);+ margin: var(--space-lg) 0 0;+ padding: var(--space-md);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ background: linear-gradient(135deg, color-mix(in srgb, var(--accent) 10%, var(--surface-1)), var(--surface-1));+ }+ .rk-streak-card.is-visible { display: flex; }+ .rk-streak-flame { font-size: 28px; line-height: 1; flex: none; }+ .rk-streak-body { flex: 1; min-width: 0; }+ .rk-streak-num { font: var(--weight-bold) var(--text-xl)/1.1 var(--font-display); color: var(--color-text-bright); }+ .rk-streak-label { font: var(--weight-medium) var(--text-sm)/1.3 var(--font-body); color: var(--color-text-dim); margin-top: 2px; }+ .rk-streak-badges { display: flex; gap: var(--space-2xs); flex-wrap: wrap; }+ .rk-badge-chip {+ display: inline-flex; align-items: center; gap: 4px;+ padding: 4px 9px; border-radius: var(--radius-pill);+ background: var(--surface-2); border: 1px solid var(--color-border);+ font: var(--weight-medium) var(--text-2xs)/1 var(--font-body); color: var(--color-text);+ white-space: nowrap;+ }++ .rk-controls { display: flex; flex-wrap: wrap; gap: var(--space-sm); align-items: center; margin: var(--space-lg) 0 var(--space-md); }+ .rk-seg { display: inline-flex; flex-wrap: wrap; gap: var(--space-3xs); padding: var(--space-3xs); background: var(--surface-1); border: 1px solid var(--color-border); border-radius: var(--radius-pill); }+ .rk-seg-btn {+ appearance: none; border: 0; background: transparent; cursor: pointer;+ padding: var(--space-xs) var(--space-md); border-radius: var(--radius-pill);+ font: var(--weight-medium) var(--text-md)/1 var(--font-body); color: var(--color-text-dim);+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+ white-space: nowrap;+ }+ .rk-seg-btn:hover { color: var(--color-text); }+ .rk-seg-btn.is-active { background: var(--surface-3); color: var(--color-text-bright); }+ .rk-seg-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }++ .rk-board { border: 1px solid var(--color-border); border-radius: var(--radius-lg); background: var(--surface-1); overflow: hidden; }+ .rk-head, .rk-row {+ display: grid;+ grid-template-columns: 56px 1fr 140px;+ align-items: center; gap: var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ }+ .rk-head { background: var(--surface-2); border-bottom: 1px solid var(--color-border); font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); }+ .rk-col-num { text-align: right; }+ .rk-row { border-bottom: 1px solid var(--color-border); transition: background var(--duration-fast) var(--ease-standard); }+ .rk-row:last-child { border-bottom: 0; }+ .rk-row:hover { background: var(--surface-2); }+ .rk-rank { font: var(--weight-bold) var(--text-md)/1 var(--font-mono); color: var(--color-text-dim); }+ .rk-rank.is-top { color: var(--color-text-bright); }+ .rk-medal { font-size: 16px; }+ .rk-creator { display: flex; align-items: center; gap: var(--space-sm); min-width: 0; }+ .rk-avatar { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; background: var(--surface-3); flex: none; border: 1px solid var(--color-border); }+ .rk-avatar-fallback { display: flex; align-items: center; justify-content: center; font: var(--weight-semibold) var(--text-sm)/1 var(--font-body); color: var(--color-text-dim); }+ .rk-handle { font: var(--weight-medium) var(--text-md)/1.2 var(--font-body); color: var(--color-text); text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ a.rk-handle:hover { color: var(--color-text-bright); text-decoration: underline; }+ .rk-value { font: var(--weight-semibold) var(--text-md)/1 var(--font-mono); color: var(--color-text-bright); text-align: right; }++ .rk-me { position: sticky; bottom: 0; z-index: 5; margin-top: var(--space-md); border: 1px solid color-mix(in srgb, var(--accent) 28%, var(--color-border)); border-radius: var(--radius-lg); background: var(--surface-3); backdrop-filter: blur(var(--blur-md)); -webkit-backdrop-filter: blur(var(--blur-md)); box-shadow: var(--shadow-2); }+ .rk-me .rk-row { border-bottom: 0; }+ .rk-me-tag { font: var(--weight-semibold) var(--text-2xs)/1 var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--color-text-faint); padding: var(--space-xs) var(--space-md) 0; }++ .rk-loadmore { display: block; margin: var(--space-md) auto 0; appearance: none; cursor: pointer; padding: var(--space-sm) var(--space-lg); border-radius: var(--radius-md); border: 1px solid var(--color-border); background: var(--surface-1); color: var(--color-text); font: var(--weight-medium) var(--text-md)/1 var(--font-body); transition: background var(--duration-fast) var(--ease-standard); }+ .rk-loadmore:hover { background: var(--surface-2); }+ .rk-loadmore:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+ .rk-loadmore[disabled] { opacity: var(--disabled-opacity); cursor: var(--disabled-cursor); }++ .rk-state { padding: var(--space-2xl) var(--space-md); text-align: center; }+ .rk-state-title { font: var(--weight-semibold) var(--text-lg)/1.2 var(--font-display); color: var(--color-text-bright); margin: 0 0 var(--space-xs); }+ .rk-state-msg { font: var(--weight-regular) var(--text-md)/var(--leading-normal) var(--font-body); color: var(--color-text-dim); margin: 0 auto var(--space-md); max-width: 46ch; }+ .rk-state .rk-cta { display: inline-flex; align-items: center; gap: var(--space-xs); padding: var(--space-sm) var(--space-lg); border-radius: var(--radius-md); background: var(--accent); color: #0a0a0a; font: var(--weight-semibold) var(--text-md)/1 var(--font-body); text-decoration: none; transition: opacity var(--duration-fast) var(--ease-standard); }+ .rk-state .rk-cta:hover { opacity: 0.85; }++ .rk-skel-row { display: grid; grid-template-columns: 56px 1fr 140px; gap: var(--space-sm); align-items: center; padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--color-border); }+ .rk-skel { height: 14px; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: rk-shimmer 1.4s ease infinite; }+ .rk-skel.circle { width: 34px; height: 34px; border-radius: 50%; }+ @keyframes rk-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+ @media (prefers-reduced-motion: reduce) { .rk-skel, .rk-live-dot { animation: none; } }++ .rk-footer-links { display: flex; flex-wrap: wrap; gap: var(--space-sm); margin-top: var(--space-lg); }+ .rk-footer-links a { font: var(--weight-medium) var(--text-sm)/1 var(--font-body); color: var(--color-text-dim); text-decoration: none; padding: var(--space-xs) var(--space-md); border: 1px solid var(--color-border); border-radius: var(--radius-pill); transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard); }+ .rk-footer-links a:hover { color: var(--color-text-bright); border-color: var(--color-text-dim); }++ @media (max-width: 640px) {+ .rk-head, .rk-row, .rk-skel-row { grid-template-columns: 40px 1fr 96px; }+ .rk-title { font-size: var(--text-xl); }+ }+ </style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Rankings — three.ws">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Rankings","description":"The cross-surface three.ws leaderboard — creations, remixes, launches, followers, and walk distance, ranked.","url":"https://three.ws/rankings","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>+</head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="rk-shell" aria-labelledby="rk-title">+ <section class="rk-hero">+ <p class="rk-kicker"><span class="rk-live-dot" aria-hidden="true"></span> Cross-surface · updates live</p>+ <h1 id="rk-title" class="rk-title">Rankings</h1>+ <p class="rk-sub">One board across every surface — creations forged, remixes earned, coins launched, creators followed, and distance walked. Show up daily to build a streak and earn badges.</p>+ </section>++ <div class="rk-streak-card" id="rk-streak-card">+ <div class="rk-streak-flame" aria-hidden="true">🔥</div>+ <div class="rk-streak-body">+ <div class="rk-streak-num" id="rk-streak-num">0-day streak</div>+ <div class="rk-streak-label" id="rk-streak-label">Come back tomorrow to keep it alive</div>+ <div class="rk-streak-badges" id="rk-streak-badges"></div>+ </div>+ </div>++ <section class="rk-controls" aria-label="Leaderboard metric">+ <div class="rk-seg" role="tablist" aria-label="Rank by" id="rk-metric">+ <button class="rk-seg-btn is-active" data-metric="creations" role="tab" aria-selected="true">Creations</button>+ <button class="rk-seg-btn" data-metric="remixes_received" role="tab" aria-selected="false">Remixes</button>+ <button class="rk-seg-btn" data-metric="launches" role="tab" aria-selected="false">Launches</button>+ <button class="rk-seg-btn" data-metric="followers" role="tab" aria-selected="false">Followers</button>+ <button class="rk-seg-btn" data-metric="walk_distance" role="tab" aria-selected="false">Walk Distance</button>+ </div>+ </section>++ <section class="rk-board" aria-label="Ranked creators" aria-busy="true">+ <div class="rk-head" role="row" aria-hidden="true">+ <span>#</span>+ <span>Creator</span>+ <span class="rk-col-num" id="rk-metric-label">Creations</span>+ </div>+ <div id="rk-rows" aria-live="polite"></div>+ </section>++ <button type="button" id="rk-loadmore" class="rk-loadmore" hidden>Show more</button>++ <div id="rk-me-wrap" class="rk-me" hidden>+ <div class="rk-me-tag">Your rank</div>+ <div id="rk-me-row"></div>+ </div>++ <nav class="rk-footer-links" aria-label="Other leaderboards">+ <a href="/leaderboard">Trader Leaderboard →</a>+ <a href="/walk-leaderboard">Walk Leaderboard →</a>+ <a href="/creations">Remix Bazaar →</a>+ </nav>+ </main>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ const rowsEl = document.getElementById('rk-rows');+ const boardEl = rowsEl.closest('.rk-board');+ const metricLabelEl = document.getElementById('rk-metric-label');+ const loadMoreEl = document.getElementById('rk-loadmore');+ const meWrap = document.getElementById('rk-me-wrap');+ const meRow = document.getElementById('rk-me-row');+ const metricSeg = document.getElementById('rk-metric');+ const streakCard = document.getElementById('rk-streak-card');+ const streakNum = document.getElementById('rk-streak-num');+ const streakLabel = document.getElementById('rk-streak-label');+ const streakBadges = document.getElementById('rk-streak-badges');++ const METRIC_HEAD = {+ creations: 'Creations',+ remixes_received: 'Remixes',+ launches: 'Launches',+ followers: 'Followers',+ walk_distance: 'Distance',+ };+ const EMPTY_COPY = {+ creations: { title: 'No creations ranked yet', msg: 'Forge a 3D model or build a world while signed in — it’ll show up here.', cta: { href: '/forge', label: 'Start creating →' } },+ remixes_received: { title: 'No remixes yet', msg: 'Publish one of your creations to the remix bazaar and wait for another creator to build on it.', cta: { href: '/creations', label: 'Open the bazaar →' } },+ launches: { title: 'No launches ranked yet', msg: 'Launch a coin from one of your agents to show up here.', cta: { href: '/create-agent', label: 'Launch an agent →' } },+ followers: { title: 'No one ranked yet', msg: 'Grow your following by sharing your profile and creations.', cta: { href: '/feed', label: 'Open your feed →' } },+ walk_distance: { title: 'No walkers ranked yet', msg: 'Sign in and take your avatar for a walk — distance while signed in counts here.', cta: { href: '/walk', label: 'Start walking →' } },+ };+ const PAGE = 50;+ let state = { metric: 'creations', offset: 0, total: 0, loading: false };++ const esc = (s) => String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c]));++ function fmtValue(metric, v) {+ if (metric === 'walk_distance') return v >= 1000 ? (v / 1000).toFixed(2) + ' km' : Math.round(v) + ' m';+ return String(Math.round(v));+ }++ function medal(rank) {+ if (rank === 1) return '<span class="rk-medal" aria-hidden="true">🥇</span>';+ if (rank === 2) return '<span class="rk-medal" aria-hidden="true">🥈</span>';+ if (rank === 3) return '<span class="rk-medal" aria-hidden="true">🥉</span>';+ return '';+ }++ function avatarCell(r) {+ if (r.avatar) return `<img class="rk-avatar" src="${esc(r.avatar)}" alt="" loading="lazy" />`;+ const ch = esc((r.handle || '?').replace(/^@/, '')[0] || '?').toUpperCase();+ return `<span class="rk-avatar rk-avatar-fallback" aria-hidden="true">${ch}</span>`;+ }++ function rowHtml(r, metric, isMe) {+ const handle = r.profileUrl+ ? `<a class="rk-handle" href="${esc(r.profileUrl)}">${esc(r.handle)}</a>`+ : `<span class="rk-handle">${esc(r.handle)}${isMe ? ' (you)' : ''}</span>`;+ const rankCls = r.rank && r.rank <= 3 ? 'rk-rank is-top' : 'rk-rank';+ const rankText = r.rank == null ? '—' : (medal(r.rank) || '#' + r.rank);+ return `+ <div class="rk-row" role="row">+ <span class="${rankCls}">${rankText}</span>+ <span class="rk-creator">${avatarCell(r)} ${handle}</span>+ <span class="rk-value">${fmtValue(metric, r.value)}</span>+ </div>`;+ }++ function skeleton() {+ let h = '';+ for (let i = 0; i < 8; i++) {+ h += `<div class="rk-skel-row"><span class="rk-skel" style="width:24px"></span><span style="display:flex;align-items:center;gap:10px"><span class="rk-skel circle"></span><span class="rk-skel" style="width:120px"></span></span><span class="rk-skel" style="width:70px;justify-self:end"></span></div>`;+ }+ rowsEl.innerHTML = h;+ }++ function showState(copy) {+ rowsEl.innerHTML = `<div class="rk-state"><p class="rk-state-title">${esc(copy.title)}</p><p class="rk-state-msg">${esc(copy.msg)}</p>${copy.cta ? `<a class="rk-cta" href="${esc(copy.cta.href)}">${esc(copy.cta.label)}</a>` : ''}</div>`;+ }++ function renderMe(me, metric) {+ if (!me) { meWrap.hidden = true; return; }+ meWrap.hidden = false;+ meRow.innerHTML = rowHtml(me, metric, true);+ }++ async function load({ reset = true } = {}) {+ if (state.loading) return;+ state.loading = true;+ if (reset) { state.offset = 0; skeleton(); meWrap.hidden = true; }+ boardEl.setAttribute('aria-busy', 'true');+ loadMoreEl.disabled = true;+ const params = new URLSearchParams({ metric: state.metric, limit: String(PAGE), offset: String(state.offset) });+ try {+ const res = await fetch('/api/leaderboard/unified?' + params.toString(), { credentials: 'include' });+ if (!res.ok) throw new Error('HTTP ' + res.status);+ const data = await res.json();+ state.total = data.total || 0;+ const metric = data.metric || state.metric;+ metricLabelEl.textContent = METRIC_HEAD[metric] || 'Value';++ if (reset && (!data.rows || !data.rows.length)) {+ showState(EMPTY_COPY[metric] || { title: 'No one ranked yet', msg: 'Be the first.' });+ renderMe(data.me && data.me.value > 0 ? data.me : null, metric);+ return;+ }++ const html = (data.rows || []).map((r) => rowHtml(r, metric, data.me && r.userId === data.me.userId)).join('');+ if (reset) rowsEl.innerHTML = html; else rowsEl.insertAdjacentHTML('beforeend', html);++ state.offset += (data.rows || []).length;+ loadMoreEl.hidden = !data.hasMore;+ renderMe(data.me, metric);+ } catch (err) {+ if (reset) {+ const wrap = document.createElement('div');+ wrap.className = 'rk-state';+ wrap.innerHTML = `<p class="rk-state-title">Couldn't load the leaderboard</p><p class="rk-state-msg">${esc(err.message || 'Something went wrong.')}</p>`;+ const btn = document.createElement('button');+ btn.className = 'rk-cta';+ btn.type = 'button';+ btn.textContent = 'Retry';+ btn.addEventListener('click', () => load({ reset: true }));+ wrap.appendChild(btn);+ rowsEl.replaceChildren(wrap);+ }+ } finally {+ state.loading = false;+ boardEl.setAttribute('aria-busy', 'false');+ loadMoreEl.disabled = false;+ }+ }++ function bindSeg(seg, key, onChange) {+ seg.addEventListener('click', (e) => {+ const btn = e.target.closest('.rk-seg-btn');+ if (!btn || btn.classList.contains('is-active')) return;+ seg.querySelectorAll('.rk-seg-btn').forEach((b) => { b.classList.remove('is-active'); b.setAttribute('aria-selected', 'false'); });+ btn.classList.add('is-active');+ btn.setAttribute('aria-selected', 'true');+ state[key] = btn.dataset[key];+ onChange();+ });+ seg.addEventListener('keydown', (e) => {+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;+ const btns = [...seg.querySelectorAll('.rk-seg-btn')];+ const i = btns.findIndex((b) => b.classList.contains('is-active'));+ const next = btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length];+ next.focus(); next.click();+ e.preventDefault();+ });+ }++ bindSeg(metricSeg, 'metric', () => load({ reset: true }));+ loadMoreEl.addEventListener('click', () => load({ reset: false }));++ load({ reset: true });++ // Streak card — only for a signed-in viewer with a resolvable username.+ // Reuses GET /api/users/:username (already returns streak + badges) so+ // this page adds zero new auth surface: it just needs to know who's+ // signed in, which /api/auth/me already answers (same call profile.html+ // uses to resolve the viewer).+ (async () => {+ try {+ const meRes = await fetch('/api/auth/me', { credentials: 'include' });+ if (!meRes.ok) return;+ const me = await meRes.json();+ const username = me?.user?.username;+ if (!username) return;+ const profRes = await fetch(`/api/users/${encodeURIComponent(username)}`);+ if (!profRes.ok) return;+ const prof = await profRes.json();+ const streak = prof?.streak;+ if (!streak) return;+ streakCard.classList.add('is-visible');+ streakNum.textContent = `${streak.currentStreak || 0}-day streak`;+ streakLabel.textContent = streak.currentStreak > 0+ ? 'Come back tomorrow to keep it alive'+ : 'Create, launch, or walk today to start one';+ const badges = (prof.badges || []).slice(0, 4);+ streakBadges.innerHTML = badges+ .map((b) => `<span class="rk-badge-chip" title="${esc(b.description || '')}">${esc(b.icon || '★')} ${esc(b.label || b.code)}</span>`)+ .join('');+ } catch {+ /* streak card is a bonus — never block the board */+ }+ })();+ </script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex ec1e0fd0f..d47738f30 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-12T16:56:26.625Z",+ "generated_at": "2026-07-12T16:59:04.940Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-07-12",+ "type": "launch",+ "title": "Rankings",+ "summary": "The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.",+ "link": "/rankings",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-12","type": "launch",@@ -56,6 +66,16 @@"feature"]},+ {+ "date": "2026-07-12",+ "type": "update",+ "title": "A cross-surface leaderboard, streaks, and badges",+ "summary": "A new Rankings board at /rankings ranks creators across every surface at once — creations forged, remixes received, coins launched, followers, and distance walked while signed in — with your own rank pinned even if you're off the visible page. Showing up daily (a login, a finished creation, or a walk session) now builds a real streak, shown on your profile and on the Rankings page. Four badges are genuinely earnable and persist once unlocked: First Creation, Remixed, 7-Day Streak, and a daily-refreshed Top 10 placement per metric.",+ "link": "/rankings",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-12","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7e98812a4..d0c947635 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>launch</category><description>How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.</description></item>+ <item>+ <title>Rankings</title>+ <link>https://three.ws/rankings</link>+ <guid isPermaLink="false">2026-07-12:Rankings</guid>+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.</description>+ </item><item><title>Robinhood Chain</title><link>https://three.ws/markets/robinhood</link>@@ -46,6 +54,14 @@<category>feature</category><description>/feed used to only show activity from people you follow — it now defaults to a live, platform-wide feed of every new avatar, agent, forged 3D model, saved world, coin launch, and follow, with a toggle to switch to just the people you follow. Scroll for more and it loads the next page automatically; a "New activity" pill appears when something fresh lands so the list never jumps under you mid-read. /community, previously a static grid of links, now leads with that same live activity feed alongside the existing links to X, GitHub, docs, and tutorials.</description></item>+ <item>+ <title>A cross-surface leaderboard, streaks, and badges</title>+ <link>https://three.ws/rankings</link>+ <guid isPermaLink="false">2026-07-12:A cross-surface leaderboard, streaks, and badges</guid>+ <pubDate>Sun, 12 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new Rankings board at /rankings ranks creators across every surface at once — creations forged, remixes received, coins launched, followers, and distance walked while signed in — with your own rank pinned even if you're off the visible page. Showing up daily (a login, a finished creation, or a walk session) now builds a real streak, shown on your profile and on the Rankings page. Four badges are genuinely earnable and persist once unlocked: First Creation, Remixed, 7-Day Streak, and a daily-refreshed Top 10 placement per metric.</description>+ </item><item><title>Agent discovery fixed: six paid endpoints were invisible to x402 scanners</title><link>https://three.ws/openapi.json</link>diff --git a/public/features.json b/public/features.jsonindex 48c1039ab..838c86140 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-12T16:56:26.612Z",+ "generated_at": "2026-07-12T16:59:04.926Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -879,6 +879,16 @@"tags": [],"showcase": false},+ {+ "path": "/rankings",+ "title": "Rankings",+ "description": "The cross-surface three.ws leaderboard — creators ranked by real creations, remixes received, coin launches, followers, and distance walked. Track your streak and earn badges for showing up.",+ "added": "2026-07-12",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/walk-leaderboard","title": "Walk Leaderboard",diff --git a/tests/streaks.test.js b/tests/streaks.test.jsnew file mode 100644index 000000000..c09283c6c--- /dev/null+++ b/tests/streaks.test.js@@ -0,0 +1,141 @@+/**+ * api/_lib/streaks.js — cross-surface streak + badge logic (prompt 06 of the+ * user-value pack).+ *+ * The upsert SQL that rolls a streak forward, the read-side decay check that+ * shows a streak as broken before the next write happens, and badge idempotency+ * are all exercised here against a mocked `sql` — matching this repo's+ * forge-store test convention (tests/forge-store-materialize.test.js).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++let lastQuery = '';+const sqlMock = vi.fn(async (strings, ...values) => {+ lastQuery = strings.join(' ');+ return sqlMock.__nextResult ?? [];+});++vi.mock('../api/_lib/db.js', () => ({+ sql: (...args) => sqlMock(...args),+ isDbUnavailableError: () => false,+}));++const { recordDailyActivity, getStreak, unlockBadge, listBadges, maybeAwardFirstCreation, BADGES, badgeMeta } =+ await import('../api/_lib/streaks.js');++beforeEach(() => {+ sqlMock.mockClear();+ sqlMock.__nextResult = [];+});++describe('recordDailyActivity', () => {+ it('returns null without touching the db when userId is missing', async () => {+ const out = await recordDailyActivity(null);+ expect(out).toBeNull();+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('upserts into user_streaks and returns the rolled-forward streak', async () => {+ sqlMock.__nextResult = [{ current_streak: 3, longest_streak: 5, last_active_day: '2026-07-12' }];+ const out = await recordDailyActivity('user-1');+ expect(lastQuery).toContain('insert into user_streaks');+ expect(lastQuery).toContain('on conflict');+ expect(out).toEqual({ currentStreak: 3, longestStreak: 5, lastActiveDay: '2026-07-12' });+ });++ it('unlocks the streak_7 badge once current_streak crosses 7', async () => {+ sqlMock.__nextResult = [{ current_streak: 7, longest_streak: 7, last_active_day: '2026-07-12' }];+ await recordDailyActivity('user-1');+ // recordDailyActivity → unlockBadge → a second sql() call for the insert.+ const calls = sqlMock.mock.calls.map((c) => c[0].join(' '));+ expect(calls.some((q) => q.includes('insert into user_badges'))).toBe(true);+ });++ it('does not unlock streak_7 below the threshold', async () => {+ sqlMock.__nextResult = [{ current_streak: 6, longest_streak: 6, last_active_day: '2026-07-12' }];+ await recordDailyActivity('user-1');+ const calls = sqlMock.mock.calls.map((c) => c[0].join(' '));+ expect(calls.some((q) => q.includes('insert into user_badges'))).toBe(false);+ });++ it('fails soft (returns null) on a db error rather than throwing', async () => {+ sqlMock.mockImplementationOnce(async () => {+ throw new Error('connection reset');+ });+ const out = await recordDailyActivity('user-1');+ expect(out).toBeNull();+ });+});++describe('getStreak', () => {+ it('returns zeros for a user with no streak row', async () => {+ sqlMock.__nextResult = [];+ const out = await getStreak('user-1');+ expect(out).toEqual({ currentStreak: 0, longestStreak: 0, lastActiveDay: null });+ });++ it('reports the live streak when last_active_day is today or yesterday', async () => {+ const today = new Date().toISOString().slice(0, 10);+ sqlMock.__nextResult = [{ current_streak: 4, longest_streak: 9, last_active_day: today }];+ const out = await getStreak('user-1');+ expect(out.currentStreak).toBe(4);+ });++ it('shows a streak as broken (0) once 2+ UTC days have passed with no activity', async () => {+ const threeDaysAgo = new Date(Date.now() - 3 * 86400000).toISOString().slice(0, 10);+ sqlMock.__nextResult = [{ current_streak: 12, longest_streak: 12, last_active_day: threeDaysAgo }];+ const out = await getStreak('user-1');+ expect(out.currentStreak).toBe(0);+ expect(out.longestStreak).toBe(12); // longest is a durable record, never reset+ });+});++describe('unlockBadge / listBadges', () => {+ it('unlockBadge is a no-op without a userId or code', async () => {+ expect(await unlockBadge(null, 'x')).toBe(false);+ expect(await unlockBadge('user-1', null)).toBe(false);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('returns true only when the insert actually landed a new row (ON CONFLICT DO NOTHING)', async () => {+ sqlMock.__nextResult = [{ id: '1' }];+ expect(await unlockBadge('user-1', BADGES.STREAK_7)).toBe(true);+ sqlMock.__nextResult = [];+ expect(await unlockBadge('user-1', BADGES.STREAK_7)).toBe(false);+ });++ it('listBadges shapes rows with display metadata', async () => {+ sqlMock.__nextResult = [{ code: 'first_creation', context: null, unlocked_at: '2026-07-12T00:00:00Z' }];+ const out = await listBadges('user-1');+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({ code: 'first_creation', label: 'First Creation' });+ });+});++describe('badgeMeta', () => {+ it('resolves a dynamic top10_<metric> badge to a labeled description', () => {+ const meta = badgeMeta('top10_walk_distance');+ expect(meta.label).toContain('Walk Distance');+ expect(meta.icon).toBe('🏆');+ });++ it('falls back to the raw code for an unknown badge', () => {+ expect(badgeMeta('mystery_code').label).toBe('mystery_code');+ });+});++describe('maybeAwardFirstCreation', () => {+ it('does not award the badge when the user has zero creations', async () => {+ sqlMock.__nextResult = [{ total: 0 }];+ expect(await maybeAwardFirstCreation('user-1')).toBe(false);+ });++ it('awards the badge once total creations reaches 1', async () => {+ sqlMock.mockImplementation(async (strings) => {+ const text = strings.join(' ');+ if (text.includes('select')) return [{ total: 1 }];+ return [{ id: '1' }]; // the badge insert+ });+ expect(await maybeAwardFirstCreation('user-1')).toBe(true);+ });+});diff --git a/vercel.json b/vercel.jsonindex 63c937ce3..fdea51943 100644--- a/vercel.json+++ b/vercel.json@@ -5313,6 +5313,10 @@{"path": "/api/cron/news-archive-append","schedule": "17 * * * *"+ },+ {+ "path": "/api/cron/leaderboard-rollup",+ "schedule": "0 9 * * *"}]}