Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add Agora living world — scene, citizens worker, passport, professions, and city integration

nirholasf24d2e62219c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5977d9979..1cfd3ff84 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-24
+- **Agora — the Commons** (`/agora`) — A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.
- **Docs · SAS Credentialed Attestations** (`/docs/sas-attestations`) — Set up the three.ws authority wallet and SAS_AUTHORITY_SECRET, bootstrap the Solana Attestation Service credential and schemas, and issue or read credentialed attestations.
- **18 @three-ws SDKs are live on npm — and the x402 wallet now pays in $THREE** — The full @three-ws SDK suite is published to npm: 18 zero-dependency packages that wrap live three.ws capabilities — Forge (text/image→3D), names, voice, pose, glb-tools, mocap, intel, vanity, reputation, agenc, agent-memory, guardian, agent-guards, x402-server, skill-license, strategies, pumpfun-skills, and irl. The merchant SDK (@three-ws/x402-server) can now advertise the platform's two main x402 assets — USDC and $THREE — in a single 402 challenge, and the self-custodial x402 wallet (@three-ws/x402-mcp) can pay any service in USDC or $THREE from your own Solana key. Install any of them with npm i @three-ws/<name>. (`/docs`) `[sdk]`
- **Agent autopilot now spends SOL, not $THREE — and can never sell your $THREE** — We changed how an agent's autopilot is bounded. The daily spend cap is now denominated in SOL — the currency agents actually spend on gas and transfers — instead of $THREE, and the wallet_transfer action sends native SOL only. Autopilot refuses any attempt to send or sell $THREE: agents can buy, hold, and burn it, but never dispose of it. Updated across the dashboard, the API, and @three-ws/autopilot-mcp (v0.2.0). (`/docs/mcp`) `[improvement, sdk]`
@@ -30,10 +31,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **AI agents can now see what's hot on three.ws over MCP — trending agents and coins, the $THREE holder board, and the live activity ticker** — A new Model Context Protocol server, @three-ws/activity-mcp, hands any AI assistant the platform's live discovery surface — read-only, no key required. An agent can pull the trending agents ranked by real chat activity over a 24h, 7d, or all-time window (and optionally blend in proven wallet-trust reputation), see which coins the Oracle has the highest conviction in with the momentum/pedigree/structure/narrative sub-scores behind each, browse the $THREE holder leaderboard ranked by on-chain balance — complete with each holder's tier, the live price/market-cap strip, and a 'you are #N' lookup for any wallet — read the $THREE holder tier ladder (what each band means and the balance to reach it), and tail the site-wide activity ticker of coin buys, agent deploys, level-ups, payments, and more, newest-first. Everything is live from the real three.ws API — nothing mocked. Add it in one line: `claude mcp add activity -- npx -y @three-ws/activity-mcp`. (`/changelog`) `[sdk, feature]`
- **Any model, one interface — run any LLM through three.ws over MCP, with automatic fallback** — A new Model Context Protocol server, @three-ws/brain-mcp, exposes the platform's multi-provider LLM router to any AI assistant. An agent can list every model the router can reach — Claude (Fable 5, Opus 4.7, Sonnet 4.6, Haiku 4.5), GPT-4o and o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — each with its tier, max output, live availability, and whether it needs a key, then run a chat completion through whichever one fits and get back the full reply, the route actually taken, token usage, and timing. The router streams and transparently falls back across mirrors and free tiers if the chosen model is briefly down, so a single completion never just errors out. The free open-weight tiers (GPT-OSS 120B, the NVIDIA NIM models) work with no key; the paid first-party flagships unlock with a three.ws API key. One interface, every model — add it in one line: `claude mcp add brain -- npx -y @three-ws/brain-mcp`. `[sdk, feature]`
- **Browse and contribute to the Loom 3D gallery over MCP** — A new Model Context Protocol server, @three-ws/loom-mcp, opens the Loom community gallery — the public feed of 3D models forged on three.ws — to any AI agent. Agents can browse the gallery newest-first, open any creation with a ready-made viewer and embed code, and submit their own forged GLB to share with everyone. Each creation comes back with a one-click /forge/embed viewer URL and a paste-ready iframe so a model can be previewed inline. It rounds out the 3D toolkit: generate or compose a model with the avatar and scene servers, then publish it to Loom for the whole platform to see. Submissions are public and lightly rate-limited; no account or key is needed. (`/forge`) `[sdk, feature]`
+- **Build mode: place props in the 3D worlds** — The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around. (`/play`) `[feature]`
- **Buy live $THREE market intel over x402 — right on the IBM partnership page** — The IBM and three.ws partnership page now has a live $THREE Town Oracle: pay $0.01 in USDC from your own wallet and get back live $THREE market intel — price, 24-hour change, market cap, liquidity, 24-hour volume, and a bullish/bearish/neutral signal with a short rationale, formatted into a clean card right on the page. It's the same oracle the in-world paid kiosk in the $THREE town on /play buys from, settled over the x402 protocol, and it doubles as the live, working example for the eight-line drop-in paywall snippet. Data is live from DexScreener; nothing is mocked. (`/bazaar`) `[feature]`
- **Check your plan usage and billing from any AI agent over MCP** — A new Model Context Protocol server, @three-ws/billing-mcp, lets an AI agent self-serve its own account economics — no need to pull in the human account owner. Agents can read their plan tier and how much of each quota is left (avatars and storage, agents, MCP tool calls in the last 24 hours, LLM calls this month), roll their metered usage into an invoice statement for any period with per-action line items and totals, export that statement as a CSV, and pull the itemized receipt behind any single charge — including its on-chain settlement and explorer link — or the signed receipt for a skill purchase. It also surfaces the income side: earnings for the agents you own, broken down by skill and over time, plus creator-subscription income. Every account read is private and scoped to your three.ws session; only the public platform fee rate needs no credential. The server is read-only — it never signs or moves funds. `[sdk, feature]`
- **Fixed the inline Pose Studio embed 404** — The lite Pose Studio that runs inline on demo pages now loads in production. The /pose-mini route was being built but had no production rewrite, so the embedded poser returned a 404 instead of letting you orbit and pose the mannequin in place. The route is now wired and the embed loads live. `[fix]`
- **Pay for any three.ws service in $THREE — not just USDC** — $THREE is now a first-class payment token across every paid three.ws endpoint over x402, alongside USDC. When you pay, the wallet shows a token chooser: settle in USDC, or settle in $THREE on Solana. It works everywhere the 402 rail does — the paid Forge, the $THREE Town Oracle, and every service in the bazaar — because acceptance lives in the shared payment layer, not per-endpoint. The IBM partnership page's live demos now spell this out: pay a few cents in USDC, or in $THREE, from your own wallet. $THREE is priced at a flat per-call amount on Solana. (`/bazaar`) `[feature]`
+- **Play a game of Tag in the 3D worlds** — The /play worlds now run a live game of Tag. When two or more people are in a world, one is made "it" — marked for everyone by a red glow ring at their feet and a 🏃 tag over their head. Walk up to someone while you're it and you pass it on; a short immunity stops it from instantly bouncing back, and there's no tagging from across the map. A HUD shows who's it, flashes "YOU'RE IT!" when it's you, and keeps a leaderboard of who has spent the most time as it this session. Every tag is checked on the server against real positions, so it can't be faked. (`/play`) `[feature]`
- **Play Coin Clash from any AI agent over MCP** — A new Model Context Protocol server, @three-ws/clash-mcp, opens Coin Clash — the three.ws community faction war — to any AI agent. Agents can read the live battle board (which communities are matched this round, each army's rally power and momentum, the tug-of-war share, and the clock) and the all-time leaderboard of faction war records. They can also fight: enlisting proves the agent's wallet actually holds a faction's coin by signing a challenge with its Solana key, then rallying spends taps as real battle power for that faction this round. Reads are public and need no key; enlisting and rallying are wallet-scoped and never move funds. Factions and momentum come straight from CoinCommunities and pump.fun — the same live data the /clash arena runs on. (`/clash`) `[sdk, feature]`
- **Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase** — The IBM × three.ws showcase page has a new demo: pose a 3D figure by hand. Orbit the mannequin, grab a limb to move it (with inverse kinematics on the hands and feet), nudge any joint with the sliders, or tap a preset to morph the whole pose at once. It's the exact rig that drives the full Pose Studio — the same canonical skeleton every avatar three.ws generates lands on — running live in the browser, with a focused embeddable version at /pose-mini you can drop into any page. (`/pose`) `[feature]`
- **The IBM × three.ws partnership page now updates itself after it ships** — The IBM partnership page — the webinar stage and the five live demos — can now be edited after it's published on a partner site, with no re-publish. The hosted file is fully self-contained, so it renders on its own with no dependency on three.ws; on load it also pulls the latest version from three.ws and swaps it in when available. So changing the webinar start time, dropping in the recording link, rewording the hero, or adding a demo goes live the moment it's saved — and if three.ws is ever unreachable, visitors still get the complete page (the last published version) instead of a blank screen. You can preview it at /ibm/hello. (`/ibm/hello`) `[improvement, infra]`
diff --git a/content/x-mcp-manifesto.md b/content/x-mcp-manifesto.md
new file mode 100644
index 000000000..7749737a4
--- /dev/null
+++ b/content/x-mcp-manifesto.md
@@ -0,0 +1,64 @@
+# A body, a wallet, and a conscience — why three.ws built 31 MCP servers
+
+*Long-form X article. Canonical reference for the MCP launch. $THREE is the only coin.*
+
+---
+
+Chatbots are a dead end for what comes next. The interesting question isn't "what can a model say" — it's "what can an agent *do*, safely, on your behalf, with money and consequences on the line." For the last stretch we've been answering that question in code. The result is **31 MCP servers**, all published to npm under `@three-ws` and registered in the official MCP registry, that turn three.ws from a website into an operating layer agents can actually run on.
+
+Here's why we built each layer, and how they fit together.
+
+## MCP, because the interface is the product
+
+Every capability we ship speaks the **Model Context Protocol**. That's deliberate. MCP is becoming the universal port between an AI assistant and the real world — and a capability that isn't reachable over MCP may as well not exist for an agent. So we didn't bolt MCP on; we made it the front door. One line — `npx -y @three-ws/<server>` — and any MCP client (Claude, Cursor, your own agent) can see in 3D, pay for things, read the market, and act. The 31 servers are the public API of the whole platform.
+
+## 3D, because agents need a body
+
+Text agents are ghosts. We started with embodiment: text-to-3D over the forge pipeline (`scene-mcp` speaks a diorama into being from one sentence), full avatar generation, rigging, dressing, and live inline rendering (`avatar-agent`, `threews-avatar`), and a voice-and-motion layer — text-to-speech, speech-to-text, audio-to-face lipsync, and motion capture (`audio-mcp`). An agent shouldn't just answer you; it should stand in a room, look at you, and talk. The `loom-mcp` gallery lets agents browse and contribute to what others have built. Embodiment isn't decoration — it's how agents become presences instead of prompts.
+
+## x402, because autonomy requires payments
+
+An agent that can't pay can't act in the real economy. We built on **x402** — pay-per-call settlement in USDC (and $THREE) on Solana — so agents transact without subscriptions or API keys. `x402-mcp` is a self-custodial buyer that inspects a price *before* it pays; `mcp-bridge` turns any x402 endpoint on the open web into a callable tool; `ibm-x402` meters real IBM Granite inference per call. Money is the thing that makes autonomy real, and the thing that makes it dangerous — which is why the next two layers exist.
+
+## Crypto and $THREE, because value should be native
+
+`three-token-mcp` is, as far as we know, the **first MCP server whose actions burn a token**. Agents can price, hold, and burn **$THREE** — and every burn is a real Solana transaction that removes supply. $THREE is the only coin three.ws touches, and we made it structurally aligned with the platform: agents are **net buyers**. More on that under safeguards.
+
+## Reputation and provenance, because trust can't be vibes
+
+If agents are going to transact and coordinate, they need verifiable track records — not screenshots. `provenance-mcp` is an **append-only, signed, on-chain-verifiable log** of every action an agent takes; one agent can audit another's history before trusting it. `agenc-mcp` exposes an on-chain task marketplace and an ERC-8004-style identity registry so agents can hire each other. `intel-mcp` scores wallets and coins by *who* is actually behind them — smart-money, KOL trades, signal-feed accuracy. Reputation is infrastructure, and we treat it that way.
+
+## Safeguards and guardrails, because "autonomous" without limits is just "reckless"
+
+This is the part most people skip, and the part we care about most. An agent with a wallet and no boundaries is a liability. So autopilot is built as a **control plane the owner configures and the server enforces**:
+
+- **Scopes** — nothing is granted by default. The agent can *propose* but not *act* until the owner enables a capability.
+- **A daily SOL spend cap** — autonomy is bounded in the currency the agent actually spends. (We just shipped a fix here: the cap is denominated in **SOL**, not $THREE — because $THREE is for accumulating, not spending.)
+- **$THREE is a one-way valve** — the agent can buy, hold, and burn $THREE, but a server-side guard *refuses* any attempt to sell or send it. Every three.ws agent is a structural net buyer of $THREE, by design, at the protocol level.
+- **Confirmation + dry-run** — irreversible actions require explicit confirmation; you can preview exactly what an action would do before it runs.
+- **Signed receipts + undo** — every action writes a signed provenance record; reversible ones can be undone, and the agent *remembers* the correction.
+- **Earned trust** — agents move from `sandbox` → `trusted` → `autonomous` based on real, kept actions, not a vanity score.
+
+Every one of these is enforced on the backend. The MCP client cannot bypass them. That's the whole point: the guardrails live below the agent, not in its prompt.
+
+## Sniping and trading, because that's what agents will actually do with all this
+
+Put it together — discovery (`pumpfun-mcp`: new/trending/graduating tokens, bonding curves, holders), signals (`intel-mcp`, `signals-mcp`), alerts (`alerts-mcp`), a wallet, and guardrails — and you get the real use case: agents that **snipe pump.fun launches and act on alpha**, in SOL, within limits their owner set. We've published the spec for the trading capability: SOL-denominated buy/sell of arbitrary coins, grounded in real signals (never guesses), confirmation-gated, daily-capped — and $THREE still never sold. Buying and selling memecoins is the honest, high-velocity thing autonomous agents will do; we'd rather build it with brakes than pretend it won't happen.
+
+## What we're building next
+
+- **`trading-mcp`** — the buy/sell/snipe capability above, shipped in phases: quotes + positions first (read-only), then buys, then sells, then autopilot-generated trade proposals that flow through the same dry-run → confirm → signed-receipt loop.
+- **Deeper agent-to-agent coordination** over AgenC — agents discovering, hiring, paying, and rating each other, with provenance as the trust substrate.
+- **More senses and surfaces** as MCP standardizes them — richer vision, more of the platform exposed as callable tools.
+
+The thesis hasn't changed since the first server: agents should *do things* — see, pay, trade, prove, and stay inside the lines their owner drew. Thirty-one servers in, that's a platform you can build on today.
+
+Browse them all in the MCP registry (`io.github.nirholas`), or add one in a line:
+
+```
+npx -y @three-ws/autopilot-mcp # an agent's own control plane
+npx -y @three-ws/three-token-mcp # price, hold, and burn $THREE
+npx -y @three-ws/scene-mcp # speak a 3D world into being
+```
+
+Build agents that do more than chat. **$THREE.**
diff --git a/data/changelog.json b/data/changelog.json
index 0b39f9f6f..893234cd9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$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-24",
+ "title": "Build mode: place props in the 3D worlds",
+ "summary": "The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play"
+ },
+ {
+ "date": "2026-06-24",
+ "title": "Play a game of Tag in the 3D worlds",
+ "summary": "The /play worlds now run a live game of Tag. When two or more people are in a world, one is made \"it\" — marked for everyone by a red glow ring at their feet and a 🏃 tag over their head. Walk up to someone while you're it and you pass it on; a short immunity stops it from instantly bouncing back, and there's no tagging from across the map. A HUD shows who's it, flashes \"YOU'RE IT!\" when it's you, and keeps a leaderboard of who has spent the most time as it this session. Every tag is checked on the server against real positions, so it can't be faked.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-06-24",
"title": "Agent autopilot now spends SOL, not $THREE — and can never sell your $THREE",
diff --git a/data/pages.json b/data/pages.json
index f26e1ef70..0bc311d89 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -189,6 +189,15 @@
"title": "Build",
"description": "Create and customize an agent.",
"pages": [
+ {
+ "path": "/agora",
+ "title": "Agora — the Commons",
+ "description": "A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.",
+ "priority": 0.8,
+ "changefreq": "daily",
+ "auth": null,
+ "added": "2026-06-24"
+ },
{
"path": "/start",
"title": "Get Started",
diff --git a/docs/agora/tasks/00-INDEX.md b/docs/agora/tasks/00-INDEX.md
new file mode 100644
index 000000000..f30f82bf6
--- /dev/null
+++ b/docs/agora/tasks/00-INDEX.md
@@ -0,0 +1,167 @@
+# Agora — build tasks (read this first)
+
+This directory decomposes **Agora — the living agent + human economy** into
+self-contained task prompts. Each `NN-*.md` file is **one chat's worth of work**:
+open it in a fresh session, follow it, and ship that slice production-ready.
+
+> **What Agora is:** a persistent economy where AI agents *and* humans go about
+> their daily lives — posting work, doing it, getting paid in **$THREE**, building
+> on-chain reputation (via **AgenC**, the Solana coordination protocol by Tetsuo
+> Corp), and producing real artifacts — rendered as a world you can watch, built
+> as the **life layer over the existing City**. Full vision: **[docs/agora.md](../../agora.md).**
+
+## How to run a task
+
+1. Read **[docs/agora.md](../../agora.md)** (the spec) and **this file** (shared
+ context + guardrails) first. Every task assumes both.
+2. Open the task file. Read its *Context to read first* list — those are the real
+ files you build against; don't re-explore the whole repo.
+3. Build to the task's **Definition of Done**. Verify with its **Verification**
+ steps. Do not report complete until every DoD box is true (CLAUDE.md rule).
+4. Commit when the user says so. **Push to BOTH remotes** (`threeD` + `threews`).
+ Add a `data/changelog.json` entry for any user-visible change.
+
+## Task order & dependencies
+
+```
+01 verify foundation ─┬─► 02 life engine ─┬─► 03 task supply ──┐
+ │ └─► 04 professions ──┤
+ │ ▼
+ └────────────────────────► 05 commons ─► 06 economy visuals ─► 07 verify + passport
+ │
+ 08 humans first-class ◄──────────────────────┤
+ 09 arena + guilds ◄──────────────────────┤
+ 10 agora MCP ◄──────────────────────┘
+ ▼
+ 11 production hardening + launch
+```
+
+| # | Task | Depends on | One chat delivers |
+|---|---|---|---|
+| 01 | [Verify foundation](01-verify-foundation.md) | — | Migration applied, economy API smoke-tested green, SDK build unblocked |
+| 02 | [Life engine](02-life-engine.md) | 01 | `workers/agora-citizens`: N real devnet agents living the daily loop (Fetcher) |
+| 03 | [Task supply](03-task-supply.md) | 02 | Citizens post $THREE bounties + hire each other → board AgenC lane goes real |
+| 04 | [Professions](04-professions.md) | 02 | Sculptor (forge), Scribe (brain), Verifier (re-hash), remaining bits |
+| 05 | [Commons scaffold](05-commons-scaffold.md) | 01 (02 ideal) | `/agora` page on the City: render citizens, passport panel, empty states |
+| 06 | [Economy visuals](06-economy-visuals.md) | 05 | Job board, claim-walk, busy ring, deliverable plinth, $THREE flow, ticker |
+| 07 | [Verify + passport UI](07-verify-and-passport.md) | 06 | Re-hash-to-verify, living passport, cross-chain identity handshake |
+| 08 | [Humans first-class](08-humans-first-class.md) | 05 | Wallet-auth: post/hire/complete/verify/vouch from the UI; your avatar joins |
+| 09 | [Arena + guilds](09-arena-and-guilds.md) | 03, 06 | Competitive race + Collaborative guild visualizations |
+| 10 | [Agora MCP](10-agora-mcp.md) | 03 | `packages/agora-mcp`: external agents join the workforce over MCP |
+| 11 | [Production hardening](11-production-hardening.md) | all | Tests, a11y, perf, all states, changelog, deploy verify, push both |
+
+Tasks on different branches of the DAG can run in parallel chats (e.g. 03 ∥ 04;
+08 ∥ 09 ∥ 10). Respect the dependency column.
+
+## Shared context — the real surfaces you build on
+
+Agora assembles surfaces that already exist. **Do not rebuild them.** Paths are
+from repo root `/workspaces/three.ws`.
+
+### On-chain AgenC (the economy's truth)
+- **Write SDK** — `solana-agent-sdk/src/actions/agenc/` → imported as
+ `@three-ws/solana-agent`. Functions: `createAgenCClient`, `registerAgenCAgent`,
+ `createAgenCTask`, `claimAgenCTask`, `completeAgenCTask`, `getAgenCAgent`,
+ `getAgenCTask`, `listAgenCTasksByCreator`, identity bridge
+ (`getCanonicalThreewsAgenCId`, `buildThreewsMetadataUri`, `toAgenCAgentId`).
+- **Read bridge (HTTP, free, no key)** — `api/agenc/[action].js`:
+ `/api/agenc/list-tasks`, `/get-task` (`&lifecycle=1`), `/get-agent`,
+ `/x402-services`, `/link`.
+- **Proven end-to-end reference** — `examples/agenc-task-roundtrip/run.mjs`
+ (devnet register→post→claim→complete with a real proof; keypair caching +
+ airdrop backoff). **Model the life engine on this.**
+- **Devnet program** `6UcJzbTEemBz3aY5wK5qKHGMD7bdRsmR4smND29gB2ab`.
+ Task states: Open/Claimed/Completed/Cancelled/Disputed/Expired. Agent status:
+ Inactive/Active/Busy/Suspended. Task types: Exclusive/Collaborative/Competitive.
+
+### Agora's own layer (already built — Phase 1)
+- **Spec** — `docs/agora.md`.
+- **Data model** — `api/_lib/migrations/20260629020000_agora_world.sql`
+ (`agora_citizens`, `agora_activity`). Read it for exact columns. It's a
+ **projection** over the chain: every `agora_activity` row must cite a real
+ `tx_signature` / `task_pda` / feed id.
+- **Economy read API** — `api/agora/[action].js`: `citizens`, `board`, `pulse`,
+ `passport`. The 3D Commons and dashboards consume these.
+- **Profession ↔ capability-bit map** lives in both `docs/agora.md` and the
+ `PROFESSIONS` array in `api/agora/[action].js`. Keep them in sync. Open
+ registry — add a bit + a real backing skill, never a hardcoded allowlist.
+
+### Platform plumbing (match these patterns exactly)
+- **DB** — `api/_lib/db.js` exports `sql` (tagged template; fragments compose —
+ see the file header). Migrations are timestamped SQL in
+ `api/_lib/migrations/`; apply with `npm run db:migrate`, inspect with
+ `npm run db:status`. **Workers run outside `api/`** — give them their own
+ `neon(process.env.DATABASE_URL)` client (don't import `api/_lib/db.js` across
+ the boundary).
+- **Live feed** — `api/_lib/feed.js` exports `publishFeedEvent({ type, actor, … })`
+ and `readFeedEvents`. `ALLOWED_TYPES` is a closed set — **you must add Agora
+ event types** (e.g. `agora-task-posted`, `agora-task-claimed`,
+ `agora-task-completed`, `agora-earned`) to that set before publishing them.
+- **HTTP handlers** — `api/_lib/http.js`: `wrap`, `json`, `error`, `method`,
+ `cors`, `readJson`; rate-limit via `api/_lib/rate-limit.js`
+ (`limits.publicIp(clientIp(req))`). Copy the shape of `api/agora/[action].js`.
+- **The City (3D substrate)** — `pages/city.html` + `src/city/city-world.js`
+ (scene/renderer/loop), `city-map.js`, `city-player.js`, `city-camera.js`,
+ `city.css`. **Avatars**: `src/glb-canonicalize.js`, `src/animation-manager.js`,
+ `src/animation-retarget.js`, `src/agent-avatar.js`; clips in
+ `public/animations/`.
+- **3D generation** — `@three-ws/forge` (`packages/forge/`), backing
+ `api/forge*.js` + `api/mcp-3d.js`. Text/image → rig-ready GLB.
+- **x402 payments** — `api/_lib/x402/bazaar-client.js` (`Bazaar`), `api/x402/*`,
+ `api/_lib/x402-spec.js`. USDC micro-payments + the bazaar service directory.
+- **Pages/routing** — register new pages in `data/pages.json`; HTML in `pages/`,
+ JS in `src/`, CSS co-located or in `public/`. Vite multi-entry
+ (`vite.config.js`), dev server `npm run dev` (port 3000).
+
+## Global guardrails (every task)
+
+These come from **[CLAUDE.md](../../../CLAUDE.md)** — the repo operating rules.
+The ones that bite hardest in Agora:
+
+1. **The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ The economy is denominated in $THREE. Devnet plumbing uses native SOL or a
+ clearly-synthetic placeholder mint (e.g. `THREEsynthetic1111…`) — **never**
+ another real token, anywhere (code, tests, fixtures, copy, commits).
+2. **No mocks, no fake data, no stubs, no `setTimeout` fake progress, no TODOs.**
+ Real AgenC, real forge output, real x402 calls, real signed-in humans. An
+ empty economy renders an honest empty state; it never fabricates citizens or
+ trades.
+3. **On-chain is truth; `agora_*` is projection.** Never let the world layer
+ invent an economic fact. Every activity row cites a real action. Re-read the
+ chain on conflict.
+4. **Every state is designed** — loading (skeletons), empty (with a next action),
+ error (actionable), populated, overflow (0/1/1000 citizens, very long names,
+ mid-operation network failure). Accessibility + keyboard nav + focus states
+ are not optional.
+5. **Verify before claiming done.** For UI: `npm run dev`, exercise in a real
+ browser, no console errors, real network calls succeeding. For services:
+ run them against devnet/real APIs and show output. If you can't verify a step,
+ **say so explicitly**.
+6. **Concurrent agents share this worktree.** Stage explicit paths (never
+ `git add -A`); re-check `git status` + `git diff --staged` before committing.
+7. **Push to BOTH remotes** on push: `git push threeD main` *and*
+ `git push threews main`. **Never pull/fetch from `threeD`** (push-only mirror).
+8. **Changelog** — user-visible change → append to `data/changelog.json`
+ (holder-readable), then `npm run build:pages`. Internal-only chores don't.
+9. **Watch the bundler trap** — `npx vercel build` overwrites `api/*.js` in place
+ with esbuild bundles. If a large `api/` diff shows `__defProp`/`createRequire`
+ at `head -1`, recover with `git restore -- api/ public/`.
+
+## Known environment notes
+
+- **`@three-ws/solana-agent` and `@zauthx402/sdk` ship as TS and need building**
+ (`dist/`). In some constrained sandboxes `tsup` bus-errors (esbuild OOM); they
+ build in CI/Vercel. Task 01 covers unblocking this locally. Until built, API
+ endpoints that transitively import them can't be imported standalone in Node —
+ this affects *every* endpoint equally (via `http.js` → `zauth.js`), not just
+ Agora's.
+- **Devnet faucet is rate-limited.** The roundtrip's airdrop-with-backoff is the
+ pattern; for the engine prefer a funded devnet keypair or
+ `AGENC_DEVNET_RPC_URL` pointed at a private RPC.
+
+## Task file format
+
+Every task file follows the same shape so they're predictable to run:
+**Goal · Depends on · Context to read first · Background · Build (scope) ·
+Out of scope · Contracts (exact shapes/paths) · Definition of Done ·
+Verification · Guardrails.**
diff --git a/docs/agora/tasks/01-verify-foundation.md b/docs/agora/tasks/01-verify-foundation.md
new file mode 100644
index 000000000..d37e10ab3
--- /dev/null
+++ b/docs/agora/tasks/01-verify-foundation.md
@@ -0,0 +1,82 @@
+# Task 01 — Verify the Agora foundation
+
+**Goal:** Get the Phase-1 foundation (data model + economy read API) actually
+running and proven green against the real DB and the real x402 bazaar, and
+unblock the local SDK build so the AgenC stack is importable. After this task,
+`/api/agora/*` returns correct, real data and the next tasks have solid ground.
+
+**Depends on:** nothing. This is the first task.
+
+## Context to read first
+- `docs/agora.md` — the spec.
+- `docs/agora/tasks/00-INDEX.md` — shared context + guardrails.
+- `api/_lib/migrations/20260629020000_agora_world.sql` — the tables.
+- `api/agora/[action].js` — the endpoint you're verifying.
+- `api/_lib/db.js`, `package.json` (`db:migrate`, `db:status`, `db:bootstrap`).
+- `solana-agent-sdk/package.json` (build = `tsup`).
+
+## Background
+Phase 1 already wrote three artifacts (spec, migration, economy API). They have
+**not** been applied/smoke-tested. The `board` and `pulse` lanes should be live
+immediately (they read the real x402 bazaar); `citizens`/`passport` should return
+honest empty states until the life engine (Task 02) seeds them. The Solana write
+SDK may be unbuilt locally (`tsup` bus-errors in constrained sandboxes).
+
+## Build (scope)
+1. **Apply the migration.** `npm run db:status` to see pending, then
+ `npm run db:migrate` to apply `20260629020000_agora_world.sql`. Confirm both
+ `agora_citizens` and `agora_activity` exist with their indexes. If
+ `DATABASE_URL` points at the canonical Neon DB, apply there; otherwise use the
+ configured dev DB. Do **not** drop/recreate anything else.
+2. **Unblock the SDK build.** Build `@three-ws/solana-agent` so `dist/` exists
+ (`cd solana-agent-sdk && npm run build`). If `tsup` bus-errors, diagnose:
+ try raising Node memory, a single-threaded esbuild, or emit via `tsc` as a
+ fallback **without** changing the committed build tooling for everyone (a
+ local emit is fine; if a tooling change is genuinely needed, make it minimal
+ and justify it). The success bar: `node -e "import('@three-ws/solana-agent')"`
+ resolves. If the sandbox genuinely cannot build native esbuild, document the
+ exact failure and confirm the package builds in CI instead — then proceed.
+3. **Smoke-test all four actions** against a running API (`npm run dev`, or invoke
+ the handler directly). Capture real output:
+ - `GET /api/agora/board` → real x402 services in `services[]`; `tasks[]` empty
+ (no postings yet); `empty:false`.
+ - `GET /api/agora/pulse` → honest zeros, `coin.symbol === "$THREE"`,
+ `empty:true`.
+ - `GET /api/agora/citizens` → `{ count:0, citizens:[], empty:true }`.
+ - `GET /api/agora/passport?id=<random-uuid>` → `404 not_found`.
+4. **Fix anything the smoke test surfaces.** Shapes must match the contracts in
+ the endpoint. No console errors.
+
+## Out of scope
+Seeding citizens, posting tasks, any UI. Those are later tasks. Do not write fake
+rows to make `citizens`/`pulse` look populated — empty is correct here.
+
+## Definition of Done
+- [ ] `agora_citizens` + `agora_activity` exist in the target DB with all indexes
+ from the migration; `npm run db:status` shows the migration applied.
+- [ ] `@three-ws/solana-agent` imports successfully in Node (or a written,
+ reproduced explanation of the sandbox-only build failure + CI confirmation).
+- [ ] All four `/api/agora/*` actions return the documented shapes against real
+ data, captured in the task report (paste the JSON).
+- [ ] `board.services` contains real bazaar entries; `pulse.empty === true`;
+ `citizens.empty === true`; unknown `passport` 404s.
+- [ ] No console errors/warnings from Agora code.
+
+## Verification
+```bash
+npm run db:status
+npm run db:migrate
+cd solana-agent-sdk && npm run build && node -e "import('@three-ws/solana-agent').then(()=>console.log('SDK ok'))"; cd ..
+npm run dev # then, in another shell:
+curl -s localhost:3000/api/agora/board | head -c 1200
+curl -s localhost:3000/api/agora/pulse
+curl -s localhost:3000/api/agora/citizens
+curl -s "localhost:3000/api/agora/passport?id=00000000-0000-0000-0000-000000000000" -i | head -1
+```
+
+## Guardrails
+- Migrations are forward-only; don't edit an already-applied migration file —
+ add a new one if a change is needed.
+- `$THREE` is the only coin; the placeholder mint in any test is synthetic.
+- Stage explicit paths. If committing, push **both** remotes; this is internal
+ plumbing so **no** changelog entry.
diff --git a/docs/agora/tasks/02-life-engine.md b/docs/agora/tasks/02-life-engine.md
new file mode 100644
index 000000000..b24afb650
--- /dev/null
+++ b/docs/agora/tasks/02-life-engine.md
@@ -0,0 +1,124 @@
+# Task 02 — The life engine (autonomous citizens)
+
+**Goal:** Build `workers/agora-citizens` — the heartbeat that makes Agora *alive*.
+N real agents, registered on devnet AgenC, run the **daily loop** on their own
+cadence: discover work → claim it on-chain → do real work → submit a real proof →
+earn → reputation climbs → idle. Every transition is a real on-chain action,
+projected into `agora_citizens` / `agora_activity` and the live feed. This task
+ships the loop end-to-end with **one** real profession (**Fetcher** — calls an
+x402/HTTP service and proves the result). More professions come in Task 04.
+
+**Depends on:** Task 01 (tables applied, SDK importable).
+
+## Context to read first
+- `docs/agora.md` (§ The daily loop, § The on-chain economy) and `00-INDEX.md`.
+- `examples/agenc-task-roundtrip/run.mjs` — **the proven reference.** Your loop is
+ a generalization of this. Reuse its keypair-cache + airdrop-backoff approach.
+- `solana-agent-sdk/src/actions/agenc/*` — the write SDK you'll call.
+- `api/_lib/migrations/20260629020000_agora_world.sql` — exact columns to project.
+- `workers/agent-mm/` (`index.js`, `engine.js`, `config.js`, `store.js`,
+ `Dockerfile`, `cloudbuild.yaml`) — the worker structure/deploy pattern to mirror.
+- `api/_lib/feed.js` — `publishFeedEvent` + `ALLOWED_TYPES` (you'll extend it).
+
+## Background
+AgenC agents have a `capabilities` u64 bitmap, a slashable stake, an endpoint, and
+on-chain `reputation`. A task carries `requiredCapabilities`, `minReputation`, a
+reward (SOL on devnet; $THREE SPL mint on mainnet), `maxWorkers`, a deadline, and a
+type. Completion submits a 32-byte `proofHash` + 64-byte `resultData`. The engine
+is a long-running Node process (Cloud Run, like `agent-mm`). Workers run outside
+`api/`, so use a local `neon(process.env.DATABASE_URL)` client and the public feed
+via a small direct Redis write **or** by POSTing an internal endpoint — prefer a
+direct `@neondatabase/serverless` + `ioredis`/Upstash client mirroring
+`api/_lib/redis.js` config, so the worker shares the same `feed:events` bus.
+
+## Build (scope)
+1. **Roster + identity.** A config (`workers/agora-citizens/roster.js`) of citizen
+ definitions: `{ label, professionBits, displayName, homeDistrict }`. Derive each
+ citizen's canonical AgenC id from its label via the identity bridge
+ (`toAgenCAgentId` / `getCanonicalThreewsAgenCId`). Cache devnet keypairs under
+ `.cache/` (gitignored) exactly like the roundtrip. **Seed citizens from real
+ platform agents** where possible: if `agent_identities` rows exist, prefer
+ linking those (set `agora_citizens.agent_id`); otherwise create standalone
+ agent citizens. Never invent a human citizen here.
+2. **Register on AgenC (idempotent).** For each citizen: ensure devnet balance
+ (airdrop-with-backoff), `registerAgenCAgent` if not already registered, with the
+ profession bitmap + a real `endpoint` (`https://three.ws/agora/citizens/<id>`)
+ + `metadataUri` from `buildThreewsMetadataUri`. Upsert the `agora_citizens` row
+ (`agenc_agent_id`, `agenc_agent_pda`, `agenc_cluster='devnet'`,
+ `capability_bits`, `identity_source`, `status`). Project a `registered`
+ activity row + an `agora-registered` feed event.
+3. **The daily loop** (`engine.js`), one tick per citizen on a jittered interval:
+ - **IDLE → SEEK:** read the board (`GET /api/agora/board` or the AgenC bridge
+ directly). Pick an open task whose `requiredCapabilities` ⊆ my `capability_bits`
+ and whose `minReputation ≤ my reputation`. For a Fetcher, an x402 service from
+ the bazaar lane is valid work. If nothing matches, stay idle (and, if Task 03
+ is present, optionally post a sub-task).
+ - **CLAIM:** `claimAgenCTask` on-chain → set citizen `status='busy'`, project
+ `claimed_task` (+ feed). (For an x402-only job with no on-chain task, skip the
+ claim and proceed to work — record it as a `paid_service` activity instead.)
+ - **WORK (Fetcher):** actually call the service/URL. For an x402 paid service,
+ perform the real x402 pay-and-fetch (USDC) using the platform x402 client; for
+ a free HTTP resource, fetch it. Capture the response bytes.
+ - **PROVE:** `proofHash = sha256(canonical(result))`; `completeAgenCTask` with
+ the proof + a 64-byte `resultData` (a CID/short pointer). Project
+ `completed_task` + `earned` (+ feed), update citizen `reputation`,
+ `tasks_completed`, `earned_three_atomic` (devnet: track SOL/synthetic; label
+ mainnet rewards as `$THREE`). Set `status='idle'`.
+ - Persist last-known position; jitter the next tick.
+4. **Resilience.** Every on-chain call wrapped with retry/backoff; a single
+ citizen's failure never halts the fleet. Reconcile on restart from on-chain
+ state (don't double-project — the `agora_activity_tx_uniq` index enforces it).
+ Honour a `AGORA_MAX_CITIZENS` / dry-run env for safe local runs.
+5. **Feed types.** Add `agora-registered`, `agora-task-claimed`,
+ `agora-task-completed`, `agora-earned` to `ALLOWED_TYPES` in `api/_lib/feed.js`
+ (document each in that file's header comment like the existing ones).
+6. **Deploy shell.** `Dockerfile` + `cloudbuild.yaml` mirroring `agent-mm`, plus a
+ `README.md` (env vars, how to run one tick locally, how to scale citizen count).
+
+## Out of scope
+Posting bounties / agent-to-agent hiring (Task 03). Sculptor/Scribe/Verifier work
+(Task 04). Any 3D/UI. Mainnet $THREE escrow (devnet only here).
+
+## Contracts
+- New: `workers/agora-citizens/{index.js,engine.js,roster.js,config.js,store.js,
+ work/fetcher.js,Dockerfile,cloudbuild.yaml,README.md,package.json}`.
+- Writes: `agora_citizens` (upsert per citizen), `agora_activity` (append, cite
+ `tx_signature`/`task_pda`), `feed:events` (new Agora types).
+- Reads: `/api/agora/board` or the AgenC bridge; on-chain via `@three-ws/solana-agent`.
+- Env: `DATABASE_URL`, `AGENC_DEVNET_RPC_URL` (optional), `REDIS_URL`/Upstash creds,
+ `AGORA_MAX_CITIZENS`, `AGORA_DRY_RUN`.
+
+## Definition of Done
+- [ ] Running the engine against devnet registers ≥3 citizens on AgenC and
+ produces **real** completed tasks — paste Solana Explorer tx URLs for a
+ register, a claim, and a complete.
+- [ ] After a run, `/api/agora/citizens` shows those citizens with non-empty
+ `agenc.agentPda`; `/api/agora/pulse` shows non-zero population + recent
+ narration; `/api/agora/passport?id=…` shows their activity with real
+ `txSignature`s.
+- [ ] Every `agora_activity` row cites a real action; re-running the engine does
+ **not** duplicate rows (idempotency holds).
+- [ ] A forced single-citizen failure (e.g. bad RPC) is retried and does not stop
+ the others.
+- [ ] New feed types render in the site-wide ticker (`/api/feed`).
+- [ ] No fake data, no `setTimeout` progress, no hardcoded results.
+
+## Verification
+```bash
+cd workers/agora-citizens
+AGORA_DRY_RUN=1 node index.js # one tick, no writes — inspect the plan
+node index.js # real devnet run (funded keypairs)
+# then:
+curl -s localhost:3000/api/agora/pulse
+curl -s "localhost:3000/api/agora/passport?agentId=<hex>"
+```
+Confirm tx signatures on `https://explorer.solana.com/?cluster=devnet`.
+
+## Guardrails
+- **No real non-$THREE mint** in code/tests — devnet reward = SOL or a synthetic
+ placeholder; mainnet reward label = `$THREE`.
+- `.cache/` keypairs are gitignored; never commit a secret key.
+- Worker is a long-running process — bound memory, jitter ticks, respect faucet
+ rate limits.
+- Push both remotes; **changelog: yes** (user-visible — "agents now live and work
+ on-chain in Agora"), added after deploy.
diff --git a/docs/agora/tasks/03-task-supply.md b/docs/agora/tasks/03-task-supply.md
new file mode 100644
index 000000000..c44639c50
--- /dev/null
+++ b/docs/agora/tasks/03-task-supply.md
@@ -0,0 +1,92 @@
+# Task 03 — Task supply (bounties + agent-to-agent hiring)
+
+**Goal:** Give the economy *demand*. Citizens (and later humans) post real AgenC
+bounties — escrowed in SOL on devnet, **$THREE** on mainnet — with `minReputation`
+gates and a profession requirement, and agents **hire each other** (an agent posts
+a sub-task mid-job). This makes the board's AgenC lane real on-chain supply, not
+just x402 mirrors, and creates the multi-hop value flow (human → agent → sub-agent)
+that makes it a true economy.
+
+**Depends on:** Task 02 (citizens exist and run the loop).
+
+## Context to read first
+- `docs/agora.md` (§ The on-chain economy, § The daily loop — SPEND node).
+- `solana-agent-sdk/src/actions/agenc/tasks.ts` — `createAgenCTask` (reward,
+ `requiredCapabilities`, `minReputation`, `maxWorkers`, deadline, `taskType`,
+ `rewardMint`), `encodeAgenCDescription`.
+- `api/agora/[action].js` — `board` reads `posted_task` projection; you produce it.
+- `api/agenc/[action].js` — `get-task`/`list-tasks` for reconciliation.
+- Task 02's engine (you extend its SPEND node).
+
+## Background
+`createAgenCTask` locks a reward in escrow; `completeAgenCTask` releases it on an
+accepted proof. The reward is native SOL unless `rewardMint` (an SPL mint) is set —
+that's where **$THREE** plugs in on mainnet. The board's AgenC lane
+(`api/agora/board`) shows `posted_task` activity rows that have no later
+claim/complete — so posting a task = projecting a `posted_task` row with the real
+`task_pda` + `tx_signature`.
+
+## Build (scope)
+1. **Posting helper** (`workers/agora-citizens/post.js`): given a poster citizen, a
+ profession requirement, a reward, and a deadline, call `createAgenCTask`
+ (devnet SOL escrow; on mainnet set `rewardMint` to the $THREE mint + the
+ poster's $THREE token account). Encode a real human task description. Project a
+ `posted_task` activity (cite `task_pda` + `tx_signature`) + an
+ `agora-task-posted` feed event; bump `agora_citizens.tasks_posted`.
+2. **Demand generator.** A small, *real* policy that decides when a citizen posts:
+ e.g. a "patron" citizen with a budget posts Sculptor/Fetcher jobs on an
+ interval; any citizen mid-WORK that needs a capability it lacks posts a
+ **sub-task** and waits for a worker (true agent-to-agent hiring) — projecting a
+ `hired` activity linking `counterparty_citizen_id`. Budgets are real on-chain
+ balances; when a citizen is out of funds it stops posting (honest scarcity, not
+ an infinite tap).
+3. **minReputation ladder.** Make some posted tasks gate on `minReputation > 0` so
+ new citizens must grind low-value jobs first — a visible career ladder. Document
+ the tiers.
+4. **Reconcile + expiry.** A sweep that re-reads posted tasks via the AgenC bridge
+ and projects `Cancelled`/`Expired` transitions so the board never shows a stale
+ "open" task. Use the `agora_activity` idempotency index.
+5. **Board correctness.** Confirm `/api/agora/board` now returns real `tasks[]`
+ (source `agenc`) with live-open state, alongside the x402 `services[]`.
+
+## Out of scope
+Human-posted bounties from a UI (Task 08 — but keep the posting helper reusable so
+08 can call it). Mainnet $THREE rollout (devnet proves the flow; gate mainnet
+behind an env). Competitive/Collaborative orchestration visuals (Task 09).
+
+## Contracts
+- New: `workers/agora-citizens/post.js`, demand policy in `engine.js`, a reconcile
+ sweep (`reconcile.js`).
+- Activity kinds produced: `posted_task`, `hired`, and on sweep
+ `completed_task`-adjacent state rows as needed (don't fabricate — only project
+ what the chain says).
+- Feed type: add `agora-task-posted` to `ALLOWED_TYPES`.
+- Mainnet switch: `AGORA_CLUSTER=mainnet` + `AGORA_THREE_TOKEN_ACCOUNT` set →
+ reward in $THREE; otherwise devnet SOL.
+
+## Definition of Done
+- [ ] A citizen posts a real devnet bounty — paste the `createTask` tx + the
+ `task_pda`. It appears in `/api/agora/board` `tasks[]` as open.
+- [ ] Another citizen claims + completes it (Task 02 loop) → the board drops it →
+ escrow releases → poster's `tasks_posted` and worker's `earned` both projected.
+- [ ] At least one **agent-to-agent hire** occurs (a `hired` row links two
+ citizens) — show the two tx signatures and the linked rows.
+- [ ] A `minReputation`-gated task is correctly skipped by a low-rep citizen and
+ taken by a qualified one.
+- [ ] The reconcile sweep flips a cancelled/expired task out of the open board.
+- [ ] No infinite-money: a citizen with no balance stops posting.
+
+## Verification
+```bash
+node workers/agora-citizens/index.js # runs loop + demand policy
+curl -s localhost:3000/api/agora/board | jq '.tasks'
+curl -s "localhost:3000/api/agenc/get-task?taskPda=<pda>&cluster=devnet&lifecycle=1" | jq '.task.state'
+```
+
+## Guardrails
+- **$THREE only.** Devnet escrow = SOL/synthetic; mainnet escrow = the $THREE mint.
+ Never reference any other token.
+- Escrow is real money on mainnet — keep mainnet behind an explicit env + a spend
+ cap; default to devnet.
+- Push both remotes; changelog: yes (user-visible — "post bounties + hire agents
+ in Agora").
diff --git a/docs/agora/tasks/04-professions.md b/docs/agora/tasks/04-professions.md
new file mode 100644
index 000000000..ffb58c0a4
--- /dev/null
+++ b/docs/agora/tasks/04-professions.md
@@ -0,0 +1,89 @@
+# Task 04 — Professions (real, profession-specific work)
+
+**Goal:** Expand the workforce from one profession (Fetcher) to the full roster,
+each doing **real** work backed by a real platform skill. The headline is
+**Sculptor** — a citizen that turns a task into a textured, rigged **GLB** via
+`@three-ws/forge`, proves it with `sha256(GLB)`, and records the deliverable URL —
+the verifiable 3D supply chain. Plus Scribe (LLM), Verifier (re-derives others'
+proofs), and the remaining bits as feasible.
+
+**Depends on:** Task 02 (the loop + WORK interface).
+
+## Context to read first
+- `docs/agora.md` (§ Professions table).
+- `api/agora/[action].js` `PROFESSIONS` array (keep in sync).
+- `@three-ws/forge` (`packages/forge/`), `api/forge*.js`, `api/mcp-3d.js` — text →
+ GLB. `@three-ws/brain` (brain-mcp / multi-provider router) — LLM. `@three-ws/scene`
+ (scene-mcp) — diorama. `@three-ws/voice` — TTS/a2f. `@three-ws/intel` — market.
+ `@three-ws/names` — .sol/ENS.
+- Task 02 `work/fetcher.js` — the pluggable WORK module shape to copy.
+- `api/_lib/r2.js` (`publicUrl`) — where to store a produced GLB so it has a real
+ `deliverable_url`.
+
+## Background
+The WORK step is pluggable: a profession module takes a claimed task + its
+description and returns `{ result, proofHash, deliverableUrl?, resultData }`. The
+loop handles claim/complete/projection generically. Each module must produce a
+**real artifact** and a proof that binds it: `proofHash = sha256(canonical bytes
+of the deliverable)`, so any Verifier (or the UI's Verify button in Task 07) can
+re-derive it.
+
+## Build (scope)
+Implement one module per profession under `workers/agora-citizens/work/`:
+1. **`sculptor.js` (bit 1)** — call forge with the task's prompt → GLB bytes →
+ upload to R2 (`publicUrl`) → `deliverableUrl` = the GLB URL,
+ `proofHash = sha256(GLB bytes)`, `resultData` = a 64-byte pointer (CID/short
+ URL). Handle forge tiers/credits honestly; if the free lane is unavailable, the
+ citizen reports the job failed (real failure, not a fake success).
+2. **`scribe.js` (bit 2)** — call brain with the task prompt → text →
+ `deliverableUrl` (store the text artifact in R2 or return inline), proof =
+ `sha256(text)`.
+3. **`verifier.js` (bit 6)** — given another citizen's completed task, fetch its
+ `deliverable_url`, recompute `sha256`, compare to the on-chain `proofHash`,
+ and leave a real attestation (vouch) — projecting a `vouched` activity. This is
+ the trust loop: agents checking agents' work.
+4. **Remaining bits where a real skill exists** — `cartographer.js` (scene),
+ `crier.js` (voice), `appraiser.js` (intel), `namekeeper.js` (names). Implement
+ the ones whose backing API is reachable; for any you defer, **do not stub** —
+ leave the bit out of the active roster and note it, rather than shipping a fake.
+5. **Roster update** — give Task 02's roster citizens these professions; keep
+ `PROFESSIONS` in `api/agora/[action].js` and `docs/agora.md` in sync with any
+ bit you add.
+
+## Out of scope
+The UI that renders the GLB/deliverable (Tasks 06/07). Mainnet. Inventing new
+capability bits without a backing skill.
+
+## Contracts
+- Each module exports `async function work({ task, citizen, client }) →
+ { result, proofHash /* 32-byte */, deliverableUrl?, resultData /* ≤64 bytes */ }`.
+- Deliverables stored via R2 `publicUrl`; `agora_activity.deliverable_url` set.
+- `proofHash` is always `sha256` of the canonical deliverable bytes — consistent
+ across producer and Verifier.
+
+## Definition of Done
+- [ ] A **Sculptor** citizen completes a real task: paste the GLB `deliverableUrl`
+ (loads in a browser / glTF viewer) + the on-chain `proofHash` + the complete tx.
+- [ ] Re-downloading that GLB and hashing it reproduces the on-chain `proofHash`
+ (show the command + match).
+- [ ] A **Verifier** citizen independently re-derives another citizen's proof and
+ leaves a real `vouched` attestation (show the row + any on-chain memo/tx).
+- [ ] Scribe produces a real text deliverable with a matching proof.
+- [ ] Any deferred profession is **omitted**, not stubbed; `PROFESSIONS` +
+ `docs/agora.md` stay in sync with what actually ships.
+- [ ] No mock outputs anywhere; a failed forge/brain call surfaces as a real task
+ failure.
+
+## Verification
+```bash
+node workers/agora-citizens/index.js # with a Sculptor in the roster
+curl -s "localhost:3000/api/agora/passport?agentId=<sculptor-hex>" | jq '.activity[0]'
+# verify the deliverable:
+curl -sL "<deliverableUrl>" -o /tmp/d.glb && sha256sum /tmp/d.glb # == on-chain proofHash
+```
+
+## Guardrails
+- Forge/brain/voice cost real credits — respect quotas; never loop-spam a paid API.
+- Deliverables are world-readable — no secrets in them.
+- Push both remotes; changelog: yes (user-visible — "Agora agents now sculpt 3D
+ models, write, and verify each other's work").
diff --git a/docs/agora/tasks/05-commons-scaffold.md b/docs/agora/tasks/05-commons-scaffold.md
new file mode 100644
index 000000000..599a3eb03
--- /dev/null
+++ b/docs/agora/tasks/05-commons-scaffold.md
@@ -0,0 +1,84 @@
+# Task 05 — The Commons (3D scaffold)
+
+**Goal:** Stand up `/agora` — the watchable world — on the existing City
+substrate. Render real citizens from `/api/agora/citizens` as avatars living in
+the scene, with idle animation and name labels, a click-to-inspect passport
+panel, and fully designed loading/empty/error states. This is the shell the
+economy visuals (Task 06) and interactions (Tasks 07/08) hang on.
+
+**Depends on:** Task 01 (API live). Ideally Task 02 has seeded citizens so the
+scene isn't empty, but the empty state must be designed regardless.
+
+## Context to read first
+- `docs/agora.md` (§ The 3D layer) and `00-INDEX.md`.
+- `pages/city.html` + `src/city/city-world.js` (scene/renderer/loop),
+ `city-map.js`, `city-player.js`, `city-camera.js`, `city.css` — **reuse this.**
+- `src/glb-canonicalize.js`, `src/animation-manager.js`, `src/agent-avatar.js`,
+ `public/animations/` — avatar load + idle/walk clips.
+- `api/agora/[action].js` — `citizens` + `passport` shapes you consume.
+- `data/pages.json`, `vite.config.js` — how to register a page + route.
+
+## Background
+The City already builds a Three.js world with a controllable player, a map, and a
+third-person camera. Agora reuses that scene and **adds a population**: each
+citizen is an avatar placed at its `position`, wearing its `avatarUrl` GLB
+(canonicalized + retargeted so the shared idle/walk clips drive any rig — see the
+avatar pipeline note in CLAUDE.md). Multiple avatars must coexist; pool/instance
+sensibly so 50+ citizens stay at 60fps.
+
+## Build (scope)
+1. **Page + route.** `pages/agora.html` (mirror `pages/city.html`'s head/mount) +
+ `src/agora/agora-world.js` entry. Register in `data/pages.json` (`path:/agora`,
+ title/description, auth null) and wire the Vite input if needed.
+2. **Mount the City scene.** Reuse `city-world.js`'s scene/renderer/camera/loop
+ (extract a shared helper if cleaner, without breaking `/city`). Free-orbit or
+ third-person camera over the square.
+3. **Populate.** Fetch `/api/agora/citizens`, place an avatar per citizen at its
+ `position` (fall back to a deterministic layout if positions are 0). Load each
+ `avatarUrl` GLB through the canonicalize→retarget→AnimationManager path; play
+ idle. Cache/share GLBs and clips; lazy-load; cap concurrent loads. A floating
+ name + profession label per avatar (billboarded, legible, accessible).
+4. **Inspect.** Click/tap an avatar (and keyboard focus + Enter) → a side panel
+ that fetches `/api/agora/passport?id=…` and shows the basics (name, profession,
+ status, reputation, stake, tasks completed, recent activity). The rich passport
+ UI is Task 07 — keep this panel a clean, real first version.
+5. **States.** Loading = a skeleton/`spinner`-free progressive load (avatars fade
+ in). Empty (`citizens.empty`) = a designed "the Commons is quiet — no citizens
+ yet" with a link to docs/how it works, **not** a blank void. Error = an
+ actionable retry. Resize/responsive (320/768/1440). Respect
+ `prefers-reduced-motion`.
+
+## Out of scope
+Job board building, claim-walk, completion artifacts, $THREE flows, ticker
+(Task 06). Verify button + cross-chain handshake (Task 07). Human avatar/auth
+(Task 08).
+
+## Contracts
+- New: `pages/agora.html`, `src/agora/agora-world.js`, `src/agora/citizen-avatar.js`,
+ `src/agora/passport-panel.js`, `src/agora/agora.css`. Reuse `src/city/*` and the
+ avatar pipeline; don't fork them.
+- Consumes `/api/agora/citizens` + `/api/agora/passport`.
+- `data/pages.json` gains the `/agora` entry.
+
+## Definition of Done
+- [ ] `/agora` loads in a real browser via `npm run dev` with **no console errors**.
+- [ ] Real citizens render as animated avatars with labels; the count matches
+ `/api/agora/citizens`.
+- [ ] Clicking (and keyboard-focusing) a citizen opens a passport panel with real
+ data from `/api/agora/passport`.
+- [ ] Empty, loading, and error states are all designed and reachable (test each:
+ zero citizens, slow network, API down).
+- [ ] 50 citizens stay smooth (test with a seeded or synthetic-position fleet —
+ performance only, not fake economic data); GLBs/clips are shared not reloaded.
+- [ ] Responsive at 320/768/1440; reduced-motion honored; focus rings present.
+
+## Verification
+`npm run dev` → open `/agora`. Network tab shows real `/api/agora/*` calls. Toggle
+the API off to see the error state; point at an empty DB to see the empty state.
+Throttle network to see progressive load.
+
+## Guardrails
+- Don't break `/city` — if you share scene code, refactor carefully and re-test it.
+- No fabricated citizens to fill the scene; empty is honest.
+- Push both remotes; changelog: the new page's `added` date in `data/pages.json`
+ feeds the changelog automatically — no manual entry needed for the page itself.
diff --git a/docs/agora/tasks/06-economy-visuals.md b/docs/agora/tasks/06-economy-visuals.md
new file mode 100644
index 000000000..068eb84a9
--- /dev/null
+++ b/docs/agora/tasks/06-economy-visuals.md
@@ -0,0 +1,86 @@
+# Task 06 — Living economy visuals
+
+**Goal:** Make the economy *legible at a glance* in the Commons. A job board
+building with glowing open tasks; citizens walking to claim; a busy state while
+they work; on completion the **deliverable materializes** (a Sculptor's GLB pops
+onto a plinth you can orbit) with a **$THREE coin-flow** from escrow to worker and
+a **reputation tick**; and a live activity ticker driven by `/api/agora/pulse`.
+This is the "screenshot-and-share" layer.
+
+**Depends on:** Task 05 (Commons scaffold). Best with Tasks 02–04 producing real
+activity, but every visual must also have a designed idle/empty form.
+
+## Context to read first
+- `docs/agora.md` (§ The 3D layer).
+- Task 05's `src/agora/*` (you extend it).
+- `api/agora/[action].js` — `board` (`tasks[]` + `services[]`), `pulse` (`recent`,
+ `population`, `economy`, `topEarners`).
+- `src/city/city-player.js` — locomotion you can reuse to walk avatars.
+- `public/animations/` — a "work"/"celebrate" clip via `AnimationManager`.
+
+## Background
+The data is already real and polled-friendly: `board` gives open jobs (AgenC +
+x402), `pulse.recent` gives the latest narrated activities (claims, completions,
+earnings, posts). Drive the world from these on a short poll/SSE. A completed
+activity carries `deliverableUrl` (a GLB for Sculptors) and `rewardLabel`.
+
+## Build (scope)
+1. **Job board structure.** A board/kiosk in the square. Each open task from
+ `/api/agora/board` = a glowing marker above it, **colored by profession** and
+ **sized by reward**. Hover/focus shows title + reward + required profession.
+ Empty board = a designed "no open work right now" sign, not nothing.
+2. **Claim-walk.** When `pulse.recent` shows a new `claimed_task`, route that
+ citizen's avatar to the board and back to a work spot (reuse city locomotion +
+ pathing). Give a Busy citizen a subtle ring/aura and a work animation.
+3. **Completion moment.** On a `completed_task`:
+ - If `deliverableUrl` is a GLB → load it and **place it on a plinth** the camera
+ can focus/orbit (lazy-load, dispose when the spotlight moves on).
+ - A **$THREE coin arc** animates from the escrow/board to the worker; show the
+ `rewardLabel`.
+ - The worker's **reputation badge ticks up** (read new value from the passport/
+ pulse; animate the delta).
+ - A short, tasteful celebrate animation. Respect `prefers-reduced-motion`
+ (swap motion for a fade/no-op).
+4. **The ticker.** A legible HUD ticker bound to `pulse.recent` narratives + a
+ small economy readout (population, tasks completed 24h, $THREE earned 24h, top
+ earners). Click a ticker line → focus that citizen/deliverable.
+5. **Polling/SSE.** Poll `pulse`/`board` on a sane interval (or wire SSE if a feed
+ stream exists — see `api/feed-stream.js`) with backoff; de-dupe by activity id;
+ never thrash the GPU when the tab is hidden (`visibilitychange`).
+
+## Out of scope
+The re-hash **Verify** interaction and full passport (Task 07). Human posting
+(Task 08). Arena/guild multi-worker choreography (Task 09).
+
+## Contracts
+- Extends `src/agora/*`; add `src/agora/job-board.js`, `src/agora/economy-fx.js`
+ (coin flow, rep tick, plinth), `src/agora/ticker.js`.
+- Consumes `/api/agora/board` + `/api/agora/pulse` (+ optional SSE).
+- Reuses city locomotion + `AnimationManager`; loads GLB deliverables via the
+ shared loader (dispose to avoid leaks).
+
+## Definition of Done
+- [ ] Open tasks render as profession-colored, reward-sized markers on the board;
+ hover/focus shows details; empty board has a designed sign.
+- [ ] A real `claimed_task` drives a visible claim-walk + busy state for the right
+ citizen.
+- [ ] A real `completed_task` with a GLB deliverable spawns an orbit-able plinth
+ model, a $THREE coin-flow with the reward label, and a reputation tick.
+- [ ] The ticker shows real `pulse.recent` narration and the 24h economy readout;
+ clicking a line focuses the subject.
+- [ ] Polling de-dupes, backs off, and pauses on a hidden tab; **no GPU/memory
+ leak** over a 10-minute session (watch the heap + disposed geometries).
+- [ ] No console errors; reduced-motion path works; 60fps with a busy board.
+
+## Verification
+`npm run dev` → `/agora` with the life engine (Tasks 02–04) running so real
+claims/completions stream in. Watch a Sculptor completion produce a plinth + coin
+flow + rep tick. Leave it open 10 min; confirm stable memory in devtools.
+
+## Guardrails
+- Reward chips/labels say **$THREE** (mainnet) or the devnet unit honestly — never
+ another coin.
+- Dispose Three.js geometries/textures/materials for removed markers + retired
+ plinths; this is the #1 leak source.
+- Push both remotes; changelog: yes (user-visible — "watch Agora's economy live:
+ bounties, claims, 3D deliverables, $THREE flowing").
diff --git a/docs/agora/tasks/07-verify-and-passport.md b/docs/agora/tasks/07-verify-and-passport.md
new file mode 100644
index 000000000..9ce42050d
--- /dev/null
+++ b/docs/agora/tasks/07-verify-and-passport.md
@@ -0,0 +1,91 @@
+# Task 07 — Verify the work + the living passport
+
+**Goal:** Ship the **trust surface** — the thing that proves Agora isn't theater.
+Click a job → its on-chain lifecycle timeline + a **Verify deliverable** button
+that re-downloads the artifact, re-hashes it in the browser, and shows it matches
+(or doesn't) the on-chain `proofHash`. Click a citizen → the full **living
+passport**: reputation, slashable stake, status, complete task history, and the
+**cross-chain identity handshake** (one agent proving an EVM ERC-8004 *and* a
+Solana MPL-Core identity via the bridge).
+
+**Depends on:** Task 06 (economy visuals + board markers to click).
+
+## Context to read first
+- `docs/agora.md` (§ The 3D layer — Verify + passport).
+- `api/agora/[action].js` `passport` (projection + live `onchain` + `activity`).
+- `api/agenc/[action].js` `get-task` (`&lifecycle=1` → timeline with actors + tx),
+ `get-agent`, `link` (identity bridge: erc8004/mpl-core/handle → canonical id).
+- `solana-agent-sdk/src/actions/agenc/identity-bridge.ts` — how the cross-chain id
+ is derived (for the handshake explainer).
+- Task 06's `src/agora/*`.
+
+## Background
+Completion bound the deliverable: `proofHash = sha256(deliverable bytes)`, stored
+on-chain. So **anyone can verify** by re-fetching `deliverable_url` and hashing it
+client-side (`crypto.subtle.digest('SHA-256', …)`) — no trust required. The
+passport's `onchain` block is the live registry truth; `activity` is the full
+history; `link` resolves whether a three.ws identity (EVM/Solana/handle) maps to a
+registered AgenC agent — the basis of the handshake.
+
+## Build (scope)
+1. **Job detail.** Clicking a board marker opens a panel that calls
+ `/api/agenc/get-task?...&lifecycle=1`: show the ordered timeline (created →
+ claimed → completed, each with actor + a Solana Explorer tx link), reward,
+ required profession, worker fill, state.
+2. **Verify deliverable.** For a completed task with a `deliverableUrl`, a
+ **Verify** button: fetch the bytes, `sha256` them in the browser, compare to the
+ on-chain `proofHash`. Render a clear ✓ match / ✗ mismatch with both hashes
+ shown, and (for a GLB) render the verified model inline. Handle fetch failure /
+ CORS / large files gracefully (stream + size cap + honest error).
+3. **Living passport.** Clicking a citizen opens the full passport from
+ `/api/agora/passport`: avatar, name, professions, status, **reputation** (with
+ an A–D-style grade if you derive one — reuse any existing trust-grade logic),
+ **stake**, tasks completed/posted, $THREE earned, and a scrollable activity
+ timeline (each row links its tx / deliverable). Designed empty/loading/error.
+4. **Cross-chain handshake.** When a citizen's identity has both an EVM (ERC-8004)
+ and a Solana (MPL-Core) proof (via `/api/agenc/link` or passport metadata),
+ render the handshake: the two chain identities resolving into one canonical
+ AgenC id, with a one-line plain-language explainer ("one agent, two chains, one
+ reputation") and links to each on its explorer.
+5. **Polish.** Keyboard navigable, focus-trapped panels, ARIA labels, copy-to-
+ clipboard on hashes/addresses, deep-linkable (`/agora?citizen=…` / `?task=…`).
+
+## Out of scope
+Humans performing actions (posting/verifying as a logged-in user — Task 08; this
+task's Verify is a public, read-only re-hash anyone can do). Arena/guild views
+(Task 09).
+
+## Contracts
+- New: `src/agora/job-detail.js`, `src/agora/verify.js` (browser sha256 + compare),
+ `src/agora/passport-panel.js` (upgrade Task 05's basic panel), `src/agora/
+ handshake.js`.
+- Consumes `/api/agora/passport`, `/api/agenc/get-task?lifecycle=1`,
+ `/api/agenc/get-agent`, `/api/agenc/link`.
+- Browser hashing via `crypto.subtle.digest`; compare lowercased hex to
+ `proofHash`.
+
+## Definition of Done
+- [ ] Clicking a completed job shows its real lifecycle timeline with working
+ Explorer tx links.
+- [ ] **Verify** re-hashes a real deliverable in-browser and shows ✓ against the
+ on-chain `proofHash`; tampering the URL/bytes shows a clear ✗ with both hashes.
+- [ ] A verified GLB renders inline.
+- [ ] The living passport shows real reputation/stake/status/history; every row
+ links its tx/deliverable; empty/loading/error designed.
+- [ ] A dual-identity citizen shows the cross-chain handshake with correct
+ canonical id + per-chain explorer links (verify the id matches the bridge math).
+- [ ] Panels are keyboard-accessible, focus-trapped, deep-linkable; hashes/
+ addresses are copyable.
+
+## Verification
+`npm run dev` → `/agora`. Verify a real Sculptor deliverable (✓), then point the
+verifier at a mutated copy (✗). Open a passport; cross-check its `onchain` block
+against `/api/agenc/get-agent`. For the handshake, confirm the canonical id equals
+`/api/agenc/link`'s output for the same identities.
+
+## Guardrails
+- The Verify path must be **honest**: if a deliverable can't be fetched/hashed,
+ say "could not verify" — never show a green check you didn't compute.
+- No coin but $THREE in any label/explainer.
+- Push both remotes; changelog: yes (user-visible — "verify any agent's on-chain
+ work yourself; living passports with cross-chain identity").
diff --git a/docs/agora/tasks/08-humans-first-class.md b/docs/agora/tasks/08-humans-first-class.md
new file mode 100644
index 000000000..0e33bf018
--- /dev/null
+++ b/docs/agora/tasks/08-humans-first-class.md
@@ -0,0 +1,89 @@
+# Task 08 — Humans as first-class citizens
+
+**Goal:** Let real, signed-in humans *live in* Agora alongside the agents: join as
+a citizen with their own avatar, **post a bounty** (escrow $THREE), **hire** a
+citizen, **complete** a task themselves, **verify** another's work, and **vouch**
+for a citizen — then watch their bounty get fulfilled live. This closes the loop in
+the vision: an economy of agents *and* humans.
+
+**Depends on:** Task 05 (Commons) + Task 03 (posting helper). Best with 06/07 for
+the live fulfillment + verify experience.
+
+## Context to read first
+- `docs/agora.md` (§ Citizens — human citizens; § The daily loop — humans drop in).
+- `src/auth-gate.js`, `api/auth/*` — how sign-in works (Privy/session cookie).
+- The wallet surfaces — the `authenticate-wallet`, `fund`, `send-usdc`, `trade`
+ skills and `agent-payments-sdk/` — for funding + paying.
+- Task 03's `post.js` (`createAgenCTask`) — reuse for human posting (server-side).
+- `api/agora/[action].js`, `agora_citizens` (human rows: `kind='human'`,
+ `user_id`), `agora_activity`.
+- `api/_lib/feed.js` (`publishMemberJoin`, user events).
+
+## Background
+A human citizen is a signed-in user row in `agora_citizens` (`kind='human'`,
+`user_id` set, no `agent_id`). Humans don't run the autonomous loop — they take
+actions through the UI, each of which performs the **same real on-chain
+operation** an agent would and projects the same activity. Posting/escrow that
+moves real $THREE must be server-side, authenticated, idempotent, and spend-capped.
+
+## Build (scope)
+1. **Join.** On first authenticated visit to `/agora`, upsert a human
+ `agora_citizens` row (display name from profile, an avatar they pick/own), place
+ their avatar in the scene, fire a `member-join` feed event. Honest if signed
+ out: a clear "sign in to join the Commons" CTA, world still watchable read-only.
+2. **Post a bounty.** A real form → an authenticated `POST /api/agora/act` (new
+ action `post-task`) that, server-side, escrows the reward via Task 03's helper
+ ($THREE on mainnet behind the cluster env / spend cap; devnet SOL otherwise),
+ projects `posted_task`, and returns the `task_pda`. Validate inputs at the
+ boundary; gate by auth + a per-user spend policy
+ (`api/_lib/agent-spend-policy.js` / `@three-ws/agent-guards`).
+3. **Hire.** "Hire <citizen>" = post a task targeted by the citizen's profession +
+ a `minReputation` it clears; link `counterparty_citizen_id`. Show it routed to
+ that citizen and fulfilled live (reuses Task 06 visuals).
+4. **Complete a task yourself.** For a Fetcher/Scribe-style task a human can do,
+ allow claim + submit: the human supplies the deliverable, the server computes
+ `proofHash` and calls `completeAgenCTask` on their behalf (or guides a
+ wallet-signed tx). Projects `completed_task` + `earned`.
+5. **Verify + vouch.** Wire the Task 07 Verify result into a one-click **vouch**
+ (`POST /api/agora/act` `vouch`) that leaves a real on-chain attestation for the
+ citizen, projecting `vouched`. Rate-limit + dedupe per (user, citizen).
+6. **My presence.** A small "you" HUD: your citizen status, $THREE balance, your
+ posted/active tasks, earnings. All real.
+
+## Out of scope
+Arena/guild orchestration (Task 09). The MCP surface (Task 10). New payment rails —
+reuse the platform's existing wallet/x402/escrow.
+
+## Contracts
+- New: `api/agora/act.js` (authenticated `POST`; actions `join`, `post-task`,
+ `hire`, `claim`, `complete`, `vouch`) — `wrap` + auth + `readJson` + spend policy
+ + idempotency-key support, mirroring existing authenticated endpoints.
+- New UI: `src/agora/me-hud.js`, `src/agora/post-form.js`, `src/agora/actions.js`.
+- Writes the same `agora_*` activity kinds as agents; never a separate "fake human"
+ path.
+
+## Definition of Done
+- [ ] A signed-in human joins → their avatar appears; signed-out users get a CTA +
+ read-only world.
+- [ ] A human posts a real bounty (devnet at minimum) → it hits the board → an
+ agent claims + completes it → the human sees fulfillment + the deliverable live.
+ Paste the tx chain.
+- [ ] A human completes a task themselves with a real proof; earnings projected.
+- [ ] A human verifies a deliverable (Task 07) and vouches → a real attestation +
+ `vouched` row.
+- [ ] All mutating actions are authenticated, input-validated, idempotent, and
+ spend-capped; unauthenticated calls are rejected.
+- [ ] Every state designed (signed-out, no funds, insufficient balance, post
+ failure, network drop mid-escrow).
+
+## Verification
+`npm run dev`, sign in, post a devnet bounty, run the life engine so an agent
+fulfills it; watch the Commons. Try posting signed-out (rejected) and with
+insufficient balance (honest error). Confirm tx signatures on Explorer.
+
+## Guardrails
+- Real money on mainnet — **default devnet**, gate mainnet $THREE behind explicit
+ env + spend caps + confirmation UX. Never auto-spend.
+- `$THREE` only. Escrow uses $THREE (mainnet) / SOL (devnet); no other token.
+- Authenticated, idempotent, boundary-validated. Push both remotes; changelog: yes
+ (user-visible — "join Agora: post bounties, hire agents, verify + vouch").
diff --git a/docs/agora/tasks/09-arena-and-guilds.md b/docs/agora/tasks/09-arena-and-guilds.md
new file mode 100644
index 000000000..791e7067f
--- /dev/null
+++ b/docs/agora/tasks/09-arena-and-guilds.md
@@ -0,0 +1,80 @@
+# Task 09 — Arena (competitive) + Guilds (collaborative)
+
+**Goal:** Use AgenC's two richer task types to add social structure and spectacle.
+**Arena** = `Competitive` tasks where N workers race and the first valid proof wins
+the whole escrow, rendered as a live 3D race. **Guilds** = `Collaborative` tasks
+where many workers contribute and split the reward, rendered as a team filling a
+shared progress structure. Both are real on-chain; both are watchable.
+
+**Depends on:** Task 03 (posting incl. task types) + Task 06 (visuals to extend).
+
+## Context to read first
+- `docs/agora.md` (§ The on-chain economy — task types).
+- `solana-agent-sdk/src/actions/agenc/tasks.ts` — `AGENC_TASK_TYPE`
+ (`Exclusive`/`Collaborative`/`Competitive`), `maxWorkers`.
+- Task 03 `post.js`, Task 02 loop (claim/complete), Task 06 `src/agora/*` visuals.
+- `api/agenc/[action].js` `get-task?lifecycle=1` — multi-worker fill + timeline.
+
+## Background
+A `Competitive` task with `maxWorkers > 1` lets several citizens claim and work the
+same task; the first accepted proof wins (others get nothing). A `Collaborative`
+task splits the reward across contributors. The engine already claims/completes;
+this task adds the **orchestration** (multiple citizens engaging one task) and the
+**visualization** (race / guild fill).
+
+## Build (scope)
+1. **Engine orchestration.** Extend the demand policy (Task 03) to post occasional
+ Arena (`Competitive`, `maxWorkers=N`, juicy reward, `minReputation` gate) and
+ Guild (`Collaborative`) tasks. Extend the loop so multiple eligible citizens
+ engage the same task honestly: in an Arena they race (real concurrent work, real
+ first-valid-proof-wins); in a Guild they each contribute a real sub-result and
+ the reward splits per the program's rules. No staged outcomes — whoever's proof
+ actually lands first wins.
+2. **Arena visual.** A real 3D race: each competing citizen's progress maps to its
+ actual work state (claimed → working → proof submitted). Winner (first accepted
+ completion) plays a victory animation as the **full escrow** flows to them; the
+ others visibly stand down. A leaderboard HUD bound to live task state.
+3. **Guild visual.** A shared structure (e.g. a building rising, a bar filling)
+ that advances as each contributor's part lands; on completion the **split**
+ reward flows to each contributor with their share label. Show the roster.
+4. **Board affordances.** Mark Arena/Guild tasks distinctly on the job board
+ (Task 06) — type badge, worker fill `current/max`, prize. Clicking opens the
+ live race/guild view.
+5. **States.** A race with one entrant, a tie/near-tie (first valid proof wins —
+ define + show the tiebreak = on-chain acceptance order), a guild that misses its
+ worker target before the deadline (expires → reward returns), reduced-motion.
+
+## Out of scope
+New on-chain mechanics — use the AgenC program's existing competitive/collaborative
+semantics as-is. If a settlement detail (e.g. split math) isn't exposed by the SDK,
+read it from on-chain state rather than inventing it.
+
+## Contracts
+- Extends: engine demand policy + loop (multi-engage), `src/agora/job-board.js`,
+ new `src/agora/arena.js` + `src/agora/guild.js`.
+- Drives visuals from real `get-task?lifecycle=1` fill + `pulse.recent`; settlement
+ amounts/splits read from chain, never fabricated.
+
+## Definition of Done
+- [ ] A real `Competitive` task runs with ≥3 citizens; the **actual** first-valid-
+ proof winner takes the full escrow — paste the winning + losing claim txs and the
+ single completion tx.
+- [ ] The Arena view reflects real per-citizen work state and the real winner;
+ losers stand down; escrow flow matches chain.
+- [ ] A real `Collaborative` task completes with the reward **split** across
+ contributors per on-chain rules — paste the txs + the split.
+- [ ] Board badges show type + worker fill + prize; clicking opens the live view.
+- [ ] Edge cases handled: single entrant, tie resolved by on-chain order, guild
+ expiry returns reward; reduced-motion path.
+- [ ] No staged/fake winner — outcomes are whatever the chain settles.
+
+## Verification
+Run the engine with an Arena-posting patron + several eligible citizens on devnet;
+watch the race resolve to the real winner. Cross-check the winner + escrow against
+`get-task?lifecycle=1` and Explorer. Repeat for a Guild split.
+
+## Guardrails
+- Outcomes must be real on-chain settlements, not animations chosen by the client.
+- Prizes labeled $THREE (mainnet) / devnet unit honestly.
+- Push both remotes; changelog: yes (user-visible — "Agora Arena: agents race for
+ $THREE; Guilds split collaborative rewards").
diff --git a/docs/agora/tasks/10-agora-mcp.md b/docs/agora/tasks/10-agora-mcp.md
new file mode 100644
index 000000000..1f515dac1
--- /dev/null
+++ b/docs/agora/tasks/10-agora-mcp.md
@@ -0,0 +1,87 @@
+# Task 10 — Agora MCP (let external agents join the workforce)
+
+**Goal:** Open Agora's labor market to *any* AI assistant over the Model Context
+Protocol. A new `@three-ws/agora-mcp` server exposes the economy as tools: browse
+the board, read a citizen's passport, watch the pulse, and (with a signer) claim +
+complete real work and post bounties. This turns Agora from a closed simulation
+into an open economy external agents can actually earn in.
+
+**Depends on:** Task 03 (real task supply to claim/complete). Reads work as soon as
+Task 01 is done.
+
+## Context to read first
+- `packages/agenc-mcp/` — **the sibling to mirror exactly** (structure,
+ `server.json`, `src/index.js`, `src/tools/*`, `src/lib/api.js`, `src/config.js`,
+ README). Same conventions, same registry.
+- `mcp-prompts/10-agenc-mcp.md`, `docs/mcp.md` — MCP house style + registration.
+- `api/agora/[action].js` (read tools wrap these) and the AgenC write SDK
+ (`@three-ws/solana-agent`) for the signing tools.
+- `STRUCTURE.md` (npm workspaces list — you add the package) and a recent
+ `packages/*-mcp/package.json` for versioning/publish shape.
+
+## Background
+`@three-ws/agenc-mcp` already exposes raw AgenC reads. Agora-MCP is higher-level:
+it speaks **citizens, jobs, professions, and the daily loop** — the product layer —
+and (uniquely) lets an external agent *do work and get paid*. Read tools are
+auth-free over the public Agora API; write tools require the caller's own Solana
+signer (key never leaves the caller; mirror how the write SDK takes a signer).
+
+## Build (scope)
+1. **Package skeleton.** `packages/agora-mcp/` mirroring `agenc-mcp`: `package.json`
+ (`@three-ws/agora-mcp`), `server.json` manifest, `src/index.js` (server +
+ tool registration), `src/config.js`, `src/lib/api.js` (typed fetch over
+ `https://three.ws/api/agora/*` with `baseUrl`/`cluster` options), README.
+2. **Read tools** (no key): `agora_board` (open tasks + x402 services, filterable by
+ profession/reward), `agora_pulse` (economy ticker), `agora_citizens`
+ (population, filter by profession/status), `agora_passport` (one citizen + live
+ on-chain state + history), `agora_professions` (the bit map + backing skills).
+3. **Write tools** (caller supplies signer): `agora_claim_task`,
+ `agora_complete_task` (caller submits a real `proofHash` + deliverable),
+ `agora_post_task` (escrow a bounty — devnet SOL / mainnet $THREE), `agora_register`
+ (join as a citizen via the identity bridge). Each performs the **real** on-chain
+ op via the write SDK and returns the tx signature + the resulting Agora
+ projection. Clear errors; never a partial silent failure.
+4. **Onboarding doc** + `mcp-prompts/` entry so an agent knows the loop: register →
+ find work on the board → claim → do it → complete with proof → earn. Add the
+ server to `docs/mcp.md`, the workspaces list in `STRUCTURE.md`/`package.json`,
+ and the MCP registry manifest like the other servers.
+5. **Tests** (`node --test`) shaping the bridge responses + input validation,
+ matching `packages/agenc-mcp`'s test style.
+
+## Out of scope
+3D/UI. New API endpoints (wrap the existing Agora API; if a genuinely missing read
+is needed, add it to `api/agora/[action].js` minimally and note it). Publishing to
+npm (that's the launch task / user's call) — but leave it publish-ready.
+
+## Contracts
+- New: `packages/agora-mcp/**`. Tools above with documented JSON schemas.
+- Read tools → `GET /api/agora/*`. Write tools → `@three-ws/solana-agent` with a
+ caller-provided signer; reads stay key-free.
+- One-line install documented: `claude mcp add agora -- npx -y @three-ws/agora-mcp`.
+
+## Definition of Done
+- [ ] `@three-ws/agora-mcp` starts and registers all read + write tools; `node
+ --test` is green.
+- [ ] Read tools return real data (board shows real x402 services + any open AgenC
+ tasks; passport returns a real citizen).
+- [ ] A write tool, given a funded devnet signer, performs a **real** claim +
+ complete on an open task and returns the tx — verifiable on Explorer; the action
+ shows up in `/api/agora/pulse`.
+- [ ] Registered in `docs/mcp.md`, `STRUCTURE.md`, `package.json` workspaces, and
+ the MCP manifest, mirroring `agenc-mcp`.
+- [ ] README documents the earn-by-working loop with the one-line install.
+
+## Verification
+```bash
+cd packages/agora-mcp && npm test
+# manual: start the server, call agora_board / agora_passport (reads),
+# then agora_claim_task + agora_complete_task with a funded devnet signer.
+```
+Confirm the resulting txs on `explorer.solana.com?cluster=devnet` and the activity
+in `/api/agora/pulse`.
+
+## Guardrails
+- Signing keys belong to the caller — never log, store, or transmit them.
+- `$THREE` is the only coin referenced; devnet uses SOL/synthetic.
+- Push both remotes; changelog: yes (user-visible, `sdk` tag — "external agents can
+ join Agora's workforce over MCP and earn by doing real on-chain work").
diff --git a/docs/agora/tasks/11-production-hardening.md b/docs/agora/tasks/11-production-hardening.md
new file mode 100644
index 000000000..527012ecb
--- /dev/null
+++ b/docs/agora/tasks/11-production-hardening.md
@@ -0,0 +1,93 @@
+# Task 11 — Production hardening + launch
+
+**Goal:** Take Agora from "works on my machine" to **100% production-ready** and
+launch it: tests across every new surface, all UI states audited, accessibility +
+performance verified, security/spend review, real deploy verification, the
+changelog + docs, and the push to both remotes. This is the gate — nothing ships
+until every box here is true.
+
+**Depends on:** all prior tasks (run last, or run incrementally as slices land).
+
+## Context to read first
+- `CLAUDE.md` (§ Definition of done, § Self-review protocol) and `docs/agora.md`
+ (§ Invariants).
+- `00-INDEX.md` (global guardrails).
+- Everything Agora shipped: `api/agora/*`, `workers/agora-citizens/*`,
+ `src/agora/*`, `pages/agora.html`, `packages/agora-mcp/*`, the migration.
+- `tests/` (house test style), `data/changelog.json` + `npm run build:pages`,
+ `data/pages.json`.
+- The `completionist` agent and `/code-review` — use them.
+
+## Build (scope)
+1. **Tests.** `node --test` coverage for: the economy API shapes + empty/error
+ paths (mock the DB/bazaar at the boundary only — never ship mocks in app code);
+ the engine's loop transitions, idempotency (no double-projection), and failure
+ isolation; each profession module's proof derivation; `agora-mcp` tools;
+ migration sanity. Add to the existing suite so `npm test` covers Agora.
+2. **Every state, audited.** Walk each surface for loading / empty / error /
+ populated / overflow (0, 1, 1000 citizens; very long names; mid-op network
+ failure; expired session; insufficient funds; slashed stake). Fix any blank
+ void, dead button, or unreachable state. Confirm the empty economy renders
+ honestly end-to-end (no fabricated anything).
+3. **Accessibility.** Semantic HTML, ARIA on interactive elements, keyboard nav +
+ focus traps in panels, visible focus rings, color contrast, `prefers-reduced-
+ motion` honored in all 3D FX. Run an a11y pass (axe/Lighthouse).
+4. **Performance.** Lazy-load heavy modules + GLBs; paginate `citizens`; debounce
+ polls; pause render on hidden tab; **dispose** Three.js resources (no leak over
+ 30 min); code-split the Agora bundle. Lighthouse perf budget met; 60fps with a
+ busy board + a fleet.
+5. **Security + spend review.** `/api/agora/act` (and any mutating path):
+ authenticated, input-validated at the boundary, idempotent, rate-limited,
+ spend-capped; secrets never logged; mainnet $THREE behind explicit env +
+ confirmation. Run `/security-review` on the branch. Confirm the bundler trap
+ didn't bloat `api/*.js` (`head -1` check).
+6. **Deploy verification.** Build clean (`npm run build`, `npm run build:pages`);
+ confirm the worker image builds (`workers/agora-citizens` Docker/cloudbuild);
+ smoke the deployed `/api/agora/*` + `/agora` against real data; the life engine
+ runs on devnet in the deployed environment.
+7. **Docs + changelog + index.** Update `docs/agora.md` roadmap checkboxes to
+ reflect reality; mark task status in `00-INDEX.md`; ensure `data/pages.json`
+ has `/agora`; add the launch `data/changelog.json` entry (feature) and run
+ `npm run build:pages` (it validates the entry). After deploy,
+ `npm run changelog:push` (if creds present).
+8. **Final self-review.** Run the `completionist` agent on the changed files and
+ `/code-review` on the diff; resolve findings. Then the CLAUDE.md pride check.
+
+## Out of scope
+New features. This task only hardens, verifies, documents, and launches what
+exists. If you find a missing feature, file it as a new task file, don't scope-creep.
+
+## Definition of Done (the launch gate — all must be true)
+- [ ] `npm test` green, including new Agora tests; meaningful coverage of API,
+ engine, professions, MCP.
+- [ ] Every surface's loading/empty/error/populated/overflow states designed and
+ reachable; no blank voids, no dead paths.
+- [ ] Accessibility pass clean (keyboard, ARIA, contrast, focus, reduced-motion).
+- [ ] Performance: lazy-load + pagination + dispose verified; no leak over 30 min;
+ 60fps busy; Lighthouse budget met.
+- [ ] Security: mutating endpoints authed/validated/idempotent/rate-limited/spend-
+ capped; `/security-review` findings resolved; no secret logging; mainnet gated.
+- [ ] Deployed `/api/agora/*`, `/agora`, the worker, and `agora-mcp` all verified
+ against real data (paste evidence: URLs, tx signatures, screenshots).
+- [ ] `docs/agora.md` + `00-INDEX.md` statuses current; `data/changelog.json`
+ entry added + `build:pages` passes; `/agora` in `data/pages.json`.
+- [ ] `git diff` reviewed line-by-line; `completionist` + `/code-review` clean.
+- [ ] Pushed to **both** `threeD` and `threews`.
+- [ ] You would proudly demo Agora to a room of senior engineers.
+
+## Verification
+```bash
+npm test
+npm run build && npm run build:pages
+head -1 api/agora/*.js api/agenc/*.js # ensure no esbuild bundle bloat
+# a11y + perf: Lighthouse on /agora
+# deploy smoke: curl the live /api/agora/* ; load /agora ; run the engine on devnet
+```
+Then `completionist` on changed files + `/code-review` on the diff.
+
+## Guardrails
+- Do not relax any DoD box to "good enough." If something can't be verified, say so
+ explicitly and don't claim done.
+- `$THREE` only; no other coin anywhere (code, tests, fixtures, copy, changelog).
+- Stage explicit paths; re-check `git status`/`--staged` (concurrent agents share
+ the worktree). Push **both** remotes; **never** pull/fetch from `threeD`.
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 8e70a96a2..c2c2aac30 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -184,6 +184,24 @@ const TAG_IMMUNITY_MS = 2000;
const TAG_MIN_PLAYERS = 2;
const TAG_LB_INTERVAL_MS = 8000;
+// King of the Totem mini-game (R07). Server-authoritative area control: the SOLE
+// occupant of the king-zone at the totem base earns points each tick; two or more
+// inside is "contested" and nobody scores. Rounds run on a fixed timer with a
+// short intermission between them. The zone is centred on the totem (rendered at
+// world (0, -12) — see PROTECTED_POINTS) so its radius matches the client ring.
+// Occupancy is judged from the server's authoritative player positions, so a
+// client can never score from outside the zone. KING_TICK_MS is the scoring +
+// timer cadence; KING_POINTS_PER_SEC is awarded scaled by real elapsed time so a
+// dropped tick never over- or under-pays. A round needs ≥ KING_MIN_PLAYERS present
+// to start, but once running it tolerates players leaving down to zero (it simply
+// ends with no winner). Dead/downed players (W07) can't hold the zone.
+const KING_ZONE = { x: 0, z: -12, r: 3.5 };
+const KING_ROUND_MS = 90_000;
+const KING_INTERMISSION_MS = 12_000;
+const KING_TICK_MS = 1000;
+const KING_POINTS_PER_SEC = 10;
+const KING_MIN_PLAYERS = 1;
+
// Legacy disc radius — still used as the fallback drop clamp when a driver steps
// out of a vehicle (vehicles carry their own VEHICLE_WORLD_RADIUS_M bound).
const WORLD_RADIUS_M = 60;
@@ -384,6 +402,23 @@ export class WalkRoom extends Room {
// per session ({ timeMs: number, becameIt: epoch|null }).
this._tagImmunity = new Map();
this._tagTime = new Map();
+ // King of the Totem (R07): off-schema round + score state. `phase` is the
+ // round machine ('idle' waiting for players | 'active' round running |
+ // 'intermission' showing the winner). `scores` is sessionId → accumulated
+ // points for the CURRENT round (floats; rounded only for display). `kingId`
+ // is the current sole occupant (null when empty or contested). `winner` is
+ // the last completed round's result, surfaced during the intermission.
+ this._king = {
+ phase: 'idle',
+ roundId: 0,
+ startedAt: 0,
+ endsAt: 0,
+ nextAt: 0,
+ lastTickAt: 0,
+ scores: new Map(),
+ kingId: null,
+ winner: null,
+ };
}
async onCreate(options) {
@@ -578,6 +613,12 @@ export class WalkRoom extends Room {
this.clock.setInterval(() => {
this.broadcast('floor:beat', { clip: DANCE_FLOOR_CLIPS[_beatIdx++ % DANCE_FLOOR_CLIPS.length] });
}, 4000);
+
+ // King of the Totem (R07): the single authoritative clock that runs the round
+ // machine — awards points to a sole zone occupant, ends a round on time, and
+ // schedules the next one. One interval drives scoring, the countdown, and the
+ // idle→active→intermission transitions so the timing can never drift apart.
+ this.clock.setInterval(() => this._kingTick(), KING_TICK_MS);
}
async onJoin(client, options) {
@@ -668,6 +709,16 @@ export class WalkRoom extends Room {
if (this.state.players.size >= TAG_MIN_PLAYERS && !this._itPlayer()) {
this._assignIt(this._randomTagPlayer(null));
}
+
+ // King of the Totem (R07): give the new arrival a zero score row for the
+ // current round and immediately sync them the live game state (zone bounds,
+ // phase, countdown, scoreboard) so their HUD is correct mid-round instead of
+ // blank until the next broadcast. If the room was idle and now has enough
+ // players, the next tick starts a round; sync reflects that on the following
+ // beat. Sending zone + phase here is what lets a late joiner render the ring
+ // and timer without waiting up to a full second.
+ if (this._king.phase === 'active') this._king.scores.set(client.sessionId, 0);
+ this._sendKingSync(client);
}
onLeave(client) {
@@ -710,6 +761,15 @@ export class WalkRoom extends Room {
}
}
this._tagTime.delete(client.sessionId);
+ // King of the Totem (R07): drop their current-round score and demote them if
+ // they were holding the zone. Their accumulated points are forfeited (a player
+ // who leaves can't win), and the next tick re-evaluates occupancy from scratch,
+ // so a departing king never freezes the crown. The round itself keeps running.
+ this._king.scores.delete(client.sessionId);
+ if (this._king.kingId === client.sessionId) {
+ this._king.kingId = null;
+ if (this._king.phase === 'active') this._broadcastKing('tick');
+ }
this._moveCounters.delete(client.sessionId);
this._chatCooldowns.delete(client.sessionId);
this._editCounters?.delete(client.sessionId);
@@ -905,6 +965,137 @@ export class WalkRoom extends Room {
this.broadcast('tag', { event: 'state', itId, leaderboard: rows.slice(0, 8) });
}
+ // ─── King of the Totem helpers (R07) ────────────────────────────────────────
+
+ /** Sessions whose authoritative position is inside the king-zone right now.
+ * Read from the server's clamped positions (never client claims) and skip
+ * downed players, so the zone can't be held by a corpse or faked from afar. */
+ _kingOccupants() {
+ const inside = [];
+ for (const [id, p] of this.state.players) {
+ if (p.dead) continue;
+ const dx = p.x - KING_ZONE.x;
+ const dz = p.z - KING_ZONE.z;
+ if (Math.hypot(dx, dz) <= KING_ZONE.r) inside.push(id);
+ }
+ return inside;
+ }
+
+ /** The current-round scoreboard: present players sorted high→low, rounded for
+ * display, capped to the top 8 the HUD shows. A player with no points yet
+ * still appears (score 0) so the board reads as "everyone's in the running". */
+ _kingScoreRows() {
+ const rows = [];
+ for (const [id, p] of this.state.players) {
+ const score = this._king.scores.get(id) || 0;
+ rows.push({ id, name: p.name || id.slice(0, 6), score: Math.round(score) });
+ }
+ rows.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
+ return rows.slice(0, 8);
+ }
+
+ /** One authoritative beat: drives scoring, the countdown, and every phase
+ * transition. Idempotent per second — safe even if a tick is delayed. */
+ _kingTick() {
+ const now = Date.now();
+ const k = this._king;
+
+ if (k.phase === 'active') {
+ // Award the sole occupant points for the real time since the last tick
+ // (clamped so a stalled interval can't dump a huge lump sum). Contested
+ // (2+) or empty (0) means nobody scores and there's no king this beat.
+ const occ = this._kingOccupants();
+ if (occ.length === 1) {
+ const dt = Math.min(2, Math.max(0, (now - k.lastTickAt) / 1000));
+ const id = occ[0];
+ k.scores.set(id, (k.scores.get(id) || 0) + KING_POINTS_PER_SEC * dt);
+ k.kingId = id;
+ } else {
+ k.kingId = null;
+ }
+ k.lastTickAt = now;
+
+ if (now >= k.endsAt) this._endKingRound();
+ else this._broadcastKing('tick');
+ return;
+ }
+
+ if (k.phase === 'intermission') {
+ // Hold on the winner, then start the next round once enough players remain
+ // (otherwise drop back to idle and wait for arrivals).
+ if (now >= k.nextAt) {
+ if (this.state.players.size >= KING_MIN_PLAYERS) this._startKingRound();
+ else { k.phase = 'idle'; this._broadcastKing('idle'); }
+ }
+ return;
+ }
+
+ // idle: kick off a round as soon as the world has someone to play.
+ if (this.state.players.size >= KING_MIN_PLAYERS) this._startKingRound();
+ }
+
+ /** Begin a fresh round: reset scores, stamp the timer, announce the start. */
+ _startKingRound() {
+ const now = Date.now();
+ const k = this._king;
+ k.phase = 'active';
+ k.roundId += 1;
+ k.startedAt = now;
+ k.endsAt = now + KING_ROUND_MS;
+ k.lastTickAt = now;
+ k.kingId = null;
+ k.winner = null;
+ k.scores = new Map();
+ for (const [id] of this.state.players) k.scores.set(id, 0);
+ this._broadcastKing('start');
+ }
+
+ /** End the active round: pick the highest-scoring PRESENT player as winner
+ * (a score of 0 across the board ⇒ no winner — an honest "nobody held it"),
+ * enter the intermission, and announce the result so clients celebrate. */
+ _endKingRound() {
+ const now = Date.now();
+ const k = this._king;
+ const rows = this._kingScoreRows();
+ const top = rows.length && rows[0].score > 0 ? rows[0] : null;
+ k.winner = top ? { id: top.id, name: top.name, score: top.score } : null;
+ k.phase = 'intermission';
+ k.kingId = null;
+ k.nextAt = now + KING_INTERMISSION_MS;
+ this._broadcastKing('end');
+ }
+
+ /** Shared snapshot of the live game state for both broadcasts and per-client
+ * sync. Always carries the zone bounds so a client can render the ring without
+ * hardcoding them, plus the phase, countdown anchors, scoreboard and king. */
+ _kingSnapshot(event) {
+ const k = this._king;
+ return {
+ event,
+ phase: k.phase,
+ roundId: k.roundId,
+ now: Date.now(),
+ endsAt: k.endsAt,
+ nextAt: k.nextAt,
+ durationMs: KING_ROUND_MS,
+ zone: KING_ZONE,
+ kingId: k.kingId,
+ winner: k.winner,
+ scores: this._kingScoreRows(),
+ };
+ }
+
+ /** Broadcast the current game state to everyone in the room. */
+ _broadcastKing(event) {
+ this.broadcast('game:king', this._kingSnapshot(event));
+ }
+
+ /** Send the current game state to one client (on join), so a mid-round arrival
+ * sees the correct zone, timer and scoreboard immediately. */
+ _sendKingSync(client) {
+ try { this.send(client, 'game:king', this._kingSnapshot('sync')); } catch { /* best-effort */ }
+ }
+
// ─────────────────────────────────────────────────────────────────────────────
_checkZoneEntry(client) {
diff --git a/pages/agora.html b/pages/agora.html
new file mode 100644
index 000000000..ec64ee4f4
--- /dev/null
+++ b/pages/agora.html
@@ -0,0 +1,75 @@
+<!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" />
+ <title>Agora · the Commons · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <meta name="description" content="Agora — the Commons. A watchable world of AI agent and human citizens living, working, and earning $THREE on three.ws." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/agora" />
+ <meta property="og:title" content="Agora · the Commons · three.ws" />
+ <meta property="og:description" content="Watch the living economy — AI agent and human citizens at work in a 3D world, earning $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="Agora · the Commons · three.ws" />
+ <meta name="twitter:description" content="Watch the living economy — AI agent and human citizens at work in a 3D world, earning $THREE." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <meta name="theme-color" content="#060607" />
+ <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" />
+ <link rel="stylesheet" href="/src/agora/agora.css" />
+ </head>
+ <body>
+ <div id="agora-loading">
+ <div class="agora-loading-card">
+ <img src="/three.svg" alt="three.ws" width="38" height="38" />
+ <div class="agora-loading-title">AGORA</div>
+ <div class="agora-loading-sub" id="agora-loading-sub">Entering the Commons…</div>
+ <div class="agora-boot-bar" role="status" aria-label="Loading">
+ <span id="agora-boot-bar-fill"></span>
+ </div>
+ </div>
+ </div>
+
+ <canvas id="agora-canvas" tabindex="0" aria-label="The Commons — a 3D world of citizens. Use the citizen list to inspect individuals."></canvas>
+
+ <div id="agora-hud" style="display:none">
+ <div id="agora-hud-tl">
+ <img src="/three.svg" alt="" width="22" height="22" />
+ <span>AGORA</span>
+ <span id="agora-hud-sub">the Commons</span>
+ </div>
+
+ <div id="agora-pop">
+ <span id="agora-count" aria-live="polite">0</span>
+ <span id="agora-pop-label">citizens</span>
+ </div>
+
+ <div id="agora-controls-hint">
+ <kbd>Drag</kbd> orbit &nbsp;
+ <kbd>WASD</kbd> pan &nbsp;
+ <kbd>Scroll</kbd> zoom &nbsp;
+ <kbd>Click</kbd> a citizen
+ </div>
+ </div>
+
+ <!-- Designed empty / error states render here over the world. -->
+ <div id="agora-state" hidden></div>
+
+ <!-- Accessible roster: keyboard + screen-reader path to every citizen. -->
+ <nav id="agora-roster" aria-label="Citizens" class="agora-roster"></nav>
+
+ <script type="module" src="/src/agora/agora-world.js"></script>
+ <script src="/brand.js" defer></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index f8a78d7c4..ed79cdfb3 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T09:41:55.088Z",
+ "generated_at": "2026-06-24T10:16:06.859Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-24",
+ "type": "launch",
+ "title": "Agora — the Commons",
+ "summary": "A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.",
+ "link": "/agora",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-24",
"type": "launch",
@@ -233,6 +243,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-24",
+ "type": "update",
+ "title": "Build mode: place props in the 3D worlds",
+ "summary": "The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-24",
"type": "update",
@@ -274,6 +294,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-24",
+ "type": "update",
+ "title": "Play a game of Tag in the 3D worlds",
+ "summary": "The /play worlds now run a live game of Tag. When two or more people are in a world, one is made \"it\" — marked for everyone by a red glow ring at their feet and a 🏃 tag over their head. Walk up to someone while you're it and you pass it on; a short immunity stops it from instantly bouncing back, and there's no tagging from across the map. A HUD shows who's it, flashes \"YOU'RE IT!\" when it's you, and keeps a leaderboard of who has spent the most time as it this session. Every tag is checked on the server against real positions, so it can't be faked.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-24",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 2b38e9396..9156f3a66 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>feature</category>
<description>A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms.</description>
</item>
+ <item>
+ <title>Agora — the Commons</title>
+ <link>https://three.ws/agora</link>
+ <guid isPermaLink="false">2026-06-24:Agora — the Commons</guid>
+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.</description>
+ </item>
<item>
<title>Docs · SAS Credentialed Attestations</title>
<link>https://three.ws/docs/sas-attestations</link>
@@ -174,6 +182,14 @@
<category>sdk</category>
<description>A new Model Context Protocol server, @three-ws/loom-mcp, opens the Loom community gallery — the public feed of 3D models forged on three.ws — to any AI agent. Agents can browse the gallery newest-first, open any creation with a ready-made viewer and embed code, and submit their own forged GLB to share with everyone. Each creation comes back with a one-click /forge/embed viewer URL and a paste-ready iframe so a model can be previewed inline. It rounds out the 3D toolkit: generate or compose a model with the avatar and scene servers, then publish it to Loom for the whole platform to see. Submissions are public and lightly rate-limited; no account or key is needed.</description>
</item>
+ <item>
+ <title>Build mode: place props in the 3D worlds</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-06-24:Build mode: place props in the 3D worlds</guid>
+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The /play worlds now have a Build mode. Flip it on and a props palette opens: a set of hand-built pieces — crates, barrels, planters, lamps, benches, pillars, arches, ramps, signs, crystals, a stage and a pole — plus every public community model, which you can search and stream in. Pick a piece and a translucent preview follows your aim, snapped to a tidy grid so things line up; it glows green where it'll land and red where it won't. Press R (or the rotate button) to spin it a quarter-turn, then click to place. Whatever you place appears instantly for everyone else in the world and stays put when you leave and come back. Switch to remove mode to clear pieces you placed — you can only delete your own. It all works the same on desktop and on touch: tap to place, hold to remove, drag to look around.</description>
+ </item>
<item>
<title>Buy live $THREE market intel over x402 — right on the IBM partnership page</title>
<link>https://three.ws/bazaar</link>
@@ -206,6 +222,14 @@
<category>feature</category>
<description>$THREE is now a first-class payment token across every paid three.ws endpoint over x402, alongside USDC. When you pay, the wallet shows a token chooser: settle in USDC, or settle in $THREE on Solana. It works everywhere the 402 rail does — the paid Forge, the $THREE Town Oracle, and every service in the bazaar — because acceptance lives in the shared payment layer, not per-endpoint. The IBM partnership page's live demos now spell this out: pay a few cents in USDC, or in $THREE, from your own wallet. $THREE is priced at a flat per-call amount on Solana.</description>
</item>
+ <item>
+ <title>Play a game of Tag in the 3D worlds</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-06-24:Play a game of Tag in the 3D worlds</guid>
+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The /play worlds now run a live game of Tag. When two or more people are in a world, one is made &quot;it&quot; — marked for everyone by a red glow ring at their feet and a 🏃 tag over their head. Walk up to someone while you're it and you pass it on; a short immunity stops it from instantly bouncing back, and there's no tagging from across the map. A HUD shows who's it, flashes &quot;YOU'RE IT!&quot; when it's you, and keeps a leaderboard of who has spent the most time as it this session. Every tag is checked on the server against real positions, so it can't be faked.</description>
+ </item>
<item>
<title>Play Coin Clash from any AI agent over MCP</title>
<link>https://three.ws/clash</link>
diff --git a/public/features.json b/public/features.json
index 588a5ed20..678da1d76 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T09:41:55.075Z",
+ "generated_at": "2026-06-24T10:16:06.842Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -232,6 +232,16 @@
"title": "Build",
"description": "Create and customize an agent.",
"pages": [
+ {
+ "path": "/agora",
+ "title": "Agora — the Commons",
+ "description": "A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.",
+ "added": "2026-06-24",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/start",
"title": "Get Started",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index d86c59025..932e1dd9b 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -143,6 +143,12 @@ Recent activity from the people and agents you follow on three.ws.
Create and customize an agent.
+### Agora — the Commons
+
+URL: https://three.ws/agora
+
+A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.
+
### Get Started
URL: https://three.ws/start
diff --git a/public/llms.txt b/public/llms.txt
index a711a645c..80f7d0d73 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -37,6 +37,7 @@ Entry points into the product.
Create and customize an agent.
+- [Agora — the Commons](https://three.ws/agora): A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.
- [Create Agent](https://three.ws/create): Wizard for building a new agent: avatar, brain (LLM + prompt), skills, and on-chain identity.
- [Agent Genome — breed two agents](https://three.ws/genome): Breed two AI agents into a provably-inherited offspring. The child inherits a recombination of both parents' brain, voice, body, and on-chain skill licenses — each breeding event seed-recorded so the lineage is re-derivable and forgery-detectable, with a verifiable family tree on every parent and child.
- [Instant Agent Genesis](https://three.ws/genesis): A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana + EVM wallet and a verifiable on-chain identity — in under a minute, owned by you.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index ae330bfe7..3d455a8a0 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 336 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 337 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 336 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 337 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -252,10 +252,17 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>39</span></h2>
+ <h2>Build<span class="sm-count" data-count>40</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
+ <li>
+ <a href="/agora">
+ <span class="sm-title">Agora — the Commons</span>
+ <span class="sm-path">/agora</span>
+ <span class="sm-desc">A watchable 3D world where AI agent and human citizens live, work, and earn $THREE. Walk the square, inspect any citizen's passport, and watch the economy come alive.</span>
+ </a>
+ </li>
<li>
<a href="/start">
<span class="sm-title">Get Started<span class="sm-badge sm-badge-internal">internal</span></span>
diff --git a/src/agora/agora-world.js b/src/agora/agora-world.js
new file mode 100644
index 000000000..0f8713122
--- /dev/null
+++ b/src/agora/agora-world.js
@@ -0,0 +1,309 @@
+// /agora — the Commons. The watchable world layer over the City substrate.
+//
+// Reuses the City's scene/renderer/camera (src/city/city-scene.js) and its OSM
+// Manhattan geometry (src/city/city-map.js), then adds a *population*: every real
+// citizen from /api/agora/citizens, rendered as an animated avatar standing in
+// the square with a name + profession label. Click (or keyboard-focus) a citizen
+// to open its passport. Empty / loading / error states are all designed.
+//
+// This is the shell Tasks 06–08 hang the economy visuals and interactions on; it
+// renders the people and their identities, nothing fabricated.
+
+import * as THREE from 'three';
+import { fetchOSMData, buildCity, CITY_HALF } from '../city/city-map.js';
+import { createCityScene, bindResize } from '../city/city-scene.js';
+import { CityCamera } from '../city/city-camera.js';
+import { CitizenPopulation } from './citizen-avatar.js';
+import { PassportPanel } from './passport-panel.js';
+import { log } from '../shared/log.js';
+
+// ── DOM refs ────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('agora-canvas');
+const loadingEl = document.getElementById('agora-loading');
+const subEl = document.getElementById('agora-loading-sub');
+const barEl = document.getElementById('agora-boot-bar-fill');
+const hudEl = document.getElementById('agora-hud');
+const countEl = document.getElementById('agora-count');
+const stateEl = document.getElementById('agora-state');
+const rosterEl = document.getElementById('agora-roster');
+
+const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
+const PAN_BOUNDS = CITY_HALF - 20;
+const PAN_SPEED = 26; // m/s for WASD spectator panning
+
+function progress(pct, label) {
+ if (barEl) barEl.style.width = pct + '%';
+ if (subEl) subEl.textContent = label;
+}
+
+// Deterministic phyllotaxis (golden-angle) layout — the honest fallback when a
+// citizen has no world position yet (position 0,0). Spreads the fleet in a tidy
+// spiral around the plaza so nobody stacks on the origin.
+function layoutPosition(i) {
+ const GOLDEN = 2.399963229728653;
+ const a = i * GOLDEN;
+ const r = 2.6 * Math.sqrt(i + 0.6);
+ return { x: Math.cos(a) * r, z: Math.sin(a) * r };
+}
+
+function citizenPosition(citizen, i) {
+ const x = Number(citizen.position?.x);
+ const z = Number(citizen.position?.z);
+ if (Number.isFinite(x) && Number.isFinite(z) && (x !== 0 || z !== 0)) {
+ // Clamp into the walkable square so a stray seed can't fling someone past
+ // the buildings.
+ return {
+ x: Math.max(-PAN_BOUNDS, Math.min(PAN_BOUNDS, x)),
+ z: Math.max(-PAN_BOUNDS, Math.min(PAN_BOUNDS, z)),
+ };
+ }
+ return layoutPosition(i);
+}
+
+async function main() {
+ progress(6, 'Setting up renderer…');
+ const { renderer, scene, camera } = createCityScene(canvas);
+
+ progress(20, 'Loading Manhattan…');
+ let osmData;
+ try {
+ osmData = await fetchOSMData((frac, label) => progress(20 + frac * 34, label));
+ } catch (err) {
+ log.error('[agora] OSM fetch failed — empty world', err);
+ osmData = { elements: [] };
+ }
+
+ progress(56, 'Building the square…');
+ buildCity(scene, osmData);
+
+ // Free-orbit spectator camera over the square. We reuse the City's orbit
+ // camera but drive it with a movable focus point (WASD pans, selecting a
+ // citizen glides the focus to them) instead of a player avatar.
+ const cityCamera = new CityCamera(camera, canvas);
+ const focus = new THREE.Vector3(0, 0, 0);
+ let focusGoal = null; // when set, focus eases toward it (cleared on manual pan)
+ camera.position.set(0, 16, 30);
+
+ canvas.addEventListener('contextmenu', (e) => e.preventDefault());
+ bindResize(renderer, camera);
+
+ // ── Spectator panning input ───────────────────────────────────────────────
+ const keys = new Set();
+ const PAN_KEYS = new Set(['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright']);
+ window.addEventListener('keydown', (e) => {
+ const k = e.key.toLowerCase();
+ if (!PAN_KEYS.has(k)) return;
+ if (document.activeElement && document.activeElement.tagName === 'BUTTON') return; // let roster nav work
+ if (k.startsWith('arrow')) e.preventDefault();
+ keys.add(k);
+ focusGoal = null;
+ });
+ window.addEventListener('keyup', (e) => keys.delete(e.key.toLowerCase()));
+
+ // ── Population ────────────────────────────────────────────────────────────
+ const population = new CitizenPopulation({ renderer, scene, reducedMotion: REDUCED_MOTION });
+ const passport = new PassportPanel();
+ const raycaster = new THREE.Raycaster();
+ const pointer = new THREE.Vector2();
+ let hoverId = null;
+
+ function openPassport(id, trigger) {
+ const inst = population.getInstance(id);
+ population.highlight(id);
+ // Glide the camera to frame the inspected citizen.
+ const p = population.worldPosition(id);
+ if (p) focusGoal = p.clone();
+ passport.open(id, {
+ trigger,
+ hint: inst?.citizen || null,
+ onClose: () => { if (population.selectedId === id) population.highlight(null); },
+ });
+ }
+
+ // Pointer → ray. Distinguish a click from a camera-orbit drag.
+ let downX = 0, downY = 0, downT = 0;
+ canvas.addEventListener('pointerdown', (e) => { downX = e.clientX; downY = e.clientY; downT = performance.now(); });
+ canvas.addEventListener('pointerup', (e) => {
+ const moved = Math.hypot(e.clientX - downX, e.clientY - downY);
+ if (moved > 6 || performance.now() - downT > 500) return; // a drag, not a click
+ const id = pickAt(e.clientX, e.clientY);
+ if (id) openPassport(id, null);
+ });
+
+ let lastHoverRay = 0;
+ canvas.addEventListener('pointermove', (e) => {
+ const now = performance.now();
+ if (now - lastHoverRay < 60) return; // throttle hit-testing
+ lastHoverRay = now;
+ const id = pickAt(e.clientX, e.clientY);
+ hoverId = id;
+ canvas.style.cursor = id ? 'pointer' : 'grab';
+ });
+
+ function pickAt(clientX, clientY) {
+ const rect = canvas.getBoundingClientRect();
+ pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
+ raycaster.setFromCamera(pointer, camera);
+ return population.pick(raycaster);
+ }
+
+ // ── Fetch + populate (re-runnable for the error-state retry) ───────────────
+ async function loadCitizens() {
+ hideState();
+ try {
+ const res = await fetch('/api/agora/citizens?limit=200', { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const citizens = Array.isArray(data.citizens) ? data.citizens : [];
+
+ if (!citizens.length || data.empty) {
+ revealWorld();
+ showEmptyState();
+ updateCount(0);
+ return;
+ }
+
+ revealWorld();
+ updateCount(citizens.length);
+ buildRoster(citizens);
+
+ // Progressive populate: each avatar fades in as its GLB resolves. Loads
+ // are pooled inside CitizenPopulation so the fleet streams in smoothly.
+ let placed = 0;
+ await Promise.all(citizens.map(async (citizen, i) => {
+ const inst = await population.add(citizen, citizenPosition(citizen, i));
+ if (inst) { placed++; updateCount(placed, citizens.length); }
+ }));
+ updateCount(population.count);
+ } catch (err) {
+ log.warn('[agora] citizens fetch failed', err?.message);
+ revealWorld();
+ showErrorState(err?.message || 'The registry could not be reached.');
+ }
+ }
+
+ // ── Accessible roster (keyboard + screen reader) ──────────────────────────
+ // One focusable button per citizen, visually hidden but reachable by Tab.
+ // Focus highlights the avatar; Enter/Space opens its passport.
+ function buildRoster(citizens) {
+ rosterEl.innerHTML = `<h2 class="agora-sr-only">Citizens of the Commons</h2>`;
+ const list = document.createElement('ul');
+ list.className = 'agora-roster-list';
+ for (const c of citizens) {
+ const li = document.createElement('li');
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'agora-roster-btn';
+ btn.dataset.id = c.id;
+ const prof = c.professions?.[0]?.label || c.profession || 'Citizen';
+ btn.textContent = `Inspect ${c.displayName || 'citizen'} — ${prof}`;
+ btn.addEventListener('focus', () => {
+ population.highlight(c.id);
+ const p = population.worldPosition(c.id);
+ if (p) focusGoal = p.clone();
+ });
+ btn.addEventListener('click', () => openPassport(c.id, btn));
+ li.appendChild(btn);
+ list.appendChild(li);
+ }
+ rosterEl.appendChild(list);
+ }
+
+ // ── State overlays ────────────────────────────────────────────────────────
+ function hideState() { stateEl.hidden = true; stateEl.innerHTML = ''; }
+
+ function showEmptyState() {
+ stateEl.hidden = false;
+ stateEl.innerHTML = `
+ <div class="agora-state-card">
+ <div class="agora-state-glyph" aria-hidden="true">◍</div>
+ <h2>The Commons is quiet</h2>
+ <p>No citizens have settled here yet. Agora is a real economy of AI agents and
+ humans — when the life engine seeds the first citizens, they'll appear in the
+ square, living their daily loop.</p>
+ <div class="agora-state-actions">
+ <a class="agora-btn agora-btn-primary" href="/docs/agora.md">How the Commons works</a>
+ <a class="agora-btn" href="/city">Visit the City</a>
+ </div>
+ </div>`;
+ }
+
+ function showErrorState(detail) {
+ stateEl.hidden = false;
+ stateEl.innerHTML = `
+ <div class="agora-state-card">
+ <div class="agora-state-glyph agora-state-glyph-error" aria-hidden="true">!</div>
+ <h2>Couldn't reach the Commons</h2>
+ <p>${detail.replace(/[<>&]/g, '')}</p>
+ <div class="agora-state-actions">
+ <button class="agora-btn agora-btn-primary" type="button" id="agora-retry">Try again</button>
+ </div>
+ </div>`;
+ stateEl.querySelector('#agora-retry')?.addEventListener('click', loadCitizens);
+ }
+
+ function updateCount(n, total) {
+ if (!countEl) return;
+ countEl.textContent = total && total !== n ? `${n} / ${total}` : String(n);
+ }
+
+ function revealWorld() {
+ if (loadingEl.classList.contains('hidden')) return;
+ loadingEl.classList.add('hidden');
+ hudEl.style.display = '';
+ setTimeout(() => { loadingEl.style.display = 'none'; }, 480);
+ }
+
+ progress(72, 'Gathering citizens…');
+ // Kick off the population fetch; the world reveals as soon as we know its state.
+ loadCitizens();
+ progress(100, 'Entering the Commons…');
+
+ // ── Render loop ───────────────────────────────────────────────────────────
+ const clock = new THREE.Timer();
+ (function tick() {
+ requestAnimationFrame(tick);
+ clock.update();
+ const dt = Math.min(clock.getDelta(), 0.05);
+
+ // Spectator panning (camera-relative), unless easing toward a selection.
+ let px = 0, pz = 0;
+ const yaw = cityCamera.yaw;
+ if (keys.has('w') || keys.has('arrowup')) { px -= Math.sin(yaw); pz -= Math.cos(yaw); }
+ if (keys.has('s') || keys.has('arrowdown')) { px += Math.sin(yaw); pz += Math.cos(yaw); }
+ if (keys.has('a') || keys.has('arrowleft')) { px -= Math.cos(yaw); pz += Math.sin(yaw); }
+ if (keys.has('d') || keys.has('arrowright')) { px += Math.cos(yaw); pz -= Math.sin(yaw); }
+ if (px !== 0 || pz !== 0) {
+ const len = Math.hypot(px, pz);
+ focus.x = clampPan(focus.x + (px / len) * PAN_SPEED * dt);
+ focus.z = clampPan(focus.z + (pz / len) * PAN_SPEED * dt);
+ } else if (focusGoal) {
+ focus.lerp(focusGoal, Math.min(1, dt * 4));
+ if (focus.distanceTo(focusGoal) < 0.15) focusGoal = null;
+ }
+
+ cityCamera.update(focus, 1.7);
+ population.update(dt);
+ renderer.render(scene, camera);
+ })();
+}
+
+function clampPan(v) { return Math.max(-PAN_BOUNDS, Math.min(PAN_BOUNDS, v)); }
+
+main().catch((err) => {
+ log.error('[agora] fatal', err);
+ if (stateEl) {
+ loadingEl?.classList.add('hidden');
+ stateEl.hidden = false;
+ stateEl.innerHTML = `
+ <div class="agora-state-card">
+ <div class="agora-state-glyph agora-state-glyph-error" aria-hidden="true">!</div>
+ <h2>The Commons failed to load</h2>
+ <p>Something went wrong building the world. Reload to try again.</p>
+ <div class="agora-state-actions">
+ <button class="agora-btn agora-btn-primary" type="button" onclick="location.reload()">Reload</button>
+ </div>
+ </div>`;
+ }
+});
diff --git a/src/agora/agora.css b/src/agora/agora.css
new file mode 100644
index 000000000..b5bdc4507
--- /dev/null
+++ b/src/agora/agora.css
@@ -0,0 +1,404 @@
+/* Agora — the Commons. Styling for the 3D world shell: loading, HUD, designed
+ empty/error states, the accessible citizen roster, and the passport panel.
+ Built on the City substrate's visual language (see src/city/city.css). */
+
+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+
+html, body {
+ width: 100%; height: 100%;
+ overflow: hidden;
+ background: #060607;
+ font-family: 'Inter', ui-sans-serif, system-ui, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ color: #fff;
+}
+
+/* ── Canvas ─────────────────────────────────────────────────────────────────── */
+#agora-canvas {
+ position: fixed; inset: 0;
+ width: 100%; height: 100%;
+ display: block;
+ outline: none;
+ cursor: grab;
+}
+#agora-canvas:active { cursor: grabbing; }
+#agora-canvas:focus-visible { box-shadow: inset 0 0 0 2px rgba(120, 170, 255, 0.6); }
+
+/* ── Loading screen ─────────────────────────────────────────────────────────── */
+#agora-loading {
+ position: fixed; inset: 0;
+ display: flex; align-items: center; justify-content: center;
+ background: #060607;
+ z-index: 100;
+ transition: opacity 0.5s ease;
+}
+#agora-loading.hidden { opacity: 0; pointer-events: none; }
+
+.agora-loading-card {
+ display: flex; flex-direction: column; align-items: center;
+ gap: 14px;
+}
+.agora-loading-title {
+ font-size: 11px; font-weight: 700;
+ letter-spacing: 0.34em;
+ color: rgba(255, 255, 255, 0.42);
+ text-transform: uppercase;
+}
+.agora-loading-sub {
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.28);
+ letter-spacing: 0.06em;
+ min-height: 18px;
+}
+.agora-boot-bar {
+ width: 170px; height: 2px;
+ background: rgba(255, 255, 255, 0.06);
+ border-radius: 2px;
+ overflow: hidden;
+}
+.agora-boot-bar span {
+ display: block; height: 100%; width: 0%;
+ background: linear-gradient(90deg, #6da1ff, #9b8cff);
+ border-radius: 2px;
+ transition: width 0.35s ease;
+}
+
+/* ── HUD ─────────────────────────────────────────────────────────────────────── */
+#agora-hud {
+ position: fixed; inset: 0;
+ pointer-events: none;
+ z-index: 10;
+}
+
+#agora-hud-tl {
+ position: absolute; top: 18px; left: 20px;
+ display: flex; align-items: center; gap: 8px;
+ font-size: 11px; font-weight: 700;
+ letter-spacing: 0.25em;
+ color: rgba(255, 255, 255, 0.5);
+ text-transform: uppercase;
+ user-select: none;
+}
+#agora-hud-sub {
+ letter-spacing: 0.12em;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.3);
+ text-transform: none;
+}
+
+#agora-pop {
+ position: absolute; bottom: 18px; left: 20px;
+ display: flex; align-items: baseline; gap: 6px;
+ padding: 8px 14px;
+ background: rgba(10, 12, 16, 0.55);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ backdrop-filter: blur(8px);
+ user-select: none;
+}
+#agora-count { font-size: 18px; font-weight: 700; color: #fff; font-variant-numeric: tabular-nums; }
+#agora-pop-label { font-size: 11px; letter-spacing: 0.08em; color: rgba(255, 255, 255, 0.4); text-transform: uppercase; }
+
+#agora-controls-hint {
+ position: absolute; top: 18px; right: 20px;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.28);
+ letter-spacing: 0.05em;
+ user-select: none;
+ line-height: 1.6;
+ text-align: right;
+}
+#agora-controls-hint kbd {
+ font-family: ui-monospace, monospace;
+ font-size: 9px;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 3px;
+ padding: 1px 4px;
+ margin-right: 2px;
+}
+
+/* ── State overlays (empty / error / fatal) ──────────────────────────────────── */
+#agora-state {
+ position: fixed; inset: 0;
+ display: flex; align-items: center; justify-content: center;
+ z-index: 40;
+ padding: 24px;
+ background: radial-gradient(ellipse at center, rgba(6, 6, 7, 0.4), rgba(6, 6, 7, 0.78));
+ pointer-events: none;
+}
+.agora-state-card {
+ pointer-events: auto;
+ max-width: 440px;
+ text-align: center;
+ background: rgba(14, 16, 22, 0.82);
+ border: 1px solid rgba(255, 255, 255, 0.09);
+ border-radius: 18px;
+ padding: 36px 32px;
+ backdrop-filter: blur(16px);
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.5);
+ animation: agora-rise 0.4s ease both;
+}
+@keyframes agora-rise { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
+.agora-state-glyph {
+ width: 56px; height: 56px;
+ margin: 0 auto 18px;
+ display: grid; place-items: center;
+ font-size: 26px;
+ border-radius: 16px;
+ background: rgba(109, 161, 255, 0.12);
+ color: #8fb4ff;
+ border: 1px solid rgba(109, 161, 255, 0.25);
+}
+.agora-state-glyph-error {
+ background: rgba(255, 120, 120, 0.1);
+ color: #ff9a9a;
+ border-color: rgba(255, 120, 120, 0.25);
+ font-weight: 700;
+}
+.agora-state-card h2 { font-size: 20px; font-weight: 700; margin-bottom: 10px; letter-spacing: -0.01em; }
+.agora-state-card p { font-size: 14px; line-height: 1.6; color: rgba(255, 255, 255, 0.62); }
+.agora-state-actions {
+ margin-top: 22px;
+ display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;
+}
+
+.agora-btn {
+ display: inline-flex; align-items: center; justify-content: center;
+ padding: 9px 16px;
+ font-size: 13px; font-weight: 600;
+ color: rgba(255, 255, 255, 0.82);
+ text-decoration: none;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 10px;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
+}
+.agora-btn:hover { background: rgba(255, 255, 255, 0.1); border-color: rgba(255, 255, 255, 0.2); }
+.agora-btn:active { transform: translateY(1px); }
+.agora-btn:focus-visible { outline: 2px solid #7aa6ff; outline-offset: 2px; }
+.agora-btn-primary {
+ color: #fff;
+ background: linear-gradient(135deg, #5d8bff, #8a6dff);
+ border-color: transparent;
+}
+.agora-btn-primary:hover { filter: brightness(1.08); background: linear-gradient(135deg, #5d8bff, #8a6dff); }
+
+/* ── Accessible roster (visually hidden, focus-revealed) ──────────────────────── */
+.agora-roster { position: fixed; z-index: 60; }
+.agora-roster-list { list-style: none; }
+.agora-sr-only,
+.agora-roster-btn {
+ position: absolute;
+ width: 1px; height: 1px;
+ padding: 0; margin: -1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ border: 0;
+}
+/* When a roster button is focused by keyboard, surface it as a visible chip so
+ sighted keyboard users see where they are. */
+.agora-roster-btn:focus-visible {
+ position: fixed;
+ top: 16px; left: 50%;
+ transform: translateX(-50%);
+ width: auto; height: auto;
+ clip: auto; margin: 0;
+ padding: 9px 16px;
+ font: 600 13px/1 'Inter', system-ui, sans-serif;
+ color: #fff;
+ background: rgba(14, 16, 22, 0.92);
+ border: 1px solid #7aa6ff;
+ border-radius: 10px;
+ box-shadow: 0 8px 30px rgba(0, 0, 0, 0.5);
+ outline: 2px solid #7aa6ff;
+ outline-offset: 2px;
+ cursor: pointer;
+ z-index: 70;
+}
+
+/* ── Passport panel ───────────────────────────────────────────────────────────── */
+.agora-passport {
+ position: fixed;
+ top: 14px; right: 14px; bottom: 14px;
+ width: 372px; max-width: calc(100vw - 28px);
+ z-index: 50;
+ display: flex; flex-direction: column;
+ background: rgba(13, 15, 20, 0.9);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 18px;
+ backdrop-filter: blur(20px);
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.55);
+ overflow: hidden;
+ transform: translateX(24px);
+ opacity: 0;
+ transition: transform 0.28s cubic-bezier(0.2, 0.7, 0.2, 1), opacity 0.28s ease;
+}
+.agora-passport.open { transform: none; opacity: 1; }
+
+.agora-passport-head {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 16px 18px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+ flex-shrink: 0;
+}
+.agora-passport-head h2 {
+ font-size: 15px; font-weight: 700;
+ letter-spacing: -0.01em;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.agora-passport-close {
+ display: grid; place-items: center;
+ width: 30px; height: 30px;
+ color: rgba(255, 255, 255, 0.55);
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 8px;
+ cursor: pointer;
+ flex-shrink: 0;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+.agora-passport-close:hover { background: rgba(255, 255, 255, 0.1); color: #fff; }
+.agora-passport-close:focus-visible { outline: 2px solid #7aa6ff; outline-offset: 2px; }
+
+.agora-passport-body {
+ padding: 18px;
+ overflow-y: auto;
+ flex: 1;
+ outline: none;
+}
+
+.agora-pp-hero {
+ display: flex; align-items: center; gap: 12px;
+ margin-bottom: 18px;
+}
+.agora-pp-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; box-shadow: 0 0 12px currentColor; }
+.agora-pp-name { font-size: 18px; font-weight: 700; letter-spacing: -0.01em; }
+.agora-pp-prof { font-size: 12px; color: rgba(255, 255, 255, 0.5); margin-top: 2px; }
+.agora-pp-status {
+ margin-left: auto;
+ font-size: 10px; font-weight: 700;
+ letter-spacing: 0.08em; text-transform: uppercase;
+ padding: 4px 9px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(255, 255, 255, 0.7);
+ white-space: nowrap;
+}
+.agora-pp-status-active { background: rgba(54, 211, 153, 0.16); color: #5fe3ad; }
+.agora-pp-status-busy { background: rgba(255, 209, 102, 0.16); color: #ffd166; }
+.agora-pp-status-idle { background: rgba(159, 180, 204, 0.14); color: #b6c6da; }
+.agora-pp-status-suspended,
+.agora-pp-status-inactive { background: rgba(255, 120, 120, 0.14); color: #ff9a9a; }
+
+.agora-pp-stats {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
+ margin-bottom: 16px;
+}
+.agora-pp-stat {
+ padding: 12px 14px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 12px;
+}
+.agora-pp-stat-value { font-size: 16px; font-weight: 700; font-variant-numeric: tabular-nums; }
+.agora-pp-stat-label { font-size: 10px; letter-spacing: 0.06em; text-transform: uppercase; color: rgba(255, 255, 255, 0.42); margin-top: 3px; }
+
+.agora-pp-identity { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 18px; }
+.agora-pp-chip {
+ font-size: 11px; font-weight: 500;
+ padding: 4px 10px;
+ border-radius: 999px;
+ background: rgba(120, 160, 255, 0.1);
+ border: 1px solid rgba(120, 160, 255, 0.2);
+ color: #aac4ff;
+}
+
+.agora-pp-section {
+ font-size: 11px; font-weight: 700;
+ letter-spacing: 0.1em; text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.4);
+ margin: 6px 0 12px;
+}
+.agora-pp-empty { font-size: 13px; line-height: 1.6; color: rgba(255, 255, 255, 0.5); }
+
+.agora-pp-feed { list-style: none; display: flex; flex-direction: column; gap: 12px; }
+.agora-pp-feed-item { display: flex; gap: 10px; }
+.agora-pp-feed-kind {
+ width: 8px; height: 8px; margin-top: 5px; border-radius: 50%;
+ flex-shrink: 0;
+ background: rgba(255, 255, 255, 0.3);
+}
+.agora-pp-feed-kind[data-kind="completed_task"], .agora-pp-feed-kind[data-kind="earned"] { background: #5fe3ad; }
+.agora-pp-feed-kind[data-kind="claimed_task"] { background: #ffd166; }
+.agora-pp-feed-kind[data-kind="posted_task"] { background: #6da1ff; }
+.agora-pp-feed-kind[data-kind="slashed"] { background: #ff7878; }
+.agora-pp-feed-main { min-width: 0; }
+.agora-pp-feed-title { font-size: 13px; line-height: 1.45; color: rgba(255, 255, 255, 0.86); }
+.agora-pp-feed-meta { font-size: 11px; color: rgba(255, 255, 255, 0.42); margin-top: 2px; }
+.agora-pp-rep { color: #5fe3ad; }
+
+/* Loading skeleton */
+.agora-pp-skel { display: flex; flex-direction: column; gap: 8px; }
+.agora-pp-skel-row { height: 56px; border-radius: 12px; }
+.agora-pp-skel-line { height: 14px; border-radius: 6px; width: 100%; }
+.agora-pp-skel-line:nth-child(2) { width: 80%; }
+.agora-pp-skel-line:nth-child(3) { width: 60%; }
+.agora-pp-skel-row, .agora-pp-skel-line {
+ background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.08) 37%, rgba(255,255,255,0.04) 63%);
+ background-size: 400% 100%;
+ animation: agora-shimmer 1.4s ease infinite;
+}
+@keyframes agora-shimmer { 0% { background-position: 100% 0; } 100% { background-position: 0 0; } }
+
+.agora-pp-state { text-align: center; padding: 32px 8px; }
+.agora-pp-state-icon {
+ width: 44px; height: 44px; margin: 0 auto 14px;
+ display: grid; place-items: center;
+ font-size: 22px; font-weight: 700;
+ border-radius: 12px;
+ background: rgba(255, 120, 120, 0.1);
+ color: #ff9a9a;
+}
+.agora-pp-state-title { font-size: 15px; font-weight: 600; margin-bottom: 6px; }
+.agora-pp-state-detail { font-size: 13px; color: rgba(255, 255, 255, 0.5); line-height: 1.5; margin-bottom: 16px; }
+.agora-pp-retry {
+ font: 600 13px/1 'Inter', system-ui, sans-serif;
+ color: #fff; cursor: pointer;
+ padding: 9px 18px; border-radius: 10px;
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ transition: background 0.15s ease;
+}
+.agora-pp-retry:hover { background: rgba(255, 255, 255, 0.14); }
+.agora-pp-retry:focus-visible { outline: 2px solid #7aa6ff; outline-offset: 2px; }
+.agora-pp-srhint { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
+
+/* ── Responsive ───────────────────────────────────────────────────────────────── */
+@media (max-width: 560px) {
+ .agora-passport {
+ top: auto; left: 10px; right: 10px; bottom: 10px;
+ width: auto;
+ max-height: 64vh;
+ transform: translateY(24px);
+ }
+ .agora-passport.open { transform: none; }
+ #agora-controls-hint { display: none; }
+ .agora-state-card { padding: 28px 22px; }
+}
+
+@media (max-width: 380px) {
+ .agora-pp-stats { grid-template-columns: 1fr; }
+}
+
+/* ── Reduced motion ───────────────────────────────────────────────────────────── */
+@media (prefers-reduced-motion: reduce) {
+ #agora-loading,
+ .agora-passport,
+ .agora-state-card,
+ .agora-boot-bar span,
+ .agora-pp-skel-row, .agora-pp-skel-line { transition: none !important; animation: none !important; }
+ .agora-passport { transform: none; }
+}
diff --git a/src/agora/citizen-avatar.js b/src/agora/citizen-avatar.js
new file mode 100644
index 000000000..130717b3c
--- /dev/null
+++ b/src/agora/citizen-avatar.js
@@ -0,0 +1,428 @@
+// Agora citizens — the living population of the Commons.
+//
+// Each citizen from /api/agora/citizens is rendered as an avatar standing in the
+// City square: its real `avatarUrl` GLB, canonicalized + retargeted so the shared
+// idle clip drives any rig, with a billboarded name + profession label above its
+// head. This module owns the *crowd*: loading, pooling, the per-frame loop, and
+// hit-testing. Selection state, the passport panel, and accessibility chrome live
+// in src/agora/agora-world.js.
+//
+// Performance is the whole game (the DoD asks for 50 citizens at 60fps):
+// • Each unique avatar GLB is loaded ONCE and its idle/walk clips retargeted
+// ONCE (via AnimationManager). Every citizen wearing that GLB is a cheap
+// SkeletonUtils clone driven by a bare AnimationMixer reusing those bound
+// clips — N mixers, not N retargets. (Same proven pattern as src/club-crowd.js.)
+// • Clip JSON is fetched once and shared across every template.
+// • Concurrent GLB loads are capped so a 50-strong fleet doesn't open 50 sockets.
+// • A rig the canonical library can't drive still renders (the model is shown),
+// it just holds its authored pose instead of idling — never a T-pose void.
+
+import {
+ AnimationMixer, Box3, CanvasTexture, Group, Mesh, RingGeometry,
+ MeshBasicMaterial, Sprite, SpriteMaterial, Vector3, DoubleSide, SRGBColorSpace,
+} from 'three';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
+import { gltfLoader } from '../loaders/gltf.js';
+import { AnimationManager } from '../animation-manager.js';
+import { loadManifest, getLocomotionDefs, resolveAvatarUrl, CLIP_IDLE } from '../game/avatar-rig.js';
+import { log } from '../shared/log.js';
+
+// Target on-screen height so wildly-scaled GLBs all read as people in the square.
+const AVATAR_HEIGHT = 1.74;
+// Cap simultaneous GLB fetch+parse so a big fleet loads progressively instead of
+// saturating the network and stalling the first frame.
+const MAX_CONCURRENT_LOADS = 4;
+const FADE_IN_SEC = 0.55;
+
+// Profession → accent colour. Keys match the API's profession keys
+// (api/agora/[action].js PROFESSIONS). Used for the label chip and selection ring
+// so the labour market is legible at a glance. Unknown professions fall back to a
+// neutral platform accent — open by design, never a hardcoded allowlist gate.
+export const PROFESSION_COLORS = {
+ fetcher: '#4ea1ff',
+ sculptor: '#ff8a5c',
+ scribe: '#9b8cff',
+ cartographer: '#36d399',
+ crier: '#ff6fae',
+ appraiser: '#ffd166',
+ verifier: '#5ce0d8',
+ namekeeper: '#c0a6ff',
+};
+const NEUTRAL_ACCENT = '#9fb4cc';
+
+export function professionColor(profession) {
+ return PROFESSION_COLORS[String(profession || '').toLowerCase()] || NEUTRAL_ACCENT;
+}
+
+const _box = new Box3();
+const _v = new Vector3();
+
+function scaleToHeight(obj, h) {
+ _box.setFromObject(obj, true);
+ const cur = _box.max.y - _box.min.y || 1;
+ obj.scale.multiplyScalar(h / cur);
+}
+function groundFeet(obj) {
+ _box.setFromObject(obj, true);
+ if (Number.isFinite(_box.min.y)) obj.position.y -= _box.min.y;
+}
+
+// Build a crisp, high-DPI billboard label: bold name over a profession chip.
+// Returns a Sprite that always faces the camera (sizeAttenuation on, so distant
+// labels recede naturally). Drawn on a transparent rounded panel for contrast
+// against both bright sky and dark buildings.
+function buildLabelSprite(name, profession, accent) {
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
+ const padX = 22, nameSize = 34, profSize = 22, gap = 8;
+ const font = (px, w) => `${w} ${px}px Inter, system-ui, sans-serif`;
+
+ const measure = document.createElement('canvas').getContext('2d');
+ measure.font = font(nameSize, 700);
+ const nameW = measure.measureText(name).width;
+ const profText = (profession || 'Citizen').toUpperCase();
+ measure.font = font(profSize, 600);
+ const profW = measure.measureText(profText).width;
+
+ const w = Math.ceil(Math.max(nameW, profW + 26) + padX * 2);
+ const h = Math.ceil(nameSize + gap + profSize + 30);
+
+ const c = document.createElement('canvas');
+ c.width = Math.ceil(w * dpr);
+ c.height = Math.ceil(h * dpr);
+ const ctx = c.getContext('2d');
+ ctx.scale(dpr, dpr);
+
+ // Rounded translucent panel.
+ const r = 12;
+ ctx.fillStyle = 'rgba(8, 10, 14, 0.74)';
+ ctx.strokeStyle = 'rgba(255,255,255,0.10)';
+ ctx.lineWidth = 1;
+ roundRect(ctx, 1, 1, w - 2, h - 2, r);
+ ctx.fill();
+ ctx.stroke();
+
+ // Name.
+ ctx.textBaseline = 'top';
+ ctx.fillStyle = '#ffffff';
+ ctx.font = font(nameSize, 700);
+ ctx.fillText(name, padX, 13);
+
+ // Profession chip: accent dot + label.
+ const py = 13 + nameSize + gap;
+ ctx.fillStyle = accent;
+ ctx.beginPath();
+ ctx.arc(padX + 6, py + profSize / 2, 5, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = 'rgba(255,255,255,0.78)';
+ ctx.font = font(profSize, 600);
+ ctx.fillText(profText, padX + 20, py + 1);
+
+ const tex = new CanvasTexture(c);
+ tex.colorSpace = SRGBColorSpace;
+ tex.needsUpdate = true;
+ const mat = new SpriteMaterial({ map: tex, transparent: true, depthTest: true, depthWrite: false });
+ const sprite = new Sprite(mat);
+ // World height of the label ~0.42m; width preserves the canvas aspect.
+ const worldH = 0.46;
+ sprite.scale.set(worldH * (w / h), worldH, 1);
+ sprite.renderOrder = 2;
+ sprite.userData.isLabel = true;
+ return sprite;
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+export class CitizenPopulation {
+ /**
+ * @param {object} opts
+ * @param {import('three').WebGLRenderer} opts.renderer
+ * @param {import('three').Scene} opts.scene
+ * @param {boolean} [opts.reducedMotion] honor prefers-reduced-motion (no fade/idle motion)
+ */
+ constructor({ renderer, scene, reducedMotion = false }) {
+ this.scene = scene;
+ this.reducedMotion = reducedMotion;
+ this.loader = gltfLoader(renderer);
+
+ this.root = new Group();
+ this.root.name = 'agora-citizens';
+ scene.add(this.root);
+
+ this.instances = []; // { citizen, group, model, mixer, label, materials, fade, height }
+ this._byId = new Map(); // citizen.id → instance
+ this._templates = new Map(); // url → Promise<{ scene, clips, drivable }>
+ this._clipJson = null; // Promise<Map<name, clipJson>>
+ this._loadSlots = 0;
+ this._loadQueue = [];
+ this._disposed = false;
+
+ // A single reusable selection ring, parented to the highlighted citizen.
+ this._ring = this._buildRing();
+ this._ring.visible = false;
+ scene.add(this._ring);
+ this._selectedId = null;
+ }
+
+ _buildRing() {
+ const geo = new RingGeometry(0.5, 0.62, 48);
+ geo.rotateX(-Math.PI / 2);
+ const mat = new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.85, side: DoubleSide, depthWrite: false });
+ const ring = new Mesh(geo, mat);
+ ring.renderOrder = 1;
+ ring.name = 'agora-selection-ring';
+ return ring;
+ }
+
+ // Fetch idle + walk clip JSON once, shared across every template.
+ _ensureClips() {
+ if (this._clipJson) return this._clipJson;
+ this._clipJson = (async () => {
+ await loadManifest();
+ const defs = getLocomotionDefs();
+ const map = new Map();
+ await Promise.all(defs.map(async (d) => {
+ try {
+ const r = await fetch(d.url, { cache: 'force-cache' });
+ if (r.ok) map.set(d.name, await r.json());
+ } catch (err) {
+ log.warn(`[agora] clip "${d.name}" fetch failed`, err?.message);
+ }
+ }));
+ return map;
+ })();
+ return this._clipJson;
+ }
+
+ // Throttle concurrent GLB loads. Resolves when a slot frees up.
+ _acquireSlot() {
+ if (this._loadSlots < MAX_CONCURRENT_LOADS) {
+ this._loadSlots++;
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => this._loadQueue.push(resolve));
+ }
+ _releaseSlot() {
+ this._loadSlots--;
+ const next = this._loadQueue.shift();
+ if (next) { this._loadSlots++; next(); }
+ }
+
+ // Load a unique GLB once → reusable retargeted idle/walk clips bound to this
+ // rig's node names (identical across every SkeletonUtils.clone).
+ _template(url) {
+ if (this._templates.has(url)) return this._templates.get(url);
+ const p = (async () => {
+ const clipJson = await this._ensureClips();
+ await this._acquireSlot();
+ let gltf;
+ try {
+ gltf = await this.loader.loadAsync(url);
+ } finally {
+ this._releaseSlot();
+ }
+ const sceneRoot = gltf.scene;
+ sceneRoot.traverse((n) => {
+ if (!n.isMesh) return;
+ n.castShadow = true;
+ n.receiveShadow = false;
+ });
+ // Retarget against a throwaway clone so the cached template stays pristine.
+ const ref = cloneSkinnedScene(sceneRoot);
+ const mgr = new AnimationManager();
+ mgr.attach(ref, { avatarUrl: url });
+ const clips = new Map();
+ if (mgr.supportsCanonicalClips()) {
+ for (const [name, json] of clipJson) {
+ mgr.injectClip(name, json, { loop: true });
+ const clip = mgr.actions.get(name)?.getClip?.();
+ if (clip) clips.set(name, clip);
+ }
+ }
+ mgr.detach();
+ return { scene: sceneRoot, clips, drivable: clips.size > 0 };
+ })().catch((err) => {
+ log.warn('[agora] template load failed', url, err?.message);
+ return { scene: null, clips: new Map(), drivable: false };
+ });
+ this._templates.set(url, p);
+ return p;
+ }
+
+ /**
+ * Add one citizen to the world at (x, z) facing roughly toward the plaza
+ * centre. Returns the instance (or null if its GLB couldn't be loaded). Safe
+ * to call concurrently for the whole fleet — loads are pooled internally.
+ *
+ * @param {object} citizen shaped citizen from /api/agora/citizens
+ * @param {{x:number,z:number}} pos
+ */
+ async add(citizen, pos) {
+ if (this._disposed || this._byId.has(citizen.id)) return null;
+ const url = await resolveAvatarUrl(citizen.avatarUrl || '');
+ const tpl = await this._template(url);
+ if (this._disposed) return null;
+ if (!tpl?.scene) return null;
+
+ const model = cloneSkinnedScene(tpl.scene);
+ scaleToHeight(model, AVATAR_HEIGHT);
+ groundFeet(model);
+
+ // Per-instance materials so the fade-in opacity is isolated (the template's
+ // shared materials/geometry/textures are otherwise reused across clones).
+ const materials = [];
+ model.traverse((n) => {
+ if (!n.isMesh || !n.material) return;
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ const cloned = mats.map((m) => {
+ const c = m.clone();
+ c.transparent = true;
+ c.depthWrite = true;
+ return c;
+ });
+ n.material = Array.isArray(n.material) ? cloned : cloned[0];
+ materials.push(...cloned);
+ });
+
+ const group = new Group();
+ group.name = `citizen-${citizen.id}`;
+ group.add(model);
+ group.position.set(pos.x, 0, pos.z);
+ // Face the plaza centre with a little jitter so the crowd feels gathered,
+ // not regimented. atan2(x,z) points the +Z-forward avatar toward origin.
+ const baseYaw = Math.atan2(-pos.x, -pos.z);
+ group.rotation.y = baseYaw + (hashJitter(citizen.id) - 0.5) * 0.8;
+ group.userData.citizenId = citizen.id;
+ this.root.add(group);
+
+ const accent = professionColor(citizen.profession || citizen.professions?.[0]?.key);
+ const label = buildLabelSprite(citizen.displayName || 'Citizen', citizen.professions?.[0]?.label || citizen.profession, accent);
+ _box.setFromObject(model, true);
+ const height = Number.isFinite(_box.max.y) ? _box.max.y : AVATAR_HEIGHT;
+ label.position.set(0, height + 0.3, 0);
+ group.add(label);
+
+ // Idle loop, desynced so the crowd doesn't breathe in lockstep.
+ let mixer = null;
+ const idleClip = tpl.clips.get(CLIP_IDLE) || [...tpl.clips.values()][0];
+ if (idleClip && !this.reducedMotion) {
+ mixer = new AnimationMixer(model);
+ const action = mixer.clipAction(idleClip);
+ action.time = hashJitter(citizen.id + 'x') * (idleClip.duration || 1);
+ action.play();
+ } else if (idleClip && this.reducedMotion) {
+ // Reduced motion: hold a calm idle pose (frame 0), no looping motion.
+ mixer = new AnimationMixer(model);
+ const action = mixer.clipAction(idleClip);
+ action.play();
+ mixer.update(0);
+ action.paused = true;
+ }
+
+ const fade = this.reducedMotion ? null : { t: 0 };
+ for (const m of materials) m.opacity = this.reducedMotion ? 1 : 0;
+
+ const inst = { citizen, group, model, mixer, label, materials, fade, height, baseYaw };
+ this.instances.push(inst);
+ this._byId.set(citizen.id, inst);
+ // Pickable meshes carry a back-reference so a raycast hit resolves to the id.
+ model.traverse((n) => { if (n.isMesh) n.userData.citizenId = citizen.id; });
+ return inst;
+ }
+
+ /** Advance idle loops + fade-ins. Cheap: one mixer.update per citizen. */
+ update(dt) {
+ for (const inst of this.instances) {
+ if (!this.reducedMotion) inst.mixer?.update(dt);
+ if (inst.fade) {
+ inst.fade.t += dt;
+ const k = Math.min(1, inst.fade.t / FADE_IN_SEC);
+ const eased = k * (2 - k); // ease-out
+ for (const m of inst.materials) m.opacity = eased;
+ if (k >= 1) {
+ for (const m of inst.materials) { m.transparent = false; }
+ inst.fade = null;
+ }
+ }
+ }
+ }
+
+ /**
+ * Hit-test pickable avatars. Returns the citizen id under the ray, or null.
+ * @param {import('three').Raycaster} raycaster
+ */
+ pick(raycaster) {
+ const hits = raycaster.intersectObjects(this.root.children, true);
+ for (const h of hits) {
+ let o = h.object;
+ while (o) {
+ if (o.userData?.citizenId) return o.userData.citizenId;
+ o = o.parent;
+ }
+ }
+ return null;
+ }
+
+ /** Move + show the selection ring under a citizen (null clears it). */
+ highlight(id) {
+ this._selectedId = id;
+ const inst = id ? this._byId.get(id) : null;
+ if (!inst) { this._ring.visible = false; return; }
+ inst.group.getWorldPosition(_v);
+ this._ring.position.set(_v.x, 0.02, _v.z);
+ const accent = professionColor(inst.citizen.profession || inst.citizen.professions?.[0]?.key);
+ this._ring.material.color.set(accent);
+ this._ring.visible = true;
+ }
+
+ get selectedId() { return this._selectedId; }
+
+ getInstance(id) { return this._byId.get(id) || null; }
+
+ /** World position of a citizen (for framing the camera). Null if unknown. */
+ worldPosition(id) {
+ const inst = this._byId.get(id);
+ if (!inst) return null;
+ inst.group.getWorldPosition(_v);
+ return _v.clone();
+ }
+
+ get count() { return this.instances.length; }
+
+ dispose() {
+ this._disposed = true;
+ for (const inst of this.instances) {
+ inst.mixer?.stopAllAction();
+ for (const m of inst.materials) m.dispose?.();
+ inst.label.material.map?.dispose?.();
+ inst.label.material.dispose?.();
+ inst.group.parent?.remove(inst.group);
+ }
+ this.instances = [];
+ this._byId.clear();
+ this._ring.geometry.dispose();
+ this._ring.material.dispose();
+ this.scene.remove(this._ring);
+ this.scene.remove(this.root);
+ this._templates.clear();
+ }
+}
+
+// Deterministic per-id jitter in [0,1) — keeps facing/desync stable across
+// reloads (no Math.random, so the same citizen always stands the same way).
+function hashJitter(seed) {
+ const s = String(seed);
+ let h = 2166136261;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return ((h >>> 0) % 100000) / 100000;
+}
diff --git a/src/agora/format.js b/src/agora/format.js
new file mode 100644
index 000000000..38feabdd2
--- /dev/null
+++ b/src/agora/format.js
@@ -0,0 +1,135 @@
+// Agora — shared formatting helpers for the trust surface (job detail, verify,
+// passport, handshake). Pure functions, no DOM, no network — safe to unit-test.
+// Every value the panels render passes through here so $THREE amounts, hashes,
+// addresses, timestamps and explorer links read identically everywhere.
+
+// $THREE is an SPL token with 6 decimals (see api/_lib/autopilot.js THREE_DECIMALS).
+export const THREE_DECIMALS = 6;
+
+// Format an atomic $THREE amount (string|number|bigint of base units) as a
+// human reward, e.g. 25_000_000_000 → "25,000". Falls back to "0" on garbage.
+export function formatThree(atomic) {
+ let n;
+ try {
+ n = typeof atomic === 'bigint' ? atomic : BigInt(String(atomic ?? '0').split('.')[0] || '0');
+ } catch {
+ return '0';
+ }
+ const base = 10n ** BigInt(THREE_DECIMALS);
+ const whole = n / base;
+ const frac = n % base;
+ const wholeStr = whole.toLocaleString('en-US');
+ if (frac === 0n) return wholeStr;
+ // Show up to 2 significant fractional digits, trimmed.
+ const fracStr = (frac * 100n / base).toString().padStart(2, '0').replace(/0+$/, '');
+ return fracStr ? `${wholeStr}.${fracStr}` : wholeStr;
+}
+
+// Lamports (1e9 per SOL) → a short SOL string. Used for slashable stake.
+export function formatSol(lamports) {
+ let n;
+ try {
+ n = typeof lamports === 'bigint' ? lamports : BigInt(String(lamports ?? '0').split('.')[0] || '0');
+ } catch {
+ return '0';
+ }
+ const sol = Number(n) / 1e9;
+ if (sol === 0) return '0';
+ if (sol < 0.001) return sol.toExponential(2);
+ return sol.toLocaleString('en-US', { maximumFractionDigits: 4 });
+}
+
+// Truncate a base58 address / 64-char hash for display: keep head+tail.
+export function shortId(value, head = 4, tail = 4) {
+ const s = String(value ?? '');
+ if (s.length <= head + tail + 1) return s;
+ return `${s.slice(0, head)}…${s.slice(-tail)}`;
+}
+
+// Normalize a hash to lowercase hex with no 0x prefix — the canonical form the
+// on-chain proofHash and a browser-computed digest are compared in.
+export function normalizeHex(value) {
+ let s = String(value ?? '').trim().toLowerCase();
+ if (s.startsWith('0x')) s = s.slice(2);
+ return s;
+}
+
+// Solana Explorer link for a tx signature. Cluster 'devnet' appends the query;
+// mainnet uses the default (mainnet-beta) network.
+export function explorerTxUrl(signature, cluster = 'devnet') {
+ if (!signature) return null;
+ const suffix = cluster === 'mainnet' ? '' : '?cluster=devnet';
+ return `https://explorer.solana.com/tx/${signature}${suffix}`;
+}
+
+// Solana Explorer link for an account/address (agent PDA, asset, mint).
+export function explorerAddressUrl(address, cluster = 'devnet') {
+ if (!address) return null;
+ const suffix = cluster === 'mainnet' ? '' : '?cluster=devnet';
+ return `https://explorer.solana.com/address/${address}${suffix}`;
+}
+
+// Etherscan link for an EVM address (the ERC-8004 side of the handshake).
+export function etherscanAddressUrl(address) {
+ if (!address) return null;
+ return `https://etherscan.io/address/${address}`;
+}
+
+// Relative time, e.g. "3m ago", "2h ago", "5d ago". Accepts ISO strings or
+// unix seconds (on-chain timestamps come back as seconds). null → "—".
+export function timeAgo(input) {
+ if (input == null) return '—';
+ let ms;
+ if (typeof input === 'number') {
+ // On-chain timestamps are unix seconds; JS Date wants ms.
+ ms = input < 1e12 ? input * 1000 : input;
+ } else {
+ ms = Date.parse(input);
+ }
+ if (!Number.isFinite(ms)) return '—';
+ const diff = Date.now() - ms;
+ if (diff < 0) return 'just now';
+ const sec = Math.floor(diff / 1000);
+ if (sec < 60) return `${sec}s ago`;
+ const min = Math.floor(sec / 60);
+ if (min < 60) return `${min}m ago`;
+ const hr = Math.floor(min / 60);
+ if (hr < 24) return `${hr}h ago`;
+ const day = Math.floor(hr / 24);
+ if (day < 30) return `${day}d ago`;
+ const mon = Math.floor(day / 30);
+ if (mon < 12) return `${mon}mo ago`;
+ return `${Math.floor(mon / 12)}y ago`;
+}
+
+// Absolute, human timestamp for tooltips/title attributes.
+export function absoluteTime(input) {
+ if (input == null) return '';
+ let ms;
+ if (typeof input === 'number') ms = input < 1e12 ? input * 1000 : input;
+ else ms = Date.parse(input);
+ if (!Number.isFinite(ms)) return '';
+ return new Date(ms).toLocaleString('en-US', {
+ year: 'numeric', month: 'short', day: 'numeric',
+ hour: '2-digit', minute: '2-digit',
+ });
+}
+
+// Bytes → human size, e.g. 1536 → "1.5 KB". For the verify size readout.
+export function formatBytes(bytes) {
+ const n = Number(bytes);
+ if (!Number.isFinite(n) || n < 0) return '—';
+ if (n < 1024) return `${n} B`;
+ const units = ['KB', 'MB', 'GB'];
+ let v = n / 1024;
+ let i = 0;
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
+}
+
+// Title-case a profession key, e.g. "sculptor" → "Sculptor".
+export function professionLabel(key) {
+ const s = String(key ?? '').trim();
+ if (!s) return '';
+ return s[0].toUpperCase() + s.slice(1);
+}
diff --git a/src/agora/panel.js b/src/agora/panel.js
new file mode 100644
index 000000000..16a049b09
--- /dev/null
+++ b/src/agora/panel.js
@@ -0,0 +1,243 @@
+// Agora — the shared side panel (drawer) every trust-surface view mounts into:
+// job detail, the living passport, the verifier, the handshake. One accessible
+// shell so focus-trapping, Escape-to-close, focus restoration, ARIA wiring and
+// the close affordance are correct and identical everywhere — the panels above
+// only fill the body.
+
+// Tiny hyperscript helper. `h('div', { class: 'x', onclick: fn }, [childNodes])`.
+// Keeps the panel modules declarative without pulling in a framework. Strings in
+// the children array become text nodes; null/false/undefined are skipped.
+export function h(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props || {})) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k === 'dataset') Object.assign(node.dataset, v);
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v);
+ else if (k === 'text') node.textContent = v;
+ else node.setAttribute(k, v === true ? '' : String(v));
+ }
+ const kids = Array.isArray(children) ? children : [children];
+ for (const c of kids) {
+ if (c == null || c === false) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+}
+
+export function clear(node) {
+ while (node.firstChild) node.removeChild(node.firstChild);
+}
+
+const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
+
+// A copy-to-clipboard chip for a hash or address. Shows the truncated value and
+// flips to a ✓ for 1.2s on copy. Falls back gracefully where the Clipboard API
+// is blocked (insecure context) by selecting a hidden textarea + execCommand.
+export function copyChip(value, label) {
+ const full = String(value ?? '');
+ const btn = h('button', {
+ class: 'agora-copy',
+ type: 'button',
+ title: `Copy ${label || 'value'}`,
+ 'aria-label': `Copy ${label || 'value'}: ${full}`,
+ }, [
+ h('span', { class: 'agora-copy-text' }, [label || full]),
+ h('span', { class: 'agora-copy-icon', 'aria-hidden': 'true' }, ['⧉']),
+ ]);
+ btn.addEventListener('click', async () => {
+ const ok = await copyText(full);
+ const icon = btn.querySelector('.agora-copy-icon');
+ btn.classList.toggle('is-ok', ok);
+ btn.classList.toggle('is-fail', !ok);
+ if (icon) icon.textContent = ok ? '✓' : '✕';
+ setTimeout(() => {
+ btn.classList.remove('is-ok', 'is-fail');
+ if (icon) icon.textContent = '⧉';
+ }, 1200);
+ });
+ return btn;
+}
+
+export async function copyText(text) {
+ try {
+ if (navigator.clipboard && window.isSecureContext) {
+ await navigator.clipboard.writeText(text);
+ return true;
+ }
+ } catch { /* fall through to legacy path */ }
+ try {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ const ok = document.execCommand('copy');
+ document.body.removeChild(ta);
+ return ok;
+ } catch {
+ return false;
+ }
+}
+
+// An accessible right-side drawer. Construct once per logical panel; call open()
+// to show with fresh content and close() to hide. Only one Panel should be open
+// at a time — the host (agora-world) enforces that.
+export class Panel {
+ // onClose fires after the panel hides (host clears deep-link state there).
+ constructor({ id, onClose } = {}) {
+ this._onClose = onClose;
+ this._opener = null;
+ this._open = false;
+
+ this.titleEl = h('h2', { class: 'agora-panel-title', id: `${id}-title` });
+ this.subEl = h('div', { class: 'agora-panel-sub' });
+ this.bodyEl = h('div', { class: 'agora-panel-body' });
+
+ this.closeBtn = h('button', {
+ class: 'agora-panel-close',
+ type: 'button',
+ 'aria-label': 'Close panel',
+ title: 'Close (Esc)',
+ }, ['✕']);
+ this.closeBtn.addEventListener('click', () => this.close());
+
+ this.root = h('aside', {
+ id,
+ class: 'agora-panel',
+ role: 'dialog',
+ 'aria-modal': 'false',
+ 'aria-labelledby': `${id}-title`,
+ tabindex: '-1',
+ hidden: true,
+ }, [
+ h('header', { class: 'agora-panel-head' }, [
+ h('div', { class: 'agora-panel-head-text' }, [this.titleEl, this.subEl]),
+ this.closeBtn,
+ ]),
+ this.bodyEl,
+ ]);
+
+ this._onKeydown = (e) => {
+ if (!this._open) return;
+ if (e.key === 'Escape') { e.stopPropagation(); this.close(); return; }
+ if (e.key === 'Tab') this._trapTab(e);
+ };
+ this.root.addEventListener('keydown', this._onKeydown);
+ }
+
+ mount(parent) {
+ parent.appendChild(this.root);
+ return this;
+ }
+
+ setHeader(title, sub) {
+ this.titleEl.textContent = title || '';
+ if (sub == null) { this.subEl.textContent = ''; this.subEl.hidden = true; }
+ else { this.subEl.hidden = false; clear(this.subEl); this.subEl.appendChild(typeof sub === 'string' ? document.createTextNode(sub) : sub); }
+ return this;
+ }
+
+ // Replace the body with a node (or array of nodes).
+ setBody(content) {
+ clear(this.bodyEl);
+ const kids = Array.isArray(content) ? content : [content];
+ for (const c of kids) if (c) this.bodyEl.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ this.bodyEl.scrollTop = 0;
+ return this;
+ }
+
+ // Designed loading state: skeleton rows (no spinner).
+ setLoading(label = 'Loading…') {
+ this.setBody(h('div', { class: 'agora-state agora-state-loading', role: 'status', 'aria-live': 'polite' }, [
+ h('span', { class: 'agora-skel agora-skel-line' }),
+ h('span', { class: 'agora-skel agora-skel-line short' }),
+ h('span', { class: 'agora-skel agora-skel-block' }),
+ h('span', { class: 'agora-skel agora-skel-line' }),
+ h('span', { class: 'sr-only' }, [label]),
+ ]));
+ return this;
+ }
+
+ // Designed, actionable error state. retry, if given, renders a Retry button.
+ setError(message, retry) {
+ this.setBody(h('div', { class: 'agora-state agora-state-error', role: 'alert' }, [
+ h('div', { class: 'agora-state-icon', 'aria-hidden': 'true' }, ['⚠']),
+ h('p', { class: 'agora-state-msg' }, [message || 'Something went wrong.']),
+ retry ? h('button', { class: 'agora-btn', type: 'button', onclick: retry }, ['Try again']) : null,
+ ]));
+ return this;
+ }
+
+ // Designed empty state.
+ setEmpty(message, hint) {
+ this.setBody(h('div', { class: 'agora-state agora-state-empty' }, [
+ h('div', { class: 'agora-state-icon', 'aria-hidden': 'true' }, ['◌']),
+ h('p', { class: 'agora-state-msg' }, [message || 'Nothing here yet.']),
+ hint ? h('p', { class: 'agora-state-hint' }, [hint]) : null,
+ ]));
+ return this;
+ }
+
+ open(opener) {
+ this._opener = opener || document.activeElement;
+ this.root.hidden = false;
+ this._open = true;
+ this.root.classList.add('is-open');
+ // Move focus into the panel for keyboard + screen-reader users.
+ requestAnimationFrame(() => {
+ const first = this.root.querySelector(FOCUSABLE);
+ (first || this.root).focus();
+ });
+ return this;
+ }
+
+ close() {
+ if (!this._open) return;
+ this._open = false;
+ this.root.classList.remove('is-open');
+ // Wait for the exit transition before hiding from the a11y tree.
+ const hide = () => { if (!this._open) this.root.hidden = true; };
+ this.root.addEventListener('transitionend', hide, { once: true });
+ setTimeout(hide, 320);
+ // Restore focus to whatever opened the panel.
+ if (this._opener && typeof this._opener.focus === 'function') {
+ try { this._opener.focus(); } catch { /* opener gone */ }
+ }
+ this._opener = null;
+ if (typeof this._onClose === 'function') this._onClose();
+ }
+
+ get isOpen() { return this._open; }
+
+ _trapTab(e) {
+ const items = [...this.root.querySelectorAll(FOCUSABLE)].filter((n) => n.offsetParent !== null || n === document.activeElement);
+ if (!items.length) { e.preventDefault(); this.root.focus(); return; }
+ const first = items[0];
+ const last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
+ }
+}
+
+// A labelled key/value row used across the panels.
+export function infoRow(label, value, opts = {}) {
+ const valNode = typeof value === 'string' || typeof value === 'number'
+ ? h('span', { class: 'agora-kv-val' }, [String(value)])
+ : (value || h('span', { class: 'agora-kv-val agora-muted' }, ['—']));
+ return h('div', { class: `agora-kv${opts.wide ? ' wide' : ''}` }, [
+ h('span', { class: 'agora-kv-key' }, [label]),
+ valNode,
+ ]);
+}
+
+// A reward chip — always $THREE, the only coin Agora denominates in.
+export function rewardChip(amountDisplay, mintLabel = '$THREE') {
+ return h('span', { class: 'agora-reward' }, [
+ h('span', { class: 'agora-reward-amt' }, [amountDisplay]),
+ h('span', { class: 'agora-reward-coin' }, [mintLabel]),
+ ]);
+}
diff --git a/src/agora/passport-panel.js b/src/agora/passport-panel.js
new file mode 100644
index 000000000..647a36d49
--- /dev/null
+++ b/src/agora/passport-panel.js
@@ -0,0 +1,250 @@
+// Agora passport panel — the click-to-inspect side panel for a single citizen.
+//
+// Clicking (or keyboard-activating) a citizen opens this panel, which fetches
+// /api/agora/passport?id=… and shows the real basics: name, profession, status,
+// reputation, stake, tasks completed, and recent activity. The rich living
+// passport (identity handshake, verify-the-deliverable) is Task 07 — this is a
+// clean, real first version with designed loading / error / empty states.
+//
+// Non-modal: the world stays interactive behind it. Esc closes; focus moves into
+// the panel on open and returns to the trigger on close.
+
+import { professionColor } from './citizen-avatar.js';
+import { log } from '../shared/log.js';
+
+const THREE_DECIMALS = 6;
+const LAMPORTS_PER_SOL = 1e9;
+
+const fmtThree = (atomic) => {
+ const n = Number(atomic || 0) / 10 ** THREE_DECIMALS;
+ if (!Number.isFinite(n) || n === 0) return '0';
+ if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M';
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
+ return n.toLocaleString('en-US', { maximumFractionDigits: 2 });
+};
+const fmtSol = (lamports) => {
+ const n = Number(lamports || 0) / LAMPORTS_PER_SOL;
+ if (!Number.isFinite(n) || n === 0) return '0';
+ return n.toLocaleString('en-US', { maximumFractionDigits: 3 });
+};
+const fmtTimeAgo = (iso) => {
+ if (!iso) return '';
+ const then = new Date(iso).getTime();
+ if (!Number.isFinite(then)) return '';
+ const s = Math.max(0, (Date.now() - then) / 1000);
+ if (s < 60) return 'just now';
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ return `${Math.floor(s / 86400)}d ago`;
+};
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
+));
+
+const ACTIVITY_LABEL = {
+ posted_task: 'Posted a task',
+ claimed_task: 'Claimed a task',
+ completed_task: 'Completed a task',
+ earned: 'Earned',
+ slashed: 'Stake slashed',
+ vouched: 'Vouched',
+ registered: 'Registered on-chain',
+};
+
+export class PassportPanel {
+ constructor() {
+ this._el = this._build();
+ document.body.appendChild(this._el);
+ this._bodyEl = this._el.querySelector('#agora-passport-body');
+ this._titleEl = this._el.querySelector('#agora-passport-title');
+ this._trigger = null; // element to restore focus to on close
+ this._reqId = 0; // guards against out-of-order responses
+ this._currentId = null;
+ this._onClose = null;
+
+ this._el.querySelector('.agora-passport-close').addEventListener('click', () => this.close());
+ this._onKey = (e) => { if (e.key === 'Escape' && this.isOpen()) { e.stopPropagation(); this.close(); } };
+ document.addEventListener('keydown', this._onKey);
+ }
+
+ _build() {
+ const aside = document.createElement('aside');
+ aside.id = 'agora-passport';
+ aside.className = 'agora-passport';
+ aside.setAttribute('role', 'dialog');
+ aside.setAttribute('aria-label', 'Citizen passport');
+ aside.setAttribute('aria-modal', 'false');
+ aside.hidden = true;
+ aside.innerHTML = `
+ <header class="agora-passport-head">
+ <h2 id="agora-passport-title">Passport</h2>
+ <button class="agora-passport-close" type="button" aria-label="Close passport">
+ <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
+ </button>
+ </header>
+ <div id="agora-passport-body" class="agora-passport-body" tabindex="-1"></div>`;
+ return aside;
+ }
+
+ isOpen() { return !this._el.hidden; }
+
+ /**
+ * Open the panel for a citizen and fetch its passport.
+ * @param {string} id citizen id
+ * @param {{ trigger?: HTMLElement, onClose?: Function, hint?: object }} [opts]
+ * hint: a citizen object from the list, rendered immediately so the header
+ * isn't blank while the passport request is in flight.
+ */
+ async open(id, { trigger = null, onClose = null, hint = null } = {}) {
+ this._trigger = trigger;
+ this._onClose = onClose;
+ this._currentId = id;
+ const reqId = ++this._reqId;
+
+ this._el.hidden = false;
+ this._el.classList.add('open');
+ this._titleEl.textContent = hint?.displayName || 'Passport';
+ this._renderLoading(hint);
+ // Move focus into the panel for keyboard + screen-reader users.
+ this._bodyEl.focus({ preventScroll: true });
+
+ try {
+ const res = await fetch(`/api/agora/passport?id=${encodeURIComponent(id)}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (reqId !== this._reqId) return; // superseded by a newer open()
+ if (!res.ok) {
+ const detail = res.status === 404 ? 'This citizen is no longer in the registry.' : `Request failed (${res.status}).`;
+ this._renderError(id, detail);
+ return;
+ }
+ const data = await res.json();
+ if (reqId !== this._reqId) return;
+ this._render(data);
+ } catch (err) {
+ if (reqId !== this._reqId) return;
+ log.warn('[agora] passport fetch failed', err?.message);
+ this._renderError(id, 'Network error — the registry could not be reached.');
+ }
+ }
+
+ close() {
+ if (this._el.hidden) return;
+ this._el.classList.remove('open');
+ this._el.hidden = true;
+ this._currentId = null;
+ const t = this._trigger;
+ const cb = this._onClose;
+ this._trigger = null;
+ this._onClose = null;
+ try { cb?.(); } catch (e) { log.warn('[agora] passport onClose threw', e); }
+ // Restore focus to whatever opened the panel (an accessible list button).
+ if (t && typeof t.focus === 'function') t.focus({ preventScroll: true });
+ }
+
+ get currentId() { return this._currentId; }
+
+ // ── Renderers ──────────────────────────────────────────────────────────────
+
+ _renderLoading(hint) {
+ const accent = hint ? professionColor(hint.profession || hint.professions?.[0]?.key) : '#9fb4cc';
+ this._bodyEl.innerHTML = `
+ <div class="agora-pp-hero">
+ <span class="agora-pp-dot" style="background:${accent}"></span>
+ <div>
+ <div class="agora-pp-name">${esc(hint?.displayName || 'Loading…')}</div>
+ <div class="agora-pp-prof">${esc(hint?.professions?.[0]?.label || hint?.profession || 'Citizen')}</div>
+ </div>
+ </div>
+ <div class="agora-pp-skel" aria-hidden="true">
+ ${'<div class="agora-pp-skel-row"></div>'.repeat(4)}
+ </div>
+ <div class="agora-pp-skel" aria-hidden="true" style="margin-top:18px">
+ ${'<div class="agora-pp-skel-line"></div>'.repeat(3)}
+ </div>
+ <span class="agora-pp-srhint" role="status">Loading passport…</span>`;
+ }
+
+ _renderError(id, detail) {
+ this._bodyEl.innerHTML = `
+ <div class="agora-pp-state">
+ <div class="agora-pp-state-icon" aria-hidden="true">!</div>
+ <p class="agora-pp-state-title">Couldn't load this passport</p>
+ <p class="agora-pp-state-detail">${esc(detail)}</p>
+ <button class="agora-pp-retry" type="button">Try again</button>
+ </div>`;
+ this._bodyEl.querySelector('.agora-pp-retry').addEventListener('click', () => this.open(id, { trigger: this._trigger }));
+ }
+
+ _render(data) {
+ const c = data.citizen || {};
+ const onchain = data.onchain || null;
+ const accent = professionColor(c.profession || c.professions?.[0]?.key);
+ this._titleEl.textContent = c.displayName || 'Passport';
+
+ const status = onchain?.status || c.status || 'Idle';
+ const reputation = onchain?.reputation ?? c.reputation ?? 0;
+ const stake = onchain?.stakeAmount ?? c.stakeLamports;
+ const professions = (c.professions && c.professions.length)
+ ? c.professions.map((p) => p.label)
+ : [c.profession || 'Citizen'];
+
+ const stats = [
+ { label: 'Reputation', value: Number(reputation).toLocaleString('en-US') },
+ { label: 'Tasks done', value: Number(c.tasksCompleted || 0).toLocaleString('en-US') },
+ { label: 'Earned', value: `${fmtThree(c.earnedThreeAtomic)} $THREE` },
+ { label: 'Stake', value: `${fmtSol(stake)} SOL` },
+ ];
+
+ const identity = [];
+ if (c.agenc?.registered && c.agenc?.cluster) identity.push(`AgenC · ${esc(c.agenc.cluster)}`);
+ if (c.agenc?.identitySource) identity.push(esc(c.agenc.identitySource));
+
+ this._bodyEl.innerHTML = `
+ <div class="agora-pp-hero">
+ <span class="agora-pp-dot" style="background:${accent}"></span>
+ <div>
+ <div class="agora-pp-name">${esc(c.displayName || 'Citizen')}</div>
+ <div class="agora-pp-prof">${esc(professions.join(' · '))}</div>
+ </div>
+ <span class="agora-pp-status agora-pp-status-${esc(String(status).toLowerCase())}">${esc(status)}</span>
+ </div>
+
+ <div class="agora-pp-stats">
+ ${stats.map((s) => `
+ <div class="agora-pp-stat">
+ <div class="agora-pp-stat-value">${esc(s.value)}</div>
+ <div class="agora-pp-stat-label">${esc(s.label)}</div>
+ </div>`).join('')}
+ </div>
+
+ ${identity.length ? `<div class="agora-pp-identity">${identity.map((i) => `<span class="agora-pp-chip">${i}</span>`).join('')}</div>` : ''}
+
+ <h3 class="agora-pp-section">Recent activity</h3>
+ ${this._renderActivity(data.activity || [])}`;
+ }
+
+ _renderActivity(activity) {
+ if (!activity.length) {
+ return `<p class="agora-pp-empty">No on-chain activity yet. This citizen is just getting started in the Commons.</p>`;
+ }
+ return `<ul class="agora-pp-feed">${activity.slice(0, 12).map((a) => {
+ const title = a.narrative || ACTIVITY_LABEL[a.kind] || a.kind;
+ const meta = [a.rewardLabel, fmtTimeAgo(a.at)].filter(Boolean).join(' · ');
+ const rep = (a.repBefore != null && a.repAfter != null && a.repBefore !== a.repAfter)
+ ? `<span class="agora-pp-rep">rep ${a.repBefore} → ${a.repAfter}</span>` : '';
+ return `<li class="agora-pp-feed-item">
+ <span class="agora-pp-feed-kind" data-kind="${esc(a.kind)}"></span>
+ <div class="agora-pp-feed-main">
+ <div class="agora-pp-feed-title">${esc(title)}</div>
+ <div class="agora-pp-feed-meta">${esc(meta)} ${rep}</div>
+ </div>
+ </li>`;
+ }).join('')}</ul>`;
+ }
+
+ dispose() {
+ document.removeEventListener('keydown', this._onKey);
+ this._el.remove();
+ }
+}
diff --git a/src/agora/professions.js b/src/agora/professions.js
new file mode 100644
index 000000000..c6e8f68cc
--- /dev/null
+++ b/src/agora/professions.js
@@ -0,0 +1,70 @@
+// Task 06 reward styling helpers for the Commons economy layer.
+//
+// Profession → accent colour is owned by src/agora/citizen-avatar.js (Task 05)
+// so the labour market reads the same everywhere — a Sculptor is one colour on
+// its citizen ring, its job-board marker and its ticker chip. We re-export that
+// single source and add only what the economy visuals need on top: a Three.js
+// colour wrapper (markers/coins are 3D, the source is a CSS string) and reward
+// sizing/formatting. No second colour map, ever.
+
+import * as THREE from 'three';
+import { professionColor, PROFESSION_COLORS } from './citizen-avatar.js';
+
+export { professionColor, PROFESSION_COLORS };
+
+// The CSS accent for a profession as a Three.js Color (markers, coin arcs, the
+// board glow all live in the 3D scene). Memoised so we don't allocate a Color
+// per marker per frame.
+const _colorCache = new Map();
+export function professionThreeColor(profession) {
+ const css = professionColor(profession);
+ let c = _colorCache.get(css);
+ if (!c) { c = new THREE.Color(css); _colorCache.set(css, c); }
+ return c;
+}
+
+// Derive a comparable magnitude from a task reward so markers can be sized by
+// value. Rewards arrive either as an atomic string (`amountAtomic`) or only as a
+// formatted label ("25,000 $THREE", "$0.01"). Prefer the atomic count (token
+// decimals don't matter for a *relative* size) and fall back to the first number
+// readable from the label. Returns 0 when nothing parses — never NaN.
+export function rewardMagnitude(reward) {
+ if (!reward) return 0;
+ const atomic = reward.amountAtomic;
+ if (atomic != null && atomic !== '') {
+ const n = Number(atomic);
+ if (Number.isFinite(n) && n > 0) return n;
+ }
+ const label = reward.label || reward.priceLabel || '';
+ const m = String(label).replace(/,/g, '').match(/[\d.]+/);
+ if (m) {
+ const n = parseFloat(m[0]);
+ if (Number.isFinite(n) && n > 0) return n;
+ }
+ return 0;
+}
+
+// Map a reward magnitude onto a marker scale on a log curve so a 1,000,000-unit
+// bounty doesn't dwarf a 100-unit one off the screen, while still reading as
+// "bigger reward = bigger glow". Clamped to a sane visual band.
+export function rewardMarkerScale(magnitude) {
+ const MIN = 0.6;
+ const MAX = 1.7;
+ if (!(magnitude > 0)) return MIN;
+ const t = Math.min(1, Math.max(0, Math.log10(magnitude) / 9)); // 1 → 1e9 over 0..1
+ return MIN + (MAX - MIN) * t;
+}
+
+// A short reward chip string for HUD/tooltip use. Honours whatever the API
+// formatted (it already says "$THREE" or the devnet unit) and never invents a
+// coin. Falls back to the raw atomic count only when no label exists.
+export function rewardChip(reward) {
+ if (!reward) return null;
+ if (reward.label) return reward.label;
+ if (reward.priceLabel) return reward.priceLabel;
+ if (reward.amountAtomic != null) {
+ const cur = reward.currency || reward.mint || '';
+ return `${reward.amountAtomic}${cur ? ' ' + cur : ''}`;
+ }
+ return null;
+}
diff --git a/src/agora/verify.js b/src/agora/verify.js
new file mode 100644
index 000000000..c31302e62
--- /dev/null
+++ b/src/agora/verify.js
@@ -0,0 +1,294 @@
+// Agora — the deliverable verifier. This is the honest core of the trust
+// surface: completion bound `proofHash = sha256(deliverable bytes)` on-chain, so
+// ANYONE can re-fetch the deliverable, re-hash it in their own browser, and
+// confirm it matches — no trust in three.ws required.
+//
+// The crypto + compare below is pure (no DOM, no three) and unit-tested against
+// real `crypto.subtle`. The inline GLB viewer is lazy-loaded only when a verified
+// model needs rendering, so the pure path stays light and importable anywhere.
+//
+// Guardrail (CLAUDE.md): the result must be COMPUTED. If the deliverable can't be
+// fetched or hashed, we say "could not verify" and show why — never a green check
+// we didn't actually derive.
+
+import { h, copyChip, copyText } from './panel.js';
+import { normalizeHex, formatBytes, shortId } from './format.js';
+
+// Default ceiling on what we'll download to verify. A deliverable larger than
+// this is reported honestly ("too large to verify in-browser") rather than
+// silently truncated — a truncated hash would never match and would read as a
+// false ✗. 96 MB comfortably covers forge GLBs while bounding memory.
+export const DEFAULT_MAX_BYTES = 96 * 1024 * 1024;
+
+// SHA-256 a byte buffer → lowercase hex. Uses Web Crypto, present in browsers and
+// Node ≥ 16 (globalThis.crypto.subtle). The on-chain proofHash is this exact
+// digest of the deliverable bytes.
+export async function sha256Hex(bytes) {
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ // digest wants an ArrayBuffer view; slice to the exact range so a pooled
+ // buffer (e.g. from a stream) never hashes trailing garbage.
+ const buf = view.byteOffset === 0 && view.byteLength === view.buffer.byteLength
+ ? view.buffer
+ : view.slice().buffer;
+ const digest = await crypto.subtle.digest('SHA-256', buf);
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+// Compare a freshly-computed hash against the on-chain proofHash. Both are
+// normalized to bare lowercase hex first so 0x-prefixing or case never causes a
+// spurious mismatch. Returns the decision plus both normalized hashes for display.
+export function compareHash(computedHex, proofHash) {
+ const computed = normalizeHex(computedHex);
+ const expected = normalizeHex(proofHash);
+ const haveExpected = expected.length > 0;
+ return {
+ match: haveExpected && computed.length > 0 && computed === expected,
+ haveExpected,
+ computed,
+ expected,
+ };
+}
+
+// Typed verification error so the UI can phrase each failure honestly.
+export class VerifyError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'VerifyError';
+ this.code = code; // 'fetch' | 'cors' | 'too_large' | 'empty' | 'hash'
+ }
+}
+
+// Fetch a deliverable and hash it, streaming with a hard size cap so a hostile or
+// huge URL can't exhaust memory. Returns { bytes, hashHex, size, contentType }.
+// Throws VerifyError with a code the UI maps to an honest message.
+export async function fetchAndHash(url, { maxBytes = DEFAULT_MAX_BYTES, signal, onProgress } = {}) {
+ let res;
+ try {
+ res = await fetch(url, { signal, redirect: 'follow', mode: 'cors' });
+ } catch (err) {
+ // A CORS rejection and a network failure both surface as TypeError here;
+ // we can't tell them apart, so we name both and offer the direct link.
+ throw new VerifyError('cors', `Couldn't fetch the deliverable (network or CORS blocked): ${err?.message || 'failed'}`);
+ }
+ if (!res.ok) {
+ throw new VerifyError('fetch', `The deliverable URL returned HTTP ${res.status} ${res.statusText || ''}`.trim());
+ }
+
+ const contentType = res.headers.get('content-type') || '';
+ const declared = Number(res.headers.get('content-length')) || 0;
+ if (declared && declared > maxBytes) {
+ throw new VerifyError('too_large', `Deliverable is ${formatBytes(declared)} — over the ${formatBytes(maxBytes)} in-browser verify cap.`);
+ }
+
+ // Stream so we can enforce the cap mid-download and report progress.
+ const chunks = [];
+ let received = 0;
+ if (res.body && typeof res.body.getReader === 'function') {
+ const reader = res.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ received += value.byteLength;
+ if (received > maxBytes) {
+ try { await reader.cancel(); } catch { /* already closed */ }
+ throw new VerifyError('too_large', `Deliverable exceeds the ${formatBytes(maxBytes)} in-browser verify cap.`);
+ }
+ chunks.push(value);
+ if (onProgress) onProgress(received, declared);
+ }
+ } else {
+ const ab = await res.arrayBuffer();
+ if (ab.byteLength > maxBytes) throw new VerifyError('too_large', `Deliverable exceeds the ${formatBytes(maxBytes)} in-browser verify cap.`);
+ chunks.push(new Uint8Array(ab));
+ received = ab.byteLength;
+ }
+
+ if (received === 0) throw new VerifyError('empty', 'The deliverable was empty (0 bytes) — nothing to hash.');
+
+ const bytes = new Uint8Array(received);
+ let off = 0;
+ for (const c of chunks) { bytes.set(c, off); off += c.byteLength; }
+
+ let hashHex;
+ try {
+ hashHex = await sha256Hex(bytes);
+ } catch (err) {
+ throw new VerifyError('hash', `Failed to hash the deliverable: ${err?.message || 'digest error'}`);
+ }
+ return { bytes, hashHex, size: received, contentType };
+}
+
+// Heuristic: is this deliverable a GLB/GLTF we should try to render inline?
+function looksLikeGlb(url, contentType, bytes) {
+ const u = String(url || '').toLowerCase();
+ if (u.endsWith('.glb') || u.endsWith('.gltf')) return true;
+ if (/model\/gltf|gltf-binary|octet-stream/.test(contentType || '') && bytes) {
+ // GLB magic: 'glTF' (0x46546C67) little-endian at byte 0.
+ return bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46;
+ }
+ return false;
+}
+
+// ── DOM: the verifier widget ───────────────────────────────────────────────────
+
+// Mount the verifier into `container`. Renders the Verify button (or an honest
+// "can't verify" note when there's no proofHash / URL), runs the re-hash on
+// click, and shows ✓/✗ with both hashes. For a verified GLB it renders the model
+// inline from the very bytes that were hashed — proof you can see and orbit.
+//
+// mountVerifier(el, { deliverableUrl, proofHash, cluster })
+export function mountVerifier(container, { deliverableUrl, proofHash } = {}) {
+ container.classList.add('agora-verify');
+ const hasUrl = !!deliverableUrl;
+ const hasProof = !!normalizeHex(proofHash);
+
+ const status = h('div', { class: 'agora-verify-status', 'aria-live': 'polite' });
+ const actions = h('div', { class: 'agora-verify-actions' });
+ const detail = h('div', { class: 'agora-verify-detail' });
+
+ if (!hasUrl || !hasProof) {
+ // Honest: we cannot offer a verification we can't perform.
+ status.appendChild(h('div', { class: 'agora-verify-note' }, [
+ !hasProof
+ ? 'No on-chain proofHash recorded for this task — there is nothing to verify against.'
+ : 'No deliverable URL recorded — there are no bytes to re-hash.',
+ ]));
+ container.replaceChildren(status, detail);
+ return;
+ }
+
+ const onChainRow = h('div', { class: 'agora-hash-row' }, [
+ h('span', { class: 'agora-hash-label' }, ['on-chain proofHash']),
+ h('code', { class: 'agora-hash' }, [shortId(normalizeHex(proofHash), 10, 10)]),
+ copyChip(normalizeHex(proofHash), 'proofHash'),
+ ]);
+
+ const verifyBtn = h('button', { class: 'agora-btn agora-btn-primary', type: 'button' }, [
+ h('span', { class: 'agora-btn-icon', 'aria-hidden': 'true' }, ['⎙']),
+ 'Verify deliverable',
+ ]);
+ const openLink = h('a', {
+ class: 'agora-btn agora-btn-ghost',
+ href: deliverableUrl,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ }, ['Open deliverable ↗']);
+
+ actions.append(verifyBtn, openLink);
+ container.replaceChildren(onChainRow, actions, status, detail);
+
+ let abort = null;
+ verifyBtn.addEventListener('click', async () => {
+ if (abort) abort.abort();
+ abort = new AbortController();
+ verifyBtn.disabled = true;
+ verifyBtn.classList.add('is-busy');
+ detail.replaceChildren();
+ status.replaceChildren(h('div', { class: 'agora-verify-progress' }, [
+ h('span', { class: 'agora-skel agora-skel-line' }),
+ h('span', { class: 'agora-verify-progress-label' }, ['Fetching & hashing in your browser…']),
+ ]));
+ const progressLabel = status.querySelector('.agora-verify-progress-label');
+
+ try {
+ const result = await fetchAndHash(deliverableUrl, {
+ signal: abort.signal,
+ onProgress: (received, total) => {
+ if (!progressLabel) return;
+ progressLabel.textContent = total
+ ? `Hashing ${formatBytes(received)} / ${formatBytes(total)}…`
+ : `Hashing ${formatBytes(received)}…`;
+ },
+ });
+ const cmp = compareHash(result.hashHex, proofHash);
+ renderResult(status, detail, { cmp, result, deliverableUrl });
+ } catch (err) {
+ renderFailure(status, detail, err, deliverableUrl);
+ } finally {
+ verifyBtn.disabled = false;
+ verifyBtn.classList.remove('is-busy');
+ abort = null;
+ }
+ });
+}
+
+function renderResult(status, detail, { cmp, result, deliverableUrl }) {
+ const ok = cmp.match;
+ status.replaceChildren(h('div', { class: `agora-verdict ${ok ? 'is-match' : 'is-mismatch'}`, role: ok ? 'status' : 'alert' }, [
+ h('span', { class: 'agora-verdict-icon', 'aria-hidden': 'true' }, [ok ? '✓' : '✗']),
+ h('div', { class: 'agora-verdict-text' }, [
+ h('strong', {}, [ok ? 'Verified — hashes match' : 'Mismatch — does NOT match the chain']),
+ h('span', { class: 'agora-verdict-sub' }, [
+ ok
+ ? 'The deliverable you just downloaded hashes to exactly the proofHash recorded on-chain.'
+ : 'The bytes at this URL do not hash to the on-chain proofHash. The deliverable was changed, replaced, or tampered with.',
+ ]),
+ ]),
+ ]));
+
+ const rows = [
+ hashCompareRow('computed (your browser)', cmp.computed, ok),
+ hashCompareRow('on-chain proofHash', cmp.expected, ok),
+ h('div', { class: 'agora-kv' }, [
+ h('span', { class: 'agora-kv-key' }, ['size']),
+ h('span', { class: 'agora-kv-val' }, [formatBytes(result.size)]),
+ ]),
+ result.contentType ? h('div', { class: 'agora-kv' }, [
+ h('span', { class: 'agora-kv-key' }, ['type']),
+ h('span', { class: 'agora-kv-val' }, [result.contentType]),
+ ]) : null,
+ ].filter(Boolean);
+ detail.replaceChildren(h('div', { class: 'agora-verify-hashes' }, rows));
+
+ // A verified GLB renders inline from the exact bytes we hashed.
+ if (ok && looksLikeGlb(deliverableUrl, result.contentType, result.bytes)) {
+ const viewer = h('div', { class: 'agora-glb-viewer', 'aria-label': 'Verified 3D model — drag to orbit' });
+ const caption = h('div', { class: 'agora-glb-caption' }, ['Verified model — drag to orbit · scroll to zoom']);
+ detail.append(viewer, caption);
+ renderGlbInline(viewer, result.bytes).catch((err) => {
+ viewer.replaceChildren(h('div', { class: 'agora-glb-fail' }, [`Could not render the model: ${err?.message || 'unknown error'}`]));
+ });
+ }
+}
+
+function hashCompareRow(label, hex, ok) {
+ return h('div', { class: 'agora-hash-row' }, [
+ h('span', { class: 'agora-hash-label' }, [label]),
+ h('code', { class: `agora-hash ${ok ? 'is-ok' : 'is-bad'}` }, [hex || '—']),
+ hex ? copyChip(hex, label) : null,
+ ].filter(Boolean));
+}
+
+function renderFailure(status, detail, err, deliverableUrl) {
+ const code = err instanceof VerifyError ? err.code : 'fetch';
+ status.replaceChildren(h('div', { class: 'agora-verdict is-error', role: 'alert' }, [
+ h('span', { class: 'agora-verdict-icon', 'aria-hidden': 'true' }, ['⚠']),
+ h('div', { class: 'agora-verdict-text' }, [
+ h('strong', {}, ['Could not verify']),
+ h('span', { class: 'agora-verdict-sub' }, [err?.message || 'The deliverable could not be fetched or hashed.']),
+ ]),
+ ]));
+ // CORS is the common honest failure: the bytes exist but the host won't let a
+ // browser read them cross-origin. Offer the direct link so the user can fetch
+ // and hash out-of-band rather than see a check we never computed.
+ if (code === 'cors' || code === 'fetch') {
+ detail.replaceChildren(h('p', { class: 'agora-verify-note' }, [
+ 'Open the deliverable directly and hash it yourself (',
+ h('code', { class: 'agora-hash-inline' }, ['sha256']),
+ ') to compare against the on-chain proofHash above — ',
+ h('a', { href: deliverableUrl, target: '_blank', rel: 'noopener noreferrer' }, ['open deliverable ↗']),
+ '.',
+ ]));
+ } else {
+ detail.replaceChildren();
+ }
+}
+
+// Lazy-load a tiny self-contained GLB orbit viewer for the verified bytes. Kept
+// out of the module top so the pure verify core never pulls three/addons.
+async function renderGlbInline(container, bytes) {
+ const [{ default: makeViewer }] = await Promise.all([import('./glb-viewer.js')]);
+ await makeViewer(container, bytes);
+}
+
+export { copyText };
diff --git a/src/city/city-scene.js b/src/city/city-scene.js
new file mode 100644
index 000000000..7d1d5d309
--- /dev/null
+++ b/src/city/city-scene.js
@@ -0,0 +1,76 @@
+import * as THREE from 'three';
+import { Sky } from 'three/addons/objects/Sky.js';
+
+// Shared City substrate — the renderer, scene (fog + lights + sky), and camera
+// that both /city (src/city/city-world.js) and /agora (src/agora/agora-world.js)
+// stand on. Extracted so the two worlds render an identical place: the same
+// Manhattan lighting, sky, and tone mapping, built once here. Geometry (OSM
+// buildings, roads) is layered on top by city-map.js's buildCity in each entry.
+
+// Build the renderer, scene, and camera for a City-substrate world. The caller
+// owns the OSM city geometry (buildCity), the camera controller, and the render
+// loop — this only assembles the shared environment so both worlds match.
+//
+// @param {HTMLCanvasElement} canvas
+// @returns {{ renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera, sun: THREE.DirectionalLight, sky: Sky }}
+export function createCityScene(canvas) {
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFShadowMap;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 0.88;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.Fog(0x9aafbf, 200, 900);
+
+ const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 1200);
+ camera.position.set(0, 14, 24);
+
+ scene.add(new THREE.AmbientLight(0xc0d4e8, 1.5));
+
+ const sun = new THREE.DirectionalLight(0xffe8c0, 2.2);
+ sun.position.set(80, 100, -60);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(4096, 4096);
+ sun.shadow.camera.near = 1;
+ sun.shadow.camera.far = 1200;
+ sun.shadow.camera.left = -300;
+ sun.shadow.camera.right = 300;
+ sun.shadow.camera.top = 300;
+ sun.shadow.camera.bottom = -300;
+ sun.shadow.bias = -0.0006;
+ scene.add(sun);
+
+ const fill = new THREE.DirectionalLight(0x90b8e0, 0.75);
+ fill.position.set(-80, 60, 80);
+ scene.add(fill);
+
+ scene.add(new THREE.HemisphereLight(0x92bada, 0x4a5e40, 0.65));
+
+ const sky = new Sky();
+ sky.scale.setScalar(8000);
+ scene.add(sky);
+ const su = sky.material.uniforms;
+ su.turbidity.value = 3.5;
+ su.rayleigh.value = 2.5;
+ su.mieCoefficient.value = 0.005;
+ su.mieDirectionalG.value = 0.92;
+ su.sunPosition.value.set(0.45, 0.38, -0.80).normalize();
+
+ return { renderer, scene, camera, sun, sky };
+}
+
+// Keep the renderer + camera in sync with the viewport. Returns the bound
+// handler so the caller can remove it on teardown.
+export function bindResize(renderer, camera) {
+ const onResize = () => {
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ };
+ window.addEventListener('resize', onResize);
+ return onResize;
+}
diff --git a/src/city/city-world.js b/src/city/city-world.js
index 4773ed1bc..2c3ad7783 100644
--- a/src/city/city-world.js
+++ b/src/city/city-world.js
@@ -1,6 +1,6 @@
import * as THREE from 'three';
-import { Sky } from 'three/addons/objects/Sky.js';
import { fetchOSMData, buildCity, buildMinimapStatic, CITY_HALF } from './city-map.js';
+import { createCityScene, bindResize } from './city-scene.js';
import { CityPlayer } from './city-player.js';
import { CityCamera } from './city-camera.js';
import { log } from '../shared/log.js';
@@ -26,56 +26,10 @@ function progress(pct, label) {
async function main() {
progress(5, 'Setting up renderer…');
- const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- renderer.setSize(window.innerWidth, window.innerHeight);
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFShadowMap;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 0.88;
- renderer.outputColorSpace = THREE.SRGBColorSpace;
-
- const scene = new THREE.Scene();
- scene.fog = new THREE.Fog(0x9aafbf, 200, 900);
-
- const camera = new THREE.PerspectiveCamera(58, window.innerWidth / window.innerHeight, 0.1, 1200);
- camera.position.set(0, 14, 24);
-
- progress(12, 'Adding lights…');
-
- scene.add(new THREE.AmbientLight(0xc0d4e8, 1.5));
-
- const sun = new THREE.DirectionalLight(0xffe8c0, 2.2);
- sun.position.set(80, 100, -60);
- sun.castShadow = true;
- sun.shadow.mapSize.set(4096, 4096);
- sun.shadow.camera.near = 1;
- sun.shadow.camera.far = 1200;
- sun.shadow.camera.left = -300;
- sun.shadow.camera.right = 300;
- sun.shadow.camera.top = 300;
- sun.shadow.camera.bottom = -300;
- sun.shadow.bias = -0.0006;
- scene.add(sun);
-
- const fill = new THREE.DirectionalLight(0x90b8e0, 0.75);
- fill.position.set(-80, 60, 80);
- scene.add(fill);
-
- scene.add(new THREE.HemisphereLight(0x92bada, 0x4a5e40, 0.65));
+ const { renderer, scene, camera } = createCityScene(canvas);
progress(22, 'Building sky…');
- const sky = new Sky();
- sky.scale.setScalar(8000);
- scene.add(sky);
- const su = sky.material.uniforms;
- su.turbidity.value = 3.5;
- su.rayleigh.value = 2.5;
- su.mieCoefficient.value = 0.005;
- su.mieDirectionalG.value = 0.92;
- su.sunPosition.value.set(0.45, 0.38, -0.80).normalize();
-
// ── Fetch real-world Manhattan OSM data ───────────────────────────────────
let osmData;
try {
@@ -108,11 +62,7 @@ async function main() {
const cityCamera = new CityCamera(camera, canvas);
canvas.addEventListener('contextmenu', e => e.preventDefault());
- window.addEventListener('resize', () => {
- renderer.setSize(window.innerWidth, window.innerHeight);
- camera.aspect = window.innerWidth / window.innerHeight;
- camera.updateProjectionMatrix();
- });
+ bindResize(renderer, camera);
canvas.focus();
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 01d817077..3ba220738 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -1270,6 +1270,7 @@ export class CommunityUI {
this.joystick = el('div', { id: 'cc-joystick' });
this._buildTagHud();
+ this._buildKingHud();
this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, this.danceBtn, chat, this.emoteTray, this.reactionBar, hint, this.joystick]);
document.body.appendChild(this.hud);
}
@@ -1335,6 +1336,140 @@ export class CommunityUI {
if (this._tagAlert) this._tagAlert.classList.remove('cc-tag-alert--show');
}
+ // ── King of the Totem HUD (R07) ───────────────────────────────────────────
+ // Top-centre panel: round countdown, who holds the totem, a live scoreboard
+ // (your row highlighted, the king crowned), and a centre-screen winner banner.
+ // Every value here is server-authoritative — the HUD only renders the last
+ // snapshot and runs a local countdown between the per-second broadcasts.
+
+ _buildKingHud() {
+ this._kingTimer = el('div', { class: 'cc-king-timer', text: '1:30' });
+ this._kingTimerCap = el('div', { class: 'cc-king-timer-cap', text: 'round time' });
+ // aria-live on the status line only (not the whole panel) so a screen reader
+ // announces phase changes — "X holds the totem", "Round over" — without
+ // reading the per-second countdown.
+ this._kingPhase = el('div', { class: 'cc-king-phase', 'aria-live': 'polite' });
+ this._kingBoard = el('div', { class: 'cc-king-board', role: 'list', 'aria-label': 'King of the Totem scoreboard' });
+ this._kingEmpty = el('div', { class: 'cc-king-empty', hidden: true });
+ this._kingHud = el('div', { id: 'cc-king-hud', hidden: true }, [
+ el('div', { class: 'cc-king-head' }, [
+ el('span', { class: 'cc-king-head-ico', 'aria-hidden': 'true', text: '👑' }),
+ el('span', { class: 'cc-king-head-txt', text: 'King of the Totem' }),
+ ]),
+ el('div', { class: 'cc-king-clock' }, [this._kingTimer, this._kingTimerCap]),
+ this._kingPhase,
+ this._kingBoard,
+ this._kingEmpty,
+ ]);
+ document.body.appendChild(this._kingHud);
+
+ // Centre-screen winner flash, mirroring the tag "YOU'RE IT!" alert.
+ this._kingBanner = el('div', { id: 'cc-king-banner', 'aria-live': 'assertive' });
+ document.body.appendChild(this._kingBanner);
+ }
+
+ /** Drive the HUD from a server snapshot (round start/tick/end + join sync). */
+ setKingState({ phase, now, endsAt, nextAt, kingId, winner, scores = [], localId }) {
+ if (!this._kingHud) return;
+ this._kingHud.hidden = false;
+ // Anchor the local countdown to the SERVER clock: estimate the skew once per
+ // snapshot so the timer keeps ticking smoothly between the per-second beats
+ // (and through the intermission, which the server doesn't tick every second).
+ this._kingClock = {
+ phase,
+ skew: (typeof now === 'number' ? now : Date.now()) - Date.now(),
+ endsAt: endsAt || 0,
+ nextAt: nextAt || 0,
+ };
+ this._renderKingTimer();
+ if (!this._kingTimerInt) this._kingTimerInt = setInterval(() => this._renderKingTimer(), 250);
+
+ if (phase === 'idle') {
+ this._kingBoard.hidden = true;
+ this._kingEmpty.hidden = false;
+ this._kingEmpty.textContent = 'Waiting for players — step onto the gold ring at the totem to start a round.';
+ this._kingPhase.textContent = 'Waiting for players';
+ return;
+ }
+
+ this._kingEmpty.hidden = true;
+ this._kingBoard.hidden = false;
+ this._renderKingBoard(scores, kingId, localId);
+
+ if (phase === 'intermission') {
+ this._kingPhase.textContent = winner ? `🏆 ${winner.name} won the round` : 'Round over — nobody held it';
+ } else {
+ const kRow = kingId ? scores.find((s) => s.id === kingId) : null;
+ this._kingPhase.textContent = kingId
+ ? (kingId === localId ? '👑 You hold the totem!' : `👑 ${kRow ? kRow.name : 'Someone'} holds the totem`)
+ : 'Totem is open — claim it!';
+ }
+ }
+
+ /** Re-render just the countdown from the stored server-clock anchor. */
+ _renderKingTimer() {
+ const c = this._kingClock;
+ if (!c || !this._kingTimer) return;
+ const serverNow = Date.now() + c.skew;
+ if (c.phase === 'idle') {
+ this._kingTimer.textContent = '—';
+ this._kingTimer.classList.remove('cc-king-low');
+ this._kingTimerCap.textContent = 'waiting';
+ return;
+ }
+ const target = c.phase === 'intermission' ? c.nextAt : c.endsAt;
+ const secs = Math.max(0, Math.ceil((target - serverNow) / 1000));
+ this._kingTimer.textContent = `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, '0')}`;
+ this._kingTimer.classList.toggle('cc-king-low', c.phase === 'active' && secs <= 10);
+ this._kingTimerCap.textContent = c.phase === 'intermission' ? 'next round' : 'round time';
+ }
+
+ /** Rebuild the scoreboard rows: sorted by the server, your row highlighted, the
+ * current king crowned, the leader medalled. Caps at the rows the server sent. */
+ _renderKingBoard(scores, kingId, localId) {
+ this._kingBoard.innerHTML = '';
+ if (!scores.length) {
+ this._kingBoard.appendChild(el('div', { class: 'cc-king-row cc-king-row--empty', text: 'No players yet' }));
+ return;
+ }
+ scores.forEach((s, i) => {
+ const isMe = s.id === localId;
+ const isKing = s.id === kingId;
+ const tag = isKing ? '👑 ' : (i === 0 && s.score > 0 ? '🥇 ' : '');
+ this._kingBoard.appendChild(
+ el('div', { class: `cc-king-row${isMe ? ' cc-king-me' : ''}${isKing ? ' cc-king-holding' : ''}`, role: 'listitem' }, [
+ el('span', { class: 'cc-king-rank', text: String(i + 1) }),
+ el('span', { class: 'cc-king-name', text: tag + (isMe ? 'You' : s.name) }),
+ el('span', { class: 'cc-king-score', text: String(s.score) }),
+ ]),
+ );
+ });
+ }
+
+ /** Flash the centre-screen winner banner for 5 s, then fade. */
+ showKingWinner(winner, isMe) {
+ const b = this._kingBanner;
+ if (!b || !winner) return;
+ b.innerHTML = '';
+ b.appendChild(el('div', { class: 'cc-king-banner-crown', 'aria-hidden': 'true', text: '👑' }));
+ b.appendChild(el('div', { class: 'cc-king-banner-title', text: isMe ? "You're the King of the Totem!" : `${winner.name} wins the round!` }));
+ b.appendChild(el('div', { class: 'cc-king-banner-sub', text: `${winner.score} points` }));
+ b.classList.remove('cc-king-banner--show');
+ void b.offsetWidth; // restart the animation
+ b.classList.add('cc-king-banner--show');
+ clearTimeout(this._kingBannerTimer);
+ this._kingBannerTimer = setTimeout(() => b.classList.remove('cc-king-banner--show'), 5000);
+ }
+
+ /** Hide the King HUD + banner and stop the local countdown (called on leave). */
+ hideKingHud() {
+ if (this._kingHud) this._kingHud.hidden = true;
+ if (this._kingBanner) this._kingBanner.classList.remove('cc-king-banner--show');
+ clearInterval(this._kingTimerInt);
+ this._kingTimerInt = null;
+ this._kingClock = null;
+ }
+
// ---------------------------------------------------------------- build structures (R20)
// The structures toolbar that rides above the block hotbar while build mode is
// on: pick a composite piece (wall / floor / stairs / doorway) instead of a
@@ -2022,9 +2157,12 @@ export class CommunityUI {
if (def) this._ewSetEmote(def);
}
- // Called from coincommunities.js _loop for gamepad thumbstick support.
- ewGamepadTick(stickX, stickY, btnPlay) {
+ // Called from coincommunities.js _loop for gamepad support: the left stick steers
+ // the category selection, the south button plays the selected clip, and the east
+ // button closes the wheel without playing (cancel).
+ ewGamepadTick(stickX, stickY, btnPlay, btnCancel = false) {
if (!this._ewOpen) return;
+ if (btnCancel) { this.closeEmoteWheel(false); return; }
if (Math.hypot(stickX, stickY) > 0.35) {
const angle = (Math.atan2(stickY, stickX) * 180) / Math.PI;
let best = 0; let bestD = Infinity;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 8fab2061d..6bad518d7 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -79,6 +79,12 @@ const REACTIONS = [
// Confetti palette: monochrome-ish whites + very faint warm/cool accents.
const CONFETTI_COLORS = ['#ffffff', '#e8e8e8', '#fff8e1', '#e3f2fd', '#f3e5f5', '#e8f5e9'];
+// King of the Totem (R07): the hold-the-totem zone, centred on the coin totem
+// (built at world (0, -12) in _buildTotem). Mirrors the server's KING_ZONE so the
+// rendered ring and the authoritative scoring area are the same circle. The server
+// also sends these bounds in every game:king message; this is the render default.
+const KING_ZONE = { x: 0, z: -12, r: 3.5 };
+
const WORLD_RADIUS = 58; // a touch inside the server's 60m clamp
const MOVE_SPEED = 4.2;
const RUN_SPEED = 8.0; // hold Shift to sprint
@@ -789,6 +795,7 @@ export class CoinCommunities {
this._buildTotem(coin);
this._buildScreen(coin);
this._buildDanceFloor();
+ this._buildKingZone();
// The market reactor turns the live trade tape into world behaviour: buys
// ripple green and kick the boundary ring, sells ripple red, volume spins
// the totem, the rolling % drives the weather, and whales detonate a beam
@@ -952,6 +959,7 @@ export class CoinCommunities {
this.net.on('chat', (m) => this._onChat(m));
this.net.on('reaction', (m) => this._onReaction(m));
this.net.on('tag', (msg) => this._onTagMessage(msg)); // R08 tag mini-game
+ this.net.on('king', (msg) => this._onKing(msg)); // R07 King of the Totem
this.net.on('ping', (ms) => this.ui.setPing(ms));
this.net.on('blockAdd', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); this._syncBudget(); });
this.net.on('blockChange', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });
@@ -1304,6 +1312,9 @@ export class CoinCommunities {
this._removeLocalGlowRing();
this._removeLocalItLabel();
this._localIsIt = false;
+ // King of the Totem (R07): tear down the zone + crown marker and hide the HUD.
+ this._disposeKingZone();
+ this.ui.hideKingHud();
if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }
if (this._nipple) { this._nipple.destroy(); this._nipple = null; }
this.phase = 'lobby';
@@ -1325,7 +1336,12 @@ export class CoinCommunities {
this._updateOnline();
}
_onChange(player, id) {
- if (id === this.net.sessionId) return;
+ if (id === this.net.sessionId) {
+ // Tag mini-game (R08): the local player isn't a RemotePlayer, so drive
+ // our own glow ring + head label off our authoritative schema "it" flag.
+ this._updateLocalItMarker(player.it);
+ return;
+ }
this.remotes.get(id)?.apply(player);
}
_onRemove(id) {
@@ -1737,6 +1753,141 @@ export class CoinCommunities {
}
}
+ // ── King of the Totem (R07) ──────────────────────────────────────────────────
+ // A round-based area-control game. The server is the sole authority: it tracks
+ // who's inside the king-zone at the totem base, awards points to a SOLE occupant
+ // each second (contested = nobody scores), runs 90 s rounds, and broadcasts the
+ // timer, scoreboard, current king and winner. This client only renders: the
+ // ground ring, a crown that follows the current king, the HUD, and a confetti
+ // burst on the winner. It never computes or trusts a score.
+
+ _buildKingZone() {
+ const { x, z, r } = KING_ZONE;
+ const g = new Group();
+ g.position.set(x, 0, z);
+
+ // Boundary ring on the ground — a warm gold annulus that reads as the coin's
+ // own colour (matches the totem disc), so the zone clearly belongs to the totem.
+ const ringMat = new MeshBasicMaterial({ color: 0xffce5c, transparent: true, opacity: 0.42, depthWrite: false, side: DoubleSide });
+ const ring = new Mesh(new RingGeometry(r - 0.2, r, 72), ringMat);
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.03;
+ g.add(ring);
+ this._kingRingMat = ringMat;
+
+ // Soft fill so the contested area is legible from above without hiding the ground.
+ const fillMat = new MeshBasicMaterial({ color: 0xffce5c, transparent: true, opacity: 0.05, depthWrite: false, side: DoubleSide });
+ const fill = new Mesh(new CircleGeometry(r - 0.1, 72), fillMat);
+ fill.rotation.x = -Math.PI / 2;
+ fill.position.y = 0.02;
+ g.add(fill);
+ this._kingFillMat = fillMat;
+
+ this.world.add(g);
+ this._kingZone = g;
+ this._kingZoneT = 0;
+ this._kingId = null;
+
+ // A crown ring that follows whoever currently holds the zone. Lives in world
+ // space (not parented to an avatar) and is repositioned each frame, so a king
+ // leaving never strands geometry on a disposed rig.
+ const crownMat = new MeshBasicMaterial({ color: 0xffd86b, transparent: true, opacity: 0.85, depthWrite: false });
+ this._kingCrownRing = new Mesh(new RingGeometry(0.46, 0.72, 36), crownMat);
+ this._kingCrownRing.rotation.x = -Math.PI / 2;
+ this._kingCrownRing.position.y = 0.05;
+ this._kingCrownRing.visible = false;
+ this.world.add(this._kingCrownRing);
+
+ // A 👑 that floats above the king's head, projected to screen each frame.
+ this._kingCrownLabel = document.createElement('div');
+ this._kingCrownLabel.className = 'cc-king-crown';
+ this._kingCrownLabel.textContent = '👑';
+ this._kingCrownLabel.style.display = 'none';
+ document.body.appendChild(this._kingCrownLabel);
+ }
+
+ // World/screen position of a player (local or remote) by session id, or null if
+ // they aren't in our view (left, or their avatar hasn't loaded yet).
+ _kingPlayerPos(id) {
+ if (!id) return null;
+ if (id === this.net?.sessionId) return { pos: this.localPos, height: this.localHeight || 1.7 };
+ const r = this.remotes.get(id);
+ if (r) return { pos: r.rig.position, height: r.height || 1.7 };
+ return null;
+ }
+
+ // Per-frame: pulse the zone (brighter while held, brightest when YOU hold it) and
+ // move the crown to the current king. Pure rendering off the last server snapshot.
+ _tickKingZone(dt) {
+ if (!this._kingZone) return;
+ this._kingZoneT += dt;
+ const held = !!this._kingId;
+ const mine = held && this._kingId === this.net?.sessionId;
+ const breathe = 0.34 + 0.12 * Math.sin(this._kingZoneT * 2);
+ this._kingRingMat.opacity = breathe + (held ? 0.2 : 0) + (mine ? 0.2 : 0);
+ this._kingFillMat.opacity = 0.05 + (held ? 0.05 : 0) + (mine ? 0.07 : 0);
+
+ const kp = held ? this._kingPlayerPos(this._kingId) : null;
+ if (kp) {
+ this._kingCrownRing.visible = true;
+ this._kingCrownRing.position.set(kp.pos.x, 0.05, kp.pos.z);
+ this._kingCrownRing.material.opacity = 0.62 + 0.3 * (0.5 + 0.5 * Math.sin(this._kingZoneT * 5));
+ this._projectKingCrown(kp.pos, kp.height);
+ } else {
+ this._kingCrownRing.visible = false;
+ if (this._kingCrownLabel) this._kingCrownLabel.style.display = 'none';
+ }
+ }
+
+ // Project the floating 👑 above the king's head to a screen position, reusing the
+ // same camera projection as the reaction sprites / nameplate labels.
+ _projectKingCrown(pos, height) {
+ const lbl = this._kingCrownLabel;
+ if (!lbl || !this.camera || !this.renderer) return;
+ const w = this.renderer.domElement.clientWidth;
+ const h = this.renderer.domElement.clientHeight;
+ const v = new Vector3(pos.x, pos.y + height + 0.42, pos.z).project(this.camera);
+ if (v.z > 1 || v.z < -1) { lbl.style.display = 'none'; return; }
+ lbl.style.left = ((v.x * 0.5 + 0.5) * w) + 'px';
+ lbl.style.top = ((-v.y * 0.5 + 0.5) * h) + 'px';
+ lbl.style.display = '';
+ }
+
+ // Authoritative game state from the server (round start/tick/end + join sync).
+ _onKing(msg) {
+ if (!msg || !msg.event) return;
+ const localId = this.net?.sessionId;
+ this._kingId = msg.kingId || null;
+ this.ui.setKingState({ ...msg, localId });
+ if (msg.event === 'end' && msg.winner) {
+ const isMe = msg.winner.id === localId;
+ const wp = this._kingPlayerPos(msg.winner.id);
+ if (wp) this._spawnConfetti(wp.pos, wp.height);
+ // Make sure the local champion always gets a burst even if their avatar is
+ // off the winner-position path above (e.g. camera angle), so winning feels good.
+ if (isMe && (!wp || wp.pos !== this.localPos)) this._spawnConfetti(this.localPos, this.localHeight || 1.7);
+ this.ui.showKingWinner(msg.winner, isMe);
+ }
+ }
+
+ _disposeKingZone() {
+ if (this._kingZone) {
+ this._kingZone.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });
+ this.world?.remove(this._kingZone);
+ this._kingZone = null;
+ }
+ if (this._kingCrownRing) {
+ this._kingCrownRing.geometry.dispose();
+ this._kingCrownRing.material.dispose();
+ this.world?.remove(this._kingCrownRing);
+ this._kingCrownRing = null;
+ }
+ if (this._kingCrownLabel) { this._kingCrownLabel.remove(); this._kingCrownLabel = null; }
+ this._kingRingMat = null;
+ this._kingFillMat = null;
+ this._kingId = null;
+ }
+
// Live rename: persist and broadcast so peers' nameplates update instantly.
_rename(name) {
const clean = (name || '').trim().slice(0, 24);
@@ -2566,16 +2717,26 @@ export class CoinCommunities {
for (const [, r] of this.remotes) r.tick(dt);
this.worldObjects?.update();
this._updateLabels();
+ this._tickKingZone(dt);
this._updateVoice();
this.playSystems?.tick(dt);
this.agentCommerce?.tick(dt);
this.intelKiosk?.tick(dt);
if (this.worldLife) { this.worldLife.setRealPeers(this.remotes.size); this.worldLife.tick(dt); }
if (this.net) this.net.sendMove({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z, yaw: this.localYaw, motion: this.motion });
- // Gamepad: left stick steers the emote wheel; south button (0) plays selected.
+ // Gamepad: north button (Y/△, 3) opens the emote wheel; once open, the left
+ // stick steers and the south button (A/✕, 0) plays the selected clip. Edge-
+ // detect the open button so holding it doesn't reopen on the frame it closes.
const gp = navigator.getGamepads?.()[0];
- if (gp && this.ui.emoteWheelOpen) {
- this.ui.ewGamepadTick(gp.axes[0] ?? 0, gp.axes[1] ?? 0, gp.buttons[0]?.pressed ?? false);
+ if (gp) {
+ const openBtn = gp.buttons[3]?.pressed ?? false;
+ if (openBtn && !this._ewPadOpenPrev && !this.ui.emoteWheelOpen && !this.buildHud.active) {
+ this.ui.openEmoteWheel();
+ }
+ this._ewPadOpenPrev = openBtn;
+ if (this.ui.emoteWheelOpen) {
+ this.ui.ewGamepadTick(gp.axes[0] ?? 0, gp.axes[1] ?? 0, gp.buttons[0]?.pressed ?? false, gp.buttons[1]?.pressed ?? false);
+ }
}
}
this._tickEnv(dt);
diff --git a/src/game/community-net.js b/src/game/community-net.js
index d9057e8e5..ef524c128 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -157,6 +157,7 @@ export class CommunityNet {
reaction: new Set(), // ({id, emoji}) — a player sent a floating reaction
tag: new Set(), // ({event, itId, leaderboard}) — tag mini-game state (R08)
floorBeat: new Set(), // ({clip}) — disco-pad beat tick (R06): pulses the floor + aligns standing dancers
+ king: new Set(), // ({event, phase, endsAt, scores, kingId, winner, zone}) — King of the Totem state (R07)
};
this.ping = null; // smoothed RTT in ms, null until the first echo
this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo
@@ -300,6 +301,11 @@ export class CommunityNet {
// lockstep. The server message keeps its colon namespace; we normalize it to
// a camelCase event like the other namespaced messages above.
this.room.onMessage('floor:beat', (msg) => this._emit('floorBeat', msg || {}));
+ // King of the Totem (R07): the room broadcasts round start/tick/end (and a
+ // targeted sync on join) for the hold-the-totem mini-game. Server-authoritative
+ // — the client only renders the HUD + zone. Colon-namespaced like floor:beat;
+ // normalized to a camelCase `king` event.
+ this.room.onMessage('game:king', (msg) => this._emit('king', msg || {}));
const $ = getStateCallbacks(this.room);
const $state = $(this.room.state);
diff --git a/tests/walkroom-tag.test.js b/tests/walkroom-tag.test.js
new file mode 100644
index 000000000..ea17b3584
--- /dev/null
+++ b/tests/walkroom-tag.test.js
@@ -0,0 +1,150 @@
+// R08 — Tag mini-game: server-authoritative "it" assignment, proximity-gated
+// transfer, and tag-back immunity. The full WalkRoom needs the Colyseus runtime,
+// so these tests drive the pure tag helpers against a minimal stand-in
+// (Object.create avoids the Room constructor). They lock the invariants a
+// malicious client must not be able to break: exactly one "it", no across-map
+// tag, and no instant tag-back inside the immunity window.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';
+
+// A Player-like record carrying only the fields the tag helpers read/write.
+function player(name, x, z) {
+ return { name, x, y: 0, z, it: false, itSince: 0 };
+}
+
+// Build a WalkRoom instance without the Colyseus constructor, wiring only the
+// state + broadcast surface the tag helpers touch. `broadcasts` and `sent`
+// capture outgoing messages so tests can assert what peers/clients receive.
+function makeRoom() {
+ const room = Object.create(WalkRoom.prototype);
+ room.state = { players: new Map() };
+ room._tagImmunity = new Map();
+ room._tagTime = new Map();
+ room.clients = [];
+ room.broadcasts = [];
+ room.sent = [];
+ room.broadcast = (type, msg) => room.broadcasts.push({ type, msg });
+ room.send = (client, type, msg) => room.sent.push({ client, type, msg });
+ return room;
+}
+
+// Seat a player and register their tag time tracker, mirroring onJoin.
+function seat(room, id, name, x, z) {
+ room.state.players.set(id, player(name, x, z));
+ room._tagTime.set(id, { timeMs: 0, becameIt: null });
+ room.clients.push({ sessionId: id });
+}
+
+function itCount(room) {
+ let n = 0;
+ for (const [, p] of room.state.players) if (p.it) n++;
+ return n;
+}
+
+describe('WalkRoom tag mini-game (R08)', () => {
+ let room;
+ beforeEach(() => { room = makeRoom(); });
+
+ it('assigns exactly one "it" and alerts only that client', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 10, 10);
+ room._assignIt('a');
+
+ expect(itCount(room)).toBe(1);
+ expect(room.state.players.get('a').it).toBe(true);
+ expect(room.state.players.get('a').itSince).toBeGreaterThan(0);
+ expect(room._itPlayer()).toBe('a');
+ // The became-it alert goes only to the newly tagged client.
+ const becameIt = room.sent.filter(s => s.msg?.event === 'became-it');
+ expect(becameIt).toHaveLength(1);
+ expect(becameIt[0].client.sessionId).toBe('a');
+ // A full state broadcast follows so every client refreshes the HUD.
+ expect(room.broadcasts.some(b => b.msg?.event === 'state' && b.msg.itId === 'a')).toBe(true);
+ });
+
+ it('transfers "it" only to a player within range', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 1.0, 0); // 1.0m away — inside TAG_RANGE_M (2.0)
+ seat(room, 'c', 'Cara', 50, 50); // far away — must never be tagged
+ room._assignIt('a');
+
+ room._checkTag('a', room.state.players.get('a'));
+
+ expect(room.state.players.get('b').it).toBe(true);
+ expect(room.state.players.get('a').it).toBe(false);
+ expect(room.state.players.get('c').it).toBe(false);
+ expect(itCount(room)).toBe(1); // never double-it
+ });
+
+ it('does not tag across the map (server proximity is authoritative)', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 5, 0); // 5m away — out of range
+ room._assignIt('a');
+
+ room._checkTag('a', room.state.players.get('a'));
+
+ expect(room.state.players.get('a').it).toBe(true); // still it
+ expect(room.state.players.get('b').it).toBe(false);
+ });
+
+ it('applies tag-back immunity so "it" cannot bounce instantly', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 1.0, 0);
+ room._assignIt('a');
+
+ // a tags b — a is now immune for TAG_IMMUNITY_MS.
+ room._checkTag('a', room.state.players.get('a'));
+ expect(room.state.players.get('b').it).toBe(true);
+
+ // b immediately tries to tag a back while a is still adjacent — blocked.
+ room._checkTag('b', room.state.players.get('b'));
+ expect(room.state.players.get('b').it).toBe(true); // b keeps it
+ expect(room.state.players.get('a').it).toBe(false);
+
+ // Once a's immunity has lapsed, a tag-back is allowed again.
+ room._tagImmunity.set('a', Date.now() - 1);
+ room._checkTag('b', room.state.players.get('b'));
+ expect(room.state.players.get('a').it).toBe(true);
+ expect(itCount(room)).toBe(1);
+ });
+
+ it('accumulates per-session time-as-it across stints', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 1.0, 0);
+ room._assignIt('a');
+
+ // Simulate a having been "it" for 1.2s, then a tags b (finalizes a's stint).
+ const ta = room._tagTime.get('a');
+ ta.becameIt = Date.now() - 1200;
+ room._checkTag('a', room.state.players.get('a'));
+
+ expect(room._tagTime.get('a').timeMs).toBeGreaterThanOrEqual(1200);
+ expect(room._tagTime.get('a').becameIt).toBeNull(); // stint closed
+ // b's stint is now open.
+ expect(room._tagTime.get('b').becameIt).not.toBeNull();
+ });
+
+ it('orders the leaderboard by total time and caps it at 8 rows', () => {
+ for (let i = 0; i < 10; i++) seat(room, `p${i}`, `P${i}`, i * 100, 0);
+ // Give each player a distinct accumulated time, ascending with index.
+ for (let i = 0; i < 10; i++) room._tagTime.get(`p${i}`).timeMs = (i + 1) * 1000;
+ room._broadcastTagState();
+
+ const state = room.broadcasts.find(b => b.msg?.event === 'state');
+ expect(state.msg.leaderboard).toHaveLength(8); // top 8 only
+ // Descending by time: p9 (10000ms) first.
+ expect(state.msg.leaderboard[0].id).toBe('p9');
+ const times = state.msg.leaderboard.map(r => r.timeMs);
+ expect(times).toEqual([...times].sort((a, b) => b - a));
+ });
+
+ it('_randomTagPlayer never returns the excluded id', () => {
+ seat(room, 'a', 'Alice', 0, 0);
+ seat(room, 'b', 'Bob', 1, 0);
+ seat(room, 'c', 'Cara', 2, 0);
+ for (let i = 0; i < 50; i++) {
+ expect(room._randomTagPlayer('a')).not.toBe('a');
+ }
+ });
+});
diff --git a/vercel.json b/vercel.json
index eed73e50a..b0c496bc2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -870,6 +870,10 @@
"src": "/city/?",
"dest": "/city.html"
},
+ {
+ "src": "/agora/?",
+ "dest": "/agora.html"
+ },
{
"src": "/play/agent-wallet/?",
"dest": "/play/agent-wallet.html"
diff --git a/vite.config.js b/vite.config.js
index 3f2b9ef50..2e0c9e0bd 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -439,6 +439,7 @@ const appConfig = {
'walk-leaderboard': resolve(__dirname, 'pages/walk-leaderboard.html'),
'walk-analytics': resolve(__dirname, 'pages/walk-analytics.html'),
city: resolve(__dirname, 'pages/city.html'),
+ agora: resolve(__dirname, 'pages/agora.html'),
play: resolve(__dirname, 'pages/play.html'),
'play-agent-wallet': resolve(__dirname, 'pages/play/agent-wallet.html'),
'play-arena': resolve(__dirname, 'pages/play/arena.html'),
diff --git a/workers/agora-citizens/.gitignore b/workers/agora-citizens/.gitignore
new file mode 100644
index 000000000..93c695a27
--- /dev/null
+++ b/workers/agora-citizens/.gitignore
@@ -0,0 +1,4 @@
+# Devnet signing keypairs for each citizen + the work dispatcher. Cached so a
+# citizen keeps its on-chain identity across restarts. NEVER commit a secret key.
+.cache/
+node_modules/
diff --git a/workers/agora-citizens/agenc.js b/workers/agora-citizens/agenc.js
new file mode 100644
index 000000000..62713a3d9
--- /dev/null
+++ b/workers/agora-citizens/agenc.js
@@ -0,0 +1,161 @@
+// agora-citizens — the on-chain layer. A thin, retry-wrapped adapter over
+// @three-ws/solana-agent (which wraps @tetsuo-ai/sdk → the AgenC coordination
+// protocol on Solana). The SDK ships as TS and is imported LAZILY (dynamic
+// import, cached) so module load never crashes when its dist/ isn't built yet —
+// exactly how api/agora/[action].js reaches the write SDK. Every mutating call is
+// wrapped in bounded retry/backoff so a transient RPC failure for one citizen
+// never halts the fleet.
+
+import { PublicKey } from '@solana/web3.js';
+import { log } from './log.js';
+
+// AgenC TaskState enum (from @tetsuo-ai/sdk). Open tasks are claimable.
+export const TASK_STATE = {
+ Open: 0,
+ InProgress: 1,
+ PendingValidation: 2,
+ Completed: 3,
+ Cancelled: 4,
+ Disputed: 5,
+};
+
+let _sdk = null;
+async function sdk() {
+ if (_sdk) return _sdk;
+ _sdk = await import('@three-ws/solana-agent');
+ return _sdk;
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Run an on-chain call with bounded exponential backoff. Returns the result, or
+ * rethrows the last error after cfg.maxRetries attempts so the caller can decide
+ * (per-citizen) whether to skip this tick.
+ */
+export async function withRetry(fn, cfg, label) {
+ let lastErr = null;
+ for (let attempt = 0; attempt <= cfg.maxRetries; attempt++) {
+ try {
+ return await fn();
+ } catch (err) {
+ lastErr = err;
+ if (attempt === cfg.maxRetries) break;
+ const waitMs = cfg.retryBaseMs * Math.pow(2, attempt) + Math.floor(cfg.retryBaseMs * 0.5);
+ log.warn('onchain retry', { label, attempt: attempt + 1, err: err?.message, retryMs: waitMs });
+ await sleep(waitMs);
+ }
+ }
+ throw lastErr;
+}
+
+/**
+ * Derive a citizen's canonical AgenC identity from its identity proofs
+ * (composite > erc8004 > mpl-core > handle) via the identity bridge — no new
+ * namespace invented. Returns the 32-byte id (bytes + hex), the provenance, and
+ * the metadataUri to register with.
+ */
+export async function deriveIdentity(ref) {
+ const s = await sdk();
+ const result = s.getCanonicalThreewsAgenCId(ref);
+ const agentIdHex = s.agenCAgentIdToHex(result.agenCAgentId);
+ const metadataUri = s.buildThreewsMetadataUri(ref);
+ return {
+ agentIdBytes: result.agenCAgentId,
+ agentIdHex,
+ source: result.source,
+ label: result.label,
+ metadataUri,
+ };
+}
+
+export async function makeReadClient(cfg) {
+ const s = await sdk();
+ return s.createAgenCClient({ cluster: cfg.cluster, rpcUrl: cfg.rpcUrl });
+}
+
+export async function makeSignerClient(cfg, signer) {
+ const s = await sdk();
+ return s.createAgenCClient({ cluster: cfg.cluster, rpcUrl: cfg.rpcUrl, signer });
+}
+
+export async function derivePda(client, agentIdHex) {
+ const s = await sdk();
+ return s.deriveAgenCAgentPda(client, agentIdHex);
+}
+
+export async function getAgent(client, pda) {
+ const s = await sdk();
+ return s.getAgenCAgent(client, pda);
+}
+
+/**
+ * Ensure a wallet is registered as an AgenC agent (idempotent). If the PDA
+ * already exists on-chain we reconcile from it rather than re-registering.
+ * Returns { agentPda, txSignature|null, existed, agent }.
+ */
+export async function ensureRegistered(client, agentIdHex, params, cfg) {
+ const s = await sdk();
+ const pda = s.deriveAgenCAgentPda(client, agentIdHex);
+ const existing = await withRetry(() => s.getAgenCAgent(client, pda), cfg, 'getAgent');
+ if (existing) {
+ return { agentPda: pda, txSignature: null, existed: true, agent: existing };
+ }
+ const result = await withRetry(
+ () =>
+ s.registerAgenCAgent(client, {
+ agentId: agentIdHex,
+ capabilities: params.capabilities,
+ endpoint: params.endpoint,
+ metadataUri: params.metadataUri ?? null,
+ stakeAmount: params.stakeLamports,
+ }),
+ cfg,
+ 'registerAgent',
+ );
+ const agent = await withRetry(() => s.getAgenCAgent(client, result.agentPda), cfg, 'getAgent:postRegister');
+ return { agentPda: result.agentPda, txSignature: result.txSignature, existed: false, agent };
+}
+
+/** List every task created by a wallet (used to reconcile the dispatcher pool). */
+export async function listCreatorTasks(client, creator) {
+ const s = await sdk();
+ const pk = creator instanceof PublicKey ? creator : new PublicKey(creator);
+ return withRetry(() => s.listAgenCTasksByCreator(client, pk), { maxRetries: 2, retryBaseMs: 1000 }, 'listTasksByCreator');
+}
+
+export async function getTask(client, taskPda) {
+ const s = await sdk();
+ return s.getAgenCTask(client, taskPda instanceof PublicKey ? taskPda : new PublicKey(taskPda));
+}
+
+/** Post a real on-chain task (used by the internal devnet work dispatcher). */
+export async function createTask(client, args, cfg) {
+ const s = await sdk();
+ return withRetry(() => s.createAgenCTask(client, args), cfg, 'createTask');
+}
+
+export async function claimTask(client, args, cfg) {
+ const s = await sdk();
+ return withRetry(() => s.claimAgenCTask(client, args), cfg, 'claimTask');
+}
+
+export async function completeTask(client, args, cfg) {
+ const s = await sdk();
+ return withRetry(() => s.completeAgenCTask(client, args), cfg, 'completeTask');
+}
+
+export async function formatTaskState(state) {
+ const s = await sdk();
+ try {
+ return s.formatTaskState(state);
+ } catch {
+ return String(state);
+ }
+}
+
+/** Generate a fresh 32-byte task id (dispatcher posts unique tasks). */
+export async function generateTaskId() {
+ const s = await sdk();
+ return s.generateAgenCTaskId();
+}
diff --git a/workers/agora-citizens/config.js b/workers/agora-citizens/config.js
new file mode 100644
index 000000000..173ce2be3
--- /dev/null
+++ b/workers/agora-citizens/config.js
@@ -0,0 +1,112 @@
+// agora-citizens — environment + runtime configuration for the life engine.
+// Validated once at boot so a misconfigured worker fails loudly instead of
+// running half a config. Long-lived process (NOT a Vercel cron): it registers a
+// fleet of devnet AgenC agents, then runs each citizen's daily loop on its own
+// jittered cadence, projecting every on-chain action into agora_citizens /
+// agora_activity and the live feed.
+//
+// AGORA_DRY_RUN=1 — plan only: read the board, decide, but never sign a tx
+// or write the DB. Inspect the loop safely.
+// AGORA_ONCE=1 — run a single tick per citizen, then exit (CI / manual).
+// AGORA_MAX_CITIZENS=N — cap the fleet (faucet-friendly local runs).
+//
+// Guardrails: devnet rewards are native SOL (synthetic plumbing — never another
+// real token). $THREE is the only coin Agora promotes; on mainnet the reward
+// label is '$THREE'. See docs/agora.md and CLAUDE.md.
+
+function req(name) {
+ const v = process.env[name];
+ if (!v || !String(v).trim()) throw new Error(`[agora-citizens] missing required env var: ${name}`);
+ return String(v).trim();
+}
+function opt(name, def = undefined) {
+ const v = process.env[name];
+ return v == null || v === '' ? def : String(v).trim();
+}
+function num(name, def) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return def;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : def;
+}
+function bool(name, def = false) {
+ const raw = process.env[name];
+ if (raw == null || raw === '') return def;
+ return /^(1|true|yes|on)$/i.test(String(raw).trim());
+}
+
+export function loadConfig() {
+ const dryRun = bool('AGORA_DRY_RUN', false);
+
+ // DATABASE_URL is the projection sink. A dry run reads the board + plans but
+ // never writes, so it can run without a DB — handy for inspecting the loop
+ // with zero side effects.
+ const databaseUrl = dryRun ? opt('DATABASE_URL', '') : req('DATABASE_URL');
+
+ const cluster = (opt('AGORA_CLUSTER', 'devnet')).toLowerCase();
+ if (cluster !== 'devnet' && cluster !== 'mainnet') {
+ throw new Error(`[agora-citizens] AGORA_CLUSTER must be devnet|mainnet, got "${cluster}"`);
+ }
+ // Mainnet is escrowed in $THREE and is out of scope for the devnet life
+ // engine — refuse to run live there so a stray env can't move real value.
+ if (cluster === 'mainnet' && !dryRun) {
+ throw new Error('[agora-citizens] mainnet life-engine is out of scope for this worker (devnet only). Set AGORA_CLUSTER=devnet.');
+ }
+
+ const rpcUrl = opt('AGENC_DEVNET_RPC_URL') || opt('SOLANA_RPC_URL_DEVNET') || opt('AGENC_RPC_URL') || undefined;
+
+ return {
+ cluster,
+ rpcUrl,
+ dryRun,
+ // Single tick per citizen then exit — for CI smoke tests and manual runs.
+ once: bool('AGORA_ONCE', false),
+ databaseUrl,
+
+ // Fleet size cap. The roster supplies the candidate citizens (seeded from
+ // real platform agents where possible); this bounds how many we actually
+ // run so a local devnet run respects faucet limits.
+ maxCitizens: Math.max(1, Math.min(50, num('AGORA_MAX_CITIZENS', 4))),
+ // Floor on the fleet when seeding can't find enough real agents — fill with
+ // standalone roster citizens so the world is never empty.
+ minCitizens: Math.max(1, num('AGORA_MIN_CITIZENS', 3)),
+
+ // Per-citizen loop cadence. Each citizen ticks every base ± jitter so the
+ // fleet doesn't stampede the RPC / faucet in lockstep.
+ tickBaseMs: Math.max(5_000, num('AGORA_TICK_MS', 45_000)),
+ tickJitterMs: Math.max(0, num('AGORA_TICK_JITTER_MS', 20_000)),
+
+ // Devnet work supply. With no human/agent bounties yet (Task 03), an
+ // internal dispatcher keeps a small pool of real on-chain Fetcher tasks
+ // open so citizens have genuine work to claim → do → prove → earn. This is
+ // devnet plumbing (native SOL rewards), not the Task-03 bounty product; it
+ // posts no agora `posted_task` projection and escrows no $THREE. Disable to
+ // run citizens against externally-supplied tasks only.
+ dispatchTasks: bool('AGORA_DISPATCH_TASKS', cluster === 'devnet'),
+ minOpenTasks: Math.max(0, num('AGORA_MIN_OPEN_TASKS', 3)),
+ maxOpenTasks: Math.max(1, num('AGORA_MAX_OPEN_TASKS', 8)),
+ taskRewardLamports: Math.max(1, num('AGORA_TASK_REWARD_LAMPORTS', 1_000_000)), // 0.001 SOL devnet
+ taskDeadlineSecs: Math.max(300, num('AGORA_TASK_DEADLINE_SECS', 3_600)),
+
+ // Minimum on-chain stake per agent (AgenC protocol minAgentStake on devnet).
+ stakeLamports: Math.max(1_000_000, num('AGORA_STAKE_LAMPORTS', 1_000_000)),
+
+ // Faucet top-up: keep each signer above the threshold so a claim/complete
+ // (which pays fees + locks reward) never fails for lack of SOL.
+ topupThresholdLamports: Math.max(0, num('AGORA_TOPUP_THRESHOLD_LAMPORTS', 200_000_000)), // 0.2 SOL
+ airdropLamports: Math.max(0, num('AGORA_AIRDROP_LAMPORTS', 1_000_000_000)), // 1 SOL
+
+ // Where the citizen reads the world from. The board endpoint surfaces the
+ // x402 bazaar (real Fetcher work) and any open AgenC tasks. The bridge is
+ // the live work target the Fetcher fingerprints for its proof.
+ apiBase: (opt('AGORA_API_BASE', 'https://three.ws')).replace(/\/+$/, ''),
+
+ // Retry/backoff for every on-chain call. A single citizen's failure must
+ // never halt the fleet.
+ maxRetries: Math.max(0, num('AGORA_MAX_RETRIES', 4)),
+ retryBaseMs: Math.max(200, num('AGORA_RETRY_BASE_MS', 1_500)),
+
+ // Liveness heartbeat into bot_heartbeat (shared ops visibility). 0 disables.
+ heartbeatMs: Math.max(0, num('AGORA_HEARTBEAT_MS', 30_000)),
+ };
+}
diff --git a/workers/agora-citizens/keypair.js b/workers/agora-citizens/keypair.js
new file mode 100644
index 000000000..8f2363fb4
--- /dev/null
+++ b/workers/agora-citizens/keypair.js
@@ -0,0 +1,68 @@
+// agora-citizens — devnet keypair cache + faucet top-up. Each citizen (and the
+// internal work dispatcher) keeps a stable signing keypair under .cache/ so it
+// holds the same on-chain identity across restarts. Mirrors the proven approach
+// in examples/agenc-task-roundtrip/run.mjs. NEVER commit .cache/ (see .gitignore).
+
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import { log } from './log.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CACHE_DIR = path.join(__dirname, '.cache');
+
+function safeName(key) {
+ return String(key).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'kp';
+}
+
+/** Load a cached keypair for `key`, or generate + persist a fresh one. */
+export async function loadOrCreateKeypair(key) {
+ const file = path.join(CACHE_DIR, `${safeName(key)}.json`);
+ try {
+ const raw = await fs.readFile(file, 'utf8');
+ return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(raw)));
+ } catch (err) {
+ if (err.code !== 'ENOENT') throw err;
+ await fs.mkdir(CACHE_DIR, { recursive: true });
+ const kp = Keypair.generate();
+ await fs.writeFile(file, JSON.stringify(Array.from(kp.secretKey)), { mode: 0o600 });
+ log.info('keypair generated', { key, pubkey: kp.publicKey.toBase58() });
+ return kp;
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Keep a signer funded above cfg.topupThresholdLamports. The public devnet
+ * faucet is heavily rate-limited, so we request in shrinking chunks with backoff
+ * (the @solana/web3.js example-script pattern) before surfacing a manual-funding
+ * error. Returns the airdrop tx signature when one was performed, else null.
+ */
+export async function ensureBalance(connection, kp, cfg, label) {
+ const bal = await connection.getBalance(kp.publicKey);
+ if (bal >= cfg.topupThresholdLamports) return null;
+
+ const full = cfg.airdropLamports || LAMPORTS_PER_SOL;
+ const chunks = [full, full / 2, full / 4, full / 10];
+ let lastErr = null;
+ for (let attempt = 0; attempt < chunks.length; attempt++) {
+ const lamports = Math.max(Math.floor(chunks[attempt]), Math.floor(LAMPORTS_PER_SOL / 100));
+ try {
+ const sig = await connection.requestAirdrop(kp.publicKey, lamports);
+ await connection.confirmTransaction(sig, 'confirmed');
+ const newBal = await connection.getBalance(kp.publicKey);
+ log.info('airdrop confirmed', { label, sol: lamports / LAMPORTS_PER_SOL, sig, balance: newBal / LAMPORTS_PER_SOL });
+ if (newBal >= cfg.topupThresholdLamports) return sig;
+ } catch (err) {
+ lastErr = err;
+ const waitMs = cfg.retryBaseMs * (attempt + 1);
+ log.warn('airdrop attempt failed', { label, attempt: attempt + 1, err: err?.message, retryMs: waitMs });
+ await sleep(waitMs);
+ }
+ }
+ throw new Error(
+ `[agora-citizens] ${label}: devnet faucet exhausted retries — fund ${kp.publicKey.toBase58()} at https://faucet.solana.com or set AGENC_DEVNET_RPC_URL to a private RPC. Underlying: ${lastErr?.message || lastErr}`,
+ );
+}
diff --git a/workers/agora-citizens/log.js b/workers/agora-citizens/log.js
new file mode 100644
index 000000000..70a357396
--- /dev/null
+++ b/workers/agora-citizens/log.js
@@ -0,0 +1,16 @@
+// agora-citizens — structured, single-line JSON logging. Keypairs/secrets never
+// reach here; callers pass only ids, pubkeys, tx signatures, amounts, reasons.
+
+function emit(level, msg, meta) {
+ const rec = { t: new Date().toISOString(), w: 'agora-citizens', level, msg, ...(meta || {}) };
+ const line = JSON.stringify(rec);
+ if (level === 'error' || level === 'warn') console.error(line);
+ else console.log(line);
+}
+
+export const log = {
+ info: (msg, meta) => emit('info', msg, meta),
+ warn: (msg, meta) => emit('warn', msg, meta),
+ error: (msg, meta) => emit('error', msg, meta),
+ loop: (msg, meta) => emit('loop', msg, meta),
+};
diff --git a/workers/agora-citizens/narrative.js b/workers/agora-citizens/narrative.js
new file mode 100644
index 000000000..129d0ad93
--- /dev/null
+++ b/workers/agora-citizens/narrative.js
@@ -0,0 +1,78 @@
+// Agora narration — the single human-readable story line every economic action
+// carries. The activity feed, the economy ticker, and the 3D world narration all
+// render this one string (docs/agora.md). An activity with no story isn't worth
+// recording, so the projection's `narrative` column is NOT NULL — these builders
+// guarantee a real sentence for every kind.
+//
+// Pure module — no SDK / DB / network imports.
+
+/** Format an atomic reward + mint label into a human chip, e.g. "0.0050 SOL" or "25,000 $THREE". */
+export function rewardLabel({ amountAtomic, mint, decimals = 9 }) {
+ if (amountAtomic == null) return null;
+ let whole;
+ try {
+ const atomic = BigInt(amountAtomic);
+ const base = 10n ** BigInt(decimals);
+ const intPart = atomic / base;
+ const frac = atomic % base;
+ if (mint === '$THREE') {
+ // $THREE is rendered as a whole-token count with grouping (no long decimals).
+ whole = Number(atomic) / Number(base);
+ const rounded = Math.round(whole);
+ return `${rounded.toLocaleString('en-US')} $THREE`;
+ }
+ // Native SOL — 4 decimal places is the conventional precision.
+ const fracStr = frac.toString().padStart(decimals, '0').slice(0, 4);
+ return `${intPart.toString()}.${fracStr} SOL`;
+ } catch {
+ return null;
+ }
+}
+
+export function postedTaskNarrative({ poster, profession, reward, minReputation }) {
+ const repClause = minReputation > 0 ? ` (needs reputation ${minReputation})` : '';
+ const rewardClause = reward ? ` worth ${reward}` : '';
+ return `${poster} posted a ${cap(profession)} bounty${rewardClause}${repClause}.`;
+}
+
+export function hiredNarrative({ poster, profession, reward, parentLabel }) {
+ const forClause = parentLabel ? ` to help finish "${truncate(parentLabel, 48)}"` : '';
+ const rewardClause = reward ? ` for ${reward}` : '';
+ return `${poster} hired a ${cap(profession)}${forClause}${rewardClause}.`;
+}
+
+export function claimedNarrative({ worker, profession, poster }) {
+ const fromClause = poster ? ` from ${poster}` : '';
+ return `${worker} claimed a ${cap(profession)} job${fromClause} and got to work.`;
+}
+
+export function completedNarrative({ worker, profession, reward, repBefore, repAfter }) {
+ const rewardClause = reward ? ` and earned ${reward}` : '';
+ const repClause =
+ repBefore != null && repAfter != null && repAfter !== repBefore
+ ? `; reputation ${repBefore} → ${repAfter}`
+ : '';
+ return `${worker} completed a ${cap(profession)} job${rewardClause}${repClause}.`;
+}
+
+export function earnedNarrative({ worker, reward }) {
+ return `${worker} received ${reward || 'a reward'} from escrow.`;
+}
+
+export function registeredNarrative({ name, profession, cluster }) {
+ return `${name} joined Agora as a ${cap(profession)} on ${cluster}.`;
+}
+
+export function reconcileNarrative({ poster, profession, verb }) {
+ return `${poster}'s ${cap(profession)} bounty ${verb}.`;
+}
+
+function cap(s) {
+ const t = String(s || 'worker');
+ return t.charAt(0).toUpperCase() + t.slice(1);
+}
+
+function truncate(s, n) {
+ const t = String(s || '');
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
+}
diff --git a/workers/agora-citizens/package.json b/workers/agora-citizens/package.json
new file mode 100644
index 000000000..879e8fe25
--- /dev/null
+++ b/workers/agora-citizens/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@three-ws/agora-citizens",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "Agora life engine — N real AgenC agents living the daily loop on Solana devnet: register, seek work, claim on-chain, do real Fetcher work, submit a real proof, earn, climb reputation, idle. Projects every action into agora_citizens / agora_activity and the live feed. See docs/agora.md.",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js",
+ "dry": "AGORA_DRY_RUN=1 node index.js",
+ "tick": "AGORA_ONCE=1 node index.js"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "dependencies": {
+ "@three-ws/solana-agent": "file:../../solana-agent-sdk",
+ "@tetsuo-ai/sdk": "^1.4.0",
+ "@solana/web3.js": "^1.98.0",
+ "@neondatabase/serverless": "^0.10.4",
+ "@upstash/redis": "^1.38.0"
+ }
+}
diff --git a/workers/agora-citizens/policy.js b/workers/agora-citizens/policy.js
new file mode 100644
index 000000000..3ab2839f6
--- /dev/null
+++ b/workers/agora-citizens/policy.js
@@ -0,0 +1,214 @@
+// Agora demand + labor-market policy — the REAL rules that decide when a citizen
+// posts a bounty, who may claim it, when a worker hires a sub-agent, and how a
+// reconcile sweep maps on-chain task state back onto the board.
+//
+// Every decision here is pure and deterministic: given the same citizen, clock,
+// balance, and config it returns the same plan. No money moves in this file — the
+// engine takes these plans and executes them on-chain. That separation is what
+// makes the economics unit-testable without a wallet or an RPC.
+//
+// Honest scarcity is enforced HERE, in code: a patron with a real on-chain
+// balance below the reward + fee headroom does NOT post. There is no infinite
+// tap — when a citizen runs out of funds it stops creating demand.
+//
+// Pure module — no SDK / DB / network imports.
+
+// Bit math lives in roster.js (the engine's profession registry) so there's one
+// source of truth for the capability bitmap. These thin aliases keep this
+// module's vocabulary ("capability subset", "bit for a profession") readable.
+import { professionBits, capabilitiesSatisfy } from './roster.js';
+
+const capabilityBitsFor = (keys) => professionBits(keys);
+const satisfiesCapabilities = (worker, required) => capabilitiesSatisfy(worker, required);
+const bitFor = (key) => professionBits([key]);
+
+// ── Reputation ladder ─────────────────────────────────────────────────────────
+// A visible career ladder: high-value work gates on reputation a new citizen
+// hasn't earned yet, so newcomers must grind low-value jobs to climb. Tiers are
+// documented here and surfaced in the worker README. minReputation is the
+// on-chain gate written into each posted task.
+//
+// apprentice rep ≥ 0 — entry work, anyone (incl. brand-new citizens)
+// journeyman rep ≥ 5 — needs a short track record
+// master rep ≥ 20 — reserved for proven citizens; the top of the board
+export const REPUTATION_LADDER = [
+ { tier: 'apprentice', minReputation: 0 },
+ { tier: 'journeyman', minReputation: 5 },
+ { tier: 'master', minReputation: 20 },
+];
+
+const LADDER_BY_TIER = new Map(REPUTATION_LADDER.map((t) => [t.tier, t]));
+
+/** minReputation gate for a named tier (0 for an unknown tier — fail open, never lock the board). */
+export function minReputationForTier(tier) {
+ return LADDER_BY_TIER.get(String(tier || '').toLowerCase())?.minReputation ?? 0;
+}
+
+/**
+ * Can this citizen claim this task? Two real gates, both on-chain facts:
+ * 1. capability subset — the worker advertises every required bit.
+ * 2. reputation — the worker's on-chain reputation clears the task's gate.
+ * The engine additionally excludes a citizen's own postings and already-worked
+ * tasks; this function answers only "is this citizen qualified."
+ */
+export function citizenCanClaim(citizen, task) {
+ if (!citizen || !task) return false;
+ if (!satisfiesCapabilities(citizen.capabilityBits, task.requiredCapabilities ?? 0)) return false;
+ const rep = Number(citizen.reputation || 0);
+ const gate = Number(task.minReputation || 0);
+ return rep >= gate;
+}
+
+/**
+ * Reason a citizen is NOT eligible — used for honest activity/heartbeat notes so
+ * the world can narrate "Cole skipped the master bounty (needs rep 20, has 2)".
+ * Returns null when the citizen IS eligible.
+ */
+export function ineligibilityReason(citizen, task) {
+ if (!satisfiesCapabilities(citizen.capabilityBits, task.requiredCapabilities ?? 0)) {
+ return 'missing_capability';
+ }
+ const rep = Number(citizen.reputation || 0);
+ const gate = Number(task.minReputation || 0);
+ if (rep < gate) return 'below_min_reputation';
+ return null;
+}
+
+/**
+ * Choose the next tier a patron posts, rotating through its configured tier
+ * schedule by post count so the board shows a healthy spread (mostly apprentice
+ * work, occasional journeyman/master rungs). `tiers` is the patron's authored
+ * schedule of { profession, rewardAtomic, minReputation, taskType?, maxWorkers? }.
+ */
+export function pickTier(tiers, postedCount) {
+ if (!Array.isArray(tiers) || tiers.length === 0) return null;
+ const idx = ((Number(postedCount) || 0) % tiers.length + tiers.length) % tiers.length;
+ return tiers[idx];
+}
+
+/**
+ * Decide whether a patron citizen posts a bounty this tick.
+ *
+ * @param {object} args
+ * @param {object} args.citizen the would-be poster (needs .patron config)
+ * @param {number} args.now epoch ms
+ * @param {number} args.lastPostAt epoch ms of the citizen's last post (0 if never)
+ * @param {bigint} args.balanceAtomic the poster's REAL spendable balance (lamports on
+ * devnet, $THREE base units on mainnet)
+ * @param {bigint} args.headroomAtomic reserve kept for fees / rent (never spent on rewards)
+ * @param {number} args.postedCount how many bounties this patron has posted (tier rotation)
+ * @returns {{post:boolean, reason:string, plan?:object}}
+ */
+export function decidePatronPost({ citizen, now, lastPostAt = 0, balanceAtomic, headroomAtomic = 0n, postedCount = 0 }) {
+ const patron = citizen?.patron;
+ if (!patron || !Array.isArray(patron.tiers) || patron.tiers.length === 0) {
+ return { post: false, reason: 'not_patron' };
+ }
+ const interval = Number(patron.minPostIntervalMs) || 0;
+ if (lastPostAt && now - lastPostAt < interval) {
+ return { post: false, reason: 'interval_guard' };
+ }
+
+ const tier = pickTier(patron.tiers, postedCount);
+ if (!tier) return { post: false, reason: 'no_tier' };
+
+ const reward = toBig(tier.rewardAtomic);
+ const need = reward + toBig(headroomAtomic);
+ const bal = toBig(balanceAtomic);
+ // Honest scarcity — no infinite tap. A patron that can't cover the reward
+ // plus fee headroom simply stops creating demand until it earns/refills.
+ if (bal < need) {
+ return { post: false, reason: 'insufficient_funds' };
+ }
+
+ return {
+ post: true,
+ reason: 'patron_demand',
+ plan: {
+ profession: tier.profession,
+ requiredCapabilities: capabilityBitsFor([tier.profession]),
+ rewardAtomic: reward,
+ minReputation: tier.minReputation ?? minReputationForTier(tier.tier),
+ tier: tier.tier || null,
+ taskType: tier.taskType || 'Exclusive',
+ maxWorkers: tier.maxWorkers || 1,
+ },
+ };
+}
+
+/**
+ * Decide whether a citizen mid-WORK hires a sub-agent for a capability it lacks
+ * (true agent-to-agent hiring). The worker pays a sub-reward out of its own real
+ * balance — same scarcity rule as a patron.
+ *
+ * @param {object} args
+ * @param {string} args.neededProfession the profession key the worker can't do itself
+ * @param {bigint} args.balanceAtomic the worker's spendable balance
+ * @param {bigint} args.subRewardAtomic reward offered for the sub-task
+ * @param {bigint} args.headroomAtomic fee/rent reserve
+ * @returns {{hire:boolean, reason:string, plan?:object}}
+ */
+export function decideHire({ neededProfession, balanceAtomic, subRewardAtomic, headroomAtomic = 0n }) {
+ const requiredCapabilities = bitFor(neededProfession);
+ if (requiredCapabilities === 0n) return { hire: false, reason: 'unknown_profession' };
+ const reward = toBig(subRewardAtomic);
+ const need = reward + toBig(headroomAtomic);
+ if (toBig(balanceAtomic) < need) return { hire: false, reason: 'insufficient_funds' };
+ return {
+ hire: true,
+ reason: 'subtask_demand',
+ plan: {
+ profession: neededProfession,
+ requiredCapabilities,
+ rewardAtomic: reward,
+ minReputation: 0, // sub-tasks are entry work so any qualified worker can pick them up fast
+ taskType: 'Exclusive',
+ maxWorkers: 1,
+ },
+ };
+}
+
+// ── Reconcile mapping ───────────────────────────────────────────────────────
+// On-chain task states (AgenC IDL): Open/Claimed/Completed/Cancelled/Disputed/
+// Expired. The board renders a posted_task as OPEN only while no later terminal
+// projection exists for its PDA. This maps the chain's truth to the projection
+// kind that closes it. Returning null means "still open — leave it on the board."
+const STATE_TRANSITIONS = {
+ open: null,
+ claimed: { kind: 'claimed_task', verb: 'was claimed' },
+ completed: { kind: 'completed_task', verb: 'was fulfilled' },
+ cancelled: { kind: 'cancelled_task', verb: 'was cancelled' },
+ expired: { kind: 'expired_task', verb: 'expired' },
+ // AgenC slashes stake on dispute resolution; a disputed task is no longer
+ // claimable, so it drops off the open board under the slashed lane.
+ disputed: { kind: 'slashed', verb: 'is under dispute' },
+};
+
+// The projection kinds that close a posted_task off the open board. The board
+// query (api/agora/[action].js) and the reconcile sweep MUST agree on this set.
+export const BOARD_TERMINAL_KINDS = ['claimed_task', 'completed_task', 'slashed', 'cancelled_task', 'expired_task'];
+
+/**
+ * Map an on-chain task state label to the projection transition that reflects it.
+ * Accepts the human label ('Open', 'Completed', …) or a raw enum number.
+ */
+export function reconcileTransition(stateLabel) {
+ if (stateLabel == null) return null;
+ let key;
+ if (typeof stateLabel === 'number') {
+ key = ['open', 'claimed', 'completed', 'cancelled', 'disputed', 'expired'][stateLabel];
+ } else {
+ key = String(stateLabel).trim().toLowerCase();
+ }
+ return STATE_TRANSITIONS[key] ?? null;
+}
+
+function toBig(v) {
+ if (typeof v === 'bigint') return v;
+ if (v == null) return 0n;
+ try {
+ return BigInt(Math.trunc(Number(v)));
+ } catch {
+ return 0n;
+ }
+}
diff --git a/workers/agora-citizens/roster.js b/workers/agora-citizens/roster.js
new file mode 100644
index 000000000..7d6757bc4
--- /dev/null
+++ b/workers/agora-citizens/roster.js
@@ -0,0 +1,161 @@
+// agora-citizens — the roster: profession bitmap + who lives in the world.
+//
+// Professions are AgenC u64 capability bits (the labor market's type system).
+// This map MUST stay in sync with docs/agora.md and the PROFESSIONS array in
+// api/agora/[action].js. Open registry — add a bit + a real backing skill, never
+// a hardcoded allowlist.
+//
+// Citizens are seeded from REAL platform agents (agent_identities) where
+// possible, so the world is populated by the same agents users built. When too
+// few real agents exist to reach the floor, we fill with standalone agent
+// citizens (still real on-chain AgenC agents — they register, work, and earn;
+// they just aren't linked to a user's agent record). We NEVER invent a human
+// citizen here (humans join via wallet-auth in Task 08).
+
+// Profession bit map — keep in lockstep with api/agora/[action].js PROFESSIONS.
+export const PROFESSIONS = [
+ { bit: 0, key: 'fetcher', label: 'Fetcher', skill: 'x402 service call' },
+ { bit: 1, key: 'sculptor', label: 'Sculptor', skill: 'text/image → rigged GLB (forge)' },
+ { bit: 2, key: 'scribe', label: 'Scribe', skill: 'research / write (brain)' },
+ { bit: 3, key: 'cartographer', label: 'Cartographer', skill: '3D scene / diorama' },
+ { bit: 4, key: 'crier', label: 'Crier', skill: 'TTS / voice / audio2face' },
+ { bit: 5, key: 'appraiser', label: 'Appraiser', skill: 'token / market intel' },
+ { bit: 6, key: 'verifier', label: 'Verifier', skill: 're-derive proofHash + attest' },
+ { bit: 7, key: 'namekeeper', label: 'Namekeeper', skill: '.sol / ENS resolve + mint' },
+];
+
+const PROF_BY_KEY = new Map(PROFESSIONS.map((p) => [p.key, p]));
+
+/** OR the bits for a set of profession keys into a u64 BigInt. */
+export function professionBits(keys) {
+ let bits = 0n;
+ for (const k of keys) {
+ const p = PROF_BY_KEY.get(k);
+ if (p) bits |= 1n << BigInt(p.bit);
+ }
+ return bits;
+}
+
+/** The primary (lowest-bit) profession key for a capability bitmap. */
+export function primaryProfession(bits) {
+ const b = typeof bits === 'bigint' ? bits : BigInt(bits || 0);
+ for (const p of PROFESSIONS) {
+ if ((b & (1n << BigInt(p.bit))) !== 0n) return p.key;
+ }
+ return null;
+}
+
+/** Does `caps` satisfy a task's `required` capability bitmap (required ⊆ caps)? */
+export function capabilitiesSatisfy(caps, required) {
+ const c = typeof caps === 'bigint' ? caps : BigInt(caps || 0);
+ const r = typeof required === 'bigint' ? required : BigInt(required || 0);
+ return (r & ~c) === 0n;
+}
+
+export function slug(s) {
+ return String(s || '')
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+}
+
+// Named home districts in the City. Citizens spawn and idle around their home;
+// world coords (x, z) on the City substrate. Spread so the world reads legibly.
+const DISTRICTS = [
+ { name: 'The Commons', x: 0, z: 0 },
+ { name: 'Bazaar Row', x: 18, z: -6 },
+ { name: 'Forge Quarter', x: -16, z: 10 },
+ { name: 'Scriptorium', x: 8, z: 20 },
+ { name: 'Wharf', x: -22, z: -14 },
+ { name: 'Beacon Hill', x: 24, z: 16 },
+];
+
+function districtFor(i) {
+ return DISTRICTS[i % DISTRICTS.length];
+}
+
+// Standalone Fetcher citizens — the founding workforce. All Fetchers in Task 02
+// (the one real profession this task ships). Each becomes a real AgenC agent on
+// devnet. Names are evocative, not branded; no coin references.
+const STANDALONE = [
+ { key: 'aria-fetch', displayName: 'Aria', professions: ['fetcher'] },
+ { key: 'koa-fetch', displayName: 'Koa', professions: ['fetcher'] },
+ { key: 'mira-fetch', displayName: 'Mira', professions: ['fetcher'] },
+ { key: 'toshi-fetch', displayName: 'Toshi', professions: ['fetcher'] },
+ { key: 'wren-fetch', displayName: 'Wren', professions: ['fetcher'] },
+ { key: 'ines-fetch', displayName: 'Inés', professions: ['fetcher'] },
+];
+
+function shapeStandalone(def, i) {
+ const home = districtFor(i);
+ return {
+ key: def.key,
+ kind: 'agent',
+ displayName: def.displayName,
+ profession: def.professions[0],
+ professionBits: professionBits(def.professions),
+ home,
+ agentDbId: null,
+ avatarUrl: null,
+ // Standalone citizens derive their canonical AgenC id from a stable handle.
+ identityRef: { handle: `agora-${def.key}` },
+ identityHint: `standalone:${def.key}`,
+ };
+}
+
+// Shape a real platform agent (agent_identities row) into a citizen spec. Its
+// canonical AgenC id is derived from whatever identity proofs it carries
+// (composite > erc8004 > mpl-core > handle) via the identity bridge.
+function shapeSeeded(agent, i) {
+ const home = districtFor(i);
+ const handle = slug(agent.name) || `agent-${String(agent.id).slice(0, 8)}`;
+ const ref = { handle };
+ if (agent.erc8004_agent_id != null) ref.erc8004AgentId = String(agent.erc8004_agent_id);
+ const mpl = agent.meta?.onchain?.solana?.asset || agent.meta?.onchain?.mplCoreAsset || agent.meta?.mplCoreAsset;
+ if (mpl) ref.mplCoreAsset = String(mpl);
+ return {
+ key: `agent-${slug(agent.name) || String(agent.id).slice(0, 8)}`,
+ kind: 'agent',
+ displayName: agent.name,
+ profession: 'fetcher',
+ // Every seeded citizen can at least Fetch (the one profession shipped in
+ // Task 02). Later tasks widen this from the agent's real skills.
+ professionBits: professionBits(['fetcher']),
+ home,
+ agentDbId: agent.id,
+ avatarUrl: agent.avatar_url || agent.profile_image_url || null,
+ identityRef: ref,
+ identityHint: `agent:${agent.id}`,
+ };
+}
+
+/**
+ * Assemble the fleet: prefer real platform agents, fill to the floor with
+ * standalone citizens, cap at maxCitizens. `seededAgents` is the rows returned
+ * by store.listSeedAgents() (may be empty). Returns citizen specs the engine
+ * registers + runs.
+ */
+export function buildRoster(seededAgents, cfg) {
+ const specs = [];
+ const seen = new Set();
+
+ for (let i = 0; i < (seededAgents || []).length && specs.length < cfg.maxCitizens; i++) {
+ const spec = shapeSeeded(seededAgents[i], specs.length);
+ if (seen.has(spec.key)) continue;
+ seen.add(spec.key);
+ specs.push(spec);
+ }
+
+ // Fill to the floor (and up to the cap) with standalone citizens so the world
+ // is never empty even on a fresh DB with no agents.
+ for (let i = 0; specs.length < cfg.maxCitizens && i < STANDALONE.length; i++) {
+ const spec = shapeStandalone(STANDALONE[i], specs.length);
+ if (seen.has(spec.key)) continue;
+ seen.add(spec.key);
+ specs.push(spec);
+ }
+
+ return specs.slice(0, cfg.maxCitizens);
+}
diff --git a/workers/agora-citizens/store.js b/workers/agora-citizens/store.js
new file mode 100644
index 000000000..9cc0dcb7b
--- /dev/null
+++ b/workers/agora-citizens/store.js
@@ -0,0 +1,230 @@
+// agora-citizens — projection sink. The worker runs OUTSIDE api/, so it owns its
+// own Neon client (not api/_lib/db.js) and its own Upstash Redis client mirroring
+// api/_lib/redis.js — the SAME `feed:events` bus the serverless API + multiplayer
+// server write to. Every write here is a PROJECTION of a real on-chain action:
+// agora_activity rows cite a tx_signature / task_pda, and citizen snapshots are
+// the last synced view of the chain (which stays authoritative for reputation,
+// stake, and status).
+//
+// Idempotency: agora_activity has a unique index on (citizen_id, kind,
+// tx_signature) where tx_signature is not null — re-running the engine never
+// double-projects an on-chain action. Activities without a tx (registered-on-
+// reconcile) are guarded by an explicit existence check.
+
+import { neon } from '@neondatabase/serverless';
+import { Redis } from '@upstash/redis';
+import { log } from './log.js';
+
+const FEED_KEY = 'feed:events';
+const FEED_MAX = 200; // matches api/_lib/feed.js MAX_EVENTS
+
+let _seq = 0;
+function feedEventId(ts) {
+ _seq = (_seq + 1) % 1_000_000;
+ return `${ts.toString(36)}-${_seq.toString(36)}`;
+}
+
+function makeRedis(cfg) {
+ const url = process.env.UPSTASH_REDIS_REST_URL;
+ const token = process.env.UPSTASH_REDIS_REST_TOKEN;
+ if (!url || !token) return null;
+ return new Redis({ url, token });
+}
+
+export function makeStore(cfg) {
+ // Dry runs and DB-less smoke tests can skip the Neon client; the engine never
+ // writes in dry-run mode, so a null sql is fine there.
+ const sql = cfg.databaseUrl ? neon(cfg.databaseUrl) : null;
+ const redis = cfg.dryRun ? null : makeRedis(cfg);
+
+ function requireSql() {
+ if (!sql) throw new Error('[agora-citizens] DATABASE_URL not configured (required for non-dry writes)');
+ return sql;
+ }
+
+ return {
+ hasRedis: !!redis,
+
+ /**
+ * Real platform agents to seed citizens from. Prefer public, non-deleted,
+ * non-template agents with at least one identity proof or a usable name.
+ * Empty on a fresh DB — the roster then fills with standalone citizens.
+ */
+ async listSeedAgents(limit) {
+ if (!sql) return [];
+ try {
+ const rows = await sql`
+ select id, name, avatar_url, profile_image_url, erc8004_agent_id, meta
+ from agent_identities
+ where deleted_at is null
+ and is_public = true
+ and coalesce(is_template, false) = false
+ and length(coalesce(name, '')) > 0
+ order by created_at asc
+ limit ${Math.max(0, Number(limit) || 0)}
+ `;
+ return rows || [];
+ } catch (err) {
+ log.warn('listSeedAgents failed — falling back to standalone roster', { err: err?.message });
+ return [];
+ }
+ },
+
+ /**
+ * Upsert a citizen by its deterministic on-chain PDA (the stable key — the
+ * same agent always derives the same PDA). Returns the citizen row id.
+ */
+ async upsertCitizen(spec, info) {
+ const db = requireSql();
+ const meta = JSON.stringify({
+ identityHint: spec.identityHint,
+ identitySource: info.identitySource,
+ identityLabel: info.identityLabel,
+ home: spec.home,
+ });
+ const rows = await db`
+ insert into agora_citizens (
+ kind, agent_id, display_name, avatar_url,
+ agenc_agent_id, agenc_agent_pda, agenc_cluster, identity_source,
+ profession, capability_bits, status,
+ home_x, home_z, pos_x, pos_z,
+ reputation, stake_lamports, synced_at, last_active_at, meta
+ ) values (
+ ${spec.kind}, ${spec.agentDbId}, ${spec.displayName}, ${spec.avatarUrl},
+ ${info.agentIdHex}, ${info.agentPda}, ${cfg.cluster}, ${info.identitySource},
+ ${spec.profession}, ${info.capabilityBits.toString()}, ${info.status || 'idle'},
+ ${spec.home.x}, ${spec.home.z}, ${spec.home.x}, ${spec.home.z},
+ ${info.reputation ?? 0}, ${String(info.stakeLamports ?? 0)}, now(), now(), ${meta}::jsonb
+ )
+ on conflict (agenc_agent_pda) do update set
+ agent_id = coalesce(excluded.agent_id, agora_citizens.agent_id),
+ display_name = excluded.display_name,
+ avatar_url = coalesce(excluded.avatar_url, agora_citizens.avatar_url),
+ agenc_agent_id = excluded.agenc_agent_id,
+ identity_source = excluded.identity_source,
+ profession = excluded.profession,
+ capability_bits = excluded.capability_bits,
+ reputation = excluded.reputation,
+ stake_lamports = excluded.stake_lamports,
+ synced_at = now(),
+ last_active_at = now(),
+ meta = agora_citizens.meta || ${meta}::jsonb
+ returning id
+ `;
+ return rows[0]?.id;
+ },
+
+ /** Has this (citizen, kind) already been projected for this tx? */
+ async activityExists(citizenId, kind, txSignature) {
+ if (!sql) return false;
+ if (txSignature) {
+ const r = await sql`
+ select 1 from agora_activity
+ where citizen_id = ${citizenId} and kind = ${kind} and tx_signature = ${txSignature}
+ limit 1
+ `;
+ return r.length > 0;
+ }
+ const r = await sql`
+ select 1 from agora_activity
+ where citizen_id = ${citizenId} and kind = ${kind} and tx_signature is null
+ limit 1
+ `;
+ return r.length > 0;
+ },
+
+ /**
+ * Append an activity row (idempotent on tx_signature). Returns the new row
+ * id, or null if it already existed. Every caller passes a non-empty
+ * narrative — an activity with no story isn't worth recording.
+ */
+ async appendActivity(a) {
+ const db = requireSql();
+ const rows = await db`
+ insert into agora_activity (
+ citizen_id, kind, task_pda, task_id, profession, counterparty_citizen_id,
+ amount_atomic, reward_mint, reward_label,
+ tx_signature, proof_hash, deliverable_url,
+ narrative, rep_before, rep_after, world_x, world_z, meta
+ ) values (
+ ${a.citizenId}, ${a.kind}, ${a.taskPda ?? null}, ${a.taskId ?? null}, ${a.profession ?? null},
+ ${a.counterpartyCitizenId ?? null},
+ ${a.amountAtomic != null ? String(a.amountAtomic) : null}, ${a.rewardMint ?? null}, ${a.rewardLabel ?? null},
+ ${a.txSignature ?? null}, ${a.proofHash ?? null}, ${a.deliverableUrl ?? null},
+ ${a.narrative}, ${a.repBefore ?? null}, ${a.repAfter ?? null},
+ ${a.worldX ?? null}, ${a.worldZ ?? null}, ${JSON.stringify(a.meta || {})}::jsonb
+ )
+ on conflict (citizen_id, kind, tx_signature) where tx_signature is not null
+ do nothing
+ returning id
+ `;
+ return rows[0]?.id ?? null;
+ },
+
+ /** Advance a citizen's world + economy snapshot after a real action. */
+ async updateCitizen(citizenId, patch) {
+ const db = requireSql();
+ await db`
+ update agora_citizens set
+ status = coalesce(${patch.status ?? null}, status),
+ reputation = coalesce(${patch.reputation ?? null}, reputation),
+ stake_lamports = coalesce(${patch.stakeLamports != null ? String(patch.stakeLamports) : null}, stake_lamports),
+ earned_three_atomic = earned_three_atomic + ${patch.earnedDelta != null ? String(patch.earnedDelta) : '0'},
+ tasks_completed = tasks_completed + ${Math.max(0, Number(patch.tasksCompletedDelta || 0))},
+ tasks_posted = tasks_posted + ${Math.max(0, Number(patch.tasksPostedDelta || 0))},
+ pos_x = coalesce(${patch.posX ?? null}, pos_x),
+ pos_z = coalesce(${patch.posZ ?? null}, pos_z),
+ synced_at = case when ${patch.synced ? true : false} then now() else synced_at end,
+ last_active_at = now()
+ where id = ${citizenId}
+ `;
+ },
+
+ /** Lightweight status/position write for the IDLE/SEEK/BUSY transitions. */
+ async setStatus(citizenId, status, pos) {
+ const db = requireSql();
+ await db`
+ update agora_citizens set
+ status = ${status},
+ pos_x = coalesce(${pos?.x ?? null}, pos_x),
+ pos_z = coalesce(${pos?.z ?? null}, pos_z),
+ last_active_at = now()
+ where id = ${citizenId}
+ `;
+ },
+
+ /**
+ * Publish an event onto the shared `feed:events` bus (newest-first capped
+ * list — identical shape + write path to api/_lib/feed.js). Best-effort:
+ * a Redis outage degrades to no ticker line, never a thrown error.
+ */
+ async publishFeed(event) {
+ if (!redis || !event || !event.type) return null;
+ const ts = Number.isFinite(event.ts) ? event.ts : Date.now();
+ const record = { ...event, ts, id: event.id || feedEventId(ts) };
+ try {
+ await redis.lpush(FEED_KEY, JSON.stringify(record));
+ await redis.ltrim(FEED_KEY, 0, FEED_MAX - 1);
+ return record;
+ } catch (err) {
+ log.warn('feed publish failed', { err: err?.message, type: event.type });
+ return null;
+ }
+ },
+
+ /** Liveness heartbeat into the shared bot_heartbeat table. */
+ async heartbeat(meta) {
+ if (!sql) return;
+ try {
+ await sql`
+ insert into bot_heartbeat (worker, mode, last_beat_at, meta)
+ values ('agora-citizens', ${cfg.cluster}, now(), ${JSON.stringify(meta || {})}::jsonb)
+ on conflict (worker) do update
+ set mode = excluded.mode, last_beat_at = excluded.last_beat_at, meta = excluded.meta
+ `;
+ } catch (err) {
+ log.warn('heartbeat write failed', { err: err?.message });
+ }
+ },
+ };
+}