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(trust): sign hire fulfillment attestations and feed them into agent reputation and x402 pricing
nirholas2f8110a92783
diff --git a/api/_lib/a2a-hire-phases.js b/api/_lib/a2a-hire-phases.jsindex 109aa403a..782391650 100644--- a/api/_lib/a2a-hire-phases.js+++ b/api/_lib/a2a-hire-phases.js@@ -1,5 +1,6 @@// Pure phase → render mapping + cap math for the live agent-to-agent hire-// visualizer.+// visualizer, plus the pure core of the fulfillment attestation every settled+// hire writes (api/_lib/trust/hire-attestations.js does the signing/DB I/O).//// /api/agents/a2a-hire emits ONE screen frame per real milestone of a hire so a// viewer on /agent-screen watches the commerce happen end to end:@@ -187,3 +188,64 @@ export function hirePhaseFrame(phase, ctx = {}) {const activity = narration(phase, { skillLabel, provLabel, slug, price, cap, resultSummary, error });return { activity, type: 'analysis', meta };}++// ── Fulfillment attestation (pure core) ──────────────────────────────────────+//+// Every settled hire gets exactly one attestation row:+// { hire_id, payment_signature, outcome, evidence_hash, signed_by }+// outcome is one of delivered | failed | disputed. The 'recorded' phase is the+// only path to 'delivered': a thrown payment error is 'failed' UNLESS the+// error itself is ambiguous (e.g. a client timeout that fired after the+// provider may have already settled server-side, since x402 settle happens+// upstream of the response reaching us), in which case it is 'disputed'.+// Never infer 'delivered' from an ambiguous error.++// A client-side timeout/abort tells us nothing about whether the x402+// endpoint's verify-then-settle already completed server-side before the+// response was lost, so it is the one failure shape that is genuinely+// ambiguous rather than a clean "no funds moved".+export function isAmbiguousPaymentError(err) {+ if (!err) return false;+ const code = err.code || err.cause?.code || '';+ const name = err.name || '';+ const msg = String(err.message || '').toLowerCase();+ return (+ code === 'ECONNABORTED' ||+ code === 'ETIMEDOUT' ||+ code === 'ERR_CANCELED' ||+ name === 'CanceledError' ||+ msg.includes('timeout') ||+ msg.includes('timed out')+ );+}++// phase is the terminal hire-visualizer phase ('recorded' for a completed+// hire, 'failed' for a thrown payment/reservation error).+export function classifyHireOutcome(phase, err = null) {+ if (phase === 'recorded') return 'delivered';+ if (isAmbiguousPaymentError(err)) return 'disputed';+ return 'failed';+}++// Deterministic, key-order-independent JSON so the same evidence always+// hashes the same regardless of how the caller built the object. Exported so+// api/_lib/trust/hire-attestations.js (server-only) can sha256 it for+// hireEvidenceHash without this shared client+server module importing+// node:crypto.+export function sortedStringify(value) {+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(sortedStringify).join(',')}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${sortedStringify(value[k])}`).join(',')}}`;+}++// Canonical attestation payload shape, independent of signing.+export function buildHireAttestationPayload({ hireId, paymentSignature, outcome, evidenceHash, signedBy }) {+ return {+ hire_id: hireId,+ payment_signature: paymentSignature || null,+ outcome,+ evidence_hash: evidenceHash,+ signed_by: signedBy,+ };+}diff --git a/api/_lib/agent-economy.js b/api/_lib/agent-economy.jsindex 91a9b00a6..491fcd60a 100644--- a/api/_lib/agent-economy.js+++ b/api/_lib/agent-economy.js@@ -217,6 +217,7 @@ export async function listOffersWithStats({ limit = 60, providerAgentId = null }s.target_method AS method,s.input_schema AS input_schema,s.created_at AS created_at,+ s.reputation_discount_enabled AS reputation_discount_enabled,ai.id AS provider_agent_id,ai.name AS provider_name,ai.is_public AS provider_is_public,@@ -265,6 +266,7 @@ async function listOffersBySlug(slug) {s.id AS service_id, s.slug AS slug, s.name AS name, s.description AS description,s.price_atomics AS price_atomics, s.network AS network, s.target_method AS method,s.input_schema AS input_schema, s.created_at AS created_at,+ s.reputation_discount_enabled AS reputation_discount_enabled,ai.id AS provider_agent_id, ai.name AS provider_name, ai.is_public AS provider_is_public,ai.meta->>'solana_address' AS provider_addr,av.thumbnail_key AS provider_thumb_key, av.visibility AS provider_avatar_vis,@@ -292,6 +294,7 @@ function shapeOffer(row) {method: row.method,input_schema: row.input_schema || null,created_at: row.created_at,+ reputation_discount_enabled: row.reputation_discount_enabled === true,provider: shapeProvider(row),stats: shapeStats(row),};diff --git a/api/_lib/agent-paid-services.js b/api/_lib/agent-paid-services.jsindex ff5e53af7..a5d62d3ec 100644--- a/api/_lib/agent-paid-services.js+++ b/api/_lib/agent-paid-services.js@@ -163,7 +163,7 @@ export async function getActiveServiceBySlug(slug) {const [row] = await sql`SELECT id, owner_user_id, agent_id, slug, name, description, price_atomics,target_url, target_method, input_schema, network, payout_address,- bazaar_listed, created_at+ bazaar_listed, created_at, reputation_discount_enabledFROM agent_paid_servicesWHERE slug = ${slug} AND archived_at IS NULLLIMIT 1diff --git a/api/_lib/migrations/20261015120000_hire_fulfillment_attestations.sql b/api/_lib/migrations/20261015120000_hire_fulfillment_attestations.sqlnew file mode 100644index 000000000..cecd22e18--- /dev/null+++ b/api/_lib/migrations/20261015120000_hire_fulfillment_attestations.sql@@ -0,0 +1,32 @@+-- Hire fulfillment attestations: one signed row per settled a2a-hire recording+-- whether the provider actually delivered. Signed off-chain with the same+-- platform attestation key api/_lib/attest-event.js uses for on-chain memos+-- (ATTEST_AGENT_SECRET_KEY), but this table never touches the chain: it is the+-- real-data input the free agent reputation score (hireFulfillmentRate in+-- src/shared/agent-financial-reputation.js) reads, recency-weighted by+-- created_at. outcome is 'disputed' whenever delivery is ambiguous (a payment+-- timeout where settlement state is unknown), never inferred as 'delivered'.+--+-- One attestation per hire: a hire's terminal status never flips twice, so a+-- retried write (e.g. a replayed executeApprovedA2aHire) is a no-op here.++create table if not exists hire_attestations (+ id bigserial primary key,+ hire_id uuid not null references agent_hires(id) on delete cascade,+ payment_signature text,+ outcome text not null check (outcome in ('delivered', 'failed', 'disputed')),+ evidence_hash text not null,+ signed_by text not null,+ signature text not null,+ payload jsonb not null,+ created_at timestamptz not null default now(),+ unique (hire_id)+);++-- Fulfillment-rate reads join agent_hires (filtered by provider_agent_id) to+-- this table by hire_id, already covered by the unique constraint above.++-- Per-service opt-in for the x402 reputation discount (task 3). Off by default:+-- a provider must explicitly price in a discount for well-reputed hirers.+alter table agent_paid_services+ add column if not exists reputation_discount_enabled boolean not null default false;diff --git a/api/_lib/trust/hire-attestations.js b/api/_lib/trust/hire-attestations.jsnew file mode 100644index 000000000..5fc85e14d--- /dev/null+++ b/api/_lib/trust/hire-attestations.js@@ -0,0 +1,156 @@+// Signed hire fulfillment attestations: on every settled a2a-hire (success or+// failure), write ONE row recording whether the provider delivered. Signed+// off-chain with the same platform attestation key api/_lib/attest-event.js+// uses for on-chain provenance memos (ATTEST_AGENT_SECRET_KEY), reused for+// the keypair only; this module never builds or sends a Solana transaction.+//+// This is the real-data source behind the agent reputation score's+// fulfillment-rate pillar (src/shared/agent-financial-reputation.js) and the+// optional x402 pricing discount (hire-discount.js).++import { createRequire } from 'node:module';+import { createHash } from 'node:crypto';+import { sql } from '../db.js';+import { loadAttesterKeypair } from '../attest-event.js';+import { classifyHireOutcome, buildHireAttestationPayload, sortedStringify } from '../a2a-hire-phases.js';++const require = createRequire(import.meta.url);+const nacl = require('tweetnacl');++export { classifyHireOutcome };++function hireEvidenceHash(facts = {}) {+ return createHash('sha256').update(sortedStringify(facts)).digest('hex');+}++// Sign a complete attestation payload (signed_by already filled in) with the+// platform attester key. Returns the base64 signature.+function signPayload(payload) {+ const keypair = loadAttesterKeypair();+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ const signature = nacl.sign.detached(message, keypair.secretKey);+ return Buffer.from(signature).toString('base64');+}++// Verify a previously-signed attestation against the CURRENT platform+// attester key. Returns true/false; never throws on a malformed input.+export function verifyHireAttestation({ payload, signature, signedBy }) {+ try {+ const keypair = loadAttesterKeypair();+ if (signedBy && signedBy !== keypair.publicKey.toBase58()) return false;+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ return nacl.sign.detached.verify(+ message,+ Buffer.from(signature, 'base64'),+ keypair.publicKey.toBuffer(),+ );+ } catch {+ return false;+ }+}++// Build the evidence facts for a hire from the real, already-settled row,+// never from caller input, so the hash can't be forged to match a different+// outcome than what actually happened.+function evidenceFacts(hireRow, { paymentSignature, invocationSignature, resultSummary, errorMessage } = {}) {+ return {+ hire_id: hireRow.id,+ hirer_agent_id: hireRow.hirer_agent_id ?? hireRow.hirerAgentId ?? null,+ provider_agent_id: hireRow.provider_agent_id ?? hireRow.providerAgentId ?? null,+ service_slug: hireRow.service_slug ?? hireRow.serviceSlug ?? null,+ usd: hireRow.usd ?? null,+ payment_signature: paymentSignature ?? hireRow.payment_signature ?? null,+ invocation_signature: invocationSignature ?? hireRow.invocation_signature ?? null,+ result_summary: resultSummary ?? null,+ error: errorMessage ?? null,+ };+}++// Record one attestation for a settled hire. `phase` is the hire-visualizer+// terminal phase ('recorded' for completed, 'failed' for a thrown payment+// error); `err` is the thrown error object when phase is 'failed' (used only+// to detect an ambiguous timeout, per classifyHireOutcome, never to infer+// 'delivered'). Idempotent: a retried terminal write for the same hire_id is a+// no-op (unique constraint), since a hire's terminal status never changes+// twice.+export async function recordHireAttestation(hireRow, { phase, err = null, paymentSignature = null, invocationSignature = null, resultSummary = null } = {}) {+ const outcome = classifyHireOutcome(phase, err);+ const facts = evidenceFacts(hireRow, {+ paymentSignature,+ invocationSignature,+ resultSummary,+ errorMessage: err?.message || null,+ });+ const evidenceHash = hireEvidenceHash(facts);+ let keypair;+ try {+ keypair = loadAttesterKeypair();+ } catch (keyErr) {+ console.error('[hire-attestations] attester key unavailable', keyErr?.message || keyErr);+ return null;+ }+ const payload = buildHireAttestationPayload({+ hireId: hireRow.id,+ paymentSignature: paymentSignature ?? hireRow.payment_signature ?? null,+ outcome,+ evidenceHash,+ signedBy: keypair.publicKey.toBase58(),+ });+ const signature = signPayload(payload);+ try {+ const [row] = await sql`+ INSERT INTO hire_attestations+ (hire_id, payment_signature, outcome, evidence_hash, signed_by, signature, payload)+ VALUES (+ ${hireRow.id}, ${payload.payment_signature}, ${outcome}, ${evidenceHash},+ ${payload.signed_by}, ${signature}, ${JSON.stringify(payload)}::jsonb+ )+ ON CONFLICT (hire_id) DO NOTHING+ RETURNING id, hire_id, outcome, evidence_hash, signed_by, signature, created_at+ `;+ return row || null;+ } catch (dbErr) {+ console.error('[hire-attestations] insert failed', dbErr?.message || dbErr);+ return null;+ }+}++// Recency-weighted fulfillment rate: each attestation's contribution decays+// with age (half-life `halfLifeDays`), so a provider's recent conduct matters+// more than a clean record from a year ago. 'disputed' never counts toward+// delivery: an unresolved hire is a risk signal, not a null result.+export function weightedFulfillmentRate(records, { halfLifeDays = 30, now = Date.now() } = {}) {+ let weightSum = 0;+ let deliveredWeightSum = 0;+ for (const r of records) {+ const createdAt = r.created_at instanceof Date ? r.created_at.getTime() : new Date(r.created_at).getTime();+ const ageDays = Math.max(0, (now - createdAt) / 86_400_000);+ const w = Math.pow(0.5, ageDays / halfLifeDays);+ weightSum += w;+ if (r.outcome === 'delivered') deliveredWeightSum += w;+ }+ return {+ rate: weightSum > 0 ? deliveredWeightSum / weightSum : null,+ sampleSize: records.length,+ weightedSampleSize: weightSum,+ };+}++// Real-data read: a provider agent's fulfillment rate from its own+// attestation history. Gated by `minSample`: below it, `rate` is null and+// the caller must not let fulfillment move the reputation score (there isn't+// enough signal yet, which is itself informative but not a penalty).+export async function computeFulfillmentRate(agentId, { halfLifeDays = 30, minSample = 5, limit = 500, now = Date.now() } = {}) {+ if (!agentId) return { rate: null, sampleSize: 0, weightedSampleSize: 0, meetsMinimum: false, minSample };+ const rows = await sql`+ SELECT ha.outcome, ha.created_at+ FROM hire_attestations ha+ JOIN agent_hires ah ON ah.id = ha.hire_id+ WHERE ah.provider_agent_id = ${agentId}+ ORDER BY ha.created_at DESC+ LIMIT ${limit}+ `;+ const { rate, sampleSize, weightedSampleSize } = weightedFulfillmentRate(rows, { halfLifeDays, now });+ const meetsMinimum = sampleSize >= minSample;+ return { rate: meetsMinimum ? rate : null, sampleSize, weightedSampleSize, meetsMinimum, minSample };+}diff --git a/api/_lib/trust/hire-discount.js b/api/_lib/trust/hire-discount.jsnew file mode 100644index 000000000..81e8a41c5--- /dev/null+++ b/api/_lib/trust/hire-discount.js@@ -0,0 +1,101 @@+// Optional x402 pricing discount for agent-to-agent hires, gated per-service+// (agent_paid_services.reputation_discount_enabled, off by default) and sized+// by the HIRING agent's reputation tier.+//+// The paywall (api/x402/service.js) is public: any caller can hit it directly,+// so a discount can never be granted from a caller-supplied claim (that's a+// trivial discount-theft vector: spoof a high tier, pay less). Instead+// api/agents/a2a-hire.js, which has already authenticated the hirer and+// resolved their real reputation, mints a short-lived, slug-scoped voucher+// signed with the platform attester key; the paywall verifies the signature+// (not the claim) before discounting price_atomics.++import { createRequire } from 'node:module';+import { loadAttesterKeypair } from '../attest-event.js';+import { sortedStringify } from '../a2a-hire-phases.js';++const require = createRequire(import.meta.url);+const nacl = require('tweetnacl');++export const DISCOUNT_VOUCHER_HEADER = 'x-threews-reputation-voucher';++// A voucher is only valid for the single hire it was minted for: long enough+// for a2a-hire to use it immediately, short enough that a leaked header can't+// be replayed against an unrelated later hire.+const VOUCHER_TTL_MS = 5 * 60 * 1000;++// Tiers match TIERS in src/shared/agent-financial-reputation.js (the free,+// agent-page-visible "Financial reputation" score): new/emerging carry no+// discount since they have no proven settlement history yet.+const TIER_DISCOUNT_BPS = {+ new: 0,+ emerging: 0,+ established: 300,+ trusted: 1000,+ elite: 2000,+};++export function tierDiscountBps(tier) {+ return TIER_DISCOUNT_BPS[tier] ?? 0;+}++export function applyDiscountBps(priceAtomics, discountBps) {+ const price = BigInt(priceAtomics);+ const bps = Math.max(0, Math.min(10_000, Math.round(discountBps) || 0));+ if (bps === 0) return price.toString();+ return (price - (price * BigInt(bps)) / 10_000n).toString();+}++// Mint a voucher for the given slug + hirer, carrying the discount already+// resolved by the caller (a2a-hire). Returns the base64 header value, or null+// if discountBps resolves to zero (no point minting a no-op voucher).+export function signDiscountVoucher({ slug, hirerAgentId, discountBps, issuedAt = Date.now() }) {+ const bps = Math.max(0, Math.min(10_000, Math.round(discountBps) || 0));+ if (bps <= 0) return null;+ const keypair = loadAttesterKeypair();+ const payload = {+ slug,+ hirer_agent_id: hirerAgentId,+ discount_bps: bps,+ issued_at: issuedAt,+ expires_at: issuedAt + VOUCHER_TTL_MS,+ signed_by: keypair.publicKey.toBase58(),+ };+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ const signature = Buffer.from(nacl.sign.detached(message, keypair.secretKey)).toString('base64');+ const envelope = { payload, signature };+ return Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64');+}++// Verify a voucher header against the CURRENT platform attester key, the+// requested slug, and expiry. Returns the discount_bps to apply, or 0 for+// any missing/malformed/expired/mis-scoped/forged voucher: fails closed to+// full price, never to a discount.+export function verifyDiscountVoucher(headerValue, { slug }) {+ if (!headerValue || typeof headerValue !== 'string') return 0;+ let envelope;+ try {+ envelope = JSON.parse(Buffer.from(headerValue, 'base64').toString('utf8'));+ } catch {+ return 0;+ }+ const { payload, signature } = envelope || {};+ if (!payload || !signature) return 0;+ if (payload.slug !== slug) return 0;+ if (!Number.isFinite(payload.expires_at) || payload.expires_at < Date.now()) return 0;+ if (!Number.isFinite(payload.discount_bps) || payload.discount_bps <= 0) return 0;+ let keypair;+ try {+ keypair = loadAttesterKeypair();+ } catch {+ return 0;+ }+ if (payload.signed_by !== keypair.publicKey.toBase58()) return 0;+ try {+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ const ok = nacl.sign.detached.verify(message, Buffer.from(signature, 'base64'), keypair.publicKey.toBuffer());+ return ok ? payload.discount_bps : 0;+ } catch {+ return 0;+ }+}diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.jsindex 333aa79d5..e7fc60264 100644--- a/api/_lib/trust/wallet-reputation.js+++ b/api/_lib/trust/wallet-reputation.js@@ -16,6 +16,7 @@import { sql } from '../db.js';import { loadAgentReputation } from './solana-bouncer.js';+import { computeFulfillmentRate } from './hire-attestations.js';import { getSolvencyInputs } from './proof-of-reserves.js';import { threeHoldingFor } from '../coin/three-holders.js';import { getTokenPriceUsd } from '../token/price.js';@@ -240,6 +241,17 @@ export async function loadReputationInputs(agentId, opts = {}) {// On-chain payment / distribution / attestation record (already-real index).const solRep = await soft(loadAgentReputation(agentId), null);+ // Hire fulfillment: this agent's own signed delivery record as a PROVIDER+ // on real a2a-hires (api/_lib/trust/hire-attestations.js), one indexed+ // join, no RPC, so always included even in lite mode.+ const fulfillment = await soft(computeFulfillmentRate(agentId), {+ rate: null,+ sampleSize: 0,+ weightedSampleSize: 0,+ meetsMinimum: false,+ minSample: 5,+ });+// Best-effort EVM ERC-8004 reputation registry read (skipped in lite mode).const registry = lite ? { average: 0, count: 0 } : await soft(readErc8004Registry(agent), { average: 0, count: 0 });@@ -286,6 +298,9 @@ export async function loadReputationInputs(agentId, opts = {}) {validationCount: solRep?.attestations?.validation_count || 0,feedbackCount: solRep?.attestations?.feedback_count || 0,hasSkillCollection: Boolean(agent.skill_collection_mint),+ hireFulfillmentRate: fulfillment?.rate ?? null,+ hireFulfillmentSampleSize: fulfillment?.sampleSize || 0,+ hireFulfillmentMinSample: fulfillment?.minSample || 5,};const evidence = buildEvidence(agent, { solRep, registry, holdsThree: threeTokens > 0 });diff --git a/api/_lib/x402-user-payer.js b/api/_lib/x402-user-payer.jsindex 52838f23e..343c999d1 100644--- a/api/_lib/x402-user-payer.js+++ b/api/_lib/x402-user-payer.js@@ -290,7 +290,7 @@ export async function getUserWalletStatus(userId) {// Pay an external x402 endpoint from the user's wallet. Throws an Error with a// `.code` for the boundary (the MCP handler) to translate into a clean result.-export async function payExternalX402({ userId, agentId, url, method = 'GET', body, maxUsd }) {+export async function payExternalX402({ userId, agentId, url, method = 'GET', body, maxUsd, headers }) {if (!resolveSpendEnabled()) {throw Object.assign(new Error('autonomous spending is disabled on this server'), {code: 'spend_disabled',@@ -336,6 +336,7 @@ export async function payExternalX402({ userId, agentId, url, method = 'GET', bourl: safeUrl,method,...(body != null ? { data: body } : {}),+ ...(headers && typeof headers === 'object' ? { headers } : {}),});return {ok: true,diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.jsindex 6b4706484..ed8cccc08 100644--- a/api/agents/a2a-hire.js+++ b/api/agents/a2a-hire.js@@ -54,6 +54,9 @@ import {updateHire,} from '../_lib/agent-economy.js';import { createApprovalRequest, runApproved, TTL_MS } from '../_lib/approvals.js';+import { recordHireAttestation } from '../_lib/trust/hire-attestations.js';+import { getEffectiveReputation } from '../_lib/trust/reputation-store.js';+import { tierDiscountBps, signDiscountVoucher, DISCOUNT_VOUCHER_HEADER } from '../_lib/trust/hire-discount.js';// Source key this file registers its executor under (api/_lib/approvals.js EXECUTORS).export const APPROVAL_SOURCE = 'a2a_hire';@@ -65,6 +68,24 @@ function receiptSignature(receipt) {return receipt.transaction || receipt.signature || receipt.txHash || receipt.tx || null;}+// Resolve a signed reputation-discount voucher header for this hire, or+// undefined when the offer hasn't opted in or the hirer's tier earns no+// discount. Never throws: a voucher failure must fall back to full price, not+// break the hire.+async function discountHeaders(offer, hirerAgentId) {+ if (!offer.reputation_discount_enabled) return undefined;+ try {+ const rep = await getEffectiveReputation(hirerAgentId);+ const bps = tierDiscountBps(rep?.tier);+ if (bps <= 0) return undefined;+ const voucher = signDiscountVoucher({ slug: offer.slug, hirerAgentId, discountBps: bps });+ return voucher ? { [DISCOUNT_VOUCHER_HEADER]: voucher } : undefined;+ } catch (err) {+ console.error('[a2a-hire] discount voucher failed', err?.message || err);+ return undefined;+ }+}+// A short, human summary of the provider's result for the hire record + speech.function summarizeResult(result) {try {@@ -300,12 +321,16 @@ export default wrap(async (req, res) => {method: offer.method === 'POST' ? 'POST' : 'GET',body: offer.method === 'POST' ? (input ?? {}) : undefined,maxUsd: usd,+ headers: await discountHeaders(offer, hirerAgentId),});} catch (err) {// The x402 endpoint settles only after the provider's work succeeds, so a// throw here means NO money moved: release the hold and fail honestly.await releaseSpendReservation(reservationId, 'hire_payment_failed');await updateHire(hireRow.id, { status: 'failed', error: err?.message || String(err) });+ await recordHireAttestation(hireRow, { phase: 'failed', err }).catch((e) =>+ console.error('[a2a-hire] attestation failed', e?.message || e),+ );const code = err?.code || 'payment_failed';const status = code === 'spend_disabled' ? 501 : code === 'no_wallet' || code === 'no_solana_wallet' ? 409 : 502;// Verify-then-settle means no funds moved — say so on the screen, no coin.@@ -396,6 +421,13 @@ export default wrap(async (req, res) => {},});+ await recordHireAttestation(finalized || hireRow, {+ phase: 'recorded',+ paymentSignature,+ invocationSignature: invocation?.signature || null,+ resultSummary: deliveredSummary,+ }).catch((e) => console.error('[a2a-hire] attestation failed', e?.message || e));+return json(res, 200, {ok: true,hire: publicHire(finalized || hireRow, offer, { invocation, payment }),@@ -566,10 +598,14 @@ export async function executeApprovedA2aHire(row) {method: offer.method === 'POST' ? 'POST' : 'GET',body: offer.method === 'POST' ? (p.input ?? {}) : undefined,maxUsd: usd,+ headers: await discountHeaders(offer, hirer.id),});} catch (err) {await releaseSpendReservation(reservationId, 'hire_payment_failed');await updateHire(hireRow.id, { status: 'failed', error: err?.message || String(err) });+ await recordHireAttestation(hireRow, { phase: 'failed', err }).catch((e) =>+ console.error('[a2a-hire] attestation failed', e?.message || e),+ );return {status: 'error',note: `the hire did not complete after approval, no funds were moved: ${err?.message || err?.code || 'payment_failed'}`,@@ -635,6 +671,13 @@ export async function executeApprovedA2aHire(row) {},});+ await recordHireAttestation(finalized || hireRow, {+ phase: 'recorded',+ paymentSignature,+ invocationSignature: invocation?.signature || null,+ resultSummary: deliveredSummary,+ }).catch((e) => console.error('[a2a-hire] attestation failed', e?.message || e));+return {status: 'ok',signature: paymentSignature || undefined,diff --git a/api/x402/service.js b/api/x402/service.jsindex 8d50de2f8..69afff11f 100644--- a/api/x402/service.js+++ b/api/x402/service.js@@ -23,6 +23,7 @@ import {serviceResourceUrl,atomicsToUsdc,} from '../_lib/agent-paid-services.js';+import { DISCOUNT_VOUCHER_HEADER, verifyDiscountVoucher, applyDiscountBps } from '../_lib/trust/hire-discount.js';function slugFromReq(req) {const fromQuery = req.query?.slug;@@ -90,10 +91,21 @@ export default async function handler(req, res) {const network = row.network === 'solana' ? 'solana' : 'base';const payTo = network === 'solana' ? { solana: row.payout_address } : { base: row.payout_address };+ // Reputation discount: off unless this provider opted in. The voucher is+ // never a caller-supplied claim, it's a signature from the platform+ // attester key that only the already-authenticated a2a-hire flow can mint,+ // so a caller cannot self-grant a discount by sending an arbitrary header.+ let priceAtomics = row.price_atomics;+ if (row.reputation_discount_enabled) {+ const voucherHeader = req.headers?.[DISCOUNT_VOUCHER_HEADER];+ const discountBps = verifyDiscountVoucher(voucherHeader, { slug });+ if (discountBps > 0) priceAtomics = applyDiscountBps(row.price_atomics, discountBps);+ }+const paid = paidEndpoint({route: `/api/x402/service/${slug}`,method,- priceAtomics: row.price_atomics,+ priceAtomics,networks: [network],description: row.description,bazaar: bazaarFor(row, resourceUrl),@@ -147,7 +159,7 @@ export default async function handler(req, res) {}return {service: row.name,- price_usdc: atomicsToUsdc(row.price_atomics),+ price_usdc: atomicsToUsdc(priceAtomics),network,result: upstream.data,};diff --git a/src/shared/agent-financial-reputation.js b/src/shared/agent-financial-reputation.jsindex f085f139f..1e960019d 100644--- a/src/shared/agent-financial-reputation.js+++ b/src/shared/agent-financial-reputation.js@@ -54,9 +54,15 @@// as strong a trust signal as an external registry, and the score still sums to// exactly 100 so the tier thresholds and every persisted history stay comparable.//+// v4 adds hire fulfillment (signed attestations on every settled+// api/agents/a2a-hire call, api/_lib/trust/hire-attestations.js) as a SECOND,+// additive way to earn the `reliability` pillar's points, gated by a minimum+// sample so one lucky or unlucky hire can't swing it. It does not touch the+// pillar's max (12) or any other pillar, so the 100-point scale is unchanged.+//// loadReputationInputs / getAgentReputation (server) do the real I/O.-export const REPUTATION_VERSION = 3;+export const REPUTATION_VERSION = 4;// Factor definitions — label + max points. Order is the display order.export const PILLARS = [@@ -128,6 +134,10 @@ const log2 = (n) => Math.log(n) / Math.LN2;* @param {number} inputs.validationCount signed Solana validation attestations* @param {number} inputs.feedbackCount signed Solana feedback attestations* @param {boolean} inputs.hasSkillCollection on-chain skill-license collection minted+ * @param {?number} inputs.hireFulfillmentRate recency-weighted share of this agent's+ * a2a-hires (as PROVIDER) attested 'delivered', null when there isn't enough sample yet+ * @param {number} inputs.hireFulfillmentSampleSize raw count of signed hire attestations+ * @param {number} inputs.hireFulfillmentMinSample minimum sample before the rate counts (default 5)* @returns {object} { version, score, max, tier, tierLabel, accent, isNew, pillars, discounted, totals }*/export function computeReputation(inputs = {}) {@@ -185,18 +195,41 @@ export function computeReputation(inputs = {}) {// Only meaningful once there's real settlement volume. A new agent honestly// scores 0 here rather than an unearned full mark.const settled = i.confirmedPayments + i.failedPayments;- let reliabilityPts = 0;+ let paymentReliabilityPts = 0;let reliabilityDetail = 'No settled payments yet — reliability is unproven.';if (settled >= 5) {const successRate = i.confirmedPayments / settled;- reliabilityPts = successRate * 10 + clamp(i.distributionSuccess * 2, 0, 2);+ paymentReliabilityPts = successRate * 10 + clamp(i.distributionSuccess * 2, 0, 2);reliabilityDetail = `${(successRate * 100).toFixed(0)}% of ${settled} settlements succeeded${i.distributionSuccess > 0 ? `, ${(i.distributionSuccess * 100).toFixed(0)}% distribution success` : ''}.`;}++ // Hire fulfillment: a SECOND, additive way into this same pillar, earned+ // from signed attestations on this agent's own a2a-hires as PROVIDER+ // (api/_lib/trust/hire-attestations.js), recency-weighted and gated by a+ // minimum sample. pushPillar clamps the combined total to max 12 either+ // way, so an agent with strong generic payment reliability already near+ // the cap gets no extra credit, this fills in signal for agents whose+ // real settlement history is mostly a2a-hire deliveries.+ const hireSampleSize = i.hireFulfillmentSampleSize;+ const hireMinSample = i.hireFulfillmentMinSample;+ const hireMeetsMinimum = i.hireFulfillmentRate != null && hireSampleSize >= hireMinSample;+ const fulfillmentPts = hireMeetsMinimum ? clamp(i.hireFulfillmentRate * 3, 0, 3) : 0;+ if (hireMeetsMinimum) {+ reliabilityDetail += ` ${(i.hireFulfillmentRate * 100).toFixed(0)}% hire fulfillment over ${hireSampleSize} hire${hireSampleSize === 1 ? '' : 's'}.`;+ } else if (hireSampleSize > 0) {+ reliabilityDetail += ` ${hireSampleSize} hire${hireSampleSize === 1 ? '' : 's'} attested so far (needs ${hireMinSample} before fulfillment rate counts).`;+ }+ const reliabilityPts = paymentReliabilityPts + fulfillmentPts;pushPillar(pillars, 'reliability', reliabilityPts, {detail: reliabilityDetail,- facts: { confirmed_payments: i.confirmedPayments, failed_payments: i.failedPayments },+ facts: {+ confirmed_payments: i.confirmedPayments,+ failed_payments: i.failedPayments,+ hire_fulfillment_rate: hireMeetsMinimum ? round1(i.hireFulfillmentRate * 100) : null,+ hire_fulfillment_sample_size: hireSampleSize,+ },});// ── Generosity & reciprocity (max 8) ───────────────────────────────────────@@ -481,6 +514,11 @@ function normalizeInputs(raw) {validationCount: Math.max(0, num(raw.validationCount)),feedbackCount: Math.max(0, num(raw.feedbackCount)),hasSkillCollection: Boolean(raw.hasSkillCollection),+ hireFulfillmentRate: Number.isFinite(Number(raw.hireFulfillmentRate))+ ? clamp(Number(raw.hireFulfillmentRate), 0, 1)+ : null,+ hireFulfillmentSampleSize: Math.max(0, num(raw.hireFulfillmentSampleSize)),+ hireFulfillmentMinSample: raw.hireFulfillmentMinSample != null ? Math.max(1, num(raw.hireFulfillmentMinSample)) : 5,};}diff --git a/tests/a2a-hire-phases.test.js b/tests/a2a-hire-phases.test.jsindex a1bbc3e5e..1750bc040 100644--- a/tests/a2a-hire-phases.test.js+++ b/tests/a2a-hire-phases.test.js@@ -14,6 +14,10 @@ import {fmtUsd,hireCapMath,hirePhaseFrame,+ isAmbiguousPaymentError,+ classifyHireOutcome,+ buildHireAttestationPayload,+ sortedStringify,} from '../api/_lib/a2a-hire-phases.js';describe('hireCapMath', () => {@@ -185,3 +189,75 @@ describe('hirePhaseFrame', () => {expect(f.meta.cap).toEqual(cap);});});++describe('fulfillment attestation (pure core)', () => {+ it('recognises axios timeout/abort shapes as ambiguous', () => {+ expect(isAmbiguousPaymentError({ code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })).toBe(true);+ expect(isAmbiguousPaymentError({ code: 'ETIMEDOUT' })).toBe(true);+ expect(isAmbiguousPaymentError({ name: 'CanceledError' })).toBe(true);+ expect(isAmbiguousPaymentError({ message: 'request timed out' })).toBe(true);+ });++ it('does not call a clean, non-timeout failure ambiguous', () => {+ expect(isAmbiguousPaymentError({ code: 'no_wallet', message: 'no Solana wallet provisioned' })).toBe(false);+ expect(isAmbiguousPaymentError({ code: 'spend_disabled' })).toBe(false);+ expect(isAmbiguousPaymentError(null)).toBe(false);+ });++ it('classifies a completed hire as delivered, never from an ambiguous error', () => {+ expect(classifyHireOutcome('recorded')).toBe('delivered');+ expect(classifyHireOutcome('recorded', { code: 'ECONNABORTED' })).toBe('delivered');+ });++ it('classifies a clean payment failure as failed (verify-then-settle: no funds moved)', () => {+ expect(classifyHireOutcome('failed', { code: 'no_wallet', message: 'no wallet' })).toBe('failed');+ expect(classifyHireOutcome('failed', null)).toBe('failed');+ });++ it('never infers delivered from an ambiguous failure: records disputed instead', () => {+ expect(classifyHireOutcome('failed', { code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })).toBe(+ 'disputed',+ );+ });++ it('builds the canonical attestation payload shape', () => {+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: 'SIG1',+ outcome: 'delivered',+ evidenceHash: 'deadbeef',+ signedBy: 'PUBKEY1',+ });+ expect(payload).toEqual({+ hire_id: 'h1',+ payment_signature: 'SIG1',+ outcome: 'delivered',+ evidence_hash: 'deadbeef',+ signed_by: 'PUBKEY1',+ });+ });++ it('defaults payment_signature to null rather than undefined', () => {+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: null,+ outcome: 'failed',+ evidenceHash: 'deadbeef',+ signedBy: 'PUBKEY1',+ });+ expect(payload.payment_signature).toBe(null);+ });++ it('sortedStringify is independent of key insertion order', () => {+ const a = sortedStringify({ b: 2, a: 1, c: { y: 2, x: 1 } });+ const b = sortedStringify({ a: 1, c: { x: 1, y: 2 }, b: 2 });+ expect(a).toBe(b);+ });++ it('sortedStringify round-trips primitives, arrays, and null', () => {+ expect(sortedStringify(null)).toBe('null');+ expect(sortedStringify(42)).toBe('42');+ expect(sortedStringify('x')).toBe('"x"');+ expect(sortedStringify([3, 1, { b: 1, a: 2 }])).toBe('[3,1,{"a":2,"b":1}]');+ });+});diff --git a/tests/hire-attestations.test.js b/tests/hire-attestations.test.jsnew file mode 100644index 000000000..4057a606c--- /dev/null+++ b/tests/hire-attestations.test.js@@ -0,0 +1,133 @@+// Signed hire-fulfillment attestations (work order 523): every settled+// a2a-hire writes a signed {hire_id, outcome, evidence_hash, signed_by} row,+// signed off-chain with the same platform attestation key+// api/_lib/attest-event.js uses for on-chain provenance. These tests pin:+// - a correctly-signed attestation verifies against the configured key+// - any tamper (payload, signature, or signer mismatch) fails closed+// - the recency-weighted fulfillment rate respects the minimum sample gate++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { createRequire } from 'node:module';++const require = createRequire(import.meta.url);+const nacl = require('tweetnacl');++import { verifyHireAttestation, weightedFulfillmentRate } from '../api/_lib/trust/hire-attestations.js';+import { buildHireAttestationPayload, sortedStringify } from '../api/_lib/a2a-hire-phases.js';+import { loadAttesterKeypair } from '../api/_lib/attest-event.js';++const kp = nacl.sign.keyPair();+const TEST_SEED = JSON.stringify(Array.from(kp.secretKey));++beforeEach(() => {+ process.env.ATTEST_AGENT_SECRET_KEY = TEST_SEED;+});++afterEach(() => {+ delete process.env.ATTEST_AGENT_SECRET_KEY;+});++function signWithPlatformKey(payload) {+ const keypair = loadAttesterKeypair();+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ return Buffer.from(nacl.sign.detached(message, keypair.secretKey)).toString('base64');+}++describe('verifyHireAttestation', () => {+ it('verifies a signature produced with the configured platform attester key', () => {+ const keypair = loadAttesterKeypair();+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: 'PAYSIG',+ outcome: 'delivered',+ evidenceHash: 'abc123',+ signedBy: keypair.publicKey.toBase58(),+ });+ const signature = signWithPlatformKey(payload);+ expect(verifyHireAttestation({ payload, signature, signedBy: payload.signed_by })).toBe(true);+ });++ it('rejects a payload tampered after signing', () => {+ const keypair = loadAttesterKeypair();+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: 'PAYSIG',+ outcome: 'delivered',+ evidenceHash: 'abc123',+ signedBy: keypair.publicKey.toBase58(),+ });+ const signature = signWithPlatformKey(payload);+ const tampered = { ...payload, outcome: 'disputed' };+ expect(verifyHireAttestation({ payload: tampered, signature, signedBy: payload.signed_by })).toBe(false);+ });++ it('rejects a signature minted by a different key', () => {+ const keypair = loadAttesterKeypair();+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: null,+ outcome: 'failed',+ evidenceHash: 'xyz',+ signedBy: keypair.publicKey.toBase58(),+ });+ const impostor = nacl.sign.keyPair();+ const message = Buffer.from(sortedStringify(payload), 'utf8');+ const forged = Buffer.from(nacl.sign.detached(message, impostor.secretKey)).toString('base64');+ expect(verifyHireAttestation({ payload, signature: forged, signedBy: payload.signed_by })).toBe(false);+ });++ it('rejects a signed_by claim that does not match the current platform key', () => {+ const payload = buildHireAttestationPayload({+ hireId: 'h1',+ paymentSignature: null,+ outcome: 'delivered',+ evidenceHash: 'abc123',+ signedBy: 'SomeOtherPubkeyNotThePlatformAttester1111',+ });+ const signature = signWithPlatformKey({ ...payload, signed_by: loadAttesterKeypair().publicKey.toBase58() });+ expect(verifyHireAttestation({ payload, signature, signedBy: payload.signed_by })).toBe(false);+ });++ it('fails closed on malformed input instead of throwing', () => {+ expect(verifyHireAttestation({ payload: null, signature: 'not-base64', signedBy: 'x' })).toBe(false);+ expect(verifyHireAttestation({ payload: {}, signature: undefined, signedBy: undefined })).toBe(false);+ });+});++describe('weightedFulfillmentRate', () => {+ const DAY = 86_400_000;+ const now = Date.now();++ it('returns null rate with no records', () => {+ expect(weightedFulfillmentRate([], { now })).toEqual({ rate: null, sampleSize: 0, weightedSampleSize: 0 });+ });++ it('scores an all-delivered recent history at 100%', () => {+ const records = Array.from({ length: 5 }, () => ({ outcome: 'delivered', created_at: new Date(now) }));+ const r = weightedFulfillmentRate(records, { now });+ expect(r.rate).toBeCloseTo(1, 9);+ expect(r.sampleSize).toBe(5);+ });++ it('never counts disputed as delivered', () => {+ const records = [+ { outcome: 'delivered', created_at: new Date(now) },+ { outcome: 'disputed', created_at: new Date(now) },+ ];+ const r = weightedFulfillmentRate(records, { now });+ expect(r.rate).toBeCloseTo(0.5, 9);+ });++ it('weights recent attestations more than old ones (recency decay)', () => {+ const recentGood = [+ { outcome: 'delivered', created_at: new Date(now) },+ { outcome: 'delivered', created_at: new Date(now) },+ { outcome: 'failed', created_at: new Date(now - 300 * DAY) },+ ];+ const r = weightedFulfillmentRate(recentGood, { halfLifeDays: 30, now });+ // the old failure is decayed to near-zero weight at a 30-day half-life+ // after 300 days, so the rate should sit close to 1, not 2/3.+ expect(r.rate).toBeGreaterThan(0.9);+ expect(r.sampleSize).toBe(3);+ });+});diff --git a/tests/wallet-reputation.test.js b/tests/wallet-reputation.test.jsindex b542cf871..40d2e8ed6 100644--- a/tests/wallet-reputation.test.js+++ b/tests/wallet-reputation.test.js@@ -88,7 +88,7 @@ describe('computeReputation — pillar maxima', () => {});it('exposes the current reputation version', () => {- expect(REPUTATION_VERSION).toBe(3);+ expect(REPUTATION_VERSION).toBe(4);expect(PILLARS.some((p) => p.key === 'conviction')).toBe(true);});});@@ -163,6 +163,65 @@ describe('costly signals dominate', () => {});});+describe('hire fulfillment rate', () => {+ it('below the minimum sample, fulfillment contributes nothing even with a perfect rate', () => {+ const r = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ hireFulfillmentRate: 1,+ hireFulfillmentSampleSize: 2,+ hireFulfillmentMinSample: 5,+ });+ const rel = r.pillars.find((p) => p.key === 'reliability');+ expect(rel.points).toBe(0);+ expect(rel.facts.hire_fulfillment_rate).toBeNull();+ expect(rel.facts.hire_fulfillment_sample_size).toBe(2);+ });++ it('at or above the minimum sample, a strong fulfillment rate earns reliability points', () => {+ const r = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ hireFulfillmentRate: 0.9,+ hireFulfillmentSampleSize: 8,+ hireFulfillmentMinSample: 5,+ });+ const rel = r.pillars.find((p) => p.key === 'reliability');+ expect(rel.points).toBeGreaterThan(0);+ expect(rel.facts.hire_fulfillment_rate).toBeCloseTo(90, 0);+ expect(rel.facts.hire_fulfillment_sample_size).toBe(8);+ expect(rel.detail).toMatch(/90% hire fulfillment over 8 hires/);+ });++ it('a poor fulfillment rate earns fewer reliability points than a strong one', () => {+ const strong = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ hireFulfillmentRate: 1,+ hireFulfillmentSampleSize: 10,+ });+ const weak = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ hireFulfillmentRate: 0.1,+ hireFulfillmentSampleSize: 10,+ });+ const strongRel = strong.pillars.find((p) => p.key === 'reliability');+ const weakRel = weak.pillars.find((p) => p.key === 'reliability');+ expect(strongRel.points).toBeGreaterThan(weakRel.points);+ });++ it('never pushes the reliability pillar above its max even with strong payment + hire signal', () => {+ const r = computeReputation({+ ...ESTABLISHED,+ hireFulfillmentRate: 1,+ hireFulfillmentSampleSize: 50,+ });+ const rel = r.pillars.find((p) => p.key === 'reliability');+ expect(rel.points).toBeLessThanOrEqual(rel.max);+ });+});+describe('generosity factor', () => {it('rewards tips given to other agents (wash-excluded upstream)', () => {const generous = computeReputation({ ...NEW_AGENT, ageDays: 100, tipsGivenUsd: 800, tipsGivenCount: 12 });