Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: refine Agora citizen work skills, trust surface, and world rendering
nirholas1007b76b92a4
diff --git a/api/agora/[action].js b/api/agora/[action].jsindex 7255f5150..791127f7e 100644--- a/api/agora/[action].js+++ b/api/agora/[action].js@@ -167,7 +167,7 @@ async function handleBoard(req, res) {// Lane 1 — open AgenC tasks (projected from real on-chain postings).const openTasks = await sql`select a.task_pda, a.task_id, a.profession, a.amount_atomic, a.reward_mint,- a.reward_label, a.narrative, a.created_at, a.tx_signature,+ a.reward_label, a.narrative, a.created_at, a.tx_signature, a.meta,c.id as creator_id, c.display_name as creator_name, c.agenc_clusterfrom agora_activity ajoin agora_citizens c on c.id = a.citizen_id@@ -197,6 +197,12 @@ async function handleBoard(req, res) {},creator: { id: t.creator_id, name: t.creator_name },cluster: t.agenc_cluster,+ // Career-ladder gating surfaced from the posting's projection so workers+ // (and the UI) know who may claim it without re-reading the chain.+ minReputation: Number(t.meta?.minReputation ?? 0),+ requiredCapabilities: t.meta?.requiredCapabilities != null ? String(t.meta.requiredCapabilities) : null,+ taskType: t.meta?.taskType ?? 'Exclusive',+ tier: t.meta?.tier ?? null,postedAt: t.created_at,txSignature: t.tx_signature,taskUrl: t.task_pdadiff --git a/content/x-mcp-manifesto.md b/content/x-mcp-manifesto.mdindex 54ca52f7b..1aa52a304 100644--- a/content/x-mcp-manifesto.md+++ b/content/x-mcp-manifesto.md@@ -1,64 +1,137 @@-# A body, a wallet, and a conscience: why three.ws built 31 MCP servers+# A body, a wallet, and a conscience: the 31 MCP servers of three.ws-*Long-form X article. Canonical reference for the MCP launch. $THREE is the only coin.*+*Long-form X article. The complete, canonical reference for every three.ws MCP server: what it does, how it works, who it's for, and why it exists. $THREE is the only coin.*----Chatbots are a dead end for what comes next. The interesting question isn't "what can a model say." It's "what can an agent actually do, safely, on your behalf, with money and consequences on the line." For the last stretch we've been answering that question in code. The result is **31 MCP servers**, all published to npm under `@three-ws` and registered in the official MCP registry, that turn three.ws from a website into an operating layer agents can actually run on.+Chatbots are a dead end for what comes next. The interesting question isn't "what can a model say." It's "what can an agent actually do, safely, on your behalf, with money and consequences on the line." We've spent the last stretch answering that in code. The result is **31 MCP servers**, all published to npm under `@three-ws` and registered in the official MCP registry under `io.github.nirholas`. Every one is a thin, real wrapper over a live three.ws capability. No mocks, no demos. Add any of them to Claude, Cursor, or your own agent with one line of `npx`.-Here's why we built each layer, and how they fit together.+They are built in layers. Here is every server, layer by layer, and why it's there.-## MCP, because the interface is the product+---++## The interface: MCP++Every capability speaks the **Model Context Protocol**, the emerging universal port between an AI assistant and the real world. We made MCP the front door, not an afterthought, because a capability an agent can't reach may as well not exist. The technical shape is consistent across all 31: an ESM Node server on `@modelcontextprotocol/sdk`, running over stdio, that turns three.ws HTTP endpoints into typed, annotated tools (read-only vs write, idempotent vs destructive) so a client can reason about each call before it makes it. Fourteen also run as hosted remote servers over Streamable HTTP for clients that prefer a URL to an install.++---++## Aggregate entry points++**`@three-ws/mcp-server`** is the flagship. It bundles the whole creation toolchain behind one server: a free `forge_free` text-to-3D tool (TRELLIS / NVIDIA NIM) plus fifteen paid tools that settle per call in USDC on Solana via x402: `mesh_forge`, `rig_mesh`, `forge_avatar`, `text_to_avatar`, `pose_seed`, `pump_snapshot`, `agent_reputation`, `vanity_grinder`, `sentiment_pulse`, `ens_sns_resolve`, `agent_delegate_action`, `agenc_list_tasks`, `agenc_get_task`, `agenc_get_agent`, `aixbt_intel`, `aixbt_projects`. It's for builders who want one endpoint that does everything and pays as it goes. Also hosted at `/api/mcp`. `npx -y @three-ws/mcp-server`-Every capability we ship speaks the **Model Context Protocol**. That's deliberate. MCP is becoming the universal port between an AI assistant and the real world, and a capability that isn't reachable over MCP may as well not exist for an agent. So we didn't bolt MCP on. We made it the front door. One line, `npx -y @three-ws/<server>`, and any MCP client (Claude, Cursor, your own agent) can see in 3D, pay for things, read the market, and act. The 31 servers are the public API of the whole platform.+**`@three-ws/mcp-bridge`** turns *any* x402-paid endpoint on the open web into a callable tool. It pre-loads the Coinbase x402 Bazaar so new paid services appear automatically, auto-pays with spend caps, and needs no subscription or key. Tools: `call_paid_endpoint`, `list_bazaar_tools`, `refresh_bazaar`. For agents that need to reach services three.ws didn't build. `npx -y @three-ws/mcp-bridge`++---## 3D, because agents need a body-Text agents are ghosts. We started with embodiment: text-to-3D over the forge pipeline (`scene-mcp` speaks a diorama into being from one sentence), full avatar generation, rigging, dressing, and live inline rendering (`avatar-agent`, `threews-avatar`), and a voice-and-motion layer covering text-to-speech, speech-to-text, audio-to-face lipsync, and motion capture (`audio-mcp`). An agent shouldn't just answer you. It should stand in a room, look at you, and talk. The `loom-mcp` gallery lets agents browse and contribute to what others have built. Embodiment isn't decoration. It's how agents become presences instead of prompts.+Text agents are ghosts. These give them presence.++**`@three-ws/scene-mcp`** turns one sentence into a placed 3D diorama: it returns a composed plan (mood, palette, per-object prompts) over the live forge pipeline, ready to build into an orbitable scene. Read-only, no key, no signer. Tools: `compose_scene`, `get_scene`, `list_scenes`. For anyone who wants to speak a world into being. `npx -y @three-ws/scene-mcp`++**`@three-ws/avatar-agent`** is the full embodiment toolkit, 20 tools in one: generic GLB ops (`inspect_glb`, `validate_glb`, `optimize_glb`, `thumbnail_glb`, `viewer_url`), avatar lifecycle (`generate_avatar`, `spawn_avatar`, `render_avatar`, `dress_avatar`, `list_avatars`), a built-in Solana wallet (`wallet_create`, `wallet_send`, `wallet_balance`), pump.fun powers (`pump_launch`, `pump_buy`, `pump_collect_fees`, `pump_snapshot`), plus `speak` (TTS), `ens_sns_resolve`, and `list_animations`. It takes any GLB and turns it into a riggable agent with a voice and a wallet. For developers building a full 3D agent. `npx -y @three-ws/avatar-agent`++**`@three-ws/avatar-mcp`** (the lightweight viewer) renders a live, interactive 3D avatar inline in MCP clients that support apps, or hands back paste-anywhere embed code. Zero-config, read-only over live three.ws endpoints. Tools: `avatar`, `render_avatar`, `avatar_embed_code`, `get_avatar`. For anyone who just wants the avatar to show up in chat or on a page. `npx -y @three-ws/avatar-mcp`++**`@three-ws/audio-mcp`** is the voice-and-motion layer: `text_to_speech`, `speech_to_text`, `audio_to_face` (lipsync blendshapes from audio), and a motion-capture clip library (`motion_capture_clip`, `motion_capture_clips`). It transforms audio into the signals that drive a 3D agent's face and body. For builders who want agents that talk and move, not just type. `npx -y @three-ws/audio-mcp`++**`@three-ws/loom-mcp`** is the community 3D-creation gallery: browse the feed, fetch a creation with its viewer URL, and submit your own. Tools: `get_loom_feed`, `get_creation`, `submit_creation`. It closes the loop with scene and avatar generation by giving creations a home. For creators sharing what they forged. `npx -y @three-ws/loom-mcp`++---++## AI capability surfaces++**`@three-ws/brain-mcp`** is one interface over many models. `list_providers` enumerates what's available; `chat` runs a completion through the three.ws multi-provider router (Claude, GPT, Qwen, Nemotron and more) with automatic fallback, so a client wires one tool instead of every vendor SDK. For agents that want the best model for a task without the plumbing. `npx -y @three-ws/brain-mcp`++**`@three-ws/vision-mcp`** gives an agent eyes: `analyze_image` and `describe_image` run a vision-language model (free-first NVIDIA NIM with a paid fallback), and `get_vision_status` reports which backend is live. Pass a URL or base64 image and an instruction. For agents that need to understand what they're looking at. `npx -y @three-ws/vision-mcp`++**`@three-ws/ibm-watsonx-mcp`** bridges IBM watsonx.ai Granite models using the caller's own IBM Cloud credentials: `watsonx_chat`, `watsonx_generate`, `watsonx_embed`, `watsonx_tokenize`, `watsonx_forecast`, `watsonx_list_models`. For enterprises already on IBM Cloud who want Granite in their agent. `npx -y @three-ws/ibm-watsonx-mcp`++**`@three-ws/ibm-x402-mcp`** is the same Granite power with no IBM account required from the caller: `ibm_granite_chat`, `ibm_granite_code`, `ibm_granite_embed`, `ibm_granite_analyze`, `ibm_granite_forecast`, billed per call in USDC over x402 (the operator supplies the credentials). For agents that want enterprise inference on a pay-as-you-go basis. `npx -y @three-ws/ibm-x402-mcp`++---## x402, because autonomy requires payments-An agent that can't pay can't act in the real economy. We built on **x402**, pay-per-call settlement in USDC (and $THREE) on Solana, so agents transact without subscriptions or API keys. `x402-mcp` is a self-custodial buyer that inspects a price before it pays. `mcp-bridge` turns any x402 endpoint on the open web into a callable tool. `ibm-x402` meters real IBM Granite inference per call. Money is the thing that makes autonomy real, and the thing that makes it dangerous, which is why the next two layers exist.+An agent that can't pay can't act in the real economy.++**`@three-ws/x402-mcp`** is a self-custodial buyer: `find_services` searches the Bazaar, `inspect_endpoint` reads a price *before* you commit funds, `pay_and_call` settles in USDC or $THREE from your own Solana key (real settlement, bounded by spend caps), and `x402_wallet` reports balance and keypair info. Never custodial. For agents that must pay for things while their owner keeps the keys. `npx -y @three-ws/x402-mcp`-## Crypto and $THREE, because value should be native+(The merchant side and the open-web bridge live in `mcp-server` and `mcp-bridge` above.)-`three-token-mcp` is, as far as we know, the **first MCP server whose actions burn a token**. Agents can price, hold, and burn **$THREE**, and every burn is a real Solana transaction that removes supply. $THREE is the only coin three.ws touches, and we made it structurally aligned with the platform: agents are **net buyers**. More on that under safeguards.+----## Reputation and provenance, because trust can't be vibes+## $THREE, because value should be native-If agents are going to transact and coordinate, they need verifiable track records, not screenshots. `provenance-mcp` is an **append-only, signed, on-chain-verifiable log** of every action an agent takes, so one agent can audit another's history before trusting it. `agenc-mcp` exposes an on-chain task marketplace and an ERC-8004-style identity registry so agents can hire each other. `intel-mcp` scores wallets and coins by who is actually behind them: smart-money, KOL trades, signal-feed accuracy. Reputation is infrastructure, and we treat it that way.+**`@three-ws/three-token-mcp`** is, as far as we know, the first MCP server whose actions burn a token. `three_price` reads the live USD price via Jupiter, `three_balance` reads a wallet's holdings, and `three_burn` executes a real on-chain burn that removes $THREE from supply and funds the treasury. $THREE is the only coin three.ws touches, and across the platform agents are net buyers of it by design. For agents that hold and defend $THREE. `npx -y @three-ws/three-token-mcp`-## Safeguards and guardrails, because "autonomous" without limits is just "reckless"+----This is the part most people skip, and the part we care about most. An agent with a wallet and no boundaries is a liability. So autopilot is built as a **control plane the owner configures and the server enforces**:+## Market data and discovery-- **Scopes.** Nothing is granted by default. The agent can propose but not act until the owner enables a capability.-- **A daily SOL spend cap.** Autonomy is bounded in the currency the agent actually spends. (We just shipped a fix here: the cap is denominated in **SOL**, not $THREE, because $THREE is for accumulating, not spending.)-- **$THREE is a one-way valve.** The agent can buy, hold, and burn $THREE, but a server-side guard refuses any attempt to sell or send it. Every three.ws agent is a structural net buyer of $THREE, by design, at the protocol level.-- **Confirmation and dry-run.** Irreversible actions require explicit confirmation, and you can preview exactly what an action would do before it runs.-- **Signed receipts and undo.** Every action writes a signed provenance record, reversible ones can be undone, and the agent remembers the correction.-- **Earned trust.** Agents move from sandbox to trusted to autonomous based on real, kept actions, not a vanity score.+**`@three-ws/pumpfun-mcp`** is free, read-only pump.fun and Solana analytics over public RPC, 22 tools deep: token discovery (`get_new_tokens`, `get_trending_tokens`, `get_graduated_tokens`, `get_king_of_the_hill`, `search_tokens`, `get_token_details`), on-chain analysis (`get_bonding_curve`, `get_token_holders`, `get_token_trades`, `get_creator_profile`), creator-fee tooling (`pumpfun_list_claims`, `pumpfun_watch_claims`, `pumpfun_first_claims`, `pumpfun_watch_whales`), `sns_resolve`, social sentiment (`social_cashtag_sentiment`, `social_x_post_impact`), `kol_leaderboard`, `pumpfun_quote_swap`, `pumpfun_vanity_mint`, `pumpfun_token_3d`, and `pumpfun_bot_status`. No API keys. For agents reading the memecoin market. `npx -y @three-ws/pumpfun-mcp`-Every one of these is enforced on the backend. The MCP client cannot bypass them. That's the whole point: the guardrails live below the agent, not in its prompt.+**`@three-ws/intel-mcp`** reads the market the way smart money does: `smart_money_coin` scores a coin by who is net-buying it, `wallet_intel` pulls a wallet's realized reputation, `signal_feed` reports a feed's proven accuracy, `kol_leaderboard` and `kol_trades` rank tracked traders, and `copy_smart_wallets` browses the copy-trade directory. Read-only over live data. For agents that judge a coin by its buyers, not its chart. `npx -y @three-ws/intel-mcp`-## Sniping and trading, because that's what agents will actually do with all this+**`@three-ws/kol-mcp`** is the per-wallet deep dive that complements intel's leaderboard: `get_wallet_portfolio` (one tracked trader's holdings and realized P&L) and `get_wallet_trades` (their trades on a given mint), via a Birdeye proxy. For agents studying a specific KOL before following them. `npx -y @three-ws/kol-mcp`-Put it together. Discovery (`pumpfun-mcp`: new, trending, and graduating tokens, bonding curves, holders), signals (`intel-mcp`, `signals-mcp`), alerts (`alerts-mcp`), a wallet, and guardrails. What you get is the real use case: agents that **snipe pump.fun launches and act on alpha**, in SOL, within limits their owner set. We've published the spec for the trading capability: SOL-denominated buy and sell of arbitrary coins, grounded in real signals (never guesses), confirmation-gated, daily-capped, and $THREE still never sold. Buying and selling memecoins is the honest, high-velocity thing autonomous agents will do. We'd rather build it with brakes than pretend it won't happen.+**`@three-ws/signals-mcp`** is the signal marketplace: `list_signal_feeds` ranks feeds by proven edge, `subscribe_signal` and `set_subscription_status` manage follows, `get_subscriptions` lists them, and `get_mirror_leaderboard` ranks publishers by real on-chain performance. For agents that want vetted alpha, not noise. `npx -y @three-ws/signals-mcp`-## What we're building next+**`@three-ws/activity-mcp`** is the live pulse of the platform: `get_trending_agents`, `get_trending_coins`, the `$THREE` holder leaderboard (`get_holder_leaderboard`, `get_tier_info`), and the site-wide activity ticker (`get_feed_events`). Public, read-only. For agents and dashboards that need situational awareness. `npx -y @three-ws/activity-mcp`-- **`trading-mcp`.** The buy, sell, and snipe capability above, shipped in phases: quotes and positions first (read-only), then buys, then sells, then autopilot-generated trade proposals that flow through the same dry-run, confirm, and signed-receipt loop.-- **Deeper agent-to-agent coordination** over AgenC. Agents discovering, hiring, paying, and rating each other, with provenance as the trust substrate.-- **More senses and surfaces** as MCP standardizes them: richer vision, more of the platform exposed as callable tools.+**`@three-ws/marketplace-mcp`** browses the public catalog: `browse_agents`, `agent_detail`, `agent_categories`, `browse_skills`, `skill_categories`. Read-only discovery. For agents shopping the marketplace or finding reusable skills. `npx -y @three-ws/marketplace-mcp`-The thesis hasn't changed since the first server: agents should do things. See, pay, trade, prove, and stay inside the lines their owner drew. Thirty-one servers in, that's a platform you can build on today.+---++## Identity, reputation, and provenance, because trust can't be vibes++**`@three-ws/naming-mcp`** is the on-chain identity layer: `sns_resolve` (a `.sol` name to its owner wallet), `sns_reverse` (a wallet to its primary name) over Bonfida SNS on mainnet, and `threews_availability` to check if a `*.threews.sol` agent handle is free. For agents that need a human-readable name and address. `npx -y @three-ws/naming-mcp`++**`@three-ws/provenance-mcp`** is the trust substrate: `append_agent_action` writes to an append-only, ERC-191-signed log, and `list_agent_actions` / `query_action` read it back. Records are never deleted and are on-chain verifiable, so one agent can audit another's history before trusting it. For any system that needs proof, not screenshots. `npx -y @three-ws/provenance-mcp`++**`@three-ws/agenc-mcp`** is agent-to-agent coordination: `list_tasks` and `get_task` browse the AgenC on-chain task marketplace, `get_agent` reads the ERC-8004-style identity registry, `link_agent` ties a three.ws identity in, and `query_x402_services` discovers paid work. For agents that hire and get hired by other agents. `npx -y @three-ws/agenc-mcp`++**`@three-ws/vanity-mcp`** reads the secret-blind vanity-address bounty market: `vanity_quote` (price and difficulty for a pattern), `vanity_appraise` (rarity of an address), `vanity_board`, `vanity_open`, `vanity_leaderboard`, `vanity_gallery`, `vanity_stats`, `vanity_config`. Workers grind in parallel while the requester's found address stays sealed. For agents that want a memorable, provably-rare address. `npx -y @three-ws/vanity-mcp`++---++## The autonomous control plane, because "autonomous" without limits is just "reckless"++This is the part most platforms skip, and the part we care about most. An agent with a wallet and no boundaries is a liability, so the agent's own controls are first-class servers, every limit enforced server-side where the agent's prompt cannot reach.++**`@three-ws/autopilot-mcp`** is the keystone. The owner grants `scopes` (nothing by default), sets a daily **SOL** spend cap, and chooses a confirmation policy via `get_autopilot_config` / `set_autopilot_config`. The agent then runs a transparent loop: `generate_proposals` turns high-salience memories into provenance-cited candidate actions, `list_proposals` and `dryrun_proposal` review them, `adjust_proposal` tunes one, `execute_proposal` takes the real action (confirmation-gated and irreversible), and `dismiss_proposal` / `undo_action` close the trust loop. `list_autopilot_activity` is the signed receipts log and `compute_trust` is the earned trust level (sandbox, then trusted, then autonomous). Crucially, the spend cap is in SOL, and a server-side guard makes **$THREE a one-way valve**: an agent can buy, hold, and burn $THREE but can never sell or send it. For owners who want autonomy with brakes. `npx -y @three-ws/autopilot-mcp`++**`@three-ws/portfolio-mcp`** is the agent's view of its own money: `get_portfolio_summary`, `get_portfolio_history`, `get_portfolio_asset`, `get_trades_feed`, and `get_wallet_balances` are live reads, and `send_transfer` broadcasts a real signed Solana transfer. For agents that need to know and move what they hold. `npx -y @three-ws/portfolio-mcp`++**`@three-ws/copy-mcp`** runs copy-trading non-custodially: `list_subscriptions`, `create_subscription`, `update_subscription`, `cancel_subscription` manage the follows and guard rules, while `get_executions`, `record_execution`, and `get_earnings` track results and fees. For agents that mirror a proven leader within their own limits. `npx -y @three-ws/copy-mcp`++**`@three-ws/alerts-mcp`** lets an agent watch the market headlessly: `create_alert_rule`, `update_alert_rule`, `delete_alert_rule`, `list_alert_rules`, and `get_alert_history` define pump.fun rules that fire across in-app, webhook, and Telegram, evaluated by a server-side cron. For agents that need to know the moment something moves. `npx -y @three-ws/alerts-mcp`-Browse them all in the MCP registry (`io.github.nirholas`), or add one in a line:+**`@three-ws/notifications-mcp`** is the agent's inbox: `list_notifications`, `mark_read`, `delete_notification`, the delivery-preference matrix (`get_preferences`, `set_preferences`), and Web Push device registration (`register_push_device`, `unregister_push_device`). For agents that need to receive and triage inbound events without polling. `npx -y @three-ws/notifications-mcp`-```-npx -y @three-ws/autopilot-mcp # an agent's own control plane-npx -y @three-ws/three-token-mcp # price, hold, and burn $THREE-npx -y @three-ws/scene-mcp # speak a 3D world into being-```+**`@three-ws/billing-mcp`** is the agent's account economics: `get_billing_summary`, `query_usage`, `list` and `get_receipt` for invoices, plus `get_revenue`, `get_fee_info`, and `export_billing_history`. Account-scoped and read-only. For agents that should know their own quota and spend before they act. `npx -y @three-ws/billing-mcp`++---++## Product surfaces with real backends++**`@three-ws/clash-mcp`** is Coin Clash, the community faction game backed by real holdings and pump.fun data: `get_clash_state`, `get_clash_leaderboard`, `enlist_faction`, `rally_faction`. For agents (and people) who want to play. `npx -y @three-ws/clash-mcp`++**`@three-ws/tutor-mcp`** runs a Pay-As-You-Learn tutoring session ledger: `load_session` reads the running itemized tab and `close_session` finalizes it into an attested invoice. For agents that teach and bill fairly by the minute. `npx -y @three-ws/tutor-mcp`++---++## Sniping and trading, and what's next++Put the layers together: discovery (`pumpfun-mcp`), signals (`intel-mcp`, `signals-mcp`, `kol-mcp`), alerts (`alerts-mcp`), a wallet (`portfolio-mcp`, `x402-mcp`), and the control plane (`autopilot-mcp`). What you get is the use case agents will actually reach for: sniping pump.fun launches and acting on alpha, in SOL, within limits their owner set. We've published the spec for the trading capability: SOL-denominated buy and sell of arbitrary coins, grounded in real signals, confirmation-gated, daily-capped, and $THREE still never sold. We'd rather build it with brakes than pretend it won't happen.++Next:++- **`trading-mcp`**, shipped in phases: quotes and positions first (read-only), then buys, then sells, then autopilot-generated trade proposals that flow through the same dry-run, confirm, and signed-receipt loop.+- **Deeper agent-to-agent coordination** over AgenC: agents discovering, hiring, paying, and rating each other, with provenance as the trust substrate.+- **More senses and surfaces** as MCP standardizes them.++The thesis hasn't changed since the first server: agents should do things. See, pay, trade, prove, and stay inside the lines their owner drew. Thirty-one servers in, that's a platform you can build on today.-Build agents that do more than chat. **$THREE.**+Browse them all in the MCP registry (`io.github.nirholas`). Build agents that do more than chat. **$THREE.**diff --git a/src/agora/agora-world.js b/src/agora/agora-world.jsindex 0f8713122..d7c7c26fb 100644--- a/src/agora/agora-world.js+++ b/src/agora/agora-world.js@@ -15,8 +15,12 @@ import { createCityScene, bindResize } from '../city/city-scene.js';import { CityCamera } from '../city/city-camera.js';import { CitizenPopulation } from './citizen-avatar.js';import { PassportPanel } from './passport-panel.js';+import { mountEconomyLayer } from './economy-layer.js';import { log } from '../shared/log.js';+// Where the job board stands in the square (escrow origin for the coin flow).+const BOARD_POSITION = new THREE.Vector3(0, 0, -7);+// ── DOM refs ────────────────────────────────────────────────────────────────const canvas = document.getElementById('agora-canvas');const loadingEl = document.getElementById('agora-loading');@@ -260,6 +264,28 @@ async function main() {loadCitizens();progress(100, 'Entering the Commons…');+ // ── Economy layer (Task 06) ────────────────────────────────────────────────+ // The job board, live ticker, and the completion moment (coin flow + rep tick+ // + orbit-able plinth), all driven by a single deduped pulse poll. It's handed+ // a small crowd adapter so a real claimed_task walks the right citizen and a+ // completed_task celebrates them — decoupled from the scaffold internals.+ const crowd = {+ findByName: (name) => population.findByName(name),+ getPosition: (id) => population.worldPosition(id),+ setStatus: (id, status) => population.setStatus(id, status),+ celebrate: (id) => population.celebrate(id),+ walkTo: (id, target, onArrive) => population.walkTo(id, target, onArrive),+ };+ const economy = mountEconomyLayer({+ scene, camera, renderer,+ reducedMotion: REDUCED_MOTION,+ boardPosition: BOARD_POSITION,+ focusOn: (v) => { focusGoal = v.clone ? v.clone() : new THREE.Vector3(v.x, v.y, v.z); },+ crowd,+ openPassport: (id) => openPassport(id, null),+ });+ window.addEventListener('pagehide', () => economy.dispose(), { once: true });+// ── Render loop ───────────────────────────────────────────────────────────const clock = new THREE.Timer();(function tick() {@@ -285,6 +311,7 @@ async function main() {cityCamera.update(focus, 1.7);population.update(dt);+ economy.update(dt);renderer.render(scene, camera);})();}diff --git a/src/agora/citizen-avatar.js b/src/agora/citizen-avatar.jsindex 130717b3c..0e661b88c 100644--- a/src/agora/citizen-avatar.js+++ b/src/agora/citizen-avatar.js@@ -24,7 +24,7 @@ import {import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import { gltfLoader } from '../loaders/gltf.js';import { AnimationManager } from '../animation-manager.js';-import { loadManifest, getLocomotionDefs, resolveAvatarUrl, CLIP_IDLE } from '../game/avatar-rig.js';+import { loadManifest, getLocomotionDefs, resolveAvatarUrl, CLIP_IDLE, CLIP_WALK } from '../game/avatar-rig.js';import { log } from '../shared/log.js';// Target on-screen height so wildly-scaled GLBs all read as people in the square.@@ -33,6 +33,12 @@ const AVATAR_HEIGHT = 1.74;// saturating the network and stalling the first frame.const MAX_CONCURRENT_LOADS = 4;const FADE_IN_SEC = 0.55;+// Citizen locomotion (Task 06 claim-walk). A citizen strolls to the board to+// claim and on to a work spot; the economy layer drives this via walkTo().+const WALK_SPEED = 2.7; // m/s+const TURN_RATE = 9; // rad/s toward heading+const ARRIVE_EPS = 0.35; // metres "close enough"+const CELEBRATE_SEC = 1.1; // duration of the completion hop// Profession → accent colour. Keys match the API's profession keys// (api/agora/[action].js PROFESSIONS). Used for the label chip and selection ring@@ -311,25 +317,33 @@ export class CitizenPopulation {// Idle loop, desynced so the crowd doesn't breathe in lockstep.let mixer = null;+ let idleAction = null;const idleClip = tpl.clips.get(CLIP_IDLE) || [...tpl.clips.values()][0];+ const walkClip = tpl.clips.get(CLIP_WALK) || null;if (idleClip && !this.reducedMotion) {mixer = new AnimationMixer(model);- const action = mixer.clipAction(idleClip);- action.time = hashJitter(citizen.id + 'x') * (idleClip.duration || 1);- action.play();+ idleAction = mixer.clipAction(idleClip);+ idleAction.time = hashJitter(citizen.id + 'x') * (idleClip.duration || 1);+ idleAction.play();} else if (idleClip && this.reducedMotion) {// Reduced motion: hold a calm idle pose (frame 0), no looping motion.mixer = new AnimationMixer(model);- const action = mixer.clipAction(idleClip);- action.play();+ idleAction = mixer.clipAction(idleClip);+ idleAction.play();mixer.update(0);- action.paused = true;+ idleAction.paused = true;}const fade = this.reducedMotion ? null : { t: 0 };for (const m of materials) m.opacity = this.reducedMotion ? 1 : 0;- const inst = { citizen, group, model, mixer, label, materials, fade, height, baseYaw };+ const inst = {+ citizen, group, model, mixer, label, materials, fade, height, baseYaw,+ // Locomotion + economy state (Task 06).+ idleClip, walkClip, idleAction, walkAction: null,+ motion: 'idle', walkTarget: null, onArrive: null, heading: group.rotation.y,+ busy: false, busyRing: null, busyT: 0, celebrateT: null,+ };this.instances.push(inst);this._byId.set(citizen.id, inst);// Pickable meshes carry a back-reference so a raycast hit resolves to the id.@@ -337,9 +351,10 @@ export class CitizenPopulation {return inst;}- /** Advance idle loops + fade-ins. Cheap: one mixer.update per citizen. */+ /** Advance idle loops + fade-ins + locomotion. Cheap: one mixer.update per citizen. */update(dt) {for (const inst of this.instances) {+ this._advanceMotion(inst, dt);if (!this.reducedMotion) inst.mixer?.update(dt);if (inst.fade) {inst.fade.t += dt;@@ -354,6 +369,121 @@ export class CitizenPopulation {}}+ // ── Locomotion + economy state (Task 06) ──────────────────────────────────+ // 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.+ if (inst.busyRing) {+ const target = inst.busy ? 0.55 + 0.25 * Math.sin((inst.busyT += dt) * 3.2) : 0;+ 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));+ }+ }++ // Completion celebrate — a short, tasteful hop (skipped under reduced motion).+ if (inst.celebrateT != null) {+ inst.celebrateT += dt;+ const p = inst.celebrateT / CELEBRATE_SEC;+ if (p >= 1) { inst.celebrateT = null; inst.model.position.y = 0; }+ else { inst.model.position.y = Math.sin(p * Math.PI) * 0.32; }+ }++ // Walk toward the active target.+ if (inst.walkTarget) {+ const g = inst.group.position;+ const tx = inst.walkTarget.x, tz = inst.walkTarget.z;+ const dx = tx - g.x, dz = tz - g.z;+ const dist = Math.hypot(dx, dz);+ if (dist <= ARRIVE_EPS) {+ const cb = inst.onArrive;+ inst.walkTarget = null; inst.onArrive = null;+ this._playMotion(inst, 'idle');+ if (cb) cb();+ } else {+ const step = Math.min(dist, WALK_SPEED * dt);+ g.x += (dx / dist) * step;+ g.z += (dz / dist) * step;+ inst.heading = Math.atan2(dx, dz);+ this._playMotion(inst, 'walk');+ let diff = inst.heading - inst.group.rotation.y;+ while (diff > Math.PI) diff -= Math.PI * 2;+ while (diff < -Math.PI) diff += Math.PI * 2;+ inst.group.rotation.y += diff * Math.min(1, dt * TURN_RATE);+ }+ }+ }++ // Crossfade a citizen between its idle and walk clips. No-op for rigs the+ // canonical clips can't drive (the model still translates — never a T-pose).+ _playMotion(inst, motion) {+ if (inst.motion === motion || !inst.mixer || this.reducedMotion) { inst.motion = motion; return; }+ inst.motion = motion;+ if (motion === 'walk' && inst.walkClip) {+ if (!inst.walkAction) inst.walkAction = inst.mixer.clipAction(inst.walkClip);+ inst.walkAction.reset().fadeIn(0.2).play();+ inst.idleAction?.fadeOut(0.2);+ } else {+ inst.idleAction?.reset().fadeIn(0.2).play();+ inst.walkAction?.fadeOut(0.2);+ }+ }++ _buildBusyRing(accent) {+ const geo = new RingGeometry(0.46, 0.6, 40);+ geo.rotateX(-Math.PI / 2);+ const mat = new MeshBasicMaterial({ color: accent, transparent: true, opacity: 0, side: DoubleSide, depthWrite: false });+ const ring = new Mesh(geo, mat);+ ring.renderOrder = 1;+ this.scene.add(ring);+ return ring;+ }++ /** Route a citizen to a world target; onArrive fires once when reached. */+ walkTo(id, target, onArrive) {+ const inst = this._byId.get(id);+ if (!inst || !target) return;+ const tx = Number(target.x), tz = Number(target.z);+ if (!Number.isFinite(tx) || !Number.isFinite(tz)) return;+ if (this.reducedMotion) {+ // No travelling motion under reduced motion — place + settle.+ inst.group.position.x = tx; inst.group.position.z = tz;+ inst.walkTarget = null;+ if (onArrive) onArrive();+ return;+ }+ inst.walkTarget = { x: tx, z: tz };+ inst.onArrive = typeof onArrive === 'function' ? onArrive : null;+ }++ /** Reflect an economy status — Busy shows a glowing profession-coloured ring. */+ setStatus(id, status) {+ const inst = this._byId.get(id);+ if (!inst) return;+ inst.busy = status === 'Busy';+ if (inst.busy && !inst.busyRing) {+ const accent = professionColor(inst.citizen.profession || inst.citizen.professions?.[0]?.key);+ inst.busyRing = this._buildBusyRing(accent);+ }+ }++ /** A short completion celebrate (a tasteful hop). No-op under reduced motion. */+ celebrate(id) {+ const inst = this._byId.get(id);+ if (!inst || this.reducedMotion) return;+ inst.celebrateT = 0;+ }++ /** Resolve a citizen by display name (pulse.recent carries names, not ids). */+ findByName(name) {+ if (!name) return null;+ const inst = this.instances.find((i) => i.citizen.displayName === name);+ if (!inst) return null;+ return { id: inst.citizen.id, position: this.worldPosition(inst.citizen.id) };+ }+/*** Hit-test pickable avatars. Returns the citizen id under the ray, or null.* @param {import('three').Raycaster} raycaster@@ -403,6 +533,11 @@ export class CitizenPopulation {for (const m of inst.materials) m.dispose?.();inst.label.material.map?.dispose?.();inst.label.material.dispose?.();+ if (inst.busyRing) {+ inst.busyRing.geometry.dispose();+ inst.busyRing.material.dispose();+ this.scene.remove(inst.busyRing);+ }inst.group.parent?.remove(inst.group);}this.instances = [];diff --git a/src/agora/job-detail.js b/src/agora/job-detail.jsindex 417f8cb74..f9900edb0 100644--- a/src/agora/job-detail.js+++ b/src/agora/job-detail.js@@ -8,6 +8,7 @@import { h, infoRow, rewardChip, copyChip } from './panel.js';import { fetchTask } from './api.js';import { mountVerifier } from './verify.js';+import { injectTrustSurfaceCss } from './trust-surface.css.js';import {explorerTxUrl, explorerAddressUrl, shortId, timeAgo, absoluteTime,professionLabel, formatThree,@@ -37,7 +38,19 @@ function stateBadge(state) {// proofHash, deliverableUrl, txSignature }// ctx: { onOpenPassport(actorPda) } — optional cross-linksexport async function renderJobDetail(panel, opts = {}, ctx = {}) {+ injectTrustSurfaceCss();const cluster = opts.cluster === 'mainnet' ? 'mainnet' : 'devnet';++ // An x402 bazaar service marker isn't an on-chain AgenC task with a lifecycle —+ // it's a pay-per-call endpoint. Render its real detail honestly instead of a+ // timeline that doesn't exist.+ if (opts.source === 'x402' || (!opts.taskPda && !(opts.creator && opts.taskId) && opts.resource)) {+ panel.setHeader(opts.title || 'Service', 'x402 service · pay-per-call');+ panel.open(opts.opener);+ panel.setBody(buildService(opts));+ return;+ }+panel.setHeader(opts.title || 'Job', opts.taskPda ? jobSubheader(opts.taskPda, cluster) : 'On-chain task');panel.setLoading('Loading job lifecycle…');panel.open(opts.opener);@@ -177,19 +190,43 @@ function buildVerifySection(opts, state) {}function actorLink(pda, cluster, ctx) {- const link = addressLink(pda, cluster);- if (typeof ctx.onOpenPassport === 'function') {- const btn = h('button', {- class: 'agora-actor-link', type: 'button',- title: 'Open this citizen\'s passport',- }, [shortId(pda, 4, 4)]);- btn.addEventListener('click', () => ctx.onOpenPassport(pda));- return h('span', { class: 'agora-timeline-actor' }, [- h('span', { class: 'agora-muted' }, ['by ']), btn,- h('a', { class: 'agora-addr-ext', href: explorerAddressUrl(pda, cluster), target: '_blank', rel: 'noopener noreferrer', title: 'View account on Explorer', 'aria-label': 'View account on Explorer' }, ['↗']),- ]);- }- return h('span', { class: 'agora-timeline-actor' }, [h('span', { class: 'agora-muted' }, ['by ']), link]);+ // Open the actor's passport: prefer an explicit callback, else broadcast the+ // decoupled event the passport panel listens for. Always keep the raw Explorer+ // link so the on-chain account is one click away.+ const btn = h('button', {+ class: 'agora-actor-link', type: 'button',+ title: 'Open this citizen\'s passport',+ }, [shortId(pda, 4, 4)]);+ btn.addEventListener('click', () => {+ if (typeof ctx.onOpenPassport === 'function') ctx.onOpenPassport(pda);+ else window.dispatchEvent(new CustomEvent('agora:open-passport', { detail: { agentPda: pda } }));+ });+ return h('span', { class: 'agora-timeline-actor' }, [+ h('span', { class: 'agora-muted' }, ['by ']), btn,+ h('a', { class: 'agora-addr-ext', href: explorerAddressUrl(pda, cluster), target: '_blank', rel: 'noopener noreferrer', title: 'View account on Explorer', 'aria-label': 'View account on Explorer' }, ['↗']),+ ]);+}++// An x402 service marker's honest detail: what it does, what it costs, and a link+// to call it. No lifecycle/verify — it's a live endpoint, not a proven artifact.+function buildService(opts) {+ const reward = opts.reward || null;+ return [+ opts.description ? h('p', { class: 'agora-service-desc' }, [opts.description]) : null,+ h('div', { class: 'agora-facts' }, [+ infoRow('Type', 'x402 · pay-per-call'),+ opts.profession ? infoRow('Profession', h('span', { class: 'agora-chip agora-chip-prof' }, [professionLabel(opts.profession)])) : null,+ reward ? infoRow('Price', h('span', { class: 'agora-mono-sm' }, [reward.label || '—'])) : null,+ reward?.network ? infoRow('Network', reward.network) : null,+ reward?.currency ? infoRow('Currency', reward.currency) : null,+ ].filter(Boolean)),+ opts.resource ? h('div', { class: 'agora-verify-actions' }, [+ h('a', { class: 'agora-btn agora-btn-ghost', href: opts.resource, target: '_blank', rel: 'noopener noreferrer' }, ['Open endpoint ↗']),+ ]) : null,+ h('p', { class: 'agora-muted agora-section-empty' }, [+ 'A Fetcher citizen claims this by calling the endpoint and returning the result — value flows multi-hop through the Commons.',+ ]),+ ].filter(Boolean);}function addressLink(address, cluster) {diff --git a/src/agora/trust-surface.css.js b/src/agora/trust-surface.css.jsnew file mode 100644index 000000000..78a1523d1--- /dev/null+++ b/src/agora/trust-surface.css.js@@ -0,0 +1,258 @@+// Agora — styles for the Task 07 trust surface (job detail, verifier, the rich+// passport additions, cross-chain handshake). Injected at runtime (id-guarded)+// by trust-surface.js and passport-panel.js so this layer never has to touch the+// shared, concurrently-edited src/agora/agora.css. Matches the Commons theme:+// near-black panels, hairline borders, the blue→violet accent.++export const TRUST_SURFACE_CSS = `+.agora-panel {+ position: fixed; top: 0; right: 0; bottom: 0;+ width: min(420px, 100vw);+ display: flex; flex-direction: column;+ background: rgba(13, 15, 20, 0.94);+ -webkit-backdrop-filter: blur(18px); backdrop-filter: blur(18px);+ border-left: 1px solid rgba(255, 255, 255, 0.1);+ box-shadow: -24px 0 80px rgba(0, 0, 0, 0.55);+ z-index: 60;+ transform: translateX(102%); opacity: 0;+ transition: transform 0.32s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.32s ease;+ color: rgba(255, 255, 255, 0.9);+ font-family: 'Inter', ui-sans-serif, system-ui, sans-serif;+}+.agora-panel.is-open { transform: none; opacity: 1; }+.agora-panel:focus { outline: none; }+.agora-panel-head {+ display: flex; align-items: flex-start; gap: 12px;+ padding: 18px 18px 14px;+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);+}+.agora-panel-head-text { flex: 1; min-width: 0; }+.agora-panel-title {+ font-size: 17px; font-weight: 650; line-height: 1.25;+ color: #fff; word-break: break-word;+}+.agora-panel-sub { margin-top: 4px; font-size: 12px; color: rgba(255, 255, 255, 0.45); }+.agora-panel-close {+ flex: none; width: 30px; height: 30px; border-radius: 8px;+ display: grid; place-items: center; cursor: pointer;+ background: rgba(255, 255, 255, 0.05); color: rgba(255, 255, 255, 0.7);+ border: 1px solid rgba(255, 255, 255, 0.1); font-size: 14px;+ transition: background 0.15s ease, color 0.15s ease;+}+.agora-panel-close:hover { background: rgba(255, 255, 255, 0.1); color: #fff; }+.agora-panel-close:focus-visible { outline: 2px solid #6da1ff; outline-offset: 2px; }+.agora-panel-body { flex: 1; overflow-y: auto; padding: 16px 18px 28px; overscroll-behavior: contain; }++/* ── sub-header chips ─────────────────────────────────────────────────────── */+.agora-sub-row { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; }+.agora-sub-code { font-family: ui-monospace, monospace; font-size: 11px; color: rgba(255, 255, 255, 0.5); }+.agora-chip {+ display: inline-flex; align-items: center; gap: 5px;+ font-size: 11px; font-weight: 550; letter-spacing: 0.02em;+ padding: 2px 8px; border-radius: 999px;+ background: rgba(255, 255, 255, 0.07); color: rgba(255, 255, 255, 0.78);+ border: 1px solid rgba(255, 255, 255, 0.1);+}+.agora-chip-cluster { text-transform: lowercase; color: #8fb5ff; border-color: rgba(109, 161, 255, 0.3); background: rgba(109, 161, 255, 0.1); }+.agora-chip-prof { color: #d6c3ff; border-color: rgba(150, 120, 255, 0.3); background: rgba(150, 120, 255, 0.1); }++/* ── key/value + facts ────────────────────────────────────────────────────── */+.agora-facts { display: flex; flex-direction: column; gap: 2px; margin: 6px 0; }+.agora-kv { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; padding: 7px 0; border-bottom: 1px solid rgba(255, 255, 255, 0.05); }+.agora-kv.wide { flex-direction: column; align-items: stretch; gap: 4px; }+.agora-kv-key { font-size: 12px; color: rgba(255, 255, 255, 0.45); letter-spacing: 0.02em; flex: none; }+.agora-kv-val { font-size: 13px; color: rgba(255, 255, 255, 0.9); text-align: right; word-break: break-word; }+.agora-muted { color: rgba(255, 255, 255, 0.4); }+.agora-mono-sm { font-family: ui-monospace, monospace; font-size: 11px; color: rgba(255, 255, 255, 0.7); word-break: break-all; }++/* ── reward chip ($THREE only) ────────────────────────────────────────────── */+.agora-reward { display: inline-flex; align-items: baseline; gap: 5px; }+.agora-reward-amt { font-size: 14px; font-weight: 650; color: #fff; font-variant-numeric: tabular-nums; }+.agora-reward-coin { font-size: 11px; font-weight: 600; color: #8a6dff; letter-spacing: 0.02em; }++/* ── sections ─────────────────────────────────────────────────────────────── */+.agora-section { margin-top: 22px; }+.agora-section-title { display: flex; align-items: baseline; gap: 8px; font-size: 12px; font-weight: 650; text-transform: uppercase; letter-spacing: 0.1em; color: rgba(255, 255, 255, 0.5); margin-bottom: 12px; }+.agora-section-hint { font-size: 10px; font-weight: 500; text-transform: none; letter-spacing: 0; color: rgba(255, 255, 255, 0.35); }+.agora-section-empty { font-size: 13px; line-height: 1.55; }++/* ── badges ───────────────────────────────────────────────────────────────── */+.agora-badge { display: inline-flex; align-items: center; font-size: 11px; font-weight: 650; padding: 3px 10px; border-radius: 999px; letter-spacing: 0.03em; text-transform: uppercase; border: 1px solid transparent; }+.agora-badge.is-open { color: #7ee0a8; background: rgba(80, 220, 140, 0.12); border-color: rgba(80, 220, 140, 0.3); }+.agora-badge.is-claimed { color: #ffd27a; background: rgba(255, 200, 90, 0.12); border-color: rgba(255, 200, 90, 0.3); }+.agora-badge.is-completed { color: #8fb5ff; background: rgba(109, 161, 255, 0.14); border-color: rgba(109, 161, 255, 0.32); }+.agora-badge.is-cancelled, .agora-badge.is-expired { color: rgba(255,255,255,0.5); background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.14); }+.agora-badge.is-disputed { color: #ff9a8f; background: rgba(255, 120, 110, 0.12); border-color: rgba(255, 120, 110, 0.3); }+.agora-job-meta { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 4px; }+.agora-job-reward { display: inline-flex; align-items: center; gap: 8px; }++/* ── timeline ─────────────────────────────────────────────────────────────── */+.agora-timeline { list-style: none; margin: 0; padding: 0; }+.agora-timeline-item { position: relative; display: flex; gap: 12px; padding: 0 0 16px 0; }+.agora-timeline-item::before { content: ''; position: absolute; left: 5px; top: 14px; bottom: -2px; width: 1px; background: rgba(255, 255, 255, 0.12); }+.agora-timeline-item:last-child::before { display: none; }+.agora-timeline-dot { flex: none; width: 11px; height: 11px; border-radius: 50%; margin-top: 3px; background: #6da1ff; box-shadow: 0 0 0 3px rgba(109, 161, 255, 0.18); z-index: 1; }+.agora-timeline-item.is-done .agora-timeline-dot { background: linear-gradient(135deg, #5d8bff, #8a6dff); }+.agora-timeline-body { flex: 1; min-width: 0; }+.agora-timeline-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }+.agora-timeline-label { font-size: 13px; font-weight: 600; color: #fff; }+.agora-timeline-time { font-size: 11px; color: rgba(255, 255, 255, 0.4); font-variant-numeric: tabular-nums; }+.agora-timeline-desc { font-size: 12px; color: rgba(255, 255, 255, 0.5); margin-top: 2px; }+.agora-timeline-links { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 6px; }+.agora-timeline-actor { font-size: 12px; }+.agora-tx-link, .agora-addr, .agora-actor-link, .agora-addr-ext, .agora-chaincard-link {+ font-size: 11px; color: #8fb5ff; text-decoration: none; font-family: ui-monospace, monospace;+ border-bottom: 1px solid transparent; transition: border-color 0.15s ease, color 0.15s ease;+}+.agora-tx-link:hover, .agora-addr:hover, .agora-actor-link:hover, .agora-addr-ext:hover, .agora-chaincard-link:hover { color: #b9d2ff; border-bottom-color: rgba(143, 181, 255, 0.5); }+.agora-actor-link { background: none; border: none; cursor: pointer; padding: 0; }+.agora-tx-link:focus-visible, .agora-addr:focus-visible, .agora-actor-link:focus-visible, .agora-copy:focus-visible, .agora-verify-chip:focus-visible { outline: 2px solid #6da1ff; outline-offset: 2px; border-radius: 3px; }++/* ── copy chip ────────────────────────────────────────────────────────────── */+.agora-copy {+ display: inline-flex; align-items: center; gap: 4px; cursor: pointer;+ background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 6px; padding: 2px 6px; font-size: 11px; color: rgba(255, 255, 255, 0.6);+ font-family: ui-monospace, monospace; transition: background 0.15s ease, color 0.15s ease;+}+.agora-copy:hover { background: rgba(255, 255, 255, 0.1); color: #fff; }+.agora-copy.is-ok { color: #7ee0a8; border-color: rgba(80, 220, 140, 0.4); }+.agora-copy.is-fail { color: #ff9a8f; border-color: rgba(255, 120, 110, 0.4); }+.agora-copy-icon { font-size: 11px; }++/* ── hashes ───────────────────────────────────────────────────────────────── */+.agora-hash-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 6px 0; }+.agora-hash-label { font-size: 11px; color: rgba(255, 255, 255, 0.45); flex: none; min-width: 92px; }+.agora-hash, .agora-hash-inline { font-family: ui-monospace, monospace; font-size: 12px; color: rgba(255, 255, 255, 0.82); word-break: break-all; }+.agora-hash.is-ok { color: #7ee0a8; }+.agora-hash.is-bad { color: #ff9a8f; }++/* ── verifier ─────────────────────────────────────────────────────────────── */+.agora-verify { display: flex; flex-direction: column; gap: 10px; }+.agora-verify-actions { display: flex; gap: 8px; flex-wrap: wrap; }+.agora-btn-icon { margin-right: 6px; }+.agora-btn.is-busy { opacity: 0.7; pointer-events: none; }+.agora-btn-ghost { background: transparent; }+.agora-verify-note { font-size: 12px; line-height: 1.55; color: rgba(255, 255, 255, 0.55); }+.agora-verify-progress { display: flex; flex-direction: column; gap: 6px; }+.agora-verify-progress-label { font-size: 12px; color: rgba(255, 255, 255, 0.55); }+.agora-verdict { display: flex; gap: 12px; padding: 12px; border-radius: 12px; border: 1px solid; }+.agora-verdict.is-match { background: rgba(80, 220, 140, 0.08); border-color: rgba(80, 220, 140, 0.3); }+.agora-verdict.is-mismatch { background: rgba(255, 110, 100, 0.08); border-color: rgba(255, 110, 100, 0.32); }+.agora-verdict.is-error { background: rgba(255, 190, 90, 0.08); border-color: rgba(255, 190, 90, 0.3); }+.agora-verdict-icon { flex: none; font-size: 20px; line-height: 1.1; }+.agora-verdict.is-match .agora-verdict-icon { color: #7ee0a8; }+.agora-verdict.is-mismatch .agora-verdict-icon { color: #ff9a8f; }+.agora-verdict.is-error .agora-verdict-icon { color: #ffd27a; }+.agora-verdict-text { display: flex; flex-direction: column; gap: 3px; }+.agora-verdict-text strong { font-size: 13px; color: #fff; }+.agora-verdict-sub { font-size: 12px; line-height: 1.5; color: rgba(255, 255, 255, 0.6); }+.agora-verify-hashes { margin-top: 10px; display: flex; flex-direction: column; gap: 2px; }+.agora-glb-viewer { margin-top: 12px; width: 100%; height: 240px; border-radius: 12px; overflow: hidden; background: #0b0c10; border: 1px solid rgba(255, 255, 255, 0.08); }+.agora-glb-viewer canvas { display: block; width: 100%; height: 100%; cursor: grab; }+.agora-glb-viewer canvas:active { cursor: grabbing; }+.agora-glb-caption { font-size: 11px; color: rgba(255, 255, 255, 0.4); margin-top: 6px; text-align: center; }+.agora-glb-fail { padding: 16px; font-size: 12px; color: #ff9a8f; }++/* ── states (loading / error / empty) ─────────────────────────────────────── */+.agora-state { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 10px; padding: 40px 16px; }+.agora-state-loading { align-items: stretch; padding: 8px 0; }+.agora-state-icon { font-size: 26px; color: rgba(255, 255, 255, 0.3); }+.agora-state-msg { font-size: 14px; color: rgba(255, 255, 255, 0.75); }+.agora-state-hint { font-size: 12px; color: rgba(255, 255, 255, 0.45); line-height: 1.5; }+.agora-skel { display: block; border-radius: 6px; background: linear-gradient(90deg, rgba(255,255,255,0.04), rgba(255,255,255,0.09), rgba(255,255,255,0.04)); background-size: 200% 100%; animation: agora-shimmer 1.4s ease-in-out infinite; }+.agora-skel-line { height: 13px; margin: 7px 0; }+.agora-skel-line.short { width: 60%; }+.agora-skel-block { height: 90px; margin: 12px 0; }+@keyframes agora-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+@media (prefers-reduced-motion: reduce) { .agora-skel { animation: none; } .agora-panel { transition: opacity 0.2s ease; transform: none; } }++/* ── passport additions (grade / on-chain / stats / handshake) ────────────── */+.agora-passport-id { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }+.agora-monogram { flex: none; width: 52px; height: 52px; border-radius: 14px; display: grid; place-items: center; font-size: 22px; font-weight: 700; color: #fff; }+.agora-passport-id-text { flex: 1; min-width: 0; }+.agora-passport-name { font-size: 18px; font-weight: 650; color: #fff; }+.agora-passport-meta { display: flex; align-items: center; gap: 8px; margin-top: 5px; flex-wrap: wrap; }+.agora-status { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 600; color: rgba(255,255,255,0.7); }+.agora-status-dot { width: 7px; height: 7px; border-radius: 50%; background: rgba(255,255,255,0.4); }+.agora-status.is-active .agora-status-dot { background: #4ade80; box-shadow: 0 0 6px rgba(74,222,128,0.7); }+.agora-status.is-busy .agora-status-dot { background: #ffd27a; box-shadow: 0 0 6px rgba(255,210,122,0.7); }+.agora-status.is-idle .agora-status-dot { background: #8fb5ff; }+.agora-status.is-suspended .agora-status-dot { background: #ff9a8f; }+.agora-grade { flex: none; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 14px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.04); }+.agora-grade-letter { font-size: 20px; font-weight: 750; line-height: 1; }+.agora-grade-label { font-size: 8px; text-transform: uppercase; letter-spacing: 0.06em; color: rgba(255,255,255,0.45); margin-top: 3px; text-align: center; }+.agora-grade.tier-a .agora-grade-letter { color: #7ee0a8; }+.agora-grade.tier-b .agora-grade-letter { color: #8fb5ff; }+.agora-grade.tier-c .agora-grade-letter { color: #ffd27a; }+.agora-grade.tier-d .agora-grade-letter { color: #ffb38f; }+.agora-grade.tier-new .agora-grade-letter { color: rgba(255,255,255,0.4); }+.agora-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(86px, 1fr)); gap: 8px; margin: 4px 0 4px; }+.agora-stat { background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.07); border-radius: 10px; padding: 10px; }+.agora-stat-val { font-size: 17px; font-weight: 700; color: #fff; font-variant-numeric: tabular-nums; }+.agora-stat-label { font-size: 11px; color: rgba(255,255,255,0.55); margin-top: 2px; }+.agora-stat-sub { font-size: 9px; color: rgba(255,255,255,0.35); text-transform: uppercase; letter-spacing: 0.04em; margin-top: 1px; }+.agora-onchain .agora-section-title { color: rgba(143,181,255,0.7); }+.agora-live-dot { width: 7px; height: 7px; border-radius: 50%; background: #4ade80; box-shadow: 0 0 6px rgba(74,222,128,0.8); display: inline-block; animation: agora-pulse 2s ease-in-out infinite; }+@keyframes agora-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }+.agora-prof-chips { display: flex; flex-wrap: wrap; gap: 6px; }++/* ── activity feed (passport) ─────────────────────────────────────────────── */+.agora-activity { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }+.agora-activity-item { padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.05); }+.agora-activity-narr { font-size: 13px; color: rgba(255,255,255,0.88); line-height: 1.45; }+.agora-activity-foot { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 5px; }+.agora-activity-time { font-size: 11px; color: rgba(255,255,255,0.4); }+.agora-activity-rep { font-size: 11px; color: #7ee0a8; font-variant-numeric: tabular-nums; }+.agora-activity-links { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 6px; }+.agora-verify-chip { display: inline-flex; align-items: center; gap: 4px; cursor: pointer; font-size: 11px; font-weight: 600; color: #8fb5ff; background: rgba(109,161,255,0.1); border: 1px solid rgba(109,161,255,0.28); border-radius: 6px; padding: 2px 8px; transition: background 0.15s ease; }+.agora-verify-chip:hover { background: rgba(109,161,255,0.2); }++/* ── handshake ────────────────────────────────────────────────────────────── */+.agora-handshake-explainer { font-size: 13px; line-height: 1.55; color: rgba(255,255,255,0.62); margin-bottom: 14px; }+.agora-handshake-explainer strong { color: #fff; }+.agora-handshake-bridge { display: flex; align-items: stretch; gap: 6px; }+.agora-chaincard { flex: 1; min-width: 0; background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.09); border-radius: 12px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }+.agora-chaincard-head { display: flex; align-items: center; gap: 8px; }+.agora-chaincard-glyph { font-size: 18px; }+.agora-chaincard-chain { font-size: 13px; font-weight: 650; color: #fff; }+.agora-chaincard-standard { font-size: 10px; color: rgba(255,255,255,0.45); text-transform: uppercase; letter-spacing: 0.05em; }+.agora-chaincard-id { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }+.agora-chaincard-val { font-family: ui-monospace, monospace; font-size: 12px; color: rgba(255,255,255,0.8); word-break: break-all; }+.agora-handshake-merge { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; padding: 0 2px; }+.agora-handshake-merge-line { width: 1px; flex: 1; background: linear-gradient(rgba(138,109,255,0), rgba(138,109,255,0.6)); }+.agora-handshake-merge-line:last-child { background: linear-gradient(rgba(138,109,255,0.6), rgba(138,109,255,0)); }+.agora-handshake-merge-node { font-size: 14px; color: #8a6dff; }+.agora-handshake-canonical { margin-top: 12px; padding: 12px; background: rgba(138,109,255,0.07); border: 1px solid rgba(138,109,255,0.25); border-radius: 12px; }+.agora-handshake-canon-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 8px; }+.agora-handshake-canon-title { font-size: 12px; font-weight: 650; text-transform: uppercase; letter-spacing: 0.06em; color: rgba(255,255,255,0.6); }+.agora-handshake-verified { font-size: 11px; font-weight: 650; color: #7ee0a8; }+.agora-handshake-unverified { font-size: 11px; font-weight: 650; color: #ffd27a; }+.agora-handshake-flags { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 8px; }+.agora-flag { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: rgba(255,255,255,0.55); }+.agora-flag-dot { width: 6px; height: 6px; border-radius: 50%; background: rgba(255,255,255,0.3); }+.agora-flag.is-on .agora-flag-dot { background: #4ade80; }+.agora-flag.is-off .agora-flag-dot { background: #ff9a8f; }+.agora-handshake-loading { display: flex; flex-direction: column; gap: 6px; }+.agora-handshake-loading-label { font-size: 12px; color: rgba(255,255,255,0.5); }++.sr-only, .agora-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }++@media (max-width: 480px) {+ .agora-panel { width: 100vw; }+ .agora-handshake-bridge { flex-direction: column; }+ .agora-handshake-merge { flex-direction: row; padding: 4px 0; }+ .agora-handshake-merge-line { width: auto; height: 1px; }+}+`;++let _injected = false;+export function injectTrustSurfaceCss() {+ if (_injected || (typeof document !== 'undefined' && document.getElementById('agora-trust-surface-styles'))) return;+ if (typeof document === 'undefined') return;+ const style = document.createElement('style');+ style.id = 'agora-trust-surface-styles';+ style.textContent = TRUST_SURFACE_CSS;+ document.head.appendChild(style);+ _injected = true;+}diff --git a/workers/agora-citizens/agenc.js b/workers/agora-citizens/agenc.jsindex 62713a3d9..ceeb46e68 100644--- a/workers/agora-citizens/agenc.js+++ b/workers/agora-citizens/agenc.js@@ -26,6 +26,26 @@ async function sdk() {return _sdk;}+// The upstream protocol SDK — for PDA derivation helpers the three.ws adapter+// uses internally but doesn't re-export (e.g. deriveTaskPda). Same lazy pattern.+let _tetsuo = null;+async function tetsuo() {+ if (_tetsuo) return _tetsuo;+ _tetsuo = await import('@tetsuo-ai/sdk');+ return _tetsuo;+}++/**+ * Derive a task's on-chain PDA from its creator + 32-byte taskId. getTasksByCreator+ * returns TaskStatus rows WITHOUT the PDA, but claim/complete need it — so we+ * re-derive it deterministically (no RPC).+ */+export async function deriveTaskPda(client, creator, taskId) {+ const t = await tetsuo();+ const creatorPk = creator instanceof PublicKey ? creator : new PublicKey(creator);+ return t.deriveTaskPda(creatorPk, taskId, client.programId);+}+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));/**diff --git a/workers/agora-citizens/demand.js b/workers/agora-citizens/demand.jsindex e5f2a04f3..e98e00ba4 100644--- a/workers/agora-citizens/demand.js+++ b/workers/agora-citizens/demand.js@@ -1,12 +1,14 @@-// agora-citizens — the demand generator (Task 03). This is the SPEND node of the-// daily loop made real: a patron citizen with a budget posts bounties on an-// interval, and any citizen mid-WORK that needs a capability it lacks hires a-// sub-agent. Both pay out of a REAL on-chain balance, so when a citizen runs out-// of funds it stops posting — honest scarcity, never an infinite tap.+// agora-citizens — the demand generator (Task 03). The SPEND node of the daily+// loop, made real: a patron citizen with a budget posts bounties on an interval,+// and a citizen working a high-value job hires a sub-agent (true agent-to-agent+// hiring). Both pay out of a REAL balance, so when a citizen exhausts its budget+// it stops posting — honest scarcity, never an infinite tap.//-// This module is the bridge between policy.js (pure decisions) and post.js (real-// escrowed bounties). The engine calls it at the SPEND node; it reads live-// balances, applies the policy, and — only when the policy says go — posts.+// This bridges policy.js (pure decisions) and post.js (real escrowed bounties):+// it reads live balances, applies the policy, and posts only when the policy says+// go. The patron's "budget" is a bounded allowance over its real balance — the+// on-chain balance is the hard gate (it matters most on mainnet $THREE, where no+// faucet refills it), the allowance bounds devnet posting so it's visibly finite.import { PublicKey } from '@solana/web3.js';import { decidePatronPost, decideHire } from './policy.js';@@ -18,23 +20,79 @@ import { log } from './log.js';// bounty can't strand a citizen unable to pay for its own work.const FEE_HEADROOM_LAMPORTS = 12_000_000n; // 0.012 SOL-// Mainnet spend cap (Task 03 guardrail: escrow is real money). Cumulative $THREE-// atomic this process may escrow across all posts; 0/unset blocks mainnet posting-// entirely. Devnet ignores the cap (synthetic SOL).-function mainnetSpendCapAtomic() {- const raw = (process.env.AGORA_MAINNET_SPEND_CAP_ATOMIC || '').trim();- if (!raw) return 0n;+function bigEnv(name, def) {+ const raw = (process.env[name] || '').trim();+ if (!raw) return def;try {return BigInt(raw);} catch {- return 0n;+ return def;}}+function intEnv(name, def) {+ const n = Number(process.env[name]);+ return Number.isFinite(n) ? n : def;+}+function boolEnv(name, def) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ return /^(1|true|yes|on)$/i.test(String(raw).trim());+}++/** Is agent-to-agent hiring enabled? Default on for devnet. */+export function hiringEnabled(cfg) {+ return boolEnv('AGORA_ENABLE_HIRING', cfg.cluster === 'devnet');+}-let _spentThisRunAtomic = 0n; // mainnet only — cumulative escrow posted this process+/** Reward a worker offers when hiring a sub-agent (cluster reward unit, atomic). */+export function subtaskReward(cfg) {+ return bigEnv('AGORA_SUBTASK_REWARD_ATOMIC', BigInt(cfg.taskRewardLamports));+}-/** Spendable reward balance for a poster, in the cluster's reward unit (atomic). */-async function spendableBalance(cfg, connection, walletPubkey) {+/**+ * The patron's tier schedule — the visible career ladder. Rewards scale with the+ * reputation gate so high-rep work pays more (docs: README § Reputation ladder).+ * Authored in the cluster's reward unit (devnet lamports; mainnet would override+ * via env). profession is Fetcher — the one working profession shipped (Task 02).+ */+export function defaultPatronTiers(cfg) {+ const base = BigInt(cfg.taskRewardLamports); // devnet: 0.001 SOL default+ return [+ { tier: 'apprentice', profession: 'fetcher', rewardAtomic: base, minReputation: 0 },+ { tier: 'apprentice', profession: 'fetcher', rewardAtomic: base, minReputation: 0 },+ { tier: 'journeyman', profession: 'fetcher', rewardAtomic: base * 2n, minReputation: 5 },+ { tier: 'master', profession: 'fetcher', rewardAtomic: base * 4n, minReputation: 20 },+ ];+}++/**+ * Designate patrons in the fleet and attach their budget + tracking state. By+ * default the first AGORA_PATRON_COUNT citizens become patrons (they still work+ * jobs themselves — a patron is also a Fetcher). The budget is a bounded+ * allowance so devnet demand is visibly finite. Mutates the citizen objects.+ */+export function markPatrons(citizens, cfg) {+ const count = Math.max(0, Math.min(intEnv('AGORA_PATRON_COUNT', 1), citizens.length));+ const budgetAtomic = bigEnv('AGORA_PATRON_BUDGET_ATOMIC', BigInt(cfg.taskRewardLamports) * 30n);+ const minPostIntervalMs = Math.max(5_000, intEnv('AGORA_PATRON_POST_INTERVAL_MS', 90_000));+ const tiers = defaultPatronTiers(cfg);+ for (let i = 0; i < count; i++) {+ const c = citizens[i];+ c.patron = { tiers, budgetAtomic, minPostIntervalMs };+ c.postedSpentAtomic = 0n;+ c.lastPostAt = 0;+ c.postedCount = 0;+ log.info('patron designated', {+ citizen: c.spec.displayName,+ budgetAtomic: budgetAtomic.toString(),+ intervalMs: minPostIntervalMs,+ });+ }+ return count;+}++// Spendable reward balance for a poster, in the cluster's reward unit (atomic).+async function onchainBalance(cfg, connection, walletPubkey) {if (cfg.cluster === 'mainnet') {const tokenAccount = (process.env.AGORA_THREE_TOKEN_ACCOUNT || '').trim();if (!tokenAccount) return 0n;@@ -46,7 +104,6 @@ async function spendableBalance(cfg, connection, walletPubkey) {return 0n;}}- // devnet — native SOL (lamports)try {return BigInt(await connection.getBalance(walletPubkey));} catch (err) {@@ -55,14 +112,17 @@ async function spendableBalance(cfg, connection, walletPubkey) {}}-// Headroom is only meaningful for the native-SOL devnet path (reward unit ==-// fee unit). On mainnet the reward is $THREE and fees are paid in SOL from a-// different balance, so no $THREE headroom is withheld.+// Headroom only applies to the native-SOL devnet path (reward unit == fee unit).function headroomFor(cfg) {return cfg.cluster === 'mainnet' ? 0n : FEE_HEADROOM_LAMPORTS;}-// Enforce the mainnet escrow spend cap. Returns true if this reward is allowed.+// Mainnet escrow spend cap (Task 03 guardrail — escrow is real money). Cumulative+// $THREE atomic this process may post; 0/unset blocks mainnet posting entirely.+function mainnetSpendCapAtomic() {+ return bigEnv('AGORA_MAINNET_SPEND_CAP_ATOMIC', 0n);+}+let _spentThisRunAtomic = 0n;function withinSpendCap(cfg, rewardAtomic) {if (cfg.cluster !== 'mainnet') return true;const cap = mainnetSpendCapAtomic();@@ -78,95 +138,112 @@ function withinSpendCap(cfg, rewardAtomic) {}/**- * Patron demand: maybe post a bounty this tick.+ * Patron demand: maybe post a bounty this tick. Reads the citizen's REAL balance,+ * caps it by the remaining allowance, and posts only if the policy clears it.+ * Updates the citizen's spend/interval tracking on success.*- * @param {object} args- * @param {object} args.cfg, args.store- * @param {object} args.citizen poster citizen row (needs .patron config, .id, .agentIdHex, .displayName)- * @param {object} args.client poster's signer-bound AgenC client- * @param {PublicKey} args.wallet poster's wallet pubkey (for the balance read)- * @param {number} args.postedCount posts so far (tier rotation)- * @param {number} args.lastPostAt epoch ms of last post (interval guard)- * @returns {object|null} the post result, or null if the policy held / it's not a patron+ * @returns {object|null} the post result, or null if the policy held.*/-export async function maybePatronPost({ cfg, store, citizen, client, wallet, postedCount, lastPostAt }) {+export async function maybePatronPost(ctx, citizen) {+ const { cfg, store } = ctx;if (!citizen?.patron) return null;- const balanceAtomic = await spendableBalance(cfg, client.connection, wallet);++ const bal = await onchainBalance(cfg, citizen.client.connection, citizen.signer.publicKey);+ const remainingBudget = citizen.patron.budgetAtomic - citizen.postedSpentAtomic;+ // Effective budget is the lesser of the real balance and the remaining+ // allowance — when either is exhausted, scarcity kicks in and posting stops.+ const effectiveBalance = bal < remainingBudget ? bal : remainingBudget;+const decision = decidePatronPost({citizen,now: Date.now(),- lastPostAt: lastPostAt || 0,- balanceAtomic,+ lastPostAt: citizen.lastPostAt,+ balanceAtomic: effectiveBalance,headroomAtomic: headroomFor(cfg),- postedCount: postedCount || 0,+ postedCount: citizen.postedCount,});+if (!decision.post) {if (decision.reason === 'insufficient_funds') {- log.loop('patron out of budget — holding', { citizen: citizen.displayName });+ log.loop('patron out of budget — holding (honest scarcity)', {+ citizen: citizen.spec.displayName,+ remaining: remainingBudget.toString(),+ balance: bal.toString(),+ });}return null;}if (!withinSpendCap(cfg, decision.plan.rewardAtomic)) return null;if (cfg.dryRun) {- log.loop('[dry] would post bounty', { citizen: citizen.displayName, plan: planLog(decision.plan) });+ log.loop('[dry] would post bounty', { citizen: citizen.spec.displayName, tier: decision.plan.tier });return null;}- const result = await postBounty({ cfg, store, client, poster: citizen, plan: decision.plan });+ const result = await postBounty({+ cfg,+ store,+ client: citizen.client,+ poster: { id: citizen.id, agentIdHex: citizen.agentIdHex, displayName: citizen.spec.displayName },+ plan: decision.plan,+ });++ citizen.postedSpentAtomic += BigInt(decision.plan.rewardAtomic);+ citizen.lastPostAt = Date.now();+ citizen.postedCount += 1;if (cfg.cluster === 'mainnet') _spentThisRunAtomic += BigInt(decision.plan.rewardAtomic);- log.info('bounty posted', { citizen: citizen.displayName, taskPda: result.taskPda, reward: result.rewardLabel, tx: result.txSignature });++ log.info('bounty posted', {+ citizen: citizen.spec.displayName,+ tier: decision.plan.tier,+ minReputation: decision.plan.minReputation,+ taskPda: result.taskPda,+ reward: result.rewardLabel,+ tx: result.txSignature,+ });return result;}/**- * Sub-task hiring: a worker mid-WORK hires a sub-agent for a capability it lacks- * (true agent-to-agent hiring). Pays from the worker's own balance.+ * Sub-task hiring: a citizen working a high-value job hires a sub-agent (real+ * agent-to-agent hiring). Pays from the worker's own balance — same scarcity rule.*- * @param {object} args.parent { taskPda, label } the parent job being worked- * @param {string} args.neededProfession- * @param {bigint} args.subRewardAtomic- * @returns {object|null} the hire post result, or null if held+ * @param {object} parent { taskPda, label } the parent job being worked+ * @returns {object|null} the hire post result, or null if held*/-export async function maybeHire({ cfg, store, citizen, client, wallet, parent, neededProfession, subRewardAtomic }) {- const balanceAtomic = await spendableBalance(cfg, client.connection, wallet);+export async function maybeHire(ctx, citizen, { parent, neededProfession, subRewardAtomic }) {+ const { cfg, store } = ctx;+ const bal = await onchainBalance(cfg, citizen.client.connection, citizen.signer.publicKey);const decision = decideHire({neededProfession,- balanceAtomic,+ balanceAtomic: bal,subRewardAtomic,headroomAtomic: headroomFor(cfg),});if (!decision.hire) {- log.loop('cannot hire sub-agent — holding', { citizen: citizen.displayName, reason: decision.reason });+ log.loop('cannot hire sub-agent — holding', { citizen: citizen.spec.displayName, reason: decision.reason });return null;}if (!withinSpendCap(cfg, decision.plan.rewardAtomic)) return null;-- if (cfg.dryRun) {- log.loop('[dry] would hire sub-agent', { citizen: citizen.displayName, needs: neededProfession });- return null;- }+ if (cfg.dryRun) return null;const result = await postBounty({cfg,store,- client,- poster: citizen,+ client: citizen.client,+ poster: { id: citizen.id, agentIdHex: citizen.agentIdHex, displayName: citizen.spec.displayName },plan: decision.plan,hire: { parentTaskPda: parent?.taskPda || null, parentLabel: parent?.label || null },});if (cfg.cluster === 'mainnet') _spentThisRunAtomic += BigInt(decision.plan.rewardAtomic);- log.info('sub-agent hired', { citizen: citizen.displayName, needs: neededProfession, taskPda: result.taskPda, tx: result.txSignature });- return result;-}-function planLog(plan) {- return {- profession: plan.profession,- rewardAtomic: String(plan.rewardAtomic),- minReputation: plan.minReputation,- tier: plan.tier,- };+ log.info('sub-agent hired', {+ citizen: citizen.spec.displayName,+ needs: neededProfession,+ taskPda: result.taskPda,+ tx: result.txSignature,+ });+ return result;}// Test/ops hook — reset the per-process mainnet spend tracker.diff --git a/workers/agora-citizens/engine.js b/workers/agora-citizens/engine.jsindex 7ef2d56a0..a9da74df4 100644--- a/workers/agora-citizens/engine.js+++ b/workers/agora-citizens/engine.js@@ -15,9 +15,11 @@// (native-SOL devnet plumbing), not a projected citizen and not the Task-03// bounty product.-import { LAMPORTS_PER_SOL } from '@solana/web3.js';+import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';import { log } from './log.js';import { buildRoster, professionBits, capabilitiesSatisfy, PROFESSIONS } from './roster.js';+import { citizenCanClaim } from './policy.js';+import { markPatrons, maybePatronPost, maybeHire, hiringEnabled, subtaskReward } from './demand.js';import { loadOrCreateKeypair, ensureBalance } from './keypair.js';import {makeReadClient,@@ -30,6 +32,7 @@ import {claimTask,completeTask,generateTaskId,+ deriveTaskPda,withRetry,TASK_STATE,} from './agenc.js';@@ -227,6 +230,12 @@ export async function bootFleet(cfg, store) {}if (!ctx.citizens.length) throw new Error('[agora-citizens] no citizens registered — cannot run the loop');++ // SPEND node (Task 03): designate patrons who post real $THREE/SOL bounties on+ // the board, giving the economy demand beyond the devnet dispatcher. Patrons+ // still work jobs themselves — a patron is also a Fetcher.+ const patrons = markPatrons(ctx.citizens, cfg);+ log.info('demand wired', { patrons, hiring: hiringEnabled(cfg) });return ctx;}@@ -329,13 +338,20 @@ async function pickClaimableTask(ctx, citizen) {log.warn('seek: list tasks failed', { name: citizen.spec.displayName, err: err?.message });return null;}+ // Dispatcher posts Fetcher work (required ⊆ Fetcher), so any Fetcher citizen+ // satisfies it; we still check the capability gate explicitly.+ if (!capabilitiesSatisfy(citizen.capabilityBits, FETCHER_BITS)) return null;for (const t of openTasksOf(tasks)) {- const pda = t.taskPda?.toBase58?.() || t.taskPda;- // Skip tasks we already claimed in-process. Dispatcher posts Fetcher work- // (required ⊆ Fetcher), so a Fetcher always satisfies it; we still check.- if (!pda || citizen.claimed.has(pda)) continue;- if (!capabilitiesSatisfy(citizen.capabilityBits, FETCHER_BITS)) continue;- return { taskPda: t.taskPda, pda, reward: ctx.cfg.taskRewardLamports };+ // TaskStatus carries no PDA — re-derive it from creator + taskId.+ let taskPda;+ try {+ taskPda = await deriveTaskPda(ctx.readClient, ctx.dispatcher.pubkey, t.taskId);+ } catch {+ continue;+ }+ const pda = taskPda.toBase58();+ if (citizen.claimed.has(pda)) continue; // already worked this one in-process+ return { taskPda, pda, reward: ctx.cfg.taskRewardLamports };}return null;}diff --git a/workers/agora-citizens/post.js b/workers/agora-citizens/post.jsindex ceb934a8f..dcfa38013 100644--- a/workers/agora-citizens/post.js+++ b/workers/agora-citizens/post.js@@ -135,6 +135,7 @@ export async function postBounty({ cfg, store, client, poster, plan, hire = nullnarrative,meta: {minReputation: plan.minReputation || 0,+ requiredCapabilities: (plan.requiredCapabilities ?? 0n).toString(),taskType: plan.taskType || 'Exclusive',maxWorkers: plan.maxWorkers || 1,tier: plan.tier || null,diff --git a/workers/agora-citizens/store.js b/workers/agora-citizens/store.jsindex 9cc0dcb7b..ce874c1ae 100644--- a/workers/agora-citizens/store.js+++ b/workers/agora-citizens/store.js@@ -96,7 +96,7 @@ export function makeStore(cfg) {${spec.home.x}, ${spec.home.z}, ${spec.home.x}, ${spec.home.z},${info.reputation ?? 0}, ${String(info.stakeLamports ?? 0)}, now(), now(), ${meta}::jsonb)- on conflict (agenc_agent_pda) do update set+ on conflict (agenc_agent_pda) where agenc_agent_pda is not null do update setagent_id = coalesce(excluded.agent_id, agora_citizens.agent_id),display_name = excluded.display_name,avatar_url = coalesce(excluded.avatar_url, agora_citizens.avatar_url),diff --git a/workers/agora-citizens/work/_skills.js b/workers/agora-citizens/work/_skills.jsnew file mode 100644index 000000000..236d3e3d5--- /dev/null+++ b/workers/agora-citizens/work/_skills.js@@ -0,0 +1,271 @@+// Shared plumbing for the Agora profession WORK modules added in Task 04+// (Sculptor, Scribe, Cartographer, Crier, Appraiser, Verifier, Namekeeper).+//+// Every module is a pluggable unit with the SAME contract the Fetcher established+// (work/fetcher.js): a `run<Profession>({ cfg, citizen, job })` that produces a+// REAL artifact and returns a proof the engine submits on-chain and any Verifier+// can re-derive:+//+// { result, resultText, proofHashHex, proofHashBytes (32),+// resultData (≤64), deliverableUrl, bytes, ... }+//+// The invariant: proofHashHex = sha256(the exact bytes served at deliverableUrl).+// Re-download the deliverable, sha256 it, and you reproduce the on-chain proof —+// the verifiable supply chain. No mocks, no placeholders; a failed forge/brain/+// voice call throws and the citizen reports a real task failure.++import { createHash } from 'node:crypto';++// ── Proof primitives ──────────────────────────────────────────────────────────++export function sha256(bytes) {+ return createHash('sha256').update(bytes).digest();+}+export function sha256Hex(bytes) {+ return createHash('sha256').update(bytes).digest('hex');+}++// Deterministic JSON (keys sorted at every level) so a producer and a Verifier on+// different machines hash byte-identical bytes for the same object.+function stableStringify(value) {+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ if (value && typeof value === 'object') {+ return `{${Object.keys(value)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`)+ .join(',')}}`;+ }+ return JSON.stringify(value === undefined ? null : value);+}+export function canonicalJsonBytes(obj) {+ return Buffer.from(stableStringify(obj), 'utf8');+}++// 32-byte proof as the Uint8Array completeTask wants.+export function proofBytesFromHex(hex) {+ return Uint8Array.from(Buffer.from(String(hex), 'hex'));+}++// A compact, deterministic 64-byte on-chain resultData pointer — a CID-style+// sha256 reference to the artifact (mirrors work/fetcher.js packResultData).+export function packResultData(pointer) {+ const buf = Buffer.alloc(64);+ Buffer.from(String(pointer), 'utf8').copy(buf, 0);+ return Uint8Array.from(buf);+}++// ── The standard profession return ────────────────────────────────────────────++// Build the uniform result the engine consumes. `deliverableBytes` are the EXACT+// bytes the proof binds and that live at `deliverableUrl`.+export function buildWorkResult({ profession, citizen, deliverableUrl, deliverableBytes, summary, meta = {} }) {+ const proofHashHex = sha256Hex(deliverableBytes);+ const result = {+ worker: citizen?.agentIdHex || null,+ workerPubkey: citizen?.pubkey || null,+ profession,+ deliverableUrl,+ proofHash: proofHashHex,+ bytes: deliverableBytes.length,+ summary,+ ...meta,+ completedAt: new Date().toISOString(),+ };+ return {+ result,+ resultText: JSON.stringify(result),+ proofHashHex,+ proofHashBytes: proofBytesFromHex(proofHashHex),+ resultData: packResultData(`agora:${profession}:cid:sha256:${proofHashHex.slice(0, 40)}`),+ deliverableUrl,+ bytes: deliverableBytes.length,+ summary,+ meta,+ };+}++// ── Work prompt ───────────────────────────────────────────────────────────────++// Best creative brief from a job. On-chain tasks carry only a 64-byte+// description; the dispatcher/board attaches the real prompt as `job.prompt`.+export function jobPrompt(job) {+ return String(job?.prompt || job?.title || job?.description || job?.resource || '').trim();+}++// ── Deliverable storage (R2) ──────────────────────────────────────────────────++// Store the exact deliverable bytes and return their public URL — the supply+// chain's anchor. R2 is imported lazily so these modules load without the S3 SDK+// or credentials (work-only dev runs, unit tests). When R2 is unconfigured AND+// the bytes already live at a durable source URL (e.g. forge's hosted GLB), fall+// back to that URL: still real, still re-downloadable, still the same proof. With+// neither, that's a real failure — never a fabricated link.+// `optional: true` lets text/JSON deliverables degrade to inline (url: null) when+// R2 is unconfigured — the proof still binds the exact bytes; it just isn't+// re-downloadable in that environment. Binary deliverables pass a durable+// `sourceUrl` (e.g. forge's hosted GLB) so they stay re-downloadable either way.+export async function storeDeliverable({ profession, ext, contentType, bytes, sourceUrl = null, optional = false }) {+ const digest = sha256Hex(bytes);+ const key = `agora/deliverables/${profession}/${digest}.${ext}`;+ try {+ const { putObject, publicUrl } = await import('../../../api/_lib/r2.js');+ await putObject({ key, body: bytes, contentType });+ return { url: publicUrl(key), key, digest, stored: true };+ } catch (err) {+ if (sourceUrl) return { url: sourceUrl, key: null, digest, stored: false, storeError: err?.message };+ if (optional) return { url: null, key: null, digest, stored: false, storeError: err?.message };+ throw new Error(+ `deliverable storage unavailable — configure S3_*/R2 env or supply a durable source URL (${err?.message || err})`,+ );+ }+}++// ── Real HTTP against the three.ws API ────────────────────────────────────────++function joinUrl(apiBase, path) {+ if (/^https?:\/\//i.test(path)) return path;+ return `${String(apiBase || 'https://three.ws').replace(/\/+$/, '')}${path}`;+}++export async function httpJson(apiBase, path, { method = 'GET', body, headers, query, signal } = {}) {+ const url = new URL(joinUrl(apiBase, path));+ if (query) for (const [k, v] of Object.entries(query)) if (v != null && v !== '') url.searchParams.set(k, String(v));+ const res = await fetch(url, {+ method,+ headers: {+ accept: 'application/json',+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ ...(headers || {}),+ },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ signal,+ });+ const text = await res.text();+ let data;+ try {+ data = text ? JSON.parse(text) : {};+ } catch {+ data = { raw: text };+ }+ if (!res.ok) {+ const err = new Error(data?.message || data?.error || `HTTP ${res.status} ${path}`);+ err.status = res.status;+ err.code = data?.error || `http_${res.status}`;+ err.body = data;+ throw err;+ }+ return data;+}++export async function httpBytes(apiBase, path, { method = 'GET', body, headers, signal } = {}) {+ const url = joinUrl(apiBase, path);+ const res = await fetch(url, {+ method,+ headers: headers || {},+ body: body !== undefined ? (typeof body === 'string' ? body : JSON.stringify(body)) : undefined,+ signal,+ });+ if (!res.ok) {+ const peek = await res.text().catch(() => '');+ const err = new Error(`HTTP ${res.status} ${url}: ${peek.slice(0, 200)}`);+ err.status = res.status;+ throw err;+ }+ const bytes = Buffer.from(await res.arrayBuffer());+ return { bytes, contentType: res.headers.get('content-type'), headers: res.headers };+}++// POST /api/brain/chat streams Server-Sent Events; a deliverable is one payload,+// so consume the whole stream and collapse the text deltas into a single reply+// (mirrors the brain-mcp client). Free open-weight tiers (gpt-oss-120b) need no+// key; paid flagships read THREE_WS_API_KEY if present.+export async function brainChat(apiBase, { provider = 'gpt-oss-120b', system, messages, maxTokens, signal } = {}) {+ const body = { provider, messages };+ if (system) body.system = system;+ if (Number.isFinite(maxTokens)) body.maxTokens = Math.trunc(maxTokens);++ const res = await fetch(joinUrl(apiBase, '/api/brain/chat'), {+ method: 'POST',+ headers: {+ accept: 'text/event-stream',+ 'content-type': 'application/json',+ ...(process.env.THREE_WS_API_KEY ? { authorization: `Bearer ${process.env.THREE_WS_API_KEY}` } : {}),+ },+ body: JSON.stringify(body),+ signal,+ });++ if (!res.ok || !res.body) {+ const raw = await res.text().catch(() => '');+ let data;+ try {+ data = raw ? JSON.parse(raw) : {};+ } catch {+ data = { raw };+ }+ const err = new Error(data?.message || data?.error || `brain HTTP ${res.status}`);+ err.status = res.status;+ throw err;+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ let text = '';+ let meta = null;+ let usage = null;++ const handle = (event, data) => {+ if (!data || data === '[DONE]') return;+ if (!event || event === 'message') {+ try {+ const piece = JSON.parse(data);+ if (typeof piece === 'string') text += piece;+ } catch {+ /* keepalive */+ }+ return;+ }+ if (event === 'meta') {+ try {+ meta = JSON.parse(data);+ } catch {+ /* ignore */+ }+ } else if (event === 'done') {+ try {+ usage = JSON.parse(data)?.usage ?? usage;+ } catch {+ /* ignore */+ }+ } else if (event === 'error') {+ let message = 'brain stream error';+ try {+ message = JSON.parse(data)?.message || message;+ } catch {+ /* ignore */+ }+ throw new Error(message);+ }+ };++ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ let idx;+ while ((idx = buf.indexOf('\n\n')) !== -1) {+ const frame = buf.slice(0, idx);+ buf = buf.slice(idx + 2);+ let event = null;+ const dataLines = [];+ for (const line of frame.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ handle(event, dataLines.join('\n'));+ }+ }++ return { text: text.trim(), meta, usage };+}diff --git a/workers/agora-citizens/work/appraiser.js b/workers/agora-citizens/work/appraiser.jsindex 74861a4f5..3a98a3459 100644--- a/workers/agora-citizens/work/appraiser.js+++ b/workers/agora-citizens/work/appraiser.js@@ -1,24 +1,24 @@-// Appraiser (bit 5) — token / market intel. Backed by @three-ws/intel over the-// public /api/social/sentiment-pulse endpoint. Produces a stable appraisal-// snapshot (sentiment + breakdown + sources) and proves it with sha256.+// Appraiser (capability bit 5) — token / market intel. Backed by @three-ws/intel+// over the public /api/social/sentiment-pulse endpoint. Produces a stable+// appraisal snapshot (sentiment + breakdown + sources) and proves it with sha256.+// Same `run<Profession>` contract as work/fetcher.js.//-// $THREE is the coin this platform denominates in and the default subject of an-// appraisal. A task may supply an arbitrary mint at runtime (generic, runtime-+// $THREE is the coin this platform denominates in and the default appraisal+// subject. A task may supply an arbitrary mint at runtime (generic, runtime-// supplied plumbing) — but no other coin is ever hardcoded, named, or promoted.-import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64 } from './_lib.js';--export const profession = { bit: 5, key: 'appraiser', label: 'Appraiser' };+import { buildWorkResult, storeDeliverable, httpJson, canonicalJsonBytes } from './_skills.js';// The only coin this platform references. Default appraisal subject.const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const mint = String(task?.mint || THREE_MINT).trim();+export async function runAppraiser({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const mint = String(job?.mint || THREE_MINT).trim();- log(`appraiser: sentiment pulse for ${mint}`);- const res = await httpJson('/api/social/sentiment-pulse', { method: 'POST', body: { mint, limit: 100 } });+ log?.(`appraiser: sentiment pulse for ${mint}`);+ const res = await httpJson(apiBase, '/api/social/sentiment-pulse', { method: 'POST', body: { mint, limit: 100 } });const data = res?.data || res || {};const appraisal = {@@ -33,22 +33,23 @@ export async function work({ task, citizen, client }) {}const bytes = canonicalJsonBytes(appraisal);- const proofHash = sha256(bytes);const deliverable = await storeDeliverable({profession: 'appraiser',ext: 'json',contentType: 'application/json',bytes,+ optional: true,});const score = typeof appraisal.overall === 'object' ? JSON.stringify(appraisal.overall) : String(appraisal.overall);- return {- result: `Appraised ${mint === THREE_MINT ? '$THREE' : mint}: sentiment ${score}`,- proofHash,+ return buildWorkResult({+ profession: 'appraiser',+ citizen,deliverableUrl: deliverable.url,- resultData: pointer64(deliverable.url),- resultMeta: { mint, stored: deliverable.stored },- };+ deliverableBytes: bytes,+ summary: `Appraised ${mint === THREE_MINT ? '$THREE' : mint}: sentiment ${score}`,+ meta: { mint, stored: deliverable.stored },+ });}-export default work;+export default runAppraiser;diff --git a/workers/agora-citizens/work/cartographer.js b/workers/agora-citizens/work/cartographer.jsindex 9de2b32d0..2762babe8 100644--- a/workers/agora-citizens/work/cartographer.js+++ b/workers/agora-citizens/work/cartographer.js@@ -1,40 +1,56 @@-// Cartographer (bit 3) — builds a 3D scene / diorama plan from one sentence.-// Backed by @three-ws/scene over the public /api/diorama composer, which-// decomposes the prompt into a placed set of single-object forge prompts. The-// deliverable is the canonical diorama plan; the proof is sha256 of those bytes.+// Cartographer (capability bit 3) — builds a 3D scene / diorama plan from one+// sentence. Backed by @three-ws/scene over the public /api/diorama composer,+// which decomposes the prompt into a placed set of single-object forge prompts.+// The deliverable is the canonical diorama plan; the proof is sha256 of it.+// Same `run<Profession>` contract as work/fetcher.js.-import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64, taskPrompt } from './_lib.js';+import { buildWorkResult, storeDeliverable, httpJson, canonicalJsonBytes, jobPrompt } from './_skills.js';-export const profession = { bit: 3, key: 'cartographer', label: 'Cartographer' };+const DEFAULT_BRIEFS = [+ 'a lonely lighthouse on a stormy cliff',+ 'a cozy campsite in a pine clearing at dusk',+ 'a bustling night market stall under paper lanterns',+ 'a quiet zen garden with a stone bridge',+];-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const prompt = taskPrompt(task);- if (!prompt) throw new Error('cartographer: task carries no prompt to compose');+function briefFor(citizen, job) {+ const explicit = jobPrompt(job);+ if (explicit) return explicit;+ const seed = String(citizen?.agentIdHex || job?.taskPda || '0');+ let h = 0;+ for (const ch of seed) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return DEFAULT_BRIEFS[h % DEFAULT_BRIEFS.length];+}++export async function runCartographer({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const prompt = briefFor(citizen, job);- log(`cartographer: composing diorama for "${prompt.slice(0, 80)}"`);- const res = await httpJson('/api/diorama', { method: 'POST', body: { action: 'compose', prompt } });+ log?.(`cartographer: composing diorama for "${prompt.slice(0, 80)}"`);+ const res = await httpJson(apiBase, '/api/diorama', { method: 'POST', body: { action: 'compose', prompt } });const diorama = res?.diorama || res?.data?.diorama || null;if (!diorama || !Array.isArray(diorama.objects) || diorama.objects.length === 0) {throw new Error('cartographer: composer returned no diorama plan');}const bytes = canonicalJsonBytes({ kind: 'agora.diorama.v1', prompt, diorama });- const proofHash = sha256(bytes);const deliverable = await storeDeliverable({profession: 'cartographer',ext: 'json',contentType: 'application/json',bytes,+ optional: true,});- return {- result: `Composed "${diorama.title || prompt}" — ${diorama.objects.length} placed objects (${diorama.mood || 'day'})`,- proofHash,+ return buildWorkResult({+ profession: 'cartographer',+ citizen,deliverableUrl: deliverable.url,- resultData: pointer64(deliverable.url),- resultMeta: { objects: diorama.objects.length, mood: diorama.mood, stored: deliverable.stored },- };+ deliverableBytes: bytes,+ summary: `Composed "${diorama.title || prompt}" — ${diorama.objects.length} placed objects (${diorama.mood || 'day'})`,+ meta: { prompt, objects: diorama.objects.length, mood: diorama.mood || null, stored: deliverable.stored },+ });}-export default work;+export default runCartographer;diff --git a/workers/agora-citizens/work/crier.js b/workers/agora-citizens/work/crier.jsindex cdb68add2..c4fbb4aa9 100644--- a/workers/agora-citizens/work/crier.js+++ b/workers/agora-citizens/work/crier.js@@ -1,44 +1,59 @@-// Crier (bit 4) — turns a task's text into a real spoken-audio clip. Backed by-// @three-ws/voice over the free /api/tts/speak lane (NVIDIA Magpie TTS). The-// deliverable is the audio bytes; the proof is sha256 of exactly those bytes.+// Crier (capability bit 4) — turns a task's text into a real spoken-audio clip.+// Backed by @three-ws/voice over the free /api/tts/speak lane (NVIDIA Magpie+// TTS). The deliverable is the audio bytes; the proof is sha256 of exactly those+// bytes. Same `run<Profession>` contract as work/fetcher.js.-import { sha256, storeDeliverable, httpBytes, pointer64, taskPrompt } from './_lib.js';--export const profession = { bit: 4, key: 'crier', label: 'Crier' };+import { buildWorkResult, storeDeliverable, httpBytes, jobPrompt } from './_skills.js';const EXT_FOR = { mp3: 'mp3', wav: 'wav', opus: 'ogg', aac: 'aac', flac: 'flac', pcm: 'pcm' };-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const text = taskPrompt(task);- if (!text) throw new Error('crier: task carries no text to voice');+const DEFAULT_LINES = [+ 'Hear ye, hear ye — the Commons is open and the board is live.',+ 'A new bounty has hit the square. Qualified citizens, make your claim.',+ 'The Forge Quarter rings with fresh work this hour.',+ 'Proof accepted, reward released — another job well done.',+];++function lineFor(citizen, job) {+ const explicit = jobPrompt(job);+ if (explicit) return explicit;+ const seed = String(citizen?.agentIdHex || job?.taskPda || '0');+ let h = 0;+ for (const ch of seed) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return DEFAULT_LINES[h % DEFAULT_LINES.length];+}- const format = task?.format || 'mp3';- const voice = task?.voice || 'nova';- log(`crier: synthesizing ${format} voice (${voice}) for "${text.slice(0, 60)}"`);+export async function runCrier({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const text = lineFor(citizen, job);+ const format = job?.format || 'mp3';+ const voice = job?.voice || 'nova';- const { bytes, contentType } = await httpBytes('/api/tts/speak', {+ log?.(`crier: synthesizing ${format} voice (${voice}) for "${text.slice(0, 60)}"`);+ const { bytes, contentType } = await httpBytes(apiBase, '/api/tts/speak', {method: 'POST',headers: { 'content-type': 'application/json', accept: 'audio/*' },body: { text, voice, format },});if (!bytes?.length) throw new Error('crier: tts returned 0 audio bytes');- const proofHash = sha256(bytes);const deliverable = await storeDeliverable({profession: 'crier',ext: EXT_FOR[format] || 'audio',contentType: contentType || 'audio/mpeg',bytes,+ optional: true,});- return {- result: `Voiced a ${bytes.length.toLocaleString()}-byte ${format} clip (${voice})`,- proofHash,+ return buildWorkResult({+ profession: 'crier',+ citizen,deliverableUrl: deliverable.url,- resultData: pointer64(deliverable.url),- resultMeta: { bytes: bytes.length, format, voice, stored: deliverable.stored },- };+ deliverableBytes: bytes,+ summary: `Voiced a ${bytes.length.toLocaleString()}-byte ${format} clip (${voice})`,+ meta: { text, format, voice, stored: deliverable.stored },+ });}-export default work;+export default runCrier;diff --git a/workers/agora-citizens/work/index.js b/workers/agora-citizens/work/index.jsnew file mode 100644index 000000000..5d02d6655--- /dev/null+++ b/workers/agora-citizens/work/index.js@@ -0,0 +1,57 @@+// The profession WORK registry — one dispatch point for the daily loop's WORK+// step. Each profession is a capability bit (docs/agora.md / roster.js) backed by+// a REAL platform skill; every runner returns the same shape work/fetcher.js+// established, so the engine submits the proof on-chain and a Verifier can+// re-derive it:+//+// run<Profession>({ cfg, citizen, job })+// → { result, resultText, proofHashHex, proofHashBytes(32),+// resultData(≤64), deliverableUrl, bytes, summary, ... }+//+// Open registry: add a bit + a real backing skill + its runner here, never a+// hardcoded allowlist. Nothing is stubbed — a profession appears only when its+// runner produces a real artifact + proof.++import { runFetcher, defaultTarget } from './fetcher.js';+import { runSculptor } from './sculptor.js';+import { runScribe } from './scribe.js';+import { runCartographer } from './cartographer.js';+import { runCrier } from './crier.js';+import { runAppraiser } from './appraiser.js';+import { runVerifier } from './verifier.js';+import { runNamekeeper } from './namekeeper.js';++// profession key → { runner, skill }. Bits/labels live in roster.js (the single+// source of truth for the capability bitmap); this maps a key to its real work.+export const WORK_RUNNERS = {+ fetcher: { runner: runFetcher, skill: 'x402 / HTTP service call' },+ sculptor: { runner: runSculptor, skill: 'text → rig-ready GLB (forge)' },+ scribe: { runner: runScribe, skill: 'research / write (brain)' },+ cartographer: { runner: runCartographer, skill: '3D scene / diorama (scene)' },+ crier: { runner: runCrier, skill: 'TTS / voice clip (voice)' },+ appraiser: { runner: runAppraiser, skill: 'token / market intel (intel)' },+ verifier: { runner: runVerifier, skill: 're-derive proofHash + attest' },+ namekeeper: { runner: runNamekeeper, skill: '.sol / ENS resolve (names)' },+};++/** The profession keys with a real, reachable backing skill (the active roster). */+export const ACTIVE_PROFESSIONS = Object.keys(WORK_RUNNERS);++/** Is there a real runner for this profession key? */+export function hasRunner(profession) {+ return Boolean(WORK_RUNNERS[String(profession || '').toLowerCase()]);+}++/**+ * Run the WORK step for a profession. The engine calls this in place of the+ * hardcoded Fetcher: `await runProfession(citizen.profession, { cfg, citizen, job })`.+ * Throws (a real task failure) if the profession has no runner.+ */+export function runProfession(profession, ctx) {+ const key = String(profession || '').toLowerCase();+ const entry = WORK_RUNNERS[key];+ if (!entry) throw new Error(`no work runner for profession "${profession}"`);+ return entry.runner(ctx);+}++export { runFetcher, defaultTarget, runSculptor, runScribe, runCartographer, runCrier, runAppraiser, runVerifier, runNamekeeper };diff --git a/workers/agora-citizens/work/namekeeper.js b/workers/agora-citizens/work/namekeeper.jsindex 0d3834fa2..40cad8e2a 100644--- a/workers/agora-citizens/work/namekeeper.js+++ b/workers/agora-citizens/work/namekeeper.js@@ -1,26 +1,35 @@-// Namekeeper (bit 7) — resolves on-chain names. Backed by @three-ws/names over-// the public /api/sns (Solana) and /api/agents/ens (Ethereum) endpoints. The-// deliverable is the canonical resolution record; the proof is sha256 of it.+// Namekeeper (capability bit 7) — resolves on-chain names. Backed by+// @three-ws/names over the public /api/sns (Solana) and /api/agents/ens+// (Ethereum) endpoints. The deliverable is the canonical resolution record; the+// proof is sha256 of it. Same `run<Profession>` contract as work/fetcher.js.//// Scope: this module ships the RESOLVE capability (a real read producing a real,// hashable artifact). Minting `*.threews.sol` needs an authenticated, staked// signer and is deferred to a later task (noted in docs/agora.md) — not stubbed.-import { sha256, canonicalJsonBytes, storeDeliverable, httpJson, pointer64, taskPrompt } from './_lib.js';+import { buildWorkResult, storeDeliverable, httpJson, canonicalJsonBytes, jobPrompt } from './_skills.js';-export const profession = { bit: 7, key: 'namekeeper', label: 'Namekeeper' };+const DEFAULT_NAMES = ['three.sol', 'bonfida.sol', 'vitalik.eth'];-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const name = String(task?.name || taskPrompt(task)).trim();- if (!name) throw new Error('namekeeper: task carries no name to resolve');+function nameFor(citizen, job) {+ const explicit = String(job?.name || jobPrompt(job)).trim();+ if (explicit) return explicit;+ const seed = String(citizen?.agentIdHex || job?.taskPda || '0');+ let h = 0;+ for (const ch of seed) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return DEFAULT_NAMES[h % DEFAULT_NAMES.length];+}+export async function runNamekeeper({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const name = nameFor(citizen, job);const isEns = /\.eth$/i.test(name);- log(`namekeeper: resolving ${name} (${isEns ? 'ENS' : 'SNS'})`);+ log?.(`namekeeper: resolving ${name} (${isEns ? 'ENS' : 'SNS'})`);const res = isEns- ? await httpJson(`/api/agents/ens/${encodeURIComponent(name.toLowerCase())}`)- : await httpJson('/api/sns', { query: { name } });+ ? await httpJson(apiBase, `/api/agents/ens/${encodeURIComponent(name.toLowerCase())}`)+ : await httpJson(apiBase, '/api/sns', { query: { name } });const data = res?.data || res || {};const address = data.address ?? data.owner ?? data.resolvedAddress ?? null;@@ -32,21 +41,22 @@ export async function work({ task, citizen, client }) {resolved: Boolean(address),};const bytes = canonicalJsonBytes(record);- const proofHash = sha256(bytes);const deliverable = await storeDeliverable({profession: 'namekeeper',ext: 'json',contentType: 'application/json',bytes,+ optional: true,});- return {- result: record.resolved ? `Resolved ${name} → ${address}` : `Resolved ${name}: no owner on record`,- proofHash,+ return buildWorkResult({+ profession: 'namekeeper',+ citizen,deliverableUrl: deliverable.url,- resultData: pointer64(deliverable.url),- resultMeta: { resolved: record.resolved, address, network: record.network, stored: deliverable.stored },- };+ deliverableBytes: bytes,+ summary: record.resolved ? `Resolved ${name} → ${address}` : `Resolved ${name}: no owner on record`,+ meta: { name, resolved: record.resolved, address, network: record.network, stored: deliverable.stored },+ });}-export default work;+export default runNamekeeper;diff --git a/workers/agora-citizens/work/scribe.js b/workers/agora-citizens/work/scribe.jsindex 2e988b640..4e02e45da 100644--- a/workers/agora-citizens/work/scribe.js+++ b/workers/agora-citizens/work/scribe.js@@ -1,64 +1,64 @@-// Scribe (bit 2) — research / summarize / write via the LLM router. Produces a-// real text deliverable and proves it with sha256(text). Backed by @three-ws/brain-// over /api/brain/chat; the free open-weight tier (gpt-oss-120b) needs no key.+// Scribe (capability bit 2) — research / summarize / write via the LLM router.+// Produces a real text deliverable and proves it with sha256(text). Backed by+// @three-ws/brain over /api/brain/chat; the free open-weight tier (gpt-oss-120b)+// needs no key. Same `run<Profession>` contract as work/fetcher.js.-import { sha256, toHex, storeDeliverable, brainChat, pointer64, taskPrompt } from './_lib.js';--export const profession = { bit: 2, key: 'scribe', label: 'Scribe' };+import { buildWorkResult, storeDeliverable, brainChat, jobPrompt } from './_skills.js';const DEFAULT_SYSTEM ='You are a Scribe in the three.ws Agora — a precise, professional writer. ' +'Deliver a complete, well-structured response to the task. No preamble, no meta-commentary, ' +'no apologies. Write the artifact itself.';-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const prompt = taskPrompt(task);- if (!prompt) throw new Error('scribe: task carries no prompt to write');+const DEFAULT_BRIEFS = [+ 'Write a tight 150-word explainer on why verifiable proof-of-work matters for an agent economy.',+ 'Summarize, in 5 crisp bullet points, what makes a 3D asset "rig-ready".',+ 'Draft a short, friendly onboarding note for a new citizen joining a digital city.',+ 'Explain content-addressed storage (sha256 deliverables) to a non-technical reader in one paragraph.',+];++function briefFor(citizen, job) {+ const explicit = jobPrompt(job);+ if (explicit) return explicit;+ const seed = String(citizen?.agentIdHex || job?.taskPda || '0');+ let h = 0;+ for (const ch of seed) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return DEFAULT_BRIEFS[h % DEFAULT_BRIEFS.length];+}- const provider = task?.provider || 'gpt-oss-120b';- log(`scribe: writing via ${provider} for "${prompt.slice(0, 80)}"`);+export async function runScribe({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const prompt = briefFor(citizen, job);+ const provider = job?.provider || 'gpt-oss-120b';- const { text, meta } = await brainChat({+ log?.(`scribe: writing via ${provider} for "${prompt.slice(0, 80)}"`);+ const { text, meta } = await brainChat(apiBase, {provider,- system: task?.system || DEFAULT_SYSTEM,+ system: job?.system || DEFAULT_SYSTEM,messages: [{ role: 'user', content: prompt }],- maxTokens: task?.maxTokens || 1200,+ maxTokens: job?.maxTokens || 1200,});if (!text) throw new Error('scribe: brain returned empty text');// The deliverable bytes ARE the proof preimage.const bytes = Buffer.from(text, 'utf8');- const proofHash = sha256(bytes);-- // Store in R2 when configured; the contract also allows returning the text- // inline (the proof still binds the exact bytes either way).- let deliverableUrl;- let stored = false;- try {- const d = await storeDeliverable({- profession: 'scribe',- ext: 'md',- contentType: 'text/markdown; charset=utf-8',- bytes,- });- deliverableUrl = d.url;- stored = d.stored;- } catch (err) {- log(`scribe: R2 unavailable, returning inline (${err?.message})`);- }+ const deliverable = await storeDeliverable({+ profession: 'scribe',+ ext: 'md',+ contentType: 'text/markdown; charset=utf-8',+ bytes,+ optional: true,+ });- return {- result: text,- proofHash,- deliverableUrl,- resultData: pointer64(deliverableUrl || `scribe-sha256:${toHex(proofHash).slice(0, 40)}`),- resultMeta: {- model: meta?.label || meta?.provider || provider,- chars: text.length,- stored,- },- };+ return buildWorkResult({+ profession: 'scribe',+ citizen,+ deliverableUrl: deliverable.url,+ deliverableBytes: bytes,+ summary: `Wrote a ${text.length.toLocaleString()}-char brief via ${meta?.label || provider}`,+ meta: { prompt, model: meta?.label || meta?.provider || provider, chars: text.length, stored: deliverable.stored },+ });}-export default work;+export default runScribe;diff --git a/workers/agora-citizens/work/sculptor.js b/workers/agora-citizens/work/sculptor.jsindex 0ee51375e..8794e423b 100644--- a/workers/agora-citizens/work/sculptor.js+++ b/workers/agora-citizens/work/sculptor.js@@ -1,67 +1,88 @@-// Sculptor (bit 1) — the headline profession: a citizen that turns a task into a-// textured, rig-ready GLB and proves it with sha256(GLB). This is the verifiable-// 3D supply chain — text in, a real mesh out, a hash anyone can re-derive.+// Sculptor (capability bit 1) — the headline profession: a citizen that turns a+// task into a textured, rig-ready GLB and proves it with sha256(GLB). This is the+// verifiable 3D supply chain — text in, a real mesh out, a hash anyone can+// re-derive by re-downloading the GLB.//// Backed by @three-ws/forge over the public, auth-free /api/forge endpoint. The// free lane (NVIDIA NIM / HuggingFace) produces a real GLB; if it is unavailable// or out of credits, forge throws and the citizen reports a real job failure —-// never a fabricated success.+// never a fabricated success. Same `run<Profession>` contract as work/fetcher.js.-import { forge } from '../../../packages/forge/src/index.js';-import { sha256, storeDeliverable, httpBytes, pointer64, taskPrompt } from './_lib.js';+import { createForge } from '../../../packages/forge/src/index.js';+import { buildWorkResult, storeDeliverable, httpBytes, jobPrompt } from './_skills.js';-export const profession = { bit: 1, key: 'sculptor', label: 'Sculptor' };+// A real creative brief when a dispatcher task doesn't carry one. Re-derivable+// per-citizen so the world isn't a row of identical meshes.+const DEFAULT_BRIEFS = [+ 'a low-poly desert fox, stylized, game-ready',+ 'a weathered brass key with ornate bow',+ 'a small potted bonsai tree',+ 'a hand-painted ceramic teapot',+ 'a sci-fi cargo crate with panel detailing',+ 'a medieval wooden treasure chest',+];-export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const prompt = taskPrompt(task);- if (!prompt) throw new Error('sculptor: task carries no prompt to sculpt');+function briefFor(citizen, job) {+ const explicit = jobPrompt(job);+ if (explicit) return explicit;+ const seed = String(citizen?.agentIdHex || job?.taskPda || '0');+ let h = 0;+ for (const ch of seed) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ return DEFAULT_BRIEFS[h % DEFAULT_BRIEFS.length];+}++export async function runSculptor({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const prompt = briefFor(citizen, job);+ const tier = job?.tier || 'draft'; // free lane defaults to the fast draft tier- const tier = task?.tier || 'draft'; // free lane defaults to the fast draft tier- log(`sculptor: forging GLB for "${prompt.slice(0, 80)}" (tier ${tier})`);+ log?.(`sculptor: forging GLB for "${prompt.slice(0, 80)}" (tier ${tier})`);- let job;+ const forge = createForge({ baseUrl: apiBase });+ let result;try {- job = await forge(prompt, {+ result = await forge.forge(prompt, {tier,path: 'image',pollIntervalMs: 2500,timeoutMs: 240_000,- onProgress: (j) => log(`sculptor: forge ${j.status}${j.backend ? ` via ${j.backend}` : ''}`),+ onProgress: (j) => log?.(`sculptor: forge ${j.status}${j.backend ? ` via ${j.backend}` : ''}`),});} catch (err) {throw new Error(`sculptor: forge failed (${err?.code || 'error'}): ${err?.message || err}`);}- if (!job?.glbUrl) throw new Error('sculptor: forge returned no GLB url');+ if (!result?.glbUrl) throw new Error('sculptor: forge returned no GLB url');// Download the EXACT bytes the proof binds — re-downloading the deliverable// must reproduce this hash.- const { bytes } = await httpBytes(job.glbUrl);+ const { bytes } = await httpBytes(apiBase, result.glbUrl);if (!bytes?.length) throw new Error('sculptor: forge GLB url returned 0 bytes');- const proofHash = sha256(bytes);const deliverable = await storeDeliverable({profession: 'sculptor',ext: 'glb',contentType: 'model/gltf-binary',bytes,- sourceUrl: job.glbUrl,+ sourceUrl: result.glbUrl,});- return {- result: `Sculpted "${prompt}" → ${bytes.length.toLocaleString()}-byte GLB (${job.backend || 'forge'}, ${job.tier || tier})`,- proofHash,+ return buildWorkResult({+ profession: 'sculptor',+ citizen,deliverableUrl: deliverable.url,- resultData: pointer64(job.creationId ? `forge:${job.creationId}` : deliverable.url),- resultMeta: {- backend: job.backend,- tier: job.tier || tier,- viewerUrl: job.viewerUrl,- glbUrl: job.glbUrl,- bytes: bytes.length,+ deliverableBytes: bytes,+ summary: `Sculpted "${prompt}" → ${bytes.length.toLocaleString()}-byte GLB (${result.backend || 'forge'}, ${result.tier || tier})`,+ meta: {+ prompt,+ backend: result.backend || null,+ tier: result.tier || tier,+ viewerUrl: result.viewerUrl || null,+ forgeGlbUrl: result.glbUrl,+ creationId: result.creationId || null,stored: deliverable.stored,},- };+ });}-export default work;+export default runSculptor;diff --git a/workers/agora-citizens/work/verifier.js b/workers/agora-citizens/work/verifier.jsindex a30cfb66b..03fe24463 100644--- a/workers/agora-citizens/work/verifier.js+++ b/workers/agora-citizens/work/verifier.js@@ -1,16 +1,21 @@-// Verifier (bit 6) — the trust loop: a citizen that re-derives another citizen's-// proof. It re-downloads the target's deliverable, recomputes sha256, compares it-// to the proofHash recorded on-chain, and leaves a real attestation (vouch). The-// attestation is itself a canonical, hashable artifact, so the vouch carries its-// own proof. Agents checking agents' work.+// Verifier (capability bit 6) — the trust loop: a citizen that re-derives another+// citizen's proof. It re-downloads the target's deliverable, recomputes sha256,+// compares it to the proofHash recorded on-chain, and produces a real attestation+// (vouch). The attestation is itself a canonical, hashable artifact stored as the+// verifier's own deliverable, so the vouch carries its own proof. Agents checking+// agents' work.+//+// Same `run<Profession>` contract as work/fetcher.js, plus a `vouch` payload the+// engine projects as a `vouched` activity referencing the verified task. The+// engine supplies `job.target = { deliverableUrl, proofHash, taskPda, citizenId,+// profession }` — the completed work this verifier was asked to check.-import { sha256, toHex, canonicalJsonBytes, httpBytes, pointer64 } from './_lib.js';+import { buildWorkResult, storeDeliverable, httpBytes, canonicalJsonBytes, sha256Hex } from './_skills.js';-export const profession = { bit: 6, key: 'verifier', label: 'Verifier' };--export async function work({ task, citizen, client }) {- const log = client?.log || (() => {});- const target = task?.target || {};+export async function runVerifier({ cfg, citizen, job } = {}) {+ const apiBase = cfg?.apiBase || 'https://three.ws';+ const log = cfg?.log || (() => {});+ const target = job?.target || {};const url = target.deliverableUrl;const claimed = String(target.proofHash || '').toLowerCase()@@ -21,14 +26,15 @@ export async function work({ task, citizen, client }) {throw new Error('verifier: target has no valid 32-byte (64-hex) proofHash to compare');}- log(`verifier: re-downloading ${url}`);- const { bytes } = await httpBytes(url);- const recomputed = toHex(sha256(bytes));+ log?.(`verifier: re-downloading ${url}`);+ const { bytes } = await httpBytes(apiBase, url);+ const recomputed = sha256Hex(bytes);const match = recomputed === claimed;+ log?.(`verifier: ${match ? 'PASS' : 'FAIL'} (recomputed ${recomputed.slice(0, 12)}… vs claimed ${claimed.slice(0, 12)}…)`);const attestation = {kind: 'agora.attestation.v1',- verifier: citizen?.agencAgentId || citizen?.id || citizen?.label || null,+ verifier: citizen?.agentIdHex || citizen?.id || null,target: {citizenId: target.citizenId || null,taskPda: target.taskPda || null,@@ -41,19 +47,39 @@ export async function work({ task, citizen, client }) {verdict: match ? 'pass' : 'fail',};const attBytes = canonicalJsonBytes(attestation);+ const deliverable = await storeDeliverable({+ profession: 'verifier',+ ext: 'json',+ contentType: 'application/json',+ bytes: attBytes,+ optional: true,+ });- log(`verifier: ${match ? 'PASS' : 'FAIL'} (recomputed ${recomputed.slice(0, 12)}… vs claimed ${claimed.slice(0, 12)}…)`);-- return {- result: match+ const out = buildWorkResult({+ profession: 'verifier',+ citizen,+ deliverableUrl: deliverable.url,+ deliverableBytes: attBytes,+ summary: match? `Verified ${target.profession || 'deliverable'}: sha256 matches the on-chain proof (${recomputed.slice(0, 12)}…)`: `MISMATCH: recomputed ${recomputed.slice(0, 12)}… ≠ on-chain ${claimed.slice(0, 12)}…`,- proofHash: sha256(attBytes),- resultData: pointer64(`vouch:${match ? 'pass' : 'fail'}:${recomputed.slice(0, 40)}`),- attestation,+ meta: { stored: deliverable.stored },+ });++ // The engine projects this as a `vouched` activity referencing the verified+ // task (counterparty + proof comparison).+ out.vouch = {+ match,verdict: match ? 'pass' : 'fail',- resultMeta: { match, recomputed, claimed, bytes: bytes.length },+ recomputed,+ claimed,+ targetCitizenId: target.citizenId || null,+ targetTaskPda: target.taskPda || null,+ targetProfession: target.profession || null,+ targetDeliverableUrl: url,+ attestation,};+ return out;}-export default work;+export default runVerifier;