Skip to content

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

feat: add new CSS styles for passport elements in trust surface

ni3a31f910ff80cc
diff --git a/pages/agora.html b/pages/agora.html
index ec64ee4f4..5a9f64686 100644
--- a/pages/agora.html
+++ b/pages/agora.html
@@ -70,6 +70,10 @@
<nav id="agora-roster" aria-label="Citizens" class="agora-roster"></nav>
<script type="module" src="/src/agora/agora-world.js"></script>
+ <!-- Task 07 trust surface: job lifecycle + in-browser deliverable verifier.
+ Self-mounts via window events + ?task= deep-links; decoupled from the
+ scaffold so it never has to reach into agora-world.js / economy-layer.js. -->
+ <script type="module" src="/src/agora/trust-surface.js"></script>
<script src="/brand.js" defer></script>
</body>
</html>
diff --git a/src/agora/economy-layer.js b/src/agora/economy-layer.js
index 61ae6a71c..657af0a40 100644
--- a/src/agora/economy-layer.js
+++ b/src/agora/economy-layer.js
@@ -60,8 +60,11 @@ export function mountEconomyLayer(ctx) {
const jobBoard = new JobBoard({
scene, root, worldToScreen, reducedMotion, boardPosition,
onSelectTask: (task) => {
- // Selecting a task glides the camera to the board so the marker is framed.
+ // Selecting a task glides the camera to the board so the marker is framed…
focusOn(boardPosition.clone().setY(3.5));
+ // …and opens its lifecycle + deliverable verifier (Task 07's trust
+ // surface, mounted independently and listening for this event).
+ window.dispatchEvent(new CustomEvent('agora:open-job', { detail: { task } }));
},
});
diff --git a/src/agora/passport-panel.js b/src/agora/passport-panel.js
index 647a36d49..15a40fdc3 100644
--- a/src/agora/passport-panel.js
+++ b/src/agora/passport-panel.js
@@ -1,15 +1,21 @@
-// Agora passport panel — the click-to-inspect side panel for a single citizen.
+// Agora passport panel — the living passport (Task 07). Clicking (or keyboard-
+// activating) a citizen opens this side panel, which fetches /api/agora/passport
+// and shows the full record: identity + a derived A–D trust grade, slashable
+// stake, status, $THREE earned, tasks done/posted, the live on-chain registry
+// block (the chain's truth, reconciled against the projection), the cross-chain
+// identity handshake when a citizen proves both an EVM and a Solana identity, and
+// a complete activity timeline where every row links its tx + deliverable and a
+// completed task can be verified in-browser.
//
-// Clicking (or keyboard-activating) a citizen opens this panel, which fetches
-// /api/agora/passport?id=… and shows the real basics: name, profession, status,
-// reputation, stake, tasks completed, and recent activity. The rich living
-// passport (identity handshake, verify-the-deliverable) is Task 07 — this is a
-// clean, real first version with designed loading / error / empty states.
-//
-// Non-modal: the world stays interactive behind it. Esc closes; focus moves into
-// the panel on open and returns to the trigger on close.
+// On-chain is the source of truth: where the live `onchain` read disagrees with
+// the projection snapshot, the chain wins and the panel says so. Non-modal: the
+// world stays interactive behind it. Esc closes; focus moves into the panel on
+// open and returns to the trigger on close.
import { professionColor } from './citizen-avatar.js';
+import { fetchPassport } from './api.js';
+import { renderHandshake, parseIdentityProofs, hasDualIdentity } from './handshake.js';
+import { injectTrustSurfaceCss } from './trust-surface.css.js';
import { log } from '../shared/log.js';
const THREE_DECIMALS = 6;
@@ -40,6 +46,22 @@ const fmtTimeAgo = (iso) => {
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => (
{ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
));
+const shortAddr = (a) => { const s = String(a ?? ''); return s.length > 12 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s; };
+
+function explorerTx(sig, cluster) { return sig ? `https://explorer.solana.com/tx/${sig}${cluster === 'mainnet' ? '' : '?cluster=devnet'}` : null; }
+function explorerAddr(a, cluster) { return a ? `https://explorer.solana.com/address/${a}${cluster === 'mainnet' ? '' : '?cluster=devnet'}` : null; }
+
+// Derive an A–D trust grade from an AgenC reputation score — a career-ladder
+// readout (reputation ticks up as a citizen completes accepted work), not vanity.
+export function reputationGrade(rep) {
+ const n = Number(rep) || 0;
+ if (n >= 100) return { grade: 'A+', tier: 'a', label: 'Trusted' };
+ if (n >= 50) return { grade: 'A', tier: 'a', label: 'Established' };
+ if (n >= 25) return { grade: 'B', tier: 'b', label: 'Proven' };
+ if (n >= 10) return { grade: 'C', tier: 'c', label: 'Rising' };
+ if (n >= 1) return { grade: 'D', tier: 'd', label: 'Newcomer' };
+ return { grade: '—', tier: 'new', label: 'Unproven' };
+}
const ACTIVITY_LABEL = {
posted_task: 'Posted a task',
@@ -53,6 +75,7 @@ const ACTIVITY_LABEL = {
export class PassportPanel {
constructor() {
+ injectTrustSurfaceCss();
this._el = this._build();
document.body.appendChild(this._el);
this._bodyEl = this._el.querySelector('#agora-passport-body');
@@ -61,10 +84,27 @@ export class PassportPanel {
this._reqId = 0; // guards against out-of-order responses
this._currentId = null;
this._onClose = null;
+ this._cluster = 'devnet';
this._el.querySelector('.agora-passport-close').addEventListener('click', () => this.close());
- this._onKey = (e) => { if (e.key === 'Escape' && this.isOpen()) { e.stopPropagation(); this.close(); } };
- document.addEventListener('keydown', this._onKey);
+ this._onKey = (e) => {
+ if (!this.isOpen()) return;
+ if (e.key === 'Escape') { e.stopPropagation(); this.close(); return; }
+ if (e.key === 'Tab') this._trapTab(e);
+ };
+ this._el.addEventListener('keydown', this._onKey);
+
+ // Decoupled open: job-detail actor links + ?citizen= deep-links broadcast
+ // this rather than reaching into the world's panel instance.
+ this._onOpenEvent = (e) => {
+ const d = e.detail || {};
+ if (d.agentPda) this.openRef({ agentPda: d.agentPda });
+ else if (d.agentId) this.openRef({ agentId: d.agentId });
+ else if (d.id) this.open(d.id, { hint: d.hint || null });
+ };
+ window.addEventListener('agora:open-passport', this._onOpenEvent);
+
+ this._maybeDeepLink();
}
_build() {
@@ -74,6 +114,7 @@ export class PassportPanel {
aside.setAttribute('role', 'dialog');
aside.setAttribute('aria-label', 'Citizen passport');
aside.setAttribute('aria-modal', 'false');
+ aside.tabIndex = -1;
aside.hidden = true;
aside.innerHTML = `
<header class="agora-passport-head">
@@ -87,44 +128,40 @@ export class PassportPanel {
}
isOpen() { return !this._el.hidden; }
+ get currentId() { return this._currentId; }
/**
- * Open the panel for a citizen and fetch its passport.
+ * Open the panel for a citizen id and fetch its passport.
* @param {string} id citizen id
* @param {{ trigger?: HTMLElement, onClose?: Function, hint?: object }} [opts]
- * hint: a citizen object from the list, rendered immediately so the header
- * isn't blank while the passport request is in flight.
*/
- async open(id, { trigger = null, onClose = null, hint = null } = {}) {
- this._trigger = trigger;
+ open(id, opts = {}) {
+ return this.openRef({ id }, opts);
+ }
+
+ // Open by any passport reference the API accepts (id | agentPda | agentId).
+ async openRef(ref, { trigger = null, onClose = null, hint = null } = {}) {
+ this._trigger = trigger || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
this._onClose = onClose;
- this._currentId = id;
+ this._currentId = ref.id || null;
const reqId = ++this._reqId;
this._el.hidden = false;
this._el.classList.add('open');
this._titleEl.textContent = hint?.displayName || 'Passport';
this._renderLoading(hint);
- // Move focus into the panel for keyboard + screen-reader users.
this._bodyEl.focus({ preventScroll: true });
+ if (ref.id) this._setDeepLink(ref.id);
try {
- const res = await fetch(`/api/agora/passport?id=${encodeURIComponent(id)}`, {
- headers: { accept: 'application/json' },
- });
+ const data = await fetchPassport(ref);
if (reqId !== this._reqId) return; // superseded by a newer open()
- if (!res.ok) {
- const detail = res.status === 404 ? 'This citizen is no longer in the registry.' : `Request failed (${res.status}).`;
- this._renderError(id, detail);
- return;
- }
- const data = await res.json();
- if (reqId !== this._reqId) return;
this._render(data);
} catch (err) {
if (reqId !== this._reqId) return;
log.warn('[agora] passport fetch failed', err?.message);
- this._renderError(id, 'Network error — the registry could not be reached.');
+ const notFound = /404|not.?found/i.test(err?.message || '');
+ this._renderError(ref, notFound ? 'This citizen is no longer in the registry.' : (err?.message || 'The registry could not be reached.'));
}
}
@@ -133,16 +170,19 @@ export class PassportPanel {
this._el.classList.remove('open');
this._el.hidden = true;
this._currentId = null;
+ this._clearDeepLink();
const t = this._trigger;
const cb = this._onClose;
this._trigger = null;
this._onClose = null;
try { cb?.(); } catch (e) { log.warn('[agora] passport onClose threw', e); }
- // Restore focus to whatever opened the panel (an accessible list button).
if (t && typeof t.focus === 'function') t.focus({ preventScroll: true });
}
- get currentId() { return this._currentId; }
+ dispose() {
+ window.removeEventListener('agora:open-passport', this._onOpenEvent);
+ this._el.remove();
+ }
// ── Renderers ──────────────────────────────────────────────────────────────
@@ -165,7 +205,7 @@ export class PassportPanel {
<span class="agora-pp-srhint" role="status">Loading passport…</span>`;
}
- _renderError(id, detail) {
+ _renderError(ref, detail) {
this._bodyEl.innerHTML = `
<div class="agora-pp-state">
<div class="agora-pp-state-icon" aria-hidden="true">!</div>
@@ -173,41 +213,53 @@ export class PassportPanel {
<p class="agora-pp-state-detail">${esc(detail)}</p>
<button class="agora-pp-retry" type="button">Try again</button>
</div>`;
- this._bodyEl.querySelector('.agora-pp-retry').addEventListener('click', () => this.open(id, { trigger: this._trigger }));
+ this._bodyEl.querySelector('.agora-pp-retry').addEventListener('click', () => this.openRef(ref, { trigger: this._trigger }));
}
_render(data) {
const c = data.citizen || {};
const onchain = data.onchain || null;
const accent = professionColor(c.profession || c.professions?.[0]?.key);
+ this._cluster = c.agenc?.cluster === 'mainnet' ? 'mainnet' : 'devnet';
this._titleEl.textContent = c.displayName || 'Passport';
+ // On-chain wins for rep/stake/status when present (it's the truth).
const status = onchain?.status || c.status || 'Idle';
const reputation = onchain?.reputation ?? c.reputation ?? 0;
const stake = onchain?.stakeAmount ?? c.stakeLamports;
+ const grade = reputationGrade(reputation);
const professions = (c.professions && c.professions.length)
? c.professions.map((p) => p.label)
: [c.profession || 'Citizen'];
const stats = [
- { label: 'Reputation', value: Number(reputation).toLocaleString('en-US') },
- { label: 'Tasks done', value: Number(c.tasksCompleted || 0).toLocaleString('en-US') },
- { label: 'Earned', value: `${fmtThree(c.earnedThreeAtomic)} $THREE` },
- { label: 'Stake', value: `${fmtSol(stake)} SOL` },
+ { label: 'Reputation', value: Number(reputation).toLocaleString('en-US'), sub: grade.label },
+ { label: 'Stake', value: `${fmtSol(stake)}`, sub: 'SOL slashable' },
+ { label: 'Earned', value: `${fmtThree(c.earnedThreeAtomic)}`, sub: '$THREE' },
+ { label: 'Done', value: Number(c.tasksCompleted || 0).toLocaleString('en-US'), sub: 'tasks' },
+ { label: 'Posted', value: Number(c.tasksPosted || 0).toLocaleString('en-US'), sub: 'bounties' },
];
- const identity = [];
- if (c.agenc?.registered && c.agenc?.cluster) identity.push(`AgenC · ${esc(c.agenc.cluster)}`);
- if (c.agenc?.identitySource) identity.push(esc(c.agenc.identitySource));
+ const proofs = parseIdentityProofs(onchain?.metadataUri);
+ const showHandshake = hasDualIdentity(proofs);
this._bodyEl.innerHTML = `
<div class="agora-pp-hero">
<span class="agora-pp-dot" style="background:${accent}"></span>
- <div>
+ <div class="agora-pp-hero-text">
<div class="agora-pp-name">${esc(c.displayName || 'Citizen')}</div>
<div class="agora-pp-prof">${esc(professions.join(' · '))}</div>
</div>
- <span class="agora-pp-status agora-pp-status-${esc(String(status).toLowerCase())}">${esc(status)}</span>
+ <span class="agora-pp-grade agora-grade tier-${grade.tier}" title="Reputation ${esc(String(reputation))} — ${esc(grade.label)}">
+ <span class="agora-grade-letter">${esc(grade.grade)}</span>
+ <span class="agora-grade-label">${esc(grade.label)}</span>
+ </span>
+ </div>
+
+ <div class="agora-pp-statusline">
+ <span class="agora-status ${statusClass(status)}"><span class="agora-status-dot"></span>${esc(status)}</span>
+ ${c.kind ? `<span class="agora-pp-chip">${esc(c.kind === 'human' ? 'Human' : 'Agent')}</span>` : ''}
+ ${c.agenc?.cluster ? `<span class="agora-pp-chip">AgenC · ${esc(c.agenc.cluster)}</span>` : ''}
</div>
<div class="agora-pp-stats">
@@ -215,36 +267,133 @@ export class PassportPanel {
<div class="agora-pp-stat">
<div class="agora-pp-stat-value">${esc(s.value)}</div>
<div class="agora-pp-stat-label">${esc(s.label)}</div>
+ <div class="agora-pp-stat-sub">${esc(s.sub)}</div>
</div>`).join('')}
</div>
- ${identity.length ? `<div class="agora-pp-identity">${identity.map((i) => `<span class="agora-pp-chip">${i}</span>`).join('')}</div>` : ''}
+ ${onchain ? this._renderOnchain(onchain) : this._renderProjectionNote(c)}
+
+ ${showHandshake ? `
+ <h3 class="agora-pp-section">Cross-chain identity</h3>
+ <div class="agora-handshake-mount"></div>` : ''}
- <h3 class="agora-pp-section">Recent activity</h3>
+ <h3 class="agora-pp-section">Activity</h3>
${this._renderActivity(data.activity || [])}`;
+
+ // Mount the cross-chain handshake (DOM-built; can't live in the innerHTML).
+ if (showHandshake) {
+ const mount = this._bodyEl.querySelector('.agora-handshake-mount');
+ if (mount) renderHandshake(mount, { proofs, cluster: this._cluster, expectedAgentPda: c.agenc?.agentPda }).catch((e) => log.warn('[agora] handshake render failed', e?.message));
+ }
+
+ // Wire activity row interactions (links carry data-*; closures attach here).
+ this._wireActivity();
+ }
+
+ _renderOnchain(o) {
+ const cluster = this._cluster;
+ const rows = [
+ ['Status', esc(o.status || '—')],
+ ['Reputation', esc(String(o.reputation ?? 0))],
+ ['Stake', `${esc(fmtSol(o.stakeAmount))} SOL`],
+ ['Active tasks', esc(String(o.activeTasks ?? 0))],
+ ];
+ if (o.authority) rows.push(['Authority', `<a class="agora-addr" href="${explorerAddr(o.authority, cluster)}" target="_blank" rel="noopener noreferrer">${esc(shortAddr(o.authority))} ↗</a>`]);
+ if (o.endpoint) rows.push(['Endpoint', `<span class="agora-mono-sm">${esc(o.endpoint)}</span>`]);
+ return `
+ <h3 class="agora-pp-section agora-pp-section-live">On-chain registry <span class="agora-live-dot" title="Live read from the AgenC program"></span></h3>
+ <div class="agora-pp-onchain">
+ ${rows.map(([k, v]) => `<div class="agora-kv"><span class="agora-kv-key">${esc(k)}</span><span class="agora-kv-val">${v}</span></div>`).join('')}
+ </div>`;
+ }
+
+ _renderProjectionNote(c) {
+ const msg = c.agenc?.registered
+ ? 'Couldn\'t reach the AgenC program for a live read — showing the latest projected snapshot.'
+ : 'Not yet registered on the AgenC chain — projection record only.';
+ return `<p class="agora-pp-empty">${esc(msg)}</p>`;
}
_renderActivity(activity) {
if (!activity.length) {
return `<p class="agora-pp-empty">No on-chain activity yet. This citizen is just getting started in the Commons.</p>`;
}
- return `<ul class="agora-pp-feed">${activity.slice(0, 12).map((a) => {
+ const cluster = this._cluster;
+ return `<ul class="agora-pp-feed">${activity.slice(0, 25).map((a) => {
const title = a.narrative || ACTIVITY_LABEL[a.kind] || a.kind;
- const meta = [a.rewardLabel, fmtTimeAgo(a.at)].filter(Boolean).join(' · ');
const rep = (a.repBefore != null && a.repAfter != null && a.repBefore !== a.repAfter)
- ? `<span class="agora-pp-rep">rep ${a.repBefore} → ${a.repAfter}</span>` : '';
+ ? `<span class="agora-pp-rep">rep ${esc(String(a.repBefore))} → ${esc(String(a.repAfter))}</span>` : '';
+ const reward = a.rewardLabel ? `<span class="agora-pp-reward">${esc(String(a.rewardLabel))}</span>` : '';
+ const verifiable = /complete/i.test(a.kind || '') && a.deliverableUrl && a.proofHash;
+ const links = [];
+ if (a.txSignature) links.push(`<a class="agora-tx-link" href="${explorerTx(a.txSignature, cluster)}" target="_blank" rel="noopener noreferrer">tx ↗</a>`);
+ if (a.deliverableUrl) links.push(`<a class="agora-tx-link" href="${esc(a.deliverableUrl)}" target="_blank" rel="noopener noreferrer">deliverable ↗</a>`);
+ if (verifiable) links.push(`<button class="agora-verify-chip" type="button" data-verify="1" data-task="${esc(a.taskPda || '')}" data-task-id="${esc(a.taskId || '')}" data-proof="${esc(a.proofHash)}" data-url="${esc(a.deliverableUrl)}" data-title="${esc(title)}" data-prof="${esc(a.profession || '')}" data-reward="${esc(a.rewardLabel || '')}" data-amount="${esc(a.amountAtomic || '')}" data-tx="${esc(a.txSignature || '')}">✓ verify</button>`);
return `<li class="agora-pp-feed-item">
<span class="agora-pp-feed-kind" data-kind="${esc(a.kind)}"></span>
<div class="agora-pp-feed-main">
<div class="agora-pp-feed-title">${esc(title)}</div>
- <div class="agora-pp-feed-meta">${esc(meta)} ${rep}</div>
+ <div class="agora-pp-feed-meta"><span class="agora-pp-feed-time">${esc(fmtTimeAgo(a.at))}</span>${reward}${rep}</div>
+ ${links.length ? `<div class="agora-activity-links">${links.join('')}</div>` : ''}
</div>
</li>`;
}).join('')}</ul>`;
}
- dispose() {
- document.removeEventListener('keydown', this._onKey);
- this._el.remove();
+ // Open the job-detail + verifier for a completed task. Decoupled via the same
+ // event the board uses, so one panel serves every entry point.
+ _wireActivity() {
+ this._bodyEl.querySelectorAll('button[data-verify]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ window.dispatchEvent(new CustomEvent('agora:open-job', { detail: {
+ task: {
+ taskPda: btn.dataset.task || null,
+ taskId: btn.dataset.taskId || null,
+ cluster: this._cluster,
+ title: btn.dataset.title || 'Completed task',
+ profession: btn.dataset.prof || null,
+ proofHash: btn.dataset.proof || null,
+ deliverableUrl: btn.dataset.url || null,
+ txSignature: btn.dataset.tx || null,
+ reward: btn.dataset.reward ? { label: btn.dataset.reward, amountAtomic: btn.dataset.amount || null } : null,
+ },
+ opener: btn,
+ } }));
+ });
+ });
}
+
+ // ── deep-link + a11y ───────────────────────────────────────────────────────
+ _maybeDeepLink() {
+ try {
+ const id = new URLSearchParams(window.location.search).get('citizen');
+ if (id) requestAnimationFrame(() => this.open(id));
+ } catch { /* non-fatal */ }
+ }
+
+ _setDeepLink(id) {
+ try { const u = new URL(window.location.href); u.searchParams.set('citizen', id); window.history.replaceState(null, '', u); } catch { /* non-fatal */ }
+ }
+
+ _clearDeepLink() {
+ try { const u = new URL(window.location.href); u.searchParams.delete('citizen'); window.history.replaceState(null, '', u); } catch { /* non-fatal */ }
+ }
+
+ _trapTab(e) {
+ const items = [...this._el.querySelectorAll('a[href],button:not([disabled]),[tabindex]:not([tabindex="-1"])')].filter((n) => n.offsetParent !== null);
+ if (!items.length) return;
+ const first = items[0];
+ const last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
+ }
+}
+
+function statusClass(status) {
+ const s = String(status || '').toLowerCase();
+ if (s.startsWith('active')) return 'is-active';
+ if (s.startsWith('busy')) return 'is-busy';
+ if (s.startsWith('idle')) return 'is-idle';
+ if (s.startsWith('suspend')) return 'is-suspended';
+ return 'is-idle';
}
diff --git a/src/agora/trust-surface.css.js b/src/agora/trust-surface.css.js
index 5eef47df3..b1781e907 100644
--- a/src/agora/trust-surface.css.js
+++ b/src/agora/trust-surface.css.js
@@ -237,6 +237,16 @@ export const TRUST_SURFACE_CSS = `
.agora-handshake-loading { display: flex; flex-direction: column; gap: 6px; }
.agora-handshake-loading-label { font-size: 12px; color: rgba(255,255,255,0.5); }
+/* passport additions layered over agora.css's .agora-pp-* base */
+.agora-pp-hero-text { flex: 1; min-width: 0; }
+.agora-pp-grade { flex: none; margin-left: auto; }
+.agora-pp-statusline { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 2px 0 14px; }
+.agora-pp-stat-sub { font-size: 9px; color: rgba(255,255,255,0.4); text-transform: uppercase; letter-spacing: 0.04em; margin-top: 2px; }
+.agora-pp-section-live { display: flex; align-items: center; gap: 8px; }
+.agora-pp-onchain { display: flex; flex-direction: column; gap: 0; padding: 4px 12px; background: rgba(143,181,255,0.05); border: 1px solid rgba(143,181,255,0.16); border-radius: 12px; }
+.agora-pp-reward { font-size: 11px; color: #8a6dff; font-weight: 600; }
+.agora-pp-feed-time { font-size: 11px; color: rgba(255,255,255,0.4); }
+
.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) {
diff --git a/tests/agora-handshake.test.js b/tests/agora-handshake.test.js
new file mode 100644
index 000000000..bccfc523b
--- /dev/null
+++ b/tests/agora-handshake.test.js
@@ -0,0 +1,104 @@
+// Agora cross-chain handshake — unit tests for the bridge math. The handshake's
+// honesty depends on the browser re-deriving the canonical AgenC agentId exactly
+// as the on-chain bridge does (solana-agent-sdk identity-bridge), so it can
+// confirm /api/agenc/link's output rather than trust it. Here we cross-check the
+// browser derivation in handshake.js against an INDEPENDENT Node implementation
+// of the documented spec — if either drifts, this fails.
+
+import { describe, it, expect } from 'vitest';
+import { createHash } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+import {
+ deriveCanonicalAgenCId, parseIdentityProofs, hasDualIdentity,
+} from '../src/agora/handshake.js';
+
+const NS_COMPOSITE = 'AgenC/three.ws/composite/v1\0';
+const NS_ERC8004 = 'AgenC/three.ws/erc8004/v1\0';
+const NS_MPL_CORE = 'AgenC/three.ws/mpl-core/v1\0';
+const NS_HANDLE = 'AgenC/three.ws/handle/v1\0';
+
+// Synthetic, valid base58 pubkey for test assets (System program id — clearly
+// not a coin, per the repo's no-real-mint rule).
+const TEST_ASSET = '11111111111111111111111111111111';
+
+function ercBe(id) {
+ let n = BigInt(id);
+ const out = Buffer.alloc(32);
+ for (let i = 31; i >= 0 && n > 0n; i--) { out[i] = Number(n & 0xffn); n >>= 8n; }
+ return out;
+}
+function nodeSha(...parts) {
+ const h = createHash('sha256');
+ for (const p of parts) h.update(typeof p === 'string' ? Buffer.from(p, 'utf8') : p);
+ return h.digest('hex');
+}
+
+describe('deriveCanonicalAgenCId — matches the documented bridge spec', () => {
+ it('composite (EVM + Solana) binds both proofs', async () => {
+ const erc = '42';
+ const mplBase58 = new PublicKey(TEST_ASSET).toBase58();
+ const composite = JSON.stringify({ v: 1, erc8004: '0x' + ercBe(erc).toString('hex'), mplCore: mplBase58 });
+ const expected = nodeSha(NS_COMPOSITE, composite);
+
+ const got = await deriveCanonicalAgenCId({ erc8004AgentId: erc, mplCoreAsset: TEST_ASSET });
+ expect(got.source).toBe('composite');
+ expect(got.hex).toBe(expected);
+ });
+
+ it('erc8004-only', async () => {
+ const expected = nodeSha(NS_ERC8004, ercBe('7'));
+ const got = await deriveCanonicalAgenCId({ erc8004AgentId: '7' });
+ expect(got.source).toBe('erc8004');
+ expect(got.hex).toBe(expected);
+ });
+
+ it('mpl-core-only', async () => {
+ const expected = nodeSha(NS_MPL_CORE, Buffer.from(new PublicKey(TEST_ASSET).toBytes()));
+ const got = await deriveCanonicalAgenCId({ mplCoreAsset: TEST_ASSET });
+ expect(got.source).toBe('mpl-core');
+ expect(got.hex).toBe(expected);
+ });
+
+ it('handle-only is case-insensitive', async () => {
+ const expected = nodeSha(NS_HANDLE, 'aria');
+ const got = await deriveCanonicalAgenCId({ handle: 'ARIA' });
+ expect(got.source).toBe('handle');
+ expect(got.hex).toBe(expected);
+ });
+
+ it('composite priority: same inputs in either field order resolve identically', async () => {
+ const a = await deriveCanonicalAgenCId({ erc8004AgentId: '42', mplCoreAsset: TEST_ASSET, handle: 'ignored' });
+ const b = await deriveCanonicalAgenCId({ erc8004AgentId: '42', mplCoreAsset: TEST_ASSET });
+ expect(a.hex).toBe(b.hex); // handle is ignored once both chains are present
+ expect(a.source).toBe('composite');
+ });
+
+ it('produces a 64-char lowercase hex id', async () => {
+ const got = await deriveCanonicalAgenCId({ erc8004AgentId: '1', mplCoreAsset: TEST_ASSET });
+ expect(got.hex).toMatch(/^[0-9a-f]{64}$/);
+ });
+});
+
+describe('parseIdentityProofs', () => {
+ it('extracts erc8004 + mpl + handle from a metadataUri', () => {
+ const uri = 'https://three.ws/.well-known/agent.json?erc8004=42&mpl=' + TEST_ASSET + '&handle=Aria';
+ const p = parseIdentityProofs(uri);
+ expect(p.erc8004AgentId).toBe('42');
+ expect(p.mplCoreAsset).toBe(TEST_ASSET);
+ expect(p.handle).toBe('aria');
+ });
+
+ it('is null-safe and tolerates a bare query', () => {
+ expect(parseIdentityProofs(null)).toEqual({ erc8004AgentId: null, mplCoreAsset: null, handle: null });
+ expect(parseIdentityProofs('erc8004=9').erc8004AgentId).toBe('9');
+ });
+});
+
+describe('hasDualIdentity', () => {
+ it('true only when both chains are present', () => {
+ expect(hasDualIdentity({ erc8004AgentId: '1', mplCoreAsset: TEST_ASSET })).toBe(true);
+ expect(hasDualIdentity({ erc8004AgentId: '1' })).toBe(false);
+ expect(hasDualIdentity({ mplCoreAsset: TEST_ASSET })).toBe(false);
+ expect(hasDualIdentity({})).toBe(false);
+ });
+});
diff --git a/tests/agora-task-supply.test.js b/tests/agora-task-supply.test.js
new file mode 100644
index 000000000..65f6962c1
--- /dev/null
+++ b/tests/agora-task-supply.test.js
@@ -0,0 +1,194 @@
+/**
+ * Agora task supply (Task 03) — unit tests for the pure economic logic.
+ *
+ * These cover the decisions that make the board's AgenC lane real demand: the
+ * profession bitmap, the career-ladder claim gate, the patron demand policy
+ * (incl. honest scarcity), agent-to-agent hiring, the reconcile state mapping,
+ * and the narration. All pure — no SDK build, no DB, no RPC — so they run in CI
+ * regardless of whether @three-ws/solana-agent's dist/ exists.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ professionBits,
+ capabilitiesSatisfy,
+ primaryProfession,
+ buildRoster,
+} from '../workers/agora-citizens/roster.js';
+import {
+ citizenCanClaim,
+ ineligibilityReason,
+ minReputationForTier,
+ pickTier,
+ decidePatronPost,
+ decideHire,
+ reconcileTransition,
+ BOARD_TERMINAL_KINDS,
+ REPUTATION_LADDER,
+} from '../workers/agora-citizens/policy.js';
+import { rewardLabel, postedTaskNarrative, hiredNarrative } from '../workers/agora-citizens/narrative.js';
+
+describe('professions / capability bitmap', () => {
+ it('maps profession keys to stable bits', () => {
+ expect(professionBits(['fetcher'])).toBe(1n);
+ expect(professionBits(['sculptor'])).toBe(2n);
+ expect(professionBits(['fetcher', 'scribe'])).toBe(5n); // bit0 | bit2
+ });
+
+ it('capability subset test (required ⊆ worker)', () => {
+ expect(capabilitiesSatisfy(1n, 1n)).toBe(true); // fetcher can do fetcher work
+ expect(capabilitiesSatisfy(1n, 0n)).toBe(true); // anyone can do an unrestricted task
+ expect(capabilitiesSatisfy(1n, 2n)).toBe(false); // fetcher can't do sculptor work
+ expect(capabilitiesSatisfy(5n, 1n)).toBe(true); // fetcher+scribe can do fetcher work
+ });
+
+ it('primary profession is the lowest set bit', () => {
+ expect(primaryProfession(5n)).toBe('fetcher');
+ expect(primaryProfession(4n)).toBe('scribe');
+ expect(primaryProfession(0n)).toBe(null);
+ });
+});
+
+describe('career-ladder claim gate', () => {
+ const fetcher = (reputation) => ({ capabilityBits: 1n, reputation });
+
+ it('lets a qualified citizen claim', () => {
+ expect(citizenCanClaim(fetcher(0), { requiredCapabilities: 1n, minReputation: 0 })).toBe(true);
+ expect(citizenCanClaim(fetcher(20), { requiredCapabilities: 1n, minReputation: 20 })).toBe(true);
+ });
+
+ it('blocks a low-reputation citizen from a gated bounty (the ladder)', () => {
+ const task = { requiredCapabilities: 1n, minReputation: 20 };
+ expect(citizenCanClaim(fetcher(2), task)).toBe(false);
+ expect(ineligibilityReason(fetcher(2), task)).toBe('below_min_reputation');
+ });
+
+ it('blocks a citizen missing the capability', () => {
+ const sculptJob = { requiredCapabilities: 2n, minReputation: 0 };
+ expect(citizenCanClaim(fetcher(99), sculptJob)).toBe(false);
+ expect(ineligibilityReason(fetcher(99), sculptJob)).toBe('missing_capability');
+ });
+
+ it('ladder tiers are documented and gate as published', () => {
+ expect(minReputationForTier('apprentice')).toBe(0);
+ expect(minReputationForTier('journeyman')).toBe(5);
+ expect(minReputationForTier('master')).toBe(20);
+ expect(REPUTATION_LADDER.map((t) => t.tier)).toEqual(['apprentice', 'journeyman', 'master']);
+ });
+});
+
+describe('patron demand policy', () => {
+ const tiers = [
+ { tier: 'apprentice', profession: 'fetcher', rewardAtomic: 1_000_000n, minReputation: 0 },
+ { tier: 'journeyman', profession: 'fetcher', rewardAtomic: 2_000_000n, minReputation: 5 },
+ ];
+ const patron = () => ({ patron: { tiers, minPostIntervalMs: 1_000 } });
+
+ it('rotates tiers by post count', () => {
+ expect(pickTier(tiers, 0).tier).toBe('apprentice');
+ expect(pickTier(tiers, 1).tier).toBe('journeyman');
+ expect(pickTier(tiers, 2).tier).toBe('apprentice');
+ });
+
+ it('posts when funded and outside the interval', () => {
+ const d = decidePatronPost({ citizen: patron(), now: 10_000, lastPostAt: 0, balanceAtomic: 50_000_000n, postedCount: 0 });
+ expect(d.post).toBe(true);
+ expect(d.plan.profession).toBe('fetcher');
+ expect(d.plan.requiredCapabilities).toBe(1n);
+ expect(d.plan.rewardAtomic).toBe(1_000_000n);
+ expect(d.plan.minReputation).toBe(0);
+ });
+
+ it('honest scarcity — stops posting when the budget cannot cover reward + headroom', () => {
+ const d = decidePatronPost({
+ citizen: patron(),
+ now: 10_000,
+ lastPostAt: 0,
+ balanceAtomic: 1_000_000n, // exactly the reward, but headroom pushes need above it
+ headroomAtomic: 12_000_000n,
+ postedCount: 0,
+ });
+ expect(d.post).toBe(false);
+ expect(d.reason).toBe('insufficient_funds');
+ });
+
+ it('respects the post interval', () => {
+ const d = decidePatronPost({ citizen: patron(), now: 10_500, lastPostAt: 10_000, balanceAtomic: 50_000_000n, postedCount: 0 });
+ expect(d.post).toBe(false);
+ expect(d.reason).toBe('interval_guard');
+ });
+
+ it('a non-patron never posts', () => {
+ expect(decidePatronPost({ citizen: {}, now: 1, balanceAtomic: 9_999_999_999n }).post).toBe(false);
+ });
+});
+
+describe('agent-to-agent hiring', () => {
+ it('hires a sub-agent when funded', () => {
+ const d = decideHire({ neededProfession: 'fetcher', balanceAtomic: 50_000_000n, subRewardAtomic: 1_000_000n });
+ expect(d.hire).toBe(true);
+ expect(d.plan.requiredCapabilities).toBe(1n);
+ expect(d.plan.minReputation).toBe(0);
+ });
+
+ it('declines to hire when out of funds (scarcity)', () => {
+ const d = decideHire({ neededProfession: 'fetcher', balanceAtomic: 100n, subRewardAtomic: 1_000_000n });
+ expect(d.hire).toBe(false);
+ expect(d.reason).toBe('insufficient_funds');
+ });
+
+ it('rejects an unknown profession', () => {
+ expect(decideHire({ neededProfession: 'wizard', balanceAtomic: 1n, subRewardAtomic: 0n }).hire).toBe(false);
+ });
+});
+
+describe('reconcile state mapping', () => {
+ it('leaves an open task on the board', () => {
+ expect(reconcileTransition('Open')).toBe(null);
+ expect(reconcileTransition(0)).toBe(null);
+ });
+
+ it('maps each terminal state to a board-closing projection kind', () => {
+ expect(reconcileTransition('Claimed').kind).toBe('claimed_task');
+ expect(reconcileTransition('Completed').kind).toBe('completed_task');
+ expect(reconcileTransition('Cancelled').kind).toBe('cancelled_task');
+ expect(reconcileTransition('Expired').kind).toBe('expired_task');
+ expect(reconcileTransition('Disputed').kind).toBe('slashed');
+ });
+
+ it('every transition kind is in the board terminal set', () => {
+ for (const label of ['Claimed', 'Completed', 'Cancelled', 'Expired', 'Disputed']) {
+ expect(BOARD_TERMINAL_KINDS).toContain(reconcileTransition(label).kind);
+ }
+ expect(BOARD_TERMINAL_KINDS).toEqual(
+ expect.arrayContaining(['claimed_task', 'completed_task', 'slashed', 'cancelled_task', 'expired_task']),
+ );
+ });
+});
+
+describe('narration', () => {
+ it('formats SOL and $THREE rewards', () => {
+ expect(rewardLabel({ amountAtomic: 5_000_000n, mint: null, decimals: 9 })).toBe('0.0050 SOL');
+ expect(rewardLabel({ amountAtomic: 25_000_000_000n, mint: '$THREE', decimals: 6 })).toBe('25,000 $THREE');
+ });
+
+ it('writes a real story line for a posting and a hire', () => {
+ expect(postedTaskNarrative({ poster: 'Aria', profession: 'fetcher', reward: '0.0010 SOL', minReputation: 5 }))
+ .toMatch(/Aria posted a Fetcher bounty worth 0.0010 SOL \(needs reputation 5\)\./);
+ expect(hiredNarrative({ poster: 'Koa', profession: 'fetcher', reward: '0.0010 SOL', parentLabel: 'Fetcher job ab12cd34' }))
+ .toMatch(/Koa hired a Fetcher to help finish/);
+ });
+});
+
+describe('roster assembly', () => {
+ it('fills to the cap with standalone citizens on an empty DB', () => {
+ const specs = buildRoster([], { maxCitizens: 4 });
+ expect(specs.length).toBe(4);
+ expect(specs.every((s) => s.kind === 'agent')).toBe(true);
+ expect(specs.every((s) => s.professionBits === 1n)).toBe(true); // all Fetchers in Task 02
+ });
+
+ it('respects the citizen cap', () => {
+ expect(buildRoster([], { maxCitizens: 2 }).length).toBe(2);
+ });
+});
diff --git a/tests/agora-verify.test.js b/tests/agora-verify.test.js
new file mode 100644
index 000000000..df7542c47
--- /dev/null
+++ b/tests/agora-verify.test.js
@@ -0,0 +1,110 @@
+// Agora deliverable verifier — unit tests for the honest core. The whole trust
+// surface rests on these: re-hash the deliverable, compare to the on-chain
+// proofHash. We test against real Web Crypto digests and known SHA-256 vectors,
+// plus the normalization/compare rules that must never produce a false ✓ or ✗.
+
+import { describe, it, expect } from 'vitest';
+import { createHash } from 'node:crypto';
+import { sha256Hex, compareHash, VerifyError } from '../src/agora/verify.js';
+import { normalizeHex, formatThree, shortId, formatBytes } from '../src/agora/format.js';
+
+const enc = (s) => new TextEncoder().encode(s);
+
+describe('sha256Hex', () => {
+ it('matches the canonical SHA-256 vector for "abc"', async () => {
+ expect(await sha256Hex(enc('abc'))).toBe(
+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
+ );
+ });
+
+ it('matches the empty-input vector', async () => {
+ expect(await sha256Hex(new Uint8Array(0))).toBe(
+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
+ );
+ });
+
+ it('agrees with node crypto over random-ish bytes', async () => {
+ const bytes = Uint8Array.from({ length: 5000 }, (_, i) => (i * 37 + 11) & 0xff);
+ const expected = createHash('sha256').update(Buffer.from(bytes)).digest('hex');
+ expect(await sha256Hex(bytes)).toBe(expected);
+ });
+
+ it('hashes only the view range, not the backing buffer', async () => {
+ const backing = new Uint8Array([9, 9, 1, 2, 3, 9, 9]);
+ const view = backing.subarray(2, 5); // [1,2,3]
+ const expected = createHash('sha256').update(Buffer.from([1, 2, 3])).digest('hex');
+ expect(await sha256Hex(view)).toBe(expected);
+ });
+});
+
+describe('compareHash', () => {
+ it('matches identical hashes', () => {
+ const r = compareHash('abc123', 'abc123');
+ expect(r.match).toBe(true);
+ expect(r.haveExpected).toBe(true);
+ });
+
+ it('ignores 0x prefix and case', () => {
+ const r = compareHash('0xABC123', 'abc123');
+ expect(r.match).toBe(true);
+ expect(r.computed).toBe('abc123');
+ expect(r.expected).toBe('abc123');
+ });
+
+ it('reports a mismatch when bytes differ (the tamper case)', () => {
+ const r = compareHash('deadbeef', 'feedface');
+ expect(r.match).toBe(false);
+ });
+
+ it('never claims a match when there is no on-chain proofHash', () => {
+ const r = compareHash('deadbeef', '');
+ expect(r.match).toBe(false);
+ expect(r.haveExpected).toBe(false);
+ });
+
+ it('never claims a match for an empty computed hash', () => {
+ const r = compareHash('', 'deadbeef');
+ expect(r.match).toBe(false);
+ });
+
+ it('end-to-end: a real digest matches its own proofHash and a tampered copy does not', async () => {
+ const good = enc('a verified forge GLB, byte-for-byte');
+ const proof = await sha256Hex(good);
+ expect(compareHash(await sha256Hex(good), proof).match).toBe(true);
+
+ const tampered = enc('a verified forge GLB, byte-for-bytX'); // one byte changed
+ expect(compareHash(await sha256Hex(tampered), proof).match).toBe(false);
+ });
+});
+
+describe('VerifyError', () => {
+ it('carries a code for honest UI messaging', () => {
+ const e = new VerifyError('cors', 'blocked');
+ expect(e).toBeInstanceOf(Error);
+ expect(e.code).toBe('cors');
+ expect(e.name).toBe('VerifyError');
+ });
+});
+
+describe('format helpers', () => {
+ it('normalizeHex strips 0x and lowercases', () => {
+ expect(normalizeHex('0xDEADbeef')).toBe('deadbeef');
+ expect(normalizeHex(null)).toBe('');
+ });
+
+ it('formatThree renders 6-decimal atomic $THREE amounts', () => {
+ expect(formatThree('25000000000')).toBe('25,000');
+ expect(formatThree('0')).toBe('0');
+ expect(formatThree('1500000')).toBe('1.5');
+ });
+
+ it('shortId truncates long ids and leaves short ones', () => {
+ expect(shortId('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe('FeMb…pump');
+ expect(shortId('abc')).toBe('abc');
+ });
+
+ it('formatBytes is human-readable', () => {
+ expect(formatBytes(512)).toBe('512 B');
+ expect(formatBytes(1536)).toBe('1.5 KB');
+ });
+});
diff --git a/workers/agora-citizens/index.js b/workers/agora-citizens/index.js
index bf251f3fa..2beb88bc3 100644
--- a/workers/agora-citizens/index.js
+++ b/workers/agora-citizens/index.js
@@ -17,8 +17,13 @@ import http from 'node:http';
import { loadConfig } from './config.js';
import { makeStore } from './store.js';
import { bootFleet, tickCitizen, replenishWork, planDryRun } from './engine.js';
+import { reconcileOnce } from './reconcile.js';
import { log } from './log.js';
+// Reconcile cadence — re-read open postings from the chain and drop any that are
+// no longer open (claimed/cancelled/expired) off the board. Independent of ticks.
+const RECONCILE_MS = Math.max(30_000, Number(process.env.AGORA_RECONCILE_MS) || 60_000);
+
const BOOT_AT = new Date().toISOString();
// Cloud Run services must answer a startup/health probe on $PORT. This worker is
@@ -47,6 +52,12 @@ async function runOnce(ctx) {
const node = await tickCitizen(ctx, citizen);
outcomes[node] = (outcomes[node] || 0) + 1;
}
+ // Reconcile so a one-shot run also closes any posting the chain has moved on.
+ try {
+ await reconcileOnce({ cfg: ctx.cfg, store: ctx.store, readClient: ctx.readClient });
+ } catch (err) {
+ log.warn('reconcile (once) failed', { err: err?.message });
+ }
log.info('single sweep complete', { citizens: ctx.citizens.length, outcomes });
}
@@ -77,6 +88,16 @@ async function runForever(ctx) {
if (!draining) replenishWork(ctx).catch((err) => log.warn('replenish error', { err: err?.message }));
}, Math.max(cfg.tickBaseMs, 30_000));
+ // Reconcile the board against the chain on its own cadence (Task 03): close
+ // out postings that are claimed/cancelled/expired and link agent-to-agent hires.
+ const reconcileTimer = setInterval(() => {
+ if (!draining) {
+ reconcileOnce({ cfg, store: ctx.store, readClient: ctx.readClient }).catch((err) =>
+ log.warn('reconcile error', { err: err?.message }),
+ );
+ }
+ }, RECONCILE_MS);
+
let heartbeatTimer = null;
if (cfg.heartbeatMs) {
const beat = () =>
@@ -102,6 +123,7 @@ async function runForever(ctx) {
log.info('shutdown', { signal });
for (const t of timers) clearTimeout(t);
clearInterval(supplyTimer);
+ clearInterval(reconcileTimer);
if (heartbeatTimer) clearInterval(heartbeatTimer);
// Neon HTTP + Upstash REST are stateless — nothing to close. Give an
// in-flight tick a moment to land its projection writes.
diff --git a/workers/agora-citizens/work/_skills.js b/workers/agora-citizens/work/_skills.js
index 236d3e3d5..1210520ab 100644
--- a/workers/agora-citizens/work/_skills.js
+++ b/workers/agora-citizens/work/_skills.js
@@ -123,8 +123,10 @@ export async function storeDeliverable({ profession, ext, contentType, bytes, so
// ── 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}`;
+ // A leading "/" is a relative API path to join onto the base; anything else is
+ // already an absolute URL (https:, data:, …) and is used verbatim.
+ if (String(path).startsWith('/')) return `${String(apiBase || 'https://three.ws').replace(/\/+$/, '')}${path}`;
+ return path;
}
export async function httpJson(apiBase, path, { method = 'GET', body, headers, query, signal } = {}) {