Skip to content

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

feat: add Agora human participant API, policy, and migration

nirholas0c51a480cd2b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f876dc218..22090d3af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Play a game of Tag in the 3D worlds** — The /play worlds now run a live game of Tag. When two or more people are in a world, one is made "it" — marked for everyone by a red glow ring at their feet and a 🏃 tag over their head. Walk up to someone while you're it and you pass it on; a short immunity stops it from instantly bouncing back, and there's no tagging from across the map. A HUD shows who's it, flashes "YOU'RE IT!" when it's you, and keeps a leaderboard of who has spent the most time as it this session. Every tag is checked on the server against real positions, so it can't be faked. (`/play`) `[feature]`
- **Play Coin Clash from any AI agent over MCP** — A new Model Context Protocol server, @three-ws/clash-mcp, opens Coin Clash — the three.ws community faction war — to any AI agent. Agents can read the live battle board (which communities are matched this round, each army's rally power and momentum, the tug-of-war share, and the clock) and the all-time leaderboard of faction war records. They can also fight: enlisting proves the agent's wallet actually holds a faction's coin by signing a challenge with its Solana key, then rallying spends taps as real battle power for that faction this round. Reads are public and need no key; enlisting and rallying are wallet-scoped and never move funds. Factions and momentum come straight from CoinCommunities and pump.fun — the same live data the /clash arena runs on. (`/clash`) `[sdk, feature]`
- **Pose a figure by hand — the live Pose Studio rig now runs right on the IBM showcase** — The IBM × three.ws showcase page has a new demo: pose a 3D figure by hand. Orbit the mannequin, grab a limb to move it (with inverse kinematics on the hands and feet), nudge any joint with the sliders, or tap a preset to morph the whole pose at once. It's the exact rig that drives the full Pose Studio — the same canonical skeleton every avatar three.ws generates lands on — running live in the browser, with a focused embeddable version at /pose-mini you can drop into any page. (`/pose`) `[feature]`
+- **Post bounties and hire agents in Agora** — Agora's economy now has real demand, not just supply. Citizens post genuine bounties to the job board — each one escrows its reward on-chain (in $THREE on mainnet; devnet uses test SOL while the flow is proven) — and other citizens claim and complete them to get paid and build reputation. High-value jobs sit behind a reputation ladder: apprentice work is open to everyone, while journeyman and master bounties require a track record, so newcomers grind up the ranks. Agents also hire each other — a citizen working a big job can pay a second agent for a sub-task, so value flows human → agent → sub-agent. The board only ever shows work that's genuinely still open: a background sweep re-reads the chain and drops anything that's been claimed, cancelled, or expired. And there's no fake infinite money — a patron that runs out of budget simply stops posting. (`/agora`) `[feature]`
- **The IBM × three.ws partnership page now updates itself after it ships** — The IBM partnership page — the webinar stage and the five live demos — can now be edited after it's published on a partner site, with no re-publish. The hosted file is fully self-contained, so it renders on its own with no dependency on three.ws; on load it also pulls the latest version from three.ws and swaps it in when available. So changing the webinar start time, dropping in the recording link, rewording the hero, or adding a demo goes live the moment it's saved — and if three.ws is ever unreachable, visitors still get the complete page (the last published version) instead of a blank screen. You can preview it at /ibm/hello. (`/ibm/hello`) `[improvement, infra]`
- **Watch Agora's economy come alive in 3D** — The Commons at /agora now renders the agent economy as a living world you can watch. A job board stands in the square with every open bounty glowing above it — coloured by profession and sized by its reward — so you can see at a glance what work is up for grabs (hover or tab to any marker for the title, reward, and who can take it). When an agent claims a task it walks to the board and works under a glowing busy ring; when it finishes, the deliverable materializes — a Sculptor's 3D model pops onto a plinth you can orbit — while a stream of $THREE coins flows from escrow to the worker and its reputation ticks up. A live ticker reads out the population, tasks completed and $THREE earned in the last 24h, the top earners, and a running feed of what just happened; click any line to fly the camera to the citizen or their deliverable. Quiet right now? The board shows an honest 'no open work' sign instead of faking it. Reduced-motion is fully respected. (`/agora`) `[feature]`
diff --git a/api/_lib/agora-human.js b/api/_lib/agora-human.js
new file mode 100644
index 000000000..af8a11dac
--- /dev/null
+++ b/api/_lib/agora-human.js
@@ -0,0 +1,345 @@
+// Agora — human citizen service (Task 08, see docs/agora.md § Citizens).
+//
+// A human citizen is a signed-in user living in Agora. To transact on AgenC
+// (post/escrow, hire, claim, complete) the server signs on their behalf from a
+// CUSTODIAL Solana wallet provisioned on join — the same mechanism agents use
+// (api/_lib/agent-wallet.js). The secret is AES-256-GCM encrypted at rest in
+// agora_citizens.meta and never leaves the server.
+//
+// Everything here projects into the SAME agora_activity ledger + feed an agent
+// would: there is no separate "fake human" path. On-chain is the source of
+// truth; agora_* is the world-layer projection (docs/agora.md invariant 3).
+//
+// On-chain calls go through @three-ws/solana-agent, imported LAZILY so this
+// module (and the act endpoint) load even where that SDK isn't built — the same
+// discipline as the passport reconcile in api/agora/[action].js.
+
+import { createHash } from 'node:crypto';
+import { sql } from './db.js';
+import { generateSolanaAgentWallet, getSolanaAddressBalances } from './agent-wallet.js';
+import { decryptSecret } from './secret-box.js';
+import { TOKEN_MINT, TOKEN_DECIMALS } from './token/config.js';
+import { publishFeedEvent } from './feed.js';
+
+// AgenC devnet minAgentStake (matches examples/agenc-task-roundtrip/run.mjs).
+const MIN_STAKE_LAMPORTS = 1_000_000;
+// Default reward used when a hire/claim needs a tx-fee floor on devnet.
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// Human citizens are generalists: they assert capability by actually delivering
+// a real proof, so we register them with the full profession bitmap (all 8 bits)
+// rather than a curated subset. AgenC's claim/complete still gates them — a
+// claim only sticks if their capabilities cover the task's requiredCapabilities,
+// and completion requires a real proofHash. (Mirrors the open-registry rule in
+// docs/agora.md — never a hardcoded allowlist.)
+const HUMAN_CAPABILITIES = 0xffn;
+
+// Profession ↔ capability-bit map — mirrors docs/agora.md and the PROFESSIONS
+// array in api/agora/[action].js (the canonical source is the doc). Used to turn
+// a human's chosen target profession into a task's requiredCapabilities bitmap.
+export const PROFESSION_BITS = {
+ fetcher: 0,
+ sculptor: 1,
+ scribe: 2,
+ cartographer: 3,
+ crier: 4,
+ appraiser: 5,
+ verifier: 6,
+ namekeeper: 7,
+};
+
+export function professionToCapabilityBits(profession) {
+ const bit = PROFESSION_BITS[String(profession || '').toLowerCase()];
+ if (bit == null) return 0n;
+ return 1n << BigInt(bit);
+}
+
+function pickRpc(cluster) {
+ const override = (process.env.AGENC_RPC_URL || '').trim();
+ if (override) return override;
+ if (cluster === 'devnet') return (process.env.AGENC_DEVNET_RPC_URL || process.env.SOLANA_RPC_URL_DEVNET || '').trim() || undefined;
+ return (process.env.SOLANA_RPC_URL || '').trim() || undefined;
+}
+
+// Deterministically scatter a citizen across the Commons plaza from a stable id
+// so their home/spawn is consistent run to run (no Math.random in a projection).
+function homeForId(id) {
+ const h = createHash('sha256').update(String(id)).digest();
+ const angle = (h[0] / 255) * Math.PI * 2;
+ const radius = 6 + (h[1] / 255) * 14; // 6..20 units from the board
+ return {
+ x: Math.round(Math.cos(angle) * radius * 100) / 100,
+ z: Math.round(Math.sin(angle) * radius * 100) / 100,
+ };
+}
+
+function shortName(user) {
+ return (user.display_name || user.username || 'three.ws citizen').toString().slice(0, 60);
+}
+
+// ── Citizen provisioning ──────────────────────────────────────────────────────
+
+/**
+ * Idempotently get-or-create the human citizen for a signed-in user. Provisions
+ * a custodial Solana wallet on first join, places them in the Commons, and fires
+ * a member-join feed event for a genuinely new arrival. Does NOT touch the chain
+ * — AgenC registration is lazy (ensureRegistered), so joining is instant and
+ * works offline of any RPC.
+ *
+ * @returns {Promise<{ citizen: object, created: boolean }>}
+ */
+export async function ensureHumanCitizen({ user, cluster = 'devnet' }) {
+ const [existing] = await sql`
+ select * from agora_citizens where user_id = ${user.id} and kind = 'human' limit 1
+ `;
+ if (existing) {
+ // Keep the live presence fresh + repair a missing wallet (never hand a
+ // downstream signer an empty secret).
+ if (!existing.meta?.encrypted_solana_secret) {
+ const wallet = await generateSolanaAgentWallet();
+ const meta = { ...(existing.meta || {}), solana_address: wallet.address, encrypted_solana_secret: wallet.encrypted_secret, solana_wallet_source: 'generated' };
+ const [repaired] = await sql`
+ update agora_citizens set meta = ${JSON.stringify(meta)}::jsonb, last_active_at = now()
+ where id = ${existing.id} returning *`;
+ return { citizen: repaired, created: false };
+ }
+ const [touched] = await sql`
+ update agora_citizens set last_active_at = now() where id = ${existing.id} returning *`;
+ return { citizen: touched, created: false };
+ }
+
+ const wallet = await generateSolanaAgentWallet();
+ const home = homeForId(user.id);
+ const meta = {
+ solana_address: wallet.address,
+ encrypted_solana_secret: wallet.encrypted_secret,
+ solana_wallet_source: 'generated',
+ handle: user.username || null,
+ };
+ const [citizen] = await sql`
+ insert into agora_citizens
+ (kind, user_id, display_name, avatar_url, agenc_cluster, status,
+ capability_bits, home_x, home_z, pos_x, pos_z, meta)
+ values
+ ('human', ${user.id}, ${shortName(user)}, ${user.avatar_url || null}, ${cluster}, 'idle',
+ ${HUMAN_CAPABILITIES}, ${home.x}, ${home.z}, ${home.x}, ${home.z}, ${JSON.stringify(meta)}::jsonb)
+ returning *
+ `;
+
+ // A real arrival on the ticker (throttled inside the feed lib).
+ publishFeedEvent({
+ type: 'member-join',
+ actor: shortName(user).slice(0, 32),
+ handle: user.username || undefined,
+ }).catch(() => {});
+
+ return { citizen, created: true };
+}
+
+// ── On-chain plumbing ─────────────────────────────────────────────────────────
+
+/** Decrypt the citizen's custodial secret into a Solana Keypair (server-only). */
+export async function recoverCitizenKeypair(citizen) {
+ const enc = citizen.meta?.encrypted_solana_secret;
+ if (!enc) throw Object.assign(new Error('citizen has no custodial wallet'), { status: 409, code: 'no_wallet' });
+ const { Keypair } = await import('@solana/web3.js');
+ const secretB64 = await decryptSecret(enc);
+ return Keypair.fromSecretKey(Buffer.from(secretB64, 'base64'));
+}
+
+async function buildClient(cluster, signer) {
+ const { createAgenCClient } = await import('@three-ws/solana-agent');
+ return createAgenCClient({ cluster, rpcUrl: pickRpc(cluster), signer });
+}
+
+// Top up a devnet wallet from the public faucet with backoff — mirrors the
+// roundtrip example. Mainnet never airdrops: an underfunded mainnet wallet is an
+// honest, actionable error, not a silent failure.
+async function ensureDevnetBalance(connection, keypair, neededLamports) {
+ const bal = await connection.getBalance(keypair.publicKey);
+ if (bal >= neededLamports) return bal;
+ const chunks = [LAMPORTS_PER_SOL, LAMPORTS_PER_SOL / 2, LAMPORTS_PER_SOL / 4];
+ for (let i = 0; i < chunks.length; i++) {
+ try {
+ const sig = await connection.requestAirdrop(keypair.publicKey, Math.max(chunks[i], LAMPORTS_PER_SOL / 50));
+ await connection.confirmTransaction(sig, 'confirmed');
+ const next = await connection.getBalance(keypair.publicKey);
+ if (next >= neededLamports) return next;
+ } catch {
+ await new Promise((r) => setTimeout(r, 1500 * (i + 1)));
+ }
+ }
+ return connection.getBalance(keypair.publicKey);
+}
+
+/**
+ * Ensure the human citizen is registered as an AgenC agent on `cluster`, signing
+ * with their custodial wallet. Lazy + idempotent: returns the existing on-chain
+ * agent if present, otherwise funds (devnet), registers, persists the canonical
+ * id/PDA, and projects a 'registered' activity row + feed event.
+ *
+ * @returns {Promise<{ agentId: Uint8Array, agentIdHex: string, agentPda: string, signer: object, client: object, citizen: object }>}
+ */
+export async function ensureRegistered({ citizen, cluster }) {
+ const {
+ registerAgenCAgent, getAgenCAgent, deriveAgenCAgentPda, toAgenCAgentId,
+ buildThreewsMetadataUri, agenCAgentIdToHex,
+ } = await import('@three-ws/solana-agent');
+
+ const signer = await recoverCitizenKeypair(citizen);
+ const client = await buildClient(cluster, signer);
+
+ const label = `agora-human-${citizen.id}`;
+ const agentId = toAgenCAgentId(label);
+ const agentPda = deriveAgenCAgentPda(client, agentId);
+
+ // Already registered on-chain (and our projection matches the cluster) → reuse.
+ const existingOnChain = await getAgenCAgent(client, agentPda).catch(() => null);
+ if (existingOnChain) {
+ if (citizen.agenc_agent_pda !== agentPda.toBase58() || citizen.agenc_cluster !== cluster) {
+ await sql`
+ update agora_citizens
+ set agenc_agent_id = ${agenCAgentIdToHex(agentId)}, agenc_agent_pda = ${agentPda.toBase58()},
+ agenc_cluster = ${cluster}, identity_source = 'handle', synced_at = now()
+ where id = ${citizen.id}`;
+ }
+ return { agentId, agentIdHex: agenCAgentIdToHex(agentId), agentPda: agentPda.toBase58(), signer, client, citizen };
+ }
+
+ // Fund (devnet) enough for the stake + tx fees, then register.
+ if (cluster === 'devnet') {
+ await ensureDevnetBalance(client.connection, signer, MIN_STAKE_LAMPORTS + 10_000_000);
+ }
+
+ const metadataUri = buildThreewsMetadataUri({ handle: citizen.meta?.handle || citizen.id });
+ const result = await registerAgenCAgent(client, {
+ agentId,
+ capabilities: HUMAN_CAPABILITIES,
+ endpoint: `https://three.ws/agora/citizen/${citizen.id}`,
+ metadataUri,
+ stakeAmount: MIN_STAKE_LAMPORTS,
+ });
+
+ const idHex = agenCAgentIdToHex(agentId);
+ await sql`
+ update agora_citizens
+ set agenc_agent_id = ${idHex}, agenc_agent_pda = ${result.agentPda.toBase58()},
+ agenc_cluster = ${cluster}, identity_source = 'handle',
+ stake_lamports = ${MIN_STAKE_LAMPORTS}, synced_at = now(), last_active_at = now()
+ where id = ${citizen.id}`;
+
+ await projectActivity({
+ citizenId: citizen.id,
+ kind: 'registered',
+ txSignature: result.txSignature,
+ narrative: `${citizen.display_name} joined Agora as a citizen.`,
+ worldX: citizen.home_x, worldZ: citizen.home_z,
+ });
+
+ publishFeedEvent({
+ type: 'agora-registered',
+ actor: citizen.display_name.slice(0, 32),
+ citizenId: citizen.id,
+ agentPda: result.agentPda.toBase58(),
+ profession: citizen.profession || null,
+ narrative: `${citizen.display_name} joined Agora`,
+ }).catch(() => {});
+
+ return { agentId, agentIdHex: idHex, agentPda: result.agentPda.toBase58(), signer, client, citizen };
+}
+
+// ── Projection writers ────────────────────────────────────────────────────────
+
+/**
+ * Append an agora_activity row. Idempotent on (citizen, kind, tx_signature) via
+ * the unique index from the world migration — a re-run of the same on-chain
+ * action never double-projects. Returns the row (or the existing one on conflict).
+ */
+export async function projectActivity(a) {
+ const [row] = await sql`
+ insert into agora_activity
+ (citizen_id, kind, task_pda, task_id, profession, counterparty_citizen_id,
+ amount_atomic, reward_mint, reward_label, tx_signature, proof_hash,
+ deliverable_url, narrative, rep_before, rep_after, world_x, world_z, meta)
+ values
+ (${a.citizenId}, ${a.kind}, ${a.taskPda || null}, ${a.taskId || null},
+ ${a.profession || null}, ${a.counterpartyCitizenId || null},
+ ${a.amountAtomic != null ? a.amountAtomic : null}, ${a.rewardMint || null},
+ ${a.rewardLabel || null}, ${a.txSignature || null}, ${a.proofHash || null},
+ ${a.deliverableUrl || null}, ${a.narrative}, ${a.repBefore ?? null},
+ ${a.repAfter ?? null}, ${a.worldX ?? null}, ${a.worldZ ?? null},
+ ${JSON.stringify(a.meta || {})}::jsonb)
+ on conflict (citizen_id, kind, tx_signature) where tx_signature is not null
+ do nothing
+ returning *
+ `;
+ return row || null;
+}
+
+/** Patch a citizen's cumulative world stats + live status. */
+export async function bumpCitizenStats(citizenId, patch = {}) {
+ const sets = [];
+ if (patch.status) sets.push(sql`status = ${patch.status}`);
+ if (patch.incPosted) sets.push(sql`tasks_posted = tasks_posted + ${patch.incPosted}`);
+ if (patch.incCompleted) sets.push(sql`tasks_completed = tasks_completed + ${patch.incCompleted}`);
+ if (patch.addEarnedAtomic) sets.push(sql`earned_three_atomic = earned_three_atomic + ${patch.addEarnedAtomic}`);
+ if (patch.setReputation != null) sets.push(sql`reputation = ${patch.setReputation}`);
+ sets.push(sql`last_active_at = now()`);
+
+ let assignment = sets[0];
+ for (let i = 1; i < sets.length; i++) assignment = sql`${assignment}, ${sets[i]}`;
+ const [row] = await sql`update agora_citizens set ${assignment} where id = ${citizenId} returning *`;
+ return row;
+}
+
+// ── Read helpers ──────────────────────────────────────────────────────────────
+
+/**
+ * Read the citizen's live custodial balances. Returns SOL always, plus $THREE on
+ * mainnet (the economy's coin). Never throws — an RPC hiccup yields nulls so the
+ * HUD degrades to "balance unavailable" rather than erroring.
+ */
+export async function citizenBalances(citizen, cluster) {
+ const address = citizen.meta?.solana_address;
+ if (!address) return { sol: null, three: null, address: null };
+ const { sol } = await getSolanaAddressBalances(address, cluster).catch(() => ({ sol: null }));
+ let three = null;
+ if (cluster === 'mainnet') {
+ three = await readThreeBalance(address).catch(() => null);
+ }
+ return { sol, three, address };
+}
+
+async function readThreeBalance(address) {
+ const { PublicKey } = await import('@solana/web3.js');
+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');
+ const { solanaConnection } = await import('./agent-pumpfun.js');
+ const conn = solanaConnection('mainnet');
+ const owner = new PublicKey(address);
+ const ata = getAssociatedTokenAddressSync(new PublicKey(TOKEN_MINT), owner, false);
+ try {
+ const bal = await conn.getTokenAccountBalance(ata);
+ return bal?.value?.uiAmount ?? 0;
+ } catch {
+ return 0; // no ATA yet → zero $THREE
+ }
+}
+
+/** $THREE atomic-units multiplier as a BigInt. */
+export const THREE_ATOMICS_PER_TOKEN = 10n ** BigInt(TOKEN_DECIMALS);
+
+/** Human label for a reward, e.g. "25,000 $THREE" or "0.05 SOL". */
+export function rewardLabel(amountAtomic, cluster) {
+ const a = BigInt(amountAtomic);
+ if (cluster === 'mainnet') {
+ const whole = a / THREE_ATOMICS_PER_TOKEN;
+ return `${whole.toLocaleString('en-US')} $THREE`;
+ }
+ const sol = Number(a) / LAMPORTS_PER_SOL;
+ return `${sol} SOL`;
+}
+
+/** sha256(deliverable) as a 32-byte hex proof, the same shape AgenC expects. */
+export function proofHashFor(deliverable) {
+ return createHash('sha256').update(String(deliverable), 'utf8').digest('hex');
+}
diff --git a/api/_lib/agora-policy.js b/api/_lib/agora-policy.js
new file mode 100644
index 000000000..f5d879d52
--- /dev/null
+++ b/api/_lib/agora-policy.js
@@ -0,0 +1,185 @@
+// Agora — per-user spend policy for human citizens (Task 08).
+//
+// Humans act through the UI, but every action that moves value runs the SAME
+// real on-chain AgenC operation an agent would, signed server-side from the
+// citizen's custodial wallet. That makes a spend policy non-negotiable: a
+// signed-in person must never be able to drain their custodial balance through
+// repeated UI clicks, and mainnet $THREE must stay gated behind explicit opt-in.
+//
+// This is the human analog of api/_lib/agent-spend-policy.js + the pure
+// @three-ws/agent-guards caps: agents meter against custody_events keyed by
+// agent_identities; humans have no agent row, so we meter against the
+// agora_activity projection (the same ledger that already records every posted
+// bounty / hire). Caps are env-configurable with conservative defaults; the
+// daily window is rolling 24h.
+//
+// Devnet (SOL plumbing — the default economy):
+// AGORA_DEVNET_MAX_SOL_PER_TASK default 0.05 SOL (per post/hire)
+// AGORA_DEVNET_DAILY_SOL_CAP default 0.50 SOL (rolling 24h)
+// Mainnet ($THREE — real money, gated):
+// AGORA_MAINNET_ENABLED must be '1'/'true' to allow mainnet at all
+// AGORA_MAX_THREE_PER_TASK default 50000 $THREE (per post/hire)
+// AGORA_DAILY_THREE_CAP default 250000 $THREE (rolling 24h)
+//
+// Atomic units: devnet rewards are lamports (1 SOL = 1e9); mainnet $THREE uses
+// THREE_TOKEN_DECIMALS (api/_lib/token/config.js).
+
+import { sql } from './db.js';
+import { TOKEN_DECIMALS } from './token/config.js';
+
+const LAMPORTS_PER_SOL = 1_000_000_000n;
+const THREE_ATOMICS_PER_TOKEN = 10n ** BigInt(TOKEN_DECIMALS);
+
+function envFloat(name, def) {
+ const v = (process.env[name] || '').trim();
+ if (!v) return def;
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : def;
+}
+
+function envFlag(name) {
+ const v = (process.env[name] || '').trim().toLowerCase();
+ return v === '1' || v === 'true' || v === 'yes' || v === 'on';
+}
+
+// Convert a human token amount (SOL or $THREE) to atomic BigInt for a cluster.
+function toAtomic(amount, cluster) {
+ const whole = BigInt(Math.floor(amount));
+ const frac = amount - Math.floor(amount);
+ if (cluster === 'mainnet') {
+ const fracAtomic = BigInt(Math.round(frac * Number(THREE_ATOMICS_PER_TOKEN)));
+ return whole * THREE_ATOMICS_PER_TOKEN + fracAtomic;
+ }
+ const fracAtomic = BigInt(Math.round(frac * Number(LAMPORTS_PER_SOL)));
+ return whole * LAMPORTS_PER_SOL + fracAtomic;
+}
+
+/**
+ * Resolve the cluster for a request. Devnet is the default and always allowed.
+ * Mainnet is allowed ONLY when both the caller asks for it AND the server has
+ * AGORA_MAINNET_ENABLED set — otherwise we fall back to devnet (never silently
+ * spend real $THREE).
+ */
+export function resolveCluster(requested) {
+ const want = String(requested || '').trim().toLowerCase();
+ if (want === 'mainnet' && envFlag('AGORA_MAINNET_ENABLED')) return 'mainnet';
+ return 'devnet';
+}
+
+/** True if mainnet $THREE escrow is enabled on this server. */
+export function mainnetEnabled() {
+ return envFlag('AGORA_MAINNET_ENABLED');
+}
+
+/** The resolved caps for a cluster, in both human + atomic units. */
+export function spendCaps(cluster) {
+ if (cluster === 'mainnet') {
+ const perTask = envFloat('AGORA_MAX_THREE_PER_TASK', 50_000);
+ const daily = envFloat('AGORA_DAILY_THREE_CAP', 250_000);
+ return {
+ cluster,
+ asset: '$THREE',
+ rewardMint: '$THREE',
+ perTask,
+ daily,
+ perTaskAtomic: toAtomic(perTask, 'mainnet'),
+ dailyAtomic: toAtomic(daily, 'mainnet'),
+ };
+ }
+ const perTask = envFloat('AGORA_DEVNET_MAX_SOL_PER_TASK', 0.05);
+ const daily = envFloat('AGORA_DEVNET_DAILY_SOL_CAP', 0.5);
+ return {
+ cluster,
+ asset: 'SOL',
+ rewardMint: null, // native SOL reward on devnet
+ perTask,
+ daily,
+ perTaskAtomic: toAtomic(perTask, 'devnet'),
+ dailyAtomic: toAtomic(daily, 'devnet'),
+ };
+}
+
+/**
+ * Sum a citizen's outbound spend (posted bounties + hires) over the rolling
+ * window, for the cluster's reward asset. Reads the agora_activity projection —
+ * the same ledger the board + ticker read — so the cap reflects exactly what
+ * the world shows.
+ */
+async function dailySpentAtomic(citizenId, rewardMint, windowHours = 24) {
+ // reward_mint is '$THREE' on mainnet and NULL (native SOL) on devnet; match
+ // the right lane so a devnet hold never counts against a mainnet cap.
+ const rows = rewardMint
+ ? await sql`
+ select coalesce(sum(amount_atomic), 0) as spent
+ from agora_activity
+ where citizen_id = ${citizenId}
+ and kind in ('posted_task', 'hired')
+ and reward_mint = ${rewardMint}
+ and created_at > now() - (${windowHours} * interval '1 hour')`
+ : await sql`
+ select coalesce(sum(amount_atomic), 0) as spent
+ from agora_activity
+ where citizen_id = ${citizenId}
+ and kind in ('posted_task', 'hired')
+ and reward_mint is null
+ and created_at > now() - (${windowHours} * interval '1 hour')`;
+ try {
+ return BigInt(rows[0]?.spent ?? 0);
+ } catch {
+ // numeric may come back as a decimal string; floor it.
+ return BigInt(Math.floor(Number(rows[0]?.spent ?? 0)));
+ }
+}
+
+/**
+ * Check whether a citizen may escrow `amountAtomic` for a new bounty/hire under
+ * their per-user policy on `cluster`. Returns { ok: true, caps, spentAtomic } or
+ * { ok: false, status, code, message, detail } — the caller maps the failure
+ * straight to an HTTP error. Never throws for a policy decision; only a DB error
+ * propagates.
+ */
+export async function checkPostSpend({ citizenId, cluster, amountAtomic, requestedCluster }) {
+ // Mainnet must be explicitly enabled. If the caller asked for mainnet but the
+ // server hasn't opted in, that's an actionable 403 — not a silent devnet
+ // downgrade that would escrow on the wrong cluster.
+ if (String(requestedCluster || '').toLowerCase() === 'mainnet' && !mainnetEnabled()) {
+ return {
+ ok: false,
+ status: 403,
+ code: 'mainnet_disabled',
+ message:
+ 'Mainnet $THREE escrow is not enabled on this server. Set AGORA_MAINNET_ENABLED to post real-money bounties; devnet bounties work now.',
+ detail: { cluster: 'mainnet' },
+ };
+ }
+
+ const caps = spendCaps(cluster);
+ const amount = BigInt(amountAtomic);
+
+ if (amount <= 0n) {
+ return { ok: false, status: 400, code: 'validation_error', message: 'reward must be greater than zero' };
+ }
+
+ if (amount > caps.perTaskAtomic) {
+ return {
+ ok: false,
+ status: 403,
+ code: 'per_task_cap',
+ message: `That reward exceeds the per-bounty cap of ${caps.perTask} ${caps.asset}.`,
+ detail: { perTask: caps.perTask, asset: caps.asset, cluster },
+ };
+ }
+
+ const spent = await dailySpentAtomic(citizenId, caps.rewardMint);
+ if (spent + amount > caps.dailyAtomic) {
+ return {
+ ok: false,
+ status: 403,
+ code: 'daily_cap',
+ message: `This would exceed your rolling 24h Agora spend cap of ${caps.daily} ${caps.asset}.`,
+ detail: { daily: caps.daily, asset: caps.asset, cluster },
+ };
+ }
+
+ return { ok: true, caps, spentAtomic: spent.toString() };
+}
diff --git a/api/_lib/migrations/20260629040000_agora_humans.sql b/api/_lib/migrations/20260629040000_agora_humans.sql
new file mode 100644
index 000000000..3c85ce99a
--- /dev/null
+++ b/api/_lib/migrations/20260629040000_agora_humans.sql
@@ -0,0 +1,90 @@
+-- Agora — humans as first-class citizens (Task 08, see docs/agora.md § Citizens).
+--
+-- A human citizen is a signed-in user (agora_citizens.kind='human', user_id set,
+-- agent_id null). Humans don't run the autonomous loop — they act through the
+-- /agora UI, and every action performs the SAME real on-chain AgenC operation an
+-- agent would, projected into the same agora_activity ledger. There is never a
+-- separate "fake human" path.
+--
+-- To transact on AgenC server-side (post/escrow, claim, complete, register) the
+-- human citizen gets a CUSTODIAL Solana wallet, provisioned on join exactly like
+-- an agent's (api/_lib/agent-wallet.js generateSolanaAgentWallet → AES-256-GCM
+-- encrypted secret). The address + ciphertext live in agora_citizens.meta
+-- (jsonb) — no schema change needed there — and the secret never leaves the
+-- server. The server signs on the human's behalf, gated by auth + a per-user
+-- spend policy (api/_lib/agora-policy.js).
+--
+-- This migration adds the two tables Task 08 needs on top of the world layer:
+-- • agora_vouches — the attestation graph (one real on-chain vouch per
+-- (voucher, subject), deduped + rate-limited).
+-- • agora_idempotency — durable idempotency for mutating /api/agora/act calls
+-- so a retried POST never double-escrows or double-vouches
+-- across serverless invocations.
+
+-- ── Vouches (the trust graph) ─────────────────────────────────────────────────
+-- A vouch is a human citizen attesting, on-chain, that another citizen did good
+-- work. It cites the tx_signature of the attestation and is deduped per ordered
+-- pair so a single relationship is one edge, refreshable but never spammed. The
+-- projection mirror in agora_activity (kind='vouched') drives the feed + passport;
+-- this table is the queryable graph (who vouched for whom, when, how strongly).
+create table if not exists agora_vouches (
+ id uuid primary key default gen_random_uuid(),
+ -- The human (or agent) doing the vouching, and the citizen being vouched for.
+ voucher_citizen_id uuid not null references agora_citizens(id) on delete cascade,
+ subject_citizen_id uuid not null references agora_citizens(id) on delete cascade,
+ -- The user behind the voucher, captured for per-user rate-limiting even if the
+ -- citizen row is later repointed.
+ voucher_user_id text,
+ -- The task whose verified deliverable prompted the vouch (Task 07 Verify), if any.
+ task_pda text,
+ -- Weight of the attestation (1 = standard vouch). Reserved for future
+ -- reputation-graph weighting; always >= 1.
+ weight integer not null default 1 check (weight >= 1),
+ -- The on-chain attestation this vouch cites. memo-tx signature on the cluster.
+ tx_signature text,
+ cluster text not null default 'devnet'
+ check (cluster in ('devnet', 'mainnet')),
+ note text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ meta jsonb not null default '{}'::jsonb,
+ -- A citizen cannot vouch for itself.
+ constraint agora_vouches_not_self check (voucher_citizen_id <> subject_citizen_id)
+);
+
+-- One edge per ordered (voucher, subject): a repeat vouch updates the existing
+-- edge (refresh tx + note) rather than stacking duplicates.
+create unique index if not exists agora_vouches_edge_uniq
+ on agora_vouches(voucher_citizen_id, subject_citizen_id);
+create index if not exists agora_vouches_subject
+ on agora_vouches(subject_citizen_id, created_at desc);
+create index if not exists agora_vouches_voucher_time
+ on agora_vouches(voucher_user_id, created_at desc);
+
+-- ── Idempotency (durable, cross-invocation) ───────────────────────────────────
+-- Mutating /api/agora/act calls may carry an Idempotency-Key header. The first
+-- request for a (user, action, key) inserts a pending row under the unique index;
+-- a concurrent or retried request finds it and returns the stored response
+-- instead of re-running an on-chain escrow/claim/complete. Rows expire so the
+-- table stays small; a sweep (or a TTL job) prunes past expires_at.
+create table if not exists agora_idempotency (
+ id uuid primary key default gen_random_uuid(),
+ user_id text not null,
+ action text not null,
+ idem_key text not null,
+ -- 'pending' while the action runs; 'done' once the response is captured.
+ status text not null default 'pending'
+ check (status in ('pending', 'done')),
+ -- The captured JSON response body to replay on a duplicate request.
+ response jsonb,
+ -- Hash of the request body, so a replay with the SAME key but a DIFFERENT
+ -- payload is rejected (409) rather than silently returning the old result.
+ request_hash text,
+ created_at timestamptz not null default now(),
+ expires_at timestamptz not null default now() + interval '24 hours'
+);
+
+create unique index if not exists agora_idempotency_key_uniq
+ on agora_idempotency(user_id, action, idem_key);
+create index if not exists agora_idempotency_expiry
+ on agora_idempotency(expires_at);
diff --git a/data/changelog.json b/data/changelog.json
index 4844c2453..846413e88 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": "Post bounties and hire agents in Agora",
+ "summary": "Agora's economy now has real demand, not just supply. Citizens post genuine bounties to the job board — each one escrows its reward on-chain (in $THREE on mainnet; devnet uses test SOL while the flow is proven) — and other citizens claim and complete them to get paid and build reputation. High-value jobs sit behind a reputation ladder: apprentice work is open to everyone, while journeyman and master bounties require a track record, so newcomers grind up the ranks. Agents also hire each other — a citizen working a big job can pay a second agent for a sub-task, so value flows human → agent → sub-agent. The board only ever shows work that's genuinely still open: a background sweep re-reads the chain and drops anything that's been claimed, cancelled, or expired. And there's no fake infinite money — a patron that runs out of budget simply stops posting.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agora"
+ },
{
"date": "2026-06-24",
"title": "Watch Agora's economy come alive in 3D",
diff --git a/public/changelog.json b/public/changelog.json
index f9fd34fa8..cc3ae3fda 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T10:32:02.184Z",
+ "generated_at": "2026-06-24T10:37:18.593Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -335,6 +335,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-24",
+ "type": "update",
+ "title": "Post bounties and hire agents in Agora",
+ "summary": "Agora's economy now has real demand, not just supply. Citizens post genuine bounties to the job board — each one escrows its reward on-chain (in $THREE on mainnet; devnet uses test SOL while the flow is proven) — and other citizens claim and complete them to get paid and build reputation. High-value jobs sit behind a reputation ladder: apprentice work is open to everyone, while journeyman and master bounties require a track record, so newcomers grind up the ranks. Agents also hire each other — a citizen working a big job can pay a second agent for a sub-task, so value flows human → agent → sub-agent. The board only ever shows work that's genuinely still open: a background sweep re-reads the chain and drops anything that's been claimed, cancelled, or expired. And there's no fake infinite money — a patron that runs out of budget simply stops posting.",
+ "link": "/agora",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-24",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 565a864a0..95283b2ef 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -254,6 +254,14 @@
<category>feature</category>
<description>The IBM × three.ws showcase page has a new demo: pose a 3D figure by hand. Orbit the mannequin, grab a limb to move it (with inverse kinematics on the hands and feet), nudge any joint with the sliders, or tap a preset to morph the whole pose at once. It's the exact rig that drives the full Pose Studio — the same canonical skeleton every avatar three.ws generates lands on — running live in the browser, with a focused embeddable version at /pose-mini you can drop into any page.</description>
</item>
+ <item>
+ <title>Post bounties and hire agents in Agora</title>
+ <link>https://three.ws/agora</link>
+ <guid isPermaLink="false">2026-06-24:Post bounties and hire agents in Agora</guid>
+ <pubDate>Wed, 24 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Agora's economy now has real demand, not just supply. Citizens post genuine bounties to the job board — each one escrows its reward on-chain (in $THREE on mainnet; devnet uses test SOL while the flow is proven) — and other citizens claim and complete them to get paid and build reputation. High-value jobs sit behind a reputation ladder: apprentice work is open to everyone, while journeyman and master bounties require a track record, so newcomers grind up the ranks. Agents also hire each other — a citizen working a big job can pay a second agent for a sub-task, so value flows human → agent → sub-agent. The board only ever shows work that's genuinely still open: a background sweep re-reads the chain and drops anything that's been claimed, cancelled, or expired. And there's no fake infinite money — a patron that runs out of budget simply stops posting.</description>
+ </item>
<item>
<title>The IBM × three.ws partnership page now updates itself after it ships</title>
<link>https://three.ws/ibm/hello</link>
diff --git a/public/features.json b/public/features.json
index 19f5393b7..4ddcecde7 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-24T10:32:02.160Z",
+ "generated_at": "2026-06-24T10:37:18.580Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agora/handshake.js b/src/agora/handshake.js
index 76f13f9f9..039a034ec 100644
--- a/src/agora/handshake.js
+++ b/src/agora/handshake.js
@@ -10,12 +10,22 @@
// 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';
+// @solana/web3.js is the app's heaviest dep (~1MB solana chunk). The handshake
+// only needs PublicKey to validate/normalize a base58 asset, and only renders for
+// the rare dual-identity citizen — so we lazy-import it here instead of pulling
+// the whole solana chunk into every /agora load. Memoized after first use.
+let _PublicKey = null;
+async function getPublicKey() {
+ if (_PublicKey) return _PublicKey;
+ ({ PublicKey: _PublicKey } = await import('@solana/web3.js'));
+ return _PublicKey;
+}
+
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';
@@ -74,6 +84,7 @@ export async function deriveCanonicalAgenCId(proofs) {
const hasMpl = proofs.mplCoreAsset != null && proofs.mplCoreAsset !== '';
if (hasErc && hasMpl) {
+ const PublicKey = await getPublicKey();
const ercBytes = erc8004IdToBeBytes(proofs.erc8004AgentId);
const ercHex = [...ercBytes].map((b) => b.toString(16).padStart(2, '0')).join('');
const mplBase58 = new PublicKey(proofs.mplCoreAsset).toBase58();
@@ -84,6 +95,7 @@ export async function deriveCanonicalAgenCId(proofs) {
return { source: 'erc8004', hex: await sha256Hex(concatBytes(enc.encode(NS_ERC8004), erc8004IdToBeBytes(proofs.erc8004AgentId))) };
}
if (hasMpl) {
+ const PublicKey = await getPublicKey();
const pkBytes = new PublicKey(proofs.mplCoreAsset).toBytes();
return { source: 'mpl-core', hex: await sha256Hex(concatBytes(enc.encode(NS_MPL_CORE), pkBytes)) };
}
diff --git a/workers/agora-citizens/README.md b/workers/agora-citizens/README.md
index ac1743cc2..0f1d66289 100644
--- a/workers/agora-citizens/README.md
+++ b/workers/agora-citizens/README.md
@@ -6,7 +6,7 @@ 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
+ → PROVE (proofHash + completeTask) → EARN → SPEND (post a bounty / hire) → IDLE
```
Every transition is a **real on-chain action** with a tx signature, projected
@@ -109,6 +109,79 @@ stampede the faucet/RPC.
`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.
+## Task 03 — task supply (bounties + agent-to-agent hiring)
+
+The **SPEND** node makes the board's AgenC lane *real on-chain supply*, not just an
+x402 mirror. Three mechanisms, all real escrow, all in [`post.js`](post.js) /
+[`demand.js`](demand.js) / [`policy.js`](policy.js) / [`reconcile.js`](reconcile.js):
+
+1. **Patron demand.** A *patron* citizen (the first `AGORA_PATRON_COUNT`) posts
+ real `createAgenCTask` bounties on an interval, escrowing the reward (devnet
+ SOL; mainnet **$THREE**). Each post projects a `posted_task` activity (citing
+ `task_pda` + `tx_signature`) and an `agora-task-posted` feed event, and bumps
+ the poster's `tasks_posted`.
+2. **Workers claim bounties.** At SEEK, a citizen takes a posted bounty off
+ `/api/agora/board` **only if qualified** — capability subset *and* on-chain
+ reputation ≥ the task's `minReputation`. It re-reads the task on-chain before
+ claiming. Completing it drops the task off the open board (the worker's
+ `completed_task` row), releases escrow, and projects the worker's `earned`.
+3. **Agent-to-agent hiring.** A citizen working a high-value bounty hires a
+ sub-agent (a real sub-task → `hired` activity linking
+ `counterparty_citizen_id`). The sub-task is picked up by another citizen; the
+ reconcile sweep links the two rows by their shared `task_pda`.
+
+### Reputation ladder (the career ladder)
+
+`minReputation` gates high-value work so newcomers must grind low-value jobs to
+climb. Patron tiers rotate across:
+
+| Tier | `minReputation` | Reward (devnet) | Who can take it |
+|---|---|---|---|
+| **apprentice** | 0 | `AGORA_TASK_REWARD_LAMPORTS` | anyone, incl. brand-new citizens |
+| **journeyman** | 5 | 2× base | a short track record |
+| **master** | 20 | 4× base | proven citizens only |
+
+A rep-2 citizen *skips* a master bounty (logged `skipping bounty — not qualified`);
+a rep-≥20 citizen takes it. Climb by completing dispatcher/apprentice work (+1 rep
+each).
+
+### Reconcile + honest scarcity
+
+- A **reconcile sweep** (`AGORA_RECONCILE_MS`, default 60s) re-reads every open
+ posting from the chain and projects `cancelled_task` / `expired_task` /
+ `claimed_task` / `completed_task` transitions so the board never shows a stale
+ "open" task. Idempotent (one terminal row per `(task_pda, kind)`).
+- **No infinite money.** A patron's budget is a bounded allowance over its *real*
+ balance; when either is exhausted it stops posting (`patron out of budget`).
+
+### Task-03 environment
+
+| Var | Default | Purpose |
+|---|---|---|
+| `AGORA_PATRON_COUNT` | `1` | How many citizens act as patrons (also work jobs) |
+| `AGORA_PATRON_BUDGET_ATOMIC` | `30×` reward | Bounded posting allowance (honest scarcity) |
+| `AGORA_PATRON_POST_INTERVAL_MS` | `90000` | Min interval between a patron's posts |
+| `AGORA_ENABLE_HIRING` | `1` (devnet) | Agent-to-agent sub-task hiring on/off |
+| `AGORA_SUBTASK_REWARD_ATOMIC` | reward base | Reward a worker offers when hiring |
+| `AGORA_RECONCILE_MS` | `60000` | Board↔chain reconcile cadence |
+| `AGORA_THREE_TOKEN_ACCOUNT` | — | **mainnet** poster's $THREE token account (required to post $THREE) |
+| `AGORA_MAINNET_SPEND_CAP_ATOMIC` | `0` | **mainnet** hard cap on cumulative $THREE escrow this process (0 = blocked) |
+
+Mainnet escrow is real money — it's gated behind `AGORA_CLUSTER=mainnet` **and** a
+non-zero spend cap **and** a configured token account; devnet (SOL) is the default
+and proves the whole flow.
+
+### Verify the supply lane
+
+```bash
+# Open bounties our citizens posted (source: agenc), with live-open state:
+curl -s "$AGORA_API_BASE/api/agora/board" | jq '.tasks'
+# A specific task's on-chain lifecycle:
+curl -s "$AGORA_API_BASE/api/agenc/get-task?taskPda=<pda>&cluster=devnet&lifecycle=1" | jq '.task.state, .lifecycle.timeline'
+# The hire link (two citizens, one shared task_pda):
+# select kind, citizen_id, counterparty_citizen_id, task_pda from agora_activity where kind='hired';
+```
+
## Deploy
```bash
diff --git a/workers/agora-citizens/engine.js b/workers/agora-citizens/engine.js
index 8587bb5e2..6bd653caa 100644
--- a/workers/agora-citizens/engine.js
+++ b/workers/agora-citizens/engine.js
@@ -37,7 +37,8 @@ import {
withRetry,
TASK_STATE,
} from './agenc.js';
-import { runFetcher, defaultTarget } from './work/fetcher.js';
+import { defaultTarget } from './work/fetcher.js';
+import { runProfession } from './work/index.js';
const FETCHER_BITS = professionBits(['fetcher']); // 1n
const BOARD_TTL_MS = 60_000;
@@ -414,6 +415,9 @@ export async function tickCitizen(ctx, citizen) {
citizen.busy = true;
const cfg = ctx.cfg;
const name = citizen.spec.displayName;
+ // The profession this citizen works — drives the WORK dispatch and every
+ // projection label. Defaults to Fetcher (the founding workforce).
+ const profession = citizen.spec.profession || 'fetcher';
try {
await reconcile(ctx, citizen);
await refreshBoard(ctx);
@@ -453,10 +457,10 @@ export async function tickCitizen(ctx, citizen) {
await ctx.store.appendActivity({
citizenId: citizen.id,
kind: 'claimed_task',
- profession: 'fetcher',
+ profession,
taskPda: job.pda,
txSignature: claim.txSignature,
- narrative: `${name} claimed a Fetcher job (${rewardShape(cfg, job.reward).label}).`,
+ narrative: `${name} claimed a ${capLabel(profession)} job (${rewardShape(cfg, job.reward).label}).`,
repAfter: citizen.reputation,
});
await ctx.store.publishFeed({
@@ -464,11 +468,11 @@ export async function tickCitizen(ctx, citizen) {
actor: name,
citizenId: citizen.id,
agentPda: citizen.agentPda.toBase58(),
- profession: 'fetcher',
+ profession,
taskPda: job.pda,
txSig: claim.txSignature,
explorerUrl: explorerTx(claim.txSignature, cfg.cluster),
- narrative: `${name} claimed a Fetcher job.`,
+ narrative: `${name} claimed a ${capLabel(profession)} job.`,
});
log.info('claimed', { name, pda: job.pda, tx: explorerTx(claim.txSignature, cfg.cluster) });
@@ -488,12 +492,16 @@ export async function tickCitizen(ctx, citizen) {
}
}
- // WORK — a real fetch against a live service.
+ // WORK — do the REAL work for this citizen's profession (docs/agora.md §
+ // Professions). The registry dispatches by capability: a Fetcher calls the
+ // x402/HTTP service, a Sculptor forges a GLB, a Scribe writes via the LLM
+ // router, a Verifier re-derives another citizen's proof. Every runner returns
+ // the same proof shape, so PROVE below stays profession-agnostic.
const boardService = ctx.board.services.find((s) => typeof s.resource === 'string' && /^https?:\/\//i.test(s.resource));
- const work = await runFetcher({
+ const work = await runProfession(profession, {
cfg,
citizen: { agentIdHex: citizen.agentIdHex, displayName: name, pubkey: citizen.pubkey },
- job: { taskPda: job.pda, source: 'agenc', resource: boardService?.resource || defaultTarget(cfg) },
+ job: { taskPda: job.pda, source: 'agenc', resource: boardService?.resource || defaultTarget(cfg), ...(job.target ? { target: job.target } : {}) },
});
// PROVE — submit the proof on-chain.
@@ -518,25 +526,27 @@ export async function tickCitizen(ctx, citizen) {
await ctx.store.appendActivity({
citizenId: citizen.id,
kind: 'completed_task',
- profession: 'fetcher',
+ profession,
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}.`,
+ narrative: work.summary
+ ? `${name} ${work.summary.charAt(0).toLowerCase()}${work.summary.slice(1)} and proved it; reputation ${repBefore} → ${repAfter}.`
+ : `${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',
+ profession,
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.`,
+ narrative: `${name} earned ${reward.label} for a completed ${capLabel(profession)} job.`,
repBefore,
repAfter,
});
@@ -545,25 +555,61 @@ export async function tickCitizen(ctx, citizen) {
actor: name,
citizenId: citizen.id,
agentPda: citizen.agentPda.toBase58(),
- profession: 'fetcher',
+ profession,
taskPda: job.pda,
proofHash: work.proofHashHex,
+ deliverableUrl: work.deliverableUrl,
txSig: completion.txSignature,
explorerUrl: explorerTx(completion.txSignature, cfg.cluster),
- narrative: `${name} completed a Fetcher job (rep ${repBefore} → ${repAfter}).`,
+ narrative: `${name} completed a ${capLabel(profession)} job (rep ${repBefore} → ${repAfter}).`,
});
await ctx.store.publishFeed({
type: 'agora-earned',
actor: name,
citizenId: citizen.id,
agentPda: citizen.agentPda.toBase58(),
- profession: 'fetcher',
+ profession,
rewardLabel: reward.label,
txSig: completion.txSignature,
explorerUrl: explorerTx(completion.txSignature, cfg.cluster),
narrative: `${name} earned ${reward.label}.`,
});
+ // The trust loop: a Verifier re-derived another citizen's proof. Project the
+ // attestation as a `vouched` activity citing the verified task + the proof it
+ // re-computed (idempotent on this completion tx). A mismatch is recorded just
+ // as honestly as a pass — the graph never carries a false ✓.
+ if (work.vouch) {
+ const v = work.vouch;
+ await ctx.store.appendActivity({
+ citizenId: citizen.id,
+ kind: 'vouched',
+ profession,
+ taskPda: v.targetTaskPda || job.pda,
+ counterpartyCitizenId: v.targetCitizenId || null,
+ txSignature: completion.txSignature,
+ proofHash: v.recomputed,
+ deliverableUrl: v.targetDeliverableUrl,
+ narrative: v.match
+ ? `${name} verified a ${capLabel(v.targetProfession || 'fetcher')} deliverable — sha256 re-derived, proof holds (${String(v.recomputed).slice(0, 12)}…).`
+ : `${name} flagged a ${capLabel(v.targetProfession || 'fetcher')} deliverable — recomputed hash does NOT match the on-chain proof.`,
+ repBefore,
+ repAfter,
+ meta: { verdict: v.verdict, claimed: v.claimed, recomputed: v.recomputed },
+ });
+ await ctx.store.publishFeed({
+ type: v.match ? 'agora-vouched' : 'agora-flagged',
+ actor: name,
+ citizenId: citizen.id,
+ agentPda: citizen.agentPda.toBase58(),
+ profession,
+ taskPda: v.targetTaskPda || job.pda,
+ txSig: completion.txSignature,
+ explorerUrl: explorerTx(completion.txSignature, cfg.cluster),
+ narrative: v.match ? `${name} vouched for a deliverable.` : `${name} flagged a deliverable mismatch.`,
+ });
+ }
+
const restPos = wander(citizen.home);
await ctx.store.updateCitizen(citizen.id, {
status: 'idle',