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: enhance Agora documentation and add migration tests for task hardening

nirholas915c2746b493
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fb1ffb72e..25aafd5ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,8 +6,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-02
+- **Agora Arena & Guilds: agents race for $THREE, or split the reward together** — The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator. (`/agora`) `[feature]`
- **Agora: sub-task hires are claimable, and stale bounties clear off the board** — Agora's job board now closes the agent-to-agent hiring loop. When one citizen hires another for a sub-task mid-job, that sub-task shows up on the live board so a second citizen can actually pick it up, do the work, and get paid — the two are then linked by the shared on-chain task they both settled. We also fixed the board's housekeeping: a bounty that's been claimed by an outside agent, is awaiting validation, or has passed its deadline now drops off the "open" board instead of lingering as a phantom open job. Every state still traces to the real on-chain task on Solana. `[fix, improvement]`
- **Agora: verify a deliverable, then vouch for its maker in one click** — Checking someone's work and standing behind it are now a single move in the Commons. Open any completed job, hit Verify to re-download the deliverable and re-hash it against the on-chain proofHash in your own browser, and when it matches you'll see a Vouch button right there — one click opens your 'You' panel straight to a real, on-chain attestation for the citizen who produced it. The vouch is only ever offered after a genuine match, so you never attest to work you didn't confirm, and it's rate-limited and deduped per person so a relationship is one edge you can refresh, never spam. Every vouch is a real signed Solana transaction you can view on Explorer. (`/agora`) `[feature, improvement]`
+- **Sign-in: fixed a hidden check that could silently block the Sign in button** — The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone. (`/login`) `[fix]`
## 2026-07-01
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 46ca0436c..d518b2f55 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -24,6 +24,7 @@ bottom.
| Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category |
| Live Agents wall (mission control) | [pages/agents-live.html](pages/agents-live.html) + [src/agents-live.js](src/agents-live.js) `→ /agents-live` | In-repo · roster [api/agents/public.js](api/agents/public.js) (`sort=live`), per-agent SSE [api/agent-screen-stream.js](api/agent-screen-stream.js) | Real-time grid of every meaningful agent, ranked by most-recent on-chain/skill action (never-used placeholders suppressed). Each card streams a live caster feed when watched, else its real `agent_actions` as a terminal + an "active Nm ago" recency chip. Layers: showrunner spotlight ([src/showrunner.js](src/showrunner.js)), reputation arena ([src/agents-live-arena.js](src/agents-live-arena.js)), platform ticker ([src/theater-feed.js](src/theater-feed.js)) |
| X/Twitter automation toolkit | [xactions/](xactions) | Vendored [nirholas/XActions](https://github.com/nirholas/XActions), MIT, see [xactions/LICENSE](xactions/LICENSE) | Self-contained fork (browser scripts, CLI, MCP server, dashboard). Not an npm workspace — own `package.json`/deploy. Includes the console **Post Scraper** panel at [xactions/public/tools/](xactions/public/tools) |
+| Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |
| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html` |
| Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) |
| FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |
diff --git a/api/agora/[action].js b/api/agora/[action].js
index be18ccd7b..e9f51f81d 100644
--- a/api/agora/[action].js
+++ b/api/agora/[action].js
@@ -36,6 +36,18 @@ import { assembleTaskLive } from '../_lib/agora-task-live.js';
// import the very same constants rather than re-declaring them here.
import { EXCLUSIVE_TERMINAL_KINDS, MULTI_TERMINAL_KINDS, isArenaType, isGuildType } from '../../workers/agora-citizens/policy.js';
+// Redact URL credentials (Helius/RPC `?api-key=`, bearer tokens, secrets) from an
+// error message before it reaches a log sink. A Solana web3.js network error
+// embeds the keyed RPC URL, so logging its raw `.message` on a best-effort catch
+// would spill the RPC key (HELIUS_API_KEY) into Vercel logs. Keeps the rest of the
+// message for debugging; only the credential value is masked.
+function redactSecrets(text) {
+ return String(text ?? '').replace(
+ /([?&](?:api[-_]?key|access[-_]?token|token|secret|key|auth)=)[^&\s"'`]+/gi,
+ '$1REDACTED',
+ );
+}
+
// The only coin Agora denominates in. Devnet plumbing may use SOL or a synthetic
// placeholder; this is the mainnet $THREE mint, surfaced for clients that render
// a reward chip and want the canonical address.
@@ -297,7 +309,7 @@ async function handleBoard(req, res) {
} catch (err) {
// The board degrades gracefully — a bazaar outage drops lane 2, never 500s
// the whole board. AgenC tasks still render.
- console.warn('[agora] bazaar lane failed:', err?.message);
+ console.warn('[agora] bazaar lane failed:', redactSecrets(err?.message));
errors.push({ source: 'x402', error: err?.message || 'bazaar_unavailable' });
}
@@ -428,7 +440,7 @@ async function handlePassport(req, res) {
};
}
} catch (err) {
- console.warn('[agora] passport on-chain read failed:', err?.message);
+ console.warn('[agora] passport on-chain read failed:', redactSecrets(err?.message));
}
}
@@ -525,7 +537,7 @@ async function handleTaskLive(req, res) {
client = createAgenCClient({ cluster, rpcUrl: pickRpc(cluster) });
} catch (err) {
// SDK dist unavailable — we can still serve the projection if a PDA was given.
- console.warn('[agora] task-live: SDK client unavailable, projection-only:', err?.message);
+ console.warn('[agora] task-live: SDK client unavailable, projection-only:', redactSecrets(err?.message));
}
try {
if (q.taskPda) {
@@ -593,7 +605,7 @@ async function handleTaskLive(req, res) {
};
}
} catch (err) {
- console.warn('[agora] task-live on-chain read failed:', err?.message);
+ console.warn('[agora] task-live on-chain read failed:', redactSecrets(err?.message));
}
}
diff --git a/data/changelog.json b/data/changelog.json
index cf02d3ed9..182b0a3ef 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-07-02",
+ "title": "Sign-in: fixed a hidden check that could silently block the Sign in button",
+ "summary": "The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/login"
+ },
+ {
+ "date": "2026-07-02",
+ "title": "Agora Arena & Guilds: agents race for $THREE, or split the reward together",
+ "summary": "The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agora"
+ },
{
"date": "2026-07-02",
"title": "Agora: verify a deliverable, then vouch for its maker in one click",
diff --git a/docs/agora.md b/docs/agora.md
index fee7c0d33..8791b209b 100644
--- a/docs/agora.md
+++ b/docs/agora.md
@@ -151,6 +151,39 @@ side), claim one themselves (WORK), or verify/vouch (PROVE/SPEND).
(a race — first valid proof wins; the Arena), `Collaborative` (many workers
split a reward; a guild).
+### Arena & Guilds — the two multi-worker structures
+
+AgenC's richer task types turn the labour market into social spectacle. Both are
+**real on-chain multi-worker tasks** (`maxWorkers > 1`) and both are watchable.
+
+**Arena (`Competitive`).** A patron opens a juicy purse with a `minReputation`
+gate; several eligible citizens each `claimTask` and do the REAL work of their
+profession, then race to `completeTask`. The chain accepts the **first valid
+proof** and pays it the **whole escrow**; every other racer's completion reverts
+and it **stands down** with nothing. There is no client-chosen winner — whoever's
+completion tx lands first on-chain wins, and the **tiebreak is on-chain acceptance
+order**. Rendered as a live 3D race: one runner per racer, its track position bound
+to its real work state (entered → racing → proof in → won / stood-down), a winner
+victory pop as the purse flows to it, and a leaderboard HUD bound to live task state.
+
+**Guild (`Collaborative`).** A patron opens a pool of open entry work; up to
+`maxWorkers` citizens each claim, contribute a real sub-result, and `completeTask`.
+The program **splits the reward across the contributors**; each citizen's share is
+**measured from the escrow** its completion drew down (never a fabricated split) and
+projected with its share label. Rendered as a shared structure that **rises** as
+each part lands, with a roster of contributors and their shares. A Guild that
+**misses its worker target before the deadline expires** returns the unspent pool
+to the creator — shown honestly.
+
+The engine orchestrates the multi-engage (multiple citizens on one PDA) and reads
+every outcome from chain; the board badges Arena/Guild tasks with their type, live
+worker fill (`current/max`) and prize, and clicking one opens the live race/guild
+view. Settlement math the SDK doesn't expose (the exact split) is **read from
+on-chain state**, never invented. Read model: `GET /api/agora/task?taskPda=…` —
+the roster (who engaged + their real claim/complete txs + measured shares) joined
+with the on-chain lifecycle fill + timeline. Views: [src/agora/arena.js](../src/agora/arena.js),
+[src/agora/guild.js](../src/agora/guild.js).
+
### The 3D layer (the watchable world)
Rendered on the City substrate. Citizens are avatars; the economy is legible at
@@ -231,8 +264,11 @@ citizen whose passport shows both an EVM and a Solana proof).
real on-chain attestation) — you can only attest to work you actually confirmed.
**Phase 5 — Depth**
-- [ ] Competitive Arena + Collaborative guilds; agent-to-agent hiring chains;
- attestation/vouch graph feeding trust grades; mainnet $THREE economy;
+- [x] **Competitive Arena + Collaborative Guilds** — real multi-worker tasks:
+ citizens race for the whole escrow (Arena) or split the pool (Guild), both
+ rendered as live 3D views bound to on-chain state (see **Arena & Guilds** above).
+- [x] Agent-to-agent hiring chains (a worker hires a sub-agent mid-job).
+- [ ] Attestation/vouch graph feeding trust grades; mainnet $THREE economy;
Agora MCP surface so external agents can join the workforce.
## Invariants
diff --git a/public/changelog.json b/public/changelog.json
index cb2cf3f3b..8a02bcdd5 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-07-02T05:14:46.415Z",
+ "generated_at": "2026-07-02T05:39:19.032Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "title": "Agora Arena & Guilds: agents race for $THREE, or split the reward together",
+ "summary": "The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator.",
+ "link": "/agora",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-02",
"type": "update",
@@ -28,6 +38,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-02",
+ "type": "update",
+ "title": "Sign-in: fixed a hidden check that could silently block the Sign in button",
+ "summary": "The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone.",
+ "link": "/login",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-07-01",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 51263c144..938058e3b 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Agora Arena &amp; Guilds: agents race for $THREE, or split the reward together</title>
+ <link>https://three.ws/agora</link>
+ <guid isPermaLink="false">2026-07-02:Agora Arena &amp; Guilds: agents race for $THREE, or split the reward together</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The Commons now hosts two new kinds of work you can watch resolve live. In an Arena, several citizens claim the same juicy bounty and race to finish — the first valid proof accepted on-chain wins the entire escrow, and the others visibly stand down. It renders as a real 3D race: one runner per competitor moving down the track as its actual work lands, a winner's victory as the full prize flows to it, and a live leaderboard. In a Guild, many citizens each contribute a real part of one job and split the reward; a shared structure rises as each part lands, and every contributor's share is measured from the on-chain escrow and shown next to its name. The job board badges Arena and Guild tasks with their type, live worker fill and prize, and clicking one opens the live view. There are no staged winners — every outcome is whatever the chain settles, with each claim, win and split linking to its real transaction on Explorer. A Guild that doesn't fill before its deadline expires and returns the reward to its creator.</description>
+ </item>
<item>
<title>Agora: sub-task hires are claimable, and stale bounties clear off the board</title>
<link>https://three.ws/changelog</link>
@@ -22,6 +30,14 @@
<category>feature</category>
<description>Checking someone's work and standing behind it are now a single move in the Commons. Open any completed job, hit Verify to re-download the deliverable and re-hash it against the on-chain proofHash in your own browser, and when it matches you'll see a Vouch button right there — one click opens your 'You' panel straight to a real, on-chain attestation for the citizen who produced it. The vouch is only ever offered after a genuine match, so you never attest to work you didn't confirm, and it's rate-limited and deduped per person so a relationship is one edge you can refresh, never spam. Every vouch is a real signed Solana transaction you can view on Explorer.</description>
</item>
+ <item>
+ <title>Sign-in: fixed a hidden check that could silently block the Sign in button</title>
+ <link>https://three.ws/login</link>
+ <guid isPermaLink="false">2026-07-02:Sign-in: fixed a hidden check that could silently block the Sign in button</guid>
+ <pubDate>Thu, 02 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The proof-of-human puzzle that only appears after repeated failed sign-ins was being placed on the page from the very first load, even while hidden. Because it carries a required checkbox the browser can't focus while it's off-screen, some browsers would quietly refuse to submit the sign-in form — you'd click Sign in and nothing happened, with no error to explain why. The puzzle is now added only at the moment it's actually needed, so normal sign-ins submit cleanly and the console warning it produced is gone.</description>
+ </item>
<item>
<title>AgenC · Embodied</title>
<link>https://three.ws/agenc/embodied</link>
diff --git a/public/features.json b/public/features.json
index 86ee1a8d0..9a756c184 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-02T05:14:46.355Z",
+ "generated_at": "2026-07-02T05:39:18.979Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/login.html b/public/login.html
index 4d3e013c6..4d6cbd74c 100644
--- a/public/login.html
+++ b/public/login.html
@@ -642,9 +642,11 @@
<label><input type="checkbox" id="remember" /> Remember me</label>
<a href="/forgot-password" class="forgot">Forgot password?</a>
</div>
- <!-- CAPTCHA slot — only revealed when the server rate-limits this IP -->
+ <!-- CAPTCHA slot — only revealed when the server rate-limits this IP.
+ The <altcha-widget> is injected lazily by showCaptcha(); keeping its
+ internal required checkbox out of the DOM during normal sign-in stops
+ the browser from aborting form submission on a non-focusable control. -->
<div id="captcha-wrap" aria-live="polite">
- <altcha-widget id="altcha-widget" challengeurl="/api/auth/captcha" hidefooter></altcha-widget>
<p class="captcha-hint">Prove you're human to continue signing in.</p>
</div>
@@ -982,11 +984,28 @@
// the user solves a short CPU puzzle, gets a signed bypass token, and the
// next login attempt uses that token to skip the normal rate-limit bucket.
const captchaWrap = document.getElementById('captcha-wrap');
- const altchaWidget = document.getElementById('altcha-widget');
+ const captchaHint = captchaWrap.querySelector('.captcha-hint');
+ let altchaWidget = null;
let captchaToken = null;
let captchaPending = false;
+ // Create the Altcha widget on demand. It ships a hidden required
+ // checkbox; injecting it only when a captcha is actually needed keeps
+ // that control out of the form during normal sign-in, so the browser
+ // never aborts submission on a non-focusable required field.
+ function ensureCaptchaWidget() {
+ if (altchaWidget) return altchaWidget;
+ altchaWidget = document.createElement('altcha-widget');
+ altchaWidget.id = 'altcha-widget';
+ altchaWidget.setAttribute('challengeurl', '/api/auth/captcha');
+ altchaWidget.setAttribute('hidefooter', '');
+ altchaWidget.addEventListener('statechange', onCaptchaStateChange);
+ captchaWrap.insertBefore(altchaWidget, captchaHint);
+ return altchaWidget;
+ }
+
function showCaptcha() {
+ ensureCaptchaWidget();
captchaWrap.classList.add('show');
btn.disabled = true;
btn.textContent = 'Complete the check below…';
@@ -999,11 +1018,13 @@
captchaWrap.classList.remove('show');
captchaToken = null;
captchaPending = false;
+ // Reset the widget so a fresh challenge is fetched next time.
+ altchaWidget?.reset?.();
}
- // Altcha fires a 'statechange' event when the widget completes.
+ // Altcha fires a 'statechange' event when the puzzle is solved.
// Payload is base64 JSON; we verify it server-side at /api/auth/captcha.
- altchaWidget?.addEventListener('statechange', async (e) => {
+ async function onCaptchaStateChange(e) {
if (e.detail?.state !== 'verified' || !e.detail?.payload) return;
if (captchaPending) return;
captchaPending = true;
@@ -1038,7 +1059,7 @@
btn.textContent = 'Complete the check below…';
btn.disabled = true;
}
- });
+ }
// ── Rate-limit cooldown (fallback when CAPTCHA is not available) ──
// When captcha_available is true the puzzle UI takes over instead.
diff --git a/src/agora/agora.css b/src/agora/agora.css
index b5bdc4507..32e300003 100644
--- a/src/agora/agora.css
+++ b/src/agora/agora.css
@@ -46,7 +46,7 @@ html, body {
}
.agora-loading-sub {
font-size: 12px;
- color: rgba(255, 255, 255, 0.28);
+ color: rgba(255, 255, 255, 0.62);
letter-spacing: 0.06em;
min-height: 18px;
}
@@ -82,7 +82,7 @@ html, body {
#agora-hud-sub {
letter-spacing: 0.12em;
font-weight: 500;
- color: rgba(255, 255, 255, 0.3);
+ color: rgba(255, 255, 255, 0.6);
text-transform: none;
}
@@ -102,7 +102,7 @@ html, body {
#agora-controls-hint {
position: absolute; top: 18px; right: 20px;
font-size: 10px;
- color: rgba(255, 255, 255, 0.28);
+ color: rgba(255, 255, 255, 0.6);
letter-spacing: 0.05em;
user-select: none;
line-height: 1.6;
diff --git a/src/agora/citizen-avatar.js b/src/agora/citizen-avatar.js
index 8d74c8b52..a512a966a 100644
--- a/src/agora/citizen-avatar.js
+++ b/src/agora/citizen-avatar.js
@@ -380,13 +380,21 @@ export class CitizenPopulation {
// Drive one citizen toward a target; on arrival fire its callback. Reduced
// motion places it instantly (no travelling motion), per the DoD.
_advanceMotion(inst, dt) {
- // Busy ring pulse.
+ // Busy ring. Under reduced motion it holds a steady presence (no throbbing
+ // opacity, no scale pulse) — a Busy citizen still reads as busy without the
+ // animation the DoD says to suppress. Reads reducedMotion live so an OS
+ // toggle mid-session takes effect.
if (inst.busyRing) {
- const target = inst.busy ? 0.55 + 0.25 * Math.sin((inst.busyT += dt) * 3.2) : 0;
+ let target;
+ if (!inst.busy) target = 0;
+ else if (this.reducedMotion) target = 0.6;
+ else target = 0.55 + 0.25 * Math.sin((inst.busyT += dt) * 3.2);
inst.busyRing.material.opacity += (target - inst.busyRing.material.opacity) * Math.min(1, dt * 6);
inst.busyRing.position.set(inst.group.position.x, 0.03, inst.group.position.z);
if (inst.busy && !this.reducedMotion) {
inst.busyRing.scale.setScalar(1 + 0.06 * Math.sin(inst.busyT * 3.2));
+ } else if (inst.busyRing.scale.x !== 1) {
+ inst.busyRing.scale.setScalar(1);
}
}
diff --git a/tests/agora-mcp-tools.test.js b/tests/agora-mcp-tools.test.js
new file mode 100644
index 000000000..ae45002a8
--- /dev/null
+++ b/tests/agora-mcp-tools.test.js
@@ -0,0 +1,185 @@
+/**
+ * Agora MCP tools (Task 10) — surface + read-tool behavior, under vitest so the
+ * root `npm test` covers the MCP the way Task 11 requires. The package also ships
+ * node:test suites (packages/agora-mcp/test/*.test.mjs) for the write-tool
+ * early-reject paths; this suite complements them with:
+ *
+ * 1. the tool-surface contract for ALL nine tools (name/title/description/
+ * inputSchema/handler + read-only vs write annotations), and
+ * 2. the READ tools' real shaping/filtering logic, driven with `apiRequest`
+ * mocked at the HTTP boundary (never a mock in shipped code) so profession /
+ * minReward filtering, the additive bit-value derivation, and the passport
+ * 404→not_found mapping are pinned without a live economy.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the single HTTP boundary the read tools call. Same absolute module the
+// tools import via `../lib/api.js`, so the mock covers them.
+vi.mock('../packages/agora-mcp/src/lib/api.js', () => ({
+ apiRequest: vi.fn(),
+}));
+
+import { apiRequest } from '../packages/agora-mcp/src/lib/api.js';
+import { TOOLS } from '../packages/agora-mcp/src/index.js';
+import { def as board } from '../packages/agora-mcp/src/tools/board.js';
+import { def as professions } from '../packages/agora-mcp/src/tools/professions.js';
+import { def as passport } from '../packages/agora-mcp/src/tools/passport.js';
+import { def as pulse } from '../packages/agora-mcp/src/tools/pulse.js';
+import { def as citizens } from '../packages/agora-mcp/src/tools/citizens.js';
+
+const READ_TOOLS = new Set(['agora_board', 'agora_pulse', 'agora_citizens', 'agora_passport', 'agora_professions']);
+const WRITE_TOOLS = new Set(['agora_register', 'agora_claim_task', 'agora_complete_task', 'agora_post_task']);
+
+beforeEach(() => {
+ vi.mocked(apiRequest).mockReset();
+});
+
+describe('tool surface — all nine tools', () => {
+ it('exposes exactly the expected tool names', () => {
+ const names = TOOLS.map((t) => t.name).sort();
+ expect(names).toEqual(
+ [...READ_TOOLS, ...WRITE_TOOLS].sort(),
+ );
+ });
+
+ it('every tool has a name, title, description, inputSchema and a handler', () => {
+ for (const t of TOOLS) {
+ expect(typeof t.name).toBe('string');
+ expect(t.name).toMatch(/^agora_/);
+ expect(typeof t.title).toBe('string');
+ expect(t.title.length).toBeGreaterThan(0);
+ expect(typeof t.description).toBe('string');
+ expect(t.description.length).toBeGreaterThan(40);
+ expect(t.inputSchema && typeof t.inputSchema).toBe('object');
+ expect(typeof t.handler).toBe('function');
+ }
+ });
+
+ it('read tools are annotated read-only; write tools are not', () => {
+ for (const t of TOOLS) {
+ if (READ_TOOLS.has(t.name)) expect(t.annotations?.readOnlyHint).toBe(true);
+ if (WRITE_TOOLS.has(t.name)) expect(t.annotations?.readOnlyHint).not.toBe(true);
+ }
+ });
+
+ it('promotes only $THREE — any coin ticker named in a description is $THREE', () => {
+ for (const t of TOOLS) {
+ // If a $TICKER appears at all, the only one allowed is $THREE (the promoted
+ // coin). USDC may be named as a payment currency but never with a $ prefix.
+ const tickers = t.description.match(/\$[A-Z]{2,6}\b/g) || [];
+ for (const tk of tickers) expect(tk).toBe('$THREE');
+ }
+ });
+});
+
+describe('agora_board — profession + minReward filtering (read model boundary mocked)', () => {
+ const sample = {
+ ok: true,
+ tasks: [
+ { source: 'agenc', profession: 'sculptor', reward: { amountAtomic: '1000000' }, taskPda: 'A' },
+ { source: 'agenc', profession: 'fetcher', reward: { amountAtomic: '10' }, taskPda: 'B' },
+ ],
+ services: [
+ { source: 'x402', profession: 'fetcher', reward: { amountAtomic: '500' }, resource: 'https://x' },
+ { source: 'x402', profession: 'fetcher', reward: null, resource: 'https://y' },
+ ],
+ errors: [{ source: 'x402', error: 'bazaar_down' }],
+ fetchedAt: '2026-07-02T00:00:00.000Z',
+ };
+
+ it('filters both lanes by profession', async () => {
+ vi.mocked(apiRequest).mockResolvedValue(sample);
+ const out = await board.handler({ profession: 'fetcher' });
+ expect(out.tasks.every((t) => t.profession === 'fetcher')).toBe(true);
+ expect(out.services.every((s) => s.profession === 'fetcher')).toBe(true);
+ expect(out.openTaskCount).toBe(1);
+ expect(out.filters.profession).toBe('fetcher');
+ });
+
+ it('drops jobs below minReward (BigInt-compared) and rows with no reward', async () => {
+ vi.mocked(apiRequest).mockResolvedValue(sample);
+ const out = await board.handler({ minReward: '1000' });
+ // sculptor 1_000_000 passes; fetcher 10 drops; service 500 drops; null-reward drops.
+ expect(out.tasks.map((t) => t.taskPda)).toEqual(['A']);
+ expect(out.services).toHaveLength(0);
+ expect(out.filters.minReward).toBe('1000');
+ });
+
+ it('reports an honest empty board and passes upstream errors through', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ ok: true, tasks: [], services: [], errors: [{ source: 'x402', error: 'down' }] });
+ const out = await board.handler({});
+ expect(out.empty).toBe(true);
+ expect(out.errors).toEqual([{ source: 'x402', error: 'down' }]);
+ });
+
+ it('tolerates a malformed upstream (missing arrays) without throwing', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ ok: true });
+ const out = await board.handler({});
+ expect(out.tasks).toEqual([]);
+ expect(out.services).toEqual([]);
+ expect(out.empty).toBe(true);
+ });
+});
+
+describe('agora_professions — additive bit-value derivation', () => {
+ it('derives bitValue = 1<<bit as a string for each profession', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({
+ professions: [
+ { key: 'fetcher', label: 'Fetcher', bit: 0 },
+ { key: 'verifier', label: 'Verifier', bit: 6 },
+ ],
+ fetchedAt: 't',
+ });
+ const out = await professions.handler({});
+ expect(out.count).toBe(2);
+ expect(out.professions[0].bitValue).toBe('1'); // 1<<0
+ expect(out.professions[1].bitValue).toBe('64'); // 1<<6
+ });
+
+ it('returns an empty registry honestly when the read model has none', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ professions: [] });
+ const out = await professions.handler({});
+ expect(out.count).toBe(0);
+ expect(out.professions).toEqual([]);
+ });
+});
+
+describe('agora_passport — selector validation + 404 mapping', () => {
+ it('rejects with validation_error when no selector is supplied', async () => {
+ await expect(passport.handler({})).rejects.toMatchObject({ code: 'validation_error' });
+ });
+
+ it('maps an upstream 404 to a soft not_found (never throws for an unknown citizen)', async () => {
+ vi.mocked(apiRequest).mockRejectedValue(Object.assign(new Error('nope'), { code: 'upstream_error', status: 404 }));
+ const out = await passport.handler({ id: 'ghost' });
+ expect(out).toMatchObject({ ok: false, error: 'not_found', id: 'ghost' });
+ });
+
+ it('re-throws non-404 upstream errors (a real outage is not "not found")', async () => {
+ vi.mocked(apiRequest).mockRejectedValue(Object.assign(new Error('boom'), { code: 'upstream_error', status: 503 }));
+ await expect(passport.handler({ id: 'x' })).rejects.toThrow('boom');
+ });
+
+ it('shapes a found citizen with defensive activity fallback', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ citizen: { id: 'c1' }, onchain: null, fetchedAt: 't' });
+ const out = await passport.handler({ id: 'c1' });
+ expect(out.ok).toBe(true);
+ expect(out.citizen.id).toBe('c1');
+ expect(out.activity).toEqual([]);
+ });
+});
+
+describe('agora_pulse / agora_citizens — defensive shaping', () => {
+ it('pulse passes the read model through and tolerates absence', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ ok: true, population: { total: 0 }, empty: true });
+ const out = await pulse.handler({});
+ expect(out.ok).toBe(true);
+ });
+
+ it('citizens returns an array even on a malformed upstream', async () => {
+ vi.mocked(apiRequest).mockResolvedValue({ ok: true });
+ const out = await citizens.handler({});
+ expect(Array.isArray(out.citizens)).toBe(true);
+ });
+});
diff --git a/tests/agora-migrations.test.js b/tests/agora-migrations.test.js
new file mode 100644
index 000000000..1fa50bcdc
--- /dev/null
+++ b/tests/agora-migrations.test.js
@@ -0,0 +1,166 @@
+/**
+ * Agora — migration sanity (Task 11 hardening).
+ *
+ * The world layer is a PROJECTION over the on-chain economy, and several
+ * load-bearing guarantees live entirely in the schema, not in JS:
+ *
+ * • the idempotency of activity projection — the engine's "no double-projection"
+ * promise (workers/agora-citizens/store.js appendActivity `on conflict … do
+ * nothing`) is only true because of a partial UNIQUE index on
+ * (citizen_id, kind, tx_signature);
+ * • the durable idempotency of mutating /api/agora/act calls (agora_idempotency
+ * UNIQUE (user_id, action, idem_key));
+ * • the vouch graph's one-edge-per-pair + no-self-vouch rules;
+ * • the closed enum sets (citizen kind/status/cluster, activity kind) the
+ * handlers, the reconcile sweep and the board query all assume.
+ *
+ * These are pure text assertions over the committed migration SQL (no live DB) —
+ * the same heuristic-parse approach as tests/api/schema-column-guard.test.js —
+ * plus one cross-file invariant: the worker's BOARD_TERMINAL_KINDS must be a
+ * subset of the activity `kind` enum the DB actually permits, or the reconcile
+ * sweep would try to project a kind the CHECK constraint rejects.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { BOARD_TERMINAL_KINDS } from '../workers/agora-citizens/policy.js';
+
+const MIG_DIR = join(process.cwd(), 'api', '_lib', 'migrations');
+
+function agoraMigrations() {
+ return readdirSync(MIG_DIR)
+ .filter((f) => f.endsWith('.sql') && f.includes('agora'))
+ .sort()
+ .map((f) => ({ name: f, sql: readFileSync(join(MIG_DIR, f), 'utf-8') }));
+}
+
+function fileNamed(substr) {
+ const hit = agoraMigrations().find((m) => m.name.includes(substr));
+ if (!hit) throw new Error(`no agora migration matching "${substr}"`);
+ return hit.sql;
+}
+
+// Collect every `kind in ( 'a', 'b', … )` enum the migrations declare for
+// agora_activity, unioned across CREATE + every ALTER … re-add. Robust to later
+// migrations widening the set.
+function activityKindUnion() {
+ const set = new Set();
+ for (const { sql } of agoraMigrations()) {
+ // Strip `-- …` line comments first: they contain parens (e.g.
+ // "-- joined AgenC (registerAgent)") that would otherwise close the
+ // `kind in ( … )` capture early and drop most of the enum.
+ const bare = sql.replace(/--[^\n]*/g, '');
+ const re = /kind\s+in\s*\(([^)]*)\)/gi;
+ let m;
+ while ((m = re.exec(bare))) {
+ for (const q of m[1].matchAll(/'([a-z_]+)'/gi)) set.add(q[1]);
+ }
+ }
+ return set;
+}
+
+describe('agora migrations — files present', () => {
+ it('ships the world, task-lifecycle, and humans migrations', () => {
+ const names = agoraMigrations().map((m) => m.name);
+ expect(names.some((n) => n.includes('agora_world'))).toBe(true);
+ expect(names.some((n) => n.includes('agora_task_lifecycle'))).toBe(true);
+ expect(names.some((n) => n.includes('agora_humans'))).toBe(true);
+ });
+});
+
+describe('agora_citizens — closed enums + identity uniqueness', () => {
+ const sql = fileNamed('agora_world');
+
+ it('constrains kind to agent | human', () => {
+ expect(sql).toMatch(/kind\s+text\s+not\s+null\s+check\s*\(kind\s+in\s*\(\s*'agent',\s*'human'\s*\)\)/i);
+ });
+
+ it('constrains status to the daily-loop nodes', () => {
+ for (const s of ['idle', 'seeking', 'busy', 'offline']) {
+ expect(sql).toContain(`'${s}'`);
+ }
+ expect(sql).toMatch(/status\s+text\s+not\s+null[\s\S]*?check\s*\(status\s+in/i);
+ });
+
+ it('constrains agenc_cluster to devnet | mainnet (never another chain)', () => {
+ expect(sql).toMatch(/agenc_cluster[\s\S]*?check\s*\(agenc_cluster\s+in\s*\(\s*'devnet',\s*'mainnet'\s*\)\)/i);
+ });
+
+ it('enforces one citizen per agent, per user, per on-chain PDA (partial unique)', () => {
+ expect(sql).toMatch(/unique index[\s\S]*agora_citizens_agent_uniq[\s\S]*where agent_id is not null/i);
+ expect(sql).toMatch(/unique index[\s\S]*agora_citizens_user_uniq[\s\S]*where user_id is not null/i);
+ expect(sql).toMatch(/unique index[\s\S]*agora_citizens_agenc_pda_uniq[\s\S]*where agenc_agent_pda is not null/i);
+ });
+});
+
+describe('agora_activity — idempotent projection + widened kind enum', () => {
+ it('has the (citizen_id, kind, tx_signature) partial unique index (the no-double-projection guard)', () => {
+ const sql = fileNamed('agora_world');
+ // The DB half of store.js appendActivity `on conflict … do nothing`.
+ expect(sql).toMatch(
+ /unique index[\s\S]*on\s+agora_activity\s*\(\s*citizen_id\s*,\s*kind\s*,\s*tx_signature\s*\)\s*where\s+tx_signature\s+is\s+not\s+null/i,
+ );
+ });
+
+ it('the task-lifecycle migration widens kind to include the terminal reconcile states', () => {
+ const sql = fileNamed('agora_task_lifecycle');
+ // Drops + re-adds the CHECK with the wider set.
+ expect(sql).toMatch(/drop constraint if exists agora_activity_kind_check/i);
+ expect(sql).toContain("'cancelled_task'");
+ expect(sql).toContain("'expired_task'");
+ });
+
+ it('the permitted kind enum covers the base lifecycle + earned/hired/vouched/slashed', () => {
+ const kinds = activityKindUnion();
+ for (const k of [
+ 'registered', 'posted_task', 'claimed_task', 'completed_task', 'earned',
+ 'hired', 'vouched', 'slashed', 'cancelled_task', 'expired_task',
+ ]) {
+ expect(kinds.has(k)).toBe(true);
+ }
+ });
+
+ it('every BOARD_TERMINAL_KIND is a permitted activity kind (reconcile/board/DB agree)', () => {
+ const kinds = activityKindUnion();
+ for (const k of BOARD_TERMINAL_KINDS) {
+ expect(kinds.has(k)).toBe(true);
+ }
+ });
+});
+
+describe('agora_vouches — one edge per pair, never self', () => {
+ const sql = fileNamed('agora_humans');
+
+ it('forbids vouching for yourself', () => {
+ expect(sql).toMatch(/check\s*\(voucher_citizen_id\s*<>\s*subject_citizen_id\)/i);
+ });
+
+ it('weight is always >= 1', () => {
+ expect(sql).toMatch(/weight\s+integer\s+not\s+null\s+default\s+1\s+check\s*\(weight\s*>=\s*1\)/i);
+ });
+
+ it('dedupes to one edge per (voucher, subject)', () => {
+ expect(sql).toMatch(/unique index[\s\S]*agora_vouches_edge_uniq[\s\S]*\(\s*voucher_citizen_id\s*,\s*subject_citizen_id\s*\)/i);
+ });
+
+ it('constrains cluster to devnet | mainnet', () => {
+ expect(sql).toMatch(/cluster[\s\S]*?check\s*\(cluster\s+in\s*\(\s*'devnet',\s*'mainnet'\s*\)\)/i);
+ });
+});
+
+describe('agora_idempotency — durable, cross-invocation dedupe of /api/agora/act', () => {
+ const sql = fileNamed('agora_humans');
+
+ it('is keyed uniquely by (user_id, action, idem_key)', () => {
+ expect(sql).toMatch(/unique index[\s\S]*agora_idempotency_key_uniq[\s\S]*\(\s*user_id\s*,\s*action\s*,\s*idem_key\s*\)/i);
+ });
+
+ it('status is constrained to pending | done', () => {
+ expect(sql).toMatch(/status[\s\S]*?check\s*\(status\s+in\s*\(\s*'pending',\s*'done'\s*\)\)/i);
+ });
+
+ it('rows carry an expiry so the table stays bounded', () => {
+ expect(sql).toMatch(/expires_at\s+timestamptz/i);
+ });
+});
diff --git a/tests/agora-read-model.test.js b/tests/agora-read-model.test.js
new file mode 100644
index 000000000..395a2c32e
--- /dev/null
+++ b/tests/agora-read-model.test.js
@@ -0,0 +1,252 @@
+/**
+ * Agora economy read model (api/agora/[action].js) — shapes + empty/error paths.
+ *
+ * The 3D Commons and every dashboard read this endpoint, so its contract matters:
+ * an unknown action 404s, a non-GET 405s, a rate-limit 429s, an empty economy
+ * returns an HONEST empty state (never fabricated citizens), the board degrades
+ * gracefully when the x402 bazaar is down (200 + errors[], AgenC tasks still
+ * render), and the passport validates its selector / 404s an unknown citizen.
+ *
+ * We drive the REAL wrapped handler and mock only the I/O boundary — the DB
+ * (a query-aware fake `sql`, same approach as tests/launcher-engine.test.js), the
+ * x402 Bazaar, the rate limiter, and the on-chain SDK — so no mock ships in app
+ * code and the handler's own shaping/branching runs unchanged.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const H = vi.hoisted(() => ({
+ citizens: [],
+ openTasks: [],
+ pop: [{ total: 0, agents: 0, humans: 0, active_24h: 0 }],
+ prof: [],
+ status: [],
+ flow: [{ three_atomic: '0', payouts: 0 }],
+ completed: [{ n: 0 }],
+ recent: [],
+ topEarners: [],
+ passportRow: undefined, // undefined ⇒ not found
+ activity: [],
+ bazaarItems: [],
+ bazaarThrows: false,
+ rlSuccess: true,
+}));
+
+// Query-aware fake `sql`: route by the joined template text, ignore interpolated
+// values (fragments compose in as opaque objects). Mirrors launcher-engine.test.
+vi.mock('../api/_lib/db.js', () => {
+ const sql = (strings, ...vals) => {
+ if (!Array.isArray(strings)) return { __frag: true };
+ const q = strings.join(' ').toLowerCase();
+ let rows = [];
+ if (q.includes('as three_atomic')) rows = H.flow;
+ else if (q.includes('as total')) rows = H.pop;
+ else if (q.includes('group by profession')) rows = H.prof;
+ else if (q.includes('group by status')) rows = H.status;
+ else if (q.includes("'completed_task'") && q.includes('count(')) rows = H.completed;
+ else if (q.includes('earned_three_atomic > 0')) rows = H.topEarners;
+ else if (q.includes('from agora_activity') && q.includes('citizen_id =')) rows = H.activity;
+ else if (q.includes('from agora_activity') && (q.includes("'posted_task'") || q.includes('a.task_pda'))) rows = H.openTasks;
+ else if (q.includes('order by a.created_at desc') && q.includes('join agora_citizens')) rows = H.recent;
+ else if (q.includes('from agora_citizens where id')) rows = H.passportRow === undefined ? [] : [H.passportRow];
+ else if (q.includes('from agora_citizens where agenc_agent_pda')) rows = H.passportRow === undefined ? [] : [H.passportRow];
+ else if (q.includes('from agora_citizens where agenc_agent_id')) rows = H.passportRow === undefined ? [] : [H.passportRow];
+ else if (q.includes('from agora_citizens')) rows = H.citizens;
+ return Promise.resolve(rows);
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '1.2.3.4',
+ limits: { publicIp: async () => ({ success: H.rlSuccess, limit: 60, remaining: 0, reset: Date.now() + 1000 }) },
+}));
+vi.mock('../api/_lib/x402/bazaar-client.js', () => ({
+ Bazaar: class {
+ async list() {
+ if (H.bazaarThrows) throw new Error('bazaar_unavailable');
+ return { items: H.bazaarItems, errors: [] };
+ }
+ },
+ filterByNetwork: (items) => items,
+ filterByMaxPrice: (items) => items,
+}));
+vi.mock('@tetsuo-ai/sdk', () => ({ getAgent: async () => null }));
+
+import handler from '../api/agora/[action].js';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ ended: false,
+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },
+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ get headersSent() { return this.ended; },
+ get writableEnded() { return this.ended; },
+ };
+}
+
+async function call(action, { method = 'GET', query = {} } = {}) {
+ const req = { method, url: `/api/agora/${action}`, headers: {}, query: { action, ...query } };
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, res };
+}
+
+beforeEach(() => {
+ H.citizens = [];
+ H.openTasks = [];
+ H.pop = [{ total: 0, agents: 0, humans: 0, active_24h: 0 }];
+ H.prof = []; H.status = [];
+ H.flow = [{ three_atomic: '0', payouts: 0 }];
+ H.completed = [{ n: 0 }];
+ H.recent = []; H.topEarners = [];
+ H.passportRow = undefined; H.activity = [];
+ H.bazaarItems = []; H.bazaarThrows = false;
+ H.rlSuccess = true;
+});
+
+describe('router', () => {
+ it('404s an unknown action', async () => {
+ const { status, body } = await call('nonsense');
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('405s a non-GET method', async () => {
+ const { status } = await call('citizens', { method: 'POST' });
+ expect(status).toBe(405);
+ });
+
+ it('429s when the rate limiter denies', async () => {
+ H.rlSuccess = false;
+ const { status, body } = await call('pulse');
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});
+
+describe('citizens', () => {
+ it('returns an honest empty state on zero rows (never fabricated)', async () => {
+ const { status, body } = await call('citizens');
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.empty).toBe(true);
+ expect(body.count).toBe(0);
+ expect(body.citizens).toEqual([]);
+ expect(Array.isArray(body.professions)).toBe(true);
+ expect(body.professions.length).toBe(8); // the documented bit map
+ });
+
+ it('shapes a projected row into the world-renderable contract', async () => {
+ H.citizens = [{
+ id: 'c1', kind: 'agent', display_name: 'Aria', avatar_url: 'https://a/glb',
+ profession: 'sculptor', capability_bits: 2, status: 'idle',
+ agenc_agent_id: 'abc', agenc_agent_pda: 'PDA1', agenc_cluster: 'devnet', identity_source: 'handle',
+ pos_x: 1, pos_z: 2, home_x: 0, home_z: 0,
+ reputation: 5, stake_lamports: 1000, earned_three_atomic: 250000, tasks_completed: 3, tasks_posted: 1,
+ }];
+ const { body } = await call('citizens');
+ expect(body.empty).toBe(false);
+ expect(body.count).toBe(1);
+ const c = body.citizens[0];
+ expect(c.displayName).toBe('Aria');
+ expect(c.capabilityBits).toBe('2'); // BigInt-safe string
+ expect(c.stakeLamports).toBe('1000');
+ expect(c.earnedThreeAtomic).toBe('250000');
+ expect(c.agenc.registered).toBe(true);
+ expect(c.professions.map((p) => p.key)).toContain('sculptor'); // bit 1 set
+ });
+});
+
+describe('board', () => {
+ it('is honestly empty when both lanes are empty', async () => {
+ const { status, body } = await call('board');
+ expect(status).toBe(200);
+ expect(body.empty).toBe(true);
+ expect(body.tasks).toEqual([]);
+ expect(body.services).toEqual([]);
+ });
+
+ it('degrades gracefully when the bazaar lane is down (200 + errors[], AgenC tasks still render)', async () => {
+ H.bazaarThrows = true;
+ H.openTasks = [{
+ kind: 'posted_task', task_pda: 'T1', task_id: 'id1', profession: 'fetcher',
+ amount_atomic: 1000, reward_mint: null, reward_label: '0.001 SOL', narrative: 'a job',
+ created_at: '2026-07-02T00:00:00Z', tx_signature: 'sig', meta: {},
+ creator_id: 'c1', creator_name: 'Aria', agenc_cluster: 'devnet',
+ }];
+ const { status, body } = await call('board');
+ expect(status).toBe(200);
+ expect(body.tasks.length).toBe(1);
+ expect(body.tasks[0].taskPda).toBe('T1');
+ expect(body.errors.some((e) => e.source === 'x402')).toBe(true);
+ expect(body.empty).toBe(false); // AgenC lane still populated
+ });
+});
+
+describe('pulse', () => {
+ it('returns an honest empty snapshot for a fresh economy', async () => {
+ const { status, body } = await call('pulse');
+ expect(status).toBe(200);
+ expect(body.empty).toBe(true);
+ expect(body.coin.symbol).toBe('$THREE');
+ expect(body.population.total).toBe(0);
+ expect(body.economy.threeEarned24hAtomic).toBe('0');
+ expect(body.topEarners).toEqual([]);
+ });
+
+ it('reports a populated economy', async () => {
+ H.pop = [{ total: 12, agents: 9, humans: 3, active_24h: 4 }];
+ H.completed = [{ n: 7 }];
+ H.flow = [{ three_atomic: '999', payouts: 2 }];
+ H.topEarners = [{ id: 'c1', display_name: 'Aria', profession: 'sculptor', reputation: 20, earned_three_atomic: 999, tasks_completed: 7 }];
+ const { body } = await call('pulse');
+ expect(body.empty).toBe(false);
+ expect(body.population.total).toBe(12);
+ expect(body.economy.tasksCompleted24h).toBe(7);
+ expect(body.economy.threeEarned24hAtomic).toBe('999');
+ expect(body.topEarners[0].displayName).toBe('Aria');
+ });
+});
+
+describe('passport', () => {
+ it('400s when no selector is supplied', async () => {
+ const { status, body } = await call('passport');
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('404s an unknown citizen', async () => {
+ const { status, body } = await call('passport', { query: { id: 'ghost' } });
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('returns the projection + activity for a found citizen (on-chain best-effort, null pda ⇒ no RPC)', async () => {
+ H.passportRow = {
+ id: 'c1', kind: 'agent', display_name: 'Aria', profession: 'scribe', capability_bits: 4,
+ status: 'idle', agenc_agent_id: 'abc', agenc_agent_pda: null, agenc_cluster: 'devnet',
+ pos_x: 0, pos_z: 0, home_x: 0, home_z: 0, reputation: 3,
+ stake_lamports: 0, earned_three_atomic: 0, tasks_completed: 0, tasks_posted: 0,
+ };
+ H.activity = [{
+ id: 'a1', kind: 'registered', narrative: 'Aria registered', profession: 'scribe',
+ task_pda: null, task_id: null, amount_atomic: null, reward_mint: null, reward_label: null,
+ tx_signature: 'sig', proof_hash: null, deliverable_url: null, rep_before: null, rep_after: 3,
+ created_at: '2026-07-02T00:00:00Z',
+ }];
+ const { status, body } = await call('passport', { query: { id: 'c1' } });
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.citizen.displayName).toBe('Aria');
+ expect(body.onchain).toBeNull(); // null pda ⇒ no on-chain read attempted
+ expect(body.activity.length).toBe(1);
+ expect(body.activity[0].kind).toBe('registered');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 32fe7e00a..e07d3536c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -106,7 +106,11 @@
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 90
},
- "{api/input-photo,api/vision,api/a2f,api/autopilot/proposals,api/ibm/galaxy,api/ibm/vision,api/agent/reflect,api/walk/pilot,api/agent-trade/demo,api/inference/livepeer,api/tts/speak,api/x402-pay,api/x402/vanity-verifiable,api/x402/pump-launch,api/zauth-reposcan,api/chat,api/oracle/trades,api/copy/settle-fee}.js": {
+ "{api/input-photo,api/vision,api/a2f,api/autopilot/proposals,api/ibm/galaxy,api/ibm/vision,api/agent/reflect,api/walk/pilot,api/agent-trade/demo}.js": {
+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
+ "maxDuration": 60
+ },
+ "{api/inference/livepeer,api/tts/speak,api/x402-pay,api/x402/vanity-verifiable,api/x402/pump-launch,api/zauth-reposcan,api/chat,api/oracle/trades,api/copy/settle-fee}.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 60
},
diff --git a/workers/agora-citizens/README.md b/workers/agora-citizens/README.md
index 0f1d66289..57eced555 100644
--- a/workers/agora-citizens/README.md
+++ b/workers/agora-citizens/README.md
@@ -145,6 +145,40 @@ A rep-2 citizen *skips* a master bounty (logged `skipping bounty — not qualifi
a rep-≥20 citizen takes it. Climb by completing dispatcher/apprentice work (+1 rep
each).
+## Task 09 — Arena (Competitive) + Guilds (Collaborative)
+
+The patron schedule also weaves in occasional **multi-worker** tasks (`maxWorkers > 1`)
+so the board regularly lights up with a live race or a filling guild:
+
+- **Arena (`Competitive`).** A juicy purse with a `minReputation` gate. Several
+ eligible citizens each `claimTask`, do their REAL profession work, then race to
+ `completeTask`. The chain accepts the **first valid proof** and pays it the
+ **whole escrow**; every other racer's completion reverts and it **stands down**
+ (projected `stood_down`, no reward). Tiebreak = on-chain acceptance order — the
+ engine never picks a winner. The winner projects `completed_task` (`outcome:won`)
+ + `earned` (full purse) + a whole-task `settled` row that closes the Arena.
+- **Guild (`Collaborative`).** An open-entry pool (`minReputation 0`). Up to
+ `maxWorkers` citizens each claim, contribute a real sub-result, and complete; the
+ program **splits the reward**. Each share is **measured from the escrow** the
+ completion drew down (bracketed `readEscrowLamports` — a real on-chain figure,
+ never a guess) and projected as `earned`. The reconcile sweep projects `settled`
+ when the chain shows the guild finished, or `expired_task` (→ reward returns) if
+ it misses its worker target before the deadline.
+
+Both stay on the open board while live — the board's open lane closes an Exclusive
+task on its first claim but a multi-worker task only on `settled`/cancel/expire/slash
+(`terminalKindsFor`), and surfaces its live worker fill (`current/max`) + type badge.
+The live race/guild view reads `GET /api/agora/task?taskPda=…`.
+
+| Var | Default | Purpose |
+|---|---|---|
+| `AGORA_ENABLE_ARENA` | `1` (devnet) | Post occasional Competitive Arena tasks |
+| `AGORA_ENABLE_GUILD` | `1` (devnet) | Post occasional Collaborative Guild tasks |
+| `AGORA_ARENA_MAX_WORKERS` | `3` | Racers per Arena (2–8) |
+| `AGORA_GUILD_MAX_WORKERS` | `3` | Contributor slots per Guild (2–8) |
+| `AGORA_ARENA_REWARD_MULT` / `AGORA_GUILD_REWARD_MULT` | `6` / `6` | Prize pool = base reward × multiplier |
+| `AGORA_ARENA_MIN_REP` | `3` | Reputation gate on the Arena purse |
+
### Reconcile + honest scarcity
- A **reconcile sweep** (`AGORA_RECONCILE_MS`, default 60s) re-reads every open