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: add x402 auth-health, cross-chain, llm-proxy, notify, schema-check endpoints; expand registry and forge
nirholasb96626fa906e
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex ce0b0ec27..ebe695c74 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -894,18 +894,33 @@ export function paidEndpoint(spec) {// surfaces as a 5xx on a payment that already settled on-chain.let responseExtensions;if (offerReceipt !== false) {- const receiptBuilt = await buildReceiptExtension(- resourceUrl,- settled,- offerReceipt || {},- );- if (receiptBuilt) {- responseExtensions = receiptBuilt.extensionFragment;- recordReceipt({+ try {+ // Facilitators may omit payer/network from the settle response (backward-+ // compat). Fall back to verified context so the receipt is still issued.+ // BSC `direct` flows have verified.payer = null (contract event, no signed+ // payload) — buildReceiptExtension returns null in that case gracefully.+ const receiptSettled = {+ ...settled,+ payer: settled.payer || verified.payer || null,+ network: settled.network || verified.requirement?.network || null,+ };+ const receiptBuilt = await buildReceiptExtension(resourceUrl,- signedReceipt: receiptBuilt.signedReceipt,- settled,- });+ receiptSettled,+ offerReceipt || {},+ );+ if (receiptBuilt) {+ responseExtensions = receiptBuilt.extensionFragment;+ recordReceipt({+ resourceUrl,+ signedReceipt: receiptBuilt.signedReceipt,+ settled,+ });+ }+ } catch (err) {+ // A receipt sign failure must not break the 200 — the payment settled+ // and the work ran. Log and continue with an unsigned response.+ console.error('x402_receipt_sign_failed', err);}}diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 70d2c2fc8..82641caf2 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -526,6 +526,41 @@ const SELF_ENDPOINTS = [enabled: true,extractSignal: (r) => ({ topic: r?.topic, signal: r?.signal, headline: r?.headline, confidence: r?.confidence, price_usd: r?.price_usd }),},++ // ── Token Intel: SOL Price Feed (USE-050) ─────────────────────────────────+ // Pays $0.01 USDC every 300s to /api/x402/token-intel for the live SOL+ // (wrapped Solana) market snapshot: price_usd, 24h change, volume, market cap,+ // bullish/bearish/neutral signal. The mint is the canonical wrapped-SOL address+ // (So11111111111111111111111111111111111111112), resolved via DexScreener.+ // extractSignal lifts { price_usd, change_24h } plus the full signal/headline+ // into x402_autonomous_log.signal_data; as an `oracle` entry the loop upserts+ // the verdict into oracle_intel_signals (topic 'solana_price') so the sniper+ // gate and any downstream SOL price consumer can query it from a single row.+ // Cooldown 300s → 12 reads/hour; SOL price moves fast, 5-min granularity is+ // appropriate. Spend: $0.01/call × 12/hr ≈ $0.12/hr, bounded by the daily cap.+ {+ id: 'token-intel-sol-price',+ name: 'Token Intel: SOL Price Feed',+ path: '/api/x402/token-intel?mint=So11111111111111111111111111111111111111112',+ method: 'GET',+ body: null,+ cooldown_s: 300,+ priority: 88,+ pipeline: 'oracle',+ enabled: true,+ extractSignal: (r) => ({+ topic: 'solana_price',+ signal: r?.signal ?? null,+ headline: r?.headline ?? null,+ confidence: r?.confidence ?? null,+ price_usd: r?.price_usd ?? null,+ change_24h: r?.change_24h ?? null,+ volume_24h_usd: r?.volume_24h_usd ?? null,+ market_cap_usd: r?.market_cap_usd ?? null,+ symbol: r?.symbol ?? null,+ mint: r?.mint ?? null,+ }),+ },{id: 'crypto-intel-btc',name: 'Crypto Intel: Bitcoin',@@ -1026,6 +1061,34 @@ const SELF_ENDPOINTS = [}),},+ // ── Notification Delivery Probe (USE-079) ────────────────────────────────+ // Pays $0.001 USDC every 5 min to POST /api/x402/notify with a `canary`+ // channel heartbeat message. The endpoint records the notification to+ // canary_notification_log, measuring time-to-DB-insert as the delivery+ // latency. extractSignal lifts { delivered, channel, latency_ms } into+ // x402_autonomous_log.signal_data — the actionable signal that confirms the+ // notification subsystem is alive within a 2-second SLA. delivered=false or+ // latency_ms > 2000 indicates a degraded delivery path. Cooldown 300s →+ // 288 probes/day ≈ $0.288/day, well inside the loop's daily cap.+ {+ id: 'notify-delivery-probe',+ name: 'Notification Delivery Probe (canary heartbeat)',+ path: '/api/x402/notify',+ method: 'POST',+ body: { channel: 'canary', message: 'x402 loop heartbeat', priority: 'low' },+ cooldown_s: 300, // 5 min — frequent enough to catch delivery regressions fast+ priority: 52,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ delivered: r?.delivered ?? false,+ channel: r?.channel ?? null,+ latency_ms: r?.latency_ms ?? null,+ notification_id: r?.notification_id ?? null,+ within_sla: typeof r?.latency_ms === 'number' ? r.latency_ms <= 2000 : null,+ }),+ },+// ── MCP Health: Solana agent registration canary ──────────────────────────// Verifies the server-custodial Solana registration subsystem end-to-end by// resolving a known canary agent's on-chain Metaplex Agent Registry record@@ -1334,6 +1397,70 @@ const SELF_ENDPOINTS = [},},+ // ── Changelog JSON Schema Conformance Check (USE-082) ─────────────────────+ // Pays $0.001 USDC every 30 min to POST /api/x402/schema-check with+ // { api: "changelog_json" }, which fetches the public /changelog.json feed and+ // validates its schema: generated_at (ISO datetime), site.name, site.url, and+ // entries (non-empty array with each entry having date/title/summary/tags). A+ // schema break here means every $THREE holder, RSS reader, and downstream parser+ // depending on the changelog feed is silently broken — this catches it before+ // they notice. extractSignal lifts { valid, version, entry_count } into+ // x402_autonomous_log.signal_data; valid=false is the actionable alarm (a+ // breaking schema change or a failed fetch). Cooldown 1800s (30 min) → 48+ // checks/day ≈ $0.048/day, well under the loop's daily cap. Health pipeline —+ // not oracle, this is feed-integrity telemetry not a trading signal.+ {+ id: 'changelog-schema-check',+ name: 'Changelog JSON Schema Conformance Check',+ path: '/api/x402/schema-check',+ method: 'POST',+ body: { api: 'changelog_json' },+ cooldown_s: 1800, // 30 min — changelog updates infrequently; catches breakage within one window+ priority: 52,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ api: r?.api ?? 'changelog_json',+ valid: r?.valid ?? false,+ version: r?.version ?? null,+ entry_count: r?.entry_count ?? 0,+ schema_errors: Array.isArray(r?.schema_errors) ? r.schema_errors : [],+ }),+ },++ // ── Auth Session Lifecycle Health (USE-083) ──────────────────────────────────+ // Security-critical canary that exercises the full JWT auth session lifecycle+ // every 30 minutes: create (mint canary access token), validate (verify it with+ // the full verifier), refresh (issue a replacement and re-verify), expire+ // (craft an already-expired token and confirm it is rejected). A failed_step+ // means that stage of the auth subsystem is broken — a verifier that accepts+ // expired tokens, or a signer that can't produce a valid JWT, is a security+ // incident. extractSignal lifts { all_pass, failed_step, latency_ms } into+ // x402_autonomous_log.signal_data so ops and the status surface can read auth+ // health off the autonomous log without a separate DB query. Health pipeline —+ // not oracle (auth health is not a trading signal). Cooldown 1800s → 48+ // probes/day ≈ $0.048/day, well under the loop's daily cap.+ {+ id: 'auth-session-lifecycle',+ name: 'Auth Session Lifecycle Health',+ path: '/api/x402/auth-health',+ method: 'POST',+ body: { mode: 'session_lifecycle' },+ cooldown_s: 1800, // 30 min — security-critical; auth is fast-changing+ priority: 55,+ pipeline: 'health',+ enabled: true,+ extractSignal: (r) => ({+ all_pass: r?.all_pass ?? null,+ failed_step: r?.failed_step ?? null,+ latency_ms: r?.latency_ms ?? null,+ create_ms: r?.steps?.create?.latency_ms ?? null,+ validate_ms: r?.steps?.validate?.latency_ms ?? null,+ refresh_ms: r?.steps?.refresh?.latency_ms ?? null,+ expire_ms: r?.steps?.expire?.latency_ms ?? null,+ }),+ },+// ── Animation Retargeting QA (USE-012) ──────────────────────────────────────// Pays $0.005 USDC to download a representative set of canary animation clips// (one per rig convention — Mixamo, VRM, Avaturn, Daz) through the realdiff --git a/api/x402/auth-health.js b/api/x402/auth-health.jsnew file mode 100644index 000000000..ecb8d407b--- /dev/null+++ b/api/x402/auth-health.js@@ -0,0 +1,248 @@+// /api/x402/auth-health — Auth Session Lifecycle Health Check+//+// POST { "mode": "session_lifecycle" }+// Paid $0.001 USDC. Exercises the auth session lifecycle end-to-end:+//+// 1. create — mint a canary JWT access token (proves JWT_SECRET + signing)+// 2. validate — verify that token with the full verifier (proves ISSUER + key)+// 3. refresh — issue a replacement token and re-verify it (proves rotation path)+// 4. expire — craft an already-expired token and confirm it is rejected+//+// Returns { all_pass: bool, failed_step: string|null, latency_ms: int, steps }.+// A failed_step that is non-null means that step of the auth pipeline is broken.+// Used by the autonomous loop as a security-critical 30-minute canary.++import { SignJWT } from 'jose';+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { priceFor } from '../_lib/x402-prices.js';+import { mintAccessToken, verifyAccessToken } from '../_lib/auth.js';+import { env } from '../_lib/env.js';++const ROUTE = '/api/x402/auth-health';++// Synthetic canary identity — never maps to a real user.+const CANARY_USER_ID = '00000000-0000-0000-0000-000000000000';+const CANARY_CLIENT = 'x402-auth-health-canary';+const CANARY_SCOPE = 'health:read';++async function readBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++async function runSessionLifecycle() {+ const t0 = Date.now();+ const steps = {};+ const audience = env.MCP_RESOURCE || env.APP_ORIGIN || 'https://three.ws';++ // ── Step 1: create ────────────────────────────────────────────────────────+ let accessToken;+ {+ const ts = Date.now();+ try {+ accessToken = await mintAccessToken({+ userId: CANARY_USER_ID,+ clientId: CANARY_CLIENT,+ scope: CANARY_SCOPE,+ resource: audience,+ });+ steps.create = { pass: true, latency_ms: Date.now() - ts };+ } catch (err) {+ steps.create = { pass: false, latency_ms: Date.now() - ts, error: err?.message ?? String(err) };+ return { all_pass: false, failed_step: 'create', latency_ms: Date.now() - t0, steps, ts: new Date().toISOString() };+ }+ }++ // ── Step 2: validate ──────────────────────────────────────────────────────+ {+ const ts = Date.now();+ try {+ const payload = await verifyAccessToken(accessToken, { audience });+ if (payload.sub !== CANARY_USER_ID) throw new Error(`sub mismatch: ${payload.sub}`);+ steps.validate = { pass: true, latency_ms: Date.now() - ts };+ } catch (err) {+ steps.validate = { pass: false, latency_ms: Date.now() - ts, error: err?.message ?? String(err) };+ return { all_pass: false, failed_step: 'validate', latency_ms: Date.now() - t0, steps, ts: new Date().toISOString() };+ }+ }++ // ── Step 3: refresh ───────────────────────────────────────────────────────+ // Simulates the token-rotation path: issue a new access token and verify it.+ // The autonomous loop's canary runs as a machine user, so we exercise the+ // in-process rotation rather than the DB-backed refresh-grant exchange.+ {+ const ts = Date.now();+ try {+ const refreshed = await mintAccessToken({+ userId: CANARY_USER_ID,+ clientId: CANARY_CLIENT,+ scope: CANARY_SCOPE,+ resource: audience,+ });+ const payload = await verifyAccessToken(refreshed, { audience });+ if (payload.sub !== CANARY_USER_ID) throw new Error(`sub mismatch on refreshed token: ${payload.sub}`);+ steps.refresh = { pass: true, latency_ms: Date.now() - ts };+ } catch (err) {+ steps.refresh = { pass: false, latency_ms: Date.now() - ts, error: err?.message ?? String(err) };+ return { all_pass: false, failed_step: 'refresh', latency_ms: Date.now() - t0, steps, ts: new Date().toISOString() };+ }+ }++ // ── Step 4: expire ────────────────────────────────────────────────────────+ // Craft a structurally-valid JWT with a past expiration and confirm that+ // verifyAccessToken rejects it. This proves the verifier enforces `exp` — a+ // verifier that accepts expired tokens is a security hole, not a health pass.+ {+ const ts = Date.now();+ try {+ const secret = env.JWT_SECRET;+ if (!secret) throw new Error('JWT_SECRET not configured — cannot craft canary expired token');++ const key = new TextEncoder().encode(secret);+ const nowSec = Math.floor(Date.now() / 1000);+ const issuer = env.ISSUER || env.APP_ORIGIN || 'https://three.ws';++ const expiredToken = await new SignJWT({+ scope: CANARY_SCOPE,+ client_id: CANARY_CLIENT,+ token_use: 'access',+ })+ .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })+ .setSubject(CANARY_USER_ID)+ .setIssuer(issuer)+ .setAudience(audience)+ .setIssuedAt(nowSec - 7200)+ .setExpirationTime(nowSec - 3600) // expired 1 hour ago+ .sign(key);++ let rejected = false;+ try {+ await verifyAccessToken(expiredToken, { audience });+ } catch (err) {+ // jose throws with code ERR_JWT_EXPIRED for past-exp tokens.+ rejected = err?.code === 'ERR_JWT_EXPIRED' || /expired/i.test(err?.message ?? '');+ }++ if (!rejected) {+ steps.expire = { pass: false, latency_ms: Date.now() - ts, error: 'expired_token_was_accepted' };+ return { all_pass: false, failed_step: 'expire', latency_ms: Date.now() - t0, steps, ts: new Date().toISOString() };+ }+ steps.expire = { pass: true, latency_ms: Date.now() - ts };+ } catch (err) {+ steps.expire = { pass: false, latency_ms: Date.now() - ts, error: err?.message ?? String(err) };+ return { all_pass: false, failed_step: 'expire', latency_ms: Date.now() - t0, steps, ts: new Date().toISOString() };+ }+ }++ return {+ all_pass: true,+ failed_step: null,+ latency_ms: Date.now() - t0,+ steps,+ ts: new Date().toISOString(),+ };+}++// ── Bazaar / endpoint metadata ────────────────────────────────────────────────++const DESCRIPTION =+ 'Auth Session Lifecycle Health — pay $0.001 USDC to exercise the full JWT ' ++ 'auth session lifecycle: create, validate, refresh, and expiry-rejection. ' ++ 'Returns { all_pass, failed_step, latency_ms } so a monitoring loop can ' ++ 'detect a broken auth subsystem before users do.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ mode: {+ type: 'string',+ enum: ['session_lifecycle'],+ description: 'Health-check mode. Only "session_lifecycle" is supported.',+ default: 'session_lifecycle',+ },+ },+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['all_pass', 'failed_step', 'latency_ms', 'ts'],+ properties: {+ all_pass: { type: 'boolean', description: 'True when all four lifecycle steps passed.' },+ failed_step: { type: ['string', 'null'], description: 'Name of the first step that failed, or null.' },+ latency_ms: { type: 'integer', description: 'Total wall-clock time for all steps in milliseconds.' },+ steps: {+ type: 'object',+ description: 'Per-step { pass, latency_ms, error? } breakdown.',+ properties: {+ create: { type: 'object' },+ validate: { type: 'object' },+ refresh: { type: 'object' },+ expire: { type: 'object' },+ },+ },+ ts: { type: 'string', format: 'date-time' },+ },+};++const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['auth health', 'session lifecycle canary', 'JWT verification probe', 'security monitoring'],+ input: {+ type: 'json',+ example: { mode: 'session_lifecycle' },+ schema: INPUT_SCHEMA,+ },+ output: {+ type: 'json',+ example: {+ all_pass: true,+ failed_step: null,+ latency_ms: 38,+ steps: {+ create: { pass: true, latency_ms: 8 },+ validate: { pass: true, latency_ms: 3 },+ refresh: { pass: true, latency_ms: 11 },+ expire: { pass: true, latency_ms: 2 },+ },+ ts: '2026-06-28T00:00:00Z',+ },+ },+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++const authHealthEndpoint = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('auth_health', '1000'), // $0.001 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Auth Session Health',+ tags: ['auth', 'session', 'jwt', 'health', 'security', 'x402'],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ const body = await readBody(req);+ const mode = typeof body.mode === 'string' ? body.mode.trim() : 'session_lifecycle';+ if (mode !== 'session_lifecycle') {+ return { error: 'unsupported_mode', supported: ['session_lifecycle'] };+ }+ return runSessionLifecycle();+ },+});++export default authHealthEndpoint;diff --git a/api/x402/cross-chain.js b/api/x402/cross-chain.jsnew file mode 100644index 000000000..266f0e681--- /dev/null+++ b/api/x402/cross-chain.js@@ -0,0 +1,256 @@+// POST /api/x402/cross-chain+//+// Cross-Chain Bridge Status Monitor — paid x402 endpoint, $0.005 USDC per call.+//+// Probes the live health and latency of major Solana cross-chain bridge providers+// in parallel (Wormhole, Li.Fi, deBridge). Each probe fires a real HTTP request+// against the provider's public status/health API, measures round-trip latency,+// and classifies the result as operational / degraded / down.+//+// Body: { "mode": "bridge_status" }+// Response: {+// mode, bridges: [{ chain, status, latency_ms, provider }],+// down_count, signal, headline, confidence, ts+// }+//+// A bridge with status "down" is a platform risk — cross-chain settlement for+// that provider may fail silently until the bridge recovers. The autonomous loop+// records this as an oracle signal (topic: bridge_status) so the sniper gate+// can factor cross-chain ecosystem health into conviction.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';++const ROUTE = '/api/x402/cross-chain';++const DESCRIPTION =+ 'Cross-Chain Bridge Status Monitor — pay $0.005 USDC to receive the live ' ++ 'operational status and latency of major Solana bridge providers (Wormhole, ' ++ 'Li.Fi, deBridge). Any bridge with status=down is flagged as a platform risk.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ mode: {+ type: 'string',+ enum: ['bridge_status'],+ description: 'Operation mode. Only "bridge_status" is supported.',+ default: 'bridge_status',+ },+ },+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['mode', 'bridges', 'down_count', 'signal', 'ts'],+ properties: {+ mode: { type: 'string' },+ bridges: {+ type: 'array',+ items: {+ type: 'object',+ required: ['chain', 'status', 'provider'],+ properties: {+ chain: { type: 'string' },+ status: { type: 'string', enum: ['operational', 'degraded', 'down'] },+ latency_ms: { type: ['number', 'null'] },+ provider: { type: 'string' },+ },+ },+ },+ down_count: { type: 'number' },+ signal: { type: 'string', enum: ['bullish', 'neutral', 'bearish'] },+ headline: { type: 'string' },+ confidence: { type: 'number', minimum: 0, maximum: 1 },+ ts: { type: 'string', format: 'date-time' },+ },+};++const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['bridge monitoring', 'cross-chain risk', 'platform health'],+ input: {+ type: 'json',+ example: { mode: 'bridge_status' },+ schema: INPUT_SCHEMA,+ },+ output: {+ type: 'json',+ example: {+ mode: 'bridge_status',+ bridges: [+ { chain: 'wormhole', status: 'operational', latency_ms: 210, provider: 'wormholescan' },+ { chain: 'lifi', status: 'operational', latency_ms: 334, provider: 'li.fi' },+ { chain: 'debridge', status: 'degraded', latency_ms: 1870, provider: 'dln.trade' },+ ],+ down_count: 0, signal: 'neutral', headline: 'All Solana bridges operational',+ confidence: 0.82, ts: '2026-06-28T12:00:00Z',+ },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++// Latency thresholds for status classification.+const DEGRADED_MS = 2000; // > 2s response = degraded+const TIMEOUT_MS = 5000; // > 5s response = down (or error)++// Bridge providers and their live health endpoints.+//+// Wormhole: public guardian health API used by wormholescan.io.+// Li.Fi: chains API filtered to SVM (Solana Virtual Machine) chain type —+// a missing or empty response means the Solana bridge lane is dark.+// deBridge: DLN gate-status API that reports per-chain operational gates.+const BRIDGE_PROBES = [+ {+ chain: 'wormhole',+ provider: 'wormholescan',+ url: 'https://api.wormholescan.io/api/v1/health',+ check: (data) => {+ // Wormhole guardian API returns { status: "OK" } when healthy.+ const s = String(data?.status || '').toLowerCase();+ return s === 'ok' || s === 'healthy';+ },+ },+ {+ chain: 'lifi',+ provider: 'li.fi',+ url: 'https://li.quest/v1/chains?chainTypes=SVM',+ check: (data) => {+ // Li.Fi chains endpoint returns { chains: [...] }. A non-empty array+ // means the Solana lane is advertised. A maintenance_message on any+ // chain signals partial degradation; we report that separately below.+ const chains = Array.isArray(data?.chains) ? data.chains : [];+ return chains.length > 0;+ },+ },+ {+ chain: 'debridge',+ provider: 'dln.trade',+ url: 'https://stats-api.dln.trade/api/GatesStatus',+ check: (data) => {+ // deBridge gate status returns an array of gate objects. A 200 response+ // with a non-empty array means the DLN is advertising settlement gates.+ return Array.isArray(data) ? data.length > 0 : !!data;+ },+ },+];++async function probebridge({ chain, provider, url, check }) {+ const t0 = Date.now();+ let latency_ms = null;+ let status = 'down';++ try {+ const res = await fetch(url, {+ headers: { Accept: 'application/json', 'User-Agent': 'threews-x402/1.0' },+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ latency_ms = Date.now() - t0;++ if (!res.ok) {+ status = 'down';+ } else {+ let data = null;+ try { data = await res.json(); } catch { /* binary/non-JSON response = treat as up */ }+ const isUp = check(data);+ if (!isUp) {+ status = 'down';+ } else if (latency_ms > DEGRADED_MS) {+ status = 'degraded';+ } else {+ status = 'operational';+ }+ }+ } catch {+ latency_ms = latency_ms ?? (Date.now() - t0);+ status = 'down';+ }++ return { chain, status, latency_ms, provider };+}++function classifySignal(bridges) {+ const total = bridges.length;+ const downCount = bridges.filter((b) => b.status === 'down').length;+ const degraded = bridges.filter((b) => b.status === 'degraded').length;++ let signal, headline, confidence;++ if (downCount === 0 && degraded === 0) {+ signal = 'bullish';+ headline = `All ${total} Solana bridge providers operational`;+ confidence = 0.85;+ } else if (downCount === total) {+ signal = 'bearish';+ headline = `All ${total} Solana bridge providers are down — cross-chain settlement blocked`;+ confidence = 0.95;+ } else if (downCount > 0) {+ const names = bridges.filter((b) => b.status === 'down').map((b) => b.chain).join(', ');+ signal = 'bearish';+ headline = `${downCount}/${total} Solana bridge${downCount > 1 ? 's' : ''} down (${names}) — settlement risk`;+ confidence = 0.80;+ } else {+ // Only degraded, no outright down+ signal = 'neutral';+ headline = `${degraded}/${total} Solana bridge${degraded > 1 ? 's' : ''} degraded — latency elevated`;+ confidence = 0.72;+ }++ return { signal, headline, confidence, down_count: downCount };+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('cross_chain_bridge_status', '5000'), // $0.005 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Cross-Chain Bridge Status',+ tags: ['bridge', 'cross-chain', 'health', 'solana', 'wormhole', 'lifi'],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ // Parse body — mode must be "bridge_status" (the only supported mode).+ let mode = 'bridge_status';+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+ if (body.mode) mode = String(body.mode).trim();+ } catch { /* default */ }++ if (mode !== 'bridge_status') {+ throw Object.assign(new Error(`unsupported mode: ${mode}`), {+ status: 400,+ code: 'unsupported_mode',+ });+ }++ // Probe all bridges in parallel — no bridge failure aborts the others.+ const bridges = await Promise.all(BRIDGE_PROBES.map((probe) => probebridge(probe)));++ const { signal, headline, confidence, down_count } = classifySignal(bridges);++ return {+ mode,+ bridges,+ down_count,+ signal,+ headline,+ confidence,+ ts: new Date().toISOString(),+ };+ },+});diff --git a/api/x402/forge.js b/api/x402/forge.jsindex fd421b9c8..f3748d236 100644--- a/api/x402/forge.js+++ b/api/x402/forge.js@@ -86,19 +86,22 @@ const MAX_VIEWS = 4;// photos) and the text→3D fallback when the free NVIDIA NIM lane is unavailable.const BACKEND = 'trellis';-// ── Content-generation health probe (mode:"health_check", type:"text") ─────────+// ── Content-generation health probe (mode:"health_check") ───────────────────────// A full text→3D job is slow ($0.05, tens of seconds) — too heavy to canary on a-// tight schedule. This lightweight mode instead exercises the generative AI lane-// every forge job depends on (the free-first LLM provider chain that drives-// prompt understanding) with one fast, real text completion. It proves content-// generation is alive and within its latency budget, returning a measured-// { generated, latency_ms, token_count } verdict the autonomous loop alerts on.-// Priced at the floor ($0.001) since it does no reconstruction.+// tight schedule. This lightweight mode exercises the generative AI lanes at the+// floor price ($0.001) without reconstruction:+// type:"text" — one real LLM text completion; proves prompt understanding alive.+// type:"image" — one real text→image call through the provider chain (NIM FLUX →+// Vertex Imagen → Replicate backstop) and persists the result to+// R2 CDN, proving the full image generation + CDN upload path.+// Both types return a measured verdict the autonomous loop alerts on.const HEALTH_CHECK_PRICE_ATOMIC = 1000; // $0.001 USDC-// The latency SLA the probe asserts. A completion slower than this (or a failure)-// flips within_budget:false and raises a forge performance alert downstream.+// Text latency SLA: LLM completion is fast; >5s means the provider is degraded.const HEALTH_CHECK_BUDGET_MS = 5000;+// Image latency SLA: image generation takes longer; >30s means a hung provider.+const HEALTH_CHECK_IMAGE_BUDGET_MS = 30_000;const HEALTH_CHECK_DEFAULT_PROMPT = 'Write one sentence about Solana.';+const HEALTH_CHECK_IMAGE_DEFAULT_PROMPT = 'A simple blue circle.';const ROUTE_DESCRIPTION ='three.ws Forge — pay-per-call text→3D and image→3D. Submit a prompt (or up ' +@@ -142,9 +145,9 @@ const INPUT_SCHEMA = {},type: {type: 'string',- enum: ['text'],+ enum: ['text', 'image'],default: 'text',- description: 'Content type for health_check mode (text generation canary).',+ description: 'Content type for health_check mode: "text" (LLM completion canary) or "image" (text→image + CDN upload canary).',},},};@@ -452,13 +455,17 @@ async function submitViaReconstruct({ prompt, imageUrls, isImageMode, aspect, ti};}-// Run the content-generation health probe: one fast, real LLM text completion-// over the platform's free-first provider chain (the same generative lane forge-// relies on). Measures end-to-end latency and the generated token count, and-// never throws — a provider outage is the very signal this probe exists to catch,-// so it returns a settled verdict (generated:false) rather than failing the paid-// call. The caller paid for a verdict; it always gets one.-export async function runForgeHealthCheck({ prompt }) {+// Run the content-generation health probe. Never throws — a provider outage is+// the very signal this probe exists to catch, so it always returns a settled+// verdict (generated:false) rather than failing the paid call.+// healthType:"text" — one fast LLM text completion, proves the prompt-+// understanding lane is alive within HEALTH_CHECK_BUDGET_MS.+// healthType:"image" — one real text→image call through the free-first provider+// chain (NIM FLUX → Vertex Imagen → Replicate), uploads the+// result to R2 CDN, and returns the durable url — proving+// the full image generation + CDN upload path is alive.+export async function runForgeHealthCheck({ prompt, healthType = 'text' }) {+ if (healthType === 'image') return runForgeImageHealthCheck(prompt);const probePrompt = (prompt && prompt.length >= 3 ? prompt : HEALTH_CHECK_DEFAULT_PROMPT);const t0 = Date.now();try {@@ -502,6 +509,40 @@ export async function runForgeHealthCheck({ prompt }) {}}+// Image generation health probe: one real text→image call through the free-first+// provider chain (NIM FLUX → Vertex Imagen → Replicate backstop), persisting the+// result to R2 CDN. The returned url proves the full generation + upload path is+// alive; a missing url means the image provider chain is down or unconfigured.+async function runForgeImageHealthCheck(prompt) {+ const probePrompt = prompt && prompt.length >= 3 ? prompt : HEALTH_CHECK_IMAGE_DEFAULT_PROMPT;+ const t0 = Date.now();+ try {+ const { imageUrl, model } = await textToImage(probePrompt, { aspectRatio: '1:1' });+ const latencyMs = Date.now() - t0;+ return {+ mode: 'health_check',+ type: 'image',+ generated: !!imageUrl,+ url: imageUrl || null,+ latency_ms: latencyMs,+ within_budget: latencyMs <= HEALTH_CHECK_IMAGE_BUDGET_MS,+ model: model || null,+ };+ } catch (err) {+ const latencyMs = Date.now() - t0;+ console.warn(`[x402/forge] health_check image generation failed: ${err?.message || err}`);+ return {+ mode: 'health_check',+ type: 'image',+ generated: false,+ url: null,+ latency_ms: latencyMs,+ within_budget: false,+ error: err?.code || 'generation_failed',+ };+ }+}+// Map a submitGeneration failure onto the right HTTP response. A provider 429 is// a transient throttle (Replicate's create-prediction limit, tightest when the// account runs low on credit). Because submit runs BEFORE settle, the payment@@ -778,10 +819,12 @@ async function parseRequestFromObject(body) {// Health-check mode: a lightweight, real content-generation canary that never// reconstructs a mesh (see runForgeHealthCheck). It supplies its own default// prompt, so it is never an empty "probe" and bypasses the 3–1000 char prompt- // rule that gates the 3D lanes. Only the documented type:"text" is supported.+ // rule that gates the 3D lanes. Supported types: "text" (LLM completion) and+ // "image" (text→image + CDN upload).const isHealthCheck = body.mode === 'health_check';if (isHealthCheck) {- return { prompt, imageUrls: [], isImageMode: false, isProbe: false, isHealthCheck: true, healthType: 'text', tier, aspect };+ const healthType = body.type === 'image' ? 'image' : 'text';+ return { prompt, imageUrls: [], isImageMode: false, isProbe: false, isHealthCheck: true, healthType, tier, aspect };}const isProbe = !prompt && !isImageMode;diff --git a/api/x402/llm-proxy.js b/api/x402/llm-proxy.jsnew file mode 100644index 000000000..b86892862--- /dev/null+++ b/api/x402/llm-proxy.js@@ -0,0 +1,199 @@+// POST /api/x402/llm-proxy { model, prompt, max_tokens }+//+// Paid LLM inference proxy — x402 micropayment endpoint for agents that want+// to run one-shot text completions without an API key of their own. Payment+// unlocks one completion through the platform's free-first provider chain:+// Groq leads for "fast" requests (sub-second latency), the full chain+// (Groq → OpenRouter → NVIDIA NIM → Anthropic) covers fallback. The+// response always includes measured wall-clock latency, token counts, and+// the actual provider/model used so callers can benchmark the route.+//+// The autonomous loop calls this every 10 minutes with a minimal "Count to 3."+// prompt to benchmark p95 latency and alert when it exceeds 3 seconds+// (api/_lib/x402/autonomous-registry.js → 'llm-proxy-latency').+//+// Body: { model: "fast"|"smart"|string, prompt: string, max_tokens?: number }+// Price: $0.005 USDC (5 000 atomics) — covers one cheap completion+//+// Response 200:+// { content, model, provider, latency_ms, tokens_used, input_tokens, output_tokens }++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { llmComplete } from '../_lib/llm.js';++const ROUTE = '/api/x402/llm-proxy';++// Map the caller-facing model alias to llmComplete options.+// "fast" → Groq leads the free chain (sub-second latency, sufficient for short prompts)+// "smart" → same chain, Anthropic backstop moves to the preferred position via anthropicModel+// any other string → treated as a direct anthropicModel hint (falls through to paid backstop)+function resolveModelOpts(modelAlias) {+ if (!modelAlias || modelAlias === 'fast') {+ return { preferNvidia: false }; // default free chain, Groq leads+ }+ if (modelAlias === 'smart') {+ return { anthropicModel: 'claude-haiku-4-5-20251001', preferNvidia: false };+ }+ // Treat the string as an explicit anthropicModel (last-resort paid lane only).+ return { anthropicModel: String(modelAlias), preferNvidia: false };+}++const DESCRIPTION =+ 'three.ws LLM Inference Proxy — pay per completion with no API key required. ' ++ 'Runs one-shot text prompts through the platform\'s free-first provider chain ' ++ '(Groq → OpenRouter → NVIDIA NIM → Anthropic). Response includes measured ' ++ 'latency, token counts, and the provider actually used. Ideal for latency ' ++ 'benchmarking, agent pipelines, and one-off completions. ' ++ 'Model aliases: "fast" (Groq, sub-second) · "smart" (Anthropic Haiku backstop). ' ++ 'Price: $0.005 USDC per completion on Base or Solana.';++const INPUT_EXAMPLE = {+ model: 'fast',+ prompt: 'Count to 3.',+ max_tokens: 10,+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['prompt'],+ properties: {+ model: {+ type: 'string',+ default: 'fast',+ description: '"fast" (default, Groq), "smart" (Anthropic Haiku), or a specific model string.',+ },+ prompt: {+ type: 'string',+ minLength: 1,+ maxLength: 4000,+ description: 'The user prompt to complete.',+ },+ max_tokens: {+ type: 'integer',+ minimum: 1,+ maximum: 2048,+ default: 256,+ description: 'Maximum tokens to generate.',+ },+ },+};++const OUTPUT_EXAMPLE = {+ content: '1, 2, 3.',+ model: 'llama-3.3-70b-versatile',+ provider: 'groq',+ latency_ms: 312,+ tokens_used: 11,+ input_tokens: 5,+ output_tokens: 6,+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['content', 'model', 'provider', 'latency_ms', 'tokens_used'],+ properties: {+ content: { type: 'string' },+ model: { type: 'string' },+ provider: { type: 'string' },+ latency_ms: { type: 'integer' },+ tokens_used: { type: 'integer' },+ input_tokens: { type: 'integer' },+ output_tokens: { type: 'integer' },+ },+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: {+ type: 'http',+ method: 'POST',+ bodyType: 'json',+ body: INPUT_EXAMPLE,+ },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: 5_000, // $0.005 USDC+ networks: ['base', 'solana'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws LLM Inference Proxy',+ tags: ['llm', 'inference', 'completion', 'proxy', 'benchmark'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const rawBody = Buffer.concat(chunks).toString();++ let body;+ try {+ body = JSON.parse(rawBody);+ } catch {+ const err = new Error('Request body must be valid JSON');+ err.status = 400;+ err.code = 'invalid_json';+ throw err;+ }++ const prompt = String(body?.prompt || '').trim();+ if (!prompt) {+ const err = new Error('"prompt" is required');+ err.status = 400;+ err.code = 'missing_prompt';+ throw err;+ }+ if (prompt.length > 4000) {+ const err = new Error('"prompt" must be at most 4000 characters');+ err.status = 400;+ err.code = 'prompt_too_long';+ throw err;+ }++ const maxTokens = Math.min(Math.max(parseInt(body?.max_tokens ?? 256, 10) || 256, 1), 2048);+ const modelAlias = body?.model || 'fast';+ const opts = resolveModelOpts(modelAlias);++ const t0 = Date.now();+ const result = await llmComplete({+ system: 'You are a helpful assistant. Be concise.',+ user: prompt,+ maxTokens,+ ...opts,+ timeoutMs: 15_000,+ });+ const latencyMs = Date.now() - t0;++ const inputTokens = result.usage?.input ?? 0;+ const outputTokens = result.usage?.output ?? 0;++ return {+ content: result.text,+ model: result.model,+ provider: result.provider,+ latency_ms: latencyMs,+ tokens_used: inputTokens + outputTokens,+ input_tokens: inputTokens,+ output_tokens: outputTokens,+ };+ },+});diff --git a/api/x402/notify.js b/api/x402/notify.jsnew file mode 100644index 000000000..2f73f44a2--- /dev/null+++ b/api/x402/notify.js@@ -0,0 +1,194 @@+// POST /api/x402/notify — Notification Delivery Probe+//+// Paid canary ($0.001 USDC) that exercises the platform notification delivery+// path end-to-end. The autonomous loop sends a heartbeat through the `canary`+// channel every 5 minutes; the endpoint records delivery timing to+// canary_notification_log and returns { delivered, channel, latency_ms } —+// the actionable signal that confirms the notification subsystem is alive.+//+// Body:+// { "channel": "canary", "message": "x402 loop heartbeat", "priority": "low" }+//+// Response:+// { delivered: true, channel: "canary", latency_ms: <number>, notification_id: "<uuid>" }++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { sql } from '../_lib/db.js';+import { priceFor } from '../_lib/x402-prices.js';++const ROUTE = '/api/x402/notify';++const VALID_CHANNELS = new Set(['canary', 'ops', 'system']);+const VALID_PRIORITIES = new Set(['low', 'normal', 'high']);++// One-time DDL guard per warm instance.+let _schemaReady = false;+async function ensureSchema() {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS canary_notification_log (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ channel text NOT NULL,+ message text NOT NULL,+ priority text NOT NULL DEFAULT 'low',+ payer text,+ latency_ms integer NOT NULL,+ delivered boolean NOT NULL DEFAULT true,+ created_at timestamptz NOT NULL DEFAULT now()+ )+ `;+ await sql`+ CREATE INDEX IF NOT EXISTS canary_notification_log_channel_ts+ ON canary_notification_log (channel, created_at DESC)+ `;+ _schemaReady = true;+}++const DESCRIPTION =+ 'Notification Delivery Probe — pay $0.001 USDC to send a canary message ' ++ 'through the platform notification channel and confirm delivery. Returns ' ++ '{ delivered, channel, latency_ms } so the autonomous loop can assert the ' ++ 'notification subsystem is alive within a 2-second SLA. Channel "canary" is ' ++ 'the x402 loop heartbeat lane; "ops" and "system" route to the ops alert surface.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ channel: {+ type: 'string',+ enum: ['canary', 'ops', 'system'],+ description: 'Delivery channel. "canary" is the autonomous-loop heartbeat lane.',+ default: 'canary',+ },+ message: {+ type: 'string',+ maxLength: 500,+ description: 'Notification message body.',+ default: 'x402 loop heartbeat',+ },+ priority: {+ type: 'string',+ enum: ['low', 'normal', 'high'],+ description: 'Delivery priority hint.',+ default: 'low',+ },+ },+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['delivered', 'channel', 'latency_ms', 'notification_id', 'ts'],+ properties: {+ delivered: { type: 'boolean' },+ channel: { type: 'string' },+ latency_ms: { type: 'integer', description: 'Time from request receipt to DB record completion.' },+ notification_id: { type: 'string', format: 'uuid' },+ message: { type: 'string' },+ priority: { type: 'string' },+ payer: { type: ['string', 'null'] },+ ts: { type: 'string', format: 'date-time' },+ },+};++const BAZAAR = {+ description: DESCRIPTION,+ useCases: ['notification health check', 'delivery canary', 'ops alerting'],+ input: {+ type: 'json',+ example: { channel: 'canary', message: 'x402 loop heartbeat', priority: 'low' },+ schema: INPUT_SCHEMA,+ },+ output: {+ type: 'json',+ example: {+ delivered: true,+ channel: 'canary',+ latency_ms: 18,+ notification_id: 'a3f3d6c2-1f1b-4f10-9b6c-1b1f5e0c9c34',+ message: 'x402 loop heartbeat',+ priority: 'low',+ payer: null,+ ts: '2026-06-28T10:00:00Z',+ },+ },+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),+};++async function readBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('notify', '1000'), // $0.001 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Notification Delivery',+ tags: ['notification', 'canary', 'health', 'delivery', 'ops'],+ }),+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req, payer }) {+ const t0 = Date.now();+ const body = await readBody(req);++ const rawChannel = typeof body.channel === 'string' ? body.channel.trim().slice(0, 64) : 'canary';+ const channel = VALID_CHANNELS.has(rawChannel) ? rawChannel : 'canary';++ const message = typeof body.message === 'string'+ ? body.message.trim().slice(0, 500)+ : 'x402 loop heartbeat';++ const rawPriority = typeof body.priority === 'string' ? body.priority.trim().toLowerCase() : 'low';+ const priority = VALID_PRIORITIES.has(rawPriority) ? rawPriority : 'low';++ let notification_id = crypto.randomUUID();+ let delivered = false;++ try {+ await ensureSchema();+ const latency_ms_pre = Date.now() - t0;+ const [row] = await sql`+ INSERT INTO canary_notification_log+ (channel, message, priority, payer, latency_ms, delivered)+ VALUES+ (${channel}, ${message}, ${priority}, ${payer ?? null}, ${latency_ms_pre}, true)+ RETURNING id+ `;+ notification_id = row?.id ?? notification_id;+ delivered = true;+ } catch (err) {+ console.error('[x402/notify] db insert failed:', err?.message);+ // delivered stays false — the signal is actionable+ }++ const latency_ms = Date.now() - t0;++ return {+ delivered,+ channel,+ latency_ms,+ notification_id,+ message,+ priority,+ payer: payer ?? null,+ ts: new Date().toISOString(),+ };+ },+});diff --git a/api/x402/schema-check.js b/api/x402/schema-check.jsnew file mode 100644index 000000000..3f3dd0416--- /dev/null+++ b/api/x402/schema-check.js@@ -0,0 +1,235 @@+// POST /api/x402/schema-check+//+// Paid endpoint ($0.001 USDC) that fetches a named three.ws public JSON API and+// validates its response schema against the declared spec. The first supported+// target is `changelog_json` — the public /changelog.json feed all $THREE holders+// and RSS consumers depend on. A schema break (missing required keys, wrong entry+// shape, empty array when entries exist) surfaces here before users notice a broken+// changelog, broken RSS, or a malformed JSON feed that chokes a downstream parser.+//+// Supported `api` values:+// changelog_json — fetches /changelog.json, validates: generated_at (ISO date-+// time), site.name, site.url (URL), entries (non-empty array+// with each entry having date/title/summary/tags). Returns+// { valid, version (generated_at date), entry_count,+// schema_errors[] }.+//+// Networks: Solana mainnet + Base mainnet. Price: $0.001 USDC.+// Consumed by the autonomous x402 loop (changelog-schema-check entry).++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { priceFor } from '../_lib/x402-prices.js';+import { env } from '../_lib/env.js';++const ROUTE = '/api/x402/schema-check';++const DESCRIPTION =+ 'three.ws JSON API schema conformance checker — pay $0.001 USDC to fetch a ' ++ 'named three.ws public API and validate its response against the declared schema. ' ++ 'Surfaces breaking schema changes before users notice a broken feed. ' ++ 'Current target: changelog_json — the /changelog.json feed holders and RSS consumers ' ++ 'depend on. Returns { valid, version, entry_count, schema_errors }.';++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['api'],+ properties: {+ api: {+ type: 'string',+ enum: ['changelog_json'],+ description: 'Which public JSON API to fetch and validate.',+ },+ },+ additionalProperties: false,+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'api', 'valid', 'entry_count', 'fetched_at'],+ properties: {+ ok: { type: 'boolean' },+ api: { type: 'string' },+ valid: { type: 'boolean', description: 'True when all required schema assertions pass.' },+ version: { type: ['string', 'null'], description: 'generated_at date from the feed, or null on fetch error.' },+ entry_count: { type: 'integer', minimum: 0 },+ schema_errors: {+ type: 'array',+ items: { type: 'string' },+ description: 'List of schema violations found. Empty when valid=true.',+ },+ fetched_at: { type: 'string', format: 'date-time' },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ api: 'changelog_json',+ valid: true,+ version: '2026-06-28',+ entry_count: 42,+ schema_errors: [],+ fetched_at: '2026-06-28T12:00:00.000Z',+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'json', example: { api: 'changelog_json' }, schema: INPUT_SCHEMA },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++const SUPPORTED_APIS = new Set(['changelog_json']);++// Validate the /changelog.json feed against its declared schema.+// Returns { valid, version, entry_count, schema_errors }.+function validateChangelogJson(data) {+ const errors = [];++ if (typeof data !== 'object' || data === null || Array.isArray(data)) {+ return { valid: false, version: null, entry_count: 0, schema_errors: ['root is not an object'] };+ }++ // generated_at must be a non-empty ISO datetime string+ if (typeof data.generated_at !== 'string' || !data.generated_at.trim()) {+ errors.push('missing or empty generated_at');+ } else {+ const d = new Date(data.generated_at);+ if (isNaN(d.getTime())) errors.push('generated_at is not a valid ISO datetime');+ }++ // site must be an object with name + url+ if (typeof data.site !== 'object' || data.site === null) {+ errors.push('missing site object');+ } else {+ if (typeof data.site.name !== 'string' || !data.site.name.trim()) {+ errors.push('missing site.name');+ }+ if (typeof data.site.url !== 'string' || !data.site.url.startsWith('http')) {+ errors.push('missing or invalid site.url');+ }+ }++ // entries must be a non-empty array+ if (!Array.isArray(data.entries)) {+ errors.push('entries is not an array');+ } else if (data.entries.length === 0) {+ errors.push('entries array is empty');+ } else {+ // Validate the first 5 entries (representative sample — avoid O(n) on large feeds)+ const sample = data.entries.slice(0, 5);+ for (let i = 0; i < sample.length; i++) {+ const entry = sample[i];+ if (typeof entry !== 'object' || entry === null) {+ errors.push(`entries[${i}] is not an object`);+ continue;+ }+ if (typeof entry.date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(entry.date)) {+ errors.push(`entries[${i}].date missing or not YYYY-MM-DD`);+ }+ if (typeof entry.title !== 'string' || !entry.title.trim()) {+ errors.push(`entries[${i}].title missing or empty`);+ }+ if (typeof entry.summary !== 'string' || !entry.summary.trim()) {+ errors.push(`entries[${i}].summary missing or empty`);+ }+ if (!Array.isArray(entry.tags) || entry.tags.length === 0) {+ errors.push(`entries[${i}].tags missing or empty`);+ }+ }+ }++ const version = (typeof data.generated_at === 'string' && data.generated_at.length >= 10)+ ? data.generated_at.slice(0, 10)+ : null;+ const entry_count = Array.isArray(data.entries) ? data.entries.length : 0;++ return { valid: errors.length === 0, version, entry_count, schema_errors: errors };+}++async function readBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8').trim();+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor('schema-check', '1000'),+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws JSON API Schema Check',+ tags: ['schema', 'validation', 'changelog', 'health', 'api'],+ }),++ async handler(req) {+ const body = await readBody(req);+ const api = body?.api;++ if (!api || !SUPPORTED_APIS.has(api)) {+ return {+ ok: false,+ error: `unsupported api "${api}"; supported: ${[...SUPPORTED_APIS].join(', ')}`,+ };+ }++ const origin = (env.APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');+ const fetched_at = new Date().toISOString();++ if (api === 'changelog_json') {+ const url = `${origin}/changelog.json`;+ let data = null;+ let fetchError = null;++ try {+ const res = await fetch(url, {+ headers: { accept: 'application/json', 'user-agent': 'threews-schema-check/1.0' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!res.ok) {+ fetchError = `http_${res.status}`;+ } else {+ data = await res.json();+ }+ } catch (err) {+ fetchError = err?.message || 'fetch_failed';+ }++ if (fetchError || data === null) {+ return {+ ok: false,+ api,+ valid: false,+ version: null,+ entry_count: 0,+ schema_errors: [fetchError || 'fetch_failed'],+ fetched_at,+ };+ }++ const { valid, version, entry_count, schema_errors } = validateChangelogJson(data);+ return { ok: true, api, valid, version, entry_count, schema_errors, fetched_at };+ }++ // Unreachable given the SUPPORTED_APIS guard above, but keeps linting clean.+ return { ok: false, error: 'unhandled_api' };+ },+});diff --git a/docs/x402-offer-receipt/00-plan.md b/docs/x402-offer-receipt/00-plan.mddeleted file mode 100644index 81490afce..000000000--- a/docs/x402-offer-receipt/00-plan.md+++ /dev/null@@ -1,71 +0,0 @@-# x402 Signed Offers & Receipts — Integration Plan--Wire the x402 Offer & Receipt extension into every paid endpoint in this repo so every `402` response carries one signed offer per accepted network, and every `200` response carries one signed receipt — without changing any handler's business logic.--## Why this exists (one paragraph)--The x402 Offer & Receipt extension produces portable, cryptographically signed artifacts that prove (a) the server committed to specific payment terms, and (b) the client received the service it paid for. Today the upside for `$0.001`-priced endpoints is mostly positioning: being early on a spec that reputation aggregators may eventually crawl. The cost is modest and the surface is contained, so this plan ships it cleanly with a single signer module and two hook points in the existing `paidEndpoint` wrapper.--## Locked-in decisions--These are decided up front so prompts don't re-litigate them. If a prompt encounters a reason to change one of these, stop and surface it before deviating.--| Decision | Value | Reason |-|---|---|---|-| Signing format | **EIP-712** (`did:pkh`) | secp256k1 only is fine — the *receipt signing key* is independent of how payers pay. No DID document to host. |-| Signing key env var | `X402_RECEIPT_SIGNING_KEY` | Hex-encoded 32-byte private key, `0x`-prefixed. **Must be a dedicated key**, not `X402_PAY_TO_*`. |-| KID format | `did:pkh:eip155:1:${signerAddress}#key-1` | Chain `1` (Ethereum mainnet) is conventional for `did:pkh` identity. The signing identity is independent of the payment chain. |-| Extension scope | **Global** in [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) | All 9 paid endpoints are symmetric; one toggle beats 9 per-file edits. |-| Extension placement on 402 body | Sibling under top-level `extensions["offer-receipt"]`, **not** nested under `bazaar` | The agentic.market validator mirrors `@x402/extensions/bazaar` exactly; nesting risks failing their schema check. |-| Receipt placement on `200` | Inside `x-payment-response` header payload's `extensions["offer-receipt"]` | Matches the spec's wire format — clients call `extractReceiptFromResponse` on the response. |-| `includeTxHash` default | `false` | Privacy-preserving default; payer address is already in the receipt. |-| Offer `validUntil` | `now + 60s` | Matches existing `maxTimeoutSeconds: 60` in every accept entry. |-| BSC `direct` scheme handling | Sign the offer with `offerType: 'direct'` | The field is a free-form string per spec. Third-party verifiers expecting `'exact'` won't accept it, which is fine — BSC users aren't the target audience for portable receipts yet. |-| Signer module location | [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) (new) | Sits next to `x402-paid-endpoint.js` and `x402-spec.js` so the hook points import it cleanly. |-| DID document hosting | **Out of scope for v1** | Not required for EIP-712 (`did:pkh` is self-describing). Add later if a verifier requires it. |--## Files touched--- [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) — **new**, exports a singleton issuer + offer/receipt sign helpers.-- [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) — wire offers into `build402Body`, wire receipts into `encodePaymentResponseHeader`.-- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) — pass payer/network through to settle so the receipt payload has what it needs.-- [api/_lib/env.js](../../api/_lib/env.js) — surface `X402_RECEIPT_SIGNING_KEY` as a typed env field.-- [.env.example](../../.env.example) — document the new env var.-- [package.json](../../package.json) — add `@x402/extensions` and (if missing) `viem`.-- All 9 endpoints in [api/x402/](../../api/x402/) — **no edits needed**. The global wrapper handles it.-- [scripts/verify-x402-receipts.js](../../scripts/verify-x402-receipts.js) — **new**, smoke test that hits a paid endpoint and verifies the signed offer + receipt round-trip.--## Prompt sequence--Each prompt is self-contained and assumes only that prior prompts in the sequence completed successfully. Run them in order.--1. [01-foundation.md](01-foundation.md) — install deps, add env var, create the signer module.-2. [02-offer-signing.md](02-offer-signing.md) — wire offer signing into the `402` response path.-3. [03-receipt-signing.md](03-receipt-signing.md) — wire receipt signing into the `200` response path.-4. [04-bazaar-declaration.md](04-bazaar-declaration.md) — declare the extension in the discovery envelope so bazaar crawlers know we sign.-5. [05-verification-script.md](05-verification-script.md) — build the end-to-end smoke test that proves offers and receipts verify.-6. [06-completionist-and-push.md](06-completionist-and-push.md) — final audit pass and push to both remotes.--## Definition of done (whole feature)--All of these must be verifiable, not asserted:--- [x] `X402_RECEIPT_SIGNING_KEY` is set in `.env.example` (placeholder), `.env` (real value), and configured in Vercel for `production` + `preview`.-- [x] `npm test` passes.-- [x] Hitting any paid endpoint without a payment header returns `402` with `body.extensions["offer-receipt"].signedOffers[]` containing one entry per accepted network.-- [x] Hitting any paid endpoint with a valid payment returns `200` with `x-payment-response` decoding to an envelope whose `extensions["offer-receipt"].signedReceipt` verifies under the signer's recovered address.-- [x] The verification script at `scripts/verify-x402-receipts.js` runs against a deployed (or `vercel dev`) instance, verifies both artifacts, and exits `0`.-- [x] No handler in `api/x402/*.js` was modified — the wiring is purely in the shared lib.-- [x] Completionist agent run against the diff returns clean.-- [x] Pushed to **both** `origin` and `threews` remotes.--## Risks & caveats--- **Key compromise.** `X402_RECEIPT_SIGNING_KEY` is the single point of failure. If it leaks, an attacker can forge offers and receipts in your name. Provision it via Vercel encrypted env, never commit it, and rotate by updating env + bumping the KID's `#key-1` → `#key-2`.-- **Settle-failure ordering.** Receipts must only be signed *after* `settlePayment` succeeds, never before. The wiring in prompt 03 must enforce this.-- **`vercel.json` collapse.** Recent commit `36dfec9a` collapsed functions config to a single wildcard. The new signer module is a `_lib` helper, not a function entry, so no `vercel.json` change is needed. Verify this assumption holds before claiming done.-- **`bazaar` schema strictness.** Per [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js#L457), the bazaar extension must mirror `@x402/extensions/bazaar` exactly. The new `offer-receipt` extension is a **sibling** to `bazaar`, not nested under it. Do not modify `bazaarExtension()` or `buildBazaarSchema()`.--## Rollback--Single env-var toggle controls the feature: if `X402_RECEIPT_SIGNING_KEY` is unset, the signer module exports a no-op issuer, the offer/receipt arrays are omitted from responses, and the feature degrades gracefully to current behavior. To roll back: unset the env var in Vercel and redeploy. Code does not need to be reverted.diff --git a/docs/x402-offer-receipt/01-foundation.md b/docs/x402-offer-receipt/01-foundation.mddeleted file mode 100644index 6504cf2d5..000000000--- a/docs/x402-offer-receipt/01-foundation.md+++ /dev/null@@ -1,95 +0,0 @@-# Prompt 01 — Foundation: deps, env, signer module--You are landing the **foundation** for the x402 Signed Offers & Receipts feature. See [00-plan.md](00-plan.md) for the locked-in decisions — do not re-litigate them.--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No mocks. No fake data. No placeholders.** Real APIs, real keys.-- **No `// TODO`, no stub functions, no commented-out code.** If you write it, finish it.-- **No `throw new Error("not implemented")`.**-- Errors handled at boundaries (network, user input). Internal code trusts itself.--## Inputs--- Locked decisions in [00-plan.md](00-plan.md):- - Signing format: **EIP-712** (`did:pkh:eip155:1:${address}#key-1`).- - Env var: `X402_RECEIPT_SIGNING_KEY` (hex private key, `0x`-prefixed, 32 bytes).- - Module path: `api/_lib/x402-offer-receipt.js`.- - When env is unset, exports a **no-op issuer** that returns `null` for sign calls. This is the rollback toggle.-- Existing env loader: [api/_lib/env.js](../../api/_lib/env.js). Add the new field there using whatever pattern the existing `X402_PAY_TO_*` fields use.--## Task--### 1. Install dependencies--```bash-npm install @x402/extensions @x402/core viem-```--`viem` may already be in [package.json](../../package.json). If so, ensure the installed version is `>=2.0.0` (required by `@x402/extensions`). Do not downgrade other packages.--### 2. Add the env var--- In [api/_lib/env.js](../../api/_lib/env.js), add `X402_RECEIPT_SIGNING_KEY` next to the existing `X402_PAY_TO_*` fields. Do not assert it as required — the no-op fallback depends on the field being optional.-- In [.env.example](../../.env.example), add a documented block. The placeholder value must clearly be a placeholder (e.g. `0xREPLACE_WITH_DEDICATED_SIGNING_KEY_HEX_64_CHARS`) and the comment must say "dedicated signing key, NOT a wallet that holds funds" and "rotate by changing the value and bumping `#key-1` → `#key-2` in code if needed."--### 3. Create the signer module--Create [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js) exporting:--```js-// One singleton issuer per process. Resolves to the EIP-712 issuer when-// X402_RECEIPT_SIGNING_KEY is set, otherwise to a no-op that returns null.-// The no-op is the feature flag — unset the env var in Vercel to roll back-// without redeploying code.-export const issuer; // { kid, signerAddress, sign } | null--// Sign one offer per accept entry on a 402 response. Returns the array of-// signed offers in the wire shape consumed by extractOffersFromPaymentRequired-// on the client side. Returns [] when the issuer is null (feature disabled).-export async function signOffersForAccepts({ accepts, resourceUrl, validitySeconds });--// Sign one receipt for a settled 200 response. Returns the signed receipt-// in the wire shape consumed by extractReceiptFromResponse on the client-// side. Returns null when the issuer is null (feature disabled) or when-// the inputs are insufficient.-export async function signReceipt({ resourceUrl, payer, network, txHash, includeTxHash });-```--Implementation requirements:--- Import `createEIP712OfferReceiptIssuer` from `@x402/extensions/offer-receipt` and `privateKeyToAccount` from `viem/accounts`.-- `kid` is exactly `did:pkh:eip155:1:${signerAddress}#key-1`. Lowercase the address per CAIP-10.-- `validitySeconds` defaults to `60` if omitted (matches `maxTimeoutSeconds`).-- `includeTxHash` defaults to `false`.-- `validUntil` is `Math.floor(Date.now() / 1000) + validitySeconds`.-- The `offerType` field on each signed offer comes from the accept's `scheme` field (so BSC's `'direct'` flows through unchanged).-- If `X402_RECEIPT_SIGNING_KEY` is malformed (wrong length, not hex), throw at module-load time with a clear `x402_receipt_signing_key_invalid` error. Don't fail silently — a malformed key means the operator intended to enable signing but configured it wrong.-- If `signReceipt` is called with `payer == null` or `network == null`, return `null` and do not throw. That's a normal condition for endpoints whose settlement skipped the facilitator (e.g. BSC `direct`); we want to keep the response shape clean.--### 4. Smoke check--After writing the module:--```bash-node --input-type=module -e "import { issuer, signOffersForAccepts, signReceipt } from './api/_lib/x402-offer-receipt.js'; console.log('issuer:', issuer ? issuer.signerAddress : 'no-op'); console.log('offers (no-op safe):', await signOffersForAccepts({ accepts: [], resourceUrl: 'https://example.com/x' })); console.log('receipt (no-op safe):', await signReceipt({ resourceUrl: 'https://example.com/x', payer: null, network: null }));"-```--With `X402_RECEIPT_SIGNING_KEY` unset, this should print `issuer: no-op`, `offers: []`, `receipt: null`. With a real key set, `issuer` should print the recovered address.--## Definition of done--- [ ] `@x402/extensions`, `@x402/core`, and `viem` (>=2) are in `package.json` `dependencies` and `npm install` succeeds.-- [ ] `api/_lib/env.js` exposes `X402_RECEIPT_SIGNING_KEY`.-- [ ] `.env.example` documents the new var with a clear placeholder and the rotation guidance.-- [ ] `api/_lib/x402-offer-receipt.js` exists and exports `issuer`, `signOffersForAccepts`, `signReceipt`.-- [ ] The smoke check above works in both modes (env set, env unset).-- [ ] `npm test` still passes.-- [ ] `git diff` reviewed by you. No `TODO`, no stubs, no commented-out code.--## Stop conditions--- If `@x402/extensions` does not expose `createEIP712OfferReceiptIssuer` at the documented path, surface this **before** writing anything else — the spec or package layout may have changed since the planning doc was written.-- If `viem` cannot be upgraded to `>=2` without breaking other packages, surface this with the conflict before proceeding.diff --git a/docs/x402-offer-receipt/02-offer-signing.md b/docs/x402-offer-receipt/02-offer-signing.mddeleted file mode 100644index 6c84a0032..000000000--- a/docs/x402-offer-receipt/02-offer-signing.md+++ /dev/null@@ -1,127 +0,0 @@-# Prompt 02 — Wire offer signing into the 402 response path--You are wiring **offer signing** into the `402 Payment Required` flow. The signer module from [01-foundation.md](01-foundation.md) is already in place at [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js). Locked-in decisions live in [00-plan.md](00-plan.md).--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No fake data, no placeholders, no stubs.**-- **Errors handled at boundaries only.**--Additional rule for this task:--- **Do not modify `bazaarExtension()` or `buildBazaarSchema()`** in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js). The bazaar crawler validator mirrors the `@x402/extensions/bazaar` shape exactly — any deviation breaks discovery. The new `offer-receipt` extension is a **sibling** to `bazaar`, not nested under it.--## Inputs--- Hook point: [api/_lib/x402-spec.js:610](../../api/_lib/x402-spec.js#L610) — the `build402Body` function.-- Signer surface (already built in prompt 01):- ```js- import { signOffersForAccepts } from './x402-offer-receipt.js';- const signedOffers = await signOffersForAccepts({- accepts: requirements, // array of accept entries (the 'requirements')- resourceUrl, // string- validitySeconds: 60, // matches maxTimeoutSeconds- });- // Returns [] when feature is disabled (env unset).- ```-- Wire shape required by the spec — what the client's `extractOffersFromPaymentRequired` expects:- ```json- {- "extensions": {- "bazaar": { ... existing ... },- "offer-receipt": {- "signedOffers": [ { kid, signature, payload: { resourceUrl, offerType, network, amount, payTo, validUntil } }, ... ]- }- }- }- ```--## Task--### 1. Make `build402Body` async-friendly--`build402Body` is currently synchronous. The offer signer is async. The cleanest change:--- Convert `build402Body` to `async function build402Body(...)`.-- Convert `send402` to `async function send402(res, opts = {})` and `await build402Body(opts)`.-- Update **every** caller of `send402` to `await` it. Audit with:- ```bash- grep -rn "send402(" api/- ```- Every call site must be inside an `async` function and prefixed with `await`. There are calls in [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) (already async) and possibly others — verify exhaustively.--### 2. Attach signed offers to the 402 body--Inside `build402Body`, after the existing fields are assembled, call `signOffersForAccepts` with the final `accepts` array and `resourceUrl`. Merge the result into `extensions`:--```js-const signedOffers = await signOffersForAccepts({- accepts: Array.isArray(accepts) ? accepts : [accepts],- resourceUrl,- validitySeconds: 60,-});--return {- x402Version: X402_VERSION,- error,- resource: { url: resourceUrl, description, mimeType },- accepts: Array.isArray(accepts) ? accepts : [accepts],- extensions: signedOffers.length- ? { bazaar, 'offer-receipt': { signedOffers } }- : { bazaar },-};-```--When the feature is disabled (env unset), `signedOffers` is `[]` and the `offer-receipt` key is omitted entirely. This keeps the 402 body byte-identical to current behaviour for the disabled case.--### 3. Mirror into the `PAYMENT-REQUIRED` header--The current code at [api/_lib/x402-spec.js:634](../../api/_lib/x402-spec.js#L634) base64-encodes the 402 body into the `PAYMENT-REQUIRED` header. After your changes that body now includes the signed offers, so the header automatically carries them — confirm this by inspection. **Do not** add a separate header.--### 4. Sanity test--Start the dev server and curl a paid endpoint without a payment header:--```bash-npm run dev &-sleep 3-curl -s -i http://localhost:3000/api/x402/dance-tip?dancer=1\&dance=rumba | tee /tmp/402.txt-```--With `X402_RECEIPT_SIGNING_KEY` set, the response body should include `extensions["offer-receipt"].signedOffers` with one entry per accept. With it unset, the body should be **byte-identical** to current behaviour (no `offer-receipt` key). Verify both modes.--Then verify a signed offer cryptographically:--```bash-node --input-type=module -e "-import { decodeSignedOffers, verifyOfferSignatureEIP712 } from '@x402/extensions/offer-receipt';-import fs from 'fs';-const raw = fs.readFileSync('/tmp/402.txt', 'utf8').split('\r\n\r\n')[1];-const body = JSON.parse(raw);-const offers = body.extensions['offer-receipt'].signedOffers;-const decoded = decodeSignedOffers(offers);-for (const d of decoded) {- const ok = await verifyOfferSignatureEIP712(d.signedOffer);- console.log(d.signedOffer.payload.network, '->', ok ? 'VERIFIED' : 'FAILED');-}-"-```--Every accept-entry network should print `VERIFIED`.--## Definition of done--- [ ] `build402Body` and `send402` are `async`; all call sites updated to `await`.-- [ ] 402 responses include `extensions["offer-receipt"].signedOffers` when env is set, and omit it cleanly when env is unset.-- [ ] Each signed offer verifies under `verifyOfferSignatureEIP712`.-- [ ] `bazaarExtension()` and `buildBazaarSchema()` are **unchanged**.-- [ ] No paid endpoint handler in `api/x402/*.js` was modified.-- [ ] `npm test` still passes.-- [ ] `git diff` reviewed.--## Stop conditions--- If you discover a `send402` caller in a non-async function that cannot trivially become async, surface the conflict instead of plumbing a `.then()` shim — async-to-callback bridging in this codebase has caused settlement-ordering bugs before.-- If the bazaar crawler validator schema test fails after the change, the extension shape leaked into `bazaar` — restore the sibling structure.diff --git a/docs/x402-offer-receipt/03-receipt-signing.md b/docs/x402-offer-receipt/03-receipt-signing.mddeleted file mode 100644index bdf5929e7..000000000--- a/docs/x402-offer-receipt/03-receipt-signing.md+++ /dev/null@@ -1,145 +0,0 @@-# Prompt 03 — Wire receipt signing into the 200 response path--You are wiring **receipt signing** into the post-settlement `200` flow. Prompts [01](01-foundation.md) and [02](02-offer-signing.md) are complete: the signer module exists and offer signing on `402` works end-to-end. Locked-in decisions live in [00-plan.md](00-plan.md).--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No fake data, no placeholders, no stubs.**-- **Errors handled at boundaries only.**--Additional rules for this task:--- **Receipts are signed only AFTER `settlePayment` succeeds.** A receipt signed before settle would attest to delivery for a payment that may not have cleared. The wiring must enforce this ordering — there is no acceptable shortcut.-- **A failed receipt sign must not fail the response.** The user paid and the work ran; we deliver the result regardless. Log the error and continue with an unsigned response.--## Inputs--- Receipt-signing hook point: [api/_lib/x402-paid-endpoint.js:199](../../api/_lib/x402-paid-endpoint.js#L199), where `x-payment-response` is set from `encodePaymentResponseHeader(settled)`.-- All inputs the receipt needs are already in scope at that point:- - `resourceUrl` — defined at line 143.- - `verified.payer` — from the `verifyPayment` step.- - `verified.requirement.network` — the accept entry that matched.- - `settled.txHash` (optional) — from `settlePayment` return value. Field name is whatever `settlePayment` actually returns; verify in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).-- Signer surface (already built in prompt 01):- ```js- import { signReceipt } from './x402-offer-receipt.js';- const signedReceipt = await signReceipt({- resourceUrl,- payer: verified.payer,- network: verified.requirement.network,- txHash: settled.txHash,- includeTxHash: false, // privacy-preserving default- });- // Returns null when feature is disabled or inputs insufficient.- ```-- Wire shape required — what the client's `extractReceiptFromResponse` expects on `x-payment-response`:- ```json- {- ... existing settle response ...,- "extensions": {- "offer-receipt": {- "signedReceipt": { kid, signature, payload: { resourceUrl, payer, network, issuedAt, txHash? } }- }- }- }- ```--## Task--### 1. Locate `encodePaymentResponseHeader`--It's at [api/_lib/x402-spec.js:436](../../api/_lib/x402-spec.js#L436). Read its current shape — it takes a `settleResult` object and returns a base64-JSON string.--You have two integration options. Pick **Option A** unless you find a concrete reason to prefer B.--**Option A (recommended): attach the receipt at the call site.**--In [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js), after the existing `settled = await settlePayment(...)` block (around line 197), sign the receipt and merge it into the envelope before encoding. Change `encodePaymentResponseHeader` to accept an envelope rather than a raw `settleResult`, or add a sibling helper. Keep the change tight — do not refactor unrelated code.--**Option B: thread the signer through `encodePaymentResponseHeader`.**--Make `encodePaymentResponseHeader` async and take `{ settleResult, signedReceipt }`. Update all callers. This is fine but slightly more churn.--### 2. Implement the wiring (Option A example shape)--```js-let settled;-try {- settled = await settlePayment({ ... });-} catch (err) {- return error(res, err.status || 502, err.code || 'settle_failed', err.message);-}--let signedReceipt = null;-try {- signedReceipt = await signReceipt({- resourceUrl,- payer: verified.payer,- network: verified.requirement.network,- txHash: settled.txHash,- includeTxHash: false,- });-} catch (err) {- // Sign failures must not break the response. Log and proceed unsigned.- console.error('x402_receipt_sign_failed', err);-}--const headerEnvelope = signedReceipt- ? { ...settled, extensions: { 'offer-receipt': { signedReceipt } } }- : settled;--res.setHeader('x-payment-response', encodePaymentResponseHeader(headerEnvelope));-```--Verify that `encodePaymentResponseHeader` is shape-agnostic enough to accept this. If it currently does field-by-field re-encoding, generalize it minimally — do not refactor beyond what's needed.--### 3. Confirm `verified.payer` and `verified.requirement.network` are populated--These come from `verifyPayment` at [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js). Trace the code path and confirm both fields are present on the returned object. If `verifyPayment` does not currently expose `payer`, fix that in the shared lib — but only the minimum needed.--For BSC `direct` flows, `verified.payer` may be `null` (the contract emits an event, no signed payload). That's expected — `signReceipt` returns `null` when payer is null, which means BSC responses ship without a receipt. Document this in a one-line comment at the call site.--### 4. Sanity test--```bash-npm run dev &-sleep 3-# Hit any paid endpoint with a valid x-payment header from a test client.-# (Use the existing test/example client in the repo — find it with: grep -rln "x-payment" --include="*.js" .)-```--After the call returns 200, decode `x-payment-response`:--```bash-node --input-type=module -e "-import { verifyReceiptSignatureEIP712 } from '@x402/extensions/offer-receipt';-const headerB64 = process.argv[2];-const envelope = JSON.parse(Buffer.from(headerB64, 'base64').toString('utf8'));-const sr = envelope.extensions?.['offer-receipt']?.signedReceipt;-if (!sr) { console.error('no signed receipt'); process.exit(1); }-const ok = await verifyReceiptSignatureEIP712(sr);-console.log(ok ? 'VERIFIED' : 'FAILED', JSON.stringify(sr.payload, null, 2));-" "<paste-the-header-value-here>"-```--Expected: `VERIFIED` and a payload containing `resourceUrl`, `payer`, `network`, `issuedAt`. No `txHash` (because `includeTxHash: false`).--## Definition of done--- [ ] After successful settlement, `x-payment-response` decodes to an envelope containing `extensions["offer-receipt"].signedReceipt`.-- [ ] The signed receipt verifies under `verifyReceiptSignatureEIP712`.-- [ ] Receipt payload includes `resourceUrl`, `payer`, `network`, `issuedAt`. No `txHash` unless `includeTxHash: true` (it's not).-- [ ] Receipts are signed **only** after `settlePayment` resolves — never before.-- [ ] A receipt-sign failure logs `x402_receipt_sign_failed` and returns the 200 anyway.-- [ ] BSC `direct` 200 responses ship without a receipt (graceful null), no error thrown.-- [ ] When `X402_RECEIPT_SIGNING_KEY` is unset, response is byte-identical to current behaviour.-- [ ] No paid endpoint handler in `api/x402/*.js` was modified.-- [ ] `npm test` still passes.-- [ ] `git diff` reviewed.--## Stop conditions--- If `verifyPayment` does not return the payer address for the EVM `exact` scheme, do not invent one — fix the upstream verifier first or surface the gap.-- If `settlePayment` does not return a `txHash` field, that's fine (we default `includeTxHash: false`). Do not add fake tx hashes.diff --git a/docs/x402-offer-receipt/04-bazaar-declaration.md b/docs/x402-offer-receipt/04-bazaar-declaration.mddeleted file mode 100644index f033a498b..000000000--- a/docs/x402-offer-receipt/04-bazaar-declaration.md+++ /dev/null@@ -1,130 +0,0 @@-# Prompt 04 — Declare extension support in bazaar discovery--The signing wiring from prompts [02](02-offer-signing.md) and [03](03-receipt-signing.md) is live. Bazaar crawlers (e.g. agentic.market) won't know your endpoints sign offers and receipts unless you advertise capability in the discovery envelope. This prompt adds that declaration.--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No fake data, no placeholders, no stubs.**--Additional rule for this task:--- **Do not modify `bazaarExtension()` or `buildBazaarSchema()` in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).** Their schemas mirror `@x402/extensions/bazaar` exactly; deviating breaks the crawler. The offer-receipt capability declaration is part of the **402 body's top-level `extensions`**, not part of `bazaar`.--## Background--Two different things live under `extensions`:--| Key | What it is | Per-request? |-|---|---|---|-| `bazaar` | Discovery metadata for crawlers — input/output schemas, descriptions. | Static per endpoint. |-| `offer-receipt` | The signed offers themselves (on 402) or the signed receipt (on 200). | **Dynamic** — generated per request. |--The plan in [00-plan.md](00-plan.md) decided they are **siblings** at the top level of `extensions`, not nested. Prompt 02 already emits the dynamic `offer-receipt` payload on 402 responses. What's missing is the **capability declaration** that a crawler reads at discovery time to know "this endpoint signs offers and receipts."--Per the x402 docs, that declaration comes from `declareOfferReceiptExtension({ includeTxHash, offerValiditySeconds })`. It returns an object describing the extension that gets merged into the discovery envelope.--## Inputs--- Helper exported by the package:- ```js- import { declareOfferReceiptExtension } from '@x402/extensions/offer-receipt';- const declaration = declareOfferReceiptExtension({- includeTxHash: false,- offerValiditySeconds: 60,- });- // Returns something like:- // { 'offer-receipt': { signer: { kid, format: 'eip712' }, includeTxHash: false, offerValiditySeconds: 60 } }- ```-- The current 402 body shape after prompt 02:- ```js- extensions: { bazaar, 'offer-receipt': { signedOffers } } // signing enabled- extensions: { bazaar } // signing disabled- ```-- After this prompt, the shape becomes:- ```js- extensions: {- bazaar,- 'offer-receipt': {- signer: { kid, format: 'eip712' },- includeTxHash: false,- offerValiditySeconds: 60,- signedOffers: [ ... ]- }- }- ```--The **declaration fields** (`signer`, `includeTxHash`, `offerValiditySeconds`) are static and identical across all 9 endpoints. The **dynamic field** (`signedOffers`) is generated per request.--## Task--### 1. Export a declaration helper from the signer module--In [api/_lib/x402-offer-receipt.js](../../api/_lib/x402-offer-receipt.js), add an export:--```js-// Static capability declaration for crawlers. Returns null when the feature-// is disabled, so callers can skip merging it.-export function offerReceiptDeclaration() {- if (!issuer) return null;- return declareOfferReceiptExtension({- includeTxHash: false,- offerValiditySeconds: 60,- });-}-```--`declareOfferReceiptExtension` returns the **whole** `{ 'offer-receipt': { ... } }` object. Be sure to merge correctly so you end up with one `'offer-receipt'` key (not two) in the final `extensions` object.--### 2. Merge the declaration into the 402 body--Update [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) `build402Body`. Take the declaration produced by `offerReceiptDeclaration()` and merge it with the per-request `signedOffers`:--```js-import { signOffersForAccepts, offerReceiptDeclaration } from './x402-offer-receipt.js';--// ...inside build402Body, after computing signedOffers...-const declaration = offerReceiptDeclaration();-const extensions = { bazaar };-if (declaration && signedOffers.length) {- extensions['offer-receipt'] = { ...declaration['offer-receipt'], signedOffers };-} else if (declaration) {- extensions['offer-receipt'] = declaration['offer-receipt'];-}-return { x402Version: X402_VERSION, error, resource: {...}, accepts: [...], extensions };-```--The `signedOffers` array shadows nothing in the declaration (declaration has no `signedOffers` key), so this is a clean merge.--### 3. Confirm `bazaar` is untouched--```bash-git diff api/_lib/x402-spec.js | grep -E 'bazaar(Extension|Schema)' | head-```--This grep should return only context lines — no `+` or `-` lines touching `bazaarExtension` or `buildBazaarSchema` function bodies.--### 4. Sanity test--```bash-npm run dev &-sleep 3-curl -s http://localhost:3000/api/x402/dance-tip?dancer=1\&dance=rumba | jq '.extensions["offer-receipt"]'-```--With `X402_RECEIPT_SIGNING_KEY` set, the output should show **both** the static declaration fields (`signer`, `includeTxHash`, `offerValiditySeconds`) **and** the dynamic `signedOffers` array. With the env unset, the `offer-receipt` key should be absent entirely.--## Definition of done--- [ ] `offerReceiptDeclaration()` is exported from `api/_lib/x402-offer-receipt.js`.-- [ ] `build402Body` merges declaration + `signedOffers` into a single `extensions["offer-receipt"]` object.-- [ ] `bazaarExtension()` and `buildBazaarSchema()` source is unchanged.-- [ ] 402 responses with env set show declaration + signed offers together.-- [ ] 402 responses with env unset show no `offer-receipt` key.-- [ ] `npm test` still passes.-- [ ] `git diff` reviewed.--## Stop conditions--- If `declareOfferReceiptExtension` is not exported from `@x402/extensions/offer-receipt` at the documented path, surface it. Do not hand-roll the declaration shape — it must match what crawlers parse.diff --git a/docs/x402-offer-receipt/05-verification-script.md b/docs/x402-offer-receipt/05-verification-script.mddeleted file mode 100644index fd603654d..000000000--- a/docs/x402-offer-receipt/05-verification-script.md+++ /dev/null@@ -1,108 +0,0 @@-# Prompt 05 — End-to-end verification script--Prompts [01](01-foundation.md) through [04](04-bazaar-declaration.md) have wired the feature. This prompt builds a standalone script that proves the whole chain works against a live (or local) server: hit a paid endpoint, extract and verify the signed offer, pay, extract and verify the signed receipt, confirm the receipt matches the offer.--This is the gate that flips the feature from "wired" to "verified end-to-end." Per [CLAUDE.md](../../CLAUDE.md): a feature is not done until this passes.--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No mocks. No fake data.** Real endpoints, real payment, real verification.-- **No `setTimeout` fake-loading or fake progress bars.** Real async or nothing.--## Inputs--- The signer module from prompt 01.-- A real payer wallet for the script to spend from. Use `X402_TEST_PAYER_KEY` (a separate env var, must be a low-balance test wallet on Base mainnet — never a production wallet).-- The exact bazaar endpoint to test against: [api/x402/dance-tip.js](../../api/x402/dance-tip.js) is the cheapest at $0.001 — use it.-- Verification helpers from `@x402/extensions/offer-receipt`:- - `extractOffersFromPaymentRequired`- - `decodeSignedOffers`- - `verifyOfferSignatureEIP712`- - `extractReceiptFromResponse`- - `verifyReceiptSignatureEIP712`- - `verifyReceiptMatchesOffer`-- Payment client: there's likely an existing test/example client in the repo. Find it with:- ```bash- grep -rln "x-payment" --include="*.js" . | grep -vE 'node_modules|api/_lib|api/x402'- ```- If no suitable client exists, use `@x402/fetch` (install if missing) to handle the 402 challenge automatically.--## Task--Create [scripts/verify-x402-receipts.js](../../scripts/verify-x402-receipts.js) as an executable Node script (`#!/usr/bin/env node`). It must:--### 1. Read config from env or argv--```-node scripts/verify-x402-receipts.js [--base https://three.ws] [--route /api/x402/dance-tip?dancer=1&dance=rumba]-```--Defaults:-- `--base` → `process.env.PUBLIC_APP_ORIGIN` or `http://localhost:3000`-- `--route` → `/api/x402/dance-tip?dancer=1&dance=rumba`-- `X402_TEST_PAYER_KEY` from env (required; fail with a clear error if missing)--### 2. Step 1 — fetch 402 and verify the signed offer--```-fetch(base + route, { method: 'GET' }) // no x-payment header-→ expect status 402-→ body = await res.json()-→ offers = extractOffersFromPaymentRequired(body)-→ decoded = decodeSignedOffers(offers)-→ for each decoded offer, await verifyOfferSignatureEIP712(d.signedOffer)-```--Print one line per offer: `OFFER <network> <kid> -> VERIFIED | FAILED`. Exit non-zero if any fails.--Pick the Base-mainnet offer for the next step. If no Base offer is advertised, exit with a clear `no_base_offer` error.--### 3. Step 2 — pay the selected offer--Use the existing payment client found in the codebase (or `@x402/fetch`) with the test payer key. The exact wiring depends on which client is in use — read its docstring and follow its pattern. Expect a `200` response.--Do **not** swallow payment errors. If the test wallet has insufficient balance, surface the actual error message and exit non-zero. **Do not retry**, **do not fall back to mocks**.--### 4. Step 3 — verify the signed receipt--```-signedReceipt = extractReceiptFromResponse(paidResponse)-→ await verifyReceiptSignatureEIP712(signedReceipt)-→ verifyReceiptMatchesOffer(signedReceipt, selectedOffer, [payerAddress])-```--Print `RECEIPT <kid> -> VERIFIED | FAILED`. Print the receipt's `payload` (resourceUrl, payer, network, issuedAt).--If `verifyReceiptMatchesOffer` fails, dump the offer payload and the receipt payload side by side and exit non-zero — the mismatch tells the operator which field drifted.--### 5. Exit code--- Exit `0` on full success.-- Exit `1` on any verification failure or payment error, with a clear final line: `verify-x402-receipts: FAILED (<reason>)`.--### 6. Add an npm script--In [package.json](../../package.json), add:--```json-"scripts": {- ...- "verify:x402-receipts": "node scripts/verify-x402-receipts.js"-}-```--## Definition of done--- [ ] `scripts/verify-x402-receipts.js` exists, is executable, and uses real payment + verification (no mocks).-- [ ] Against a running `npm run dev` instance (or a deployed `https://three.ws`), it prints `OFFER ... VERIFIED` for every advertised network, `RECEIPT ... VERIFIED`, and exits `0`.-- [ ] With `X402_RECEIPT_SIGNING_KEY` unset on the server, the script exits non-zero with `no_signed_offers_in_response` — confirming the absence test.-- [ ] With a tampered offer (manually flip a byte in the signature), the script exits non-zero with the verifier's error message.-- [ ] `npm run verify:x402-receipts` works as documented.-- [ ] `git diff` reviewed.--## Stop conditions--- If the codebase has no existing way to drive a real x402 payment from a script, **do not** invent one with mocked signatures. Either use `@x402/fetch` (real implementation), or surface that you need the operator to install a real client. The whole point of this script is to be real.-- If `verifyReceiptMatchesOffer` requires the payer address but the test client doesn't expose it, derive it deterministically from `X402_TEST_PAYER_KEY` via `privateKeyToAccount(...).address`. That's the real address, not a mock.diff --git a/docs/x402-offer-receipt/06-completionist-and-push.md b/docs/x402-offer-receipt/06-completionist-and-push.mddeleted file mode 100644index f684720cc..000000000--- a/docs/x402-offer-receipt/06-completionist-and-push.md+++ /dev/null@@ -1,111 +0,0 @@-# Prompt 06 — Completionist pass + push to both remotes--Prompts [01](01-foundation.md)–[05](05-verification-script.md) have wired and verified the feature. This is the final gate before shipping: audit the diff against [CLAUDE.md](../../CLAUDE.md)'s hard rules, fix anything flagged, then push to both GitHub remotes.--## Project rules (must follow)--From [CLAUDE.md](../../CLAUDE.md):--- **No mocks. No fake data. No placeholders.**-- **No TODO comments. No stubs.**-- **No commented-out code.**-- **No `throw new Error("not implemented")`.**-- **No `setTimeout` fake-loading.**-- **No fallback sample arrays shipped to production.**-- **Errors handled at boundaries only.**-- Push to **both** `origin` (3D-Agent) **and** `threews` (three.ws) remotes. Never push without explicit user approval. Never force-push.--## Task--### 1. Verify the feature is wired end-to-end--Before auditing, confirm the feature works:--```bash-# With X402_RECEIPT_SIGNING_KEY set in your local .env:-npm run dev &-sleep 3-npm run verify:x402-receipts-# Expect: every OFFER VERIFIED, RECEIPT VERIFIED, exit 0-```--If this fails, **stop** — go back to whichever prompt the failure points to. Do not push a broken feature.--### 2. Run the completionist audit--From [CLAUDE.md](../../CLAUDE.md): "Before stopping on a feature task, run the **completionist** subagent to audit your changed files for the rules above. Fix every item it flags. Then stop."--Run the completionist on the diff:--```bash-git status-git diff main -- api/_lib/ scripts/ package.json .env.example-```--Spawn the completionist subagent with the full diff and the list of changed files. Fix every flagged item — no exceptions. Re-run the audit until it returns clean.--### 3. Sanity check against the full Definition of Done in [00-plan.md](00-plan.md)--Go through the plan's DoD checklist line by line. For each unchecked item, either check it (with evidence) or fix the underlying issue. The list:--- [ ] `X402_RECEIPT_SIGNING_KEY` documented in `.env.example`, real value in local `.env`, configured in Vercel `production` + `preview` (operator confirms this — surface it explicitly if you can't verify Vercel state).-- [ ] `npm test` passes.-- [ ] Paid endpoints return `402` with `extensions["offer-receipt"].signedOffers[]` — verify with the script.-- [ ] Paid endpoints return `200` with `x-payment-response` containing a verifiable `signedReceipt` — verify with the script.-- [ ] `scripts/verify-x402-receipts.js` exits `0`.-- [ ] No handler in `api/x402/*.js` was modified (`git diff main -- api/x402/`).-- [ ] Completionist returns clean.-- [ ] Ready to push to **both** remotes.--### 4. Commit--Stage only the files this feature touched. Do **not** `git add .` — there are unrelated modifications in the working tree (see `git status` from the start of this session: `api/_lib/x402-paid-endpoint.js`, `api/_lib/x402-permit2.js` deletion, `api/_lib/x402-spec.js`, `api/wk.js`, `api/x402-status.js`, `public/x402.js`, `vercel.json`). Some of those may overlap with our changes; verify carefully.--Use the project's commit-message style (check `git log` for tone). Single commit, descriptive:--```-feat(x402): signed offers on 402 + signed receipts on 200--Wires the x402 Offer & Receipt extension into the shared paidEndpoint-wrapper so every paid endpoint signs offers on 402 challenges and-receipts on 200 deliveries. EIP-712 signing under did:pkh, controlled-by X402_RECEIPT_SIGNING_KEY (unset = feature off, byte-identical to-prior behaviour).--Co-Authored-By: Claude Opus 4.7 <[email protected]>-```--(Pass via HEREDOC per [CLAUDE.md](../../CLAUDE.md)'s git protocol.)--### 5. Push to BOTH remotes--```bash-git push origin <branch>-git push threews <branch>-```--If either push fails, surface the error and stop. **Do not** silently leave the repos out of sync. **Do not** force-push.--### 6. Confirm--After both pushes succeed, print a short summary:--- Files changed (count + key paths).-- Verification script status.-- Both push targets and their resulting commit SHAs.--## Definition of done--- [ ] `npm run verify:x402-receipts` passes end-to-end against a live server.-- [ ] Completionist audit returns clean.-- [ ] All plan DoD items checked.-- [ ] One descriptive commit on the working branch.-- [ ] `git push origin` succeeded.-- [ ] `git push threews` succeeded.-- [ ] Summary printed.--## Stop conditions--- If the completionist flags issues you cannot fix without changing locked-in decisions from [00-plan.md](00-plan.md), surface the conflict instead of overriding the plan unilaterally.-- If `git push` to either remote fails (auth, hook rejection, conflict), surface the error verbatim. Do not retry destructively, do not skip hooks, do not force-push.-- If unrelated modifications in the working tree (the ones listed in step 4) are intermixed with the feature changes, ask the operator how to split before committing. Do not lump unrelated work into the feature commit.