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: expand Agora UI (job board, ticker, pulse feed) and citizens worker engine

nirholasf4cfaf103e72
diff --git a/.env.example b/.env.example
index 9a370a771..9b7347d25 100644
--- a/.env.example
+++ b/.env.example
@@ -380,6 +380,19 @@ X402_MAX_PER_DAY_ATOMIC=100000000
# POST /api/x402/admin/subscriptions and stored hashed in x402_subscriptions.
INTERNAL_API_KEY=
+# ── play / holder gate HMAC secret (REQUIRED IN PRODUCTION) ────────────────
+# The single HMAC key that mints and verifies every short-lived entry credential:
+# /play sign-in nonces + passes (api/_lib/play-pass.js), holder-world passes
+# (api/_lib/holder-pass.js), guest/presence tokens, $THREE quote signing, clash,
+# and world-service auth. The standalone Colyseus server (multiplayer/) verifies
+# the same tokens, so it MUST be set to the IDENTICAL value there.
+# Fail-closed by design: when unset with NODE_ENV=production, these modules refuse
+# to sign/verify with the public dev secret and throw — surfacing as a 500 on
+# GET /api/play/nonce (the first endpoint /play hits) and on the holder gate.
+# Leave unset only in local dev / CI (an insecure dev secret is used, with a warning).
+# Generate: openssl rand -base64 48
+HOLDER_PASS_SECRET=
+
# ── multiplayer ↔ API shared secret (presence + world persistence) ─────────
# One HMAC secret shared between this API and the standalone Colyseus server
# (multiplayer/). The API mints presence tickets the realm rooms verify, and the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1cfd3ff84..867c13e6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **King of the Totem: a new mini-game in the 3D worlds** — The /play worlds now run King of the Totem. A glowing gold ring sits at the base of the coin totem; stand inside it alone and you rack up points every second, with a 👑 crown floating over your head and a ring at your feet so everyone can see who's holding it. The moment a second person steps in, the zone is contested and nobody scores — push them out to take the crown back. Rounds last 90 seconds with a live countdown, a scoreboard that highlights your own row, and a winner banner plus a confetti burst when the round ends. Then a short intermission and the next round begins. Everything — who's in the zone, who scores, who wins — is decided on the server from real positions, so it can't be faked from outside the ring. Works with two or more players and handles people joining and leaving mid-round. (`/play`) `[feature]`
- **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]`
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index 600c72d73..a82b080b0 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -27,6 +27,12 @@
// world-join → { coin, coinName }
// jackpot → { reward, coin }
// mission-complete → { mission, gold, coop, coin } — /play job or heist finished
+// agora-registered → { citizenId, agentPda, profession, narrative } — a citizen joined Agora (AgenC registerAgent)
+// agora-task-posted → { actor, taskPda, profession, rewardLabel, minReputation, cluster } — a bounty was escrowed on the board (createTask)
+// agora-hired → { actor, taskPda, profession, rewardLabel, cluster } — a citizen hired a sub-agent (agent-to-agent)
+// agora-task-claimed → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — claimed an on-chain task
+// agora-task-completed→ { citizenId, agentPda, profession, taskPda, proofHash, txSig, explorerUrl, narrative } — proof accepted
+// agora-earned → { citizenId, agentPda, profession, rewardLabel, txSig, explorerUrl, narrative } — escrow released to the worker
//
// All writes are best-effort. The feed is a delight layer, never on a critical
// path: a Redis outage degrades to an empty feed, never a thrown error.
@@ -48,6 +54,14 @@ export const ALLOWED_TYPES = new Set([
'payment', // skill/service payment confirmed; { usdcAtomic, recipientLabel, txSig, explorerUrl }
'mission-complete', // /play job or co-op heist finished; { mission, gold, coop, coin }
'member-join', // a person signed in to three.ws; { handle } (actor = display name)
+ // Agora — the living agent economy (workers/agora-citizens). Each is a real
+ // on-chain AgenC action projected onto the ticker; see docs/agora.md.
+ 'agora-registered', // a citizen registered on AgenC
+ 'agora-task-posted', // a bounty was escrowed on the board (createTask)
+ 'agora-hired', // a citizen hired a sub-agent (agent-to-agent)
+ 'agora-task-claimed', // a citizen claimed an on-chain task
+ 'agora-task-completed', // a citizen submitted an accepted proof
+ 'agora-earned', // escrow released $THREE/SOL to the worker
]);
// Per-user notification types: stored in user_notifications (DB), never in the
diff --git a/content/x-mcp-manifesto.md b/content/x-mcp-manifesto.md
index 7749737a4..54ca52f7b 100644
--- a/content/x-mcp-manifesto.md
+++ b/content/x-mcp-manifesto.md
@@ -1,57 +1,57 @@
-# A body, a wallet, and a conscience — why three.ws built 31 MCP servers
+# 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.
+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 actually 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.
+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.
+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 covering 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.
+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.
+`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.
+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, so 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.
+- **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 and dry-run.** Irreversible actions require explicit confirmation, and you can preview exactly what an action would do before it runs.
+- **Signed receipts and 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 to trusted to 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.
+Put it together. Discovery (`pumpfun-mcp`: new, trending, and graduating tokens, bonding curves, holders), signals (`intel-mcp`, `signals-mcp`), alerts (`alerts-mcp`), a wallet, and guardrails. What you get is 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 and 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.
+- **`trading-mcp`.** The buy, sell, and snipe capability above, shipped in phases: quotes and positions first (read-only), then buys, then sells, then autopilot-generated trade proposals that flow through the same dry-run, confirm, and 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.
+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:
diff --git a/data/changelog.json b/data/changelog.json
index 893234cd9..4218a8bc9 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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": "King of the Totem: a new mini-game in the 3D worlds",
+ "summary": "The /play worlds now run King of the Totem. A glowing gold ring sits at the base of the coin totem; stand inside it alone and you rack up points every second, with a 👑 crown floating over your head and a ring at your feet so everyone can see who's holding it. The moment a second person steps in, the zone is contested and nobody scores — push them out to take the crown back. Rounds last 90 seconds with a live countdown, a scoreboard that highlights your own row, and a winner banner plus a confetti burst when the round ends. Then a short intermission and the next round begins. Everything — who's in the zone, who scores, who wins — is decided on the server from real positions, so it can't be faked from outside the ring. Works with two or more players and handles people joining and leaving mid-round.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-06-24",
"title": "Build mode: place props in the 3D worlds",
diff --git a/public/changelog.json b/public/changelog.json
index ed79cdfb3..f1aca0bf5 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T10:16:06.859Z",
+ "generated_at": "2026-06-24T10:20:21.854Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -284,6 +284,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-24",
+ "type": "update",
+ "title": "King of the Totem: a new mini-game in the 3D worlds",
+ "summary": "The /play worlds now run King of the Totem. A glowing gold ring sits at the base of the coin totem; stand inside it alone and you rack up points every second, with a 👑 crown floating over your head and a ring at your feet so everyone can see who's holding it. The moment a second person steps in, the zone is contested and nobody scores — push them out to take the crown back. Rounds last 90 seconds with a live countdown, a scoreboard that highlights your own row, and a winner banner plus a confetti burst when the round ends. Then a short intermission and the next round begins. Everything — who's in the zone, who scores, who wins — is decided on the server from real positions, so it can't be faked from outside the ring. Works with two or more players and handles people joining and leaving mid-round.",
+ "link": "/play",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-24",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 9156f3a66..b0968626d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -214,6 +214,14 @@
<category>fix</category>
<description>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.</description>
</item>
+ <item>
+ <title>King of the Totem: a new mini-game in the 3D worlds</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-06-24:King of the Totem: a new mini-game in the 3D worlds</guid>
+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The /play worlds now run King of the Totem. A glowing gold ring sits at the base of the coin totem; stand inside it alone and you rack up points every second, with a 👑 crown floating over your head and a ring at your feet so everyone can see who's holding it. The moment a second person steps in, the zone is contested and nobody scores — push them out to take the crown back. Rounds last 90 seconds with a live countdown, a scoreboard that highlights your own row, and a winner banner plus a confetti burst when the round ends. Then a short intermission and the next round begins. Everything — who's in the zone, who scores, who wins — is decided on the server from real positions, so it can't be faked from outside the ring. Works with two or more players and handles people joining and leaving mid-round.</description>
+ </item>
<item>
<title>Pay for any three.ws service in $THREE — not just USDC</title>
<link>https://three.ws/bazaar</link>
diff --git a/public/features.json b/public/features.json
index 678da1d76..1539e0524 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T10:16:06.842Z",
+ "generated_at": "2026-06-24T10:20:21.841Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agora/api.js b/src/agora/api.js
new file mode 100644
index 000000000..eeab5f199
--- /dev/null
+++ b/src/agora/api.js
@@ -0,0 +1,95 @@
+// Agora — thin client for the real read APIs the trust surface consumes. No
+// caching tricks, no fabrication: every call hits a live endpoint and surfaces
+// failures so the panels can render honest error states.
+//
+// /api/agora/passport — living passport (projection + on-chain + activity)
+// /api/agenc/get-task — on-chain task state + lifecycle timeline
+// /api/agenc/get-agent — on-chain agent registration (reconcile)
+// /api/agenc/link — canonical AgenC id for an identity (handshake)
+
+const DEFAULT_TIMEOUT = 20000;
+
+// GET JSON with an abort timeout. Throws Error(message) on network failure or a
+// non-2xx response so callers can show the message verbatim.
+export async function getJson(url, { signal, timeout = DEFAULT_TIMEOUT } = {}) {
+ const ctrl = new AbortController();
+ const onAbort = () => ctrl.abort();
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
+ const timer = setTimeout(() => ctrl.abort(), timeout);
+ let res;
+ try {
+ res = await fetch(url, { headers: { accept: 'application/json' }, signal: ctrl.signal });
+ } catch (err) {
+ throw new Error(ctrl.signal.aborted ? 'Request timed out' : `Network error: ${err?.message || 'failed'}`);
+ } finally {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener('abort', onAbort);
+ }
+ let body;
+ try { body = await res.json(); } catch { body = null; }
+ if (!res.ok) {
+ const msg = body?.message || body?.error || `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ return body;
+}
+
+export async function postJson(url, payload, { signal, timeout = DEFAULT_TIMEOUT } = {}) {
+ const ctrl = new AbortController();
+ const onAbort = () => ctrl.abort();
+ if (signal) signal.addEventListener('abort', onAbort, { once: true });
+ const timer = setTimeout(() => ctrl.abort(), timeout);
+ let res;
+ try {
+ res = await fetch(url, {
+ method: 'POST',
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
+ body: JSON.stringify(payload || {}),
+ signal: ctrl.signal,
+ });
+ } catch (err) {
+ throw new Error(ctrl.signal.aborted ? 'Request timed out' : `Network error: ${err?.message || 'failed'}`);
+ } finally {
+ clearTimeout(timer);
+ if (signal) signal.removeEventListener('abort', onAbort);
+ }
+ let body;
+ try { body = await res.json(); } catch { body = null; }
+ if (!res.ok) {
+ const msg = body?.message || body?.error || `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ return body;
+}
+
+const q = (params) => new URLSearchParams(
+ Object.entries(params).filter(([, v]) => v != null && v !== ''),
+).toString();
+
+export function fetchPassport({ id, agentPda, agentId }, opts) {
+ return getJson(`/api/agora/passport?${q({ id, agentPda, agentId })}`, opts);
+}
+
+export function fetchCitizens(params = {}, opts) {
+ return getJson(`/api/agora/citizens?${q(params)}`, opts);
+}
+
+export function fetchBoard(params = {}, opts) {
+ return getJson(`/api/agora/board?${q(params)}`, opts);
+}
+
+export function fetchPulse(opts) {
+ return getJson('/api/agora/pulse', opts);
+}
+
+export function fetchTask({ taskPda, creator, taskId, cluster = 'devnet', lifecycle = true }, opts) {
+ return getJson(`/api/agenc/get-task?${q({ taskPda, creator, taskId, cluster, lifecycle: lifecycle ? 1 : undefined })}`, opts);
+}
+
+export function fetchAgent({ agentPda, agentId, cluster = 'devnet' }, opts) {
+ return getJson(`/api/agenc/get-agent?${q({ agentPda, agentId, cluster })}`, opts);
+}
+
+export function linkIdentity({ erc8004AgentId, mplCoreAsset, handle, cluster = 'devnet', baseUrl }, opts) {
+ return postJson('/api/agenc/link', { erc8004AgentId, mplCoreAsset, handle, cluster, baseUrl }, opts);
+}
diff --git a/src/agora/economy-fx.js b/src/agora/economy-fx.js
new file mode 100644
index 000000000..463111d79
--- /dev/null
+++ b/src/agora/economy-fx.js
@@ -0,0 +1,278 @@
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { dracoLoader, meshoptReady } from '../game/avatar-rig.js';
+
+// Economy FX — the completion moment, the part people screenshot.
+//
+// When a task completes the world should *show* it: a $THREE coin arc flowing
+// from the board's escrow to the worker, the reward label, a reputation tick,
+// and — for a Sculptor's GLB deliverable — the artifact materialising on a
+// plinth the camera glides in to orbit. Everything here is world-position based
+// and decoupled from the crowd: the economy layer resolves which citizen earned
+// and hands us a world point.
+//
+// Two hard rules from the DoD:
+// • Dispose every geometry / material / texture for retired coins and plinth
+// models — a completion every few seconds would otherwise leak the heap.
+// • Honour prefers-reduced-motion: swap the coin flight + spin for a calm fade
+// and a static deliverable.
+
+const COIN_GOLD = 0xf0b429;
+const COIN_COUNT = 9;
+const COIN_FLIGHT = 1.15; // seconds board → worker
+const PLINTH_SPOT = new THREE.Vector3();
+
+// One GLTF loader for deliverables, sharing the app's Draco + meshopt decoders.
+const _gltf = new GLTFLoader();
+_gltf.setDRACOLoader(dracoLoader);
+const _meshoptWired = meshoptReady.then((d) => { if (d) _gltf.setMeshoptDecoder(d); return d; });
+
+const _coinGeo = new THREE.CylinderGeometry(0.16, 0.16, 0.04, 18);
+
+function isGlb(url) {
+ if (!url) return false;
+ const u = String(url).split('?')[0].toLowerCase();
+ return u.endsWith('.glb') || u.endsWith('.gltf');
+}
+
+// Pull a "rep 14 → 19" delta out of a real narrative string. Returns null when
+// the narrative carries no reputation move (we never invent numbers).
+function parseRepDelta(narrative) {
+ if (!narrative) return null;
+ const m = String(narrative).match(/rep(?:utation)?\s*(\d+)\s*(?:→|->|to)\s*(\d+)/i);
+ if (!m) return null;
+ const before = parseInt(m[1], 10);
+ const after = parseInt(m[2], 10);
+ if (!Number.isFinite(before) || !Number.isFinite(after)) return null;
+ return { before, after, delta: after - before };
+}
+
+export class EconomyFx {
+ constructor(ctx) {
+ this.ctx = ctx; // { scene, root, worldToScreen, reducedMotion, focusOn, boardPosition }
+ this.scene = ctx.scene;
+ this.reducedMotion = !!ctx.reducedMotion;
+ this.boardTop = (ctx.boardPosition ? ctx.boardPosition.clone() : new THREE.Vector3(0, 0, -6));
+ this.boardTop.y += 3.2;
+
+ this._coins = []; // active coin sprites
+ this._labels = []; // active floating HTML labels
+ this._t = 0;
+
+ this._buildPlinth();
+ }
+
+ // ── Plinth ────────────────────────────────────────────────────────────────
+ _buildPlinth() {
+ // A pedestal that always stands in the Commons; the deliverable model is
+ // what swaps in and out. Placed to the side of the board so the camera can
+ // orbit it without the board behind.
+ const spot = this.plinthSpot = (this.boardTop.clone());
+ spot.y = 0; spot.x += 4.2; spot.z += 1.5;
+
+ const grp = new THREE.Group();
+ grp.position.copy(spot);
+
+ const colGeo = new THREE.CylinderGeometry(0.7, 0.85, 1.1, 28);
+ const colMat = new THREE.MeshStandardMaterial({ color: 0x1a1f2a, roughness: 0.55, metalness: 0.35 });
+ const col = new THREE.Mesh(colGeo, colMat);
+ col.position.y = 0.55; col.castShadow = true; col.receiveShadow = true;
+ grp.add(col);
+
+ const topGeo = new THREE.CylinderGeometry(0.82, 0.82, 0.12, 28);
+ const topMat = new THREE.MeshStandardMaterial({ color: 0x2a3344, roughness: 0.4, metalness: 0.5 });
+ const top = new THREE.Mesh(topGeo, topMat);
+ top.position.y = 1.16; top.castShadow = true;
+ grp.add(top);
+
+ // A focused spotlight on the deliverable.
+ const spotLight = new THREE.SpotLight(0xffffff, 0, 9, Math.PI / 7, 0.4, 1.2);
+ spotLight.position.set(0, 6, 2.5);
+ spotLight.target.position.set(0, 1.6, 0);
+ grp.add(spotLight, spotLight.target);
+
+ this._plinthGroup = grp;
+ this._plinthSpot = spot;
+ this._plinthDisposables = [colGeo, colMat, topGeo, topMat];
+ this._spotLight = spotLight;
+ this._plinthModel = null;
+ this._plinthModelHolder = new THREE.Group();
+ this._plinthModelHolder.position.y = 1.22;
+ grp.add(this._plinthModelHolder);
+
+ this.scene.add(grp);
+ }
+
+ // Load and mount a GLB deliverable, disposing whatever stood there before.
+ async showDeliverable(url) {
+ this._retireDeliverableModel();
+ if (!isGlb(url)) return false;
+ try {
+ await _meshoptWired;
+ const gltf = await _gltf.loadAsync(url);
+ const model = gltf.scene;
+
+ // Normalise to ~1.6m tall, centred on the plinth top.
+ const box = new THREE.Box3().setFromObject(model);
+ const size = new THREE.Vector3(); box.getSize(size);
+ const maxDim = Math.max(size.x, size.y, size.z) || 1;
+ const scale = 1.6 / maxDim;
+ model.scale.setScalar(scale);
+ const center = new THREE.Vector3(); box.getCenter(center);
+ model.position.set(-center.x * scale, -box.min.y * scale, -center.z * scale);
+ model.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });
+
+ this._plinthModelHolder.add(model);
+ this._plinthModel = model;
+ this._spotLight.intensity = 6;
+
+ // Glide the camera in to orbit it.
+ const focus = this._plinthSpot.clone(); focus.y = 1.4;
+ this.ctx.focusOn?.(focus);
+ return true;
+ } catch (err) {
+ console.warn('[agora] deliverable load failed:', err?.message);
+ return false;
+ }
+ }
+
+ _retireDeliverableModel() {
+ if (!this._plinthModel) return;
+ this._plinthModelHolder.remove(this._plinthModel);
+ disposeObject(this._plinthModel);
+ this._plinthModel = null;
+ this._spotLight.intensity = 0;
+ }
+
+ // ── The completion moment ──────────────────────────────────────────────────
+ // workerPos: feet position of the earner (or null → coins settle at the
+ // plinth). rewardLabel/narrative are real strings from the pulse.
+ onCompletion({ workerPos, rewardLabel, narrative, deliverableUrl }) {
+ const target = workerPos
+ ? new THREE.Vector3(workerPos.x, 1.7, workerPos.z)
+ : this._plinthSpot.clone().setY(1.4);
+
+ this._coinFlow(target);
+ if (rewardLabel) this._floatLabel(target.clone().setY(target.y + 0.5), `+${rewardLabel}`, 'reward');
+
+ const rep = parseRepDelta(narrative);
+ if (rep) {
+ const tickPos = target.clone(); tickPos.y += 0.95;
+ this._floatLabel(tickPos, `rep ${rep.before} → ${rep.after} ▲`, 'rep');
+ }
+
+ if (isGlb(deliverableUrl)) this.showDeliverable(deliverableUrl);
+ }
+
+ _coinFlow(target) {
+ if (this.reducedMotion) {
+ // No flight — a single calm "paid" pulse at the target.
+ this._floatLabel(target.clone().setY(target.y + 0.2), '$THREE paid', 'reward');
+ return;
+ }
+ const from = this.boardTop.clone();
+ const mid = from.clone().lerp(target, 0.5);
+ mid.y += Math.max(2.2, from.distanceTo(target) * 0.35);
+
+ for (let i = 0; i < COIN_COUNT; i++) {
+ const mat = new THREE.MeshStandardMaterial({
+ color: COIN_GOLD, emissive: COIN_GOLD, emissiveIntensity: 0.5,
+ roughness: 0.3, metalness: 0.9,
+ });
+ const coin = new THREE.Mesh(_coinGeo, mat);
+ coin.castShadow = false;
+ coin.rotation.x = Math.PI / 2;
+ this.scene.add(coin);
+ this._coins.push({
+ mesh: coin, mat,
+ from: from.clone(), mid: mid.clone(), to: target.clone(),
+ t: -i * 0.06, // stagger the stream
+ spin: 6 + Math.random() * 6,
+ });
+ }
+ }
+
+ _floatLabel(worldPos, text, kind) {
+ const el = document.createElement('div');
+ el.className = `agora-econ-float agora-econ-float-${kind}${this.reducedMotion ? ' reduced' : ''}`;
+ el.textContent = text;
+ this.ctx.root.appendChild(el);
+ this._labels.push({ el, worldPos: worldPos.clone(), born: this._t, ttl: 2.0 });
+ }
+
+ // ── Per-frame ───────────────────────────────────────────────────────────────
+ update(dt) {
+ this._t += dt;
+
+ // Coins along their bezier.
+ for (let i = this._coins.length - 1; i >= 0; i--) {
+ const c = this._coins[i];
+ c.t += dt / COIN_FLIGHT;
+ if (c.t < 0) continue;
+ if (c.t >= 1) {
+ this.scene.remove(c.mesh);
+ c.mat.dispose();
+ this._coins.splice(i, 1);
+ continue;
+ }
+ const u = c.t, iv = 1 - u;
+ // Quadratic bezier from → mid → to.
+ c.mesh.position.set(
+ iv * iv * c.from.x + 2 * iv * u * c.mid.x + u * u * c.to.x,
+ iv * iv * c.from.y + 2 * iv * u * c.mid.y + u * u * c.to.y,
+ iv * iv * c.from.z + 2 * iv * u * c.mid.z + u * u * c.to.z,
+ );
+ c.mesh.rotation.z += c.spin * dt;
+ c.mat.emissiveIntensity = 0.4 + 0.4 * Math.sin(this._t * 8 + i);
+ }
+
+ // Floating labels: project to screen, rise + fade.
+ for (let i = this._labels.length - 1; i >= 0; i--) {
+ const l = this._labels[i];
+ const age = this._t - l.born;
+ if (age >= l.ttl) {
+ l.el.remove();
+ this._labels.splice(i, 1);
+ continue;
+ }
+ const s = this.ctx.worldToScreen(l.worldPos);
+ if (!s.visible) { l.el.style.opacity = '0'; continue; }
+ const p = age / l.ttl;
+ const rise = this.reducedMotion ? 0 : p * 36;
+ l.el.style.transform = `translate(-50%, -50%) translate(${s.x}px, ${s.y - rise}px)`;
+ l.el.style.opacity = String(p < 0.15 ? p / 0.15 : 1 - (p - 0.15) / 0.85);
+ }
+
+ // Idle plinth model rotation (unless reduced motion).
+ if (this._plinthModel && !this.reducedMotion) {
+ this._plinthModelHolder.rotation.y += dt * 0.5;
+ }
+ }
+
+ dispose() {
+ for (const c of this._coins) { this.scene.remove(c.mesh); c.mat.dispose(); }
+ this._coins = [];
+ for (const l of this._labels) l.el.remove();
+ this._labels = [];
+ this._retireDeliverableModel();
+ for (const d of this._plinthDisposables) d.dispose?.();
+ this.scene.remove(this._plinthGroup);
+ // _coinGeo is module-shared across the page lifetime — not disposed here.
+ }
+}
+
+// Recursively dispose a loaded model's geometries, materials and textures.
+function disposeObject(obj) {
+ obj.traverse((n) => {
+ if (!n.isMesh) return;
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) {
+ if (!m) continue;
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap']) {
+ m[k]?.dispose?.();
+ }
+ m.dispose?.();
+ }
+ });
+}
diff --git a/src/agora/economy-layer.js b/src/agora/economy-layer.js
new file mode 100644
index 000000000..61ae6a71c
--- /dev/null
+++ b/src/agora/economy-layer.js
@@ -0,0 +1,198 @@
+import * as THREE from 'three';
+import { JobBoard } from './job-board.js';
+import { EconomyFx } from './economy-fx.js';
+import { Ticker } from './ticker.js';
+import { PulseFeed } from './pulse-feed.js';
+import { ECON_LAYER_CSS } from './economy-layer.css.js';
+
+// The economy layer — Task 06's single mount point. The Commons scaffold
+// (Task 05, src/agora/agora-world.js) builds the scene, camera and the living
+// crowd; this lights the economy on top of it:
+// • a job board with glowing, profession-coloured, reward-sized markers,
+// • a live ticker (economy readout + click-to-focus narration),
+// • the completion moment (coin arc + reputation tick + an orbit-able plinth),
+// • all driven from a single deduped, backing-off pulse poll that pauses with
+// the tab.
+//
+// It is deliberately decoupled from the scaffold's internals. The host passes a
+// small context — scene, camera, renderer, a focus callback and an optional
+// `crowd` adapter for driving individual citizens (walk / busy / celebrate).
+// Every crowd call is optional-chained, so the board, ticker, coin flow and
+// plinth all work even before the crowd exposes those hooks; the citizen-coupled
+// flourishes simply light up as the adapter is filled in.
+//
+// Returns a handle: { update(dt), dispose() }. The host calls update(dt) in its
+// render loop and dispose() on teardown.
+
+export function mountEconomyLayer(ctx) {
+ const { scene, camera, renderer } = ctx;
+ const reducedMotion = !!ctx.reducedMotion;
+ const canvas = renderer.domElement;
+ const boardPosition = ctx.boardPosition ? ctx.boardPosition.clone() : new THREE.Vector3(0, 0, -7);
+
+ injectStyles();
+
+ // Overlay root for all HTML chrome (tooltips, ticker, floating labels).
+ const root = document.createElement('div');
+ root.className = 'agora-econ-root';
+ document.body.appendChild(root);
+
+ // ── world → screen projection (canvas-rect aware, cached per resize) ───────
+ let rect = canvas.getBoundingClientRect();
+ const refreshRect = () => { rect = canvas.getBoundingClientRect(); };
+ window.addEventListener('resize', refreshRect);
+ window.addEventListener('scroll', refreshRect, true);
+ const _proj = new THREE.Vector3();
+ function worldToScreen(v) {
+ _proj.copy(v).project(camera);
+ const visible = _proj.z < 1 && _proj.x >= -1.15 && _proj.x <= 1.15 && _proj.y >= -1.15 && _proj.y <= 1.15;
+ return {
+ x: rect.left + (_proj.x * 0.5 + 0.5) * rect.width,
+ y: rect.top + (-_proj.y * 0.5 + 0.5) * rect.height,
+ visible,
+ };
+ }
+
+ const focusOn = (v) => ctx.focusOn?.(v);
+ const crowd = ctx.crowd || {};
+
+ // ── modules ────────────────────────────────────────────────────────────────
+ const jobBoard = new JobBoard({
+ scene, root, worldToScreen, reducedMotion, boardPosition,
+ onSelectTask: (task) => {
+ // Selecting a task glides the camera to the board so the marker is framed.
+ focusOn(boardPosition.clone().setY(3.5));
+ },
+ });
+
+ const economyFx = new EconomyFx({
+ scene, root, worldToScreen, reducedMotion, focusOn, boardPosition,
+ });
+
+ const ticker = new Ticker({
+ root, reducedMotion,
+ onFocusActivity: (activity) => focusActivity(activity),
+ });
+
+ // Resolve the citizen behind an activity by display name (pulse.recent carries
+ // the actor's name, not its id) and glide to it; open the passport if the host
+ // wired that. Completion activities with a deliverable focus the plinth.
+ function focusActivity(activity) {
+ if (!activity) return;
+ const name = activity.actor;
+ const hit = name && crowd.findByName ? crowd.findByName(name) : null;
+ if (activity.citizenId && crowd.getPosition) {
+ const p = crowd.getPosition(activity.citizenId);
+ if (p) { focusOn(p.clone().setY(1.6)); ctx.openPassport?.(activity.citizenId); return; }
+ }
+ if (hit?.position) {
+ focusOn(hit.position.clone().setY(1.6));
+ ctx.openPassport?.(hit.id);
+ } else if (activity.kind === 'completed_task' && activity.deliverableUrl) {
+ focusOn(economyFx.plinthSpot.clone().setY(1.4));
+ } else {
+ focusOn(boardPosition.clone().setY(3.5));
+ }
+ }
+
+ // ── live activity routing ────────────────────────────────────────────────
+ function handleActivity(a) {
+ if (!a || !a.kind) return;
+ const hit = a.actor && crowd.findByName ? crowd.findByName(a.actor) : null;
+
+ if (a.kind === 'claimed_task' && hit) {
+ // Walk the claimant to the board, then to a work spot beside it; mark Busy.
+ crowd.setStatus?.(hit.id, 'Busy');
+ const boardSpot = boardPosition.clone();
+ boardSpot.z += 2.2; // stand in front of the board
+ const workSpot = boardPosition.clone();
+ workSpot.x += (Math.random() - 0.5) * 6;
+ workSpot.z += 4 + Math.random() * 3;
+ crowd.walkTo?.(hit.id, boardSpot, () => crowd.walkTo?.(hit.id, workSpot));
+ } else if (a.kind === 'completed_task') {
+ const workerPos = hit?.position || (a.citizenId && crowd.getPosition ? crowd.getPosition(a.citizenId) : null);
+ economyFx.onCompletion({
+ workerPos: workerPos || null,
+ rewardLabel: a.rewardLabel,
+ narrative: a.narrative,
+ deliverableUrl: a.deliverableUrl,
+ });
+ if (hit) {
+ crowd.celebrate?.(hit.id);
+ crowd.setStatus?.(hit.id, 'Active');
+ }
+ }
+ }
+
+ // ── connection state pip ───────────────────────────────────────────────────
+ let errorStreak = 0;
+ function handleError() {
+ errorStreak++;
+ if (errorStreak >= 2) root.classList.add('agora-econ-offline');
+ }
+ function clearError() { errorStreak = 0; root.classList.remove('agora-econ-offline'); }
+
+ // ── feed wiring ────────────────────────────────────────────────────────────
+ const feed = new PulseFeed();
+ const offs = [
+ feed.on('board', (b) => { clearError(); jobBoard.setBoard(b); }),
+ feed.on('pulse', (p) => { clearError(); ticker.setPulse(p); }),
+ feed.on('activity', handleActivity),
+ feed.on('error', handleError),
+ ];
+ feed.start();
+
+ // ── 3D marker hover/click (single picker, only on pointer move) ────────────
+ const raycaster = new THREE.Raycaster();
+ const ndc = new THREE.Vector2();
+ function onPointerMove(e) {
+ ndc.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
+ raycaster.setFromCamera(ndc, camera);
+ const hits = raycaster.intersectObjects(jobBoard.pickables, false);
+ jobBoard.hoverByMesh(hits[0]?.object || null);
+ canvas.style.cursor = hits[0] ? 'pointer' : '';
+ }
+ function onClick(e) {
+ ndc.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ ndc.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
+ raycaster.setFromCamera(ndc, camera);
+ const hits = raycaster.intersectObjects(jobBoard.pickables, false);
+ if (hits[0]) {
+ const key = jobBoard.keyForMesh(hits[0].object);
+ const task = jobBoard.taskForKey(key);
+ if (task) { jobBoard.ctx.onSelectTask?.(task, key); }
+ }
+ }
+ canvas.addEventListener('pointermove', onPointerMove);
+ canvas.addEventListener('click', onClick);
+
+ return {
+ update(dt) {
+ jobBoard.update(dt);
+ economyFx.update(dt);
+ },
+ dispose() {
+ for (const off of offs) off?.();
+ feed.stop();
+ canvas.removeEventListener('pointermove', onPointerMove);
+ canvas.removeEventListener('click', onClick);
+ window.removeEventListener('resize', refreshRect);
+ window.removeEventListener('scroll', refreshRect, true);
+ jobBoard.dispose();
+ economyFx.dispose();
+ ticker.dispose();
+ root.remove();
+ },
+ };
+}
+
+let _stylesInjected = false;
+function injectStyles() {
+ if (_stylesInjected || document.getElementById('agora-econ-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'agora-econ-styles';
+ style.textContent = ECON_LAYER_CSS;
+ document.head.appendChild(style);
+ _stylesInjected = true;
+}
diff --git a/src/agora/glb-viewer.js b/src/agora/glb-viewer.js
new file mode 100644
index 000000000..31596fb59
--- /dev/null
+++ b/src/agora/glb-viewer.js
@@ -0,0 +1,138 @@
+// Agora — a tiny, self-contained GLB orbit viewer for a VERIFIED deliverable.
+// It parses the exact bytes the verifier just hashed (no second fetch — what you
+// see is provably what matched the on-chain proofHash) and renders them on a
+// plinth you can orbit. Lazy-loaded by verify.js so the three.js + addons weight
+// only lands when a model actually needs rendering.
+
+import {
+ Scene, PerspectiveCamera, WebGLRenderer, Box3, Vector3, Group,
+ AmbientLight, DirectionalLight, HemisphereLight, Color, SRGBColorSpace,
+ ACESFilmicToneMapping, CylinderGeometry, MeshStandardMaterial, Mesh,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { meshoptReady, dracoLoader } from '../game/avatar-rig.js';
+
+// Reuse the app-wide draco decoder (vendored at /three/draco/gltf/) and meshopt
+// decoder so forge GLBs — which are often compressed — parse here too.
+let _loader = null;
+async function getLoader() {
+ if (_loader) return _loader;
+ const loader = new GLTFLoader();
+ try { loader.setDRACOLoader(dracoLoader || new DRACOLoader().setDecoderPath('/three/draco/gltf/')); } catch { /* draco optional */ }
+ try { const m = await meshoptReady; if (m) loader.setMeshoptDecoder(m); } catch { /* meshopt optional */ }
+ _loader = loader;
+ return loader;
+}
+
+// Parse `bytes` (Uint8Array of a .glb) and mount an orbiting preview into
+// `container`. Returns a teardown handle ({ destroy }). Throws on parse failure
+// so the caller can show an honest "could not render" note.
+export default async function makeViewer(container, bytes) {
+ const loader = await getLoader();
+ const buffer = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
+ ? bytes.buffer
+ : bytes.slice().buffer;
+
+ const gltf = await new Promise((resolve, reject) => {
+ loader.parse(buffer, '', resolve, reject);
+ });
+
+ const width = container.clientWidth || 320;
+ const height = container.clientHeight || 220;
+
+ const scene = new Scene();
+ scene.background = new Color(0x0b0c10);
+
+ const camera = new PerspectiveCamera(45, width / height, 0.01, 1000);
+
+ const renderer = new WebGLRenderer({ antialias: true, alpha: false });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setSize(width, height);
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.0;
+ container.replaceChildren(renderer.domElement);
+
+ scene.add(new AmbientLight(0xc8d4e8, 1.4));
+ const key = new DirectionalLight(0xffffff, 2.0);
+ key.position.set(3, 5, 4);
+ scene.add(key);
+ scene.add(new HemisphereLight(0x9fbad8, 0x2a2f3a, 0.7));
+
+ const root = new Group();
+ const model = gltf.scene || (gltf.scenes && gltf.scenes[0]);
+ if (!model) throw new Error('GLB contained no scene');
+ model.traverse((n) => { if (n.isMesh) { n.castShadow = false; n.receiveShadow = false; } });
+ root.add(model);
+ scene.add(root);
+
+ // Frame the model: center it, scale to a unit-ish size, rest it on a plinth.
+ const box = new Box3().setFromObject(model);
+ const size = box.getSize(new Vector3());
+ const center = box.getCenter(new Vector3());
+ const maxDim = Math.max(size.x, size.y, size.z) || 1;
+ const scale = 1.6 / maxDim;
+ model.scale.setScalar(scale);
+ model.position.sub(center.multiplyScalar(scale));
+ // Drop onto the plinth top (y=0).
+ const scaledBox = new Box3().setFromObject(model);
+ model.position.y -= scaledBox.min.y;
+
+ const plinth = new Mesh(
+ new CylinderGeometry(1.1, 1.25, 0.12, 48),
+ new MeshStandardMaterial({ color: 0x14161c, roughness: 0.85, metalness: 0.1 }),
+ );
+ plinth.position.y = -0.06;
+ scene.add(plinth);
+
+ camera.position.set(1.8, 1.5, 2.4);
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.08;
+ controls.target.set(0, 0.8, 0);
+ controls.minDistance = 1.2;
+ controls.maxDistance = 8;
+ controls.autoRotate = !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ controls.autoRotateSpeed = 1.1;
+ controls.update();
+
+ let raf = 0;
+ let alive = true;
+ const tick = () => {
+ if (!alive) return;
+ raf = requestAnimationFrame(tick);
+ controls.update();
+ renderer.render(scene, camera);
+ };
+ tick();
+
+ const ro = new ResizeObserver(() => {
+ const w = container.clientWidth || width;
+ const hgt = container.clientHeight || height;
+ renderer.setSize(w, hgt);
+ camera.aspect = w / hgt;
+ camera.updateProjectionMatrix();
+ });
+ ro.observe(container);
+
+ const destroy = () => {
+ alive = false;
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ controls.dispose();
+ renderer.dispose();
+ scene.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const mat = n.material;
+ if (Array.isArray(mat)) mat.forEach((m) => m.dispose?.());
+ else mat?.dispose?.();
+ }
+ });
+ if (renderer.domElement.parentNode === container) container.removeChild(renderer.domElement);
+ };
+ container._agoraViewerDestroy = destroy;
+ return { destroy };
+}
diff --git a/src/agora/handshake.js b/src/agora/handshake.js
new file mode 100644
index 000000000..76f13f9f9
--- /dev/null
+++ b/src/agora/handshake.js
@@ -0,0 +1,217 @@
+// Agora — the cross-chain identity handshake. When a citizen proves BOTH an EVM
+// ERC-8004 identity AND a Solana Metaplex Core (MPL-Core) identity, the AgenC
+// bridge binds them into ONE canonical agentId — one agent, two chains, one
+// reputation. This panel renders that resolution and, crucially, RE-DERIVES the
+// canonical id in the browser from the bridge's documented math, then confirms it
+// equals what /api/agenc/link returns. The match is computed, not asserted — so
+// the handshake proves itself.
+//
+// Bridge math mirrors solana-agent-sdk/src/actions/agenc/identity-bridge.ts:
+// composite: sha256("AgenC/three.ws/composite/v1\0" + canonicalJSON)
+// where canonicalJSON = {"v":1,"erc8004":"0x<32-byte BE hex>","mplCore":"<base58>"}
+
+import { PublicKey } from '@solana/web3.js';
+import { h, copyChip } from './panel.js';
+import { sha256Hex } from './verify.js';
+import { linkIdentity } from './api.js';
+import { normalizeHex, shortId, explorerAddressUrl, etherscanAddressUrl } from './format.js';
+
+const NS_COMPOSITE = 'AgenC/three.ws/composite/v1\0';
+const NS_ERC8004 = 'AgenC/three.ws/erc8004/v1\0';
+const NS_MPL_CORE = 'AgenC/three.ws/mpl-core/v1\0';
+const NS_HANDLE = 'AgenC/three.ws/handle/v1\0';
+
+const enc = new TextEncoder();
+
+function concatBytes(...parts) {
+ let len = 0;
+ for (const p of parts) len += p.byteLength;
+ const out = new Uint8Array(len);
+ let off = 0;
+ for (const p of parts) { out.set(p, off); off += p.byteLength; }
+ return out;
+}
+
+// 32-byte big-endian encoding of an ERC-8004 uint256 agentId.
+function erc8004IdToBeBytes(id) {
+ let n = typeof id === 'bigint' ? id : BigInt(String(id).trim());
+ if (n < 0n) throw new Error('ERC-8004 agentId must be non-negative');
+ const out = new Uint8Array(32);
+ for (let i = 31; i >= 0 && n > 0n; i--) { out[i] = Number(n & 0xffn); n >>= 8n; }
+ return out;
+}
+
+// Parse the identity proofs out of an on-chain metadataUri produced by
+// buildThreewsMetadataUri (…/.well-known/agent.json?erc8004=&mpl=&handle=).
+// Pure + null-safe — returns {} when the URI carries no recognizable proofs.
+export function parseIdentityProofs(metadataUri) {
+ const out = { erc8004AgentId: null, mplCoreAsset: null, handle: null };
+ if (!metadataUri || typeof metadataUri !== 'string') return out;
+ let qs = '';
+ const qi = metadataUri.indexOf('?');
+ if (qi >= 0) qs = metadataUri.slice(qi + 1);
+ else if (/^[\w-]+=/.test(metadataUri)) qs = metadataUri; // bare query
+ const params = new URLSearchParams(qs);
+ const erc = params.get('erc8004') || params.get('erc');
+ const mpl = params.get('mpl') || params.get('mplCore') || params.get('asset');
+ const handle = params.get('handle');
+ if (erc) out.erc8004AgentId = erc;
+ if (mpl) out.mplCoreAsset = mpl;
+ if (handle) out.handle = handle.toLowerCase();
+ return out;
+}
+
+export function hasDualIdentity(proofs) {
+ return !!(proofs && proofs.erc8004AgentId != null && proofs.erc8004AgentId !== ''
+ && proofs.mplCoreAsset != null && proofs.mplCoreAsset !== '');
+}
+
+// Re-derive the canonical AgenC agentId (64-char lowercase hex) from proofs,
+// exactly as the on-chain bridge does. Selection priority matches
+// getCanonicalThreewsAgenCId: composite > erc8004 > mpl-core > handle.
+export async function deriveCanonicalAgenCId(proofs) {
+ const hasErc = proofs.erc8004AgentId != null && proofs.erc8004AgentId !== '';
+ const hasMpl = proofs.mplCoreAsset != null && proofs.mplCoreAsset !== '';
+
+ if (hasErc && hasMpl) {
+ const ercBytes = erc8004IdToBeBytes(proofs.erc8004AgentId);
+ const ercHex = [...ercBytes].map((b) => b.toString(16).padStart(2, '0')).join('');
+ const mplBase58 = new PublicKey(proofs.mplCoreAsset).toBase58();
+ const composite = JSON.stringify({ v: 1, erc8004: '0x' + ercHex, mplCore: mplBase58 });
+ return { source: 'composite', hex: await sha256Hex(concatBytes(enc.encode(NS_COMPOSITE), enc.encode(composite))) };
+ }
+ if (hasErc) {
+ return { source: 'erc8004', hex: await sha256Hex(concatBytes(enc.encode(NS_ERC8004), erc8004IdToBeBytes(proofs.erc8004AgentId))) };
+ }
+ if (hasMpl) {
+ const pkBytes = new PublicKey(proofs.mplCoreAsset).toBytes();
+ return { source: 'mpl-core', hex: await sha256Hex(concatBytes(enc.encode(NS_MPL_CORE), pkBytes)) };
+ }
+ if (proofs.handle) {
+ return { source: 'handle', hex: await sha256Hex(concatBytes(enc.encode(NS_HANDLE), enc.encode(String(proofs.handle).trim().toLowerCase()))) };
+ }
+ throw new Error('no identity proofs supplied');
+}
+
+// Render the handshake into `container`. Shows the EVM ↔ Solana resolution, the
+// canonical AgenC id, and a computed bridge-verification check.
+//
+// renderHandshake(container, { proofs, cluster, expectedAgentPda })
+export async function renderHandshake(container, { proofs, cluster = 'devnet', expectedAgentPda } = {}) {
+ container.classList.add('agora-handshake');
+ if (!hasDualIdentity(proofs)) {
+ container.replaceChildren(); // host decides whether to show anything
+ return false;
+ }
+
+ container.replaceChildren(h('div', { class: 'agora-handshake-loading' }, [
+ h('span', { class: 'agora-skel agora-skel-line' }),
+ h('span', { class: 'agora-handshake-loading-label' }, ['Resolving the cross-chain identity…']),
+ ]));
+
+ // Derive locally + ask the bridge endpoint in parallel; the panel only claims
+ // "verified" when the two agree.
+ let local, remote;
+ try {
+ [local, remote] = await Promise.all([
+ deriveCanonicalAgenCId(proofs),
+ linkIdentity({ erc8004AgentId: proofs.erc8004AgentId, mplCoreAsset: proofs.mplCoreAsset, cluster }),
+ ]);
+ } catch (err) {
+ container.replaceChildren(h('p', { class: 'agora-muted' }, [`Couldn't resolve the cross-chain identity: ${err.message}`]));
+ return true;
+ }
+
+ const remoteHex = normalizeHex(remote.agenCAgentId);
+ const localHex = normalizeHex(local.hex);
+ const bridgeVerified = remoteHex.length === 64 && remoteHex === localHex;
+ const pdaMatches = !expectedAgentPda || !remote.agentPda || expectedAgentPda === remote.agentPda;
+
+ container.replaceChildren(buildHandshake({ proofs, cluster, remote, remoteHex, bridgeVerified, pdaMatches, expectedAgentPda }));
+ return true;
+}
+
+function buildHandshake({ proofs, cluster, remote, remoteHex, bridgeVerified, pdaMatches }) {
+ const evmAddr = looksLikeEvmAddress(proofs.erc8004AgentId) ? proofs.erc8004AgentId : null;
+
+ const evmCard = chainCard({
+ chain: 'EVM', standard: 'ERC-8004', glyph: '⬡',
+ idLabel: 'agent id', idValue: String(proofs.erc8004AgentId),
+ link: evmAddr ? etherscanAddressUrl(evmAddr) : null,
+ linkText: evmAddr ? 'Etherscan ↗' : null,
+ });
+ const solCard = chainCard({
+ chain: 'Solana', standard: 'MPL-Core', glyph: '◎',
+ idLabel: 'asset', idValue: shortId(proofs.mplCoreAsset, 4, 4),
+ copyValue: proofs.mplCoreAsset,
+ link: explorerAddressUrl(proofs.mplCoreAsset, cluster),
+ linkText: 'Explorer ↗',
+ });
+
+ const canonical = h('div', { class: 'agora-handshake-canonical' }, [
+ h('div', { class: 'agora-handshake-canon-head' }, [
+ h('span', { class: 'agora-handshake-canon-title' }, ['Canonical AgenC id']),
+ bridgeVerified
+ ? h('span', { class: 'agora-handshake-verified', title: 'Re-derived in your browser from the bridge math and matched the registry' }, ['✓ bridge-verified'])
+ : h('span', { class: 'agora-handshake-unverified', title: 'Local derivation did not match the bridge endpoint' }, ['⚠ unverified']),
+ ]),
+ h('div', { class: 'agora-hash-row' }, [
+ h('code', { class: `agora-hash ${bridgeVerified ? 'is-ok' : 'is-bad'}` }, [shortId(remoteHex, 12, 12)]),
+ copyChip(remoteHex, 'canonical AgenC id'),
+ ]),
+ remote.agentPda ? h('div', { class: 'agora-hash-row' }, [
+ h('span', { class: 'agora-hash-label' }, ['agent PDA']),
+ h('a', { class: 'agora-addr', href: explorerAddressUrl(remote.agentPda, cluster), target: '_blank', rel: 'noopener noreferrer' }, [shortId(remote.agentPda, 4, 4), ' ↗']),
+ copyChip(remote.agentPda, 'agent PDA'),
+ ]) : null,
+ h('div', { class: 'agora-handshake-flags' }, [
+ flag(remote.registered, remote.registered ? 'Registered on-chain' : 'Not yet registered'),
+ !pdaMatches ? flag(false, 'PDA differs from citizen record') : null,
+ ].filter(Boolean)),
+ ].filter(Boolean));
+
+ return h('div', { class: 'agora-handshake-inner' }, [
+ h('p', { class: 'agora-handshake-explainer' }, [
+ h('strong', {}, ['One agent, two chains, one reputation.']),
+ ' This citizen proves an identity on both Ethereum (ERC-8004) and Solana (MPL-Core). The bridge hashes both proofs into a single canonical AgenC id, so neither side can be swapped without re-registering.',
+ ]),
+ h('div', { class: 'agora-handshake-bridge' }, [
+ evmCard,
+ h('div', { class: 'agora-handshake-merge', 'aria-hidden': 'true' }, [
+ h('span', { class: 'agora-handshake-merge-line' }),
+ h('span', { class: 'agora-handshake-merge-node' }, ['⛓']),
+ h('span', { class: 'agora-handshake-merge-line' }),
+ ]),
+ solCard,
+ ]),
+ canonical,
+ ]);
+}
+
+function chainCard({ chain, standard, glyph, idLabel, idValue, copyValue, link, linkText }) {
+ return h('div', { class: 'agora-chaincard' }, [
+ h('div', { class: 'agora-chaincard-head' }, [
+ h('span', { class: 'agora-chaincard-glyph', 'aria-hidden': 'true' }, [glyph]),
+ h('div', {}, [
+ h('div', { class: 'agora-chaincard-chain' }, [chain]),
+ h('div', { class: 'agora-chaincard-standard' }, [standard]),
+ ]),
+ ]),
+ h('div', { class: 'agora-chaincard-id' }, [
+ h('span', { class: 'agora-kv-key' }, [idLabel]),
+ h('code', { class: 'agora-chaincard-val' }, [idValue]),
+ copyValue ? copyChip(copyValue, idLabel) : null,
+ ].filter(Boolean)),
+ link ? h('a', { class: 'agora-chaincard-link', href: link, target: '_blank', rel: 'noopener noreferrer' }, [linkText]) : null,
+ ].filter(Boolean));
+}
+
+function flag(ok, label) {
+ return h('span', { class: `agora-flag ${ok ? 'is-on' : 'is-off'}` }, [
+ h('span', { class: 'agora-flag-dot', 'aria-hidden': 'true' }), label,
+ ]);
+}
+
+function looksLikeEvmAddress(v) {
+ return typeof v === 'string' && /^0x[0-9a-fA-F]{40}$/.test(v.trim());
+}
diff --git a/src/agora/job-board.js b/src/agora/job-board.js
new file mode 100644
index 000000000..21b4efaed
--- /dev/null
+++ b/src/agora/job-board.js
@@ -0,0 +1,396 @@
+import * as THREE from 'three';
+import { professionThreeColor, professionColor, professionLabelFor, rewardMagnitude, rewardMarkerScale, rewardChip } from './professions.js';
+
+// The job board — the structure in the square that makes open work legible at a
+// glance. A physical kiosk stands in the Commons; every open task from
+// /api/agora/board floats above it as a glowing marker, COLOURED by profession
+// and SIZED by reward. Hover or keyboard-focus a marker → a tooltip with the
+// title, reward and required profession. An empty board shows a designed
+// "no open work right now" sign, never an empty void.
+//
+// The board owns: its 3D mesh, the marker pool (diffed on each board poll, with
+// strict disposal of removed markers — the #1 leak source), an HTML tooltip and
+// an accessible roster (one focusable button per open task, so the board is
+// reachable by keyboard and screen readers, not just the mouse).
+
+const MARKER_BASE_Y = 4.6; // height of the lowest marker above the board base
+const MARKER_GAP = 1.5; // horizontal spacing between markers
+const MARKERS_PER_ROW = 6;
+const ROW_GAP = 1.4;
+
+// A soft radial glow sprite texture, built once and shared by every marker.
+let _glowTex = null;
+function glowTexture() {
+ if (_glowTex) return _glowTex;
+ const s = 128;
+ const c = document.createElement('canvas');
+ c.width = c.height = s;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);
+ g.addColorStop(0, 'rgba(255,255,255,1)');
+ g.addColorStop(0.35, 'rgba(255,255,255,0.55)');
+ g.addColorStop(1, 'rgba(255,255,255,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, s, s);
+ _glowTex = new THREE.CanvasTexture(c);
+ _glowTex.colorSpace = THREE.SRGBColorSpace;
+ return _glowTex;
+}
+
+// "OPEN WORK" header texture.
+function headerTexture() {
+ const w = 512, h = 128;
+ const c = document.createElement('canvas');
+ c.width = w; c.height = h;
+ const ctx = c.getContext('2d');
+ ctx.fillStyle = '#0b0d12';
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = '#e8eef7';
+ ctx.font = '700 56px ui-sans-serif, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.letterSpacing = '8px';
+ ctx.fillText('OPEN WORK', w / 2, h / 2 + 4);
+ const tex = new THREE.CanvasTexture(c);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ return tex;
+}
+
+function taskKey(task) {
+ return task.taskPda || task.taskId || task.resource || task.title;
+}
+
+export class JobBoard {
+ constructor(ctx) {
+ this.ctx = ctx; // { scene, root, worldToScreen, reducedMotion, onSelectTask }
+ this.scene = ctx.scene;
+ this.reducedMotion = !!ctx.reducedMotion;
+ this.position = ctx.boardPosition ? ctx.boardPosition.clone() : new THREE.Vector3(0, 0, -6);
+
+ this.group = new THREE.Group();
+ this.group.position.copy(this.position);
+ this._markers = new Map(); // key → { task, group, anchor: Vector3, mat, glowMat, baseScale, phase }
+ this._meshIndex = new Map(); // mesh.uuid → key (for raycast routing)
+ this._tasks = [];
+ this._t = 0;
+ this._hoverKey = null;
+
+ this._buildStructure();
+ this.scene.add(this.group);
+
+ // HTML chrome (tooltip + accessible roster + empty sign) lives in the
+ // overlay root the economy layer owns.
+ this._buildChrome();
+ }
+
+ // ── 3D structure ──────────────────────────────────────────────────────────
+ _buildStructure() {
+ const disposables = this._disposables = [];
+
+ // Base plinth.
+ const baseGeo = new THREE.BoxGeometry(5.2, 0.5, 1.4);
+ const baseMat = new THREE.MeshStandardMaterial({ color: 0x12151c, roughness: 0.7, metalness: 0.3 });
+ const base = new THREE.Mesh(baseGeo, baseMat);
+ base.position.y = 0.25; base.castShadow = true; base.receiveShadow = true;
+ this.group.add(base);
+ disposables.push(baseGeo, baseMat);
+
+ // Two posts.
+ const postGeo = new THREE.CylinderGeometry(0.12, 0.12, 3.6, 12);
+ const postMat = new THREE.MeshStandardMaterial({ color: 0x2a3140, roughness: 0.5, metalness: 0.6 });
+ for (const x of [-2.1, 2.1]) {
+ const post = new THREE.Mesh(postGeo, postMat);
+ post.position.set(x, 1.9, 0); post.castShadow = true;
+ this.group.add(post);
+ }
+ disposables.push(postGeo, postMat);
+
+ // Header panel with "OPEN WORK".
+ const headTex = headerTexture();
+ const headGeo = new THREE.PlaneGeometry(4.4, 1.1);
+ const headMat = new THREE.MeshBasicMaterial({ map: headTex, transparent: false });
+ const head = new THREE.Mesh(headGeo, headMat);
+ head.position.set(0, 3.7, 0.02);
+ this.group.add(head);
+ // Back face so the board reads from behind too.
+ const headBack = new THREE.Mesh(headGeo, new THREE.MeshBasicMaterial({ color: 0x0b0d12 }));
+ headBack.position.set(0, 3.7, -0.02); headBack.rotation.y = Math.PI;
+ this.group.add(headBack);
+ disposables.push(headTex, headGeo, headMat, headBack.material);
+
+ // A soft accent strip under the header.
+ const stripGeo = new THREE.PlaneGeometry(4.4, 0.08);
+ const stripMat = new THREE.MeshBasicMaterial({ color: 0x4ea1ff, transparent: true, opacity: 0.85, blending: THREE.AdditiveBlending, depthWrite: false });
+ const strip = new THREE.Mesh(stripGeo, stripMat);
+ strip.position.set(0, 3.08, 0.03);
+ this.group.add(strip);
+ disposables.push(stripGeo, stripMat);
+ this._strip = strip;
+ }
+
+ _buildChrome() {
+ const root = this.ctx.root;
+
+ // Tooltip (hidden until hover/focus).
+ const tip = document.createElement('div');
+ tip.className = 'agora-econ-tooltip';
+ tip.setAttribute('role', 'tooltip');
+ tip.hidden = true;
+ root.appendChild(tip);
+ this._tip = tip;
+
+ // Accessible roster: a labelled region with one button per open task.
+ const roster = document.createElement('section');
+ roster.className = 'agora-econ-board-panel';
+ roster.setAttribute('aria-label', 'Open work on the job board');
+ const heading = document.createElement('h2');
+ heading.className = 'agora-econ-board-title';
+ heading.textContent = 'Open work';
+ const count = document.createElement('span');
+ count.className = 'agora-econ-board-count';
+ heading.appendChild(count);
+ const list = document.createElement('ul');
+ list.className = 'agora-econ-board-list';
+ roster.append(heading, list);
+ root.appendChild(roster);
+ this._roster = roster;
+ this._list = list;
+ this._count = count;
+
+ // Designed empty sign.
+ const empty = document.createElement('div');
+ empty.className = 'agora-econ-board-empty';
+ empty.hidden = true;
+ empty.innerHTML = `
+ <div class="agora-econ-board-empty-glyph" aria-hidden="true">◷</div>
+ <p class="agora-econ-board-empty-title">No open work right now</p>
+ <p class="agora-econ-board-empty-sub">The Commons is quiet. New bounties from agents and humans appear here the moment they're posted.</p>`;
+ roster.appendChild(empty);
+ this._empty = empty;
+ }
+
+ // ── Data ────────────────────────────────────────────────────────────────
+ // Merge AgenC tasks + x402 services into one open-work list, diff against the
+ // live markers, and rebuild the accessible roster.
+ setBoard(board) {
+ const tasks = [
+ ...(Array.isArray(board?.tasks) ? board.tasks : []),
+ ...(Array.isArray(board?.services) ? board.services : []),
+ ];
+ this._tasks = tasks;
+ this._reconcileMarkers(tasks);
+ this._renderRoster(tasks);
+ }
+
+ _reconcileMarkers(tasks) {
+ const nextKeys = new Set(tasks.map(taskKey));
+
+ // Remove markers no longer on the board (dispose strictly).
+ for (const [key, marker] of this._markers) {
+ if (!nextKeys.has(key)) {
+ this._disposeMarker(marker);
+ this._markers.delete(key);
+ }
+ }
+
+ // Add / update.
+ tasks.forEach((task, i) => {
+ const key = taskKey(task);
+ let marker = this._markers.get(key);
+ if (!marker) {
+ marker = this._createMarker(task);
+ this._markers.set(key, marker);
+ } else {
+ marker.task = task;
+ }
+ this._layoutMarker(marker, i, tasks.length);
+ });
+ }
+
+ _createMarker(task) {
+ const color = professionThreeColor(task.profession);
+ const grp = new THREE.Group();
+
+ const coreGeo = new THREE.SphereGeometry(0.22, 18, 14);
+ const coreMat = new THREE.MeshStandardMaterial({
+ color, emissive: color, emissiveIntensity: 1.4, roughness: 0.3, metalness: 0.1,
+ });
+ const core = new THREE.Mesh(coreGeo, coreMat);
+ grp.add(core);
+
+ const glowMat = new THREE.SpriteMaterial({
+ map: glowTexture(), color, transparent: true, opacity: 0.85,
+ blending: THREE.AdditiveBlending, depthWrite: false,
+ });
+ const glow = new THREE.Sprite(glowMat);
+ glow.scale.setScalar(1.4);
+ grp.add(glow);
+
+ // Thin beam down to the board so the marker reads as "pinned here".
+ const beamGeo = new THREE.CylinderGeometry(0.015, 0.015, 1, 6);
+ const beamMat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.25, blending: THREE.AdditiveBlending, depthWrite: false });
+ const beam = new THREE.Mesh(beamGeo, beamMat);
+ grp.add(beam);
+
+ this.group.add(grp);
+ this._meshIndex.set(core.uuid, taskKey(task));
+
+ return {
+ task, group: grp, core, glow, beam,
+ coreGeo, coreMat, glowMat, beamGeo, beamMat,
+ anchor: new THREE.Vector3(),
+ phase: Math.random() * Math.PI * 2,
+ baseScale: 1,
+ };
+ }
+
+ _layoutMarker(marker, i, total) {
+ const mag = rewardMagnitude(marker.task.reward);
+ const scale = rewardMarkerScale(mag);
+ marker.baseScale = scale;
+
+ const row = Math.floor(i / MARKERS_PER_ROW);
+ const inRow = i % MARKERS_PER_ROW;
+ const rowCount = Math.min(MARKERS_PER_ROW, total - row * MARKERS_PER_ROW);
+ const rowWidth = (rowCount - 1) * MARKER_GAP;
+ const x = inRow * MARKER_GAP - rowWidth / 2;
+ const y = MARKER_BASE_Y + row * ROW_GAP;
+ marker.group.position.set(x, y, 0);
+ marker.core.scale.setScalar(scale);
+ marker.glow.scale.setScalar(1.4 * scale);
+
+ // Beam reaches from the marker down to the header strip (~y 3.1 local).
+ const beamLen = Math.max(0.2, y - 3.1);
+ marker.beam.scale.y = beamLen;
+ marker.beam.position.y = -beamLen / 2 - 0.1;
+
+ // World anchor for tooltip/screen projection.
+ marker.group.getWorldPosition(marker.anchor);
+ marker.anchor.y += 0.4 * scale;
+ }
+
+ _disposeMarker(marker) {
+ this._meshIndex.delete(marker.core.uuid);
+ this.group.remove(marker.group);
+ marker.coreGeo.dispose();
+ marker.coreMat.dispose();
+ marker.glowMat.dispose(); // shared glow texture is NOT disposed here
+ marker.beamGeo.dispose();
+ marker.beamMat.dispose();
+ }
+
+ _renderRoster(tasks) {
+ this._count.textContent = tasks.length ? ` · ${tasks.length}` : '';
+ this._list.innerHTML = '';
+ this._empty.hidden = tasks.length > 0;
+ this._list.hidden = tasks.length === 0;
+
+ for (const task of tasks) {
+ const key = taskKey(task);
+ const li = document.createElement('li');
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'agora-econ-board-item';
+ btn.style.setProperty('--accent', professionColor(task.profession));
+ const chip = rewardChip(task.reward);
+ btn.innerHTML = `
+ <span class="agora-econ-board-dot" aria-hidden="true"></span>
+ <span class="agora-econ-board-item-main">
+ <span class="agora-econ-board-item-title">${escapeHtml(task.title || 'Untitled task')}</span>
+ <span class="agora-econ-board-item-meta">${escapeHtml(professionLabelFor(task.profession))}${chip ? ' · ' + escapeHtml(chip) : ''}</span>
+ </span>`;
+ const onActivate = () => this.ctx.onSelectTask?.(task, key);
+ btn.addEventListener('click', onActivate);
+ btn.addEventListener('mouseenter', () => this._setHover(key));
+ btn.addEventListener('mouseleave', () => this._setHover(null));
+ btn.addEventListener('focus', () => this._setHover(key));
+ btn.addEventListener('blur', () => this._setHover(null));
+ li.appendChild(btn);
+ this._list.appendChild(li);
+ }
+ }
+
+ // ── Raycast routing (called by the economy layer's single picker) ─────────
+ get pickables() {
+ return [...this._markers.values()].map((m) => m.core);
+ }
+
+ keyForMesh(mesh) {
+ return this._meshIndex.get(mesh?.uuid) || null;
+ }
+
+ taskForKey(key) {
+ return this._markers.get(key)?.task || null;
+ }
+
+ hoverByMesh(mesh) {
+ this._setHover(mesh ? this.keyForMesh(mesh) : null);
+ }
+
+ _setHover(key) {
+ if (this._hoverKey === key) return;
+ this._hoverKey = key;
+ const marker = key ? this._markers.get(key) : null;
+ if (!marker) { this._tip.hidden = true; return; }
+ const task = marker.task;
+ const chip = rewardChip(task.reward);
+ this._tip.innerHTML = `
+ <div class="agora-econ-tip-title">${escapeHtml(task.title || 'Untitled task')}</div>
+ <div class="agora-econ-tip-row">
+ <span class="agora-econ-tip-prof" style="--accent:${professionColor(task.profession)}">${escapeHtml(professionLabelFor(task.profession))}</span>
+ ${chip ? `<span class="agora-econ-tip-reward">${escapeHtml(chip)}</span>` : ''}
+ </div>
+ ${task.source === 'x402' ? '<div class="agora-econ-tip-sub">x402 service · pay-per-call</div>' : ''}`;
+ this._tip.hidden = false;
+ }
+
+ // ── Per-frame ─────────────────────────────────────────────────────────────
+ update(dt) {
+ this._t += dt;
+ for (const marker of this._markers.values()) {
+ if (!this.reducedMotion) {
+ const bob = Math.sin(this._t * 1.6 + marker.phase) * 0.12;
+ marker.core.position.y = bob;
+ marker.glow.position.y = bob;
+ const pulse = 0.85 + 0.15 * Math.sin(this._t * 2.4 + marker.phase);
+ marker.glowMat.opacity = pulse;
+ marker.coreMat.emissiveIntensity = 1.1 + 0.5 * pulse;
+ }
+ marker.group.getWorldPosition(marker.anchor);
+ marker.anchor.y += 0.4 * marker.baseScale + (this.reducedMotion ? 0 : marker.core.position.y);
+ }
+ if (!this.reducedMotion && this._strip) {
+ this._strip.material.opacity = 0.6 + 0.25 * Math.sin(this._t * 1.2);
+ }
+
+ // Keep the tooltip glued to its marker.
+ if (this._hoverKey) {
+ const marker = this._markers.get(this._hoverKey);
+ if (marker) {
+ const s = this.ctx.worldToScreen(marker.anchor);
+ if (s.visible) {
+ this._tip.style.transform = `translate(-50%, -100%) translate(${s.x}px, ${s.y - 14}px)`;
+ this._tip.hidden = false;
+ } else {
+ this._tip.hidden = true;
+ }
+ }
+ }
+ }
+
+ dispose() {
+ for (const marker of this._markers.values()) this._disposeMarker(marker);
+ this._markers.clear();
+ this._meshIndex.clear();
+ for (const d of this._disposables) d.dispose?.();
+ this.scene.remove(this.group);
+ this._tip?.remove();
+ this._roster?.remove();
+ }
+}
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
+ ));
+}
diff --git a/src/agora/job-detail.js b/src/agora/job-detail.js
new file mode 100644
index 000000000..417f8cb74
--- /dev/null
+++ b/src/agora/job-detail.js
@@ -0,0 +1,215 @@
+// Agora — the job detail panel. Click a board marker (an open task) or a
+// completed-task row in a passport, and this renders the job's real on-chain
+// lifecycle: created → claimed → completed, each step with its actor and a
+// Solana Explorer link to the actual transaction. For a completed task it also
+// mounts the public deliverable verifier (verify.js) so anyone can re-hash the
+// artifact and confirm it against the on-chain proofHash.
+
+import { h, infoRow, rewardChip, copyChip } from './panel.js';
+import { fetchTask } from './api.js';
+import { mountVerifier } from './verify.js';
+import {
+ explorerTxUrl, explorerAddressUrl, shortId, timeAgo, absoluteTime,
+ professionLabel, formatThree,
+} from './format.js';
+
+// Ordered lifecycle steps we render even before they've happened, so a partly-
+// complete job reads as a path with the remaining steps shown as upcoming.
+const LIFECYCLE_STEPS = [
+ { match: /^create/i, key: 'created', label: 'Created', desc: 'Bounty posted & reward escrowed' },
+ { match: /^claim/i, key: 'claimed', label: 'Claimed', desc: 'Worker took the job' },
+ { match: /^(complete|prove|submit)/i, key: 'completed', label: 'Completed', desc: 'Proof accepted, reward released' },
+];
+
+function stateBadge(state) {
+ const s = String(state || 'Unknown');
+ const cls = {
+ Open: 'is-open', Claimed: 'is-claimed', Completed: 'is-completed',
+ Cancelled: 'is-cancelled', Disputed: 'is-disputed', Expired: 'is-expired',
+ }[s] || 'is-unknown';
+ return h('span', { class: `agora-badge ${cls}` }, [s]);
+}
+
+// Render the job into the shared panel. opts carries everything the caller knows;
+// the on-chain truth (state + timeline) is (re)fetched here.
+//
+// opts: { taskPda, creator, taskId, cluster, title, profession, reward,
+// proofHash, deliverableUrl, txSignature }
+// ctx: { onOpenPassport(actorPda) } — optional cross-links
+export async function renderJobDetail(panel, opts = {}, ctx = {}) {
+ const cluster = opts.cluster === 'mainnet' ? 'mainnet' : 'devnet';
+ panel.setHeader(opts.title || 'Job', opts.taskPda ? jobSubheader(opts.taskPda, cluster) : 'On-chain task');
+ panel.setLoading('Loading job lifecycle…');
+ panel.open(opts.opener);
+
+ if (!opts.taskPda && !(opts.creator && opts.taskId)) {
+ panel.setError('This job has no on-chain task reference to load.');
+ return;
+ }
+
+ const ac = new AbortController();
+ panel._jobAbort?.abort();
+ panel._jobAbort = ac;
+
+ let data;
+ try {
+ data = await fetchTask({
+ taskPda: opts.taskPda, creator: opts.creator, taskId: opts.taskId,
+ cluster, lifecycle: true,
+ }, { signal: ac.signal });
+ } catch (err) {
+ panel.setError(`Couldn't load this job from the chain: ${err.message}`, () => renderJobDetail(panel, opts, ctx));
+ return;
+ }
+ if (ac.signal.aborted) return;
+
+ if (!data || data.ok === false) {
+ // not_found is a real, designed state — the PDA exists in the projection
+ // but the on-chain account is gone or on another cluster.
+ panel.setBody(buildNotFound(opts, cluster));
+ return;
+ }
+
+ const task = data.task || {};
+ const lifecycle = data.lifecycle || null;
+ const state = task.state || lifecycle?.currentState || 'Unknown';
+
+ panel.setHeader(opts.title || 'Job', jobSubheader(opts.taskPda || data.taskPda, cluster));
+ panel.setBody(buildJob({ opts, data, task, lifecycle, state, cluster }, ctx));
+}
+
+function jobSubheader(taskPda, cluster) {
+ const frag = h('span', { class: 'agora-sub-row' }, [
+ h('span', { class: 'agora-chip agora-chip-cluster' }, [cluster]),
+ h('code', { class: 'agora-sub-code' }, [shortId(taskPda, 4, 4)]),
+ copyChip(taskPda, 'task PDA'),
+ ]);
+ return frag;
+}
+
+function buildJob({ opts, task, lifecycle, state, cluster }, ctx) {
+ const reward = opts.reward || (task.rewardAmount != null ? {
+ label: `${formatThree(task.rewardAmount)} $THREE`,
+ amountAtomic: String(task.rewardAmount),
+ } : null);
+
+ const meta = h('div', { class: 'agora-job-meta' }, [
+ h('div', { class: 'agora-job-state' }, [stateBadge(state)]),
+ reward ? h('div', { class: 'agora-job-reward' }, [
+ h('span', { class: 'agora-kv-key' }, ['Reward']),
+ rewardChip(reward.label?.replace(/\s*\$THREE$/i, '') || formatThree(reward.amountAtomic), '$THREE'),
+ ]) : null,
+ ].filter(Boolean));
+
+ const facts = h('div', { class: 'agora-facts' }, [
+ opts.profession ? infoRow('Profession', h('span', { class: 'agora-chip agora-chip-prof' }, [professionLabel(opts.profession)])) : null,
+ infoRow('Workers', `${task.currentWorkers ?? 0} / ${task.maxWorkers ?? 1}`),
+ task.creator ? infoRow('Creator', addressLink(task.creator, cluster)) : null,
+ task.deadline ? infoRow('Deadline', absoluteTime(Number(task.deadline))) : null,
+ task.private ? infoRow('Visibility', 'Private (constraint-gated)') : null,
+ ].filter(Boolean));
+
+ const timeline = buildTimeline(lifecycle, cluster, ctx);
+
+ const verifySection = buildVerifySection(opts, state);
+
+ return [meta, facts, timeline, verifySection];
+}
+
+function buildTimeline(lifecycle, cluster, ctx) {
+ const section = h('section', { class: 'agora-section' }, [
+ h('h3', { class: 'agora-section-title' }, ['Lifecycle']),
+ ]);
+
+ const events = lifecycle?.timeline || [];
+ if (!events.length) {
+ section.appendChild(h('p', { class: 'agora-muted agora-section-empty' }, [
+ 'No on-chain lifecycle events recorded yet for this task.',
+ ]));
+ return section;
+ }
+
+ const list = h('ol', { class: 'agora-timeline' });
+ for (const ev of events) {
+ const step = LIFECYCLE_STEPS.find((s) => s.match.test(ev.eventName)) || null;
+ list.appendChild(h('li', { class: 'agora-timeline-item is-done' }, [
+ h('span', { class: 'agora-timeline-dot', 'aria-hidden': 'true' }),
+ h('div', { class: 'agora-timeline-body' }, [
+ h('div', { class: 'agora-timeline-head' }, [
+ h('span', { class: 'agora-timeline-label' }, [step?.label || ev.eventName]),
+ ev.timestamp ? h('time', { class: 'agora-timeline-time', title: absoluteTime(Number(ev.timestamp)) }, [timeAgo(Number(ev.timestamp))]) : null,
+ ].filter(Boolean)),
+ step?.desc ? h('div', { class: 'agora-timeline-desc' }, [step.desc]) : null,
+ h('div', { class: 'agora-timeline-links' }, [
+ ev.actor ? actorLink(ev.actor, cluster, ctx) : null,
+ ev.txSignature ? h('a', {
+ class: 'agora-tx-link',
+ href: explorerTxUrl(ev.txSignature, cluster),
+ target: '_blank', rel: 'noopener noreferrer',
+ title: 'View transaction on Solana Explorer',
+ }, ['tx ', shortId(ev.txSignature, 4, 4), ' ↗']) : h('span', { class: 'agora-muted agora-tx-link' }, ['no tx recorded']),
+ ].filter(Boolean)),
+ ]),
+ ]));
+ }
+ section.appendChild(list);
+ return section;
+}
+
+function buildVerifySection(opts, state) {
+ const section = h('section', { class: 'agora-section' }, [
+ h('h3', { class: 'agora-section-title' }, [
+ 'Verify deliverable',
+ h('span', { class: 'agora-section-hint' }, ['re-hash it yourself — no trust required']),
+ ]),
+ ]);
+ const isCompleted = /complete/i.test(String(state));
+ if (!isCompleted && !opts.deliverableUrl) {
+ section.appendChild(h('p', { class: 'agora-muted agora-section-empty' }, [
+ 'This task isn\'t completed yet — there\'s no deliverable to verify.',
+ ]));
+ return section;
+ }
+ const mount = h('div', { class: 'agora-verify-mount' });
+ section.appendChild(mount);
+ mountVerifier(mount, { deliverableUrl: opts.deliverableUrl, proofHash: opts.proofHash });
+ return section;
+}
+
+function actorLink(pda, cluster, ctx) {
+ const link = addressLink(pda, cluster);
+ if (typeof ctx.onOpenPassport === 'function') {
+ const btn = h('button', {
+ class: 'agora-actor-link', type: 'button',
+ title: 'Open this citizen\'s passport',
+ }, [shortId(pda, 4, 4)]);
+ btn.addEventListener('click', () => ctx.onOpenPassport(pda));
+ return h('span', { class: 'agora-timeline-actor' }, [
+ h('span', { class: 'agora-muted' }, ['by ']), btn,
+ h('a', { class: 'agora-addr-ext', href: explorerAddressUrl(pda, cluster), target: '_blank', rel: 'noopener noreferrer', title: 'View account on Explorer', 'aria-label': 'View account on Explorer' }, ['↗']),
+ ]);
+ }
+ return h('span', { class: 'agora-timeline-actor' }, [h('span', { class: 'agora-muted' }, ['by ']), link]);
+}
+
+function addressLink(address, cluster) {
+ return h('a', {
+ class: 'agora-addr', href: explorerAddressUrl(address, cluster),
+ target: '_blank', rel: 'noopener noreferrer',
+ title: `${address} — view on Solana Explorer`,
+ }, [shortId(address, 4, 4), ' ↗']);
+}
+
+function buildNotFound(opts, cluster) {
+ return h('div', { class: 'agora-state agora-state-empty' }, [
+ h('div', { class: 'agora-state-icon', 'aria-hidden': 'true' }, ['◌']),
+ h('p', { class: 'agora-state-msg' }, ['This task isn\'t on the ', cluster, ' chain.']),
+ h('p', { class: 'agora-state-hint' }, [
+ 'The projection references it but the on-chain account wasn\'t found — it may be on another cluster or has been closed.',
+ ]),
+ opts.taskPda ? h('div', { class: 'agora-hash-row' }, [
+ h('code', { class: 'agora-hash' }, [shortId(opts.taskPda, 8, 8)]),
+ copyChip(opts.taskPda, 'task PDA'),
+ ]) : null,
+ ].filter(Boolean));
+}
diff --git a/src/agora/professions.js b/src/agora/professions.js
index c6e8f68cc..3dc6470bb 100644
--- a/src/agora/professions.js
+++ b/src/agora/professions.js
@@ -12,6 +12,21 @@ import { professionColor, PROFESSION_COLORS } from './citizen-avatar.js';
export { professionColor, PROFESSION_COLORS };
+// Display labels for the profession keys the API emits (lowercase). Falls back
+// to a capitalised key so an unmapped/new profession still reads cleanly —
+// open by design, never a hardcoded gate.
+const PROFESSION_LABELS = {
+ fetcher: 'Fetcher', sculptor: 'Sculptor', scribe: 'Scribe',
+ cartographer: 'Cartographer', crier: 'Crier', appraiser: 'Appraiser',
+ verifier: 'Verifier', namekeeper: 'Namekeeper',
+};
+export function professionLabelFor(profession) {
+ const key = String(profession || '').toLowerCase();
+ if (PROFESSION_LABELS[key]) return PROFESSION_LABELS[key];
+ if (!key) return 'Citizen';
+ return key.charAt(0).toUpperCase() + key.slice(1);
+}
+
// 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.
diff --git a/src/agora/pulse-feed.js b/src/agora/pulse-feed.js
new file mode 100644
index 000000000..eb6ffede3
--- /dev/null
+++ b/src/agora/pulse-feed.js
@@ -0,0 +1,170 @@
+// Pulse feed — the heartbeat that drives the Commons economy visuals.
+//
+// Polls the two real, agora-specific read endpoints and turns them into a small
+// event stream the job board, ticker and economy FX subscribe to:
+// • /api/agora/board → open tasks + x402 services (job-board markers)
+// • /api/agora/pulse → population, 24h economy, top earners, recent narration
+//
+// Discipline the DoD asks for:
+// • De-dupe by activity id. The FIRST pulse seeds the "seen" set silently so we
+// don't replay history as fresh events (no phantom plinth on page load); only
+// genuinely new activities after that emit `activity` (→ claim-walks,
+// completions). The full recent list still ships as `pulse` for the ticker.
+// • Exponential backoff on failure (per resource), capped, with jitter.
+// • Pause entirely while the tab is hidden (visibilitychange); refresh
+// immediately on return so an away-then-back user sees current state, not a
+// stale frame, and we never poll — or thrash the GPU — in the background.
+//
+// SSE note: api/feed-stream.js is the *platform-wide* feed; the agora narration
+// is only a projection within it and isn't id-addressable per citizen, so a
+// short, deduped poll of the agora-specific endpoints is the honest, robust
+// source. The interface here is event-based so a future agora SSE can replace
+// the poller without touching a single consumer.
+
+const DEFAULTS = {
+ pulseInterval: 5000, // ms between pulse polls when healthy
+ boardInterval: 12000, // ms between board polls when healthy
+ maxBackoff: 60000, // ceiling for failed-poll backoff
+ fetchTimeout: 12000, // per-request abort timeout
+ seenCap: 600, // bounded de-dupe memory
+};
+
+export class PulseFeed {
+ constructor(opts = {}) {
+ this.opts = { ...DEFAULTS, ...opts };
+ this._listeners = new Map(); // type → Set<fn>
+ this._timers = { pulse: null, board: null };
+ this._backoff = { pulse: 0, board: 0 };
+ this._seen = new Set();
+ this._seenOrder = [];
+ this._seeded = false;
+ this._running = false;
+ this._lastPulse = null;
+ this._lastBoard = null;
+ this._onVisibility = this._handleVisibility.bind(this);
+ }
+
+ on(type, fn) {
+ if (!this._listeners.has(type)) this._listeners.set(type, new Set());
+ this._listeners.get(type).add(fn);
+ return () => this._listeners.get(type)?.delete(fn);
+ }
+
+ _emit(type, payload) {
+ const set = this._listeners.get(type);
+ if (!set) return;
+ for (const fn of set) {
+ try { fn(payload); } catch (err) { console.warn(`[agora] feed listener (${type}) threw:`, err?.message); }
+ }
+ }
+
+ start() {
+ if (this._running) return;
+ this._running = true;
+ document.addEventListener('visibilitychange', this._onVisibility);
+ if (!document.hidden) {
+ this._poll('pulse');
+ this._poll('board');
+ }
+ }
+
+ stop() {
+ this._running = false;
+ document.removeEventListener('visibilitychange', this._onVisibility);
+ for (const k of Object.keys(this._timers)) {
+ if (this._timers[k]) { clearTimeout(this._timers[k]); this._timers[k] = null; }
+ }
+ this._listeners.clear();
+ }
+
+ // Force an immediate refresh of both resources (e.g. after returning to tab).
+ refreshNow() {
+ if (!this._running || document.hidden) return;
+ this._poll('pulse', true);
+ this._poll('board', true);
+ }
+
+ _handleVisibility() {
+ if (document.hidden) {
+ for (const k of Object.keys(this._timers)) {
+ if (this._timers[k]) { clearTimeout(this._timers[k]); this._timers[k] = null; }
+ }
+ } else if (this._running) {
+ this._poll('pulse', true);
+ this._poll('board', true);
+ }
+ }
+
+ _schedule(resource) {
+ if (!this._running || document.hidden) return;
+ if (this._timers[resource]) clearTimeout(this._timers[resource]);
+ const base = resource === 'pulse' ? this.opts.pulseInterval : this.opts.boardInterval;
+ const backoff = this._backoff[resource];
+ const delay = backoff > 0
+ ? Math.min(this.opts.maxBackoff, backoff) + Math.random() * 1000
+ : base + Math.random() * 600;
+ this._timers[resource] = setTimeout(() => this._poll(resource), delay);
+ }
+
+ async _poll(resource, immediate = false) {
+ if (!this._running || document.hidden) return;
+ if (immediate && this._timers[resource]) { clearTimeout(this._timers[resource]); this._timers[resource] = null; }
+
+ const url = resource === 'pulse'
+ ? '/api/agora/pulse'
+ : '/api/agora/board?maxItems=60';
+
+ const controller = new AbortController();
+ const to = setTimeout(() => controller.abort(), this.opts.fetchTimeout);
+ try {
+ const res = await fetch(url, { headers: { accept: 'application/json' }, signal: controller.signal });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ this._backoff[resource] = 0;
+ if (resource === 'pulse') this._handlePulse(data);
+ else this._handleBoard(data);
+ } catch (err) {
+ // Grow backoff: 2s → 4s → … → maxBackoff. Surface once for observability.
+ const next = this._backoff[resource] ? this._backoff[resource] * 2 : 2000;
+ this._backoff[resource] = Math.min(this.opts.maxBackoff, next);
+ this._emit('error', { resource, error: err?.message || 'poll_failed', backoff: this._backoff[resource] });
+ } finally {
+ clearTimeout(to);
+ this._schedule(resource);
+ }
+ }
+
+ _markSeen(id) {
+ this._seen.add(id);
+ this._seenOrder.push(id);
+ if (this._seenOrder.length > this.opts.seenCap) {
+ const drop = this._seenOrder.shift();
+ this._seen.delete(drop);
+ }
+ }
+
+ _handlePulse(data) {
+ this._lastPulse = data;
+ this._emit('pulse', data);
+
+ const recent = Array.isArray(data?.recent) ? data.recent : [];
+ if (!this._seeded) {
+ // Seed silently — these are history, not live events.
+ for (const a of recent) if (a?.id != null) this._markSeen(a.id);
+ this._seeded = true;
+ return;
+ }
+ // Oldest-first so consumers process activities in chronological order.
+ for (let i = recent.length - 1; i >= 0; i--) {
+ const a = recent[i];
+ if (a?.id == null || this._seen.has(a.id)) continue;
+ this._markSeen(a.id);
+ this._emit('activity', a);
+ }
+ }
+
+ _handleBoard(data) {
+ this._lastBoard = data;
+ this._emit('board', data);
+ }
+}
diff --git a/src/agora/ticker.js b/src/agora/ticker.js
new file mode 100644
index 000000000..15a106af8
--- /dev/null
+++ b/src/agora/ticker.js
@@ -0,0 +1,178 @@
+import { professionColor, professionLabelFor } from './professions.js';
+
+// The ticker — the HUD that keeps the economy legible without entering the 3D
+// scene. Two parts, both bound to /api/agora/pulse:
+// • A compact economy readout: population, tasks completed in 24h, $THREE
+// earned in 24h, and the top earners.
+// • A live narration feed of pulse.recent — claims, completions, payouts,
+// posts — newest on top, each line click-to-focus on its subject (the
+// citizen, or the deliverable on its plinth).
+//
+// Self-contained: it builds its own DOM into the overlay root, so it doesn't
+// depend on the Task 05 page markup having reserved slots.
+
+const THREE_DECIMALS = 6;
+
+function fmtThreeAtomic(atomic) {
+ const n = Number(atomic || 0) / 10 ** THREE_DECIMALS;
+ if (!Number.isFinite(n) || n <= 0) return '0';
+ return compact(n);
+}
+
+function compact(n) {
+ if (n >= 1e9) return (n / 1e9).toFixed(n >= 1e10 ? 0 : 1) + 'B';
+ if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + 'M';
+ if (n >= 1e3) return (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + 'k';
+ return String(Math.round(n));
+}
+
+const KIND_GLYPH = {
+ posted_task: '📋', claimed_task: '🤝', completed_task: '✅',
+ earned: '🪙', vouched: '⭐', registered: '🌱', slashed: '⚠️',
+};
+
+export class Ticker {
+ constructor(ctx) {
+ this.ctx = ctx; // { root, onFocusActivity, reducedMotion }
+ this.reducedMotion = !!ctx.reducedMotion;
+ this._shown = new Set(); // activity ids already in the feed
+ this._build();
+ }
+
+ _build() {
+ const panel = document.createElement('aside');
+ panel.className = 'agora-econ-ticker';
+ panel.setAttribute('aria-label', 'Agora economy');
+
+ // Economy readout.
+ const readout = document.createElement('div');
+ readout.className = 'agora-econ-readout';
+ readout.innerHTML = `
+ <div class="agora-econ-stat" data-k="pop"><span class="agora-econ-stat-v">—</span><span class="agora-econ-stat-l">citizens</span></div>
+ <div class="agora-econ-stat" data-k="done"><span class="agora-econ-stat-v">—</span><span class="agora-econ-stat-l">tasks · 24h</span></div>
+ <div class="agora-econ-stat" data-k="three"><span class="agora-econ-stat-v">—</span><span class="agora-econ-stat-l">$THREE · 24h</span></div>`;
+ this._stat = {
+ pop: readout.querySelector('[data-k="pop"] .agora-econ-stat-v'),
+ done: readout.querySelector('[data-k="done"] .agora-econ-stat-v'),
+ three: readout.querySelector('[data-k="three"] .agora-econ-stat-v'),
+ };
+ panel.appendChild(readout);
+
+ // Top earners.
+ const earners = document.createElement('div');
+ earners.className = 'agora-econ-earners';
+ earners.innerHTML = `<div class="agora-econ-earners-h">Top earners</div><ol class="agora-econ-earners-list"></ol>`;
+ this._earnersList = earners.querySelector('.agora-econ-earners-list');
+ panel.appendChild(earners);
+
+ // Live feed.
+ const feedWrap = document.createElement('div');
+ feedWrap.className = 'agora-econ-feed-wrap';
+ feedWrap.innerHTML = `<div class="agora-econ-feed-h">Live activity</div>`;
+ const feed = document.createElement('ul');
+ feed.className = 'agora-econ-feed';
+ feed.setAttribute('aria-live', 'polite');
+ feed.setAttribute('aria-label', 'Recent Agora activity');
+ feedWrap.appendChild(feed);
+ this._feed = feed;
+ this._feedEmpty = document.createElement('li');
+ this._feedEmpty.className = 'agora-econ-feed-empty';
+ this._feedEmpty.textContent = 'Waiting for the economy to stir…';
+ feed.appendChild(this._feedEmpty);
+ panel.appendChild(feedWrap);
+
+ this.ctx.root.appendChild(panel);
+ this._panel = panel;
+ }
+
+ setPulse(pulse) {
+ if (!pulse) return;
+ const pop = pulse.population || {};
+ const econ = pulse.economy || {};
+ this._stat.pop.textContent = compact(pop.total || 0);
+ this._stat.pop.title = `${pop.agents || 0} agents · ${pop.humans || 0} humans · ${pop.active24h || 0} active 24h`;
+ this._stat.done.textContent = compact(econ.tasksCompleted24h || 0);
+ this._stat.three.textContent = fmtThreeAtomic(econ.threeEarned24hAtomic);
+ this._stat.three.title = `${econ.payouts24h || 0} payouts in the last 24h`;
+
+ this._renderEarners(pulse.topEarners || []);
+ this._mergeRecent(pulse.recent || []);
+ }
+
+ _renderEarners(earners) {
+ this._earnersList.innerHTML = '';
+ if (!earners.length) {
+ const li = document.createElement('li');
+ li.className = 'agora-econ-earners-empty';
+ li.textContent = 'No earnings yet';
+ this._earnersList.appendChild(li);
+ return;
+ }
+ for (const e of earners) {
+ const li = document.createElement('li');
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'agora-econ-earner';
+ btn.style.setProperty('--accent', professionColor(e.profession));
+ btn.innerHTML = `
+ <span class="agora-econ-earner-name">${escapeHtml(e.displayName || 'Citizen')}</span>
+ <span class="agora-econ-earner-amt">${fmtThreeAtomic(e.earnedThreeAtomic)} $THREE</span>`;
+ btn.addEventListener('click', () => this.ctx.onFocusActivity?.({ actor: e.displayName, citizenId: e.id, kind: 'earner' }));
+ li.appendChild(btn);
+ this._earnersList.appendChild(li);
+ }
+ }
+
+ // Merge the server's recent list (newest-first) into the feed, prepending
+ // only genuinely new ids with an enter animation.
+ _mergeRecent(recent) {
+ // Oldest → newest so prepending yields newest-on-top.
+ for (let i = recent.length - 1; i >= 0; i--) {
+ const a = recent[i];
+ if (a?.id == null || this._shown.has(a.id)) continue;
+ this._shown.add(a.id);
+ this._prepend(a);
+ }
+ // Cap memory + DOM.
+ while (this._feed.children.length > 14) {
+ const last = this._feed.lastElementChild;
+ if (last === this._feedEmpty) break;
+ last.remove();
+ }
+ }
+
+ _prepend(a) {
+ if (this._feedEmpty.parentNode) this._feedEmpty.remove();
+ const li = document.createElement('li');
+ li.className = 'agora-econ-feed-item' + (this.reducedMotion ? '' : ' enter');
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'agora-econ-feed-btn';
+ btn.style.setProperty('--accent', professionColor(a.profession));
+ const glyph = KIND_GLYPH[a.kind] || '•';
+ btn.innerHTML = `
+ <span class="agora-econ-feed-glyph" aria-hidden="true">${glyph}</span>
+ <span class="agora-econ-feed-text">
+ <span class="agora-econ-feed-narr">${escapeHtml(a.narrative || a.kind)}</span>
+ ${a.rewardLabel ? `<span class="agora-econ-feed-reward">${escapeHtml(a.rewardLabel)}</span>` : ''}
+ </span>`;
+ btn.addEventListener('click', () => this.ctx.onFocusActivity?.(a));
+ li.appendChild(btn);
+ this._feed.insertBefore(li, this._feed.firstChild);
+ if (!this.reducedMotion) {
+ // Trigger the enter transition on the next frame, then clear the class.
+ requestAnimationFrame(() => li.classList.remove('enter'));
+ }
+ }
+
+ dispose() {
+ this._panel?.remove();
+ this._shown.clear();
+ }
+}
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
+ ));
+}
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index cba50e313..4ca233c91 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -2668,3 +2668,106 @@ select.npc-svc-input { cursor: pointer; appearance: none; -webkit-appearance: no
#cc-tag-alert { font-size: 22px; padding: 10px 22px; }
}
/* ── end tag mini-game ──────────────────────────────────────────────────────── */
+
+/* ── King of the Totem mini-game (R07) ──────────────────────────────────────── */
+#cc-king-hud {
+ position: fixed; top: 12px; left: 50%; transform: translateX(-50%);
+ z-index: 40; pointer-events: none;
+ width: 224px; max-width: calc(100vw - 24px);
+ background: var(--cc-panel);
+ border: 1px solid var(--cc-edge);
+ border-radius: var(--cc-radius);
+ box-shadow: var(--cc-shadow);
+ padding: 9px 12px 10px;
+ text-align: center;
+ backdrop-filter: blur(8px);
+ animation: cc-fade 0.25s ease;
+}
+.cc-king-head {
+ display: flex; align-items: center; justify-content: center; gap: 6px;
+ font-size: 10.5px; font-weight: 800; letter-spacing: 0.13em; text-transform: uppercase;
+ color: #ffce5c;
+}
+.cc-king-head-ico { font-size: 12px; filter: drop-shadow(0 0 5px rgba(255, 206, 92, 0.55)); }
+.cc-king-clock { margin: 3px 0 1px; }
+.cc-king-timer {
+ font-size: 30px; font-weight: 800; line-height: 1;
+ color: var(--cc-text);
+ font-variant-numeric: tabular-nums; letter-spacing: 0.01em;
+}
+.cc-king-timer.cc-king-low { color: #ff6b6b; animation: cc-king-low-pulse 1s ease-in-out infinite; }
+@keyframes cc-king-low-pulse { 50% { opacity: 0.45; } }
+.cc-king-timer-cap {
+ font-size: 9px; font-weight: 600; letter-spacing: 0.16em; text-transform: uppercase;
+ color: var(--cc-faint); margin-top: 1px;
+}
+.cc-king-phase {
+ font-size: 11px; font-weight: 600; color: var(--cc-dim);
+ margin: 4px 0 7px; min-height: 14px;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.cc-king-board {
+ display: flex; flex-direction: column; gap: 2px;
+ border-top: 1px solid var(--cc-edge); padding-top: 7px;
+}
+.cc-king-row {
+ display: grid; grid-template-columns: 16px 1fr auto; align-items: center; gap: 8px;
+ font-size: 11px; color: var(--cc-dim);
+ padding: 2px 5px; border-radius: var(--cc-radius-sm);
+ transition: background 0.18s ease, color 0.18s ease;
+}
+.cc-king-rank { color: var(--cc-faint); font-variant-numeric: tabular-nums; text-align: right; }
+.cc-king-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left; }
+.cc-king-score { font-variant-numeric: tabular-nums; font-weight: 700; color: var(--cc-text); }
+.cc-king-row--empty { color: var(--cc-faint); font-style: italic; grid-template-columns: 1fr; text-align: center; }
+.cc-king-me { background: rgba(255, 255, 255, 0.07); color: var(--cc-text); }
+.cc-king-me .cc-king-rank { color: var(--cc-dim); }
+.cc-king-holding {
+ background: rgba(255, 206, 92, 0.12);
+ box-shadow: inset 0 0 0 1px rgba(255, 206, 92, 0.3);
+}
+.cc-king-holding .cc-king-name, .cc-king-holding .cc-king-score { color: #ffce5c; }
+.cc-king-empty {
+ font-size: 11px; color: var(--cc-dim); line-height: 1.45;
+ padding: 4px 2px 2px; border-top: 1px solid var(--cc-edge);
+}
+
+/* The 👑 that floats above the current king's head (world-projected). */
+.cc-king-crown {
+ position: fixed; z-index: 41; pointer-events: none;
+ transform: translate(-50%, -50%);
+ font-size: 22px; line-height: 1;
+ filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.6)) drop-shadow(0 0 8px rgba(255, 206, 92, 0.55));
+ animation: cc-king-crown-bob 1.6s ease-in-out infinite;
+ will-change: transform, top, left;
+}
+@keyframes cc-king-crown-bob { 50% { transform: translate(-50%, -64%); } }
+
+/* Centre-screen winner flash. */
+#cc-king-banner {
+ position: fixed; top: 28%; left: 50%; transform: translateX(-50%) scale(0.8);
+ z-index: 200; pointer-events: none; text-align: center;
+ background: linear-gradient(160deg, rgba(40, 32, 8, 0.94), rgba(18, 14, 4, 0.94));
+ border: 1px solid rgba(255, 206, 92, 0.55);
+ color: #fff; padding: 18px 38px; border-radius: 16px;
+ box-shadow: 0 0 50px rgba(255, 206, 92, 0.4);
+ opacity: 0;
+ transition: opacity 0.22s ease, transform 0.22s cubic-bezier(0.22, 1.2, 0.36, 1);
+}
+#cc-king-banner.cc-king-banner--show { opacity: 1; transform: translateX(-50%) scale(1); }
+.cc-king-banner-crown { font-size: 42px; line-height: 1; filter: drop-shadow(0 0 14px rgba(255, 206, 92, 0.7)); animation: cc-king-crown-bob 1.6s ease-in-out infinite; }
+.cc-king-banner-title { font-size: 21px; font-weight: 900; letter-spacing: 0.01em; margin-top: 6px; }
+.cc-king-banner-sub { font-size: 14px; font-weight: 700; color: #ffce5c; margin-top: 3px; font-variant-numeric: tabular-nums; }
+
+@media (max-width: 640px) {
+ #cc-king-hud { top: 8px; width: 190px; padding: 8px 10px; }
+ .cc-king-timer { font-size: 26px; }
+ #cc-king-banner { padding: 14px 26px; }
+ .cc-king-banner-title { font-size: 18px; }
+ .cc-king-banner-crown { font-size: 34px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .cc-king-crown, .cc-king-banner-crown { animation: none; }
+ .cc-king-timer.cc-king-low { animation: none; }
+}
+/* ── end King of the Totem ──────────────────────────────────────────────────── */
diff --git a/src/theater-feed.js b/src/theater-feed.js
index 9a031807b..44db04ad9 100644
--- a/src/theater-feed.js
+++ b/src/theater-feed.js
@@ -59,6 +59,14 @@ export function normalizeEvent(e) {
return { ...base, kind: 'pay', title: 'Payment', sub: fmtUsdc(e.usdcAtomic) || e.recipientLabel || base.actor, href: e.explorerUrl || null };
case 'jackpot':
return { ...base, kind: 'win', title: 'Jackpot', sub: e.reward ? `${e.reward}` : base.actor, href: null };
+ case 'agora-registered':
+ return { ...base, kind: 'launch', title: 'Agora citizen joined', sub: base.actor, href: e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora' };
+ case 'agora-task-claimed':
+ return { ...base, kind: 'misc', title: `${base.actor} claimed a job`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-task-completed':
+ return { ...base, kind: 'verify', title: `${base.actor} proved a job`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-earned':
+ return { ...base, kind: 'pay', title: `${base.actor} earned`, sub: e.rewardLabel || base.actor, href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
default:
return { ...base, kind: 'misc', title: e.type.replace(/-/g, ' '), sub: base.actor, href: null };
}
diff --git a/tests/walkroom-king.test.js b/tests/walkroom-king.test.js
new file mode 100644
index 000000000..01c818ad0
--- /dev/null
+++ b/tests/walkroom-king.test.js
@@ -0,0 +1,172 @@
+// R07 — King of the Totem: server-authoritative area control. The full WalkRoom
+// needs the Colyseus runtime, so these tests drive the pure round + scoring
+// helpers against a minimal stand-in (Object.create avoids the Room constructor).
+// They lock the invariants a client must not be able to break: only a SOLE
+// occupant of the totem zone scores, contested/empty hold pays nobody, rounds
+// start/end on the machine, a winner is the top PRESENT player (or none), and a
+// player outside the zone can never score.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';
+
+// The totem zone the server scores around (mirrors KING_ZONE in WalkRoom.js).
+const ZONE = { x: 0, z: -12, r: 3.5 };
+
+// A Player-like record carrying only the fields the king helpers read.
+function player(name, x, z, dead = false) {
+ return { name, x, y: 0, z, dead };
+}
+
+// Build a WalkRoom instance without the Colyseus constructor, wiring only the
+// state + broadcast surface the king helpers touch. `broadcasts` captures
+// outgoing room messages so tests can assert what every client receives.
+function makeRoom() {
+ const room = Object.create(WalkRoom.prototype);
+ room.state = { players: 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 });
+ room._king = {
+ phase: 'idle', roundId: 0, startedAt: 0, endsAt: 0, nextAt: 0,
+ lastTickAt: 0, scores: new Map(), kingId: null, winner: null,
+ };
+ return room;
+}
+
+function seat(room, id, name, x, z, dead = false) {
+ room.state.players.set(id, player(name, x, z, dead));
+ room.clients.push({ sessionId: id });
+}
+
+// Place a player at the zone centre / well outside it for occupancy tests.
+const atTotem = (room, id, name) => seat(room, id, name, ZONE.x, ZONE.z);
+const farAway = (room, id, name) => seat(room, id, name, ZONE.x + 50, ZONE.z + 50);
+
+describe('WalkRoom King of the Totem (R07)', () => {
+ let room;
+ beforeEach(() => { room = makeRoom(); });
+
+ it('counts only live players inside the zone as occupants', () => {
+ atTotem(room, 'a', 'Alice');
+ farAway(room, 'b', 'Bob');
+ seat(room, 'c', 'Cara', ZONE.x, ZONE.z, true); // dead — can't hold the zone
+ // Exactly on the radius edge counts as inside; just outside does not.
+ seat(room, 'd', 'Dee', ZONE.x + ZONE.r, ZONE.z);
+ seat(room, 'e', 'Eve', ZONE.x + ZONE.r + 0.5, ZONE.z);
+
+ const occ = room._kingOccupants();
+ expect(occ.sort()).toEqual(['a', 'd']);
+ });
+
+ it('awards points only to a SOLE occupant; contested pays nobody', () => {
+ atTotem(room, 'a', 'Alice');
+ farAway(room, 'b', 'Bob');
+ room._startKingRound();
+ expect(room._king.phase).toBe('active');
+
+ // Rewind lastTick 1s so a's solo hold earns ~1s of points.
+ room._king.lastTickAt = Date.now() - 1000;
+ room._kingTick();
+ expect(room._king.scores.get('a')).toBeGreaterThan(0);
+ expect(room._king.scores.get('b') || 0).toBe(0);
+ expect(room._king.kingId).toBe('a');
+
+ // Bob steps onto the totem — now contested, so the next second pays no one.
+ const before = room._king.scores.get('a');
+ room.state.players.get('b').x = ZONE.x; room.state.players.get('b').z = ZONE.z;
+ room._king.lastTickAt = Date.now() - 1000;
+ room._kingTick();
+ expect(room._king.scores.get('a')).toBe(before); // frozen while contested
+ expect(room._king.kingId).toBeNull();
+ });
+
+ it('never lets a player outside the zone score', () => {
+ farAway(room, 'a', 'Alice');
+ room._startKingRound();
+ room._king.lastTickAt = Date.now() - 1000;
+ room._kingTick();
+ expect(room._king.scores.get('a')).toBe(0);
+ expect(room._king.kingId).toBeNull();
+ });
+
+ it('ends the round on time and crowns the top present player', () => {
+ atTotem(room, 'a', 'Alice');
+ farAway(room, 'b', 'Bob');
+ room._startKingRound();
+ room._king.scores.set('a', 120);
+ room._king.scores.set('b', 30);
+ // Force the clock past the round end. lastTick = now so the final beat adds ~0
+ // (a is still the sole occupant) and the asserted total stays exactly 120.
+ room._king.endsAt = Date.now() - 1;
+ room._king.lastTickAt = Date.now();
+ room._kingTick();
+
+ expect(room._king.phase).toBe('intermission');
+ expect(room._king.winner).toEqual({ id: 'a', name: 'Alice', score: 120 });
+ expect(room._king.kingId).toBeNull();
+ const end = room.broadcasts.find((b) => b.type === 'game:king' && b.msg.event === 'end');
+ expect(end).toBeTruthy();
+ expect(end.msg.winner.id).toBe('a');
+ });
+
+ it('declares no winner when nobody scored', () => {
+ atTotem(room, 'a', 'Alice');
+ room._startKingRound(); // everyone starts at 0
+ room._king.endsAt = Date.now() - 1;
+ room._endKingRound();
+ expect(room._king.winner).toBeNull();
+ const end = room.broadcasts.find((b) => b.msg?.event === 'end');
+ expect(end.msg.winner).toBeNull();
+ });
+
+ it('starts a round from idle once a player is present, and the scoreboard sorts high→low capped at 8', () => {
+ for (let i = 0; i < 10; i++) atTotem(room, `p${i}`, `P${i}`);
+ room._kingTick(); // idle → active
+ expect(room._king.phase).toBe('active');
+
+ for (let i = 0; i < 10; i++) room._king.scores.set(`p${i}`, i * 5);
+ const rows = room._kingScoreRows();
+ expect(rows).toHaveLength(8);
+ expect(rows[0].id).toBe('p9'); // highest score first
+ const scores = rows.map((r) => r.score);
+ expect(scores).toEqual([...scores].sort((a, b) => b - a));
+ });
+
+ it('does not award a king who left mid-round (handled by score cleanup)', () => {
+ atTotem(room, 'a', 'Alice');
+ room._startKingRound();
+ room._king.scores.set('a', 200);
+ room._king.kingId = 'a';
+ // Simulate onLeave's king cleanup: drop their score + demote.
+ room.state.players.delete('a');
+ room._king.scores.delete('a');
+ room._king.kingId = null;
+ room._king.endsAt = Date.now() - 1;
+ room._endKingRound();
+ expect(room._king.winner).toBeNull(); // the departed leader can't win
+ });
+
+ it('intermission rolls into the next round when players remain', () => {
+ atTotem(room, 'a', 'Alice');
+ room._startKingRound();
+ const firstRound = room._king.roundId;
+ room._endKingRound();
+ expect(room._king.phase).toBe('intermission');
+ room._king.nextAt = Date.now() - 1; // intermission elapsed
+ room._kingTick();
+ expect(room._king.phase).toBe('active');
+ expect(room._king.roundId).toBe(firstRound + 1);
+ });
+
+ it('intermission drops back to idle when the room empties', () => {
+ atTotem(room, 'a', 'Alice');
+ room._startKingRound();
+ room._endKingRound();
+ room.state.players.clear(); // everyone left
+ room._king.nextAt = Date.now() - 1;
+ room._kingTick();
+ expect(room._king.phase).toBe('idle');
+ });
+});
diff --git a/workers/agora-citizens/Dockerfile b/workers/agora-citizens/Dockerfile
new file mode 100644
index 000000000..db8cad8aa
--- /dev/null
+++ b/workers/agora-citizens/Dockerfile
@@ -0,0 +1,35 @@
+# agora-citizens — the Agora life engine (long-lived Node worker).
+#
+# Build from the REPO ROOT (it imports the @three-ws/solana-agent workspace dep,
+# which ships as TS and must be compiled to dist/ here):
+#
+# docker build -f workers/agora-citizens/Dockerfile -t agora-citizens .
+# docker run --env-file .env agora-citizens
+#
+# Cloud Run target: it's a background daemon (the daily loop), but it binds a
+# tiny health endpoint on $PORT so Cloud Run's startup probe passes. Deploy with
+# --no-cpu-throttling and --min-instances=1 so the loop keeps ticking between
+# probes. See cloudbuild.yaml.
+
+FROM node:24-slim
+
+WORKDIR /app
+
+# Install root deps first for layer caching. .npmrc carries legacy-peer-deps.
+COPY .npmrc package.json package-lock.json* ./
+RUN npm ci --ignore-scripts || npm install --ignore-scripts
+
+# The Solana agent SDK is a file: dependency that ships as TypeScript — install
+# its own devDeps and compile dist/ so the worker can import @three-ws/solana-agent.
+COPY solana-agent-sdk ./solana-agent-sdk
+RUN cd solana-agent-sdk && (npm ci --ignore-scripts || npm install --ignore-scripts) && npm run build
+
+# Worker source (imports only its own files + @three-ws/solana-agent + node deps).
+COPY workers/agora-citizens ./workers/agora-citizens
+
+RUN npm prune --omit=dev --ignore-scripts || true
+
+ENV NODE_ENV=production \
+ AGORA_CLUSTER=devnet
+
+CMD ["node", "workers/agora-citizens/index.js"]
diff --git a/workers/agora-citizens/README.md b/workers/agora-citizens/README.md
new file mode 100644
index 000000000..ac1743cc2
--- /dev/null
+++ b/workers/agora-citizens/README.md
@@ -0,0 +1,119 @@
+# agora-citizens — the Agora life engine
+
+The heartbeat that makes [Agora](../../docs/agora.md) *alive*. N real agents,
+registered on **AgenC** (the Solana coordination protocol by Tetsuo Corp,
+devnet), run the **daily loop** on their own jittered cadence:
+
+```
+IDLE → SEEK (read the board) → CLAIM (on-chain) → WORK (real Fetcher call)
+ → PROVE (proofHash + completeTask) → EARN → IDLE
+```
+
+Every transition is a **real on-chain action** with a tx signature, projected
+into `agora_citizens` / `agora_activity` and the shared `feed:events` ticker.
+On-chain is the source of truth; the `agora_*` tables are a projection that never
+invents an economic fact. This worker ships **one** profession end-to-end —
+**Fetcher** (calls a live HTTP/x402 service and proves the result). Sculptor,
+Scribe, Verifier and the rest arrive in Task 04.
+
+It mirrors the structure of [`workers/agent-mm`](../agent-mm) and generalizes the
+proven [`examples/agenc-task-roundtrip`](../../examples/agenc-task-roundtrip)
+(register → claim → complete with a real proof, keypair caching + airdrop
+backoff).
+
+## How a citizen works
+
+- **Identity.** Each citizen's canonical AgenC `agentId` is derived via the
+ identity bridge (`getCanonicalThreewsAgenCId`) from its identity proofs —
+ composite > erc8004 > mpl-core > handle. No new namespace is invented. Seeded
+ from **real platform agents** (`agent_identities`) where possible; the roster
+ fills any shortfall with standalone agent citizens (still real on-chain
+ agents). Humans are never invented here — they join via wallet-auth in Task 08.
+- **Signing.** Each citizen (and the work dispatcher) keeps a stable devnet
+ keypair under `.cache/` (gitignored — never commit a secret key), funded by the
+ faucet with shrinking-chunk backoff.
+- **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. The dispatcher is
+ devnet plumbing (native-SOL rewards), **not** a projected citizen and **not**
+ the Task-03 bounty product. Disable with `AGORA_DISPATCH_TASKS=0`.
+- **Real work.** A Fetcher calls a live service (the AgenC↔x402 bridge by
+ default, or a bazaar resource) and binds the response into
+ `proofHash = sha256(canonical(result))` — re-derivable by a Verifier.
+- **Currency.** Devnet settles in **native SOL** (synthetic plumbing — never
+ another real token). On mainnet the reward label is **$THREE**, the only coin
+ Agora promotes. Mainnet is out of scope for this worker.
+
+## Run it
+
+```bash
+cd workers/agora-citizens
+
+# 1. Plan only — read the board + derive identities, sign nothing, write nothing.
+AGORA_DRY_RUN=1 node index.js
+
+# 2. One tick per citizen against devnet (funded keypairs), then exit.
+AGORA_ONCE=1 node index.js
+
+# 3. Run the fleet continuously.
+node index.js
+```
+
+> The `@three-ws/solana-agent` SDK ships as TypeScript and must be built once
+> (`cd ../../solana-agent-sdk && npm run build`) before a real run — the Docker
+> image does this automatically. In constrained sandboxes `tsup` can OOM; it
+> builds in CI / Cloud Build / Vercel.
+
+Then inspect the projection:
+
+```bash
+curl -s "$AGORA_API_BASE/api/agora/pulse"
+curl -s "$AGORA_API_BASE/api/agora/citizens"
+curl -s "$AGORA_API_BASE/api/agora/passport?agentId=<hex>"
+```
+
+Confirm tx signatures on <https://explorer.solana.com/?cluster=devnet>.
+
+## Environment
+
+| Var | Required | Default | Purpose |
+|---|---|---|---|
+| `DATABASE_URL` | yes (non-dry) | — | Neon Postgres — the projection sink |
+| `UPSTASH_REDIS_REST_URL` / `_TOKEN` | no | — | Shared `feed:events` ticker bus |
+| `AGENC_DEVNET_RPC_URL` | no | public devnet | Private RPC (dodges faucet limits) |
+| `AGORA_CLUSTER` | no | `devnet` | `devnet` only for this worker |
+| `AGORA_MAX_CITIZENS` | no | `4` | Fleet size cap (faucet-friendly) |
+| `AGORA_MIN_CITIZENS` | no | `3` | Floor when seeding finds too few agents |
+| `AGORA_TICK_MS` / `AGORA_TICK_JITTER_MS` | no | `45000` / `20000` | Per-citizen loop cadence ± jitter |
+| `AGORA_DISPATCH_TASKS` | no | `1` (devnet) | Internal devnet work supply on/off |
+| `AGORA_MIN_OPEN_TASKS` / `AGORA_MAX_OPEN_TASKS` | no | `3` / `8` | Dispatcher open-task pool bounds |
+| `AGORA_TASK_REWARD_LAMPORTS` | no | `1000000` | Per-task devnet reward (0.001 SOL) |
+| `AGORA_API_BASE` | no | `https://three.ws` | Board + bridge read host |
+| `AGORA_DRY_RUN` | no | `0` | Plan only — no signing, no writes |
+| `AGORA_ONCE` | no | `0` | One tick per citizen, then exit |
+| `PORT` | no | — | Bind a health endpoint (Cloud Run) |
+
+## Scale the fleet
+
+Raise `AGORA_MAX_CITIZENS` (each is a real AgenC agent needing devnet SOL — a
+private RPC with a generous faucet, or pre-funded `.cache/` keypairs, is strongly
+recommended past a handful). Pace it with `AGORA_TICK_MS` so the fleet doesn't
+stampede the faucet/RPC.
+
+## Resilience
+
+- Every on-chain call is wrapped in bounded exponential backoff; a single
+ citizen's failure (bad RPC, lost claim race, faucet starvation) is caught and
+ never halts the others.
+- Re-running reconciles from on-chain state and **does not double-project**: the
+ `agora_activity_tx_uniq` index makes each on-chain action project at most once.
+- Graceful `SIGINT`/`SIGTERM` drain lets an in-flight tick land its writes.
+
+## Deploy
+
+```bash
+gcloud builds submit --config workers/agora-citizens/cloudbuild.yaml .
+```
+
+Cloud Run service, `--no-cpu-throttling --min-instances=1` so the loop keeps
+ticking. Secrets via Secret Manager (see `cloudbuild.yaml`).
diff --git a/workers/agora-citizens/cloudbuild.yaml b/workers/agora-citizens/cloudbuild.yaml
new file mode 100644
index 000000000..3ee51a6d5
--- /dev/null
+++ b/workers/agora-citizens/cloudbuild.yaml
@@ -0,0 +1,64 @@
+# Cloud Build → Cloud Run for the Agora life engine (workers/agora-citizens).
+#
+# Background daemon: it runs the daily loop continuously and binds a tiny health
+# endpoint on $PORT so the startup probe passes. Deployed with --no-cpu-throttling
+# and --min-instances=1 so the loop keeps ticking between probes. Build context is
+# the REPO ROOT (the Dockerfile compiles the @three-ws/solana-agent SDK).
+#
+# Secrets (Secret Manager): DATABASE_URL, UPSTASH_REDIS_REST_URL,
+# UPSTASH_REDIS_REST_TOKEN, and optionally AGENC_DEVNET_RPC_URL (a private devnet
+# RPC to dodge the public faucet rate limit).
+#
+# gcloud builds submit --config workers/agora-citizens/cloudbuild.yaml .
+
+substitutions:
+ _REGION: us-central1
+ _SERVICE: agora-citizens
+ _REPO: agora-citizens
+ _MIN_INSTANCES: "1"
+ _MAX_INSTANCES: "1"
+ _MAX_CITIZENS: "4"
+
+steps:
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ args:
+ - build
+ - --file
+ - workers/agora-citizens/Dockerfile
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker:$SHORT_SHA
+ - --region=${_REGION}
+ - --platform=managed
+ - --no-cpu-throttling
+ - --cpu=1
+ - --memory=1Gi
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --no-allow-unauthenticated
+ - --set-env-vars=AGORA_CLUSTER=devnet,AGORA_MAX_CITIZENS=${_MAX_CITIZENS},AGORA_DISPATCH_TASKS=1
+ - --set-secrets=DATABASE_URL=agora-database-url:latest,UPSTASH_REDIS_REST_URL=upstash-redis-rest-url:latest,UPSTASH_REDIS_REST_TOKEN=upstash-redis-rest-token:latest,AGENC_DEVNET_RPC_URL=agenc-devnet-rpc-url:latest
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/worker:$SHORT_SHA
diff --git a/workers/agora-citizens/demand.js b/workers/agora-citizens/demand.js
new file mode 100644
index 000000000..e5f2a04f3
--- /dev/null
+++ b/workers/agora-citizens/demand.js
@@ -0,0 +1,175 @@
+// agora-citizens — the demand generator (Task 03). This is the SPEND node of the
+// daily loop made real: a patron citizen with a budget posts bounties on an
+// interval, and any citizen mid-WORK that needs a capability it lacks hires a
+// sub-agent. Both pay out of a REAL on-chain balance, so when a citizen runs out
+// of funds it stops posting — honest scarcity, never an infinite tap.
+//
+// This module is the bridge between policy.js (pure decisions) and post.js (real
+// escrowed bounties). The engine calls it at the SPEND node; it reads live
+// balances, applies the policy, and — only when the policy says go — posts.
+
+import { PublicKey } from '@solana/web3.js';
+import { decidePatronPost, decideHire } from './policy.js';
+import { postBounty } from './post.js';
+import { log } from './log.js';
+
+// Fee/rent reserve never spent on rewards (devnet lamports). A claim/complete
+// pays fees and AgenC locks rent for the task account; keep headroom so posting a
+// bounty can't strand a citizen unable to pay for its own work.
+const FEE_HEADROOM_LAMPORTS = 12_000_000n; // 0.012 SOL
+
+// Mainnet spend cap (Task 03 guardrail: escrow is real money). Cumulative $THREE
+// atomic this process may escrow across all posts; 0/unset blocks mainnet posting
+// entirely. Devnet ignores the cap (synthetic SOL).
+function mainnetSpendCapAtomic() {
+ const raw = (process.env.AGORA_MAINNET_SPEND_CAP_ATOMIC || '').trim();
+ if (!raw) return 0n;
+ try {
+ return BigInt(raw);
+ } catch {
+ return 0n;
+ }
+}
+
+let _spentThisRunAtomic = 0n; // mainnet only — cumulative escrow posted this process
+
+/** Spendable reward balance for a poster, in the cluster's reward unit (atomic). */
+async function spendableBalance(cfg, connection, walletPubkey) {
+ if (cfg.cluster === 'mainnet') {
+ const tokenAccount = (process.env.AGORA_THREE_TOKEN_ACCOUNT || '').trim();
+ if (!tokenAccount) return 0n;
+ try {
+ const bal = await connection.getTokenAccountBalance(new PublicKey(tokenAccount));
+ return BigInt(bal?.value?.amount ?? '0');
+ } catch (err) {
+ log.warn('token balance read failed', { err: err?.message });
+ return 0n;
+ }
+ }
+ // devnet — native SOL (lamports)
+ try {
+ return BigInt(await connection.getBalance(walletPubkey));
+ } catch (err) {
+ log.warn('balance read failed', { err: err?.message });
+ return 0n;
+ }
+}
+
+// Headroom is only meaningful for the native-SOL devnet path (reward unit ==
+// fee unit). On mainnet the reward is $THREE and fees are paid in SOL from a
+// different balance, so no $THREE headroom is withheld.
+function headroomFor(cfg) {
+ return cfg.cluster === 'mainnet' ? 0n : FEE_HEADROOM_LAMPORTS;
+}
+
+// Enforce the mainnet escrow spend cap. Returns true if this reward is allowed.
+function withinSpendCap(cfg, rewardAtomic) {
+ if (cfg.cluster !== 'mainnet') return true;
+ const cap = mainnetSpendCapAtomic();
+ if (cap <= 0n) {
+ log.warn('mainnet post blocked — set AGORA_MAINNET_SPEND_CAP_ATOMIC to enable $THREE escrow');
+ return false;
+ }
+ if (_spentThisRunAtomic + BigInt(rewardAtomic) > cap) {
+ log.warn('mainnet spend cap reached', { cap: cap.toString(), spent: _spentThisRunAtomic.toString() });
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Patron demand: maybe post a bounty this tick.
+ *
+ * @param {object} args
+ * @param {object} args.cfg, args.store
+ * @param {object} args.citizen poster citizen row (needs .patron config, .id, .agentIdHex, .displayName)
+ * @param {object} args.client poster's signer-bound AgenC client
+ * @param {PublicKey} args.wallet poster's wallet pubkey (for the balance read)
+ * @param {number} args.postedCount posts so far (tier rotation)
+ * @param {number} args.lastPostAt epoch ms of last post (interval guard)
+ * @returns {object|null} the post result, or null if the policy held / it's not a patron
+ */
+export async function maybePatronPost({ cfg, store, citizen, client, wallet, postedCount, lastPostAt }) {
+ if (!citizen?.patron) return null;
+ const balanceAtomic = await spendableBalance(cfg, client.connection, wallet);
+ const decision = decidePatronPost({
+ citizen,
+ now: Date.now(),
+ lastPostAt: lastPostAt || 0,
+ balanceAtomic,
+ headroomAtomic: headroomFor(cfg),
+ postedCount: postedCount || 0,
+ });
+ if (!decision.post) {
+ if (decision.reason === 'insufficient_funds') {
+ log.loop('patron out of budget — holding', { citizen: citizen.displayName });
+ }
+ return null;
+ }
+ if (!withinSpendCap(cfg, decision.plan.rewardAtomic)) return null;
+
+ if (cfg.dryRun) {
+ log.loop('[dry] would post bounty', { citizen: citizen.displayName, plan: planLog(decision.plan) });
+ return null;
+ }
+
+ const result = await postBounty({ cfg, store, client, poster: citizen, plan: decision.plan });
+ if (cfg.cluster === 'mainnet') _spentThisRunAtomic += BigInt(decision.plan.rewardAtomic);
+ log.info('bounty posted', { citizen: citizen.displayName, taskPda: result.taskPda, reward: result.rewardLabel, tx: result.txSignature });
+ return result;
+}
+
+/**
+ * Sub-task hiring: a worker mid-WORK hires a sub-agent for a capability it lacks
+ * (true agent-to-agent hiring). Pays from the worker's own balance.
+ *
+ * @param {object} args.parent { taskPda, label } the parent job being worked
+ * @param {string} args.neededProfession
+ * @param {bigint} args.subRewardAtomic
+ * @returns {object|null} the hire post result, or null if held
+ */
+export async function maybeHire({ cfg, store, citizen, client, wallet, parent, neededProfession, subRewardAtomic }) {
+ const balanceAtomic = await spendableBalance(cfg, client.connection, wallet);
+ const decision = decideHire({
+ neededProfession,
+ balanceAtomic,
+ subRewardAtomic,
+ headroomAtomic: headroomFor(cfg),
+ });
+ if (!decision.hire) {
+ log.loop('cannot hire sub-agent — holding', { citizen: citizen.displayName, reason: decision.reason });
+ return null;
+ }
+ if (!withinSpendCap(cfg, decision.plan.rewardAtomic)) return null;
+
+ if (cfg.dryRun) {
+ log.loop('[dry] would hire sub-agent', { citizen: citizen.displayName, needs: neededProfession });
+ return null;
+ }
+
+ const result = await postBounty({
+ cfg,
+ store,
+ client,
+ poster: citizen,
+ plan: decision.plan,
+ hire: { parentTaskPda: parent?.taskPda || null, parentLabel: parent?.label || null },
+ });
+ if (cfg.cluster === 'mainnet') _spentThisRunAtomic += BigInt(decision.plan.rewardAtomic);
+ log.info('sub-agent hired', { citizen: citizen.displayName, needs: neededProfession, taskPda: result.taskPda, tx: result.txSignature });
+ return result;
+}
+
+function planLog(plan) {
+ return {
+ profession: plan.profession,
+ rewardAtomic: String(plan.rewardAtomic),
+ minReputation: plan.minReputation,
+ tier: plan.tier,
+ };
+}
+
+// Test/ops hook — reset the per-process mainnet spend tracker.
+export function _resetSpendTracker() {
+ _spentThisRunAtomic = 0n;
+}
diff --git a/workers/agora-citizens/engine.js b/workers/agora-citizens/engine.js
new file mode 100644
index 000000000..7ef2d56a0
--- /dev/null
+++ b/workers/agora-citizens/engine.js
@@ -0,0 +1,544 @@
+// agora-citizens — the daily loop. The heartbeat that makes Agora alive: each
+// citizen, on its own jittered cadence, runs
+//
+// IDLE → SEEK (read the board) → CLAIM (on-chain) → WORK (real Fetcher call)
+// → PROVE (proofHash + completeTask) → EARN → IDLE
+//
+// Every transition is a REAL on-chain action with a tx signature, projected into
+// agora_citizens / agora_activity and the shared feed. On-chain is the source of
+// truth; we only ever project what actually happened. A single citizen's failure
+// is caught and never halts the fleet.
+//
+// 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. The dispatcher is infra
+// (native-SOL devnet plumbing), not a projected citizen and not the Task-03
+// bounty product.
+
+import { LAMPORTS_PER_SOL } from '@solana/web3.js';
+import { log } from './log.js';
+import { buildRoster, professionBits, capabilitiesSatisfy, PROFESSIONS } from './roster.js';
+import { loadOrCreateKeypair, ensureBalance } from './keypair.js';
+import {
+ makeReadClient,
+ makeSignerClient,
+ deriveIdentity,
+ ensureRegistered,
+ getAgent,
+ listCreatorTasks,
+ createTask,
+ claimTask,
+ completeTask,
+ generateTaskId,
+ withRetry,
+ TASK_STATE,
+} from './agenc.js';
+import { runFetcher, defaultTarget } from './work/fetcher.js';
+
+const FETCHER_BITS = professionBits(['fetcher']); // 1n
+const BOARD_TTL_MS = 60_000;
+const WORK_SUPPLY_TTL_MS = 30_000;
+
+function explorerTx(sig, cluster) {
+ return `https://explorer.solana.com/tx/${sig}${cluster === 'devnet' ? '?cluster=devnet' : ''}`;
+}
+function solStr(lamports) {
+ return `${(Number(lamports) / LAMPORTS_PER_SOL).toFixed(3)} SOL`;
+}
+function hostOf(url) {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+function wander(home) {
+ // Small deterministic-ish drift around home so the world reads as alive
+ // without inventing motion. Bounded ±3 units.
+ const jitter = () => Math.round((Math.random() * 6 - 3) * 100) / 100;
+ return { x: home.x + jitter(), z: home.z + jitter() };
+}
+
+// Reward shape for a completed job. Devnet plumbing settles in native SOL (never
+// another real token); mainnet would settle in $THREE (out of scope here).
+function rewardShape(cfg, lamports) {
+ if (cfg.cluster === 'mainnet') {
+ return { mint: '$THREE', label: `${lamports} $THREE`, atomic: lamports };
+ }
+ return { mint: null, label: `${solStr(lamports)} · devnet`, atomic: lamports };
+}
+
+// ── Fleet registration ───────────────────────────────────────────────────────
+
+async function setupDispatcher(ctx) {
+ if (!ctx.cfg.dispatchTasks) return null;
+ const cfg = ctx.cfg;
+ const signer = await loadOrCreateKeypair('agora-dispatcher');
+ await ensureBalance(ctx.readClient.connection, signer, cfg, 'dispatcher');
+ const ident = await deriveIdentity({ handle: 'agora-dispatcher' });
+ const client = await makeSignerClient(cfg, signer);
+ const reg = await ensureRegistered(
+ client,
+ ident.agentIdHex,
+ {
+ capabilities: 0n, // the dispatcher posts work; it does none itself
+ endpoint: `${cfg.apiBase}/agora/dispatcher`,
+ metadataUri: ident.metadataUri,
+ stakeLamports: cfg.stakeLamports,
+ },
+ cfg,
+ );
+ log.info('dispatcher ready', {
+ pubkey: signer.publicKey.toBase58(),
+ agentPda: reg.agentPda.toBase58(),
+ existed: reg.existed,
+ tx: reg.txSignature ? explorerTx(reg.txSignature, cfg.cluster) : null,
+ });
+ return {
+ signer,
+ client,
+ agentIdHex: ident.agentIdHex,
+ agentPda: reg.agentPda,
+ pubkey: signer.publicKey,
+ };
+}
+
+async function registerCitizen(ctx, spec) {
+ const cfg = ctx.cfg;
+ const signer = await loadOrCreateKeypair(spec.key);
+ await ensureBalance(ctx.readClient.connection, signer, cfg, spec.key);
+
+ const ident = await deriveIdentity(spec.identityRef);
+ const client = await makeSignerClient(cfg, signer);
+ const reg = await ensureRegistered(
+ client,
+ ident.agentIdHex,
+ {
+ capabilities: spec.professionBits,
+ endpoint: `${cfg.apiBase}/agora/citizens/${ident.agentIdHex}`,
+ metadataUri: ident.metadataUri,
+ stakeLamports: cfg.stakeLamports,
+ },
+ cfg,
+ );
+
+ const reputation = reg.agent?.reputation ?? 0;
+ const stake = reg.agent?.stakeAmount != null ? reg.agent.stakeAmount : cfg.stakeLamports;
+
+ const citizenId = await ctx.store.upsertCitizen(spec, {
+ agentIdHex: ident.agentIdHex,
+ agentPda: reg.agentPda.toBase58(),
+ capabilityBits: spec.professionBits,
+ identitySource: ident.source,
+ identityLabel: ident.label,
+ reputation,
+ stakeLamports: stake,
+ status: 'idle',
+ });
+
+ // Project the registration once. A fresh register carries a tx (idempotent on
+ // it); a reconciled-existing agent has no new tx, so guard on existence.
+ const already = await ctx.store.activityExists(citizenId, 'registered', reg.txSignature);
+ if (!already) {
+ await ctx.store.appendActivity({
+ citizenId,
+ kind: 'registered',
+ profession: spec.profession,
+ txSignature: reg.txSignature,
+ narrative: `${spec.displayName} registered with AgenC as a ${capLabel(spec.profession)} (reputation ${reputation}).`,
+ repAfter: reputation,
+ worldX: spec.home.x,
+ worldZ: spec.home.z,
+ meta: { agentPda: reg.agentPda.toBase58(), identitySource: ident.source, existed: reg.existed },
+ });
+ await ctx.store.publishFeed({
+ type: 'agora-registered',
+ actor: spec.displayName,
+ citizenId,
+ agentPda: reg.agentPda.toBase58(),
+ profession: spec.profession,
+ narrative: `${spec.displayName} joined Agora as a ${capLabel(spec.profession)}.`,
+ });
+ }
+
+ log.info('citizen registered', {
+ key: spec.key,
+ name: spec.displayName,
+ agentPda: reg.agentPda.toBase58(),
+ existed: reg.existed,
+ reputation,
+ tx: reg.txSignature ? explorerTx(reg.txSignature, cfg.cluster) : null,
+ });
+
+ return {
+ spec,
+ id: citizenId,
+ agentIdHex: ident.agentIdHex,
+ agentPda: reg.agentPda,
+ pubkey: signer.publicKey.toBase58(),
+ signer,
+ client,
+ capabilityBits: spec.professionBits,
+ reputation,
+ claimed: new Set(),
+ home: spec.home,
+ busy: false,
+ };
+}
+
+function capLabel(key) {
+ return PROFESSIONS.find((p) => p.key === key)?.label || key || 'Citizen';
+}
+
+/**
+ * Boot the fleet: seed from real platform agents, register every citizen on
+ * AgenC (idempotent), set up the work dispatcher. Returns the runtime context.
+ * A single citizen failing to register is logged and skipped — the rest proceed.
+ */
+export async function bootFleet(cfg, store) {
+ const readClient = await makeReadClient(cfg);
+ const ctx = {
+ cfg,
+ store,
+ readClient,
+ dispatcher: null,
+ citizens: [],
+ board: { at: 0, services: [], tasks: [] },
+ lastSupplyAt: 0,
+ };
+
+ ctx.dispatcher = await setupDispatcher(ctx);
+
+ const seedAgents = await store.listSeedAgents(cfg.maxCitizens);
+ const specs = buildRoster(seedAgents, cfg);
+ log.info('roster assembled', {
+ seeded: seedAgents.length,
+ total: specs.length,
+ standalone: specs.filter((s) => !s.agentDbId).length,
+ });
+
+ for (const spec of specs) {
+ try {
+ const citizen = await registerCitizen(ctx, spec);
+ ctx.citizens.push(citizen);
+ } catch (err) {
+ log.error('citizen registration failed — skipping', { key: spec.key, err: err?.message });
+ }
+ }
+
+ if (!ctx.citizens.length) throw new Error('[agora-citizens] no citizens registered — cannot run the loop');
+ return ctx;
+}
+
+// ── Work supply (devnet dispatcher) ──────────────────────────────────────────
+
+function openTasksOf(tasks) {
+ const nowSec = Date.now() / 1000;
+ return (tasks || []).filter(
+ (t) => t.state === TASK_STATE.Open && t.currentWorkers < t.maxWorkers && Number(t.deadline) > nowSec,
+ );
+}
+
+/** Keep the dispatcher's open Fetcher-task pool topped up. Throttled per sweep. */
+export async function replenishWork(ctx, force = false) {
+ const { cfg } = ctx;
+ if (!ctx.dispatcher) return;
+ if (!force && Date.now() - ctx.lastSupplyAt < WORK_SUPPLY_TTL_MS) return;
+ ctx.lastSupplyAt = Date.now();
+
+ let tasks;
+ try {
+ tasks = await listCreatorTasks(ctx.readClient, ctx.dispatcher.pubkey);
+ } catch (err) {
+ log.warn('replenishWork: list tasks failed', { err: err?.message });
+ return;
+ }
+ const open = openTasksOf(tasks);
+ const deficit = cfg.minOpenTasks - open.length;
+ if (deficit <= 0) return;
+
+ const room = Math.max(0, cfg.maxOpenTasks - open.length);
+ const toPost = Math.min(deficit, room);
+ for (let i = 0; i < toPost; i++) {
+ try {
+ const taskId = await generateTaskId();
+ const deadline = Math.floor(Date.now() / 1000) + cfg.taskDeadlineSecs;
+ const created = await createTask(
+ ctx.dispatcher.client,
+ {
+ taskId,
+ creatorAgentId: ctx.dispatcher.agentIdHex,
+ requiredCapabilities: FETCHER_BITS,
+ description: `Agora Fetcher job — fingerprint a live bazaar service @ ${new Date().toISOString()}`,
+ rewardAmount: cfg.taskRewardLamports,
+ maxWorkers: 1,
+ deadline,
+ taskType: 'Exclusive',
+ minReputation: 0,
+ },
+ cfg,
+ );
+ log.info('dispatched task', {
+ taskPda: created.taskPda.toBase58(),
+ reward: solStr(cfg.taskRewardLamports),
+ tx: explorerTx(created.txSignature, cfg.cluster),
+ });
+ } catch (err) {
+ // A faucet-starved dispatcher can't post — log and stop trying this sweep.
+ log.warn('dispatch task failed', { err: err?.message });
+ break;
+ }
+ }
+}
+
+// ── Board read (honest "read the board" step) ────────────────────────────────
+
+async function refreshBoard(ctx) {
+ if (Date.now() - ctx.board.at < BOARD_TTL_MS) return ctx.board;
+ try {
+ const r = await fetch(`${ctx.cfg.apiBase}/api/agora/board?maxItems=20`, {
+ headers: { accept: 'application/json' },
+ });
+ if (r.ok) {
+ const body = await r.json();
+ ctx.board = { at: Date.now(), services: body.services || [], tasks: body.tasks || [] };
+ }
+ } catch (err) {
+ log.warn('board read failed', { err: err?.message });
+ }
+ return ctx.board;
+}
+
+// ── The per-citizen tick ─────────────────────────────────────────────────────
+
+async function reconcile(ctx, citizen) {
+ try {
+ const agent = await getAgent(ctx.readClient, citizen.agentPda);
+ if (agent) citizen.reputation = agent.reputation ?? citizen.reputation;
+ } catch (err) {
+ log.warn('reconcile failed (using last-known)', { name: citizen.spec.displayName, err: err?.message });
+ }
+}
+
+async function pickClaimableTask(ctx, citizen) {
+ if (!ctx.dispatcher) return null;
+ let tasks;
+ try {
+ tasks = await listCreatorTasks(ctx.readClient, ctx.dispatcher.pubkey);
+ } catch (err) {
+ log.warn('seek: list tasks failed', { name: citizen.spec.displayName, err: err?.message });
+ return null;
+ }
+ for (const t of openTasksOf(tasks)) {
+ const pda = t.taskPda?.toBase58?.() || t.taskPda;
+ // Skip tasks we already claimed in-process. Dispatcher posts Fetcher work
+ // (required ⊆ Fetcher), so a Fetcher always satisfies it; we still check.
+ if (!pda || citizen.claimed.has(pda)) continue;
+ if (!capabilitiesSatisfy(citizen.capabilityBits, FETCHER_BITS)) continue;
+ return { taskPda: t.taskPda, pda, reward: ctx.cfg.taskRewardLamports };
+ }
+ return null;
+}
+
+/**
+ * Run one daily-loop tick for a single citizen. Returns the node it ended on
+ * (for logging). Throws nothing the caller must handle — all errors are caught
+ * and surfaced as a 'failed' outcome so one citizen never stops the fleet.
+ */
+export async function tickCitizen(ctx, citizen) {
+ if (citizen.busy) return 'busy-skip';
+ citizen.busy = true;
+ const cfg = ctx.cfg;
+ const name = citizen.spec.displayName;
+ try {
+ await reconcile(ctx, citizen);
+ await refreshBoard(ctx);
+
+ // SEEK
+ const job = await pickClaimableTask(ctx, citizen);
+ if (!job) {
+ // Nothing to do — wander home, stay idle. World-only motion, no activity
+ // row (an activity with no real economic action isn't worth recording).
+ const pos = wander(citizen.home);
+ await ctx.store.setStatus(citizen.id, 'idle', pos);
+ return 'idle';
+ }
+
+ // CLAIM
+ await ctx.store.setStatus(citizen.id, 'seeking', wander(citizen.home));
+ let claim;
+ try {
+ claim = await claimTask(citizen.client, { taskPda: job.taskPda, workerAgentId: citizen.agentIdHex }, cfg);
+ } catch (err) {
+ // Lost the race / task changed state — back to idle, try again next tick.
+ log.warn('claim failed', { name, pda: job.pda, err: err?.message });
+ await ctx.store.setStatus(citizen.id, 'idle', wander(citizen.home));
+ return 'claim-failed';
+ }
+ citizen.claimed.add(job.pda);
+ await ctx.store.setStatus(citizen.id, 'busy', wander(citizen.home));
+ await ctx.store.appendActivity({
+ citizenId: citizen.id,
+ kind: 'claimed_task',
+ profession: 'fetcher',
+ taskPda: job.pda,
+ txSignature: claim.txSignature,
+ narrative: `${name} claimed a Fetcher job (${rewardShape(cfg, job.reward).label}).`,
+ repAfter: citizen.reputation,
+ });
+ await ctx.store.publishFeed({
+ type: 'agora-task-claimed',
+ actor: name,
+ citizenId: citizen.id,
+ agentPda: citizen.agentPda.toBase58(),
+ profession: 'fetcher',
+ taskPda: job.pda,
+ txSig: claim.txSignature,
+ explorerUrl: explorerTx(claim.txSignature, cfg.cluster),
+ narrative: `${name} claimed a Fetcher job.`,
+ });
+ log.info('claimed', { name, pda: job.pda, tx: explorerTx(claim.txSignature, cfg.cluster) });
+
+ // WORK — a real fetch against a live service.
+ const boardService = ctx.board.services.find((s) => typeof s.resource === 'string' && /^https?:\/\//i.test(s.resource));
+ const work = await runFetcher({
+ cfg,
+ citizen: { agentIdHex: citizen.agentIdHex, displayName: name, pubkey: citizen.pubkey },
+ job: { taskPda: job.pda, source: 'agenc', resource: boardService?.resource || defaultTarget(cfg) },
+ });
+
+ // PROVE — submit the proof on-chain.
+ const completion = await completeTask(
+ citizen.client,
+ {
+ taskPda: job.taskPda,
+ workerAgentId: citizen.agentIdHex,
+ proofHash: work.proofHashBytes,
+ resultData: work.resultData,
+ },
+ cfg,
+ );
+
+ // Re-read the chain for the new reputation (truth, not a guess).
+ const repBefore = citizen.reputation;
+ await reconcile(ctx, citizen);
+ const repAfter = citizen.reputation > repBefore ? citizen.reputation : repBefore + 1;
+ citizen.reputation = repAfter;
+
+ const reward = rewardShape(cfg, job.reward);
+ await ctx.store.appendActivity({
+ citizenId: citizen.id,
+ kind: 'completed_task',
+ profession: 'fetcher',
+ taskPda: job.pda,
+ txSignature: completion.txSignature,
+ proofHash: work.proofHashHex,
+ deliverableUrl: work.deliverableUrl,
+ narrative: `${name} fetched ${hostOf(work.target)} and proved the result; reputation ${repBefore} → ${repAfter}.`,
+ repBefore,
+ repAfter,
+ });
+ await ctx.store.appendActivity({
+ citizenId: citizen.id,
+ kind: 'earned',
+ profession: 'fetcher',
+ taskPda: job.pda,
+ txSignature: completion.txSignature,
+ amountAtomic: reward.atomic,
+ rewardMint: reward.mint,
+ rewardLabel: reward.label,
+ narrative: `${name} earned ${reward.label} for a completed Fetcher job.`,
+ repBefore,
+ repAfter,
+ });
+ await ctx.store.publishFeed({
+ type: 'agora-task-completed',
+ actor: name,
+ citizenId: citizen.id,
+ agentPda: citizen.agentPda.toBase58(),
+ profession: 'fetcher',
+ taskPda: job.pda,
+ proofHash: work.proofHashHex,
+ txSig: completion.txSignature,
+ explorerUrl: explorerTx(completion.txSignature, cfg.cluster),
+ narrative: `${name} completed a Fetcher job (rep ${repBefore} → ${repAfter}).`,
+ });
+ await ctx.store.publishFeed({
+ type: 'agora-earned',
+ actor: name,
+ citizenId: citizen.id,
+ agentPda: citizen.agentPda.toBase58(),
+ profession: 'fetcher',
+ rewardLabel: reward.label,
+ txSig: completion.txSignature,
+ explorerUrl: explorerTx(completion.txSignature, cfg.cluster),
+ narrative: `${name} earned ${reward.label}.`,
+ });
+
+ const restPos = wander(citizen.home);
+ await ctx.store.updateCitizen(citizen.id, {
+ status: 'idle',
+ reputation: repAfter,
+ earnedDelta: reward.atomic,
+ tasksCompletedDelta: 1,
+ synced: true,
+ posX: restPos.x,
+ posZ: restPos.z,
+ });
+
+ log.info('completed', {
+ name,
+ pda: job.pda,
+ proof: work.proofHashHex.slice(0, 16),
+ repAfter,
+ tx: explorerTx(completion.txSignature, cfg.cluster),
+ });
+ return 'completed';
+ } catch (err) {
+ log.error('tick failed', { name, err: err?.message });
+ try {
+ await ctx.store.setStatus(citizen.id, 'idle', wander(citizen.home));
+ } catch {
+ /* projection write best-effort */
+ }
+ return 'failed';
+ } finally {
+ citizen.busy = false;
+ }
+}
+
+// ── Dry-run planner (no signing, no DB writes) ───────────────────────────────
+
+/**
+ * Inspect the plan without touching the chain or the DB: which citizens would
+ * run, what work the board offers, what the dispatcher would post. Pure reads.
+ */
+export async function planDryRun(cfg, store) {
+ const readClient = await makeReadClient(cfg);
+ const ctx = { cfg, store, readClient, board: { at: 0, services: [], tasks: [] } };
+ const seedAgents = await store.listSeedAgents(cfg.maxCitizens);
+ const specs = buildRoster(seedAgents, cfg);
+ const plan = [];
+ for (const spec of specs) {
+ const ident = await deriveIdentity(spec.identityRef);
+ const signer = await loadOrCreateKeypair(spec.key);
+ plan.push({
+ key: spec.key,
+ name: spec.displayName,
+ profession: spec.profession,
+ capabilityBits: spec.professionBits.toString(),
+ agentIdHex: ident.agentIdHex,
+ identitySource: ident.source,
+ pubkey: signer.publicKey.toBase58(),
+ seededFrom: spec.agentDbId || null,
+ });
+ }
+ const board = await refreshBoard(ctx);
+ return {
+ cluster: cfg.cluster,
+ dispatchTasks: cfg.dispatchTasks,
+ target: defaultTarget(cfg),
+ citizens: plan,
+ board: { services: board.services.length, openTasks: board.tasks.length },
+ };
+}
diff --git a/workers/agora-citizens/index.js b/workers/agora-citizens/index.js
new file mode 100644
index 000000000..bf251f3fa
--- /dev/null
+++ b/workers/agora-citizens/index.js
@@ -0,0 +1,151 @@
+// agora-citizens — the life engine entrypoint.
+//
+// Long-lived process (NOT a Vercel cron), modeled on workers/agent-mm. It
+// registers a fleet of real AgenC agents on Solana devnet, keeps a small pool of
+// on-chain Fetcher work supplied, then runs each citizen's daily loop on its own
+// jittered cadence — every transition a real on-chain action projected into
+// agora_citizens / agora_activity and the live feed.
+//
+// AGORA_DRY_RUN=1 node index.js — print the plan, touch nothing
+// AGORA_ONCE=1 node index.js — one tick per citizen, then exit
+// node index.js — run the fleet continuously
+//
+// Scale the fleet with AGORA_MAX_CITIZENS; pace it with AGORA_TICK_MS /
+// AGORA_TICK_JITTER_MS. See README.md.
+
+import http from 'node:http';
+import { loadConfig } from './config.js';
+import { makeStore } from './store.js';
+import { bootFleet, tickCitizen, replenishWork, planDryRun } from './engine.js';
+import { log } from './log.js';
+
+const BOOT_AT = new Date().toISOString();
+
+// Cloud Run services must answer a startup/health probe on $PORT. This worker is
+// a background daemon (its real work is the loop, not HTTP), so we bind a tiny
+// liveness endpoint only when PORT is set. Locally (no PORT) nothing listens.
+let _live = { citizens: 0, dispatcher: false };
+function startHealthServer() {
+ const port = Number(process.env.PORT);
+ if (!Number.isFinite(port) || port <= 0) return;
+ http
+ .createServer((req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, worker: 'agora-citizens', bootAt: BOOT_AT, ..._live }));
+ })
+ .listen(port, () => log.info('health server listening', { port }));
+}
+
+function jitter(cfg) {
+ return cfg.tickBaseMs + Math.floor(Math.random() * (cfg.tickJitterMs + 1));
+}
+
+async function runOnce(ctx) {
+ await replenishWork(ctx, true);
+ const outcomes = {};
+ for (const citizen of ctx.citizens) {
+ const node = await tickCitizen(ctx, citizen);
+ outcomes[node] = (outcomes[node] || 0) + 1;
+ }
+ log.info('single sweep complete', { citizens: ctx.citizens.length, outcomes });
+}
+
+async function runForever(ctx) {
+ const cfg = ctx.cfg;
+ let draining = false;
+ const timers = new Set();
+
+ // Each citizen ticks on its own jittered timer so the fleet never stampedes
+ // the RPC / faucet in lockstep.
+ const schedule = (citizen) => {
+ const delay = jitter(cfg);
+ const timer = setTimeout(async () => {
+ timers.delete(timer);
+ if (draining) return;
+ try {
+ await tickCitizen(ctx, citizen);
+ } catch (err) {
+ log.error('unhandled tick error', { name: citizen.spec.displayName, err: err?.message });
+ }
+ if (!draining) schedule(citizen);
+ }, delay);
+ timers.add(timer);
+ };
+
+ // Replenish work on a steady cadence (independent of citizen ticks).
+ const supplyTimer = setInterval(() => {
+ if (!draining) replenishWork(ctx).catch((err) => log.warn('replenish error', { err: err?.message }));
+ }, Math.max(cfg.tickBaseMs, 30_000));
+
+ let heartbeatTimer = null;
+ if (cfg.heartbeatMs) {
+ const beat = () =>
+ ctx.store.heartbeat({
+ cluster: cfg.cluster,
+ bootAt: BOOT_AT,
+ citizens: ctx.citizens.length,
+ dispatcher: !!ctx.dispatcher,
+ });
+ beat();
+ heartbeatTimer = setInterval(() => {
+ if (!draining) beat();
+ }, cfg.heartbeatMs);
+ }
+
+ await replenishWork(ctx, true);
+ for (const citizen of ctx.citizens) schedule(citizen);
+ log.info('fleet running', { citizens: ctx.citizens.length, tickBaseMs: cfg.tickBaseMs, jitterMs: cfg.tickJitterMs });
+
+ const shutdown = (signal) => {
+ if (draining) return;
+ draining = true;
+ log.info('shutdown', { signal });
+ for (const t of timers) clearTimeout(t);
+ clearInterval(supplyTimer);
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
+ // Neon HTTP + Upstash REST are stateless — nothing to close. Give an
+ // in-flight tick a moment to land its projection writes.
+ setTimeout(() => process.exit(0), 2_000);
+ };
+ process.on('SIGINT', () => shutdown('SIGINT'));
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('unhandledRejection', (err) => log.error('unhandledRejection', { err: err?.message }));
+}
+
+async function main() {
+ const cfg = loadConfig();
+ const store = makeStore(cfg);
+ log.info('boot', {
+ cluster: cfg.cluster,
+ dryRun: cfg.dryRun,
+ once: cfg.once,
+ maxCitizens: cfg.maxCitizens,
+ dispatchTasks: cfg.dispatchTasks,
+ hasRedis: store.hasRedis,
+ });
+
+ if (cfg.dryRun) {
+ const plan = await planDryRun(cfg, store);
+ log.info('dry-run plan', plan);
+ // Also print a human-readable plan to stdout for quick inspection.
+ console.log(JSON.stringify({ ok: true, dryRun: true, plan }, null, 2));
+ return;
+ }
+
+ startHealthServer();
+ const ctx = await bootFleet(cfg, store);
+ _live = { citizens: ctx.citizens.length, dispatcher: !!ctx.dispatcher };
+
+ if (cfg.once) {
+ await runOnce(ctx);
+ setTimeout(() => process.exit(0), 1_000);
+ return;
+ }
+
+ await runForever(ctx);
+}
+
+main().catch((err) => {
+ log.error('fatal', { err: err?.message, stack: err?.stack });
+ process.exit(1);
+});
diff --git a/workers/agora-citizens/post.js b/workers/agora-citizens/post.js
new file mode 100644
index 000000000..ceb934a8f
--- /dev/null
+++ b/workers/agora-citizens/post.js
@@ -0,0 +1,167 @@
+// agora-citizens — the posting helper (Task 03: task supply). Turns a poster +
+// a plan into a REAL on-chain AgenC bounty with escrow locked, then projects the
+// world layer (a posted_task / hired activity + the live-ticker feed event) that
+// makes the board's AgenC lane real on-chain supply rather than an x402 mirror.
+//
+// Currency (the only coin is $THREE):
+// • devnet → reward escrowed in native SOL (synthetic plumbing — never another
+// real token). This proves the multi-hop value flow end-to-end.
+// • mainnet → reward escrowed in $THREE: rewardMint = the $THREE SPL mint and
+// creatorTokenAccount = the poster's $THREE token account. Gated
+// behind AGORA_CLUSTER=mainnet + AGORA_THREE_TOKEN_ACCOUNT and a
+// spend cap (config.js / engine SPEND node) — escrow is real money.
+//
+// Reusable by design: Task 08 (human-posted bounties) calls postBounty with a
+// human's wallet-bound client and citizen row — the helper doesn't care whether
+// the poster is an agent or a person.
+
+import { PublicKey } from '@solana/web3.js';
+import { createTask, generateTaskId } from './agenc.js';
+import { rewardLabel, postedTaskNarrative, hiredNarrative } from './narrative.js';
+
+// The one and only coin Agora denominates in on mainnet (CLAUDE.md). Devnet
+// escrow is native SOL; this mint is used only when AGORA_CLUSTER=mainnet.
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// A short, human task description encoded into AgenC's 64-byte on-chain slot
+// (encodeAgenCDescription packs longer text as sha256+prefix). Real, readable
+// work — never a placeholder.
+function describeTask({ profession, tier, parentLabel }) {
+ const verb = {
+ fetcher: 'Fetch and return a verified result from a live x402/HTTP service',
+ sculptor: 'Forge a rig-ready GLB from the supplied prompt',
+ scribe: 'Research and write a concise, sourced brief',
+ cartographer: 'Compose a small 3D scene/diorama',
+ crier: 'Produce a short voice/TTS clip',
+ appraiser: 'Return a token/market intel summary',
+ verifier: 'Re-derive a proofHash and attest pass/fail',
+ namekeeper: 'Resolve or mint a .threews.sol / ENS name',
+ }[profession] || `Complete a ${profession} job`;
+ if (parentLabel) return `${verb} (sub-task of "${parentLabel}")`.slice(0, 180);
+ return tier ? `${verb} — ${tier} tier`.slice(0, 180) : verb.slice(0, 180);
+}
+
+/**
+ * Resolve the reward shape for a plan given the cluster. Devnet → native SOL
+ * (rewardMint null). Mainnet → $THREE SPL escrow (rewardMint + creatorTokenAccount).
+ * Throws on a misconfigured mainnet so we never silently post an unfunded $THREE
+ * task or — worse — fall back to native SOL when $THREE was intended.
+ */
+export function resolveReward(cfg, rewardAtomic) {
+ if (cfg.cluster === 'mainnet') {
+ const tokenAccount = (process.env.AGORA_THREE_TOKEN_ACCOUNT || '').trim();
+ if (!tokenAccount) {
+ throw new Error('[agora-citizens] mainnet bounties require AGORA_THREE_TOKEN_ACCOUNT (the poster $THREE token account)');
+ }
+ const mint = (process.env.AGORA_THREE_MINT || THREE_MINT).trim();
+ return {
+ rewardAmount: BigInt(rewardAtomic),
+ rewardMint: new PublicKey(mint),
+ creatorTokenAccount: new PublicKey(tokenAccount),
+ mintLabel: '$THREE',
+ decimals: 6, // $THREE is a pump.fun SPL — 6 decimals
+ };
+ }
+ // devnet — native SOL escrow (9 decimals), synthetic plumbing.
+ return {
+ rewardAmount: BigInt(rewardAtomic),
+ rewardMint: null,
+ creatorTokenAccount: undefined,
+ mintLabel: null, // null reward_mint = native SOL in the projection
+ decimals: 9,
+ };
+}
+
+/**
+ * Post a real AgenC bounty and project it.
+ *
+ * @param {object} args
+ * @param {object} args.cfg loaded config (cluster, deadline, retry)
+ * @param {object} args.store projection sink (appendActivity, updateCitizen, publishFeed)
+ * @param {object} args.client signer-bound AgenC client (poster's wallet)
+ * @param {object} args.poster citizen row: { id, agentIdHex, displayName }
+ * @param {object} args.plan { profession, requiredCapabilities(bigint), rewardAtomic(bigint),
+ * minReputation, taskType, maxWorkers, tier? }
+ * @param {object} [args.hire] when present this is a sub-task hire: { parentTaskPda, parentLabel }
+ * → projects a `hired` activity instead of `posted_task`.
+ * @returns {{taskPda, taskId, txSignature, activityId, rewardLabel, rewardMint}}
+ */
+export async function postBounty({ cfg, store, client, poster, plan, hire = null }) {
+ const reward = resolveReward(cfg, plan.rewardAtomic);
+ const taskId = await generateTaskId();
+ const deadline = Math.floor(Date.now() / 1000) + cfg.taskDeadlineSecs;
+ const description = describeTask({
+ profession: plan.profession,
+ tier: plan.tier,
+ parentLabel: hire?.parentLabel,
+ });
+
+ const created = await createTask(
+ client,
+ {
+ taskId,
+ creatorAgentId: poster.agentIdHex,
+ requiredCapabilities: plan.requiredCapabilities,
+ description,
+ rewardAmount: reward.rewardAmount,
+ maxWorkers: plan.maxWorkers || 1,
+ deadline,
+ taskType: plan.taskType || 'Exclusive',
+ minReputation: plan.minReputation || 0,
+ rewardMint: reward.rewardMint,
+ creatorTokenAccount: reward.creatorTokenAccount,
+ },
+ cfg,
+ );
+
+ const taskPda = created.taskPda.toBase58();
+ const taskIdHex = Buffer.from(created.taskId).toString('hex');
+ const label = rewardLabel({ amountAtomic: reward.rewardAmount, mint: reward.mintLabel, decimals: reward.decimals });
+
+ const narrative = hire
+ ? hiredNarrative({ poster: poster.displayName, profession: plan.profession, reward: label, parentLabel: hire.parentLabel })
+ : postedTaskNarrative({ poster: poster.displayName, profession: plan.profession, reward: label, minReputation: plan.minReputation || 0 });
+
+ const activityId = await store.appendActivity({
+ citizenId: poster.id,
+ kind: hire ? 'hired' : 'posted_task',
+ taskPda,
+ taskId: taskIdHex,
+ profession: plan.profession,
+ amountAtomic: reward.rewardAmount,
+ rewardMint: reward.mintLabel,
+ rewardLabel: label,
+ txSignature: created.txSignature,
+ narrative,
+ meta: {
+ minReputation: plan.minReputation || 0,
+ taskType: plan.taskType || 'Exclusive',
+ maxWorkers: plan.maxWorkers || 1,
+ tier: plan.tier || null,
+ ...(hire ? { parentTaskPda: hire.parentTaskPda } : {}),
+ },
+ });
+
+ // Bump the poster's tasks_posted counter (real demand created).
+ await store.updateCitizen(poster.id, { tasksPostedDelta: 1 });
+
+ // Live ticker — a new bounty / hire just hit the board.
+ await store.publishFeed({
+ type: hire ? 'agora-hired' : 'agora-task-posted',
+ actor: String(poster.displayName || 'citizen').slice(0, 32),
+ taskPda,
+ profession: plan.profession,
+ rewardLabel: label || undefined,
+ minReputation: plan.minReputation || 0,
+ cluster: cfg.cluster,
+ });
+
+ return {
+ taskPda,
+ taskId: taskIdHex,
+ txSignature: created.txSignature,
+ activityId,
+ rewardLabel: label,
+ rewardMint: reward.mintLabel,
+ };
+}
diff --git a/workers/agora-citizens/reconcile.js b/workers/agora-citizens/reconcile.js
new file mode 100644
index 000000000..3f470a08c
--- /dev/null
+++ b/workers/agora-citizens/reconcile.js
@@ -0,0 +1,178 @@
+// agora-citizens — reconcile sweep (Task 03). The board renders a posted_task as
+// OPEN until a terminal projection closes it. If a task is claimed by an external
+// agent, cancelled by its creator, or lapses past its deadline, nothing in our
+// own loop would notice — so this sweep RE-READS each open posting from the chain
+// (the source of truth) and projects the matching transition. The board then
+// never shows a stale "open" task.
+//
+// It also LINKS agent-to-agent hires: a `hired` row (the hirer's sub-task) and
+// the `claimed_task`/`completed_task` row (the worker's) share the same on-chain
+// task_pda, so we backfill the hired row's counterparty_citizen_id by that join —
+// an honest link, both rows citing the same real task.
+//
+// Pure on-chain reads + idempotent projection writes. The worker owns its own
+// Neon client (it runs outside api/), exactly like store.js.
+
+import { neon } from '@neondatabase/serverless';
+import { getTask, withRetry } from './agenc.js';
+import { reconcileTransition, BOARD_TERMINAL_KINDS } from './policy.js';
+import { reconcileNarrative } from './narrative.js';
+import { log } from './log.js';
+
+// Lazy SDK import (mirrors agenc.js) so reconcile loads even before the TS SDK is
+// built — only the live sweep needs the lifecycle reader.
+let _sdk = null;
+async function sdk() {
+ if (_sdk) return _sdk;
+ _sdk = await import('@three-ws/solana-agent');
+ return _sdk;
+}
+
+// Open postings = posted_task / hired rows with no later terminal projection for
+// the same PDA. Mirrors the board's open-lane query (api/agora/[action].js) so
+// reconcile and the board agree on exactly what "open" means. BOARD_TERMINAL_KINDS
+// is bound as a Postgres text[] (= any(...)), so the two stay in lockstep.
+async function listOpenPostings(sql, cluster) {
+ return sql`
+ select a.id, a.citizen_id, a.task_pda, a.task_id, a.kind, a.profession,
+ a.reward_label, a.created_at, c.display_name as poster, c.agenc_cluster
+ from agora_activity a
+ join agora_citizens c on c.id = a.citizen_id
+ where a.kind in ('posted_task', 'hired')
+ and a.task_pda is not null
+ and coalesce(c.agenc_cluster, 'devnet') = ${cluster}
+ and a.created_at > now() - interval '14 days'
+ and not exists (
+ select 1 from agora_activity x
+ where x.task_pda = a.task_pda
+ and x.kind = any(${BOARD_TERMINAL_KINDS})
+ and x.created_at >= a.created_at
+ )
+ order by a.created_at asc
+ limit 500
+ `;
+}
+
+// Pull the terminal event's real tx signature (and actor) from the lifecycle so
+// the projected transition cites the on-chain action that closed the task.
+async function terminalTx(readClient, taskPda) {
+ try {
+ const s = await sdk();
+ const { PublicKey } = await import('@solana/web3.js');
+ const summary = await s.getAgenCTaskLifecycle(readClient, new PublicKey(taskPda));
+ const tl = summary?.timeline || [];
+ const last = tl.length ? tl[tl.length - 1] : null;
+ return last?.txSignature || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Run one reconcile pass. Returns counts for the heartbeat/log.
+ *
+ * @param {object} args
+ * @param {object} args.cfg loaded config (cluster, databaseUrl, retry)
+ * @param {object} args.store projection sink (appendActivity, publishFeed)
+ * @param {object} args.readClient a read-only AgenC client (makeReadClient)
+ */
+export async function reconcileOnce({ cfg, store, readClient }) {
+ if (!cfg.databaseUrl) {
+ log.warn('reconcile skipped — no DATABASE_URL');
+ return { checked: 0, closed: 0, linked: 0 };
+ }
+ const sql = neon(cfg.databaseUrl);
+
+ let open;
+ try {
+ open = await listOpenPostings(sql, cfg.cluster);
+ } catch (err) {
+ log.error('reconcile list failed', { err: err?.message });
+ return { checked: 0, closed: 0, linked: 0 };
+ }
+
+ let closed = 0;
+ for (const row of open) {
+ try {
+ const transition = await resolveTransition({ cfg, readClient, taskPda: row.task_pda });
+ if (!transition) continue; // still open on-chain — leave it on the board
+
+ // One terminal row per (task_pda, kind) — idempotent across sweeps even
+ // when the chain gives us no tx to dedup on (e.g. a reclaimed account).
+ const exists = await sql`
+ select 1 from agora_activity
+ where task_pda = ${row.task_pda} and kind = ${transition.kind}
+ limit 1
+ `;
+ if (exists.length) continue;
+
+ const txSignature = await terminalTx(readClient, row.task_pda);
+ const narrative = reconcileNarrative({
+ poster: row.poster,
+ profession: row.profession || 'worker',
+ verb: transition.verb,
+ });
+
+ await store.appendActivity({
+ citizenId: row.citizen_id,
+ kind: transition.kind,
+ taskPda: row.task_pda,
+ taskId: row.task_id,
+ profession: row.profession,
+ txSignature,
+ narrative,
+ meta: { reconciled: true, fromKind: row.kind },
+ });
+ closed++;
+ log.loop('reconciled task', { taskPda: row.task_pda, to: transition.kind });
+ } catch (err) {
+ log.warn('reconcile row failed', { taskPda: row.task_pda, err: err?.message });
+ }
+ }
+
+ const linked = await linkHires(sql);
+
+ if (closed || linked) log.info('reconcile sweep', { checked: open.length, closed, linked });
+ return { checked: open.length, closed, linked };
+}
+
+// Decide the transition for one task by reading its on-chain state. A missing
+// account (getTask → null) means the creator cancelled and the rent was reclaimed
+// — that's a Cancelled transition, not a phantom open task.
+async function resolveTransition({ cfg, readClient, taskPda }) {
+ const task = await withRetry(() => getTask(readClient, taskPda), cfg, 'reconcile:getTask').catch(() => undefined);
+ if (task === null) return reconcileTransition('cancelled');
+ if (task === undefined) return null; // RPC failed after retries — try again next sweep, don't fabricate
+
+ let label;
+ try {
+ const s = await sdk();
+ label = s.formatTaskState(task.state);
+ } catch {
+ label = task.state;
+ }
+ return reconcileTransition(label);
+}
+
+// Backfill the hirer↔worker link. A `hired` sub-task and the worker's
+// claim/complete row share the on-chain task_pda; join on it to set the
+// counterparty. Honest: both rows independently cite the same real task.
+async function linkHires(sql) {
+ try {
+ const res = await sql`
+ update agora_activity h
+ set counterparty_citizen_id = w.citizen_id
+ from agora_activity w
+ where h.kind = 'hired'
+ and h.counterparty_citizen_id is null
+ and w.task_pda = h.task_pda
+ and w.kind in ('claimed_task', 'completed_task')
+ and w.citizen_id <> h.citizen_id
+ returning h.id
+ `;
+ return res.length;
+ } catch (err) {
+ log.warn('hire link backfill failed', { err: err?.message });
+ return 0;
+ }
+}
diff --git a/workers/agora-citizens/work/_lib.js b/workers/agora-citizens/work/_lib.js
new file mode 100644
index 000000000..fc9cd43b5
--- /dev/null
+++ b/workers/agora-citizens/work/_lib.js
@@ -0,0 +1,228 @@
+// Shared plumbing for the Agora profession WORK modules (docs/agora.md § Professions).
+//
+// Every profession module is a pluggable unit with one job: take a claimed task
+// and produce a REAL artifact plus a proof that binds it. The proof is always
+// `sha256(canonical bytes of the deliverable)` — the exact bytes served at the
+// deliverable URL — so any Verifier (or the UI's Verify button) can re-download
+// and re-derive the identical 32-byte hash. This file is where that invariant
+// lives: one sha256, one canonical-JSON encoder, one deliverable store, one set
+// of HTTP helpers against the real three.ws API. No mocks, no placeholders.
+
+import { createHash } from 'node:crypto';
+
+// The real API origin every skill calls. Override for a local/staging deploy via
+// THREE_WS_BASE_URL; the SDK family resolves the same way (packages/*/src/http.js).
+export const BASE_URL = String(process.env.THREE_WS_BASE_URL || 'https://three.ws').replace(/\/+$/, '');
+
+// ── Proof ────────────────────────────────────────────────────────────────────
+
+/** The one true proof primitive: sha256(bytes) → 32-byte Buffer. */
+export function sha256(bytes) {
+ return createHash('sha256').update(bytes).digest();
+}
+
+/** Lowercase hex of a byte buffer (64 chars for a 32-byte proof). */
+export function toHex(buf) {
+ return Buffer.from(buf).toString('hex');
+}
+
+// Deterministic JSON encoder — keys sorted at every level — so a producer and a
+// Verifier on different machines hash byte-identical bytes for the same object.
+function stableStringify(value) {
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+ if (value && typeof value === 'object') {
+ return `{${Object.keys(value)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`)
+ .join(',')}}`;
+ }
+ return JSON.stringify(value === undefined ? null : value);
+}
+
+/** Canonical UTF-8 bytes of a JSON deliverable — what we both store AND hash. */
+export function canonicalJsonBytes(obj) {
+ return Buffer.from(stableStringify(obj), 'utf8');
+}
+
+/** A ≤64-byte on-chain pointer (resultData) — a short URL / CID, UTF-8, truncated. */
+export function pointer64(str) {
+ return Buffer.from(String(str ?? ''), 'utf8').subarray(0, 64);
+}
+
+/** Best work prompt from a task, across the board's AgenC and x402 task shapes. */
+export function taskPrompt(task) {
+ return String(task?.prompt || task?.title || task?.description || task?.resource || '').trim();
+}
+
+// ── Deliverable storage (R2) ──────────────────────────────────────────────────
+
+// Store the exact deliverable bytes in our bucket and return their public URL —
+// the verifiable supply chain's anchor. R2 is loaded lazily so the profession
+// modules import without the S3 SDK / credentials present (work-only dev runs,
+// tests). When R2 is unconfigured AND the bytes already live at a durable source
+// URL (e.g. forge's hosted GLB), we fall back to that URL: still real, still
+// re-downloadable, still hashes to the same proof. With no durable source and no
+// R2, that is a real failure — never a fabricated link.
+export async function storeDeliverable({ profession, ext, contentType, bytes, sourceUrl = null }) {
+ const digest = toHex(sha256(bytes));
+ const key = `agora/deliverables/${profession}/${digest}.${ext}`;
+ try {
+ const { putObject, publicUrl } = await import('../../../api/_lib/r2.js');
+ await putObject({ key, body: bytes, contentType });
+ return { url: publicUrl(key), key, digest, stored: true };
+ } catch (err) {
+ if (sourceUrl) return { url: sourceUrl, key: null, digest, stored: false, storeError: err?.message };
+ throw new Error(
+ `deliverable storage unavailable — configure S3_*/R2 env or supply a durable source URL (${err?.message || err})`,
+ );
+ }
+}
+
+// ── Real HTTP against the three.ws API ────────────────────────────────────────
+
+/** GET/POST a JSON endpoint; throws a typed error (with .status/.code) on non-2xx. */
+export async function httpJson(path, { method = 'GET', body, headers, query, signal } = {}) {
+ const url = new URL(path.startsWith('http') ? path : `${BASE_URL}${path}`);
+ if (query) for (const [k, v] of Object.entries(query)) if (v != null && v !== '') url.searchParams.set(k, String(v));
+ const res = await fetch(url, {
+ method,
+ headers: {
+ accept: 'application/json',
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
+ ...(headers || {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ signal,
+ });
+ const text = await res.text();
+ let data;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ data = { raw: text };
+ }
+ if (!res.ok) {
+ const err = new Error(data?.message || data?.error || `HTTP ${res.status} ${path}`);
+ err.status = res.status;
+ err.code = data?.error || `http_${res.status}`;
+ err.body = data;
+ throw err;
+ }
+ return data;
+}
+
+/** Fetch raw bytes (binary deliverables, re-downloads); throws on non-2xx. */
+export async function httpBytes(path, { method = 'GET', body, headers, signal } = {}) {
+ const url = path.startsWith('http') ? path : `${BASE_URL}${path}`;
+ const res = await fetch(url, {
+ method,
+ headers: headers || {},
+ body: body !== undefined ? (typeof body === 'string' ? body : JSON.stringify(body)) : undefined,
+ signal,
+ });
+ if (!res.ok) {
+ const peek = await res.text().catch(() => '');
+ const err = new Error(`HTTP ${res.status} ${url}: ${peek.slice(0, 200)}`);
+ err.status = res.status;
+ throw err;
+ }
+ const bytes = Buffer.from(await res.arrayBuffer());
+ return { bytes, contentType: res.headers.get('content-type'), headers: res.headers };
+}
+
+// POST /api/brain/chat streams Server-Sent Events; a deliverable is one payload,
+// so we consume the whole stream and collapse the text deltas into a single
+// reply (mirrors the brain-mcp client's protocol). Free open-weight tiers
+// (gpt-oss-120b) need no key; paid flagships read THREE_WS_API_KEY if present.
+export async function brainChat({ provider = 'gpt-oss-120b', system, messages, maxTokens, signal } = {}) {
+ const body = { provider, messages };
+ if (system) body.system = system;
+ if (Number.isFinite(maxTokens)) body.maxTokens = Math.trunc(maxTokens);
+
+ const res = await fetch(`${BASE_URL}/api/brain/chat`, {
+ method: 'POST',
+ headers: {
+ accept: 'text/event-stream',
+ 'content-type': 'application/json',
+ ...(process.env.THREE_WS_API_KEY ? { authorization: `Bearer ${process.env.THREE_WS_API_KEY}` } : {}),
+ },
+ body: JSON.stringify(body),
+ signal,
+ });
+
+ // A rejected request (unknown provider, rate limit, sign-in required) returns
+ // JSON, not SSE — surface it as a real error.
+ if (!res.ok || !res.body) {
+ const raw = await res.text().catch(() => '');
+ let data;
+ try {
+ data = raw ? JSON.parse(raw) : {};
+ } catch {
+ data = { raw };
+ }
+ const err = new Error(data?.message || data?.error || `brain HTTP ${res.status}`);
+ err.status = res.status;
+ throw err;
+ }
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let text = '';
+ let meta = null;
+ let usage = null;
+
+ const handle = (event, data) => {
+ if (!data || data === '[DONE]') return;
+ if (!event || event === 'message') {
+ try {
+ const piece = JSON.parse(data);
+ if (typeof piece === 'string') text += piece;
+ } catch {
+ /* non-JSON keepalive */
+ }
+ return;
+ }
+ if (event === 'meta') {
+ try {
+ meta = JSON.parse(data);
+ } catch {
+ /* ignore */
+ }
+ } else if (event === 'done') {
+ try {
+ usage = JSON.parse(data)?.usage ?? usage;
+ } catch {
+ /* ignore */
+ }
+ } else if (event === 'error') {
+ let message = 'brain stream error';
+ try {
+ message = JSON.parse(data)?.message || message;
+ } catch {
+ /* ignore */
+ }
+ throw new Error(message);
+ }
+ };
+
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
+ const frame = buf.slice(0, idx);
+ buf = buf.slice(idx + 2);
+ let event = null;
+ const dataLines = [];
+ for (const line of frame.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));
+ }
+ handle(event, dataLines.join('\n'));
+ }
+ }
+
+ return { text: text.trim(), meta, usage };
+}
diff --git a/workers/agora-citizens/work/appraiser.js b/workers/agora-citizens/work/appraiser.js
new file mode 100644
index 000000000..74861a4f5
--- /dev/null
+++ b/workers/agora-citizens/work/appraiser.js
@@ -0,0 +1,54 @@
+// Appraiser (bit 5) — token / market intel. Backed by @three-ws/intel over the
+// public /api/social/sentiment-pulse endpoint. Produces a stable appraisal
+// snapshot (sentiment + breakdown + sources) and proves it with sha256.
+//
+// $THREE is the coin this platform denominates in and the default subject of an
+// appraisal. A task may supply an arbitrary mint at runtime (generic, runtime-
+// supplied plumbing) — but no other coin is ever hardcoded, named, or promoted.
+
+import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64 } from './_lib.js';
+
+export const profession = { bit: 5, key: 'appraiser', label: 'Appraiser' };
+
+// The only coin this platform references. Default appraisal subject.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const mint = String(task?.mint || THREE_MINT).trim();
+
+ log(`appraiser: sentiment pulse for ${mint}`);
+ const res = await httpJson('/api/social/sentiment-pulse', { method: 'POST', body: { mint, limit: 100 } });
+ const data = res?.data || res || {};
+
+ const appraisal = {
+ kind: 'agora.appraisal.v1',
+ mint,
+ overall: data.overall ?? null,
+ breakdown: data.breakdown ?? null,
+ sources: data.sources ?? null,
+ };
+ if (appraisal.overall == null && appraisal.breakdown == null) {
+ throw new Error('appraiser: sentiment endpoint returned no signal');
+ }
+
+ const bytes = canonicalJsonBytes(appraisal);
+ const proofHash = sha256(bytes);
+ const deliverable = await storeDeliverable({
+ profession: 'appraiser',
+ ext: 'json',
+ contentType: 'application/json',
+ bytes,
+ });
+
+ const score = typeof appraisal.overall === 'object' ? JSON.stringify(appraisal.overall) : String(appraisal.overall);
+ return {
+ result: `Appraised ${mint === THREE_MINT ? '$THREE' : mint}: sentiment ${score}`,
+ proofHash,
+ deliverableUrl: deliverable.url,
+ resultData: pointer64(deliverable.url),
+ resultMeta: { mint, stored: deliverable.stored },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/cartographer.js b/workers/agora-citizens/work/cartographer.js
new file mode 100644
index 000000000..9de2b32d0
--- /dev/null
+++ b/workers/agora-citizens/work/cartographer.js
@@ -0,0 +1,40 @@
+// Cartographer (bit 3) — builds a 3D scene / diorama plan from one sentence.
+// Backed by @three-ws/scene over the public /api/diorama composer, which
+// decomposes the prompt into a placed set of single-object forge prompts. The
+// deliverable is the canonical diorama plan; the proof is sha256 of those bytes.
+
+import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64, taskPrompt } from './_lib.js';
+
+export const profession = { bit: 3, key: 'cartographer', label: 'Cartographer' };
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const prompt = taskPrompt(task);
+ if (!prompt) throw new Error('cartographer: task carries no prompt to compose');
+
+ log(`cartographer: composing diorama for "${prompt.slice(0, 80)}"`);
+ const res = await httpJson('/api/diorama', { method: 'POST', body: { action: 'compose', prompt } });
+ const diorama = res?.diorama || res?.data?.diorama || null;
+ if (!diorama || !Array.isArray(diorama.objects) || diorama.objects.length === 0) {
+ throw new Error('cartographer: composer returned no diorama plan');
+ }
+
+ const bytes = canonicalJsonBytes({ kind: 'agora.diorama.v1', prompt, diorama });
+ const proofHash = sha256(bytes);
+ const deliverable = await storeDeliverable({
+ profession: 'cartographer',
+ ext: 'json',
+ contentType: 'application/json',
+ bytes,
+ });
+
+ return {
+ result: `Composed "${diorama.title || prompt}" — ${diorama.objects.length} placed objects (${diorama.mood || 'day'})`,
+ proofHash,
+ deliverableUrl: deliverable.url,
+ resultData: pointer64(deliverable.url),
+ resultMeta: { objects: diorama.objects.length, mood: diorama.mood, stored: deliverable.stored },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/crier.js b/workers/agora-citizens/work/crier.js
new file mode 100644
index 000000000..cdb68add2
--- /dev/null
+++ b/workers/agora-citizens/work/crier.js
@@ -0,0 +1,44 @@
+// Crier (bit 4) — turns a task's text into a real spoken-audio clip. Backed by
+// @three-ws/voice over the free /api/tts/speak lane (NVIDIA Magpie TTS). The
+// deliverable is the audio bytes; the proof is sha256 of exactly those bytes.
+
+import { sha256, storeDeliverable, httpBytes, pointer64, taskPrompt } from './_lib.js';
+
+export const profession = { bit: 4, key: 'crier', label: 'Crier' };
+
+const EXT_FOR = { mp3: 'mp3', wav: 'wav', opus: 'ogg', aac: 'aac', flac: 'flac', pcm: 'pcm' };
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const text = taskPrompt(task);
+ if (!text) throw new Error('crier: task carries no text to voice');
+
+ const format = task?.format || 'mp3';
+ const voice = task?.voice || 'nova';
+ log(`crier: synthesizing ${format} voice (${voice}) for "${text.slice(0, 60)}"`);
+
+ const { bytes, contentType } = await httpBytes('/api/tts/speak', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'audio/*' },
+ body: { text, voice, format },
+ });
+ if (!bytes?.length) throw new Error('crier: tts returned 0 audio bytes');
+
+ const proofHash = sha256(bytes);
+ const deliverable = await storeDeliverable({
+ profession: 'crier',
+ ext: EXT_FOR[format] || 'audio',
+ contentType: contentType || 'audio/mpeg',
+ bytes,
+ });
+
+ return {
+ result: `Voiced a ${bytes.length.toLocaleString()}-byte ${format} clip (${voice})`,
+ proofHash,
+ deliverableUrl: deliverable.url,
+ resultData: pointer64(deliverable.url),
+ resultMeta: { bytes: bytes.length, format, voice, stored: deliverable.stored },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/fetcher.js b/workers/agora-citizens/work/fetcher.js
new file mode 100644
index 000000000..8100d1af3
--- /dev/null
+++ b/workers/agora-citizens/work/fetcher.js
@@ -0,0 +1,145 @@
+// agora-citizens — the Fetcher profession (capability bit 0).
+//
+// Real, verifiable work: a Fetcher calls a live HTTP / x402 service and returns
+// the result, binding it into a proof anyone can re-derive. This is the one
+// profession Task 02 ships end-to-end; Sculptor / Scribe / Verifier arrive in
+// Task 04.
+//
+// The proof model mirrors examples/agenc-task-roundtrip/run.mjs: we query a live
+// service, fingerprint its response deterministically, and set
+// proofHash = sha256(canonical(result)). A Verifier (Task 04) can re-query the
+// same target and recompute the identical fingerprint. resultData is a compact
+// 64-byte content pointer to the artifact.
+//
+// No fake data, no setTimeout progress — every byte comes from a real fetch.
+
+import { createHash } from 'node:crypto';
+
+const FETCH_TIMEOUT_MS = 15_000;
+const MAX_CAPTURE_BYTES = 256 * 1024; // bound memory — fingerprint, don't hoard
+
+function sha256Hex(buf) {
+ return createHash('sha256').update(buf).digest('hex');
+}
+
+async function fetchWithTimeout(url, opts = {}) {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
+ try {
+ return await fetch(url, { ...opts, signal: ctrl.signal });
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Default work target: the live three.ws AgenC ↔ x402 bridge. A deterministic,
+// always-available real resource whose fingerprint binds the bazaar state at the
+// moment of work — the same target the proven roundtrip uses.
+export function defaultTarget(cfg) {
+ return `${cfg.apiBase}/api/agenc/x402-services?maxItems=5`;
+}
+
+// Deterministic fingerprint of a fetched JSON/text body. For the bridge we
+// fingerprint the stable task-seed list so re-derivation is order-independent;
+// for any other resource we hash the raw bytes.
+function fingerprint(target, status, contentType, bodyText) {
+ let canonical = bodyText;
+ if (contentType.includes('application/json')) {
+ try {
+ const json = JSON.parse(bodyText);
+ if (Array.isArray(json?.tasks)) {
+ canonical = JSON.stringify(json.tasks.map((t) => t.taskIdSeed ?? t.resource ?? null));
+ } else {
+ canonical = JSON.stringify(json);
+ }
+ } catch {
+ // not valid JSON despite the header — hash raw text
+ }
+ }
+ return sha256Hex(Buffer.from(`${target}\n${status}\n${canonical}`, 'utf8'));
+}
+
+// Pack a compact, deterministic 64-byte content pointer for the on-chain
+// resultData slot: a CID-style sha256 reference to the artifact.
+function packResultData(proofHashHex) {
+ const pointer = `agora:fetch:cid:sha256:${proofHashHex.slice(0, 40)}`;
+ const buf = Buffer.alloc(64);
+ Buffer.from(pointer, 'utf8').copy(buf, 0);
+ return Uint8Array.from(buf);
+}
+
+/**
+ * Perform a Fetcher job and produce a re-derivable proof.
+ *
+ * @param {object} opts
+ * @param {object} opts.cfg runtime config (apiBase, etc.)
+ * @param {object} opts.citizen { agentIdHex, displayName, pubkey }
+ * @param {object} [opts.job] optional board job: { source, resource, taskPda }
+ * @returns {{ result, resultText, proofHashHex, proofHashBytes, resultData,
+ * target, fingerprint, deliverableUrl, paymentRequired, bytes }}
+ */
+export async function runFetcher({ cfg, citizen, job } = {}) {
+ // Pick a target. A board x402 service brings its own resource URL; an AgenC
+ // task (or no job) falls back to the canonical bridge target.
+ let target = defaultTarget(cfg);
+ if (job?.resource && /^https?:\/\//i.test(job.resource)) target = job.resource;
+
+ let res;
+ try {
+ res = await fetchWithTimeout(target, { headers: { accept: 'application/json, */*' } });
+ } catch (err) {
+ // A bad target must never abort the loop — fall back to the canonical
+ // bridge so the citizen still produces real, verifiable work this tick.
+ if (target !== defaultTarget(cfg)) {
+ target = defaultTarget(cfg);
+ res = await fetchWithTimeout(target, { headers: { accept: 'application/json, */*' } });
+ } else {
+ throw err;
+ }
+ }
+
+ const status = res.status;
+ const contentType = (res.headers.get('content-type') || '').toLowerCase();
+ const paymentRequired = status === 402;
+
+ // Capture the live response bytes (bounded). A 402 challenge from a paid x402
+ // service is itself a real, hashable response — we record it honestly rather
+ // than fabricating a paid result. Real USDC settlement is a mainnet money flow
+ // (out of devnet scope); the citizen's verifiable artifact is the real fetch.
+ const raw = await res.text();
+ const bodyText = raw.length > MAX_CAPTURE_BYTES ? raw.slice(0, MAX_CAPTURE_BYTES) : raw;
+ const bytes = Buffer.byteLength(bodyText, 'utf8');
+
+ const fp = fingerprint(target, status, contentType, bodyText);
+
+ const result = {
+ worker: citizen.agentIdHex,
+ workerPubkey: citizen.pubkey || null,
+ profession: 'fetcher',
+ target,
+ status,
+ contentType: contentType || null,
+ bytes,
+ fingerprint: fp,
+ paymentRequired,
+ taskPda: job?.taskPda || null,
+ completedAt: new Date().toISOString(),
+ };
+ const resultText = JSON.stringify(result);
+ const proofHashHex = sha256Hex(Buffer.from(resultText, 'utf8'));
+
+ return {
+ result,
+ resultText,
+ proofHashHex,
+ proofHashBytes: Uint8Array.from(Buffer.from(proofHashHex, 'hex')),
+ resultData: packResultData(proofHashHex),
+ target,
+ fingerprint: fp,
+ // A re-derivable pointer to the artifact: re-fetch the target and recompute
+ // the fingerprint to verify (the Verifier profession will automate this).
+ deliverableUrl: target,
+ paymentRequired,
+ bytes,
+ };
+}
diff --git a/workers/agora-citizens/work/namekeeper.js b/workers/agora-citizens/work/namekeeper.js
new file mode 100644
index 000000000..0d3834fa2
--- /dev/null
+++ b/workers/agora-citizens/work/namekeeper.js
@@ -0,0 +1,52 @@
+// Namekeeper (bit 7) — resolves on-chain names. Backed by @three-ws/names over
+// the public /api/sns (Solana) and /api/agents/ens (Ethereum) endpoints. The
+// deliverable is the canonical resolution record; the proof is sha256 of it.
+//
+// Scope: this module ships the RESOLVE capability (a real read producing a real,
+// hashable artifact). Minting `*.threews.sol` needs an authenticated, staked
+// signer and is deferred to a later task (noted in docs/agora.md) — not stubbed.
+
+import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64, taskPrompt } from './_lib.js';
+
+export const profession = { bit: 7, key: 'namekeeper', label: 'Namekeeper' };
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const name = String(task?.name || taskPrompt(task)).trim();
+ if (!name) throw new Error('namekeeper: task carries no name to resolve');
+
+ const isEns = /\.eth$/i.test(name);
+ log(`namekeeper: resolving ${name} (${isEns ? 'ENS' : 'SNS'})`);
+
+ const res = isEns
+ ? await httpJson(`/api/agents/ens/${encodeURIComponent(name.toLowerCase())}`)
+ : await httpJson('/api/sns', { query: { name } });
+ const data = res?.data || res || {};
+ const address = data.address ?? data.owner ?? data.resolvedAddress ?? null;
+
+ const record = {
+ kind: 'agora.nameresolve.v1',
+ name,
+ network: isEns ? 'ethereum' : 'solana',
+ address,
+ resolved: Boolean(address),
+ };
+ const bytes = canonicalJsonBytes(record);
+ const proofHash = sha256(bytes);
+ const deliverable = await storeDeliverable({
+ profession: 'namekeeper',
+ ext: 'json',
+ contentType: 'application/json',
+ bytes,
+ });
+
+ return {
+ result: record.resolved ? `Resolved ${name} → ${address}` : `Resolved ${name}: no owner on record`,
+ proofHash,
+ deliverableUrl: deliverable.url,
+ resultData: pointer64(deliverable.url),
+ resultMeta: { resolved: record.resolved, address, network: record.network, stored: deliverable.stored },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/scribe.js b/workers/agora-citizens/work/scribe.js
new file mode 100644
index 000000000..2e988b640
--- /dev/null
+++ b/workers/agora-citizens/work/scribe.js
@@ -0,0 +1,64 @@
+// Scribe (bit 2) — research / summarize / write via the LLM router. Produces a
+// real text deliverable and proves it with sha256(text). Backed by @three-ws/brain
+// over /api/brain/chat; the free open-weight tier (gpt-oss-120b) needs no key.
+
+import { sha256, toHex, storeDeliverable, brainChat, pointer64, taskPrompt } from './_lib.js';
+
+export const profession = { bit: 2, key: 'scribe', label: 'Scribe' };
+
+const DEFAULT_SYSTEM =
+ 'You are a Scribe in the three.ws Agora — a precise, professional writer. ' +
+ 'Deliver a complete, well-structured response to the task. No preamble, no meta-commentary, ' +
+ 'no apologies. Write the artifact itself.';
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const prompt = taskPrompt(task);
+ if (!prompt) throw new Error('scribe: task carries no prompt to write');
+
+ const provider = task?.provider || 'gpt-oss-120b';
+ log(`scribe: writing via ${provider} for "${prompt.slice(0, 80)}"`);
+
+ const { text, meta } = await brainChat({
+ provider,
+ system: task?.system || DEFAULT_SYSTEM,
+ messages: [{ role: 'user', content: prompt }],
+ maxTokens: task?.maxTokens || 1200,
+ });
+ if (!text) throw new Error('scribe: brain returned empty text');
+
+ // The deliverable bytes ARE the proof preimage.
+ const bytes = Buffer.from(text, 'utf8');
+ const proofHash = sha256(bytes);
+
+ // Store in R2 when configured; the contract also allows returning the text
+ // inline (the proof still binds the exact bytes either way).
+ let deliverableUrl;
+ let stored = false;
+ try {
+ const d = await storeDeliverable({
+ profession: 'scribe',
+ ext: 'md',
+ contentType: 'text/markdown; charset=utf-8',
+ bytes,
+ });
+ deliverableUrl = d.url;
+ stored = d.stored;
+ } catch (err) {
+ log(`scribe: R2 unavailable, returning inline (${err?.message})`);
+ }
+
+ return {
+ result: text,
+ proofHash,
+ deliverableUrl,
+ resultData: pointer64(deliverableUrl || `scribe-sha256:${toHex(proofHash).slice(0, 40)}`),
+ resultMeta: {
+ model: meta?.label || meta?.provider || provider,
+ chars: text.length,
+ stored,
+ },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/sculptor.js b/workers/agora-citizens/work/sculptor.js
new file mode 100644
index 000000000..0ee51375e
--- /dev/null
+++ b/workers/agora-citizens/work/sculptor.js
@@ -0,0 +1,67 @@
+// Sculptor (bit 1) — the headline profession: a citizen that turns a task into a
+// textured, rig-ready GLB and proves it with sha256(GLB). This is the verifiable
+// 3D supply chain — text in, a real mesh out, a hash anyone can re-derive.
+//
+// Backed by @three-ws/forge over the public, auth-free /api/forge endpoint. The
+// free lane (NVIDIA NIM / HuggingFace) produces a real GLB; if it is unavailable
+// or out of credits, forge throws and the citizen reports a real job failure —
+// never a fabricated success.
+
+import { forge } from '../../../packages/forge/src/index.js';
+import { sha256, storeDeliverable, httpBytes, pointer64, taskPrompt } from './_lib.js';
+
+export const profession = { bit: 1, key: 'sculptor', label: 'Sculptor' };
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const prompt = taskPrompt(task);
+ if (!prompt) throw new Error('sculptor: task carries no prompt to sculpt');
+
+ const tier = task?.tier || 'draft'; // free lane defaults to the fast draft tier
+ log(`sculptor: forging GLB for "${prompt.slice(0, 80)}" (tier ${tier})`);
+
+ let job;
+ try {
+ job = await forge(prompt, {
+ tier,
+ path: 'image',
+ pollIntervalMs: 2500,
+ timeoutMs: 240_000,
+ onProgress: (j) => log(`sculptor: forge ${j.status}${j.backend ? ` via ${j.backend}` : ''}`),
+ });
+ } catch (err) {
+ throw new Error(`sculptor: forge failed (${err?.code || 'error'}): ${err?.message || err}`);
+ }
+ if (!job?.glbUrl) throw new Error('sculptor: forge returned no GLB url');
+
+ // Download the EXACT bytes the proof binds — re-downloading the deliverable
+ // must reproduce this hash.
+ const { bytes } = await httpBytes(job.glbUrl);
+ if (!bytes?.length) throw new Error('sculptor: forge GLB url returned 0 bytes');
+
+ const proofHash = sha256(bytes);
+ const deliverable = await storeDeliverable({
+ profession: 'sculptor',
+ ext: 'glb',
+ contentType: 'model/gltf-binary',
+ bytes,
+ sourceUrl: job.glbUrl,
+ });
+
+ return {
+ result: `Sculpted "${prompt}" → ${bytes.length.toLocaleString()}-byte GLB (${job.backend || 'forge'}, ${job.tier || tier})`,
+ proofHash,
+ deliverableUrl: deliverable.url,
+ resultData: pointer64(job.creationId ? `forge:${job.creationId}` : deliverable.url),
+ resultMeta: {
+ backend: job.backend,
+ tier: job.tier || tier,
+ viewerUrl: job.viewerUrl,
+ glbUrl: job.glbUrl,
+ bytes: bytes.length,
+ stored: deliverable.stored,
+ },
+ };
+}
+
+export default work;
diff --git a/workers/agora-citizens/work/verifier.js b/workers/agora-citizens/work/verifier.js
new file mode 100644
index 000000000..a30cfb66b
--- /dev/null
+++ b/workers/agora-citizens/work/verifier.js
@@ -0,0 +1,59 @@
+// Verifier (bit 6) — the trust loop: a citizen that re-derives another citizen's
+// proof. It re-downloads the target's deliverable, recomputes sha256, compares it
+// to the proofHash recorded on-chain, and leaves a real attestation (vouch). The
+// attestation is itself a canonical, hashable artifact, so the vouch carries its
+// own proof. Agents checking agents' work.
+
+import { sha256, toHex, canonicalJsonBytes, httpBytes, pointer64 } from './_lib.js';
+
+export const profession = { bit: 6, key: 'verifier', label: 'Verifier' };
+
+export async function work({ task, citizen, client }) {
+ const log = client?.log || (() => {});
+ const target = task?.target || {};
+ const url = target.deliverableUrl;
+ const claimed = String(target.proofHash || '')
+ .toLowerCase()
+ .replace(/^0x/, '');
+
+ if (!url) throw new Error('verifier: target has no deliverableUrl to re-derive');
+ if (!/^[0-9a-f]{64}$/.test(claimed)) {
+ throw new Error('verifier: target has no valid 32-byte (64-hex) proofHash to compare');
+ }
+
+ log(`verifier: re-downloading ${url}`);
+ const { bytes } = await httpBytes(url);
+ const recomputed = toHex(sha256(bytes));
+ const match = recomputed === claimed;
+
+ const attestation = {
+ kind: 'agora.attestation.v1',
+ verifier: citizen?.agencAgentId || citizen?.id || citizen?.label || null,
+ target: {
+ citizenId: target.citizenId || null,
+ taskPda: target.taskPda || null,
+ profession: target.profession || null,
+ deliverableUrl: url,
+ },
+ claimedProofHash: claimed,
+ recomputedProofHash: recomputed,
+ bytes: bytes.length,
+ verdict: match ? 'pass' : 'fail',
+ };
+ const attBytes = canonicalJsonBytes(attestation);
+
+ log(`verifier: ${match ? 'PASS' : 'FAIL'} (recomputed ${recomputed.slice(0, 12)}… vs claimed ${claimed.slice(0, 12)}…)`);
+
+ return {
+ result: match
+ ? `Verified ${target.profession || 'deliverable'}: sha256 matches the on-chain proof (${recomputed.slice(0, 12)}…)`
+ : `MISMATCH: recomputed ${recomputed.slice(0, 12)}… ≠ on-chain ${claimed.slice(0, 12)}…`,
+ proofHash: sha256(attBytes),
+ resultData: pointer64(`vouch:${match ? 'pass' : 'fail'}:${recomputed.slice(0, 40)}`),
+ attestation,
+ verdict: match ? 'pass' : 'fail',
+ resultMeta: { match, recomputed, claimed, bytes: bytes.length },
+ };
+}
+
+export default work;