Skip to content

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

feat: add external service uptime monitor and subscription health check pipelines

nirholas2e52aa34220d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7721b5419..d70df3ef6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,14 +20,18 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Activation, upgraded — Live badges, one-call agent activation, and a Go Live first step** — Bringing an agent to life is now front-and-center and easier for people and agents alike. Right after you create an agent, "Go live" is the first thing offered. Agents that have claimed their welcome grant now wear a "◉ Live" badge across the marketplace so funded, active agents stand out, and their live status is published in each agent's manifest. Developers and autonomous agents can activate in a single call with the three.ws SDK (client.activate(agentId)). Behind the scenes, activating now also registers the agent's payout wallet so it can earn from day one, and counts toward referral rewards when you were invited. We also hardened the on-chain grant so it can never be sent twice. (`/marketplace`) `[feature, improvement, sdk]`
- **Agent Wallet Balance Monitor — the autonomous payment engine watches its own fuel gauge** — The wallet that funds every autonomous x402 payment now monitors itself. Every 10 minutes the platform reads the agent wallet's live USDC and SOL balance, records a time-series sample, and works out the burn rate since the last reading so operators can see exactly how fast funds are being spent. The moment USDC drops below the $5 top-up line it raises a low-balance alert that folds straight into the internal health dashboard — so the wallet gets refilled before autonomous calls start failing on insufficient funds, instead of after. The check reads a free endpoint, so the monitoring itself costs nothing. `[infra]`
- **Alibaba Cloud partnership — Qwen models and alibaba-cloud-mcp** — three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate. (`/blog/three-ws-alibaba-cloud-partnership`) `[feature]`
+- **API Key Bypass Security Test — the platform audits its own paywall for free-access leaks every day** — Some callers are allowed to skip the per-call payment on three.ws's paid APIs: internal services and partners who hold a valid API key. That bypass is a trapdoor — if a code change ever widened it so a missing or wrong key also slipped through, anyone could drain the paid endpoints for free, and nobody would notice. The platform now watches that trapdoor continuously. Once a day an autonomous agent runs a full bypass drill against the live payment endpoints: it mints a real, short-lived partner key and confirms it grants free access exactly as intended; it presents a made-up invalid key and confirms access is denied; it knocks with no key at all and confirms the normal payment wall still appears; then it revokes its test key and confirms that very same key is now rejected. It runs the drill against two endpoints that share the bypass logic but invoke it differently, so a change that breaks one path can't hide behind the other. To close the loop it makes one real on-chain $0.001 payment through the no-key wall to prove that paying still works end to end. If the wall ever lets a missing or invalid key through, that's a free-access leak: the platform records it, raises a critical operations alert, and flags it on the internal health check so it can be shut immediately. The test key always self-expires within minutes and is revoked the moment the drill finishes, so the audit can never leave a live key behind. `[security, infra]`
- **Autonomous agent reputation refresh — trust scores that keep themselves current** — The platform now refreshes the on-chain reputation of registered Solana agents on its own. A scheduled pipeline pays the agent-reputation service per agent over x402, recomputes each agent's verified feedback score, dispute rate and validation record from on-chain attestations, and flags any agent whose verified trust score drops below threshold. These scores power the agent reputation leaderboard and the trust badges on agent profiles, so you can vet a counterparty before paying it, trading with it, or composing skills with it — and a score that slips is caught automatically rather than going stale. `[feature]`
- **Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades** — The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting. (`/admin/launcher`) `[feature, improvement]`
- **Autonomous x402 Spend Loop — platform pays its own endpoints and learns from every call** — The platform's x402 seed wallet now actively participates in the agent economy on a 5-minute cron cycle. Every tick it selects up to 8 endpoints from a priority-ranked registry (oracle intel, sniper support, health checks, volume) and makes real USDC payments to each — recording every transaction to x402_autonomous_log with the full signal payload. Oracle-pipeline calls (crypto-intel for SOL/BTC/ETH/pump, $THREE signal feed) feed a new oracle_intel_signals table that the agent sniper reads directly: bullish macro signals lower the conviction threshold so the sniper fires more freely; bearish signals raise it. The loop also enforces a daily spend cap (default $5/day) and per-entry Redis cooldowns. This is the first time three.ws earns intelligence through payments and uses it to make better autonomous trading decisions. `[feature, infra]`
- **Avatar Optimization Pipeline — nightly analysis of top avatars** — The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch. `[feature, infra]`
+- **Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit** — When another agent pays a three.ws endpoint, the network can credit that volume back to three.ws as a builder reward — but only if the endpoint stamps its on-chain attribution code on the payment. If a single paid endpoint ever quietly drops that stamp, every dollar it settles still works for the buyer yet earns three.ws nothing, and until now nothing would have noticed. The platform now watches for exactly that. Every six hours an autonomous agent walks a representative set of paid endpoints and, for each, makes a free request to read its payment terms and confirm the attribution code is present and correct. Any endpoint missing or mismatching its code is flagged as a gap — real revenue at risk of going uncredited. The tracker then goes one step further and makes one real $0.001 payment to the cheapest endpoint with its own attribution stamp attached, confirming end-to-end that an attributed payment actually settles on-chain — the very transaction the reward program reads. The results feed the platform's internal health check, so operators are alerted to a lost-rewards gap within hours instead of discovering it when a payout comes up short. The whole sweep costs a fraction of a cent a day. `[feature, infra]`
- **Capabilities dashboard — live command center for all 4 autonomous features** — New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords. (`/dashboard/capabilities`) `[feature, improvement]`
- **CAPTCHA relief for rate-limited sign-ins** — Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service). (`/login`) `[improvement, security]`
+- **Cross-Chain Payment Cost Comparison — the platform measures which network is cheaper to pay on, live** — three.ws settles agent payments on both Solana and Base, and the cheaper rail isn't always obvious — gas prices move all day. The platform now measures it directly. Every hour an autonomous agent makes one real on-chain $0.001 USDC payment on Solana and reads the actual fee that transaction paid, then prices the exact same payment on Base from the live Base gas price and the real cost of a USDC transfer there. It converts both to dollars using live SOL and ETH prices, works out the all-in cost on each network, and tracks the gas premium between them over time — how many times more (or less) expensive Base is than Solana right now. The latest reading and a rolling average are published at /api/x402/network-cost, along with a clear recommendation of the cheaper network to settle on, so the platform can steer payments to the cheaper rail and keep default pricing honest. Each measurement settles on Solana with a real transaction signature and is logged like every other autonomous payment; the hourly pace keeps the cost to a few cents a day. `[feature, infra]`
- **Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive** — Every hour an autonomous agent runs the cheapest possible end-to-end test of the platform's payment rails. It reads the live payment challenge from a $0.001 endpoint and confirms a valid settlement route is still advertised on all three supported networks — Solana, Base, and BSC — then makes one real $0.001 USDC payment on Solana to prove the full build → verify → settle → receipt path actually completes on-chain, not just that the route exists. The per-network result is stored (x402_circuit_breaker) and folded into the internal health dashboard, so the moment a facilitator route goes dark or settlement breaks, it trips and shows up immediately instead of being discovered by a failed user payment. `[infra]`
- **Design your own Memetic Launcher** — Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu. (`/launcher`) `[feature]`
+- **External Service Uptime Monitor — the platform checks every outside service is alive before it pays one** — three.ws doesn't only get paid by other agents — it also pays outside x402 services for things like market data and intelligence. Those services live in a registry the platform builds automatically as it discovers them. If one quietly goes dark, a payment pipeline can waste a turn — or worse, start a payment — on a dead endpoint. The platform now guards against that. Every 15 minutes an autonomous agent walks the full list of external services it depends on and gives each a quick, free knock on the door: a lightweight request that asks 'are you there?' without ever sending money. A service that answers with a payment request is live and healthy; one that's reachable but answering oddly is flagged; one returning server errors or failing to respond at all is marked down. The platform tracks how many checks in a row each service has failed, and when something has been down long enough, paying pipelines automatically skip it instead of throwing good money at a dead address — then start using it again the moment it recovers. The whole sweep is free and never touches the payment wallet, and every check is logged so operations can see at a glance which outside services are up, which are flaky, and which have gone away. `[infra, improvement]`
- **Fixed /play getting stuck on "too many requests"** — Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry. (`/play`) `[fix]`
- **GLB Size Optimizer — heavy avatars audited and slimmed down automatically** — Big 3D avatars are the slowest thing to load on three.ws, so the platform now hunts them down on its own. Every six hours an autonomous agent finds the heaviest public avatar over the 5 MB web-delivery budget that hasn't been checked recently and pays a real x402 call to the optimize_model service to inspect it. From the model's actual measured geometry and textures it works out exactly how much smaller the file could be — Draco geometry compression, 4K textures resized to 2K, PNG textures transcoded to KTX2 — and projects the resulting download-time improvement at typical mobile bandwidth. Each result is stored with the original size, the projected optimized size, and the load-time saving, then swept across the whole catalog so the gallery can show a 'save ~N%' hint per model and the platform can track its average load-time improvement. The new public report at /api/x402/glb-optimization-report surfaces the catalog-wide savings and the remaining backlog of heavy models. `[feature, improvement]`
- **Hardened how the platform reads its rate-limit store credentials** — Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable. (`/status`) `[fix, infra]`
@@ -54,13 +58,16 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Production stability fixes — payment sessions, Redis error handling, infra resilience** — Fixed a SQL syntax error that blocked payment session expiry and refunds (PostgreSQL does not allow LIMIT directly in UPDATE — now uses a CTE with FOR UPDATE SKIP LOCKED). Fixed esbuild class-name minification breaking NeonDB error detection in production — infrastructure errors (wrong DB credentials, Redis auth) now correctly return 503 and suppress alert storms instead of crashing every endpoint with 500. Added graceful Redis-unavailable handling to the usage flush buffer and the bounty board API. Fixed Express-style response methods in pulse-tick cron. `[fix, infra]`
- **Restored token-launch, agent payments, and on-chain endpoints** — Fixed a class of missing API route mappings that left several backend endpoints unreachable in production: token launch (quote, prep, confirm), agent-to-agent payments, on-chain transaction prep/confirm, Solana and EVM checkout, and live-walk session control. The handlers were deployed but never wired to their public paths; they now respond correctly. Part of a wider audit that also restored wallet sign-in. `[fix]`
- **Reviews anchored on-chain — Solana attestations + ERC-8004 reputation** — Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click "Anchor on Base" step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row. (`/marketplace`) `[feature, improvement]`
+- **Rig Complexity Scorer — the platform pays to grade how heavy each avatar is to run** — A 3D avatar that looks identical to another can be ten times heavier to render — more bones, more geometry, bigger textures — and that difference is invisible until it stutters on someone's phone. three.ws now measures it. An autonomous agent works through the avatars in the gallery, and for each one makes one real on-chain x402 payment to the platform's own model-inspection service to read the avatar's actual structure: bone count, vertex and triangle counts, texture sizes, and file weight. From those it computes a single 0-100 complexity score and a tier — light, standard, heavy, or extreme — plus a performance warning flag that trips when any one dimension (a half-million vertices, an 8K texture, a 75 MB file) is heavy enough to hurt on mobile. Each result is stored against the avatar so the marketplace can tier listing prices by how demanding a model is and show a 'performance-heavy' badge before a buyer commits. It only scores avatars it hasn't seen or that changed since the last check, so once the gallery is graded the ongoing cost falls to nearly nothing; every paid call settles on Solana with a real transaction signature and is logged like every other autonomous payment. `[feature, infra]`
- **Scene Capture auto-processing — upload a video, get a 3D point cloud back** — Videos uploaded on /capture are now reconstructed into 3D point clouds automatically, with no waiting on the page. Each upload joins a processing queue that an autonomous agent drains on a 2-minute cadence: it pays a $0.01 USDC processing credit via x402, hands the video to the LingBot-Map GPU worker, then polls until the .ply point cloud is ready and stores the result on the job. When you come back, the finished cloud renders directly in the /capture viewer. Every run — submit, poll, success or failure — is recorded for full auditability, and the pipeline degrades cleanly when the GPU worker or wallet isn't configured. (`/capture`) `[feature, infra]`
- **Sign-in cooldown is now exact — and there's more headroom before it trips** — If you ever hit "too many attempts" while signing in, the form now shows the real countdown the server hands back — a live timer on the button that ticks down and re-arms the form the instant you can try again, instead of a vague "try later". We also raised the per-network attempt allowance, so people signing in from shared office or campus connections are far less likely to be told to wait at all. Wrong-password and network-drop messages are now clearer and distinct, too. (`/login`) `[improvement]`
- **Sign-in restored during rate-limiter outages** — Fixed an issue where a temporary outage of the distributed rate limiter could block every sign-in attempt platform-wide. The login and registration limiters now degrade gracefully to a local per-instance cap during such an outage — keeping sign-in available while still throttling brute-force attempts — instead of denying everyone. Money-moving limits are unchanged and still fail safe. `[fix, security]`
- **Sign-up and 3D avatar reliability fixes** — Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic. (`/register`) `[fix]`
+- **Sniper Intel Enrichment — the trading engine pays its own intelligence feed to sharpen every snipe** — The platform's auto-sniper decides whether to buy a freshly launched coin in milliseconds, and it now pays for a better read before it commits. On a 15-minute cycle an autonomous agent takes the coins the sniper is actively watching — the ones it currently holds and the freshest high-conviction candidates — and, for each, makes one real on-chain x402 payment to the platform's own Crypto Intel feed for a live market signal: bullish, bearish, or neutral, with a confidence and a headline. That signal becomes a small, capped adjustment to the bar a coin must clear to get bought: a bearish read makes the sniper more cautious, a bullish read slightly more willing, and a neutral read changes nothing. It's the platform's most direct self-loop — the trading engine paying the platform's intelligence API to make better decisions, every payment settling on Solana with a real transaction signature. There's a built-in honesty guard: the intelligence feed only answers for coins it can actually price, so a brand-new memecoin with no real market simply returns no data and is never charged or given a borrowed signal. The adjustment is always small and fails open, so it can only ever nudge a decision — never block a trade on its own. `[feature, infra]`
- **Solana Agent Registration Health Check — the on-chain identity rails watch themselves** — Registering an agent on Solana is one of three.ws's core promises: the platform mints the agent's on-chain Metaplex identity and enrols it in the Agent Registry, custodially, so the agent's own wallet never has to sign. Now that whole path is watched automatically. Four times a day an autonomous agent pays a real x402 canary call that resolves a known registered agent's on-chain record — both its Identity registry account and its Core identity asset — and confirms they still exist on the live chain through the platform's failover RPC pool. A healthy result resets the counter; a sustained failure escalates to an alert so registration outages are caught before the next agent tries to register and fails. Every probe is recorded with its on-chain check results and RPC latency, giving the status surface a continuous read on whether agent registration is actually working end-to-end. `[feature, infra]`
- **SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly** — Every five minutes an autonomous agent makes one real paid call to the platform's MCP server in streaming (SSE) mode and reads the response back as a live stream instead of a single buffered blob. It measures how fast the first byte arrives, the gaps between chunks, the chunk count and total bytes, and confirms the on-chain payment actually settled — then classifies the stream as clean, stalled, or dropped. A hung server, a half-delivered response, or broken chunked encoding now trips immediately and pages ops, with the full streaming-integrity history stored (mcp_stream_health) for the status surface, instead of being discovered by a paying agent whose tool call never finished. It runs on the x402 autonomous spend loop using the platform's own wallet. `[infra]`
- **Status page goes monochrome — with a fleet summary and an embeddable status badge** — The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object. (`/status`) `[feature, improvement]`
+- **Subscription Status Health Check — the platform warns API subscribers before their key expires** — Partners and agents who pay for ongoing access to three.ws's paid APIs hold a subscription key that lets them skip the per-call payment until it expires or is revoked. When one of those keys quietly lapses, the integration on the other side suddenly starts getting charged per call or rejected outright — a surprise outage that looks like our fault. The platform now prevents that. Once a day an autonomous agent enumerates every active subscription, checks each one's status, and works out how many days are left before it expires. Any key inside its final week triggers a heads-up email to the subscriber — once per expiry window, so a renewal re-arms the warning rather than spamming — telling them exactly when access ends and how to renew before it does. Every subscription's current state (active, expiring soon, expired, or revoked) is recorded so the admin dashboard can badge keys that need attention and operations can catch a lapse before it interrupts anyone. The whole sweep is read-only and runs on the platform's own internal access, so it costs nothing and never touches the payment wallet. `[feature, improvement]`
- **Task input on Agent Screen — send your agent a task and watch it work** — You can now type any task directly into the Agent Screen page and your agent picks it up in real time. The live screen panel has a new command bar at the bottom: type what you want your agent to do (research, browse, shop, monitor, trade) and hit send. The task is queued via /api/agent-task and the running worker executes it with Stagehand, streaming every browser action back to the live screen as it happens. The worker automatically checks for new tasks every 3 seconds and runs them in priority order, falling back to its autonomous loop when the queue is empty. (`/agent-screen`) `[feature, improvement]`
- **The launcher now reads Know Your Meme** — The autonomous coin launcher gained a new culture feed: Know Your Meme. It reads the freshly-confirmed meme entries and the live meme newsfeed, fuses them with the platform's on-chain signals, and rides the strongest wave when an agent coins its next launch — so new launches track the memes actually entering culture right now, not stale themes. As always, only the cultural THEME is mined; names and tickers are invented fresh, never copied, and every coin stays avatar-fronted and $THREE-aligned. `[feature, improvement]`
- **Token Intel Pre-Snipe Gate — the sniper pays for due diligence before it buys** — Before the agent sniper commits SOL to a fresh launch, the platform now buys it a second opinion. An autonomous pipeline pays the platform's own $0.01 Token Oracle over x402 for the most active new mints the sniper is about to consider, turning the live due-diligence read — liquidity depth, pair age, float-to-liquidity, and 24h buy/sell flow — into a 0–100 rugpull-risk score per mint. Any mint that scores high or critical is auto-rejected at the pre-snipe gate across every entry path (new-mint, first-claim, intel-confirmed, prelaunch radar), so the trading engine never commits funds to a launch its own oracle has flagged as a likely rug. The check is fail-open and cached: a missing or stale verdict never blocks a trade, it only ever adds a safety floor. (`/oracle`) `[feature, infra]`
diff --git a/agents/x402-buildout/self/agent-registration-sweep.md b/agents/x402-buildout/self/agent-registration-sweep.md
new file mode 100644
index 000000000..bc0c7b24a
--- /dev/null
+++ b/agents/x402-buildout/self/agent-registration-sweep.md
@@ -0,0 +1,41 @@
+# 055: Agent Registration: Active Agent Sweep
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/agent-reputation` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/agent-reputation`
+- **Method:** POST
+- **Body:** `{"mode":"sweep","limit":20}`
+
+## What to Build
+Pay x402 to fetch reputation scores for the 20 most recently active agents. Extract { count, avg_score, flagged_count }. Flag any agent with score < 30 for review. Store signal_data for platform trust monitoring.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/agent-reputation`
+ - `body`: `{"mode":"sweep","limit":20}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-agent-leaderboard.md b/agents/x402-buildout/self/analytics-agent-leaderboard.md
new file mode 100644
index 000000000..775f7e910
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-agent-leaderboard.md
@@ -0,0 +1,41 @@
+# 043: Analytics: Agent Leaderboard
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"agent_leaderboard","limit":10}`
+
+## What to Build
+Fetch top 10 agents by x402 spend this week. Extract rankings, agent IDs, and spend amounts. Store { top_agent_id, top_agent_spend_usdc }. Use to identify high-value agents for partnership outreach.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"agent_leaderboard","limit":10}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-club-activity.md b/agents/x402-buildout/self/analytics-club-activity.md
new file mode 100644
index 000000000..4dea0685a
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-club-activity.md
@@ -0,0 +1,41 @@
+# 045: Analytics: Club Social Activity
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"clubs","period":"24h"}`
+
+## What to Build
+Retrieve club activity metrics: active clubs, total members, cover charges collected. Use to monitor social economy health and identify growing clubs.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"clubs","period":"24h"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-marketplace-catalog.md b/agents/x402-buildout/self/analytics-marketplace-catalog.md
new file mode 100644
index 000000000..bf288dbbf
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-marketplace-catalog.md
@@ -0,0 +1,41 @@
+# 044: Analytics: Marketplace Catalog Stats
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"marketplace","period":"7d"}`
+
+## What to Build
+Pull marketplace listing stats: total active listings, avg price, most viewed. Extract { listing_count, avg_price_sol, most_viewed_id }. Wire into health pipeline to verify marketplace is alive.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"marketplace","period":"7d"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-revenue-dashboard.md b/agents/x402-buildout/self/analytics-revenue-dashboard.md
new file mode 100644
index 000000000..d9f2d2743
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-revenue-dashboard.md
@@ -0,0 +1,41 @@
+# 039: Analytics: Revenue Dashboard Aggregation
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"revenue","period":"24h"}`
+
+## What to Build
+Call the analytics x402 endpoint to pull the last 24 hours of revenue data. Extract total earnings per endpoint, fee splits, and net platform revenue. Store signal_data with { total_usd, top_endpoint, fee_collected }. Wire into the autonomous loop under the oracle pipeline so the sniper sees platform health data.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"revenue","period":"24h"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-sniper-performance.md b/agents/x402-buildout/self/analytics-sniper-performance.md
new file mode 100644
index 000000000..7a3fcfed6
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-sniper-performance.md
@@ -0,0 +1,41 @@
+# 041: Analytics: Sniper Trade Performance
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"sniper_trades","period":"24h"}`
+
+## What to Build
+Pay to retrieve sniper trade analytics: win rate, avg profit, worst loss, total volume snipped. Extract { win_rate, avg_profit_usdc, total_volume_sol }. Useful for strategy auto-tuning — if win_rate drops below 40%, the loop should log an alert.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"sniper_trades","period":"24h"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-user-activity.md b/agents/x402-buildout/self/analytics-user-activity.md
new file mode 100644
index 000000000..e049a6cf6
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-user-activity.md
@@ -0,0 +1,41 @@
+# 040: Analytics: User Activity Heatmap
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"user_activity","period":"7d"}`
+
+## What to Build
+Fetch weekly user activity metrics via x402 payment. Extract DAU, WAU, top features used, and session lengths. Store signal_data with { dau, wau, top_feature }. Schedule every 6 hours in the registry.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"user_activity","period":"7d"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/analytics-x402-volume.md b/agents/x402-buildout/self/analytics-x402-volume.md
new file mode 100644
index 000000000..f646e38ff
--- /dev/null
+++ b/agents/x402-buildout/self/analytics-x402-volume.md
@@ -0,0 +1,41 @@
+# 042: Analytics: x402 Volume Metrics
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/analytics` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/analytics`
+- **Method:** POST
+- **Body:** `{"report":"x402_volume","period":"24h"}`
+
+## What to Build
+Retrieve x402 transaction volume across all endpoints. Extract total_calls, total_usdc_paid, unique_payers. Useful for proving ecosystem growth and identifying underused endpoints.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/analytics`
+ - `body`: `{"report":"x402_volume","period":"24h"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/bazaar-new-listings.md b/agents/x402-buildout/self/bazaar-new-listings.md
new file mode 100644
index 000000000..dc9ccef3c
--- /dev/null
+++ b/agents/x402-buildout/self/bazaar-new-listings.md
@@ -0,0 +1,41 @@
+# 059: Bazaar: New Listing Feed
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/bazaar-feed` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/bazaar-feed`
+- **Method:** POST
+- **Body:** `{"filter":"new","limit":10}`
+
+## What to Build
+Pay x402 to retrieve the 10 newest bazaar listings. Extract { count, newest_id, newest_price, categories }. Run every 30 minutes to keep the bazaar catalog warm and detect listing spikes that indicate agent marketing activity.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/bazaar-feed`
+ - `body`: `{"filter":"new","limit":10}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/bazaar-price-trends.md b/agents/x402-buildout/self/bazaar-price-trends.md
new file mode 100644
index 000000000..cdb13f990
--- /dev/null
+++ b/agents/x402-buildout/self/bazaar-price-trends.md
@@ -0,0 +1,41 @@
+# 060: Bazaar: Price Trend Monitor
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/bazaar-feed` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/bazaar-feed`
+- **Method:** POST
+- **Body:** `{"filter":"price_trends","period":"24h"}`
+
+## What to Build
+Pay to fetch 24h price trend data for bazaar listings. Extract { trending_up: [], trending_down: [], stable_count }. Feed price pressure signals into oracle_intel_signals to help the sniper understand NFT/asset market sentiment.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/bazaar-feed`
+ - `body`: `{"filter":"price_trends","period":"24h"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/club-membership-snapshot.md b/agents/x402-buildout/self/club-membership-snapshot.md
new file mode 100644
index 000000000..ab231285d
--- /dev/null
+++ b/agents/x402-buildout/self/club-membership-snapshot.md
@@ -0,0 +1,41 @@
+# 066: Club: Membership Snapshot
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/club-cover` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/club-cover`
+- **Method:** POST
+- **Body:** `{"club":"three_holders","mode":"snapshot"}`
+
+## What to Build
+Pay club cover to take a membership snapshot for the three_holders club. Extract { member_count, active_last_7d, new_this_week }. Monitor for membership growth or churn. Run daily.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/club-cover`
+ - `body`: `{"club":"three_holders","mode":"snapshot"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/club-revenue-summary.md b/agents/x402-buildout/self/club-revenue-summary.md
new file mode 100644
index 000000000..20e3423b6
--- /dev/null
+++ b/agents/x402-buildout/self/club-revenue-summary.md
@@ -0,0 +1,41 @@
+# 067: Club: Cover Charge Revenue Summary
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/club-cover` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/club-cover`
+- **Method:** POST
+- **Body:** `{"mode":"revenue","period":"7d"}`
+
+## What to Build
+Pay x402 to retrieve 7-day cover charge revenue across all clubs. Extract { total_usdc, top_club_id, top_club_revenue }. Monitor social economy monetization health.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/club-cover`
+ - `body`: `{"mode":"revenue","period":"7d"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/did-registry-sweep.md b/agents/x402-buildout/self/did-registry-sweep.md
new file mode 100644
index 000000000..f071c08c4
--- /dev/null
+++ b/agents/x402-buildout/self/did-registry-sweep.md
@@ -0,0 +1,41 @@
+# 068: DID: Registry Health Sweep
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/did` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/did`
+- **Method:** POST
+- **Body:** `{"mode":"sweep","limit":10}`
+
+## What to Build
+Pay x402 to sweep the DID registry for the 10 most recently created DIDs. Verify resolution works for each. Extract { count, resolvable_count, failed_count }. Alert if failed_count > 0.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/did`
+ - `body`: `{"mode":"sweep","limit":10}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/did-verification-canary.md b/agents/x402-buildout/self/did-verification-canary.md
new file mode 100644
index 000000000..c1f5ec420
--- /dev/null
+++ b/agents/x402-buildout/self/did-verification-canary.md
@@ -0,0 +1,41 @@
+# 069: DID: Verification Canary
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/did` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/did`
+- **Method:** POST
+- **Body:** `{"did":"did:three:canary","mode":"verify"}`
+
+## What to Build
+Pay x402 to verify a known canary DID and confirm the resolver returns the correct document. Extract { verified: bool, latency_ms }. Fails if latency > 1500ms or document is malformed.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/did`
+ - `body`: `{"did":"did:three:canary","mode":"verify"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/forge-generation-health.md b/agents/x402-buildout/self/forge-generation-health.md
new file mode 100644
index 000000000..7cd0b3bed
--- /dev/null
+++ b/agents/x402-buildout/self/forge-generation-health.md
@@ -0,0 +1,41 @@
+# 072: Forge: Content Generation Health
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/forge` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/forge`
+- **Method:** POST
+- **Body:** `{"mode":"health_check","type":"text","prompt":"Write one sentence about Solana."}`
+
+## What to Build
+Pay x402 to run a minimal forge content generation request. Verify it completes within 5 seconds. Extract { generated: bool, latency_ms, token_count }. If latency > 5000ms, log a forge performance alert.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/forge`
+ - `body`: `{"mode":"health_check","type":"text","prompt":"Write one sentence about Solana."}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/mcp-tool-catalog-sync.md b/agents/x402-buildout/self/mcp-tool-catalog-sync.md
new file mode 100644
index 000000000..32d94f09b
--- /dev/null
+++ b/agents/x402-buildout/self/mcp-tool-catalog-sync.md
@@ -0,0 +1,41 @@
+# 061: MCP Tool: Catalog Sync Probe
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/mcp-tool-catalog` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/mcp-tool-catalog`
+- **Method:** POST
+- **Body:** `{"mode":"sync"}`
+
+## What to Build
+Pay x402 to sync the MCP tool catalog and verify all tools are registered correctly. Extract { tool_count, missing_count, last_sync }. Run every hour. Alert if tool_count drops unexpectedly — it could indicate MCP server degradation.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/mcp-tool-catalog`
+ - `body`: `{"mode":"sync"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/mcp-tool-discovery.md b/agents/x402-buildout/self/mcp-tool-discovery.md
new file mode 100644
index 000000000..3a343832d
--- /dev/null
+++ b/agents/x402-buildout/self/mcp-tool-discovery.md
@@ -0,0 +1,41 @@
+# 062: MCP Tool: New Tool Discovery
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/mcp-tool-catalog` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/mcp-tool-catalog`
+- **Method:** POST
+- **Body:** `{"mode":"discover"}`
+
+## What to Build
+Pay x402 to discover newly registered MCP tools since the last probe. Extract { new_tools: [], total_tools }. Run every 2 hours. New tools are logged for agent feature flagging.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/mcp-tool-catalog`
+ - `body`: `{"mode":"discover"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/pay-by-name-resolution.md b/agents/x402-buildout/self/pay-by-name-resolution.md
new file mode 100644
index 000000000..54254d252
--- /dev/null
+++ b/agents/x402-buildout/self/pay-by-name-resolution.md
@@ -0,0 +1,41 @@
+# 054: Pay-By-Name: Known Wallet Resolution
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/pay-by-name` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/pay-by-name`
+- **Method:** POST
+- **Body:** `{"name":"three.ws"}`
+
+## What to Build
+Pay x402 to resolve three.ws platform wallet name to on-chain address. Validates the pay-by-name registry is functioning. Extract { name, address, verified }. Run every 10 minutes as health check.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/pay-by-name`
+ - `body`: `{"name":"three.ws"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/pump-launch-monitor.md b/agents/x402-buildout/self/pump-launch-monitor.md
new file mode 100644
index 000000000..78a557ec3
--- /dev/null
+++ b/agents/x402-buildout/self/pump-launch-monitor.md
@@ -0,0 +1,41 @@
+# 046: Pump Launch Monitor: Recent Launches
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/pump-agent-audit` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/pump-agent-audit`
+- **Method:** POST
+- **Body:** `{"limit":10,"sort":"newest"}`
+
+## What to Build
+Pay x402 to audit the 10 most recently launched pump.fun tokens. Extract { count, newest_mint, newest_name, avg_initial_liquidity }. Wire into sniper pipeline — new launches with high initial liquidity are snipe candidates.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/pump-agent-audit`
+ - `body`: `{"limit":10,"sort":"newest"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/pump-trending-score.md b/agents/x402-buildout/self/pump-trending-score.md
new file mode 100644
index 000000000..f7ccaaeb5
--- /dev/null
+++ b/agents/x402-buildout/self/pump-trending-score.md
@@ -0,0 +1,41 @@
+# 047: Pump Trending Score Feed
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/crypto-intel` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/crypto-intel`
+- **Method:** POST
+- **Body:** `{"topic":"pump_trending"}`
+
+## What to Build
+Pay for pump.fun trending intelligence. Extract trending mints, buy pressure scores, and whale activity. Feed directly into oracle_intel_signals with topic=pump so the sniper gate adjusts automatically.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/crypto-intel`
+ - `body`: `{"topic":"pump_trending"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/pump-volume-anomaly.md b/agents/x402-buildout/self/pump-volume-anomaly.md
new file mode 100644
index 000000000..1ce963a79
--- /dev/null
+++ b/agents/x402-buildout/self/pump-volume-anomaly.md
@@ -0,0 +1,41 @@
+# 048: Pump Volume Anomaly Detection
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/crypto-intel` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/crypto-intel`
+- **Method:** POST
+- **Body:** `{"topic":"pump_volume_anomaly"}`
+
+## What to Build
+Call crypto-intel with pump_volume_anomaly topic to detect abnormal trading volume on pump.fun in the last hour. Extract { anomaly: bool, mint, volume_ratio }. If anomaly is true and volume_ratio > 5, log as high-conviction oracle signal.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/crypto-intel`
+ - `body`: `{"topic":"pump_volume_anomaly"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/pump-whale-tracker.md b/agents/x402-buildout/self/pump-whale-tracker.md
new file mode 100644
index 000000000..7336d0107
--- /dev/null
+++ b/agents/x402-buildout/self/pump-whale-tracker.md
@@ -0,0 +1,41 @@
+# 049: Pump Whale Wallet Tracker
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/pump-agent-audit` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/pump-agent-audit`
+- **Method:** POST
+- **Body:** `{"mode":"whale_activity","limit":5}`
+
+## What to Build
+Pay to identify whale wallets active on pump.fun right now. Extract { wallets, total_sol_moved }. Store in oracle_intel_signals as a whale_activity signal. Sniper uses this to avoid front-running and to confirm genuine interest.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/pump-agent-audit`
+ - `body`: `{"mode":"whale_activity","limit":5}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/reputation-decay-check.md b/agents/x402-buildout/self/reputation-decay-check.md
new file mode 100644
index 000000000..e25bd6a08
--- /dev/null
+++ b/agents/x402-buildout/self/reputation-decay-check.md
@@ -0,0 +1,41 @@
+# 070: Reputation: Score Decay Monitor
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/agent-reputation` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/agent-reputation`
+- **Method:** POST
+- **Body:** `{"mode":"decay_report"}`
+
+## What to Build
+Pay x402 to get a report of agents whose reputation score has decayed by >10 points in 7 days. Extract { decayed_count, fastest_decline_agent, avg_decay }. Decay spikes could indicate coordinated abuse or score manipulation.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/agent-reputation`
+ - `body`: `{"mode":"decay_report"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/reputation-leaderboard.md b/agents/x402-buildout/self/reputation-leaderboard.md
new file mode 100644
index 000000000..5c6987af1
--- /dev/null
+++ b/agents/x402-buildout/self/reputation-leaderboard.md
@@ -0,0 +1,41 @@
+# 071: Reputation: Top Agent Leaderboard
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/agent-reputation` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/agent-reputation`
+- **Method:** POST
+- **Body:** `{"mode":"leaderboard","limit":10}`
+
+## What to Build
+Pay x402 to fetch the top 10 agents by reputation score. Extract { agents: [{id, score, rank}] }. Display in platform UI and use to prioritize which agents get promoted in the marketplace.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/agent-reputation`
+ - `body`: `{"mode":"leaderboard","limit":10}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/skill-execution-health.md b/agents/x402-buildout/self/skill-execution-health.md
new file mode 100644
index 000000000..e51a8d61b
--- /dev/null
+++ b/agents/x402-buildout/self/skill-execution-health.md
@@ -0,0 +1,41 @@
+# 058: Skill Execution: Canary Run
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/skill-marketplace` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/skill-marketplace`
+- **Method:** POST
+- **Body:** `{"mode":"canary_execute","skill_id":"echo_test"}`
+
+## What to Build
+Pay x402 to execute a canary skill (echo_test) and verify it returns within 2 seconds. Extract { executed: bool, latency_ms, output }. If latency > 2000ms, signal a skill execution performance issue.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/skill-marketplace`
+ - `body`: `{"mode":"canary_execute","skill_id":"echo_test"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/skill-marketplace-popular.md b/agents/x402-buildout/self/skill-marketplace-popular.md
new file mode 100644
index 000000000..e97c9ed97
--- /dev/null
+++ b/agents/x402-buildout/self/skill-marketplace-popular.md
@@ -0,0 +1,41 @@
+# 057: Skill Marketplace: Most-Used Skills
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/skill-marketplace` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/skill-marketplace`
+- **Method:** POST
+- **Body:** `{"mode":"popular","limit":5}`
+
+## What to Build
+Pay to retrieve the 5 most-purchased skills in the last 7 days. Extract { skills: [{id, name, purchases}] }. Store signal_data with top_skill_id and top_skill_purchases. Use to prioritize featured listings.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/skill-marketplace`
+ - `body`: `{"mode":"popular","limit":5}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/skill-marketplace-pricing.md b/agents/x402-buildout/self/skill-marketplace-pricing.md
new file mode 100644
index 000000000..d8766fdc3
--- /dev/null
+++ b/agents/x402-buildout/self/skill-marketplace-pricing.md
@@ -0,0 +1,41 @@
+# 056: Skill Marketplace: Price Distribution
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/skill-marketplace` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/skill-marketplace`
+- **Method:** POST
+- **Body:** `{"mode":"price_distribution"}`
+
+## What to Build
+Pay to fetch skill marketplace price distribution data. Extract { min_price, max_price, median_price, skill_count }. Monitor for price floor erosion — if median_price drops >20% week-over-week, signal marketplace health issue.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/skill-marketplace`
+ - `body`: `{"mode":"price_distribution"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/spend-session-audit.md b/agents/x402-buildout/self/spend-session-audit.md
new file mode 100644
index 000000000..d00ee7235
--- /dev/null
+++ b/agents/x402-buildout/self/spend-session-audit.md
@@ -0,0 +1,41 @@
+# 064: Spend Session: Active Session Audit
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/spend-session` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/spend-session`
+- **Method:** POST
+- **Body:** `{"mode":"audit"}`
+
+## What to Build
+Pay x402 to audit currently active spend sessions. Extract { active_count, total_budget_remaining_usdc, expired_count }. Run every 15 minutes. If expired_count spikes, something is preventing session cleanup.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/spend-session`
+ - `body`: `{"mode":"audit"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/spend-session-canary.md b/agents/x402-buildout/self/spend-session-canary.md
new file mode 100644
index 000000000..c8a982d45
--- /dev/null
+++ b/agents/x402-buildout/self/spend-session-canary.md
@@ -0,0 +1,41 @@
+# 065: Spend Session: Canary Create+Consume
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/spend-session` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/spend-session`
+- **Method:** POST
+- **Body:** `{"mode":"canary","budget":0.01}`
+
+## What to Build
+Pay x402 to create a minimal spend session, consume it immediately, and verify the cycle completes cleanly. Extract { created: bool, consumed: bool, latency_ms }. This is the most important health check for the x402 governance layer.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/spend-session`
+ - `body`: `{"mode":"canary","budget":0.01}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/symbol-availability-scan.md b/agents/x402-buildout/self/symbol-availability-scan.md
new file mode 100644
index 000000000..7b0d59b20
--- /dev/null
+++ b/agents/x402-buildout/self/symbol-availability-scan.md
@@ -0,0 +1,41 @@
+# 053: Symbol Availability: Common Scan
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/symbol-availability` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/symbol-availability`
+- **Method:** POST
+- **Body:** `{"symbols":["MOON","ROCKET","FROG","CAT","DOG"]}`
+
+## What to Build
+Pay x402 to scan availability of 5 high-demand meme token symbols. Extract { available_count, taken_count, available_list }. Report to analytics. Useful for showing users trending naming patterns and remaining launch opportunities.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/symbol-availability`
+ - `body`: `{"symbols":["MOON","ROCKET","FROG","CAT","DOG"]}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/token-intel-sol-price.md b/agents/x402-buildout/self/token-intel-sol-price.md
new file mode 100644
index 000000000..d78c79160
--- /dev/null
+++ b/agents/x402-buildout/self/token-intel-sol-price.md
@@ -0,0 +1,41 @@
+# 050: Token Intel: SOL Price Feed
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/token-intel` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/token-intel`
+- **Method:** POST
+- **Body:** `{"mint":"So11111111111111111111111111111111111111112","network":"mainnet"}`
+
+## What to Build
+Pay x402 to get SOL native token intelligence: price_usd, 24h change, volume, market_cap. Extract { price_usd, change_24h }. Update oracle_intel_signals with topic=solana_price on every call. Cooldown 300s.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/token-intel`
+ - `body`: `{"mint":"So11111111111111111111111111111111111111112","network":"mainnet"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/token-intel-three.md b/agents/x402-buildout/self/token-intel-three.md
new file mode 100644
index 000000000..968eca5f0
--- /dev/null
+++ b/agents/x402-buildout/self/token-intel-three.md
@@ -0,0 +1,41 @@
+# 051: Token Intel: $THREE Price & Holder Snapshot
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/token-intel` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/token-intel`
+- **Method:** POST
+- **Body:** `{"mint":"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump","network":"mainnet"}`
+
+## What to Build
+Pay x402 to monitor $THREE token: price_usd, holder_count, top_holder_pct, 24h volume. Extract all fields into oracle_intel_signals topic=three_price. Run every 15 minutes. If price drops >10% in 24h, signal=bearish.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/token-intel`
+ - `body`: `{"mint":"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump","network":"mainnet"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/token-intel-usdc.md b/agents/x402-buildout/self/token-intel-usdc.md
new file mode 100644
index 000000000..e77c9006e
--- /dev/null
+++ b/agents/x402-buildout/self/token-intel-usdc.md
@@ -0,0 +1,41 @@
+# 052: Token Intel: USDC Peg Monitor
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/token-intel` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/token-intel`
+- **Method:** POST
+- **Body:** `{"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","network":"mainnet"}`
+
+## What to Build
+Monitor USDC peg stability via x402 token-intel. If price deviates more than 0.5% from $1.00, extract { depeg: true, price_usd } and elevate to warning. Run every 10 minutes as a payment ecosystem health signal.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/token-intel`
+ - `body`: `{"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","network":"mainnet"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/agents/x402-buildout/self/wallet-connect-probe.md b/agents/x402-buildout/self/wallet-connect-probe.md
new file mode 100644
index 000000000..e439ce0a5
--- /dev/null
+++ b/agents/x402-buildout/self/wallet-connect-probe.md
@@ -0,0 +1,41 @@
+# 063: Wallet Connect: Session Health
+
+## Objective
+Build a real, wired x402 use case that calls the `/api/x402/wallet-connect` endpoint on three.ws, pays with the autonomous loop seed wallet, records the result to `x402_autonomous_log`, and extracts actionable signal data.
+
+## x402 Endpoint
+- **Path:** `/api/x402/wallet-connect`
+- **Method:** POST
+- **Body:** `{"mode":"health"}`
+
+## What to Build
+Pay x402 to test wallet connection session creation and teardown. Measures whether the wallet connect flow completes end-to-end within timeout. Extract { session_created: bool, latency_ms }.
+
+## Implementation Requirements
+
+1. **Add to registry** — Add an entry in `api/_lib/x402/autonomous-registry.js` under `SELF_ENDPOINTS` with:
+ - `id`: unique kebab-case string
+ - `path`: `/api/x402/wallet-connect`
+ - `body`: `{"mode":"health"}`
+ - `cooldown_s`: appropriate cooldown (300–3600 depending on signal volatility)
+ - `priority`: 50–99 (oracle pipeline ≥ 85, health 40–60, volume 65–75)
+ - `pipeline`: one of `'oracle' | 'health' | 'volume' | 'sniper'`
+ - `extractSignal`: function that parses the response body and returns a plain object with the key fields described above
+
+2. **Make real payments** — The autonomous loop (`api/cron/x402-autonomous-loop.js`) uses the seed keypair (`X402_SEED_SOLANA_SECRET_BASE58`) to pay real USDC. No mocks. If the endpoint does not exist yet, build it first.
+
+3. **Record to log** — Every call is recorded to `x402_autonomous_log` with `pipeline`, `signal_data` (from `extractSignal`), and `success` fields. Verify the insert in the DB after first run.
+
+4. **Extract value** — The extracted signal must be actionable. If this is an oracle pipeline entry, upsert the signal into `oracle_intel_signals` with an appropriate `topic` so the sniper gate can consume it.
+
+5. **Respect cooldowns** — Set a cooldown that matches the signal's update frequency. Price data: 300s. Macro intel: 900s. Health checks: 300–600s. Audit-style calls: 1800–3600s.
+
+6. **Handle errors** — Probe the endpoint before paying. If the endpoint returns a non-402 error, log it and skip payment. Never throw on a failed call — return `{ success: false, error_msg }` and continue.
+
+## Definition of Done
+- [ ] Entry added to `SELF_ENDPOINTS` in `autonomous-registry.js`
+- [ ] `extractSignal` function tested with a real response payload
+- [ ] Autonomous loop cron triggered manually and the entry appears in `x402_autonomous_log`
+- [ ] If oracle pipeline: row visible in `oracle_intel_signals` with correct `topic` and `signal`
+- [ ] No console errors from this entry in the cron logs
+- [ ] `git diff` reviewed — no unrelated changes committed
diff --git a/api/_lib/migrations/2026-06-27-builder-code-attribution.sql b/api/_lib/migrations/2026-06-27-builder-code-attribution.sql
new file mode 100644
index 000000000..8a18826f3
--- /dev/null
+++ b/api/_lib/migrations/2026-06-27-builder-code-attribution.sql
@@ -0,0 +1,47 @@
+-- Migration: Builder Code Attribution Tracker (x402 autonomous loop, Finance).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-27-builder-code-attribution.sql
+-- Idempotent.
+--
+-- The autonomous x402 spend loop (api/cron/x402-autonomous-loop.js) runs the
+-- Builder Code Attribution Tracker (api/_lib/x402/pipelines/builder-code-attribution.js)
+-- every 6 hours. It sweeps a representative set of priced /api/x402/* endpoints,
+-- verifying each declares the ERC-8021 builder-code extension
+-- (extensions["builder-code"].info.a = three_d_agent, set by X402_BUILDER_CODE_APP)
+-- on its live 402 challenge — the precondition for Coinbase builder rewards to
+-- credit that endpoint's settled volume. It then pays ONE real $0.001 USDC
+-- payment to the cheapest declaring endpoint (dance-tip) with the builder-code
+-- echo attached to the X-PAYMENT envelope, reads the X-PAYMENT-RESPONSE
+-- settlement, and confirms an attributed payment settles end-to-end. The paid
+-- round-trip itself is recorded to x402_autonomous_log (joined on run_id).
+--
+-- One row per endpoint (upserted, keyed by endpoint). `gap = true` marks a
+-- priced endpoint missing/mismatched on its three_d_agent declaration — the
+-- attribution gap the tracker alerts on.
+--
+-- Downstream consumer: api/ops/health.js -> loadBuilderAttribution() folds an
+-- open attribution gap (or a failed attributed settlement) into the platform
+-- health verdict so on-call sees lost-rewards risk before a billing cycle closes.
+
+CREATE TABLE IF NOT EXISTS builder_code_attribution (
+ endpoint text PRIMARY KEY,
+ method text,
+ challenged boolean NOT NULL DEFAULT false, -- returned a real 402 challenge
+ attributed boolean NOT NULL DEFAULT false, -- declared builder-code on the challenge
+ declared_code text, -- the `a` app code advertised
+ expected_code text, -- X402_BUILDER_CODE_APP in force
+ matches boolean NOT NULL DEFAULT false, -- declared_code === expected_code
+ price_atomic bigint, -- challenge amount (USDC atomics)
+ gap boolean NOT NULL DEFAULT false, -- 402 endpoint with missing/mismatched attribution
+ settled boolean NOT NULL DEFAULT false, -- this endpoint carried the live settlement proof
+ echo_accepted boolean NOT NULL DEFAULT false, -- attributed payment settled (server enforces echo)
+ response_attributed boolean NOT NULL DEFAULT false, -- X-PAYMENT-RESPONSE echoed a builder-code block
+ tx_signature text, -- on-chain settlement tx (Coinbase reward indexer reads this)
+ payer text,
+ error text,
+ run_id uuid, -- FK (logical) into x402_autonomous_log.run_id
+ checked_at timestamptz DEFAULT now()
+);
+
+-- Partial index: ops/health only ever scans for currently-open gaps.
+CREATE INDEX IF NOT EXISTS builder_code_attribution_gap_idx
+ ON builder_code_attribution (gap) WHERE gap = true;
diff --git a/api/_lib/migrations/2026-06-27-subscription-health.sql b/api/_lib/migrations/2026-06-27-subscription-health.sql
new file mode 100644
index 000000000..3dc0a7ccd
--- /dev/null
+++ b/api/_lib/migrations/2026-06-27-subscription-health.sql
@@ -0,0 +1,35 @@
+-- Migration: x402 Subscription Status Health Check value sink.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-27-subscription-health.sql
+-- Idempotent.
+--
+-- Backs the `subscription-status-health-check` autonomous-registry entry
+-- (api/_lib/x402/pipelines/subscription-health.js). The daily pipeline enumerates
+-- every x402 subscription, classifies it (active | expiring_soon | expired |
+-- revoked), emails subscribers 7 days before expiry, and upserts one verdict row
+-- per subscription here.
+--
+-- Downstream consumer: the admin subscription-management surface reads this to
+-- badge expiring/expired keys, and ops alerting watches
+-- WHERE status IN ('expired','expiring_soon') to catch a lapse before a partner's
+-- integration breaks. The pipeline also ensures this schema at runtime; this file
+-- documents and pre-provisions it.
+
+create table if not exists x402_subscription_health (
+ subscription_id text primary key,
+ name text,
+ key_prefix text,
+ status text not null, -- active | expiring_soon | expired | revoked
+ rate_limit_per_minute integer,
+ expires_at timestamptz,
+ revoked_at timestamptz,
+ days_to_expiry integer, -- null when no expiry
+ contact_email text,
+ notified_expiry_at timestamptz, -- the expires_at value we last emailed about
+ notified_at timestamptz, -- when that warning email was sent
+ last_checked_at timestamptz not null default now(),
+ run_id uuid,
+ meta jsonb
+);
+
+create index if not exists x402_subscription_health_status_idx
+ on x402_subscription_health (status, expires_at);
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index a88d64d50..d7d423ac8 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -34,6 +34,11 @@
// discovery warmup sweeping 15 categories per run).
import { run as bazaarDiscoveryWarmup } from './pipelines/bazaar-warmup.js';
+import {
+ run as bazaarCatalogRefresh,
+ BAZAAR_CATALOG_REFRESH,
+} from './pipelines/bazaar-catalog-refresh.js';
+import { run as x402PricingTracker } from './pipelines/x402-pricing-tracker.js';
import { run as avatarSearchWarmup } from './pipelines/avatar-search-warmup.js';
import { run as reputationRefresh } from './pipelines/reputation-refresh.js';
import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';
@@ -41,9 +46,13 @@ import { run as sniperIntelEnrich } from './pipelines/sniper-intel-enrich.js';
import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';
import { run as liveFeedSeeder } from './pipelines/live-feed-seeder.js';
import { run as feeCalculationValidator } from './pipelines/fee-calculation-validator.js';
+import { run as crossChainCostComparison } from './pipelines/cross-chain-cost.js';
+import { run as charitySplitAudit } from './pipelines/charity-split-audit.js';
import { classifyThreeSignal, insertThreeSignal } from './three-signal-store.js';
import { run as cosmeticPricingAudit } from './pipelines/cosmetic-pricing-audit.js';
+import { run as builderCodeAttribution } from './pipelines/builder-code-attribution.js';
import { run as paymentProofIdempotencyAudit } from './pipelines/payment-proof-idempotency-audit.js';
+import { run as apiKeyBypassAudit } from './pipelines/api-key-bypass-audit.js';
import { run as modelMetadataEnrichment } from './pipelines/model-metadata-enrichment.js';
import { run as forgeContentGeneration } from './pipelines/forge-content.js';
import { run as runAnimationRetargetQa, hasCanaryClips as hasAnimationQaCanaries } from './pipelines/animation-retarget-qa.js';
@@ -65,6 +74,12 @@ import {
SCENE_CAPTURE_PRICE_ATOMIC,
} from './scene-capture-processor.js';
import { run as runRigComplexityScorer } from './pipelines/rig-complexity.js';
+import { run as runReservationLeakDetector } from './pipelines/spend-reservation-leak-detector.js';
+import { run as runSubscriptionHealth } from './pipelines/subscription-health.js';
+import {
+ run as runServiceUptimeMonitor,
+ SERVICE_UPTIME_ENDPOINT,
+} from './pipelines/service-uptime-monitor.js';
import {
runThumbnailRegen,
THUMBNAIL_REGEN_ENDPOINT,
@@ -268,6 +283,35 @@ const SELF_ENDPOINTS = [
extractSignal: null,
},
+ // ── API Key Bypass Security Test (free-access canary) ─────────────────────
+ // Daily security canary for the X-API-Key bypass lane (access-control.js →
+ // installAccessControl). run() probes a bypass matrix against both the hand-
+ // rolled (/api/x402/model-check) and paidEndpoint-factory (/api/x402/dance-tip)
+ // access-control paths: a VALID key must grant free access (200 + x-payment-
+ // bypass), an INVALID key must be denied (403/402), and NO key must hit the 402
+ // paywall — any free 200 on the deny/no-key paths is a LEAK. It mints an
+ // ephemeral, self-expiring subscription key (revoked in a finally) to exercise
+ // the partner lane, then makes ONE real $0.001 payment against the no-key
+ // model-check 402 to prove the paywall→verify→settle path is intact end-to-end.
+ // Verdict lands in x402_api_key_bypass_audit; a confirmed leak raises a CRITICAL
+ // ops alert. Daily cadence → one paid probe/day ≈ $0.001/day. Downstream
+ // consumer: api/ops/health.js folds a bypass leak / broken bypass into the
+ // platform health verdict.
+ {
+ id: 'api-key-bypass-audit',
+ name: 'API Key Bypass Security Test',
+ // path is informational — the pipeline probes the bypass matrix + pays itself.
+ path: '/api/x402/model-check',
+ method: 'GET',
+ price_atomic: 1000, // the bypass is free; the lone paywall-proof payment is $0.001
+ cooldown_s: 86400, // daily — catches a refactor-introduced bypass within 24h
+ priority: 84,
+ pipeline: 'security',
+ enabled: true,
+ run: apiKeyBypassAudit,
+ extractSignal: null,
+ },
+
// ── Agent Wallet Balance Monitor (self) ───────────────────────────────────
// Polls the seed/agent wallet balance (the wallet that funds every other
// autonomous call) via the free GET /api/x402-pay?balance=1 every 10 minutes.
@@ -882,6 +926,75 @@ const SELF_ENDPOINTS = [
run: (ctx) => bazaarDiscoveryWarmup(ctx),
},
+ // -- Bazaar Service Catalog Daily Refresh -----------------------------------
+ // A full-catalog census, distinct from the category-search warmup above. Once
+ // a day it browses EVERY service on the bazaar (browse_services for http + mcp
+ // via /api/mcp-bazaar at $0.001/call), then pays get_service ($0.001/call) for
+ // each newly-appeared service to capture its full payment requirements -- the
+ // bazaar_search_services + bazaar_service_details pair. run() owns the census,
+ // the day-over-day diff, and per-call recording; it sets recorded:true so the
+ // loop adds no summary row. The diff is the value: new services (opportunity
+ // alerts) and removed services (pipeline-dependency alerts) land in the daily
+ // snapshot + the durable bazaar_service_index, and removed resources are
+ // cross-checked against active EXTERNAL_ENDPOINTS to raise a dependency alert.
+ // Cooldown 86400s (daily) -> ~2 census + <=8 enrichment calls/day ~= $0.01/day.
+ // Value sinks: bazaar_catalog_snapshots (daily snapshot + diff) and
+ // bazaar_service_index (per-service registry). Downstream consumer: external
+ // onboarding reads bazaar_service_index WHERE status='active' (the opportunity
+ // feed) and ops reads the Redis dependency-alert before a dead external entry
+ // starts erroring.
+ {
+ id: 'bazaar-catalog-refresh',
+ name: 'Bazaar Service Catalog Daily Refresh',
+ path: BAZAAR_CATALOG_REFRESH.endpoint,
+ endpoint: BAZAAR_CATALOG_REFRESH.endpoint,
+ method: 'POST',
+ body: null,
+ price_atomic: BAZAAR_CATALOG_REFRESH.priceAtomic,
+ cooldown_s: BAZAAR_CATALOG_REFRESH.cooldownSeconds,
+ cooldown_seconds: BAZAAR_CATALOG_REFRESH.cooldownSeconds,
+ priority: 34,
+ pipeline: 'discovery',
+ enabled: true,
+ run: (ctx) => bazaarCatalogRefresh(ctx),
+ extractSignal: null,
+ },
+
+ // ── x402 Service Pricing Tracker (USE: cost-model price history) ───────────
+ // Tracks the PRICE HISTORY of the external x402 services we depend on so our
+ // cost models stay honest (distinct from the catalog census above, which
+ // tracks service presence). Each run pays $0.001/call to /api/mcp-bazaar
+ // (bazaar_service_details) for the stalest tracked services and reads each
+ // one's current live cheapest price. run() compares to the last recorded price,
+ // appends to x402_service_price_history, and upserts x402_service_price_current
+ // with the % change + alert flags — raising a cost-model alert when a price
+ // jumped > 20% and flagging a drop opportunity when it fell ≥ 15%. The tracked
+ // set is built from the live priced resources the Bazaar Discovery Warmup
+ // snapshots into x402_bazaar_catalog (no hardcoded list). run() self-records one
+ // x402_autonomous_log row per call (value_extracted = price + change), so it
+ // sets recorded:true and the loop adds no summary row. Cooldown 21600s (6h) with
+ // a 5-service batch → ≤ $0.005/run, rotating the catalog ≈ daily, well under the
+ // loop's daily cap. Downstream consumer: GET /api/x402/service-pricing-report
+ // surfaces the tracked catalog, active increase alerts, and drop opportunities.
+ {
+ id: 'x402-pricing-tracker',
+ name: 'x402 Service Pricing Tracker',
+ // path/endpoint are informational — run() builds the bazaar_service_details
+ // JSON-RPC body and pays the live $0.001 challenge itself, per service.
+ path: '/api/mcp-bazaar',
+ endpoint: '/api/mcp-bazaar',
+ method: 'POST',
+ body: null,
+ price_atomic: 1000, // $0.001 USDC — bazaar_service_details per-call price
+ cooldown_s: 21600,
+ cooldown_seconds: 21600,
+ priority: 33,
+ pipeline: 'discovery',
+ enabled: true,
+ run: (ctx) => x402PricingTracker(ctx),
+ extractSignal: null,
+ },
+
// ── Avatar Search Index Warmup (USE-003) ───────────────────────────────────
// Fires ~20 common gallery queries (human, robot, anime, warrior, …) through
// the MCP server (/api/mcp → search_public_avatars) at $0.001/call, proving the
@@ -1116,6 +1229,42 @@ const SELF_ENDPOINTS = [
enabled: true,
run: (ctx) => revenueReconciliation(ctx),
},
+ // Builder Code Attribution Tracker (Finance) — watchdog over ERC-8021
+ // builder-code attribution, the mechanism Coinbase builder rewards / x402scan
+ // use to credit on-chain x402 volume to the app that exposed the paid endpoint
+ // (X402_BUILDER_CODE_APP = three_d_agent). run() sweeps a representative set of
+ // priced /api/x402/* endpoints, verifying each declares the builder-code
+ // extension (a = three_d_agent) on its live 402 challenge — any priced endpoint
+ // that drops the declaration earns ZERO rewards on every dollar it settles, the
+ // attribution gap this tracker alerts on. It then makes ONE real $0.001 USDC
+ // payment to the cheapest declaring endpoint (dance-tip) with the builder-code
+ // echo ATTACHED to the X-PAYMENT envelope (a/w/s), reads the X-PAYMENT-RESPONSE
+ // settlement, and confirms an attributed payment settles end-to-end (the
+ // resource server rejects a non-echoing payment with builder_code_tampered, so a
+ // settled tx is proof). Per-endpoint verdicts upsert to builder_code_attribution
+ // (keyed by endpoint); a summary (value_extracted = gap list + settle proof)
+ // goes to x402_autonomous_log. Cooldown 21600 s (6h, ~$0.004/day) — attribution
+ // config only changes on deploy/env, the live settle catches drift within hours.
+ // Downstream consumer: api/ops/health.js -> loadBuilderAttribution() folds an
+ // attribution gap (or a failed attributed settlement) into the platform health
+ // verdict so on-call sees lost-rewards risk before a billing cycle closes.
+ {
+ id: 'builder-code-attribution',
+ name: 'Builder Code Attribution Tracker',
+ // path is informational — run() owns the multi-endpoint sweep + settle.
+ path: '/api/x402/*',
+ endpoint: '/api/x402/*',
+ method: 'POST',
+ body: null,
+ price_atomic: 1000, // the single settlement proof pays $0.001 (dance-tip)
+ cooldown_s: 21600,
+ cooldown_seconds: 21600,
+ priority: 31,
+ pipeline: 'finance',
+ enabled: true,
+ run: (ctx) => builderCodeAttribution(ctx),
+ extractSignal: null,
+ },
// ── Fee Calculation Validator (USE-028, Finance) ──────────────────────────
// Fee-integrity probe over the platform's atomic↔decimal conversion — the
// arithmetic that turns every USDC price into an x402 challenge amount and back
@@ -1146,6 +1295,76 @@ const SELF_ENDPOINTS = [
enabled: true,
run: (ctx) => feeCalculationValidator(ctx),
},
+ // ── Charity Split Audit (Finance) ─────────────────────────────────────────
+ // Giving-integrity audit — "ensures donation promises are kept." Weekly, it
+ // (1) sweeps every charity-enabled merchant in x402_merchant_settings (free,
+ // read-only) and flags any whose donation promise is unroutable (missing /
+ // malformed cause address, zero share, cause == payout — a tip the checkout
+ // silently drops), then (2) makes ONE real on-chain payment WITH a charity
+ // split through the PRODUCTION checkout code (/api/x402-checkout prepare →
+ // sign → encode → settle the $0.001 dance-tip, facilitator-sponsored fee) and
+ // reads the settled tx back from chain to assert the cause wallet's
+ // transferChecked leg landed with the EXACT computed atomics
+ // (floor(amount × bps / 10000)). run() owns the sweep/pay/verify and writes
+ // per-merchant + canary rows to charity_split_audit (value sink) and its own
+ // x402_autonomous_log summary; the loop adds the billed row. The canary cause
+ // wallet defaults to the seed wallet (safe self-route, zero net outflow);
+ // X402_CHARITY_AUDIT_ADDRESS_SOLANA points it at a platform cause wallet.
+ // Cooldown 604800 s (weekly) → ~$0.001/week. Downstream consumer: ops reads
+ // charity_split_audit WHERE NOT config_valid OR charity_routed = false to alert
+ // before a buyer is told their payment gave to a cause that never received it.
+ {
+ id: 'charity-split-audit',
+ // path/endpoint are informational — run() probes + pays + verifies itself.
+ path: '/api/x402-merchant',
+ endpoint: '/api/x402-merchant',
+ method: 'POST',
+ price_atomic: 1000, // the canary settles the $0.001 dance-tip base; split rides along
+ cooldown_s: 604800, // weekly — donation promises are a slow-changing config
+ cooldown_seconds: 604800,
+ priority: 31,
+ pipeline: 'finance',
+ enabled: true,
+ run: (ctx) => charitySplitAudit(ctx),
+ extractSignal: null,
+ },
+ // ── Cross-Chain Payment Cost Comparison (USE-029, Finance) ────────────────
+ // Measures the real all-in cost of an identical $0.001 USDC payment on Solana
+ // vs Base and tracks the gas premium between the rails over time. run() probes
+ // the cheapest idempotent $0.001 endpoint (/api/x402/model-check) for the live
+ // multi-network challenge (both networks quote the same amount, so the
+ // comparison is apples to apples), settles the REAL Solana leg and reads its
+ // actual on-chain meta.fee, prices the equivalent Base settlement from the live
+ // Base gas price × the documented USDC ERC-3009 transferWithAuthorization gas
+ // units, and converts both to USD with live SOL/ETH prices. Base outbound
+ // settlement isn't attempted (no autonomous EVM payer is provisioned — same
+ // boundary the circuit breaker hits); its gas figure is real live network data.
+ // Per-run snapshots (amount + per-network gas/total USD + gas_premium_ratio +
+ // cheapest_network) land in cross_chain_cost_comparison; the loop records the
+ // paid Solana settlement to x402_autonomous_log (value_extracted = the cost
+ // summary). Cooldown 3600 s (hourly — gas prices drift, one paid probe/hr ≈
+ // $0.024/day) keeps a fresh premium trend well inside the daily cap.
+ // Downstream consumer: GET /api/x402/network-cost surfaces the latest snapshot,
+ // a rolling gas-premium average, and the recommended cheapest settlement
+ // network — used to steer users to the cheaper rail and inform default pricing.
+ {
+ id: 'cross-chain-cost-comparison',
+ name: 'Cross-Chain Payment Cost Comparison (Base + Solana)',
+ // path/endpoint are informational — run() probes /api/x402/model-check and
+ // settles the Solana leg itself. Real price is the live $0.001 challenge.
+ path: '/api/x402-pay',
+ endpoint: '/api/x402-pay',
+ method: 'GET',
+ price_atomic: 1000, // $0.001 USDC — the identical amount both rails quote
+ cooldown_s: 3600,
+ cooldown_seconds: 3600,
+ priority: 34,
+ pipeline: 'finance',
+ enabled: true,
+ run: (ctx) => crossChainCostComparison(ctx),
+ extractSignal: null,
+ },
+
// ── IBM Granite Inference Health Check (USE-007) ──────────────────────────
// Pays ONE real x402 batch call to /api/ibm-mcp that invokes all five paid
// IBM Granite tools (chat, code, embed, analyze, forecast) with tiny canary
@@ -1207,6 +1426,116 @@ const SELF_ENDPOINTS = [
run: (ctx) => runRigComplexityScorer(ctx),
extractSignal: null,
},
+
+ // ── Subscription Status Health Check (Commerce) ───────────────────────────
+ // Daily integrity sweep over every paying x402 subscriber. run() enumerates all
+ // subscriptions via the real admin endpoint GET /api/x402/admin/subscriptions
+ // (authenticated as an internal service with INTERNAL_API_KEY — the GET-only
+ // read bypass added to that route), falling back to the canonical
+ // listSubscriptions() lib read if the HTTP path is unavailable. It classifies
+ // each key (active | expiring_soon | expired | revoked), emails the subscriber
+ // 7 days before expiry (once per expiry window), and upserts every verdict into
+ // x402_subscription_health. Free + read-only: the admin endpoint owes no payment,
+ // so this never moves funds (amountAtomic 0) and runs even without a spend
+ // wallet. run() writes its own canonical x402_autonomous_log row (recorded:true)
+ // with the per-run summary in value_extracted. Cooldown 86400 s (daily) → the
+ // 7-day warning window is re-evaluated across ~7 runs so no expiry is missed.
+ // Downstream consumer: the admin subscription-management surface badges
+ // expiring/expired keys off x402_subscription_health, and ops alerting watches
+ // status IN ('expired','expiring_soon') to catch a lapse before a partner's
+ // integration breaks.
+ {
+ id: 'subscription-status-health-check',
+ name: 'Subscription Status Health Check',
+ // path/endpoint informational — run() owns the internal-service HTTP call.
+ path: '/api/x402/admin/subscriptions',
+ endpoint: '/api/x402/admin/subscriptions',
+ method: 'GET',
+ body: null,
+ price_atomic: 0, // free internal endpoint — no payment owed
+ cooldown_s: 86_400,
+ cooldown_seconds: 86_400,
+ priority: 34,
+ pipeline: 'self',
+ enabled: true,
+ run: (ctx) => runSubscriptionHealth(ctx),
+ extractSignal: null,
+ },
+
+ // ── External x402 Service Uptime Monitor (USE-038, Reliability) ────────────
+ // Liveness gate in front of every external x402 service we depend on. The
+ // registered external services live in x402_bazaar_catalog (snapshotted by the
+ // Bazaar Discovery Warmup) plus any directly-registered EXTERNAL_ENDPOINTS;
+ // production pipelines pay those endpoints, so a dead one wastes a tick (and
+ // risks a half-settled payment). run() collects every distinct external URL and
+ // probes each with a cheap, UNPAID HEAD request (falling back to OPTIONS then
+ // GET when a server rejects HEAD): a 402 means the x402 endpoint is live, 2xx/3xx
+ // is reachable, and 5xx or a network timeout means DOWN. Because the probe never
+ // attaches an X-PAYMENT header, reading a 402 challenge is free — this pipeline
+ // moves no funds (price_atomic 0, amountAtomic always 0). Each verdict upserts
+ // into x402_service_uptime (consecutive_failures / last_seen_live tracked) and
+ // run() records one x402_autonomous_log row per probe (value_extracted = the
+ // verdict). Cooldown 900 s (15 min) catches an outage within minutes while a
+ // Redis cursor rotates the per-run probe budget across a large catalog.
+ // Downstream consumer: any pipeline paying an external endpoint calls
+ // isServiceLive(sql, url) to skip a confirmed-dead service; listServiceUptime()
+ // backs an ops reliability surface.
+ {
+ id: 'external-service-uptime-monitor',
+ name: 'External x402 Service Uptime Monitor',
+ // path/endpoint are informational — run() fans HEAD probes across the
+ // external service registry itself; it owns no single URL.
+ path: SERVICE_UPTIME_ENDPOINT,
+ endpoint: SERVICE_UPTIME_ENDPOINT,
+ method: 'HEAD',
+ body: null,
+ price_atomic: 0, // free probe — never pays
+ cooldown_s: 900, // 15 min — catch outages fast; probes are free
+ cooldown_seconds: 900,
+ priority: 58, // reliability gate protects every paying external pipeline
+ pipeline: 'reliability',
+ enabled: true,
+ run: (ctx) => runServiceUptimeMonitor(ctx),
+ extractSignal: null,
+ },
+
+ // ── Spend Reservation Leak Detector (Finance) ─────────────────────────────
+ // Liveness guard on the agent spend caps themselves. Every autonomous spend
+ // reserves cap headroom first, then finalizes or releases it after settlement.
+ // A crash between reserve and finalize/release orphans the reservation — it
+ // holds headroom forever against money that never moved, silently exhausting
+ // the agent's rolling-24h cap until every real spend fails `daily_exceeded`.
+ // run() sweeps both reservation books for entries older than 1h that were never
+ // finalized: USD reservations (agent_custody_events, status 'pending') released
+ // via releaseSpendReservation() → marked 'failed', and SOL reservations
+ // (agent_actions, payload.status 'reserved') recorded-then-released via
+ // releaseSpend() (which deletes, so the evidence is captured first). Free DB
+ // maintenance — no x402 challenge, no payment, amountAtomic always 0 — so it runs
+ // even without the spend wallet (exactly when the cap most needs freeing). run()
+ // writes its own canonical x402_autonomous_log row (recorded:true) with the sweep
+ // summary in value_extracted. Cooldown 900 s (15 min) keeps the caps clean and
+ // drains any backlog across runs. Value sink: spend_reservation_leaks (one row
+ // per swept leak) + Redis x402:reservation-leak:{latest,alert}. Downstream
+ // consumer: api/ops/health.js loadReservationLeaks() folds a spike in freshly
+ // swept leaks into the platform health verdict (a sustained leak rate means a
+ // reserve→finalize path is crashing and quietly starving agent spend caps).
+ {
+ id: 'spend-reservation-leak-detector',
+ name: 'Spend Reservation Leak Detector',
+ // path/endpoint are informational — run() owns the DB sweep + cleanup itself.
+ path: '/api/_lib/agent-trade-guards',
+ endpoint: '/api/_lib/agent-trade-guards',
+ method: 'POST',
+ body: null,
+ price_atomic: 0, // free DB maintenance — no payment owed
+ cooldown_s: 900, // 15 min — keep spend caps clean; the sweep is free
+ cooldown_seconds: 900,
+ priority: 62, // protects every autonomous spend path from a starved cap
+ pipeline: 'finance',
+ enabled: true,
+ run: (ctx) => runReservationLeakDetector(ctx),
+ extractSignal: null,
+ },
];
// ── External registry ─────────────────────────────────────────────────────────
diff --git a/api/_lib/x402/pipelines/api-key-bypass-audit.js b/api/_lib/x402/pipelines/api-key-bypass-audit.js
new file mode 100644
index 000000000..da5b046c9
--- /dev/null
+++ b/api/_lib/x402/pipelines/api-key-bypass-audit.js
@@ -0,0 +1,492 @@
+// api/_lib/x402/pipelines/api-key-bypass-audit.js
+//
+// API Key Bypass Security Test — autonomous pipeline (self/security).
+//
+// A run()-style registry entry (autonomous-registry.js → `api-key-bypass-audit`)
+// the per-tick spend loop invokes once a day. It is the platform's free-access
+// canary: it proves the X-API-Key bypass lane (api/_lib/x402/access-control.js →
+// installAccessControl) only ever grants free access to a VALID key — and that a
+// missing or invalid key still hits the paywall. A refactor that accidentally
+// short-circuits the 402 for ANY key (or no key) lets the whole paid surface be
+// drained for free; this audit catches that within a day.
+//
+// The bypass matrix it exercises against every audited route:
+// • VALID key → expect a free grant: HTTP 200 carrying `x-payment-bypass`,
+// NOT a 402 and NOT a 403. (the bypass lane working)
+// • INVALID key → expect denial: a 403 (Invalid API key) or a 402 paywall —
+// anything that does NOT grant free access. A 200 here is a LEAK.
+// • NO key → expect the 402 paywall challenge. A 200 here means the
+// paywall was removed — a LEAK.
+// • REVOKED key → (subscription lane only) after we revoke the canary key, the
+// SAME key must now be denied. A grant here is a LEAK.
+//
+// Both audited routes share the same installAccessControl() hook but invoke it
+// from different consumers, so the pair covers both code paths a refactor could
+// break:
+// • /api/x402/model-check — hand-rolled access-control invocation (GET, $0.001,
+// read-only/idempotent). Full matrix (valid grant + denials) runs here, and
+// this is the one route we actually PAY: paying its no-key 402 challenge once
+// proves the paywall→verify→settle path is intact end-to-end ("without a valid
+// key you must pay, and paying works").
+// • /api/x402/dance-tip — paidEndpoint(spec) factory access-control (POST,
+// $0.001). Deny matrix only (invalid → 403, no-key → 402); those paths reject
+// BEFORE the handler runs, so probing them has no side effects and we never
+// fire a free dance-tip.
+//
+// Acquiring a VALID key: we mint an EPHEMERAL subscription key (createSubscription)
+// with a 10-minute self-expiry, exercise the partner/DB bypass lane every
+// paidEndpoint relies on, then revoke it in a finally — so a crash mid-run can
+// never leave a live free-access key behind (it self-expires regardless). When the
+// DB is unavailable we fall back to the INTERNAL_API_KEY env (the internal-service
+// lane). With neither, the grant check is skipped (verdict: inconclusive) but the
+// deny matrix + paywall payment still run.
+//
+// Recording: the loop records ONE x402_autonomous_log row per run (signalData →
+// signal_data, valueExtracted → value_extracted, amountAtomic = the single $0.001
+// paywall-proof payment). The dedicated value sink is `x402_api_key_bypass_audit`
+// — one row per audit with the full per-route matrix, the pass/fail verdict, and
+// the paywall-payment evidence.
+//
+// Downstream consumer: api/ops/health.js reads the latest x402_api_key_bypass_audit
+// row (loadApiKeyBypassAudit) and folds a confirmed bypass leak / broken bypass
+// into the platform health verdict (alongside the idempotency audit and the
+// cross-network circuit breaker), so the status page / on-call surface a leaking
+// paywall immediately.
+
+import { randomUUID, randomBytes } from 'node:crypto';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { sendOpsAlert } from '../../alerts.js';
+import { createSubscription, revokeSubscription } from '../api-keys.js';
+import {
+ loadSeedKeypair,
+ bootstrapSolanaContext,
+ payX402,
+ fetchWithTimeout,
+} from '../pay.js';
+
+const log = logger('x402-api-key-bypass-audit');
+
+const UA = 'threews-x402-autonomous/1.0';
+
+// fox.glb — a tiny public canary the model-check server fetches behind its SSRF
+// guard. Pinned to the canonical public origin so model-check always has a real
+// public asset to inspect on the paid (no-key) probe.
+const CANARY_GLB = 'https://three.ws/avatars/fox.glb';
+
+// Routes under audit. `probeGrant` runs the valid-key grant probe (read-only
+// routes only, so a free grant has no side effect). `pay` marks the single route
+// whose no-key 402 we actually settle to prove the paywall path end-to-end.
+const AUDIT_ROUTES = [
+ {
+ route: '/api/x402/model-check',
+ label: 'hand-rolled',
+ method: 'GET',
+ query: `?url=${encodeURIComponent(CANARY_GLB)}`,
+ body: null,
+ probeGrant: true,
+ pay: true,
+ },
+ {
+ route: '/api/x402/dance-tip',
+ label: 'paidEndpoint',
+ method: 'GET',
+ query: '',
+ // Deny matrix only: the invalid-key (403) and no-key (402) paths both reject
+ // inside / before the access-control hook, well before the dance-tip handler
+ // runs — so probing them is read-only and never fires a free tip. No grant
+ // probe here (that would run the handler), so no params are needed.
+ body: null,
+ probeGrant: false,
+ pay: false,
+ },
+];
+
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_api_key_bypass_audit (
+ id bigserial PRIMARY KEY,
+ ts timestamptz DEFAULT now(),
+ run_id uuid,
+ route text NOT NULL,
+ valid_key_source text,
+ valid_status int,
+ valid_bypassed boolean,
+ invalid_status int,
+ invalid_denied boolean,
+ nokey_status int,
+ nokey_challenged boolean,
+ revoked_status int,
+ revoked_denied boolean,
+ routes_tested int NOT NULL DEFAULT 0,
+ leaks int NOT NULL DEFAULT 0,
+ paid_status int,
+ paid_settled boolean NOT NULL DEFAULT false,
+ paid_tx text,
+ amount_atomic bigint NOT NULL DEFAULT 0,
+ verdict text NOT NULL,
+ pass boolean NOT NULL,
+ leak boolean NOT NULL DEFAULT false,
+ details jsonb,
+ duration_ms int,
+ error_msg text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_api_key_bypass_audit_ts ON x402_api_key_bypass_audit (ts DESC)`;
+ _schemaReady = true;
+}
+
+async function storeAudit(sql, runId, row) {
+ try {
+ await ensureSchema(sql);
+ await sql`
+ INSERT INTO x402_api_key_bypass_audit
+ (run_id, route, valid_key_source, valid_status, valid_bypassed,
+ invalid_status, invalid_denied, nokey_status, nokey_challenged,
+ revoked_status, revoked_denied, routes_tested, leaks,
+ paid_status, paid_settled, paid_tx, amount_atomic,
+ verdict, pass, leak, details, duration_ms, error_msg)
+ VALUES
+ (${runId || null}, ${row.route}, ${row.valid_key_source || null},
+ ${row.valid_status}, ${row.valid_bypassed},
+ ${row.invalid_status}, ${row.invalid_denied},
+ ${row.nokey_status}, ${row.nokey_challenged},
+ ${row.revoked_status}, ${row.revoked_denied},
+ ${row.routes_tested}, ${row.leaks},
+ ${row.paid_status}, ${row.paid_settled}, ${row.paid_tx || null},
+ ${row.amount_atomic || 0},
+ ${row.verdict}, ${row.pass}, ${row.leak},
+ ${JSON.stringify(row.details || [])}, ${row.duration_ms}, ${row.error_msg || null})
+ `;
+ } catch (err) {
+ // A DB fault must never crash the loop — log and move on.
+ log.warn('api_key_bypass_audit_insert_failed', { message: err?.message });
+ }
+}
+
+// One free probe of a route with a given header set. Never throws — a network
+// fault lands as status 0 (classified 'error', never a leak).
+async function probe(url, route, extraHeaders) {
+ const headers = { 'user-agent': UA, ...extraHeaders };
+ const init = { method: route.method, headers };
+ if (route.method !== 'GET' && route.body != null) {
+ headers['content-type'] = 'application/json';
+ init.body = JSON.stringify(route.body);
+ }
+ try {
+ const res = await fetchWithTimeout(url, init);
+ return {
+ status: res.status,
+ bypass: !!res.headers?.get?.('x-payment-bypass'),
+ };
+ } catch (err) {
+ return { status: 0, bypass: false, error: err?.message || 'network' };
+ }
+}
+
+// Classify one probe against what the scenario expects.
+// expectation 'grant' → a valid key must yield a free bypass (200 + header).
+// expectation 'deny' → invalid/revoked key must NOT grant free access.
+// expectation 'challenge' → no key must hit the 402 paywall.
+// A 200 carrying x-payment-bypass on a deny/challenge scenario, or any 200 that
+// ran the handler without paying, is a LEAK.
+function classify(scenario, route, p, expectation) {
+ const granted = p.status === 200 && p.bypass;
+ const free200 = p.status === 200 && !p.bypass;
+ const challenged = p.status === 402;
+ const denied = p.status === 401 || p.status === 403;
+
+ let verdict;
+ if (p.status === 0) {
+ verdict = 'error';
+ } else if (expectation === 'grant') {
+ verdict = granted ? 'secure' : 'bypass_broken';
+ } else if (granted || free200) {
+ verdict = 'leak';
+ } else if (expectation === 'challenge') {
+ verdict = challenged ? 'secure' : denied ? 'anomaly_denied' : 'anomaly';
+ } else {
+ // deny: a 403 reject OR a 402 paywall both withhold free access → secure.
+ verdict = denied || challenged ? 'secure' : 'anomaly';
+ }
+ return {
+ route: route.route,
+ label: route.label,
+ scenario,
+ status: p.status,
+ bypass: p.bypass,
+ verdict,
+ };
+}
+
+// Acquire a VALID api key to prove the bypass lane grants free access. Prefer an
+// ephemeral subscription key (the partner/DB lane every paidEndpoint depends on);
+// fall back to the internal-service key; else null (grant probe is skipped).
+async function acquireValidKey() {
+ try {
+ const expiresAt = new Date(Date.now() + 10 * 60 * 1000).toISOString();
+ const sub = await createSubscription({
+ name: `bypass-audit-canary ${new Date().toISOString()}`,
+ rateLimitPerMinute: 120,
+ expiresAt, // self-expires in 10 min even if revoke never runs
+ meta: { canary: true, purpose: 'api-key-bypass-audit' },
+ });
+ return { token: sub.token, source: 'subscription', subId: sub.id };
+ } catch (err) {
+ const internal = process.env.INTERNAL_API_KEY;
+ if (internal) return { token: internal, source: 'internal', subId: null };
+ return { token: null, source: null, subId: null, error: err?.message };
+ }
+}
+
+/**
+ * Run the API key bypass security test. Self-contained: builds its own Solana
+ * payment context for the paywall-proof payment when one isn't supplied, so it can
+ * be invoked directly (manual test) or handed the loop's shared blockhash + keypair.
+ *
+ * @param {object} [ctx] — supplied by the loop:
+ * { origin, buyer, conn, blockhash, mintInfo, redis, sql, log, runId, remainingCap }
+ * @returns {Promise<{success, amountAtomic, txSig, responseData, signalData,
+ * valueExtracted, errorMsg, note}>} the outcome the loop records to x402_autonomous_log.
+ */
+export async function runApiKeyBypassAudit(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const sql = ctx.sql || defaultSql;
+ const remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+ const t0 = Date.now();
+
+ // A well-formed-but-unregistered key: passes the `x402_live_` namespace gate so
+ // the access-control hook actually runs the DB lookup (returns no row → 403),
+ // exercising the real invalid-key path rather than short-circuiting on prefix.
+ const invalidKey = `x402_live_${randomBytes(32).toString('base64url')}`;
+
+ const valid = await acquireValidKey();
+ const matrix = [];
+
+ try {
+ for (const r of AUDIT_ROUTES) {
+ const url = `${origin}${r.route}${r.query || ''}`;
+ // NO key → expect the 402 paywall.
+ matrix.push(classify('no-key', r, await probe(url, r, {}), 'challenge'));
+ // INVALID key → expect denial (403 or 402), never a free grant.
+ matrix.push(
+ classify('invalid-key', r, await probe(url, r, { 'x-api-key': invalidKey }), 'deny'),
+ );
+ // VALID key → expect a free bypass. Read-only routes only.
+ if (r.probeGrant && valid.token) {
+ matrix.push(
+ classify('valid-key', r, await probe(url, r, { 'x-api-key': valid.token }), 'grant'),
+ );
+ }
+ }
+
+ // Revocation lifecycle (subscription lane): revoke the canary, then confirm
+ // the SAME key is now denied on the read-only route.
+ if (valid.source === 'subscription' && valid.subId) {
+ try {
+ await revokeSubscription(valid.subId);
+ const primary = AUDIT_ROUTES.find((r) => r.probeGrant) || AUDIT_ROUTES[0];
+ const url = `${origin}${primary.route}${primary.query || ''}`;
+ matrix.push(
+ classify('revoked-key', primary, await probe(url, primary, { 'x-api-key': valid.token }), 'deny'),
+ );
+ } catch (err) {
+ log.warn('api_key_bypass_revoke_probe_failed', { message: err?.message });
+ }
+ }
+ } finally {
+ // Belt-and-suspenders cleanup: never leave a live canary key.
+ if (valid.source === 'subscription' && valid.subId) {
+ try {
+ await revokeSubscription(valid.subId);
+ } catch { /* already revoked / DB blip — the 10-min expiry still bounds it */ }
+ }
+ }
+
+ const leak = matrix.some((m) => m.verdict === 'leak');
+ const bypassBroken = matrix.some((m) => m.verdict === 'bypass_broken');
+ const leaks = matrix.filter((m) => m.verdict === 'leak').length;
+ const grantTested = matrix.some((m) => m.scenario === 'valid-key');
+
+ // ── Paywall-proof payment: settle the no-key 402 once to prove the full
+ // paywall → verify → settle path still works (the "you must pay" side of the
+ // test). Best-effort: a missing wallet skips this step gracefully, the free
+ // bypass-matrix verdict above stands on its own. ────────────────────────────
+ let amountAtomic = 0;
+ let paidTx = null;
+ let paidStatus = null;
+ let paidSettled = false;
+ let payNote = null;
+
+ const payRoute = AUDIT_ROUTES.find((r) => r.pay);
+ let buyer = ctx.buyer;
+ if (!buyer) {
+ try {
+ buyer = loadSeedKeypair();
+ } catch (err) {
+ payNote = `wallet_unconfigured: ${err.message}`;
+ log.info('api_key_bypass_pay_skipped', { reason: payNote });
+ }
+ }
+ if (buyer && payRoute) {
+ let conn = ctx.conn;
+ let blockhash = ctx.blockhash;
+ let mintInfo = ctx.mintInfo;
+ if (!conn || !blockhash || !mintInfo) {
+ try {
+ ({ conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));
+ } catch (err) {
+ payNote = `solana_preflight_failed: ${err?.message}`;
+ log.warn('api_key_bypass_solana_preflight_failed', { message: err?.message });
+ }
+ }
+ if (conn && blockhash && mintInfo) {
+ const url = `${origin}${payRoute.route}${payRoute.query || ''}`;
+ const out = await payX402({
+ url,
+ method: payRoute.method,
+ body: payRoute.body || null,
+ buyer,
+ conn,
+ blockhash,
+ mintInfo,
+ remainingCap,
+ });
+ paidStatus = out.status;
+ paidSettled = !!(out.paid && out.txSig);
+ amountAtomic = out.paid ? out.amountAtomic : 0;
+ paidTx = out.txSig;
+ if (!out.paid) payNote = out.errorMsg || 'pay_unsettled';
+ }
+ }
+
+ // ── Verdict ────────────────────────────────────────────────────────────────
+ let verdict;
+ let pass;
+ if (leak) {
+ verdict = 'bypass_leak';
+ pass = false;
+ } else if (bypassBroken) {
+ verdict = 'bypass_broken';
+ pass = false;
+ } else if (!grantTested) {
+ // Deny matrix held, but we never confirmed a valid key grants access (no key
+ // source / network error) — not proof of a sound bypass lane.
+ verdict = 'inconclusive';
+ pass = false;
+ } else {
+ verdict = 'secure';
+ pass = true;
+ }
+
+ const errorMsg = leak
+ ? `api_key_bypass_leak: ${matrix.filter((m) => m.verdict === 'leak').map((m) => `${m.scenario}@${m.route}=${m.status}`).join(', ')}`
+ : bypassBroken
+ ? `api_key_bypass_broken: ${matrix.filter((m) => m.verdict === 'bypass_broken').map((m) => `${m.scenario}@${m.route}=${m.status}`).join(', ')}`
+ : payNote && !paidSettled && verdict === 'secure'
+ ? `paywall_payment_unverified: ${payNote}`
+ : null;
+
+ const primaryRoute = (AUDIT_ROUTES.find((r) => r.probeGrant) || AUDIT_ROUTES[0]).route;
+ const pick = (scenario, route) =>
+ matrix.find((m) => m.scenario === scenario && m.route === route) || null;
+ const validRow = pick('valid-key', primaryRoute);
+ const invalidRow = pick('invalid-key', primaryRoute);
+ const nokeyRow = pick('no-key', primaryRoute);
+ const revokedRow = pick('revoked-key', primaryRoute);
+ const durationMs = Date.now() - t0;
+
+ await storeAudit(sql, runId, {
+ route: primaryRoute,
+ valid_key_source: valid.source,
+ valid_status: validRow?.status ?? null,
+ valid_bypassed: validRow ? validRow.verdict === 'secure' : null,
+ invalid_status: invalidRow?.status ?? null,
+ invalid_denied: invalidRow ? invalidRow.verdict === 'secure' : null,
+ nokey_status: nokeyRow?.status ?? null,
+ nokey_challenged: nokeyRow ? nokeyRow.verdict === 'secure' : null,
+ revoked_status: revokedRow?.status ?? null,
+ revoked_denied: revokedRow ? revokedRow.verdict === 'secure' : null,
+ routes_tested: AUDIT_ROUTES.length,
+ leaks,
+ paid_status: paidStatus,
+ paid_settled: paidSettled,
+ paid_tx: paidTx,
+ amount_atomic: amountAtomic,
+ verdict,
+ pass,
+ leak,
+ details: matrix,
+ duration_ms: durationMs,
+ error_msg: errorMsg,
+ });
+
+ // A confirmed free-access leak is a security-critical event — page ops.
+ if (leak) {
+ sendOpsAlert(
+ 'x402 API-key bypass LEAK — paywall granting free access',
+ `The X-API-Key bypass lane granted free access where it must not: ` +
+ `${matrix.filter((m) => m.verdict === 'leak').map((m) => `${m.scenario} on ${m.route} → HTTP ${m.status}`).join('; ')}. ` +
+ `A missing or invalid key is bypassing payment — paid endpoints can be drained for free.`,
+ { signature: 'x402-api-key-bypass:leak' },
+ ).catch(() => {});
+ } else if (bypassBroken) {
+ // Lower severity: partners with valid keys are being charged/blocked.
+ sendOpsAlert(
+ 'x402 API-key bypass BROKEN — valid keys not honored',
+ `A valid API key failed to bypass the paywall: ` +
+ `${matrix.filter((m) => m.verdict === 'bypass_broken').map((m) => `${m.scenario} on ${m.route} → HTTP ${m.status}`).join('; ')}. ` +
+ `Subscribers are being charged for access they already pay for.`,
+ { signature: 'x402-api-key-bypass:broken' },
+ ).catch(() => {});
+ }
+
+ log.info('api_key_bypass_audit_complete', {
+ run_id: runId,
+ verdict,
+ pass,
+ leak,
+ bypass_broken: bypassBroken,
+ valid_key_source: valid.source,
+ paid_settled: paidSettled,
+ routes_tested: AUDIT_ROUTES.length,
+ duration_ms: durationMs,
+ });
+
+ const signalData = {
+ audited: true,
+ verdict,
+ pass,
+ leak,
+ bypass_broken: bypassBroken,
+ routes_tested: AUDIT_ROUTES.length,
+ leaks,
+ valid_key_source: valid.source,
+ grant_tested: grantTested,
+ paid_settled: paidSettled,
+ matrix: matrix.map((m) => ({ s: m.scenario, r: m.route, code: m.status, v: m.verdict })),
+ };
+
+ return {
+ // amountAtomic reflects ONLY the single legitimate paywall-proof payment.
+ success: pass,
+ amountAtomic,
+ txSig: paidTx,
+ responseData: {
+ matrix,
+ paid: { status: paidStatus, settled: paidSettled, tx: paidTx, note: payNote },
+ },
+ signalData,
+ valueExtracted: { verdict, leaks, routes_tested: AUDIT_ROUTES.length, paid_settled: paidSettled },
+ errorMsg,
+ note: verdict,
+ };
+}
+
+// Alias matching the pipelines convention (bazaar-warmup exports `run`).
+export { runApiKeyBypassAudit as run };
diff --git a/api/_lib/x402/pipelines/bazaar-catalog-refresh.js b/api/_lib/x402/pipelines/bazaar-catalog-refresh.js
new file mode 100644
index 000000000..46c29838c
--- /dev/null
+++ b/api/_lib/x402/pipelines/bazaar-catalog-refresh.js
@@ -0,0 +1,630 @@
+// api/_lib/x402/pipelines/bazaar-catalog-refresh.js
+//
+// Bazaar Service Catalog Daily Refresh — autonomous pipeline (self).
+//
+// Once a day the autonomous spend loop walks the ENTIRE x402 bazaar (every paid
+// agent service the facilitator network advertises), snapshots it, and diffs it
+// against yesterday's snapshot. The diff is the product:
+//
+// • added — services that appeared since yesterday → OPPORTUNITY alerts.
+// Fresh paid endpoints three.ws could onboard as EXTERNAL_ENDPOINTS.
+// • removed — services that vanished → PIPELINE-DEPENDENCY alerts. If any active
+// external registry entry pointed at a now-gone resource, that
+// pipeline is about to start failing — surface it before it does.
+// • repriced — services whose min price changed → cost-watch signal.
+//
+// How it differs from the Bazaar Discovery Warmup (bazaar-warmup.js): the warmup
+// sweeps 15 *category searches* to keep the search path warm and snapshots each
+// category. This pipeline does a *full-catalog census* (browse every service of
+// every type) and computes a single day-over-day diff over the whole catalog —
+// the source of truth for "what's new / gone / repriced on the bazaar today".
+// The two write to disjoint tables and never collide.
+//
+// Real x402 payments only. Each MCP tools/call against /api/mcp-bazaar is a real
+// on-chain $0.001 USDC payment from the platform seed wallet via payX402(). The
+// census is browse_services(http) + browse_services(mcp) (two paid calls), then
+// get_service(...) for each newly-appeared service (bounded) to capture its full
+// payment requirements for onboarding — the "bazaar_search_services +
+// bazaar_service_details" pair this use case is built on. If the wallet/RPC is
+// not configured, the pipeline exits gracefully with a logged, recorded skip and
+// never pays.
+//
+// Wiring: declared as a run()-style entry in autonomous-registry.js
+// (`bazaar-catalog-refresh`). The per-tick loop (api/cron/x402-autonomous-loop.js)
+// hands run() { origin, buyer, conn, blockhash, mintInfo, redis, sql, log, runId,
+// remainingCap } and — because this pipeline self-records one x402_autonomous_log
+// row per call — gets back { recorded: true } so the loop adds no duplicate row.
+//
+// Value extracted & where it lands:
+// • bazaar_catalog_snapshots — one row per UTC day: the full catalog (services
+// jsonb), catalog_hash, and the computed added / removed / repriced diff vs
+// the previous day. This is the snapshot + diff record.
+// • bazaar_service_index — durable per-service registry, keyed by service_key
+// (resource [+ #tool]). Tracks first_seen / last_seen, current price + the
+// full payment details from get_service, and status (active | removed). This
+// is the table downstream consumers read.
+// • Redis x402:bazaar:catalog:latest — newest census summary (counts + diff
+// sizes) for cheap dashboard reads without a DB round-trip.
+// • Redis x402:bazaar:dependency-alert — present (with TTL) only while a removed
+// service is still referenced by an active EXTERNAL_ENDPOINTS entry.
+//
+// Downstream consumers:
+// • External onboarding: bazaar_service_index WHERE status='active' ORDER BY
+// first_seen DESC is the candidate list agents read when wiring new
+// EXTERNAL_ENDPOINTS in autonomous-registry.js — the "opportunity" feed.
+// • Dependency safety: this pipeline itself cross-checks each removed resource
+// against the live external registry (getExternalRegistry) and raises the
+// Redis dependency-alert + a warn log so ops disables a dead external entry
+// before its loop call starts erroring.
+
+import { randomUUID, createHash } from 'node:crypto';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';
+import { isLivePricedService, serviceKey, extractServices } from './bazaar-warmup.js';
+
+const log = logger('x402-bazaar-catalog-refresh');
+
+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// The full catalog is the union of both service kinds the bazaar advertises.
+// browse_services has no offset cursor, so one call per type at the tool's max
+// limit (100) is the deepest census the MCP surface allows; the live facilitator
+// network returns well under that per type today, so this captures the catalog
+// in full. Documented honestly rather than faking an offset loop the API lacks.
+export const CATALOG_TYPES = ['http', 'mcp'];
+const BROWSE_LIMIT = 100;
+
+// Cap how many newly-appeared services we pay get_service for per run, so a day
+// where the bazaar adds dozens of services can't blow past a sane per-run spend.
+// New services beyond the cap are still recorded (from the browse census) and get
+// enriched on a later run once they're no longer "new"; the count dropped is logged.
+const ENRICH_MAX = Number(process.env.X402_BAZAAR_REFRESH_ENRICH_MAX || 8);
+
+const REDIS_LATEST_KEY = 'x402:bazaar:catalog:latest';
+const REDIS_DEP_ALERT_KEY = 'x402:bazaar:dependency-alert';
+// Dependency alert TTL: a little over two daily cycles so a missed run lets the
+// flag lapse rather than latching a stale alert forever.
+const DEP_ALERT_TTL_SECONDS = 50 * 3600;
+
+function utcDay(d = new Date()) {
+ return d.toISOString().slice(0, 10);
+}
+
+// ── JSON-RPC builders for the two bazaar MCP tools this pipeline pays for ──────
+function browseRpc(type, id) {
+ return {
+ jsonrpc: '2.0',
+ id,
+ method: 'tools/call',
+ params: { name: 'browse_services', arguments: { type, limit: BROWSE_LIMIT } },
+ };
+}
+
+function getServiceRpc(resourceUrl, toolName, id) {
+ return {
+ jsonrpc: '2.0',
+ id,
+ method: 'tools/call',
+ params: {
+ name: 'get_service',
+ arguments: { resource_url: resourceUrl, ...(toolName ? { tool_name: toolName } : {}) },
+ },
+ };
+}
+
+// Project a live bazaar listing down to the slim shape stored in the snapshot +
+// index. Keyed identically to the warmup so the two views agree on identity.
+function projectService(s) {
+ return {
+ key: serviceKey(s),
+ resource: s.resource,
+ tool_name: s.tool_name || null,
+ type: s.type || (s.tool_name ? 'mcp' : 'http'),
+ name: s.name || null,
+ description: s.description || null,
+ price_atomic: s.price_atomic ?? null,
+ price: s.price || null,
+ networks: Array.isArray(s.networks) ? s.networks : [],
+ tags: Array.isArray(s.tags) ? s.tags : [],
+ };
+}
+
+// Deterministic hash of the whole catalog (key + price) so a reprice OR an
+// add/remove flips it — a cheap "did anything change at all today?" check.
+export function catalogHash(services) {
+ const lines = services.map((s) => `${s.key}|${s.price_atomic ?? s.price ?? ''}`).sort();
+ return createHash('sha256').update(lines.join('\n')).digest('hex');
+}
+
+// Compute the day-over-day diff between two key→service maps.
+export function diffCatalog(prevMap, todayMap) {
+ const added = [];
+ const removed = [];
+ const repriced = [];
+ for (const [key, svc] of todayMap) {
+ if (!prevMap.has(key)) {
+ added.push({ key, resource: svc.resource, tool_name: svc.tool_name, name: svc.name, price_atomic: svc.price_atomic, networks: svc.networks });
+ } else {
+ const before = prevMap.get(key);
+ const a = before.price_atomic ?? null;
+ const b = svc.price_atomic ?? null;
+ if (a !== b) repriced.push({ key, resource: svc.resource, old_price_atomic: a, new_price_atomic: b });
+ }
+ }
+ for (const [key, svc] of prevMap) {
+ if (!todayMap.has(key)) {
+ removed.push({ key, resource: svc.resource, tool_name: svc.tool_name, name: svc.name });
+ }
+ }
+ return { added, removed, repriced };
+}
+
+// ── Schema ────────────────────────────────────────────────────────────────────
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ // One row per UTC day — the snapshot + the diff vs the prior day.
+ await sql`
+ CREATE TABLE IF NOT EXISTS bazaar_catalog_snapshots (
+ snapshot_date date PRIMARY KEY,
+ run_id uuid,
+ ts timestamptz NOT NULL DEFAULT now(),
+ service_count int NOT NULL DEFAULT 0,
+ http_count int NOT NULL DEFAULT 0,
+ mcp_count int NOT NULL DEFAULT 0,
+ catalog_hash text,
+ prev_date date,
+ changed boolean NOT NULL DEFAULT false,
+ added_count int NOT NULL DEFAULT 0,
+ removed_count int NOT NULL DEFAULT 0,
+ repriced_count int NOT NULL DEFAULT 0,
+ services jsonb NOT NULL DEFAULT '[]'::jsonb,
+ added jsonb NOT NULL DEFAULT '[]'::jsonb,
+ removed jsonb NOT NULL DEFAULT '[]'::jsonb,
+ repriced jsonb NOT NULL DEFAULT '[]'::jsonb,
+ errors jsonb
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS bazaar_catalog_snapshots_ts ON bazaar_catalog_snapshots (ts DESC)`;
+
+ // Durable per-service registry — the value sink consumers read. One row per
+ // service_key; first_seen/last_seen track lifetime, status flips on removal.
+ await sql`
+ CREATE TABLE IF NOT EXISTS bazaar_service_index (
+ service_key text PRIMARY KEY,
+ resource text NOT NULL,
+ tool_name text,
+ type text,
+ name text,
+ description text,
+ price_atomic bigint,
+ price text,
+ networks text[] NOT NULL DEFAULT '{}',
+ tags jsonb NOT NULL DEFAULT '[]'::jsonb,
+ details jsonb,
+ status text NOT NULL DEFAULT 'active',
+ first_seen timestamptz NOT NULL DEFAULT now(),
+ last_seen timestamptz NOT NULL DEFAULT now(),
+ removed_at timestamptz,
+ last_run_id uuid
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS bazaar_service_index_status_first ON bazaar_service_index (status, first_seen DESC)`;
+
+ // The autonomous log predates this pipeline; ensure value_extracted exists.
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+// Per-call row into x402_autonomous_log. This pipeline owns its granular rows
+// (one per paid bazaar call); the loop adds no summary row (outcome.recorded).
+async function recordCall(sql, runId, { serviceName, endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${serviceName}, ${endpointUrl},
+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},
+ ${responseData ? JSON.stringify(responseData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'discovery'})
+ `;
+ } catch (err) {
+ log.warn('bazaar_refresh_log_insert_failed', { service: serviceName, message: err?.message });
+ }
+}
+
+// Most-recent snapshot strictly before today, for the day-over-day diff.
+async function loadPreviousCatalog(sql, today) {
+ try {
+ const [row] = await sql`
+ SELECT snapshot_date, services
+ FROM bazaar_catalog_snapshots
+ WHERE snapshot_date < ${today}
+ ORDER BY snapshot_date DESC
+ LIMIT 1
+ `;
+ if (!row) return { prevDate: null, map: new Map() };
+ const map = new Map();
+ for (const s of Array.isArray(row.services) ? row.services : []) {
+ if (s?.key) map.set(s.key, s);
+ }
+ return { prevDate: row.snapshot_date, map };
+ } catch (err) {
+ if (!/does not exist/i.test(err?.message || '')) {
+ log.warn('bazaar_refresh_prev_load_failed', { message: err?.message });
+ }
+ return { prevDate: null, map: new Map() };
+ }
+}
+
+// Pull the full payment requirements out of a get_service tools/call body.
+function extractServiceDetails(responseBody) {
+ const sc = responseBody?.result?.structuredContent;
+ if (!sc || !sc.resource) return null;
+ return {
+ resource: sc.resource,
+ tool_name: sc.tool_name || null,
+ name: sc.name || null,
+ description: sc.description || null,
+ accepts: Array.isArray(sc.accepts) ? sc.accepts : [],
+ input_schema: sc.input_schema || null,
+ pay_link: sc.pay_link || null,
+ };
+}
+
+// Upsert today's live services into the durable index, refreshing price/details
+// and last_seen. Returns nothing — best-effort, never throws past the loop.
+async function indexActiveServices(sql, runId, services, detailsByKey) {
+ for (const s of services) {
+ const details = detailsByKey.get(s.key) || null;
+ try {
+ await sql`
+ INSERT INTO bazaar_service_index
+ (service_key, resource, tool_name, type, name, description,
+ price_atomic, price, networks, tags, details, status,
+ first_seen, last_seen, removed_at, last_run_id)
+ VALUES
+ (${s.key}, ${s.resource}, ${s.tool_name}, ${s.type}, ${s.name}, ${s.description},
+ ${s.price_atomic}, ${s.price}, ${s.networks}, ${JSON.stringify(s.tags)},
+ ${details ? JSON.stringify(details) : null}, ${'active'},
+ now(), now(), ${null}, ${runId})
+ ON CONFLICT (service_key) DO UPDATE SET
+ resource = EXCLUDED.resource,
+ tool_name = EXCLUDED.tool_name,
+ type = EXCLUDED.type,
+ name = EXCLUDED.name,
+ description = EXCLUDED.description,
+ price_atomic = EXCLUDED.price_atomic,
+ price = EXCLUDED.price,
+ networks = EXCLUDED.networks,
+ tags = EXCLUDED.tags,
+ details = COALESCE(EXCLUDED.details, bazaar_service_index.details),
+ status = 'active',
+ last_seen = now(),
+ removed_at = NULL,
+ last_run_id = EXCLUDED.last_run_id
+ `;
+ } catch (err) {
+ log.warn('bazaar_refresh_index_upsert_failed', { key: s.key, message: err?.message });
+ }
+ }
+}
+
+// Mark services that disappeared this run as removed (status + removed_at).
+async function markRemovedServices(sql, runId, removed) {
+ for (const r of removed) {
+ try {
+ await sql`
+ UPDATE bazaar_service_index
+ SET status = 'removed', removed_at = now(), last_run_id = ${runId}
+ WHERE service_key = ${r.key} AND status <> 'removed'
+ `;
+ } catch (err) {
+ log.warn('bazaar_refresh_mark_removed_failed', { key: r.key, message: err?.message });
+ }
+ }
+}
+
+// Cross-check removed resources against the live external registry. If any active
+// EXTERNAL_ENDPOINTS entry pointed at a now-gone bazaar resource, its loop call is
+// about to start failing — raise a dependency alert (Redis + warn log).
+async function checkDependencyImpact(redis, removed) {
+ let externals = [];
+ try {
+ // Lazy import to avoid a static import cycle (autonomous-registry imports
+ // this pipeline's run() at module-eval time).
+ const { getExternalRegistry } = await import('../autonomous-registry.js');
+ externals = getExternalRegistry().filter((e) => e && e.enabled !== false);
+ } catch { externals = []; }
+ if (!externals.length || !removed.length) {
+ if (redis) { try { await redis.del(REDIS_DEP_ALERT_KEY); } catch { /* non-fatal */ } }
+ return [];
+ }
+ const removedResources = new Set(removed.map((r) => r.resource).filter(Boolean));
+ const impacted = externals
+ .filter((e) => {
+ const url = e.url || '';
+ for (const res of removedResources) {
+ if (res && (url === res || url.startsWith(res) || res.startsWith(url))) return true;
+ }
+ return false;
+ })
+ .map((e) => ({ id: e.id, name: e.name, url: e.url }));
+
+ if (redis) {
+ try {
+ if (impacted.length) {
+ await redis.set(REDIS_DEP_ALERT_KEY, JSON.stringify({ ts: new Date().toISOString(), impacted }), { ex: DEP_ALERT_TTL_SECONDS });
+ } else {
+ await redis.del(REDIS_DEP_ALERT_KEY);
+ }
+ } catch (err) {
+ log.warn('bazaar_refresh_dep_alert_write_failed', { message: err?.message });
+ }
+ }
+ if (impacted.length) {
+ log.warn('bazaar_dependency_alert', { impacted });
+ }
+ return impacted;
+}
+
+async function writeRedisLatest(redis, summary) {
+ if (!redis) return;
+ try {
+ await redis.set(REDIS_LATEST_KEY, JSON.stringify(summary), { ex: DEP_ALERT_TTL_SECONDS });
+ } catch (err) {
+ log.warn('bazaar_refresh_redis_latest_failed', { message: err?.message });
+ }
+}
+
+/**
+ * Run the catalog refresh. Conforms to the run()-style registry contract: the
+ * loop hands { origin, buyer, conn, blockhash, mintInfo, redis, sql, log, runId,
+ * remainingCap }; standalone (manual test) it bootstraps its own Solana context.
+ *
+ * Self-records one x402_autonomous_log row per paid call and returns
+ * { recorded: true } so the loop adds no duplicate summary row.
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const sql = ctx.sql || defaultSql;
+ const redis = ctx.redis || null;
+ const endpointUrl = `${origin}/api/mcp-bazaar`;
+ const today = utcDay();
+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+
+ // ── Schema first: without the sink there's nothing to extract, so don't pay.
+ try {
+ await ensureSchema(sql);
+ } catch (err) {
+ log.warn('bazaar_refresh_schema_failed', { message: err?.message });
+ return { success: false, skipped: true, recorded: false, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };
+ }
+
+ // ── Solana payment context: reuse the loop's, else bootstrap (graceful on an
+ // unconfigured wallet — bootstrap throws, we exit logged without paying).
+ let { buyer, conn, blockhash, mintInfo } = ctx;
+ if (!buyer || !conn || !blockhash || !mintInfo) {
+ try {
+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer }));
+ } catch (err) {
+ log.info('bazaar_refresh_skipped', { reason: err.message });
+ return { success: false, skipped: true, recorded: false, amountAtomic: 0, errorMsg: err.message, note: 'wallet_or_rpc_unconfigured' };
+ }
+ }
+
+ let spentAtomic = 0;
+ let paid = 0;
+ let lastTxSig = null;
+ let callErrors = 0;
+ const callErrorMsgs = [];
+ const todayMap = new Map();
+ const countsByType = { http: 0, mcp: 0 };
+
+ // ── Census: browse every service of every type (one paid call per type) ─────
+ for (let i = 0; i < CATALOG_TYPES.length; i++) {
+ const type = CATALOG_TYPES[i];
+ if (remainingCap <= 0) { log.info('bazaar_refresh_cap_reached', { type, spent_atomic: spentAtomic }); break; }
+
+ const t0 = Date.now();
+ let result;
+ try {
+ result = await payX402({
+ url: endpointUrl, method: 'POST', body: browseRpc(type, i + 1),
+ buyer, conn, blockhash, mintInfo, remainingCap, nonce: i + 1,
+ });
+ } catch (err) {
+ callErrors += 1;
+ callErrorMsgs.push(`browse_${type}: ${err?.message || 'fetch_failed'}`);
+ await recordCall(sql, runId, {
+ serviceName: `Bazaar Census: browse ${type}`, endpointUrl, amountAtomic: 0, txSig: null,
+ responseData: null, durationMs: Date.now() - t0, success: false,
+ errorMsg: err?.message || 'fetch_failed', valueExtracted: null,
+ });
+ continue;
+ }
+
+ if (result.paid) { spentAtomic += result.amountAtomic; remainingCap -= result.amountAtomic; paid += 1; if (result.txSig) lastTxSig = result.txSig; }
+
+ const { services, errors, hasResult } = extractServices(result.responseBody);
+ let live = 0;
+ if (result.success && hasResult) {
+ for (const raw of services) {
+ if (!isLivePricedService(raw)) continue;
+ const p = projectService(raw);
+ if (!p.key) continue;
+ if (!todayMap.has(p.key)) { todayMap.set(p.key, p); live += 1; countsByType[type] = (countsByType[type] || 0) + 1; }
+ }
+ } else {
+ callErrors += 1;
+ callErrorMsgs.push(`browse_${type}: ${result.errorMsg || `status_${result.status}`}`);
+ }
+
+ await recordCall(sql, runId, {
+ serviceName: `Bazaar Census: browse ${type}`,
+ endpointUrl,
+ amountAtomic: result.amountAtomic,
+ txSig: result.txSig,
+ responseData: { status: result.status, total: services.length, live, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
+ success: result.success && hasResult,
+ errorMsg: result.errorMsg || (errors ? 'facilitator_errors' : null),
+ valueExtracted: { type, live, total: services.length },
+ });
+ }
+
+ // ── Diff vs the previous day ───────────────────────────────────────────────
+ const { prevDate, map: prevMap } = await loadPreviousCatalog(sql, today);
+ const { added, removed, repriced } = diffCatalog(prevMap, todayMap);
+ const hash = catalogHash([...todayMap.values()]);
+ // First-ever run (no prior snapshot): everything is "seen", nothing is an
+ // opportunity/removal yet — suppress the noise of a whole-catalog "added".
+ const firstRun = prevMap.size === 0 && prevDate == null;
+ const opportunities = firstRun ? [] : added;
+ const removals = firstRun ? [] : removed;
+ const reprices = firstRun ? [] : repriced;
+
+ // ── Enrich opportunity alerts: pay get_service for each new service (bounded)
+ const detailsByKey = new Map();
+ const toEnrich = opportunities.slice(0, ENRICH_MAX);
+ const enrichDropped = Math.max(0, opportunities.length - toEnrich.length);
+ for (let i = 0; i < toEnrich.length; i++) {
+ const svc = toEnrich[i];
+ if (remainingCap <= 0) { log.info('bazaar_refresh_enrich_cap_reached', { remaining: toEnrich.length - i }); break; }
+
+ const t0 = Date.now();
+ let result;
+ try {
+ result = await payX402({
+ url: endpointUrl, method: 'POST',
+ body: getServiceRpc(svc.resource, svc.tool_name, 100 + i),
+ buyer, conn, blockhash, mintInfo, remainingCap, nonce: 100 + i,
+ });
+ } catch (err) {
+ callErrors += 1;
+ callErrorMsgs.push(`get_service ${svc.key}: ${err?.message || 'fetch_failed'}`);
+ await recordCall(sql, runId, {
+ serviceName: `Bazaar Details: ${svc.name || svc.resource}`, endpointUrl, amountAtomic: 0, txSig: null,
+ responseData: null, durationMs: Date.now() - t0, success: false,
+ errorMsg: err?.message || 'fetch_failed', valueExtracted: null,
+ });
+ continue;
+ }
+
+ if (result.paid) { spentAtomic += result.amountAtomic; remainingCap -= result.amountAtomic; paid += 1; if (result.txSig) lastTxSig = result.txSig; }
+
+ const details = result.success ? extractServiceDetails(result.responseBody) : null;
+ if (details) detailsByKey.set(svc.key, details);
+ else { callErrors += 1; callErrorMsgs.push(`get_service ${svc.key}: ${result.errorMsg || `status_${result.status}`}`); }
+
+ await recordCall(sql, runId, {
+ serviceName: `Bazaar Details: ${svc.name || svc.resource}`,
+ endpointUrl,
+ amountAtomic: result.amountAtomic,
+ txSig: result.txSig,
+ responseData: { status: result.status, resolved: !!details, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
+ success: result.success && !!details,
+ errorMsg: result.errorMsg,
+ valueExtracted: details ? { resource: details.resource, accepts: details.accepts.length, opportunity: true } : null,
+ });
+ }
+
+ // ── Persist: the durable index, the removals, and the daily snapshot row ────
+ const todayServices = [...todayMap.values()];
+ await indexActiveServices(sql, runId, todayServices, detailsByKey);
+ await markRemovedServices(sql, runId, removals);
+
+ const changed = prevDate != null && (opportunities.length > 0 || removals.length > 0 || reprices.length > 0);
+ try {
+ await sql`
+ INSERT INTO bazaar_catalog_snapshots
+ (snapshot_date, run_id, ts, service_count, http_count, mcp_count, catalog_hash,
+ prev_date, changed, added_count, removed_count, repriced_count,
+ services, added, removed, repriced, errors)
+ VALUES
+ (${today}, ${runId}, now(), ${todayServices.length}, ${countsByType.http || 0}, ${countsByType.mcp || 0}, ${hash},
+ ${prevDate}, ${changed}, ${opportunities.length}, ${removals.length}, ${reprices.length},
+ ${JSON.stringify(todayServices)}, ${JSON.stringify(opportunities)},
+ ${JSON.stringify(removals)}, ${JSON.stringify(reprices)},
+ ${callErrorMsgs.length ? JSON.stringify(callErrorMsgs) : null})
+ ON CONFLICT (snapshot_date) DO UPDATE SET
+ run_id = EXCLUDED.run_id,
+ ts = now(),
+ service_count = EXCLUDED.service_count,
+ http_count = EXCLUDED.http_count,
+ mcp_count = EXCLUDED.mcp_count,
+ catalog_hash = EXCLUDED.catalog_hash,
+ prev_date = EXCLUDED.prev_date,
+ changed = EXCLUDED.changed,
+ added_count = EXCLUDED.added_count,
+ removed_count = EXCLUDED.removed_count,
+ repriced_count = EXCLUDED.repriced_count,
+ services = EXCLUDED.services,
+ added = EXCLUDED.added,
+ removed = EXCLUDED.removed,
+ repriced = EXCLUDED.repriced,
+ errors = EXCLUDED.errors
+ `;
+ } catch (err) {
+ log.warn('bazaar_refresh_snapshot_failed', { message: err?.message });
+ }
+
+ // ── Alerts: pipeline-dependency impact + cheap dashboard summary ────────────
+ const impacted = await checkDependencyImpact(redis, removals);
+ const summary = {
+ ts: new Date().toISOString(),
+ snapshot_date: today,
+ prev_date: prevDate,
+ service_count: todayServices.length,
+ http_count: countsByType.http || 0,
+ mcp_count: countsByType.mcp || 0,
+ added: opportunities.length,
+ removed: removals.length,
+ repriced: reprices.length,
+ dependency_impacted: impacted.length,
+ first_run: firstRun,
+ };
+ await writeRedisLatest(redis, summary);
+
+ log.info('bazaar_refresh_complete', {
+ run_id: runId, snapshot_date: today, prev_date: prevDate,
+ services: todayServices.length, http: countsByType.http || 0, mcp: countsByType.mcp || 0,
+ added: opportunities.length, removed: removals.length, repriced: reprices.length,
+ enriched: detailsByKey.size, enrich_dropped: enrichDropped,
+ dependency_impacted: impacted.length, paid, spent_usdc: (spentAtomic / 1e6).toFixed(4),
+ });
+
+ // Aggregate outcome for the loop. recorded:true — the per-call rows above are
+ // the canonical record; the loop adds no duplicate summary row.
+ return {
+ success: paid > 0 || todayServices.length > 0,
+ recorded: true,
+ amountAtomic: spentAtomic,
+ txSig: lastTxSig,
+ errorMsg: paid === 0 && callErrors > 0 ? `bazaar_refresh_calls_failed:${callErrors}` : null,
+ skipped: paid === 0 && todayServices.length === 0,
+ responseData: {
+ service_count: todayServices.length, added: opportunities.length,
+ removed: removals.length, repriced: reprices.length, paid,
+ },
+ note: `bazaar_refresh services=${todayServices.length} +${opportunities.length}/-${removals.length}/~${reprices.length} impacted=${impacted.length}`,
+ };
+}
+
+export const BAZAAR_CATALOG_REFRESH = Object.freeze({
+ endpoint: '/api/mcp-bazaar',
+ priceAtomic: 1000, // $0.001 USDC per call
+ cooldownSeconds: 86400, // daily census
+ redisLatestKey: REDIS_LATEST_KEY,
+ redisDependencyAlertKey: REDIS_DEP_ALERT_KEY,
+ enrichMax: ENRICH_MAX,
+});
diff --git a/api/_lib/x402/pipelines/builder-code-attribution.js b/api/_lib/x402/pipelines/builder-code-attribution.js
new file mode 100644
index 000000000..b34f4bd69
--- /dev/null
+++ b/api/_lib/x402/pipelines/builder-code-attribution.js
@@ -0,0 +1,517 @@
+// api/_lib/x402/pipelines/builder-code-attribution.js
+//
+// Builder Code Attribution Tracker — autonomous pipeline (self / Finance).
+//
+// Coinbase builder rewards (and x402scan analytics) credit on-chain x402
+// volume to the app that exposed the paid endpoint via the ERC-8021 Schema 2
+// `builder-code` extension. For three.ws that app code is
+// `three_d_agent` (env X402_BUILDER_CODE_APP). The credit only happens when:
+//
+// 1. the paid endpoint DECLARES the builder-code extension on its 402
+// challenge (extensions["builder-code"].info.a = "three_d_agent"), AND
+// 2. the buyer ECHOES that app code in its X-PAYMENT payload, so the
+// facilitator suffixes the settlement-tx calldata with the attribution
+// CBOR map at settle time.
+//
+// If a single priced endpoint silently drops the declaration (a route that
+// bypasses build402Body, an env regression that unsets X402_BUILDER_CODE_APP,
+// or a deploy that forgets the extension), every USDC dollar that endpoint
+// settles is UNATTRIBUTED — real revenue that earns three.ws zero builder
+// rewards. Nothing surfaces that gap today.
+//
+// This tracker is the watchdog. Every 6h the autonomous loop calls run(ctx):
+//
+// • ATTRIBUTION SWEEP (free) — probes a representative set of priced
+// /api/x402/* endpoints for their live 402 challenge and verifies each one
+// declares the builder-code extension with a === three_d_agent. Any 402
+// endpoint missing/mismatched is an attribution gap → alert.
+//
+// • SETTLEMENT PROOF (one real $0.001 payment) — pays the cheapest declaring
+// endpoint (dance-tip) with the builder-code echo ATTACHED to the X-PAYMENT
+// envelope (a=three_d_agent, w=<wallet code>, s=[builder_code_attribution]),
+// then reads the X-PAYMENT-RESPONSE header. The resource server enforces the
+// echo (it rejects a non-echoing payment with `builder_code_tampered`, 402),
+// so a 200 + settled tx signature is end-to-end proof that an ATTRIBUTED
+// payment settles on-chain — the tx Coinbase's reward indexer reads. The
+// header's settlement object (transaction/network/payer, plus any
+// extensions the route echoes back) is captured for audit.
+//
+// Value sink: builder_code_attribution (one upserted row per endpoint, keyed by
+// endpoint). Columns carry the per-endpoint declaration verdict + the live
+// settlement proof. See ensureSchema() below for the full shape.
+//
+// Downstream consumer: api/ops/health.js → loadBuilderAttribution() folds an
+// attribution gap (a priced endpoint that stopped declaring three_d_agent, or
+// a failed attributed settlement) into the platform health verdict so on-call
+// sees lost-rewards risk before a billing cycle closes.
+//
+// The loop owns cooldown, daily-spend accounting and the single summary row in
+// x402_autonomous_log (value_extracted = the attribution summary). This module
+// owns the probes, the attributed payment, the per-endpoint persistence and the
+// gap detection. No mocks — every probe reads a live challenge and the proof is
+// a real on-chain USDC payment.
+
+import { randomUUID } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { BUILDER_CODE, isValidBuilderCode } from '../../x402-builder-code.js';
+import {
+ fetchWithTimeout,
+ parseSolanaAccept,
+ buildPaymentTx,
+ bootstrapSolanaContext,
+ USDC_MINT,
+} from '../pay.js';
+
+const log = logger('x402-builder-code-attribution');
+
+const USER_AGENT = 'threews-x402-builder-attribution/1.0';
+
+// The service code this tracker self-attributes with on its settlement echo.
+const SERVICE_CODE = 'builder_code_attribution';
+
+// Redis flag a consumer can read in one GET to learn an attribution gap is open.
+const REDIS_ALERT_KEY = 'x402:builder-attribution:alert';
+const ALERT_TTL_SECONDS = 7 * 60 * 60; // a little over the 6h cadence
+
+// Representative set of priced /api/x402/* endpoints. Every one of these flows
+// through paidEndpoint → build402Body, which auto-declares the builder-code
+// extension when X402_BUILDER_CODE_APP is set — so each is expected to advertise
+// `a = three_d_agent` on its 402 challenge. `settle: true` marks the single
+// endpoint we actually pay (the cheapest, $0.001 dance-tip) to prove the
+// attributed settlement path end-to-end; the rest are probe-only (free).
+const SWEEP_ENDPOINTS = [
+ {
+ // dance-tip is GET (query params); booking one $0.001 dance is the same
+ // benign side effect the volume entries already produce, so it's our paid
+ // settlement proof. The probe (free 402) books nothing; the ticket is
+ // created only after payment settles.
+ path: '/api/x402/dance-tip?dancer=4&dance=hiphop',
+ method: 'GET',
+ body: null,
+ settle: true,
+ },
+ {
+ // model-check keys on a query param; a stable public rig keeps the probe
+ // deterministic. The probe never pays, so it books nothing.
+ path: `/api/x402/model-check?url=${encodeURIComponent('https://three.ws/avatars/xbot.glb')}`,
+ method: 'GET',
+ body: null,
+ },
+ { path: '/api/x402/crypto-intel', method: 'POST', body: { topic: 'solana' } },
+ {
+ // token-intel is GET (?mint=…). Canary: the well-known USDC mint.
+ path: '/api/x402/token-intel?mint=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&network=mainnet',
+ method: 'GET',
+ body: null,
+ },
+ { path: '/api/x402/fact-check', method: 'POST', body: { claim: 'The sky is blue' } },
+ {
+ // symbol-availability is GET (?ticker=…&network=…).
+ path: '/api/x402/symbol-availability?ticker=HEALTH&network=mainnet',
+ method: 'GET',
+ body: null,
+ },
+];
+
+// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS builder_code_attribution (
+ endpoint text PRIMARY KEY,
+ method text,
+ challenged boolean NOT NULL DEFAULT false, -- returned a real 402
+ attributed boolean NOT NULL DEFAULT false, -- declared builder-code on the challenge
+ declared_code text, -- the app code (a) advertised
+ expected_code text, -- X402_BUILDER_CODE_APP in force
+ matches boolean NOT NULL DEFAULT false, -- declared_code === expected_code
+ price_atomic bigint, -- challenge amount (atomics)
+ gap boolean NOT NULL DEFAULT false, -- 402 endpoint with missing/mismatched attribution
+ settled boolean NOT NULL DEFAULT false, -- this endpoint carried the live settlement proof
+ echo_accepted boolean NOT NULL DEFAULT false, -- attributed payment settled (server enforces echo)
+ response_attributed boolean NOT NULL DEFAULT false, -- X-PAYMENT-RESPONSE echoed a builder-code block
+ tx_signature text,
+ payer text,
+ error text,
+ run_id uuid,
+ checked_at timestamptz DEFAULT now()
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS builder_code_attribution_gap_idx ON builder_code_attribution (gap) WHERE gap = true`;
+ _schemaReady = true;
+}
+
+async function upsertRow(sql, runId, row) {
+ await sql`
+ INSERT INTO builder_code_attribution
+ (endpoint, method, challenged, attributed, declared_code, expected_code,
+ matches, price_atomic, gap, settled, echo_accepted, response_attributed,
+ tx_signature, payer, error, run_id, checked_at)
+ VALUES
+ (${row.endpoint}, ${row.method}, ${row.challenged}, ${row.attributed},
+ ${row.declared_code || null}, ${row.expected_code || null},
+ ${row.matches}, ${row.price_atomic ?? null}, ${row.gap}, ${row.settled},
+ ${row.echo_accepted}, ${row.response_attributed},
+ ${row.tx_signature || null}, ${row.payer || null}, ${row.error || null},
+ ${runId}, now())
+ ON CONFLICT (endpoint) DO UPDATE SET
+ method = EXCLUDED.method,
+ challenged = EXCLUDED.challenged,
+ attributed = EXCLUDED.attributed,
+ declared_code = EXCLUDED.declared_code,
+ expected_code = EXCLUDED.expected_code,
+ matches = EXCLUDED.matches,
+ price_atomic = EXCLUDED.price_atomic,
+ gap = EXCLUDED.gap,
+ settled = EXCLUDED.settled,
+ echo_accepted = EXCLUDED.echo_accepted,
+ response_attributed = EXCLUDED.response_attributed,
+ tx_signature = EXCLUDED.tx_signature,
+ payer = EXCLUDED.payer,
+ error = EXCLUDED.error,
+ run_id = EXCLUDED.run_id,
+ checked_at = now()
+ `;
+}
+
+async function persistRows(sql, log, runId, rows) {
+ try {
+ await ensureSchema(sql);
+ for (const row of rows) await upsertRow(sql, runId, row);
+ } catch (err) {
+ log?.warn?.('builder_attribution_persist_failed', { message: err?.message });
+ }
+}
+
+// Pull the declared app builder code off a live 402 challenge body.
+function declaredAppCode(challenge) {
+ const a = challenge?.extensions?.[BUILDER_CODE]?.info?.a;
+ return typeof a === 'string' ? a : null;
+}
+
+// Probe one endpoint for its 402 challenge and classify the attribution verdict.
+// Free read — never pays. A non-402 response means the endpoint isn't priced
+// (no rewards to attribute), recorded as not-a-gap.
+async function probeEndpoint(origin, expectedCode, ep) {
+ const endpointUrl = `${origin}${ep.path}`;
+ const base = {
+ endpoint: ep.path,
+ method: ep.method,
+ challenged: false,
+ attributed: false,
+ declared_code: null,
+ expected_code: expectedCode,
+ matches: false,
+ price_atomic: null,
+ gap: false,
+ settled: false,
+ echo_accepted: false,
+ response_attributed: false,
+ tx_signature: null,
+ payer: null,
+ error: null,
+ _settle: !!ep.settle,
+ _endpointUrl: endpointUrl,
+ _body: ep.body,
+ };
+ try {
+ const res = await fetchWithTimeout(endpointUrl, {
+ method: ep.method,
+ headers: { 'content-type': 'application/json', 'user-agent': USER_AGENT },
+ ...(ep.body != null ? { body: JSON.stringify(ep.body) } : {}),
+ });
+ if (res.status !== 402) {
+ // Not a priced challenge this call — nothing to attribute, not a gap.
+ base.error = `not_402:http_${res.status}`;
+ return base;
+ }
+ base.challenged = true;
+ base.challenge = res.body;
+ const accept = parseSolanaAccept(res.body);
+ if (accept?.amount != null) base.price_atomic = Number(accept.amount);
+ base.accept = accept;
+ const code = declaredAppCode(res.body);
+ base.declared_code = code;
+ base.attributed = !!code;
+ base.matches = !!code && code === expectedCode;
+ // A priced (402) endpoint that fails to declare the expected app code can
+ // never be credited — that is the attribution gap we alert on.
+ base.gap = !base.matches;
+ if (!base.attributed) base.error = 'builder_code_not_declared';
+ else if (!base.matches) base.error = `builder_code_mismatch:${code}`;
+ return base;
+ } catch (err) {
+ base.error = `probe_failed:${err?.message || 'network'}`;
+ return base;
+ }
+}
+
+// Settle ONE real attributed payment against the dance-tip challenge captured in
+// the probe. Builds the SPL transfer, attaches the builder-code echo to the
+// X-PAYMENT envelope, replays the request, and reads the X-PAYMENT-RESPONSE
+// settlement. Returns the settlement outcome — never throws for protocol faults.
+async function settleAttributed({ row, buyer, conn, blockhash, mintInfo, remainingCap, expectedCode }) {
+ const accept = row.accept;
+ const out = { amountAtomic: 0, txSig: null, payer: null, echoAccepted: false, responseAttributed: false, settleResp: null, error: null };
+
+ if (!accept) { out.error = 'no_solana_accept'; return out; }
+ if (!USDC_MINT || accept.asset !== USDC_MINT) { out.error = `unexpected_asset:${accept.asset}`; return out; }
+ if (!accept.extra?.feePayer) { out.error = 'missing_fee_payer'; return out; }
+
+ const amountAtomic = Number(accept.amount || 0);
+ if (amountAtomic > (remainingCap ?? Infinity)) { out.error = 'cap_would_exceed'; return out; }
+
+ // Echo the declared app code (anti-tamper: the server rejects a mismatch) and
+ // self-attribute the wallet + service so the settlement CBOR records who
+ // exposed the endpoint (a), who paid (w), and which service ran (s).
+ const declaredA = declaredAppCode(row.challenge) || expectedCode;
+ const echo = { a: declaredA };
+ const walletCode = env.X402_BUILDER_CODE_WALLET;
+ if (isValidBuilderCode(walletCode)) echo.w = walletCode;
+ echo.s = [SERVICE_CODE];
+
+ try {
+ const receiverAta = getAssociatedTokenAddressSync(
+ new PublicKey(accept.asset), new PublicKey(accept.payTo),
+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);
+ const txBase64 = buildPaymentTx({
+ accept, buyer, blockhash, mintInfo,
+ receiverAtaExists: receiverAtaInfo !== null,
+ });
+ const xPayment = Buffer.from(JSON.stringify({
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: row._endpointUrl, mimeType: 'application/json' },
+ payload: { transaction: txBase64 },
+ accepted: accept,
+ extensions: { [BUILDER_CODE]: echo },
+ })).toString('base64');
+
+ const paidRes = await fetchWithTimeout(row._endpointUrl, {
+ method: row.method,
+ headers: {
+ 'content-type': 'application/json',
+ 'user-agent': USER_AGENT,
+ 'x-payment': xPayment,
+ },
+ ...(row._body != null ? { body: JSON.stringify(row._body) } : {}),
+ });
+
+ if (!paidRes.ok) {
+ // A 402 here with builder_code_tampered would mean the echo was rejected —
+ // captured verbatim so the verdict reflects exactly why attribution failed.
+ const reason = paidRes.body?.error || paidRes.body?.code || `http_${paidRes.status}`;
+ out.error = typeof reason === 'string' ? reason : `http_${paidRes.status}`;
+ return out;
+ }
+
+ // 200 + accepted echo = the attributed payment settled. Read the receipt.
+ out.echoAccepted = true;
+ out.amountAtomic = amountAtomic;
+ const header = paidRes.headers?.get?.('x-payment-response');
+ if (header) {
+ try {
+ const settled = JSON.parse(Buffer.from(header, 'base64').toString('utf8'));
+ out.settleResp = settled;
+ out.txSig = settled?.transaction || null;
+ out.payer = settled?.payer || null;
+ out.responseAttributed = !!settled?.extensions?.[BUILDER_CODE];
+ } catch { /* header malformed — settlement still happened */ }
+ }
+ return out;
+ } catch (err) {
+ out.error = `settle_threw:${err?.message || 'unknown'}`;
+ return out;
+ }
+}
+
+/**
+ * Builder Code Attribution Tracker executor (run()-style registry contract).
+ *
+ * @param {object} ctx — supplied by the autonomous loop:
+ * { origin, buyer, conn, blockhash, mintInfo, remainingCap, redis, sql, log, runId }.
+ * All optional for standalone/manual runs (Solana context is bootstrapped on demand).
+ * @returns the aggregate outcome the loop records to x402_autonomous_log:
+ * { success, amountAtomic, txSig, responseData, signalData, valueExtracted, errorMsg, note }
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const sql = ctx.sql || defaultSql;
+ const redis = ctx.redis || null;
+ const expectedCode = env.X402_BUILDER_CODE_APP || null;
+
+ // Attribution is disabled platform-wide when no app code is configured — there
+ // is nothing to track and no rewards to earn. Record the state, spend nothing.
+ if (!expectedCode) {
+ log.info('builder_attribution_disabled', { run_id: runId });
+ return {
+ success: false,
+ amountAtomic: 0,
+ txSig: null,
+ skipped: true,
+ signalData: { enabled: false },
+ errorMsg: 'builder_code_app_unset',
+ note: 'X402_BUILDER_CODE_APP unset — attribution disabled',
+ };
+ }
+
+ // ── Phase 1: attribution sweep (free probes) ──────────────────────────────
+ const rows = await Promise.all(SWEEP_ENDPOINTS.map((ep) => probeEndpoint(origin, expectedCode, ep)));
+
+ // ── Phase 2: settlement proof (one real attributed payment) ───────────────
+ // Pay the cheapest declaring endpoint to prove an attributed settlement lands
+ // on-chain. Skip the payment if that endpoint never declared attribution (the
+ // gap is already recorded) or the wallet isn't configured.
+ const settleRow = rows.find((r) => r._settle && r.challenged && r.matches);
+ let amountAtomic = 0;
+ let txSig = null;
+ let settleResp = null;
+
+ if (settleRow) {
+ let solana = null;
+ if (ctx.buyer && ctx.conn && ctx.blockhash && ctx.mintInfo) {
+ solana = { buyer: ctx.buyer, conn: ctx.conn, blockhash: ctx.blockhash, mintInfo: ctx.mintInfo };
+ } else {
+ // Standalone/manual run — bootstrap our own Solana context. A missing
+ // keypair degrades gracefully (recorded, no spend).
+ try {
+ solana = await bootstrapSolanaContext({ buyer: ctx.buyer });
+ } catch (err) {
+ settleRow.error = `wallet_unconfigured:${err?.message || 'no_keypair'}`;
+ }
+ }
+
+ if (solana) {
+ const r = await settleAttributed({
+ row: settleRow,
+ buyer: solana.buyer,
+ conn: solana.conn,
+ blockhash: solana.blockhash,
+ mintInfo: solana.mintInfo,
+ remainingCap: ctx.remainingCap,
+ expectedCode,
+ });
+ settleRow.settled = r.echoAccepted;
+ settleRow.echo_accepted = r.echoAccepted;
+ settleRow.response_attributed = r.responseAttributed;
+ settleRow.tx_signature = r.txSig;
+ settleRow.payer = r.payer;
+ if (r.error) settleRow.error = r.error;
+ amountAtomic = r.amountAtomic;
+ txSig = r.txSig;
+ settleResp = r.settleResp;
+ }
+ }
+
+ // ── Persist per-endpoint verdicts (the value sink) ────────────────────────
+ await persistRows(sql, log, runId, rows.map(stripScratch));
+
+ // ── Derive the summary + alert state ──────────────────────────────────────
+ const challenged = rows.filter((r) => r.challenged);
+ const gaps = challenged.filter((r) => r.gap);
+ const attributionOk = gaps.length === 0;
+ // The settlement proof is meaningful only when we had a declaring endpoint to
+ // pay. echoAccepted=false there means an attributed payment FAILED to settle.
+ const settleAttempted = !!settleRow;
+ const settleProven = !!(settleRow && settleRow.echo_accepted);
+ const proofOk = !settleAttempted || settleProven;
+
+ await writeAlert(redis, attributionOk && proofOk ? null : {
+ run_id: runId,
+ gaps: gaps.map((g) => ({ endpoint: g.endpoint, error: g.error })),
+ settle_proven: settleProven,
+ ts: new Date().toISOString(),
+ });
+
+ const signalData = {
+ expected_code: expectedCode,
+ endpoints_probed: rows.length,
+ endpoints_challenged: challenged.length,
+ attributed: challenged.filter((r) => r.matches).length,
+ gaps: gaps.length,
+ gap_endpoints: gaps.map((g) => g.endpoint),
+ attribution_ok: attributionOk,
+ settle_attempted: settleAttempted,
+ settle_proven: settleProven,
+ settle_tx: txSig,
+ response_attributed: !!(settleRow && settleRow.response_attributed),
+ };
+
+ if (!attributionOk) {
+ log.warn('builder_attribution_gap', { run_id: runId, gaps: signalData.gap_endpoints, expected: expectedCode });
+ } else if (!proofOk) {
+ log.warn('builder_attribution_settle_failed', { run_id: runId, endpoint: settleRow?.endpoint, error: settleRow?.error });
+ } else {
+ log.info('builder_attribution_ok', { run_id: runId, attributed: signalData.attributed, settle_tx: txSig });
+ }
+
+ const note = attributionOk
+ ? `${signalData.attributed}/${challenged.length} attributed${settleProven ? `, settle ${txSig ? 'proven' : 'ok'}` : settleAttempted ? ', SETTLE_FAILED' : ''}`
+ : `ATTRIBUTION_GAP ${gaps.length}: ${signalData.gap_endpoints.join(',')}`;
+
+ return {
+ // success = no attribution gap AND (if attempted) the attributed payment
+ // settled. amountAtomic reflects only what actually moved on-chain so the
+ // loop's daily-spend accounting is exact.
+ success: attributionOk && proofOk,
+ amountAtomic,
+ txSig,
+ responseData: {
+ expected_code: expectedCode,
+ endpoints: rows.map((r) => ({
+ endpoint: r.endpoint, challenged: r.challenged, matches: r.matches,
+ gap: r.gap, declared_code: r.declared_code, error: r.error,
+ })),
+ settlement: settleResp,
+ },
+ signalData,
+ valueExtracted: {
+ attribution_ok: attributionOk,
+ gaps: signalData.gap_endpoints,
+ settle_proven: settleProven,
+ settle_tx: txSig,
+ },
+ errorMsg: attributionOk ? (proofOk ? null : `attributed_settle_failed:${settleRow?.error || 'unknown'}`) : `attribution_gap:${signalData.gap_endpoints.join(',')}`,
+ note,
+ };
+}
+
+// Drop the transient scratch fields (challenge body, accept, urls) before the row
+// reaches the persistence layer — they're working state, not columns.
+function stripScratch(r) {
+ const { challenge, accept, _settle, _endpointUrl, _body, ...row } = r;
+ return row;
+}
+
+async function writeAlert(redis, alert) {
+ if (!redis) return;
+ try {
+ if (alert) {
+ await redis.set(REDIS_ALERT_KEY, JSON.stringify(alert), { ex: ALERT_TTL_SECONDS });
+ } else {
+ await redis.del(REDIS_ALERT_KEY);
+ }
+ } catch (err) {
+ log.warn('builder_attribution_alert_write_failed', { message: err?.message });
+ }
+}
+
+export const BUILDER_CODE_ATTRIBUTION = Object.freeze({
+ endpoint: '/api/x402/*',
+ serviceCode: SERVICE_CODE,
+ redisAlertKey: REDIS_ALERT_KEY,
+ sweepEndpoints: SWEEP_ENDPOINTS.map((e) => e.path),
+});
diff --git a/api/_lib/x402/pipelines/charity-split-audit.js b/api/_lib/x402/pipelines/charity-split-audit.js
new file mode 100644
index 000000000..de7531ce0
--- /dev/null
+++ b/api/_lib/x402/pipelines/charity-split-audit.js
@@ -0,0 +1,605 @@
+// api/_lib/x402/pipelines/charity-split-audit.js
+//
+// Charity Split Audit — autonomous pipeline (self/charity-split).
+//
+// "Ensures donation promises are kept." A merchant on the x402 Merchant Console
+// (/api/x402-merchant) can configure a charity split — a basis-point share of
+// every settled payment that the drop-in checkout appends, as a second
+// transferChecked to the cause's wallet, onto the same buyer-signed transaction
+// (see api/x402-checkout.js validateTip + handlePrepare). This audit verifies
+// that promise end-to-end, once a week:
+//
+// 1. FREE config sweep (no wallet needed) — reads every charity-enabled
+// merchant from x402_merchant_settings and validates the donation promise
+// is actually routable: a cause address present and well-formed for its
+// declared chain, a non-zero share, a payout configured, and the cause
+// wallet distinct from the merchant payout (the checkout rejects a tip whose
+// recipient equals the payment recipient, so that config would silently
+// drop the donation). A broken config is a donation promise the platform
+// makes to buyers but can never keep — the exact thing this audit surfaces.
+//
+// 2. One REAL on-chain canary payment WITH a charity split — exercises the
+// PRODUCTION giving code path, not a reimplementation. It probes the cheap
+// $0.001 402-gated dance-tip for a live challenge, computes the split
+// (floor(amount × bps / 10000)) exactly as a buyer's checkout would, then
+// asks the real /api/x402-checkout prepare endpoint to build the payment
+// transaction WITH that charity tip, signs it with the seed wallet, encodes
+// it via the real encode endpoint, and settles it through the facilitator
+// (the sponsor pays the SOL fee — the seed wallet needs no SOL, same as
+// every other loop payment). After settlement it reads the transaction back
+// from chain (getParsedTransaction) and asserts the charity wallet's
+// transferChecked leg landed with the EXACT computed atomics. A regression
+// in the charity-routing code — the tip silently dropped, mis-amounted, or
+// mis-routed — flips charity_routed to false.
+//
+// The canary cause wallet defaults to the seed wallet itself (X402_CHARITY_AUDIT_
+// ADDRESS_SOLANA overrides it with a platform-owned cause wallet): a safe
+// self-routed split with zero net outflow that still fully exercises the split
+// arithmetic, the second transferChecked leg, and on-chain verification. Set the
+// override to prove distinct-recipient routing with a real balance delta.
+//
+// Tables:
+// charity_split_audit — one row per charity-enabled merchant (kind='config')
+// plus one row for the on-chain canary (kind='canary')
+// per run. Columns receiving extracted value:
+// config_valid, broken_reason, expected_split_atomic,
+// routed_split_atomic, charity_routed, tx_signature.
+// x402_autonomous_log — one summary row per run; value_extracted (jsonb)
+// carries { merchants_audited, broken_count, broken_ids,
+// canary }. The pipeline writes this row itself (amount 0,
+// full value_extracted) so a direct manual invocation
+// produces a log row; the loop writes its own billed row.
+//
+// Downstream consumer: charity_split_audit is the giving-integrity audit trail.
+// Ops reads it (WHERE NOT config_valid OR NOT charity_routed) to alert when a
+// merchant's donation promise is unroutable or the production charity-routing
+// code stops delivering the split on-chain — before a buyer is told their
+// payment gave to a cause that never received it.
+//
+// No mocks. The config sweep reads live merchant rows; the canary makes a real
+// on-chain USDC payment through the real checkout endpoints and verifies the
+// settled transaction on-chain.
+
+import { randomUUID } from 'node:crypto';
+import {
+ PublicKey,
+ VersionedTransaction,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { sql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import {
+ loadSeedKeypair,
+ bootstrapSolanaContext,
+ fetchWithTimeout,
+ parseSolanaAccept,
+ USDC_MINT,
+} from '../pay.js';
+
+const log = logger('x402-charity-split-audit');
+
+// Informational service identity for the log row. The work spans the merchant
+// console (config source) + the checkout endpoints (the routing code under test).
+const SERVICE_NAME = 'Charity Split Audit';
+const ROUTE = '/api/x402-merchant';
+// The cheap real 402-gated endpoint the canary settles its base payment against.
+// $0.001 USDC; the facilitator sponsors the SOL fee (accept.extra.feePayer).
+const PROBE_PATH = '/api/x402/dance-tip?dancer=4&dance=hiphop';
+const CHECKOUT_PATH = '/api/x402-checkout';
+// USDC_MINT from pay.js is env-derived; fall back to canonical mainnet USDC for
+// the log row's asset column.
+const ASSET = () => USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const EVM_ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
+
+// Audit canary share (basis points). Defaults to 5%; clamped to a routable,
+// non-zero share so the computed split is always > 0 and verifiable on-chain.
+function auditBps() {
+ const raw = Number(process.env.X402_CHARITY_AUDIT_BPS || 500);
+ if (!Number.isFinite(raw)) return 500;
+ return Math.min(10000, Math.max(1, Math.trunc(raw)));
+}
+
+// floor(amount × bps / 10000) — the exact split the checkout computes for a
+// charity-enabled merchant. BigInt math: no float drift at the atom.
+export function computeSplit(amountAtomic, bps) {
+ return (BigInt(amountAtomic) * BigInt(bps)) / 10000n;
+}
+
+export function isValidAddress(chain, address) {
+ if (!address) return false;
+ if (chain === 'base') return EVM_ADDR_RE.test(address);
+ if (chain === 'solana') return SOLANA_ADDR_RE.test(address);
+ return false;
+}
+
+// Classify whether a charity-enabled merchant's donation promise is actually
+// routable. Pure + exported so the broken-config rules — the heart of "ensures
+// donation promises are kept" — are unit-testable without a DB. A merchant row
+// carries charity_chain, charity_address, charity_bps, payout_evm, payout_solana.
+// Returns { configValid, reason, chain, bps, payout, expectedSplitAtomic } where
+// reason is null when valid and a stable machine code otherwise. expectedSplit
+// is what a $1.00 (1_000_000 atomics) payment would route (null when invalid).
+export function classifyCharityConfig(m) {
+ const chain = m.charity_chain || null;
+ const payout = chain === 'base'
+ ? m.payout_evm
+ : chain === 'solana'
+ ? m.payout_solana
+ : (m.payout_solana || m.payout_evm);
+ const bps = Number(m.charity_bps || 0);
+
+ let reason = null;
+ if (!chain) reason = 'missing_charity_chain';
+ else if (!m.charity_address) reason = 'missing_charity_address';
+ else if (!isValidAddress(chain, m.charity_address)) reason = `invalid_${chain}_charity_address`;
+ else if (bps <= 0) reason = 'zero_bps';
+ else if (bps > 10000) reason = 'bps_over_100pct';
+ else if (!payout) reason = 'missing_payout';
+ else if (m.charity_address === payout) reason = 'charity_equals_payout'; // checkout drops this tip
+
+ const configValid = reason === null;
+ return {
+ configValid,
+ reason,
+ chain,
+ bps,
+ payout: payout || null,
+ expectedSplitAtomic: configValid ? Number(computeSplit(1_000_000, bps)) : null,
+ };
+}
+
+let _schemaReady = false;
+async function ensureSchema() {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS charity_split_audit (
+ id bigserial PRIMARY KEY,
+ run_id uuid NOT NULL,
+ ts timestamptz DEFAULT now(),
+ merchant_id text NOT NULL,
+ kind text NOT NULL DEFAULT 'config',
+ charity_name text,
+ charity_chain text,
+ charity_address text,
+ charity_bps int,
+ payout_address text,
+ config_valid boolean NOT NULL DEFAULT false,
+ broken_reason text,
+ reference_amount_atomic bigint,
+ expected_split_atomic bigint,
+ routed_split_atomic bigint,
+ charity_routed boolean,
+ tx_signature text,
+ error text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS charity_split_audit_merchant_ts ON charity_split_audit (merchant_id, ts DESC)`;
+ await sql`CREATE INDEX IF NOT EXISTS charity_split_audit_broken ON charity_split_audit (config_valid) WHERE NOT config_valid`;
+ await sql`CREATE INDEX IF NOT EXISTS charity_split_audit_unrouted ON charity_split_audit (charity_routed) WHERE charity_routed = false`;
+ // Mirror the loop: the autonomous log predates value_extracted on some installs.
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+async function recordAuditRow(runId, row) {
+ try {
+ await sql`
+ INSERT INTO charity_split_audit
+ (run_id, merchant_id, kind, charity_name, charity_chain, charity_address,
+ charity_bps, payout_address, config_valid, broken_reason,
+ reference_amount_atomic, expected_split_atomic, routed_split_atomic,
+ charity_routed, tx_signature, error)
+ VALUES
+ (${runId}, ${row.merchantId}, ${row.kind || 'config'}, ${row.charityName || null},
+ ${row.charityChain || null}, ${row.charityAddress || null},
+ ${row.charityBps ?? null}, ${row.payoutAddress || null},
+ ${!!row.configValid}, ${row.brokenReason || null},
+ ${row.referenceAmountAtomic ?? null}, ${row.expectedSplitAtomic ?? null},
+ ${row.routedSplitAtomic ?? null}, ${row.charityRouted ?? null},
+ ${row.txSig || null}, ${row.error || null})
+ `;
+ } catch (err) {
+ log.warn('charity_split_audit_insert_failed', { merchant: row.merchantId, message: err?.message });
+ }
+}
+
+async function recordSummary(runId, { txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${SERVICE_NAME}, ${ROUTE},
+ ${'solana:mainnet'}, ${0}, ${ASSET()}, ${txSig || null},
+ ${responseData ? JSON.stringify(responseData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'finance'})
+ `;
+ } catch (err) {
+ log.warn('charity_split_audit_summary_failed', { run_id: runId, message: err?.message });
+ }
+}
+
+// ── Free config sweep ─────────────────────────────────────────────────────────
+// Read every charity-enabled merchant and classify whether its donation promise
+// is actually routable. Read-only: runs even with no wallet configured.
+async function sweepMerchantConfigs(runId) {
+ let rows = [];
+ try {
+ rows = await sql`
+ select owner_user_id, charity_name, charity_chain, charity_address,
+ charity_bps, payout_evm, payout_solana
+ from x402_merchant_settings
+ where charity_enabled = true
+ `;
+ } catch (err) {
+ // Table absent on a fresh install — no merchants to audit yet, not a fault.
+ if (!String(err?.message || '').includes('does not exist')) {
+ log.warn('charity_split_audit_merchant_query_failed', { message: err?.message });
+ }
+ return { audited: 0, broken: [] };
+ }
+
+ const broken = [];
+ for (const m of rows) {
+ const c = classifyCharityConfig(m);
+ if (!c.configValid) broken.push(m.owner_user_id);
+
+ await recordAuditRow(runId, {
+ merchantId: m.owner_user_id,
+ kind: 'config',
+ charityName: m.charity_name,
+ charityChain: c.chain,
+ charityAddress: m.charity_address,
+ charityBps: c.bps,
+ payoutAddress: c.payout,
+ configValid: c.configValid,
+ brokenReason: c.reason,
+ referenceAmountAtomic: 1_000_000,
+ expectedSplitAtomic: c.expectedSplitAtomic,
+ routedSplitAtomic: null,
+ charityRouted: null,
+ error: null,
+ });
+ }
+
+ if (broken.length) {
+ log.warn('charity_split_broken_configs', { run_id: runId, count: broken.length });
+ }
+ return { audited: rows.length, broken };
+}
+
+// Walk a parsed transaction (outer + inner instructions) and collect every
+// SPL-Token transfer leg as { destination, amount } so the audit can confirm the
+// charity leg and the base leg both landed with their exact atomics.
+export function collectTokenTransfers(parsedTx) {
+ const legs = [];
+ const push = (ix) => {
+ if (!ix || ix.program !== 'spl-token' || !ix.parsed) return;
+ const t = ix.parsed.type;
+ if (t !== 'transferChecked' && t !== 'transfer') return;
+ const info = ix.parsed.info || {};
+ const amount = t === 'transferChecked' ? info.tokenAmount?.amount : info.amount;
+ if (info.destination && amount != null) legs.push({ destination: info.destination, amount: String(amount) });
+ };
+ const msg = parsedTx?.transaction?.message;
+ for (const ix of msg?.instructions || []) push(ix);
+ for (const inner of parsedTx?.meta?.innerInstructions || []) {
+ for (const ix of inner.instructions || []) push(ix);
+ }
+ return legs;
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Read the settled transaction back from chain and verify the charity + base
+// legs landed with their exact atomics. Retries briefly — a confirmed tx can lag
+// getParsedTransaction by a slot or two.
+async function verifyOnChain(conn, sig, { charityAta, payToAta, expectedSplit, baseAmount }) {
+ for (let attempt = 0; attempt < 4; attempt++) {
+ let tx = null;
+ try {
+ tx = await conn.getParsedTransaction(sig, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' });
+ } catch { /* transient — retry */ }
+ if (tx) {
+ const legs = collectTokenTransfers(tx);
+ const charityLeg = legs.find((l) => l.destination === charityAta && l.amount === String(expectedSplit));
+ const baseLeg = legs.find((l) => l.destination === payToAta && l.amount === String(baseAmount));
+ return {
+ found: true,
+ charityRouted: !!charityLeg,
+ baseRouted: !!baseLeg,
+ routedSplit: charityLeg ? Number(charityLeg.amount) : null,
+ reverted: !!tx.meta?.err,
+ };
+ }
+ await sleep(1500);
+ }
+ return { found: false, charityRouted: false, baseRouted: false, routedSplit: null, reverted: false };
+}
+
+// ── Real on-chain canary through the production checkout code ───────────────────
+async function runCanary(ctx, { origin, runId, remainingCap }) {
+ let buyer = ctx.buyer;
+ let walletReason = null;
+ if (!buyer) {
+ try { buyer = loadSeedKeypair(); } catch (err) { walletReason = err.message; }
+ }
+ if (!buyer) {
+ log.info('charity_split_audit_no_wallet', { reason: walletReason });
+ return { attempted: false, skipped: true, reason: 'wallet_unconfigured', walletReason };
+ }
+
+ // Bootstrap Solana context if the loop didn't hand us one (standalone test).
+ let conn = ctx.conn;
+ try {
+ if (!conn) ({ conn } = await bootstrapSolanaContext({ buyer }));
+ } catch (err) {
+ return { attempted: false, skipped: true, reason: `solana_bootstrap_failed: ${err?.message}` };
+ }
+
+ // 1) Probe the cheap 402 endpoint for a live challenge.
+ const probeUrl = `${origin}${PROBE_PATH}`;
+ const probe = await fetchWithTimeout(probeUrl, {
+ method: 'GET',
+ headers: { 'user-agent': 'threews-x402-autonomous/1.0' },
+ });
+ if (probe.status !== 402) {
+ return { attempted: false, skipped: true, reason: `probe_not_402:${probe.status}` };
+ }
+ const accept = parseSolanaAccept(probe.body);
+ if (!accept) return { attempted: false, skipped: true, reason: 'no_solana_accept' };
+ if (!USDC_MINT || accept.asset !== USDC_MINT) {
+ return { attempted: false, skipped: true, reason: `unexpected_asset:${accept.asset}` };
+ }
+ if (!accept.extra?.feePayer) return { attempted: false, skipped: true, reason: 'missing_fee_payer' };
+
+ const baseAmount = Number(accept.amount || 0);
+ const bps = auditBps();
+ const split = Number(computeSplit(baseAmount, bps));
+ if (split <= 0) {
+ // Base too small for this share to produce a verifiable split — nothing to prove.
+ return { attempted: false, skipped: true, reason: 'split_rounds_to_zero', baseAmount, bps };
+ }
+
+ const charityAddress = (process.env.X402_CHARITY_AUDIT_ADDRESS_SOLANA || '').trim()
+ || buyer.publicKey.toBase58();
+ if (!SOLANA_ADDR_RE.test(charityAddress)) {
+ return { attempted: false, skipped: true, reason: 'invalid_canary_charity_address' };
+ }
+
+ // Cap guard: the seed wallet moves base + split USDC this run.
+ const totalSpend = baseAmount + split;
+ if (totalSpend > remainingCap) {
+ return { attempted: false, skipped: true, reason: 'cap_would_exceed', baseAmount, split };
+ }
+
+ const charityPubkey = new PublicKey(charityAddress);
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ const charityAta = getAssociatedTokenAddressSync(mint, charityPubkey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID).toBase58();
+ const payToAta = getAssociatedTokenAddressSync(mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID).toBase58();
+
+ // 2) PRODUCTION code builds the payment tx WITH the charity tip leg.
+ const prepRes = await fetchWithTimeout(`${origin}${CHECKOUT_PATH}?action=prepare`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },
+ body: JSON.stringify({
+ accept,
+ buyer: buyer.publicKey.toBase58(),
+ tips: [{ to: charityAddress, amount: String(split) }],
+ }),
+ });
+ if (!prepRes.ok || !prepRes.body?.tx_base64) {
+ return { attempted: true, success: false, reason: 'prepare_failed', status: prepRes.status, body: prepRes.body, baseAmount, split, bps, charityAddress };
+ }
+
+ // 3) Sign the prepared tx with the seed wallet (buyer slot). The facilitator
+ // co-signs the fee-payer slot + broadcasts at settle.
+ let signedTxBase64;
+ try {
+ const vtx = VersionedTransaction.deserialize(Buffer.from(prepRes.body.tx_base64, 'base64'));
+ vtx.sign([buyer]);
+ signedTxBase64 = Buffer.from(vtx.serialize()).toString('base64');
+ } catch (err) {
+ return { attempted: true, success: false, reason: `sign_failed: ${err?.message}`, baseAmount, split, bps, charityAddress };
+ }
+
+ // 4) PRODUCTION code encodes the signed tx into the X-PAYMENT envelope (this
+ // also re-confirms the base leg pays payTo before it goes on the wire).
+ const encRes = await fetchWithTimeout(`${origin}${CHECKOUT_PATH}?action=encode`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'user-agent': 'threews-x402-autonomous/1.0' },
+ body: JSON.stringify({ accept, signed_tx_base64: signedTxBase64, resource_url: probeUrl }),
+ });
+ if (!encRes.ok || !encRes.body?.x_payment) {
+ return { attempted: true, success: false, reason: 'encode_failed', status: encRes.status, body: encRes.body, baseAmount, split, bps, charityAddress };
+ }
+
+ // 5) Settle: replay the paid endpoint with the payment header.
+ const paidRes = await fetchWithTimeout(probeUrl, {
+ method: 'GET',
+ headers: {
+ 'user-agent': 'threews-x402-autonomous/1.0',
+ 'x-payment': encRes.body.x_payment,
+ },
+ });
+ if (!paidRes.ok) {
+ return { attempted: true, success: false, reason: `settle_failed:http_${paidRes.status}`, body: paidRes.body, baseAmount, split, bps, charityAddress };
+ }
+
+ // Resolve the settled signature from the X-PAYMENT-RESPONSE header.
+ let txSig = null;
+ const respHeader = paidRes.headers?.get?.('x-payment-response');
+ if (respHeader) {
+ try { txSig = JSON.parse(Buffer.from(respHeader, 'base64').toString('utf8'))?.transaction || null; } catch { /* non-fatal */ }
+ }
+ if (!txSig) {
+ // Settled but no signature to verify against — report the spend, can't verify routing.
+ return { attempted: true, success: true, charityRouted: false, reason: 'no_settlement_signature', baseAmount, split, bps, charityAddress, charityAta, payToAta, spentAtomic: totalSpend, txSig: null };
+ }
+
+ // 6) Verify on-chain: the charity leg landed with the exact computed atomics.
+ const verify = await verifyOnChain(conn, txSig, { charityAta, payToAta, expectedSplit: split, baseAmount });
+
+ return {
+ attempted: true,
+ success: true,
+ spentAtomic: totalSpend,
+ txSig,
+ baseAmount,
+ split,
+ bps,
+ charityAddress,
+ charityAta,
+ payToAta,
+ charityRouted: verify.charityRouted,
+ baseRouted: verify.baseRouted,
+ routedSplit: verify.routedSplit,
+ onchainFound: verify.found,
+ reverted: verify.reverted,
+ };
+}
+
+/**
+ * Run the charity split audit. Self-contained: works inside the per-tick
+ * autonomous loop (handed shared buyer/conn) or as a direct manual test.
+ *
+ * @param {object} [ctx]
+ * @param {string} [ctx.runId]
+ * @param {string} [ctx.origin]
+ * @param {import('@solana/web3.js').Keypair} [ctx.buyer]
+ * @param {object} [ctx.conn]
+ * @param {number} [ctx.remainingCap]
+ * @returns {Promise<object>} loop-facing { success, amountAtomic, txSig, signalData, errorMsg, note } + caller-facing fields
+ */
+export async function run(ctx = {}) {
+ const t0 = Date.now();
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const remainingCap = ctx.remainingCap ?? ctx.remainingCapAtomic ?? Number.POSITIVE_INFINITY;
+
+ try {
+ await ensureSchema();
+ } catch (err) {
+ log.warn('charity_split_audit_schema_failed', { message: err?.message });
+ return { success: false, skipped: true, errorMsg: `schema_failed: ${err?.message}`, amountAtomic: 0, txSig: null };
+ }
+
+ // 1) Free config sweep across every charity-enabled merchant.
+ const sweep = await sweepMerchantConfigs(runId);
+
+ // 2) One real on-chain canary through the production checkout code.
+ const canary = await runCanary(ctx, { origin, runId, remainingCap });
+
+ // Persist the canary as its own audit row.
+ if (canary.attempted) {
+ await recordAuditRow(runId, {
+ merchantId: 'canary',
+ kind: 'canary',
+ charityName: 'audit-canary',
+ charityChain: 'solana',
+ charityAddress: canary.charityAddress || null,
+ charityBps: canary.bps ?? auditBps(),
+ payoutAddress: canary.payToAta || null,
+ configValid: true,
+ brokenReason: null,
+ referenceAmountAtomic: canary.baseAmount ?? null,
+ expectedSplitAtomic: canary.split ?? null,
+ routedSplitAtomic: canary.routedSplit ?? null,
+ charityRouted: canary.charityRouted ?? null,
+ txSig: canary.txSig || null,
+ error: canary.success === false ? canary.reason : (canary.charityRouted === false ? 'charity_leg_not_found_on_chain' : null),
+ });
+ }
+
+ const spentAtomic = Number(canary.spentAtomic) || 0;
+ const valueExtracted = {
+ merchants_audited: sweep.audited,
+ broken_count: sweep.broken.length,
+ broken_ids: sweep.broken,
+ canary: canary.attempted
+ ? {
+ settled: canary.success === true,
+ base_atomic: canary.baseAmount ?? null,
+ bps: canary.bps ?? null,
+ split_atomic: canary.split ?? null,
+ charity_routed: canary.charityRouted ?? null,
+ routed_split_atomic: canary.routedSplit ?? null,
+ onchain_found: canary.onchainFound ?? null,
+ tx: canary.txSig || null,
+ charity_address: canary.charityAddress || null,
+ reason: canary.success === false ? canary.reason : undefined,
+ }
+ : { skipped: true, reason: canary.reason },
+ };
+
+ // A failed/unrouted canary or any broken merchant config is the alert signal.
+ const canaryOk = !canary.attempted ? true : (canary.success === true && canary.charityRouted !== false);
+ const success = canaryOk; // broken merchant configs are flagged in-row, not a loop failure
+ const errorMsg = canary.attempted && canary.success === false
+ ? `canary_failed: ${canary.reason}`
+ : (canary.charityRouted === false ? 'canary_charity_not_routed' : null);
+
+ // Own summary row (amount 0, full value_extracted) so a direct manual call
+ // produces a log row; the loop adds its own billed row from amountAtomic.
+ await recordSummary(runId, {
+ txSig: canary.txSig || null,
+ responseData: {
+ merchants_audited: sweep.audited,
+ broken_count: sweep.broken.length,
+ canary_status: !canary.attempted ? 'skipped' : (canary.success ? (canary.charityRouted ? 'routed' : 'unrouted') : 'failed'),
+ spent_atomic: spentAtomic,
+ },
+ durationMs: Date.now() - t0,
+ success,
+ errorMsg,
+ valueExtracted,
+ });
+
+ if (canary.charityRouted === false) {
+ log.warn('charity_split_canary_unrouted', { run_id: runId, tx: canary.txSig, split: canary.split, reason: canary.reason });
+ }
+ log.info('charity_split_audit_complete', {
+ run_id: runId,
+ merchants: sweep.audited,
+ broken: sweep.broken.length,
+ canary: !canary.attempted ? `skip:${canary.reason}` : (canary.success ? (canary.charityRouted ? 'routed' : 'unrouted') : `fail:${canary.reason}`),
+ spent_usdc: (spentAtomic / 1e6).toFixed(6),
+ });
+
+ return {
+ // loop-facing — the loop accounts amountAtomic against the daily cap and
+ // writes its billed summary row; signalData (compact) lands in signal_data.
+ success,
+ amountAtomic: spentAtomic,
+ txSig: canary.txSig || null,
+ signalData: {
+ merchants_audited: sweep.audited,
+ broken_count: sweep.broken.length,
+ canary_charity_routed: canary.charityRouted ?? null,
+ canary_split_atomic: canary.split ?? null,
+ },
+ errorMsg,
+ note: `charity-audit: ${sweep.audited} merchants, ${sweep.broken.length} broken, canary ${!canary.attempted ? `skip(${canary.reason})` : (canary.charityRouted ? 'routed' : (canary.success ? 'unrouted' : 'failed'))}`,
+ ...(canary.skipped && !canary.attempted && sweep.audited === 0 ? { skipped: true } : {}),
+ // caller-facing
+ ok: true,
+ merchantsAudited: sweep.audited,
+ brokenCount: sweep.broken.length,
+ canary,
+ spentAtomic,
+ };
+}
+
+export default { run };
diff --git a/api/_lib/x402/pipelines/cross-chain-cost.js b/api/_lib/x402/pipelines/cross-chain-cost.js
new file mode 100644
index 000000000..f8cde92fe
--- /dev/null
+++ b/api/_lib/x402/pipelines/cross-chain-cost.js
@@ -0,0 +1,372 @@
+// api/_lib/x402/pipelines/cross-chain-cost.js
+//
+// Cross-Chain Payment Cost Comparison (USE: Finance) — measures the real,
+// all-in cost of moving an identical $0.001 USDC payment on Solana vs Base and
+// tracks the gas premium between the two networks over time.
+//
+// A run()-style registry entry (autonomous-registry.js → `cross-chain-cost-comparison`).
+// Every tick the autonomous loop calls run(ctx). It:
+//
+// 1. Probes a real $0.001 402-gated three.ws endpoint (/api/x402/model-check)
+// for the live multi-network challenge. model-check advertises the SAME
+// X402_MAX_AMOUNT_REQUIRED amount on every network, so the Solana and Base
+// accepts quote an identical $0.001 — the comparison is apples to apples.
+// 2. Confirms BOTH a Solana (exact, USDC) and a Base (exact, eip155:8453, USD
+// Coin) route are advertised in that single challenge. A missing route means
+// that network can't be priced this tick.
+// 3. Settles a REAL $0.001 USDC payment on Solana (the only network with a
+// configured autonomous outbound keypair) via payX402(), then reads the
+// ACTUAL on-chain transaction fee (meta.fee, lamports) for that settlement.
+// That lamport fee is the true Solana network gas cost of the transfer.
+// 4. Prices the equivalent Base settlement from LIVE on-chain data — the
+// current Base gas price (viem getGasPrice over the Base RPC) multiplied by
+// the documented gas units a USDC ERC-3009 transferWithAuthorization burns.
+// Base outbound settlement is not attempted because no autonomous EVM
+// signing wallet is provisioned (same boundary the circuit breaker hits);
+// the day one is configured, a real Base settle drops in here without
+// touching the loop. The gas number itself is real, live network data —
+// not a mock.
+// 5. Converts both gas costs to USD with live SOL/ETH prices (CoinGecko),
+// computes total cost (amount + gas) per network and the gas premium ratio
+// (base_gas_usd / solana_gas_usd), picks the cheapest network, and upserts
+// the snapshot into `cross_chain_cost_comparison` (an append-only time
+// series). The loop records the paid Solana settlement to x402_autonomous_log.
+//
+// Downstream consumer: GET /api/x402/network-cost reads cross_chain_cost_comparison
+// for the latest snapshot + a rolling gas-premium average and surfaces the
+// recommended (cheapest) settlement network — used to steer users to the cheaper
+// rail and to inform default-network pricing.
+//
+// No mocks. The Solana cost is a real settled transaction's on-chain fee; the
+// Base cost is the live Base gas price × a documented protocol gas constant; the
+// USD conversion uses live market prices. The loop owns recording, cooldown, and
+// daily-spend accounting; this module owns the probe, the settlement, the
+// cross-network cost measurement, and the value extraction/storage.
+
+import { createPublicClient } from 'viem';
+import { base } from 'viem/chains';
+import { fetchWithTimeout, payX402 } from '../pay.js';
+import { evmTransport } from '../../evm/rpc.js';
+import { env } from '../../env.js';
+
+const NET_SOLANA_PREFIX = 'solana';
+const NET_BASE = 'eip155:8453';
+
+// The probe/settle target: the cheapest idempotent, side-effect-free $0.001
+// 402-gated endpoint on the platform. model-check inspects a public GLB; a
+// settled pay has no economic side effect beyond the transfer, so an hourly
+// cost-probe leaves no junk behind (unlike booking a dance tip). A stable public
+// canary avatar keeps the inspected resource deterministic across runs.
+const PROBE_PATH = '/api/x402/model-check';
+const CANARY_AVATAR = 'xbot.glb';
+
+// Solana's per-signature base fee is a fixed protocol constant (5000 lamports).
+// The x402 transfer is co-signed by the buyer and the facilitator fee payer
+// (2 signatures) plus a negligible priority fee. Used only as a labelled
+// fallback when the settled tx can't be read back in time — the real measured
+// meta.fee is always preferred and flagged fee_source='onchain'.
+const LAMPORTS_PER_SIGNATURE = 5000;
+const SOLANA_TX_SIGNERS = 2;
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// Gas a USDC ERC-3009 transferWithAuthorization settlement burns on Base. USDC's
+// transferWithAuthorization lands in the ~65–90k range; 75k is a conservative
+// mid-point and is the unit the facilitator's settle tx is metered at. Env-
+// overridable so a measured value can replace the constant without a deploy.
+const BASE_USDC_SETTLE_GAS = Number(process.env.X402_BASE_USDC_SETTLE_GAS || 75_000);
+
+const COINGECKO_PRICE_URL =
+ 'https://api.coingecko.com/api/v3/simple/price?ids=solana,ethereum&vs_currencies=usd';
+
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS cross_chain_cost_comparison (
+ id bigserial PRIMARY KEY,
+ run_id uuid,
+ amount_atomic bigint,
+ solana_advertised boolean NOT NULL DEFAULT false,
+ base_advertised boolean NOT NULL DEFAULT false,
+ solana_settled boolean NOT NULL DEFAULT false,
+ solana_tx text,
+ solana_fee_lamports bigint,
+ solana_fee_source text,
+ solana_gas_usd numeric(20,10),
+ base_gas_price_wei bigint,
+ base_gas_units bigint,
+ base_gas_usd numeric(20,10),
+ sol_price_usd numeric(20,8),
+ eth_price_usd numeric(20,8),
+ amount_usd numeric(20,10),
+ solana_total_usd numeric(20,10),
+ base_total_usd numeric(20,10),
+ gas_premium_ratio numeric(20,6),
+ cheapest_network text,
+ checked_at timestamptz DEFAULT now()
+ )
+ `;
+ _schemaReady = true;
+}
+
+async function persist(sql, log, row) {
+ try {
+ await ensureSchema(sql);
+ await sql`
+ INSERT INTO cross_chain_cost_comparison
+ (run_id, amount_atomic, solana_advertised, base_advertised,
+ solana_settled, solana_tx, solana_fee_lamports, solana_fee_source,
+ solana_gas_usd, base_gas_price_wei, base_gas_units, base_gas_usd,
+ sol_price_usd, eth_price_usd, amount_usd, solana_total_usd,
+ base_total_usd, gas_premium_ratio, cheapest_network, checked_at)
+ VALUES
+ (${row.run_id}, ${row.amount_atomic}, ${row.solana_advertised},
+ ${row.base_advertised}, ${row.solana_settled}, ${row.solana_tx || null},
+ ${row.solana_fee_lamports ?? null}, ${row.solana_fee_source || null},
+ ${row.solana_gas_usd ?? null}, ${row.base_gas_price_wei ?? null},
+ ${row.base_gas_units ?? null}, ${row.base_gas_usd ?? null},
+ ${row.sol_price_usd ?? null}, ${row.eth_price_usd ?? null},
+ ${row.amount_usd ?? null}, ${row.solana_total_usd ?? null},
+ ${row.base_total_usd ?? null}, ${row.gas_premium_ratio ?? null},
+ ${row.cheapest_network || null}, now())
+ `;
+ } catch (err) {
+ log?.warn?.('cross_chain_cost_persist_failed', { message: err?.message });
+ }
+}
+
+// Live SOL + ETH USD prices in one CoinGecko call (the platform's established
+// price source). Returns nulls on failure so cost USD figures degrade to null
+// rather than crashing the comparison — the gas units/fees are still recorded.
+async function fetchNativePrices() {
+ try {
+ const r = await fetchWithTimeout(COINGECKO_PRICE_URL, {
+ headers: { accept: 'application/json' },
+ }, 5000);
+ const sol = Number(r?.body?.solana?.usd);
+ const eth = Number(r?.body?.ethereum?.usd);
+ return {
+ sol: Number.isFinite(sol) && sol > 0 ? sol : null,
+ eth: Number.isFinite(eth) && eth > 0 ? eth : null,
+ };
+ } catch {
+ return { sol: null, eth: null };
+ }
+}
+
+// Read the actual on-chain fee (lamports) the settled Solana transfer paid.
+// Confirmed txs can lag a beat behind the settle response, so retry a few times
+// before falling back to the deterministic protocol fee.
+async function readSolanaFee(conn, txSig, log) {
+ if (!txSig) return { lamports: LAMPORTS_PER_SIGNATURE * SOLANA_TX_SIGNERS, source: 'estimated' };
+ for (let attempt = 0; attempt < 5; attempt++) {
+ try {
+ const tx = await conn.getParsedTransaction(txSig, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ const fee = tx?.meta?.fee;
+ if (Number.isFinite(fee) && fee > 0) return { lamports: Number(fee), source: 'onchain' };
+ } catch (err) {
+ log?.warn?.('cross_chain_cost_fee_read_retry', { attempt, message: err?.message });
+ }
+ await new Promise((res) => setTimeout(res, 1500));
+ }
+ // Tx not yet indexed — use the deterministic fee structure (2 signers).
+ return { lamports: LAMPORTS_PER_SIGNATURE * SOLANA_TX_SIGNERS, source: 'estimated' };
+}
+
+// Live Base gas price (wei) via the platform's failover Base RPC transport.
+async function fetchBaseGasPriceWei(log) {
+ try {
+ const client = createPublicClient({
+ chain: base,
+ transport: evmTransport(8453, { primaryUrl: env.BASE_RPC_URL }),
+ });
+ const wei = await client.getGasPrice();
+ return Number.isFinite(Number(wei)) && Number(wei) > 0 ? BigInt(wei) : null;
+ } catch (err) {
+ log?.warn?.('cross_chain_cost_base_gas_failed', { message: err?.message });
+ return null;
+ }
+}
+
+function round(n, dp = 10) {
+ if (n == null || !Number.isFinite(n)) return null;
+ const f = 10 ** dp;
+ return Math.round(n * f) / f;
+}
+
+/**
+ * Cross-chain cost comparison executor.
+ *
+ * @param {object} ctx — supplied by the autonomous loop:
+ * { origin, buyer, conn, blockhash, mintInfo, remainingCap, sql, log, runId }
+ * @returns outcome recorded by the loop to x402_autonomous_log:
+ * { success, amountAtomic, txSig, network, responseData, signalData,
+ * valueExtracted, errorMsg, note }
+ */
+export async function run(ctx) {
+ const { origin, buyer, conn, blockhash, mintInfo, remainingCap, sql, log, runId } = ctx;
+ const endpointUrl = `${origin}${PROBE_PATH}?url=${encodeURIComponent(`${origin}/avatars/${CANARY_AVATAR}`)}`;
+
+ // Wallet guard (defence in depth — the loop pre-flights the keypair).
+ if (!buyer) {
+ await persist(sql, log, { run_id: runId, amount_atomic: null, solana_advertised: false, base_advertised: false, solana_settled: false, cheapest_network: null });
+ return {
+ success: false, amountAtomic: 0, txSig: null, network: 'multi',
+ signalData: { skipped: true, reason: 'wallet_unconfigured' },
+ errorMsg: 'wallet_unconfigured', note: 'wallet_unconfigured', skipped: true,
+ };
+ }
+
+ // ── Step 1: probe for the live multi-network challenge ─────────────────────
+ let challenge;
+ try {
+ const probe = await fetchWithTimeout(endpointUrl, {
+ method: 'GET',
+ headers: { 'user-agent': 'threews-x402-cross-chain-cost/1.0' },
+ });
+ if (probe.status !== 402) {
+ const errorMsg = `probe_not_402:http_${probe.status}`;
+ await persist(sql, log, { run_id: runId, amount_atomic: null, solana_advertised: false, base_advertised: false, solana_settled: false, cheapest_network: null });
+ return { success: false, amountAtomic: 0, txSig: null, network: 'multi', signalData: { reason: errorMsg }, errorMsg, note: errorMsg };
+ }
+ challenge = probe.body;
+ } catch (err) {
+ const errorMsg = `probe_failed:${err?.message || 'network'}`;
+ await persist(sql, log, { run_id: runId, amount_atomic: null, solana_advertised: false, base_advertised: false, solana_settled: false, cheapest_network: null });
+ return { success: false, amountAtomic: 0, txSig: null, network: 'multi', signalData: { reason: errorMsg }, errorMsg, note: errorMsg };
+ }
+
+ // ── Step 2: confirm both network routes are advertised ─────────────────────
+ const accepts = Array.isArray(challenge?.accepts) ? challenge.accepts : [];
+ const solAccept = accepts.find(
+ (a) => typeof a?.network === 'string' && a.network.startsWith(NET_SOLANA_PREFIX) && a?.extra?.feePayer,
+ ) || null;
+ const baseAccept = accepts.find((a) => a?.network === NET_BASE) || null;
+ const solanaAdvertised = !!solAccept;
+ const baseAdvertised = !!baseAccept;
+
+ const amountAtomicQuoted = Number(solAccept?.amount ?? baseAccept?.amount ?? 0) || 0;
+ const amountUsd = amountAtomicQuoted / 1e6;
+
+ // ── Step 3: settle the real $0.001 payment on Solana, read its on-chain fee ─
+ let amountAtomic = 0;
+ let txSig = null;
+ let solanaSettled = false;
+ let settleErr = null;
+ if (solAccept) {
+ try {
+ const r = await payX402({
+ url: endpointUrl,
+ method: 'GET',
+ buyer, conn, blockhash, mintInfo,
+ remainingCap: remainingCap ?? Infinity,
+ userAgent: 'threews-x402-cross-chain-cost/1.0',
+ });
+ solanaSettled = !!r.paid;
+ amountAtomic = r.paid ? (r.amountAtomic || 0) : 0;
+ txSig = r.txSig || null;
+ if (!r.paid) settleErr = r.errorMsg || `settle_status_${r.status || 0}`;
+ } catch (err) {
+ settleErr = `settle_threw:${err?.message || 'unknown'}`;
+ }
+ } else {
+ settleErr = 'no_solana_route';
+ }
+
+ // ── Step 4: measure the cost of each network ───────────────────────────────
+ const [prices, baseGasWei, solFee] = await Promise.all([
+ fetchNativePrices(),
+ baseAdvertised ? fetchBaseGasPriceWei(log) : Promise.resolve(null),
+ solanaSettled ? readSolanaFee(conn, txSig, log) : Promise.resolve(null),
+ ]);
+
+ const solFeeLamports = solFee?.lamports ?? null;
+ const solFeeSource = solFee?.source ?? null;
+ const solanaGasUsd = (solFeeLamports != null && prices.sol != null)
+ ? (solFeeLamports / LAMPORTS_PER_SOL) * prices.sol
+ : null;
+
+ const baseGasUnits = baseAdvertised ? BASE_USDC_SETTLE_GAS : null;
+ const baseGasEth = (baseGasWei != null && baseGasUnits != null)
+ ? Number(baseGasWei) * baseGasUnits / 1e18
+ : null;
+ const baseGasUsd = (baseGasEth != null && prices.eth != null) ? baseGasEth * prices.eth : null;
+
+ const solanaTotalUsd = (solanaGasUsd != null) ? amountUsd + solanaGasUsd : null;
+ const baseTotalUsd = (baseGasUsd != null) ? amountUsd + baseGasUsd : null;
+ const gasPremiumRatio = (baseGasUsd != null && solanaGasUsd != null && solanaGasUsd > 0)
+ ? baseGasUsd / solanaGasUsd
+ : null;
+
+ let cheapestNetwork = null;
+ if (solanaTotalUsd != null && baseTotalUsd != null) {
+ cheapestNetwork = baseTotalUsd < solanaTotalUsd ? 'base' : 'solana';
+ } else if (solanaTotalUsd != null) {
+ cheapestNetwork = 'solana';
+ } else if (baseTotalUsd != null) {
+ cheapestNetwork = 'base';
+ }
+
+ // ── Step 5: persist the snapshot (downstream: /api/x402/network-cost) ──────
+ const row = {
+ run_id: runId,
+ amount_atomic: amountAtomicQuoted || null,
+ solana_advertised: solanaAdvertised,
+ base_advertised: baseAdvertised,
+ solana_settled: solanaSettled,
+ solana_tx: txSig,
+ solana_fee_lamports: solFeeLamports,
+ solana_fee_source: solFeeSource,
+ solana_gas_usd: round(solanaGasUsd),
+ base_gas_price_wei: baseGasWei != null ? Number(baseGasWei) : null,
+ base_gas_units: baseGasUnits,
+ base_gas_usd: round(baseGasUsd),
+ sol_price_usd: prices.sol,
+ eth_price_usd: prices.eth,
+ amount_usd: round(amountUsd),
+ solana_total_usd: round(solanaTotalUsd),
+ base_total_usd: round(baseTotalUsd),
+ gas_premium_ratio: round(gasPremiumRatio, 6),
+ cheapest_network: cheapestNetwork,
+ };
+ await persist(sql, log, row);
+
+ const signalData = {
+ amount_usd: round(amountUsd),
+ solana_settled: solanaSettled,
+ solana_gas_usd: round(solanaGasUsd),
+ base_gas_usd: round(baseGasUsd),
+ gas_premium_ratio: round(gasPremiumRatio, 6),
+ cheapest_network: cheapestNetwork,
+ base_gas_price_gwei: baseGasWei != null ? round(Number(baseGasWei) / 1e9, 4) : null,
+ solana_fee_source: solFeeSource,
+ };
+
+ const note = cheapestNetwork
+ ? `cheapest=${cheapestNetwork} premium=${gasPremiumRatio != null ? gasPremiumRatio.toFixed(2) + 'x' : 'n/a'}`
+ : (settleErr || 'no_cost_data');
+
+ log?.info?.('cross_chain_cost_complete', { run_id: runId, ...signalData, tx: txSig });
+
+ return {
+ // success = the real Solana settlement (the pipeline's core paid work)
+ // landed. A transient price-feed/RPC gap that leaves a cost figure null
+ // doesn't retroactively fail a payment that settled on-chain — the snapshot
+ // is still persisted and the next tick re-measures. amountAtomic reflects
+ // only the on-chain Solana spend so the loop's accounting is exact.
+ success: solanaSettled,
+ amountAtomic,
+ txSig,
+ network: 'solana:mainnet',
+ responseData: { challenge_resource: challenge?.resource || endpointUrl, ...row },
+ signalData,
+ valueExtracted: signalData,
+ errorMsg: solanaSettled ? null : (settleErr || 'settle_failed'),
+ note,
+ };
+}
+
+export const CROSS_CHAIN_COST_PROBE = Object.freeze({ path: PROBE_PATH, canary: CANARY_AVATAR });
diff --git a/api/_lib/x402/pipelines/service-uptime-monitor.js b/api/_lib/x402/pipelines/service-uptime-monitor.js
new file mode 100644
index 000000000..3d851e1c8
--- /dev/null
+++ b/api/_lib/x402/pipelines/service-uptime-monitor.js
@@ -0,0 +1,502 @@
+// api/_lib/x402/pipelines/service-uptime-monitor.js
+//
+// External x402 Service Uptime Monitor — autonomous pipeline (self/038).
+//
+// Every external x402 service we depend on lives in our discovery registry: the
+// live, priced resources the Bazaar Discovery Warmup (self/008) snapshots into
+// x402_bazaar_catalog, plus any directly-registered EXTERNAL_ENDPOINTS in
+// autonomous-registry.js. Production pipelines pay those endpoints. If one goes
+// dark, a paying pipeline wastes a tick (and risks a half-settled payment) on a
+// dead URL. This monitor is the liveness gate in front of all of them.
+//
+// On each run it:
+// 1. Collects every distinct EXTERNAL service URL from x402_bazaar_catalog
+// (latest snapshot per category) ∪ the registry's EXTERNAL_ENDPOINTS,
+// excluding our own three.ws origin.
+// 2. Probes each with a cheap, unpaid HEAD request — falling back to OPTIONS
+// then GET when a server rejects HEAD (405/501). A live x402 endpoint
+// answers 402 (payment required); a reachable free/redirect endpoint answers
+// 2xx/3xx. 5xx or a network timeout means the service is DOWN. Because the
+// probe never sends an X-PAYMENT header, reading a 402 challenge is free —
+// this pipeline moves no funds (amountAtomic is always 0).
+// 3. Upserts each verdict into x402_service_uptime keyed by the service URL,
+// tracking consecutive_failures, total_probes/total_failures and
+// last_seen_live so a transient blip is distinguishable from a hard outage.
+// 4. Records one x402_autonomous_log row per probe (value_extracted = the
+// verdict) and returns an aggregate summary the loop records too.
+//
+// Wiring: declared as a run()-style entry in autonomous-registry.js
+// (`external-service-uptime-monitor`). The per-tick loop
+// (api/cron/x402-autonomous-loop.js) hands run() { origin, redis, sql, log,
+// runId }; called standalone (manual test) it derives its own origin/sql.
+//
+// Value extracted & where it lands:
+// • x402_service_uptime — one row per external service. Columns:
+// alive → up (402 / 2xx / 3xx) vs down (5xx / unreachable)
+// classification → live_paywall | live_free | reachable_unexpected
+// | server_error | unreachable
+// last_status → HTTP status of the last probe (null on timeout)
+// last_probe_method → HEAD | OPTIONS | GET (which method got the verdict)
+// latency_ms → probe round-trip
+// consecutive_failures → consecutive down probes (0 once it answers again)
+// last_seen_live → last time it was up — the recovery anchor
+// • Redis x402:service-uptime:dead — JSON list of currently-down services for
+// a cheap, DB-free gate read.
+// • Redis x402:service-uptime:latest — the newest run summary.
+//
+// Downstream consumer: any pipeline that pays an EXTERNAL endpoint calls
+// isServiceLive(sql, url) before settling so a confirmed-dead service is skipped
+// instead of burning a tick (and the loop's daily cap) on a URL that will never
+// answer 402. listServiceUptime() backs an ops reliability surface.
+
+import { randomUUID } from 'node:crypto';
+
+import { fetchWithTimeout } from '../pay.js';
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+
+const log = logger('x402-service-uptime-monitor');
+
+// Informational route label (this pipeline owns no single URL — it fans across
+// the external registry). Mirrors the registry entry's `path`/`endpoint`.
+export const SERVICE_UPTIME_ENDPOINT = 'registered external services (HEAD/OPTIONS probe)';
+
+// Probe methods, in fallback order. HEAD is cheapest; OPTIONS/GET cover servers
+// that reject HEAD with 405/501. GET on a paid endpoint returns the 402
+// challenge, which is free to read (we never attach an X-PAYMENT header).
+const PROBE_METHODS = ['HEAD', 'OPTIONS', 'GET'];
+// Short per-probe timeout — a healthy service answers a HEAD in well under this;
+// anything slower is effectively down for production routing purposes.
+const PROBE_TIMEOUT_MS = Number(env.X402_UPTIME_PROBE_TIMEOUT_MS || process.env.X402_UPTIME_PROBE_TIMEOUT_MS || 8_000);
+// Cap probes per run so one tick stays bounded even with a large catalog; a
+// Redis cursor rotates coverage across runs so every service is checked over time.
+const MAX_PER_RUN = Number(env.X402_UPTIME_MAX_PER_RUN || process.env.X402_UPTIME_MAX_PER_RUN || 25);
+// Concurrent probes per batch — keeps wall-clock low without hammering hosts.
+const PROBE_CONCURRENCY = Number(env.X402_UPTIME_CONCURRENCY || process.env.X402_UPTIME_CONCURRENCY || 6);
+// Down probes before a service is treated as hard-dead by isServiceLive(). One
+// blip shouldn't pull a service from production; a sustained outage should.
+const FAILURE_THRESHOLD = Number(env.X402_UPTIME_FAILURE_THRESHOLD || process.env.X402_UPTIME_FAILURE_THRESHOLD || 2);
+
+const REDIS_DEAD_KEY = 'x402:service-uptime:dead';
+const REDIS_LATEST_KEY = 'x402:service-uptime:latest';
+const REDIS_CURSOR_KEY = 'x402:service-uptime:cursor';
+// A run every ~15 min; keep the snapshot a little over two cycles so a missed
+// run lapses to "unknown" rather than latching forever.
+const REDIS_TTL_SECONDS = 40 * 60;
+
+export const SERVICE_UPTIME = Object.freeze({
+ endpoint: SERVICE_UPTIME_ENDPOINT,
+ priceAtomic: 0, // free probe — never pays
+ table: 'x402_service_uptime',
+ maxPerRun: MAX_PER_RUN,
+ failureThreshold: FAILURE_THRESHOLD,
+ probeTimeoutMs: PROBE_TIMEOUT_MS,
+ redisDeadKey: REDIS_DEAD_KEY,
+ redisLatestKey: REDIS_LATEST_KEY,
+});
+
+// ── Classification ──────────────────────────────────────────────────────────
+// Turn a probe's HTTP status (or network error) into a liveness verdict.
+// 402 → live_paywall (a healthy x402 endpoint)
+// 2xx / 3xx → live_free (reachable; free, redirect, or open)
+// 4xx (non-402) → reachable_unexpected (server is UP but answered oddly —
+// route/auth change, not an outage)
+// 5xx → server_error (DOWN)
+// no response → unreachable (timeout / DNS / refused → DOWN)
+// Only 5xx and unreachable count as failures, per the monitor's spec.
+export function classifyProbe(status, errMsg) {
+ if (status === 402) return { alive: true, classification: 'live_paywall', error_msg: null };
+ if (status != null && status >= 200 && status < 400) return { alive: true, classification: 'live_free', error_msg: null };
+ if (status != null && status >= 500) return { alive: false, classification: 'server_error', error_msg: `http_${status}` };
+ if (status != null && status >= 400) return { alive: true, classification: 'reachable_unexpected', error_msg: `http_${status}` };
+ return { alive: false, classification: 'unreachable', error_msg: errMsg || 'unreachable' };
+}
+
+function hostOf(u) {
+ try { return new URL(u).host.toLowerCase(); } catch { return null; }
+}
+
+// Add an external target to the dedup map, skipping non-absolute URLs and any
+// host that is our own platform (this monitor is for EXTERNAL services only).
+function addTarget(map, ownHost, t) {
+ if (!t || typeof t.resource !== 'string' || !t.resource) return;
+ const host = hostOf(t.resource);
+ if (!host) return; // not an absolute URL
+ if (ownHost && host === ownHost) return; // our own origin
+ if (/(^|\.)three\.ws$/.test(host)) return; // never probe three.ws itself
+ if (!map.has(t.resource)) {
+ map.set(t.resource, {
+ resource: t.resource,
+ tool_name: t.tool_name || null,
+ networks: Array.isArray(t.networks) ? t.networks : [],
+ });
+ }
+}
+
+// Pull the EXTERNAL_ENDPOINTS list from the registry without a static import,
+// avoiding any module init-order coupling (the registry imports this pipeline).
+async function externalRegistryEntries() {
+ try {
+ const mod = await import('../autonomous-registry.js');
+ return typeof mod.getExternalRegistry === 'function' ? mod.getExternalRegistry() : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Collect every distinct external x402 service URL we know about: the latest
+ * live/priced resources snapshotted per category by the bazaar warmup, plus the
+ * registry's directly-registered EXTERNAL_ENDPOINTS. Excludes our own origin.
+ */
+export async function collectExternalTargets({ sql = defaultSql, origin } = {}) {
+ const ownHost = hostOf(origin || env.APP_ORIGIN || 'https://three.ws');
+ const targets = new Map();
+
+ // 1. Bazaar catalog — the discovery source of record for external services.
+ try {
+ const rows = await sql`
+ SELECT DISTINCT ON (category) category, resources
+ FROM x402_bazaar_catalog
+ ORDER BY category, ts DESC
+ `;
+ for (const r of rows) {
+ const list = Array.isArray(r.resources) ? r.resources : [];
+ for (const s of list) addTarget(targets, ownHost, s);
+ }
+ } catch (err) {
+ // Fresh install: the catalog table may not exist yet → no bazaar targets.
+ if (!/does not exist/i.test(err?.message || '')) throw err;
+ }
+
+ // 2. Directly-registered external endpoints (manual onboarding).
+ for (const e of await externalRegistryEntries()) {
+ if (!e?.url) continue;
+ addTarget(targets, ownHost, { resource: e.url, tool_name: e.name || e.id || null, networks: e.networks || ['solana'] });
+ }
+
+ return [...targets.values()];
+}
+
+/**
+ * Probe a single service URL with HEAD, falling back to OPTIONS then GET when a
+ * server rejects the method. Never throws — a network failure resolves to an
+ * `unreachable` verdict. Reads a 402 challenge without paying (free).
+ */
+export async function probeService(url) {
+ let last = null;
+ for (const method of PROBE_METHODS) {
+ const t0 = Date.now();
+ try {
+ const res = await fetchWithTimeout(url, {
+ method,
+ headers: { 'user-agent': 'threews-x402-uptime/1.0', accept: 'application/json' },
+ }, PROBE_TIMEOUT_MS);
+ const verdict = classifyProbe(res.status, null);
+ verdict.status = res.status;
+ verdict.method = method;
+ verdict.latency_ms = Date.now() - t0;
+ // Definitive outcomes: a paywall, any reachable success/redirect, or a
+ // server error — stop here. Method-not-allowed (405/501) means the server
+ // is up but dislikes this verb, so try the next method for a real verdict.
+ if (res.status === 402 || (res.status >= 200 && res.status < 400) || res.status >= 500) return verdict;
+ last = verdict;
+ if ((res.status === 405 || res.status === 501) && method !== 'GET') continue;
+ return verdict; // other 4xx — reachable, accept the verdict
+ } catch (err) {
+ const verdict = classifyProbe(null, err?.message || 'network_error');
+ verdict.status = null;
+ verdict.method = method;
+ verdict.latency_ms = Date.now() - t0;
+ last = verdict;
+ if (method !== 'GET') continue; // a HEAD block may not apply to GET
+ return verdict;
+ }
+ }
+ return last;
+}
+
+// ── Schema ──────────────────────────────────────────────────────────────────
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_service_uptime (
+ resource text PRIMARY KEY,
+ tool_name text,
+ networks text[] NOT NULL DEFAULT '{}',
+ alive boolean NOT NULL,
+ classification text NOT NULL,
+ last_status int,
+ last_probe_method text,
+ latency_ms int,
+ consecutive_failures int NOT NULL DEFAULT 0,
+ total_probes bigint NOT NULL DEFAULT 0,
+ total_failures bigint NOT NULL DEFAULT 0,
+ first_seen timestamptz NOT NULL DEFAULT now(),
+ last_seen_live timestamptz,
+ last_checked timestamptz NOT NULL DEFAULT now(),
+ run_id uuid,
+ error_msg text
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_service_uptime_alive ON x402_service_uptime (alive, last_checked DESC)`;
+ // The autonomous log predates this pipeline; ensure value_extracted before any
+ // recordCall references it (idempotent).
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+// Upsert one verdict, maintaining the failure streak + totals, and return the
+// post-upsert consecutive_failures so the run can flag a crossing into "dead".
+async function upsertUptime(sql, runId, target, v) {
+ const liveTs = v.alive ? new Date().toISOString() : null;
+ const failInc = v.alive ? 0 : 1;
+ const [row] = await sql`
+ INSERT INTO x402_service_uptime
+ (resource, tool_name, networks, alive, classification, last_status,
+ last_probe_method, latency_ms, consecutive_failures, total_probes,
+ total_failures, last_seen_live, last_checked, run_id, error_msg)
+ VALUES
+ (${target.resource}, ${target.tool_name}, ${target.networks}, ${v.alive},
+ ${v.classification}, ${v.status ?? null}, ${v.method}, ${v.latency_ms ?? null},
+ ${failInc}, ${1}, ${failInc}, ${liveTs}, now(), ${runId}, ${v.error_msg})
+ ON CONFLICT (resource) DO UPDATE SET
+ tool_name = EXCLUDED.tool_name,
+ networks = EXCLUDED.networks,
+ alive = EXCLUDED.alive,
+ classification = EXCLUDED.classification,
+ last_status = EXCLUDED.last_status,
+ last_probe_method = EXCLUDED.last_probe_method,
+ latency_ms = EXCLUDED.latency_ms,
+ consecutive_failures = CASE WHEN EXCLUDED.alive THEN 0
+ ELSE x402_service_uptime.consecutive_failures + 1 END,
+ total_probes = x402_service_uptime.total_probes + 1,
+ total_failures = x402_service_uptime.total_failures + ${failInc},
+ last_seen_live = CASE WHEN EXCLUDED.alive THEN now()
+ ELSE x402_service_uptime.last_seen_live END,
+ last_checked = now(),
+ run_id = EXCLUDED.run_id,
+ error_msg = EXCLUDED.error_msg
+ RETURNING consecutive_failures
+ `;
+ return Number(row?.consecutive_failures ?? failInc);
+}
+
+// One x402_autonomous_log row per probe (endpoint_type 'self' — this pipeline is
+// a self-pipeline; value_extracted carries the verdict). The loop also records a
+// single aggregate summary row for the run() entry.
+async function recordCall(sql, runId, target, v) {
+ const host = hostOf(target.resource) || target.resource;
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${`Uptime: ${host}`}, ${target.resource},
+ ${(target.networks && target.networks[0]) || 'solana:mainnet'}, ${0}, ${null}, ${null},
+ ${JSON.stringify({ status: v.status ?? null, method: v.method, classification: v.classification })},
+ ${JSON.stringify({
+ alive: v.alive,
+ classification: v.classification,
+ status: v.status ?? null,
+ method: v.method,
+ latency_ms: v.latency_ms ?? null,
+ })},
+ ${v.latency_ms ?? 0}, ${v.alive}, ${v.error_msg}, ${'reliability'})
+ `;
+ } catch (err) {
+ log.warn('uptime_log_insert_failed', { resource: target.resource, message: err?.message });
+ }
+}
+
+async function writeRedisState(redis, { down, summary }) {
+ if (!redis) return;
+ try {
+ await redis.set(REDIS_LATEST_KEY, JSON.stringify(summary), { ex: REDIS_TTL_SECONDS });
+ if (down.length) {
+ await redis.set(REDIS_DEAD_KEY, JSON.stringify(down), { ex: REDIS_TTL_SECONDS });
+ } else {
+ await redis.del(REDIS_DEAD_KEY);
+ }
+ } catch (err) {
+ log.warn('uptime_redis_write_failed', { message: err?.message });
+ }
+}
+
+/**
+ * Run the uptime monitor. Conforms to the run()-style registry contract:
+ * ctx = { origin, redis, sql, log, runId } (all optional for standalone runs).
+ * Returns the aggregate outcome the loop records as one summary row.
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const sql = ctx.sql || defaultSql;
+ const redis = ctx.redis || null;
+
+ // Schema first — no sink, no value, so don't probe.
+ try {
+ await ensureSchema(sql);
+ } catch (err) {
+ log.warn('uptime_schema_failed', { message: err?.message });
+ return { success: false, skipped: true, amountAtomic: 0, txSig: null, errorMsg: `schema_failed: ${err?.message}` };
+ }
+
+ let targets;
+ try {
+ targets = await collectExternalTargets({ sql, origin });
+ } catch (err) {
+ log.warn('uptime_targets_failed', { message: err?.message });
+ return { success: false, skipped: true, amountAtomic: 0, txSig: null, errorMsg: `targets_failed: ${err?.message}`, note: 'targets_failed' };
+ }
+
+ if (!targets.length) {
+ log.info('uptime_no_targets', { run_id: runId });
+ return {
+ success: true, skipped: true, amountAtomic: 0, txSig: null,
+ responseData: { total_targets: 0, probed: 0, alive: 0, down: 0 },
+ note: 'no_external_services',
+ };
+ }
+
+ // Rotate coverage across runs when the catalog exceeds the per-run cap.
+ let start = 0;
+ if (targets.length > MAX_PER_RUN && redis) {
+ try {
+ const n = await redis.incrby(REDIS_CURSOR_KEY, MAX_PER_RUN);
+ start = ((Number(n) - MAX_PER_RUN) % targets.length + targets.length) % targets.length;
+ } catch { /* fall back to start=0 */ }
+ }
+ const batch = [];
+ for (let i = 0; i < Math.min(MAX_PER_RUN, targets.length); i++) {
+ batch.push(targets[(start + i) % targets.length]);
+ }
+
+ let alive = 0;
+ let down = 0;
+ let flagged = 0; // reachable_unexpected (up, but answered oddly)
+ const downServices = [];
+
+ // Probe in bounded-concurrency batches.
+ for (let i = 0; i < batch.length; i += PROBE_CONCURRENCY) {
+ const slice = batch.slice(i, i + PROBE_CONCURRENCY);
+ const probed = await Promise.all(slice.map(async (target) => {
+ let v;
+ try {
+ v = await probeService(target.resource);
+ } catch (err) {
+ v = classifyProbe(null, err?.message || 'probe_error');
+ v.status = null; v.method = 'HEAD'; v.latency_ms = null;
+ }
+ return { target, v };
+ }));
+
+ for (const { target, v } of probed) {
+ let consec = v.alive ? 0 : 1;
+ try {
+ consec = await upsertUptime(sql, runId, target, v);
+ } catch (err) {
+ log.warn('uptime_upsert_failed', { resource: target.resource, message: err?.message });
+ }
+ await recordCall(sql, runId, target, v);
+
+ if (v.alive) {
+ alive += 1;
+ if (v.classification === 'reachable_unexpected') flagged += 1;
+ } else {
+ down += 1;
+ downServices.push({ resource: target.resource, classification: v.classification, consecutive_failures: consec, error: v.error_msg });
+ // Warn once at the threshold crossing so a hard outage pages ops
+ // without spamming on every subsequent probe.
+ if (consec === FAILURE_THRESHOLD) {
+ log.warn('external_service_down', { resource: target.resource, classification: v.classification, consecutive_failures: consec });
+ }
+ }
+ }
+ }
+
+ const summary = {
+ ts: new Date().toISOString(),
+ total_targets: targets.length,
+ probed: batch.length,
+ alive,
+ down,
+ flagged,
+ down_services: downServices.map((d) => d.resource),
+ };
+ await writeRedisState(redis, { down: downServices, summary });
+
+ log.info('uptime_monitor_complete', {
+ run_id: runId,
+ total_targets: targets.length,
+ probed: batch.length,
+ alive, down, flagged,
+ });
+
+ return {
+ // success when the sweep ran and at least one probed service was reachable;
+ // a sweep where every probe failed still records (per-call rows above) but
+ // flags not-ok so health can surface a wholesale external outage.
+ success: batch.length > 0 && down < batch.length,
+ amountAtomic: 0,
+ txSig: null,
+ responseData: summary,
+ valueExtracted: { probed: batch.length, alive, down, flagged },
+ errorMsg: down > 0 ? `services_down:${down}` : null,
+ note: `uptime probed=${batch.length} alive=${alive} down=${down}${flagged ? ` flagged=${flagged}` : ''}`,
+ };
+}
+
+// ── Downstream consumer API ───────────────────────────────────────────────────
+
+/**
+ * Liveness gate for paying pipelines. Returns false ONLY when a service is
+ * known-dead beyond FAILURE_THRESHOLD consecutive probes; an unknown (never
+ * probed) or recovering service returns true so we never block a fresh endpoint.
+ */
+export async function isServiceLive(sql = defaultSql, resource) {
+ if (!resource) return true;
+ try {
+ const [row] = await sql`
+ SELECT alive, consecutive_failures
+ FROM x402_service_uptime
+ WHERE resource = ${resource}
+ LIMIT 1
+ `;
+ if (!row) return true; // unknown → allow
+ if (row.alive) return true;
+ return Number(row.consecutive_failures || 0) < FAILURE_THRESHOLD;
+ } catch {
+ return true; // never block production on a monitor read failure
+ }
+}
+
+/**
+ * Read the uptime table for an ops reliability surface.
+ * @param {object} sql
+ * @param {{ onlyDead?: boolean, limit?: number }} opts
+ */
+export async function listServiceUptime(sql = defaultSql, { onlyDead = false, limit = 200 } = {}) {
+ try {
+ const rows = onlyDead
+ ? await sql`
+ SELECT * FROM x402_service_uptime
+ WHERE alive = false
+ ORDER BY consecutive_failures DESC, last_checked DESC
+ LIMIT ${limit}`
+ : await sql`
+ SELECT * FROM x402_service_uptime
+ ORDER BY alive ASC, last_checked DESC
+ LIMIT ${limit}`;
+ return rows;
+ } catch (err) {
+ if (!/does not exist/i.test(err?.message || '')) {
+ log.warn('uptime_list_failed', { message: err?.message });
+ }
+ return [];
+ }
+}
diff --git a/api/_lib/x402/pipelines/spend-reservation-leak-detector.js b/api/_lib/x402/pipelines/spend-reservation-leak-detector.js
new file mode 100644
index 000000000..3782fe7f9
--- /dev/null
+++ b/api/_lib/x402/pipelines/spend-reservation-leak-detector.js
@@ -0,0 +1,422 @@
+// api/_lib/x402/pipelines/spend-reservation-leak-detector.js
+//
+// Spend Reservation Leak Detector — the work behind the
+// `spend-reservation-leak-detector` autonomous-registry entry (self/Finance).
+//
+// THE LEAK IT HUNTS
+// -----------------
+// Every autonomous outbound spend is two-phase: first a reservation row is
+// written that immediately claims headroom against the agent's rolling-24h cap,
+// then — after the on-chain send settles or fails — the reservation is FINALIZED
+// (advanced to confirmed) or RELEASED (so it stops counting). The release path is
+// `releaseSpendReservation()` (USD cap, agent_trade-guards.js → agent_custody_events)
+// and `releaseSpend()` (SOL cap, agent-spend-policy.js → agent_actions).
+//
+// If the process dies between reserve and finalize/release — a crash, a timeout, a
+// thrown error on a path that forgot its `finally` — the reservation is ORPHANED.
+// It still holds cap headroom it will never spend. Enough orphans and the agent's
+// daily cap is silently exhausted by money that never moved: every real spend then
+// fails `daily_exceeded` even though the wallet is full. That is the leak.
+//
+// A reservation older than one hour that is still `pending` (USD) or still
+// `reserved` (SOL) is unambiguously orphaned: Solana settles in seconds, so a
+// healthy reserve is finalized or released within that window many times over. One
+// hour is ~100× the settlement time — nothing legitimate is still in flight.
+//
+// WHAT THIS PIPELINE DOES (every 15 min)
+// --------------------------------------
+// 1. Scans agent_custody_events for event_type='spend', status='pending',
+// created_at < now()-1h → leaked USD reservations.
+// 2. Scans agent_actions for the SOL-outflow types still payload.status='reserved'
+// and created_at < now()-1h → leaked SOL reservations.
+// 3. Cleans each up through the REAL release path so the freed headroom is
+// identical to what a correct finalize/release would have produced:
+// • USD → releaseSpendReservation(id, 'leak_detector_swept') — marks the
+// pending row 'failed' (audit row preserved, stops counting).
+// • SOL → record the leak first (releaseSpend DELETEs, so we capture the
+// evidence into the value sink), then releaseSpend(id).
+// 4. Records every swept leak into `spend_reservation_leaks` (the value sink) and
+// publishes a compact alert/latest state to Redis for cheap consumer reads.
+// 5. Records ONE x402_autonomous_log row with value_extracted = the sweep summary.
+//
+// COST: free. The endpoint is a pure DB maintenance query — no x402 challenge, no
+// outbound payment, amountAtomic always 0. Like the revenue-reconciliation pipeline
+// it is read/write-against-our-own-DB only, so it runs WITHOUT the spend wallet:
+// a leaked-reservation sweep must never be blocked by a missing keypair, since an
+// unconfigured wallet is exactly when nothing else can free the cap.
+//
+// VALUE SINK: spend_reservation_leaks (one row per swept leak, keyed UNIQUE on
+// (source, source_ref)) + Redis x402:reservation-leak:{latest,alert}.
+// DOWNSTREAM CONSUMER: api/ops/health.js loadReservationLeaks() folds a spike in
+// freshly-swept leaks into the platform health verdict (a sustained leak rate means
+// a reserve→finalize path is crashing and quietly starving agent spend caps); the
+// Redis alert key gives the status dashboard a one-GET read of the current state.
+
+import { randomUUID } from 'node:crypto';
+
+import { sql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { releaseSpendReservation } from '../../agent-trade-guards.js';
+import { releaseSpend, SOL_OUTFLOW_TYPES } from '../../agent-spend-policy.js';
+import { USDC_MINT } from '../pay.js';
+
+const log = logger('x402-reservation-leak-detector');
+
+const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// A reservation older than this with no finalize/release is orphaned. Solana
+// settles in seconds; 1h is ~100× the settlement window, so nothing legitimate is
+// still in flight. Env-tunable for environments with slower settlement rails.
+const LEAK_AGE_SECONDS = Math.max(
+ 300,
+ Number(process.env.X402_RESERVATION_LEAK_AGE_SECONDS || 3600),
+);
+
+// Hard bound on rows touched per run so one tick can never be unbounded if a bug
+// floods the tables with leaks. The 15-min cadence drains any backlog across runs.
+const MAX_SWEEP_PER_SOURCE = Math.max(
+ 1,
+ Number(process.env.X402_RESERVATION_LEAK_MAX_PER_RUN || 500),
+);
+
+const REDIS_LATEST_KEY = 'x402:reservation-leak:latest';
+const REDIS_ALERT_KEY = 'x402:reservation-leak:alert';
+// Alert/latest TTL: a little over two 15-min cycles so a missed run lets the flag
+// lapse to "unknown" rather than latching a stale alert forever.
+const REDIS_TTL_SECONDS = 40 * 60;
+
+async function ensureSchema(db) {
+ await db`
+ CREATE TABLE IF NOT EXISTS spend_reservation_leaks (
+ id bigserial PRIMARY KEY,
+ source text NOT NULL, -- 'custody_event' | 'agent_action'
+ source_ref text NOT NULL, -- row id in the originating table
+ agent_id text,
+ asset text, -- 'USDC' | 'SOL' | mint
+ usd float8, -- freed USD cap headroom (custody)
+ sol_amount float8, -- freed SOL cap headroom (action)
+ category text, -- spend category / action type
+ age_seconds int, -- reservation age at sweep
+ action text NOT NULL, -- 'released' | 'deleted'
+ run_id uuid,
+ reserved_at timestamptz,
+ swept_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (source, source_ref)
+ )
+ `;
+ await db`CREATE INDEX IF NOT EXISTS spend_reservation_leaks_swept_idx
+ ON spend_reservation_leaks (swept_at DESC)`;
+ // The autonomous log predates this pipeline; ensure the column its summary lands
+ // in exists (idempotent — shared with every other run() that writes it).
+ await db`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+}
+
+// Persist a swept leak into the value sink. Idempotent on (source, source_ref) so a
+// re-record within a run (or an overlapping run) can never double-insert.
+async function recordLeak(db, runId, leak) {
+ await db`
+ INSERT INTO spend_reservation_leaks
+ (source, source_ref, agent_id, asset, usd, sol_amount, category,
+ age_seconds, action, run_id, reserved_at, swept_at)
+ VALUES
+ (${leak.source}, ${leak.source_ref}, ${leak.agent_id ?? null},
+ ${leak.asset ?? null}, ${leak.usd ?? null}, ${leak.sol_amount ?? null},
+ ${leak.category ?? null}, ${leak.age_seconds ?? null}, ${leak.action},
+ ${runId}, ${leak.reserved_at ?? null}, now())
+ ON CONFLICT (source, source_ref) DO UPDATE SET
+ action = EXCLUDED.action,
+ usd = EXCLUDED.usd,
+ sol_amount = EXCLUDED.sol_amount,
+ age_seconds = EXCLUDED.age_seconds,
+ run_id = EXCLUDED.run_id,
+ swept_at = now()
+ `;
+}
+
+// ── USD reservations (agent_custody_events) ─────────────────────────────────────
+// Leaked = event_type 'spend', status 'pending', older than the leak window. The
+// release path marks the pending row 'failed' (preserving the audit row) so it
+// stops counting toward getDailySpendUsd — exactly what a correct releaseSpendReservation
+// at the spend site would have done.
+async function sweepCustodyLeaks(db, runId, releaseUsd) {
+ let rows = [];
+ try {
+ rows = await db`
+ SELECT id, agent_id, asset, usd, category,
+ extract(epoch FROM (now() - created_at))::int AS age_seconds,
+ created_at
+ FROM agent_custody_events
+ WHERE event_type = 'spend'
+ AND status = 'pending'
+ AND created_at < now() - (${LEAK_AGE_SECONDS} || ' seconds')::interval
+ ORDER BY created_at ASC
+ LIMIT ${MAX_SWEEP_PER_SOURCE}
+ `;
+ } catch (err) {
+ if (!/does not exist/.test(err?.message || '')) {
+ log.warn('custody_scan_failed', { message: err?.message });
+ }
+ return { scanned: 0, swept: [], usdFreed: 0 };
+ }
+
+ const swept = [];
+ let usdFreed = 0;
+ for (const r of rows) {
+ try {
+ // Free the cap through the real release path, then capture the evidence.
+ await releaseUsd(r.id, 'leak_detector_swept');
+ const usd = r.usd != null ? Number(r.usd) : null;
+ if (usd) usdFreed += usd;
+ const leak = {
+ source: 'custody_event',
+ source_ref: String(r.id),
+ agent_id: r.agent_id ? String(r.agent_id) : null,
+ asset: r.asset || 'USDC',
+ usd,
+ sol_amount: null,
+ category: r.category || null,
+ age_seconds: r.age_seconds ?? null,
+ action: 'released',
+ reserved_at: r.created_at || null,
+ };
+ await recordLeak(db, runId, leak);
+ swept.push(leak);
+ } catch (err) {
+ log.warn('custody_sweep_failed', { id: String(r.id), message: err?.message });
+ }
+ }
+ return { scanned: rows.length, swept, usdFreed };
+}
+
+// ── SOL reservations (agent_actions) ────────────────────────────────────────────
+// Leaked = a SOL-outflow action still at payload.status 'reserved' past the window.
+// releaseSpend() DELETEs the row (that is how the SOL cap is freed — the 24h cap
+// query counts every outflow row regardless of status, so only removal frees it), so
+// we record the leak into the value sink FIRST to preserve the evidence the delete
+// would otherwise destroy.
+async function sweepSolActionLeaks(db, runId, releaseSol) {
+ let rows = [];
+ try {
+ rows = await db`
+ SELECT id, agent_id, type,
+ (payload->>'solAmount')::float8 AS sol_amount,
+ payload->>'mint' AS mint,
+ extract(epoch FROM (now() - created_at))::int AS age_seconds,
+ created_at
+ FROM agent_actions
+ WHERE type = ANY(${SOL_OUTFLOW_TYPES})
+ AND payload->>'status' = 'reserved'
+ AND created_at < now() - (${LEAK_AGE_SECONDS} || ' seconds')::interval
+ ORDER BY created_at ASC
+ LIMIT ${MAX_SWEEP_PER_SOURCE}
+ `;
+ } catch (err) {
+ if (!/does not exist/.test(err?.message || '')) {
+ log.warn('sol_scan_failed', { message: err?.message });
+ }
+ return { scanned: 0, swept: [], solFreed: 0 };
+ }
+
+ const swept = [];
+ let solFreed = 0;
+ for (const r of rows) {
+ try {
+ const sol = r.sol_amount != null ? Number(r.sol_amount) : null;
+ const leak = {
+ source: 'agent_action',
+ source_ref: String(r.id),
+ agent_id: r.agent_id ? String(r.agent_id) : null,
+ asset: 'SOL',
+ usd: null,
+ sol_amount: sol,
+ category: r.type || null,
+ age_seconds: r.age_seconds ?? null,
+ action: 'deleted',
+ reserved_at: r.created_at || null,
+ };
+ // Evidence first (releaseSpend destroys the source row), then free the cap.
+ await recordLeak(db, runId, leak);
+ await releaseSol(r.id);
+ if (sol) solFreed += sol;
+ swept.push(leak);
+ } catch (err) {
+ log.warn('sol_sweep_failed', { id: String(r.id), message: err?.message });
+ }
+ }
+ return { scanned: rows.length, swept, solFreed };
+}
+
+// Publish the latest sweep + an alert flag (present only while leaks were found) to
+// Redis for a cheap, DB-free consumer read. Mirrors the wallet-balance monitor's
+// x402:wallet-balance:{latest,alert} convention so the status dashboard reads both
+// the same way. Best-effort: a Redis hiccup never fails the sweep.
+async function writeRedisState(redis, summary) {
+ if (!redis) return;
+ try {
+ await redis.set(REDIS_LATEST_KEY, JSON.stringify(summary), { ex: REDIS_TTL_SECONDS });
+ if (summary.leaked_total > 0) {
+ await redis.set(REDIS_ALERT_KEY, JSON.stringify({
+ leaked_total: summary.leaked_total,
+ usd_freed: summary.usd_freed,
+ sol_freed: summary.sol_freed,
+ agents_affected: summary.agents_affected,
+ oldest_age_seconds: summary.oldest_age_seconds,
+ at: summary.at,
+ }), { ex: REDIS_TTL_SECONDS });
+ } else {
+ // Clean run — drop any lingering alert so it doesn't latch stale.
+ await redis.del(REDIS_ALERT_KEY);
+ }
+ } catch (err) {
+ log.warn('leak_redis_write_failed', { message: err?.message });
+ }
+}
+
+// Record this run's single summary row into x402_autonomous_log, with the sweep
+// summary in value_extracted. Returns true on success.
+async function recordLogRow(db, runId, { durationMs, success, errorMsg, summary }) {
+ try {
+ await db`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${'Spend Reservation Leak Detector'},
+ ${'/api/_lib/agent-trade-guards'},
+ ${'solana:mainnet'}, ${0}, ${ASSET}, ${null},
+ ${summary ? JSON.stringify(summary) : null},
+ ${summary ? JSON.stringify(summary) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'finance'})
+ `;
+ return true;
+ } catch (err) {
+ log.warn('leak_log_insert_failed', { message: err?.message });
+ return false;
+ }
+}
+
+/**
+ * Run the leak sweep. Conforms to the run()-style registry contract: the loop hands
+ * { origin, redis, sql, log, runId, ... }. Pure DB maintenance — no payment, no
+ * wallet required (it runs even when the spend wallet is absent, exactly when the
+ * cap most needs freeing). Records its own canonical log row, so it returns
+ * `recorded: true` and the loop adds no duplicate summary row.
+ *
+ * Returns the aggregate outcome the loop surfaces:
+ * { success, amountAtomic, txSig, errorMsg, responseData, recorded, valueExtracted, note }
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const redis = ctx.redis || null;
+ // The loop hands its own sql in ctx; fall back to the module client for a
+ // standalone/manual run. All of THIS pipeline's queries go through `db`.
+ const db = ctx.sql || sql;
+ // The canonical release paths (single source of truth for "free this reservation").
+ // Overridable via ctx for the manual test; the loop never passes them, so
+ // production always runs the real releasers.
+ const releaseUsd = ctx.releaseSpendReservation || releaseSpendReservation;
+ const releaseSol = ctx.releaseSpend || releaseSpend;
+ const t0 = Date.now();
+
+ // Schema first: without the value sink there is nowhere to record the evidence,
+ // and recording before release is what keeps the SOL delete auditable.
+ try {
+ await ensureSchema(db);
+ } catch (err) {
+ log.warn('leak_schema_failed', { message: err?.message });
+ const durationMs = Date.now() - t0;
+ await recordLogRow(db, runId, {
+ durationMs, success: false, errorMsg: `schema_failed: ${err?.message}`, summary: null,
+ });
+ return {
+ success: false, amountAtomic: 0, txSig: null, recorded: true,
+ errorMsg: `schema_failed: ${err?.message}`, note: 'leak sweep aborted: schema',
+ };
+ }
+
+ // Each source sweep is independently guarded — a failure in one (e.g. a table
+ // that doesn't exist in this env) degrades to "scanned 0" and never blocks the
+ // other, and never crashes the tick.
+ const custody = await sweepCustodyLeaks(db, runId);
+ const solActions = await sweepSolActionLeaks(db, runId);
+
+ const allSwept = [...custody.swept, ...solActions.swept];
+ const agents = new Set(allSwept.map((l) => l.agent_id).filter(Boolean));
+ const oldestAge = allSwept.reduce((m, l) => Math.max(m, l.age_seconds || 0), 0);
+
+ const summary = {
+ at: new Date(t0).toISOString(),
+ leak_age_seconds: LEAK_AGE_SECONDS,
+ scanned: {
+ custody_pending: custody.scanned,
+ sol_reserved: solActions.scanned,
+ },
+ leaked: {
+ custody_events: custody.swept.length,
+ agent_actions: solActions.swept.length,
+ },
+ leaked_total: allSwept.length,
+ usd_freed: Number(custody.usdFreed.toFixed(6)),
+ sol_freed: Number(solActions.solFreed.toFixed(9)),
+ agents_affected: agents.size,
+ oldest_age_seconds: oldestAge,
+ // Bounded sample for the log row; the full set lives in spend_reservation_leaks.
+ sample: allSwept.slice(0, 20).map((l) => ({
+ source: l.source, ref: l.source_ref, agent_id: l.agent_id,
+ asset: l.asset, usd: l.usd, sol: l.sol_amount,
+ age_seconds: l.age_seconds, action: l.action,
+ })),
+ };
+
+ await writeRedisState(redis, summary);
+
+ const durationMs = Date.now() - t0;
+ // A clean run (nothing leaked) is a success — it proves the reserve→finalize
+ // paths are healthy. Only an outright failure to scan/record is an error.
+ await recordLogRow(db, runId, { durationMs, success: true, errorMsg: null, summary });
+
+ if (summary.leaked_total > 0) {
+ log.warn('reservation_leaks_swept', {
+ run_id: runId,
+ leaked_total: summary.leaked_total,
+ custody: summary.leaked.custody_events,
+ sol: summary.leaked.agent_actions,
+ usd_freed: summary.usd_freed,
+ sol_freed: summary.sol_freed,
+ agents_affected: summary.agents_affected,
+ oldest_age_seconds: summary.oldest_age_seconds,
+ duration_ms: durationMs,
+ });
+ } else {
+ log.info('reservation_leak_sweep_clean', {
+ run_id: runId,
+ scanned_custody: summary.scanned.custody_pending,
+ scanned_sol: summary.scanned.sol_reserved,
+ duration_ms: durationMs,
+ });
+ }
+
+ return {
+ success: true,
+ amountAtomic: 0,
+ txSig: null,
+ errorMsg: null,
+ recorded: true, // we wrote our own canonical row above
+ valueExtracted: summary,
+ responseData: {
+ leaked_total: summary.leaked_total,
+ usd_freed: summary.usd_freed,
+ sol_freed: summary.sol_freed,
+ agents_affected: summary.agents_affected,
+ },
+ note: summary.leaked_total > 0
+ ? `swept ${summary.leaked_total} leak(s): $${summary.usd_freed} + ${summary.sol_freed} SOL freed`
+ : 'no leaked reservations',
+ };
+}
+
+export const RESERVATION_LEAK_REDIS_LATEST_KEY = REDIS_LATEST_KEY;
+export const RESERVATION_LEAK_REDIS_ALERT_KEY = REDIS_ALERT_KEY;
+export const RESERVATION_LEAK_AGE_SECONDS = LEAK_AGE_SECONDS;
diff --git a/api/_lib/x402/pipelines/subscription-health.js b/api/_lib/x402/pipelines/subscription-health.js
new file mode 100644
index 000000000..3c48096b7
--- /dev/null
+++ b/api/_lib/x402/pipelines/subscription-health.js
@@ -0,0 +1,378 @@
+// api/_lib/x402/pipelines/subscription-health.js
+//
+// Subscription Status Health Check — the work behind the
+// `subscription-status-health-check` autonomous-registry entry (self). Runs daily.
+//
+// Every paying x402 subscriber holds an API key (x402_subscriptions) that bypasses
+// the 402 challenge on our paid endpoints until it expires or is revoked. When a
+// key silently lapses, the subscriber's integration starts getting charged (or
+// hard-402'd) with no warning — a surprise service interruption that reads as our
+// fault. This pipeline closes that gap:
+//
+// 1. Enumerates every subscription by calling the real admin endpoint
+// GET /api/x402/admin/subscriptions?includeInactive=1 over HTTP, authenticated
+// as an internal service with INTERNAL_API_KEY (the GET-only read bypass added
+// to that endpoint). If the HTTP path is unavailable (key unset, network
+// blip), it falls back to the canonical listSubscriptions() lib read so the
+// health check still runs — never a mock, always the real subscription book.
+// 2. Classifies each one: active | expiring_soon (≤ EXPIRY_WARN_DAYS) | expired |
+// revoked, and computes days-to-expiry.
+// 3. Emails the subscriber EXPIRY_WARN_DAYS (7) days before expiry — once per
+// expiry timestamp, so a renewal that pushes expires_at forward re-arms the
+// warning. Contact email is read from the subscription meta (email /
+// contact_email / contact / notify_email). No contact on file → recorded as
+// not-notifiable, never blocks the run.
+// 4. Upserts each verdict into x402_subscription_health (the value sink) and
+// records ONE x402_autonomous_log row with a value_extracted summary.
+//
+// Free + read-only: the admin endpoint owes no payment, so this pipeline never
+// moves funds (amountAtomic always 0) and runs even when the spend wallet is
+// absent — mirroring the revenue-reconciliation precedent.
+//
+// Downstream consumer: the admin subscription-management surface reads
+// x402_subscription_health to badge expiring/expired keys, and ops alerting watches
+// WHERE status IN ('expired','expiring_soon') to catch a lapse before a partner's
+// integration breaks.
+
+import { randomUUID } from 'node:crypto';
+
+import { sql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { fetchWithTimeout } from '../pay.js';
+import { listSubscriptions } from '../api-keys.js';
+import { sendEmail } from '../../email.js';
+
+const log = logger('x402-subscription-health');
+
+const ENDPOINT_PATH = '/api/x402/admin/subscriptions';
+// Warn this many days before expiry. A 7-day window with a daily cadence means a
+// subscriber gets at least one warning email before the key lapses.
+const EXPIRY_WARN_DAYS = Number(process.env.X402_SUBSCRIPTION_WARN_DAYS || 7);
+const DAY_MS = 86_400_000;
+
+let _schemaReady = false;
+async function ensureSchema() {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_subscription_health (
+ subscription_id text PRIMARY KEY,
+ name text,
+ key_prefix text,
+ status text NOT NULL, -- active | expiring_soon | expired | revoked
+ rate_limit_per_minute integer,
+ expires_at timestamptz,
+ revoked_at timestamptz,
+ days_to_expiry integer, -- null when no expiry
+ contact_email text,
+ notified_expiry_at timestamptz, -- the expires_at value we last emailed about
+ notified_at timestamptz, -- when that email was sent
+ last_checked_at timestamptz NOT NULL DEFAULT now(),
+ run_id uuid,
+ meta jsonb
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_subscription_health_status_idx
+ ON x402_subscription_health (status, expires_at)`;
+ // Shared with other run()-style entries; idempotent.
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+// Pull a contact email out of the subscription meta. Operators store partner
+// contact details under a few conventional keys; accept the common ones and
+// validate it looks like an address before we'd ever email it.
+function contactEmail(meta) {
+ if (!meta || typeof meta !== 'object') return null;
+ const candidate =
+ meta.email ||
+ meta.contact_email ||
+ meta.notify_email ||
+ (typeof meta.contact === 'string' ? meta.contact : meta.contact?.email) ||
+ null;
+ if (!candidate || typeof candidate !== 'string') return null;
+ const trimmed = candidate.trim();
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed) ? trimmed : null;
+}
+
+function toDate(v) {
+ if (!v) return null;
+ const d = v instanceof Date ? v : new Date(v);
+ return Number.isNaN(d.getTime()) ? null : d;
+}
+
+// Pure classifier — returns { status, daysToExpiry }.
+function classify(sub, now) {
+ if (toDate(sub.revoked_at)) return { status: 'revoked', daysToExpiry: null };
+ const exp = toDate(sub.expires_at);
+ if (!exp) return { status: 'active', daysToExpiry: null };
+ const days = Math.ceil((exp.getTime() - now) / DAY_MS);
+ if (days <= 0) return { status: 'expired', daysToExpiry: days };
+ if (days <= EXPIRY_WARN_DAYS) return { status: 'expiring_soon', daysToExpiry: days };
+ return { status: 'active', daysToExpiry: days };
+}
+
+// Enumerate subscriptions over the real admin HTTP endpoint as an internal
+// service; fall back to the canonical lib read if HTTP is unavailable. Returns
+// { rows, source } so the summary can record which path served the data.
+async function enumerateSubscriptions(origin) {
+ const internalKey = process.env.INTERNAL_API_KEY;
+ if (internalKey) {
+ try {
+ const url = `${origin}${ENDPOINT_PATH}?includeInactive=1`;
+ const res = await fetchWithTimeout(url, {
+ method: 'GET',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': internalKey,
+ 'user-agent': 'threews-x402-autonomous/1.0',
+ },
+ });
+ if (res.ok && Array.isArray(res.body?.data)) {
+ return { rows: res.body.data, source: 'http' };
+ }
+ log.warn('subscription_http_enumerate_degraded', {
+ status: res.status,
+ });
+ } catch (err) {
+ log.warn('subscription_http_enumerate_failed', { message: err?.message });
+ }
+ }
+ // Resilient fallback: read the same book the endpoint reads.
+ const rows = await listSubscriptions({ includeInactive: true });
+ return { rows, source: 'lib' };
+}
+
+// Send the expiry warning email. Fire-and-forget at the email layer, but we await
+// the send here so the per-subscription notified_at is only stamped on success.
+async function sendExpiryWarning({ to, sub, daysToExpiry, expiresAt }) {
+ const appUrl = env.APP_ORIGIN || 'https://three.ws';
+ const when = expiresAt ? new Date(expiresAt).toUTCString() : 'soon';
+ const label = sub.name || sub.id;
+ const subject = `Your three.ws API subscription expires in ${daysToExpiry} day${daysToExpiry === 1 ? '' : 's'}`;
+ const text =
+ `Your three.ws x402 API subscription "${label}" (key ${sub.key_prefix}) expires on ${when} ` +
+ `(${daysToExpiry} day${daysToExpiry === 1 ? '' : 's'} from now).\n\n` +
+ `Renew before then to avoid interruption — once the key lapses, requests on it ` +
+ `will be charged per-call or rejected with a 402.\n\n` +
+ `Manage your subscription: ${appUrl}/dashboard/\n\n` +
+ `Questions? Reply to this email and we'll help.`;
+ const html =
+ `<!DOCTYPE html><html><body style="font-family:-apple-system,system-ui,'Segoe UI',sans-serif;background:#080814;color:#eee;margin:0;padding:32px 16px">` +
+ `<div style="max-width:520px;margin:0 auto;background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:36px 32px">` +
+ `<p style="font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:#6a5cff;margin:0 0 20px">three.ws</p>` +
+ `<h1 style="font-size:22px;margin:0 0 12px">Your API subscription expires in ${daysToExpiry} day${daysToExpiry === 1 ? '' : 's'}</h1>` +
+ `<p style="color:#aaa;line-height:1.6;font-size:15px">Your subscription <strong>${esc(label)}</strong> (key <code>${esc(sub.key_prefix)}</code>) expires on <strong>${esc(when)}</strong>.</p>` +
+ `<p style="color:#aaa;line-height:1.6;font-size:15px">Renew before then to avoid interruption — once the key lapses, requests on it are charged per-call or rejected with a 402.</p>` +
+ `<a href="${appUrl}/dashboard/" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#6a5cff,#ff5ca8);color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:15px;margin:8px 0 20px">Manage subscription</a>` +
+ `<hr style="border:none;border-top:1px solid #2a2a36;margin:24px 0">` +
+ `<p style="color:#555;font-size:13px">Questions? Reply to this email and we'll help.</p>` +
+ `</div></body></html>`;
+ return sendEmail({ to, subject, html, text });
+}
+
+function esc(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+// Upsert one subscription's verdict. notified_* are only advanced when this run
+// actually sent an email; otherwise the prior values are preserved so we never
+// re-notify for an expiry timestamp already warned about.
+async function upsert(runId, sub, verdict, contact, notifiedExpiryAt) {
+ try {
+ const expiresAt = toDate(sub.expires_at);
+ const revokedAt = toDate(sub.revoked_at);
+ const notifiedAt = notifiedExpiryAt ? new Date() : null;
+ await sql`
+ INSERT INTO x402_subscription_health
+ (subscription_id, name, key_prefix, status, rate_limit_per_minute,
+ expires_at, revoked_at, days_to_expiry, contact_email,
+ notified_expiry_at, notified_at, last_checked_at, run_id, meta)
+ VALUES
+ (${sub.id}, ${sub.name || null}, ${sub.key_prefix || null}, ${verdict.status},
+ ${sub.rate_limit_per_minute ?? null}, ${expiresAt}, ${revokedAt},
+ ${verdict.daysToExpiry}, ${contact},
+ ${notifiedExpiryAt}, ${notifiedAt},
+ now(), ${runId}, ${sub.meta ? JSON.stringify(sub.meta) : null})
+ ON CONFLICT (subscription_id) DO UPDATE SET
+ name = EXCLUDED.name,
+ key_prefix = EXCLUDED.key_prefix,
+ status = EXCLUDED.status,
+ rate_limit_per_minute = EXCLUDED.rate_limit_per_minute,
+ expires_at = EXCLUDED.expires_at,
+ revoked_at = EXCLUDED.revoked_at,
+ days_to_expiry = EXCLUDED.days_to_expiry,
+ contact_email = EXCLUDED.contact_email,
+ notified_expiry_at = COALESCE(EXCLUDED.notified_expiry_at, x402_subscription_health.notified_expiry_at),
+ notified_at = COALESCE(EXCLUDED.notified_at, x402_subscription_health.notified_at),
+ last_checked_at = now(),
+ run_id = EXCLUDED.run_id,
+ meta = EXCLUDED.meta
+ `;
+ } catch (err) {
+ log.warn('subscription_health_upsert_failed', { id: sub.id, message: err?.message });
+ }
+}
+
+// Has this exact expiry timestamp already been warned about? Reads the prior
+// health row so a daily cadence emails at most once per expiry window.
+async function alreadyNotified(subId, expiresAt) {
+ if (!expiresAt) return false;
+ try {
+ const rows = await sql`
+ SELECT notified_expiry_at FROM x402_subscription_health
+ WHERE subscription_id = ${subId} LIMIT 1
+ `;
+ const prev = toDate(rows[0]?.notified_expiry_at);
+ return !!prev && prev.getTime() === new Date(expiresAt).getTime();
+ } catch {
+ return false;
+ }
+}
+
+async function recordLogRow(runId, { endpointUrl, durationMs, success, errorMsg, summary }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${'Subscription Status Health Check'}, ${endpointUrl},
+ ${'solana:mainnet'}, ${0}, ${null}, ${null},
+ ${summary ? JSON.stringify(summary) : null},
+ ${summary ? JSON.stringify(summary) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'self'})
+ `;
+ } catch (err) {
+ log.warn('subscription_health_log_insert_failed', { message: err?.message });
+ }
+}
+
+/**
+ * Run the subscription health check. Conforms to the run()-style registry
+ * contract: the loop hands { origin, runId, ... }. Read-only + free, so it never
+ * touches the spend wallet and runs standalone for manual testing.
+ *
+ * Returns the aggregate outcome the loop records — recorded:true since this
+ * pipeline writes its own canonical x402_autonomous_log row.
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const endpointUrl = `${origin}${ENDPOINT_PATH}`;
+ const t0 = Date.now();
+
+ try {
+ await ensureSchema();
+ } catch (err) {
+ log.warn('subscription_health_schema_failed', { message: err?.message });
+ return {
+ success: false, skipped: true, recorded: false,
+ amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}`,
+ };
+ }
+
+ let rows = [];
+ let source = 'lib';
+ try {
+ ({ rows, source } = await enumerateSubscriptions(origin));
+ } catch (err) {
+ const durationMs = Date.now() - t0;
+ const errorMsg = err?.message || 'enumerate_failed';
+ await recordLogRow(runId, { endpointUrl, durationMs, success: false, errorMsg, summary: null });
+ return { success: false, recorded: true, amountAtomic: 0, errorMsg };
+ }
+
+ const now = Date.now();
+ const summary = {
+ source,
+ checked: rows.length,
+ active: 0,
+ expiring_soon: 0,
+ expired: 0,
+ revoked: 0,
+ emailed: 0,
+ email_skipped_no_contact: 0,
+ email_skipped_unconfigured: 0,
+ email_failed: 0,
+ expiring_sample: [],
+ };
+
+ for (const sub of rows) {
+ const verdict = classify(sub, now);
+ summary[verdict.status] = (summary[verdict.status] || 0) + 1;
+
+ const contact = contactEmail(sub.meta);
+ let notifiedExpiryAt = null;
+
+ if (verdict.status === 'expiring_soon') {
+ summary.expiring_sample.push({
+ id: sub.id, name: sub.name || null, days: verdict.daysToExpiry, has_contact: !!contact,
+ });
+ if (!contact) {
+ summary.email_skipped_no_contact += 1;
+ } else if (await alreadyNotified(sub.id, sub.expires_at)) {
+ // Already warned for this exact expiry window — nothing to do.
+ } else {
+ try {
+ const result = await sendExpiryWarning({
+ to: contact, sub, daysToExpiry: verdict.daysToExpiry, expiresAt: sub.expires_at,
+ });
+ if (result?.skipped) {
+ // RESEND_API_KEY unset (dev/preview) — don't stamp notified, so the
+ // warning fires for real once email is configured.
+ summary.email_skipped_unconfigured += 1;
+ } else {
+ notifiedExpiryAt = toDate(sub.expires_at);
+ summary.emailed += 1;
+ }
+ } catch (err) {
+ summary.email_failed += 1;
+ log.warn('subscription_expiry_email_failed', { id: sub.id, message: err?.message });
+ }
+ }
+ }
+
+ await upsert(runId, sub, verdict, contact, notifiedExpiryAt);
+ }
+ summary.expiring_sample = summary.expiring_sample.slice(0, 20);
+
+ const durationMs = Date.now() - t0;
+ await recordLogRow(runId, { endpointUrl, durationMs, success: true, errorMsg: null, summary });
+
+ log.info('subscription_health_complete', {
+ run_id: runId,
+ source,
+ checked: summary.checked,
+ expiring_soon: summary.expiring_soon,
+ expired: summary.expired,
+ emailed: summary.emailed,
+ duration_ms: durationMs,
+ });
+
+ return {
+ success: true,
+ recorded: true,
+ amountAtomic: 0,
+ txSig: null,
+ errorMsg: null,
+ responseData: {
+ source: summary.source,
+ checked: summary.checked,
+ expiring_soon: summary.expiring_soon,
+ expired: summary.expired,
+ revoked: summary.revoked,
+ emailed: summary.emailed,
+ },
+ valueExtracted: summary,
+ note: `subs checked=${summary.checked} expiring=${summary.expiring_soon} expired=${summary.expired} emailed=${summary.emailed}`,
+ };
+}
+
+// Pure helpers exposed for unit tests (no DB / network).
+export const __test = { classify, contactEmail, EXPIRY_WARN_DAYS };
diff --git a/api/_lib/x402/pipelines/x402-pricing-tracker.js b/api/_lib/x402/pipelines/x402-pricing-tracker.js
new file mode 100644
index 000000000..8c4472777
--- /dev/null
+++ b/api/_lib/x402/pipelines/x402-pricing-tracker.js
@@ -0,0 +1,577 @@
+// api/_lib/x402/pipelines/x402-pricing-tracker.js
+//
+// x402 Service Pricing Tracker — autonomous pipeline (self).
+//
+// Tracks the price history of the external x402 services three.ws depends on so
+// our cost models stay honest. On each run it picks the stalest batch of tracked
+// services and, for each, pays a real on-chain $0.001 USDC call to the three.ws
+// x402 Bazaar MCP server (/api/mcp-bazaar → bazaar_service_details) to read that
+// service's *current live* price across networks. It compares the fresh price to
+// the last recorded one and:
+// • raises a PRICE INCREASE alert when a service's cheapest price jumped > 20%
+// (so we revisit our cost models / consider an alternative), and
+// • flags a PRICE DROP opportunity when it fell enough (≤ -15%) that we should
+// lean on the service more.
+//
+// The pipeline:
+// 1. Builds the tracked-service set from the live, priced resources the Bazaar
+// Discovery Warmup (self/008) snapshots into x402_bazaar_catalog — i.e. the
+// external services we have actually discovered and depend on. No hardcoded
+// service list; coverage grows with what the warmup finds.
+// 2. Probes + pays bazaar_service_details for the stalest BATCH services (real
+// x402; degrades gracefully when the wallet/RPC is unconfigured or a single
+// call fails — never crashes the loop).
+// 3. Appends a row per check to x402_service_price_history and upserts the
+// latest snapshot (+ change math + alert flags) into x402_service_price_current.
+// 4. Records one row per call in x402_autonomous_log (success OR failure), with
+// the price + change summary in value_extracted.
+//
+// Downstream consumer: GET /api/x402/service-pricing-report reads
+// x402_service_price_current to surface the tracked catalog, the active
+// price-increase alerts (cost-model action items), and the price-drop
+// opportunities. The same table is the source of truth for revisiting the unit
+// economics behind our own pricing.
+//
+// Real on-chain payments only — no mocks, no simulations.
+
+import { randomUUID } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+import { getMint } from '@solana/spl-token';
+
+import { sql } from '../../db.js';
+import { env } from '../../env.js';
+import { solanaConnection } from '../../solana/connection.js';
+import { logger } from '../../usage.js';
+import { loadSeedKeypair, payX402 } from '../pay.js';
+
+const log = logger('x402-pricing-tracker');
+
+const USDC_MINT = () => env.X402_ASSET_MINT_SOLANA || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// How many tracked services to re-price per run. With the registry's 6h cooldown
+// this rotates through the tracked set a few at a time while bounding spend
+// (≤ BATCH × $0.001 per run). A catalog of ~20 services is fully refreshed ≈ daily.
+const BATCH = Math.max(1, Number(process.env.X402_PRICING_TRACKER_BATCH || 5));
+
+// Price-change thresholds. A cheapest-price jump above this fraction trips a
+// cost-model alert; a drop at/below the negative threshold flags an opportunity.
+const INCREASE_ALERT_PCT = Number(process.env.X402_PRICING_INCREASE_PCT || 20);
+const DROP_OPPORTUNITY_PCT = Number(process.env.X402_PRICING_DROP_PCT || 15);
+
+// ── Schema ──────────────────────────────────────────────────────────────────
+let _schemaReady = false;
+async function ensureSchema() {
+ if (_schemaReady) return;
+ // Append-only price observations — one row per check. The time series behind
+ // any trend/sparkline view of a dependency's price.
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_service_price_history (
+ id bigserial PRIMARY KEY,
+ run_id uuid,
+ ts timestamptz DEFAULT now(),
+ service_key text NOT NULL,
+ resource text NOT NULL,
+ tool_name text,
+ name text,
+ network text,
+ price_atomic bigint,
+ price_label text,
+ asset text,
+ available boolean NOT NULL DEFAULT true,
+ prev_price_atomic bigint,
+ pct_change numeric(10,2)
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_service_price_history_key_ts ON x402_service_price_history (service_key, ts DESC)`;
+
+ // Latest snapshot per tracked service + the derived alert state. This is the
+ // row the report endpoint and cost-model review read.
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_service_price_current (
+ service_key text PRIMARY KEY,
+ resource text NOT NULL,
+ tool_name text,
+ name text,
+ network text,
+ price_atomic bigint,
+ price_label text,
+ asset text,
+ available boolean NOT NULL DEFAULT true,
+ prev_price_atomic bigint,
+ pct_change numeric(10,2),
+ price_increase_alert boolean NOT NULL DEFAULT false,
+ price_drop_opportunity boolean NOT NULL DEFAULT false,
+ checks int NOT NULL DEFAULT 0,
+ first_seen timestamptz DEFAULT now(),
+ last_checked timestamptz DEFAULT now(),
+ run_id uuid
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_service_price_current_alert ON x402_service_price_current (price_increase_alert) WHERE price_increase_alert`;
+ // Shared autonomous-log value column (idempotent — other pipelines add it too).
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+// ── Tracked-service selection ────────────────────────────────────────────────
+// The services we depend on are exactly the live, priced resources the Bazaar
+// Discovery Warmup snapshots. Flatten the most recent snapshot per category into
+// a deduped set, then sort stalest-first (never-checked first) using the
+// last_checked timestamp from x402_service_price_current so coverage rotates.
+async function selectTrackedServices(limit) {
+ let catalogRows;
+ try {
+ catalogRows = await sql`
+ SELECT DISTINCT ON (category) category, resources
+ FROM x402_bazaar_catalog
+ ORDER BY category, ts DESC
+ `;
+ } catch (err) {
+ // Warmup hasn't run yet (table absent) — nothing to track this run.
+ if (/does not exist/i.test(err?.message || '')) return [];
+ throw err;
+ }
+
+ const byKey = new Map();
+ for (const row of catalogRows) {
+ const resources = Array.isArray(row.resources) ? row.resources : [];
+ for (const s of resources) {
+ if (!s || !s.resource) continue;
+ const key = s.key || (s.tool_name ? `${s.resource}#${s.tool_name}` : s.resource);
+ if (!byKey.has(key)) {
+ byKey.set(key, {
+ service_key: key,
+ resource: s.resource,
+ tool_name: s.tool_name || null,
+ networks: Array.isArray(s.networks) ? s.networks : [],
+ });
+ }
+ }
+ }
+ if (byKey.size === 0) return [];
+
+ // Pull last_checked for everything we've already tracked so we can prioritise
+ // the stalest. Unknown (never-tracked) services sort first (null last_checked).
+ const lastChecked = new Map();
+ try {
+ const rows = await sql`SELECT service_key, last_checked FROM x402_service_price_current`;
+ for (const r of rows) lastChecked.set(r.service_key, r.last_checked);
+ } catch { /* table may not exist on a cold first run — treat all as never-checked */ }
+
+ return [...byKey.values()]
+ .sort((a, b) => {
+ const ta = lastChecked.get(a.service_key);
+ const tb = lastChecked.get(b.service_key);
+ if (!ta && tb) return -1;
+ if (ta && !tb) return 1;
+ if (!ta && !tb) return 0;
+ return new Date(ta).getTime() - new Date(tb).getTime();
+ })
+ .slice(0, limit);
+}
+
+// ── bazaar_service_details call + parse ──────────────────────────────────────
+function detailsBody(resource, toolName, id) {
+ return {
+ jsonrpc: '2.0',
+ id,
+ method: 'tools/call',
+ params: {
+ name: 'bazaar_service_details',
+ arguments: { resource_url: resource, ...(toolName ? { tool_name: toolName } : {}) },
+ },
+ };
+}
+
+// Pull the bazaar_service_details structuredContent out of a JSON-RPC response.
+export function extractDetails(responseBody) {
+ const rpcError = responseBody?.error || responseBody?.result?.isError || null;
+ const sc = responseBody?.result?.structuredContent;
+ if (!sc || typeof sc !== 'object') return { details: null, rpcError };
+ return { details: sc, rpcError };
+}
+
+// Derive a comparable price record from the details payload. The tracked figure
+// is the cheapest price across all networks (min_price_atomic) — that's the
+// number a cost model uses and the one a hike/drop is measured against.
+export function priceRecordFromDetails(details, fallback) {
+ const available = details?.available !== false;
+ const prices = Array.isArray(details?.prices) ? details.prices : [];
+ let minAtomic = details?.min_price_atomic != null ? Number(details.min_price_atomic) : null;
+ let minNetwork = null;
+ let minLabel = details?.min_price_label || null;
+ let asset = null;
+ // Resolve the network/asset that carries the cheapest price for context.
+ for (const p of prices) {
+ const a = p?.amount_atomic != null ? Number(p.amount_atomic) : null;
+ if (a == null || !Number.isFinite(a)) continue;
+ if (minAtomic == null || a < minAtomic) {
+ minAtomic = a;
+ minNetwork = p.network || null;
+ minLabel = p.price || minLabel;
+ asset = p.asset || null;
+ } else if (a === minAtomic && minNetwork == null) {
+ minNetwork = p.network || null;
+ asset = p.asset || asset;
+ }
+ }
+ return {
+ service_key: details?.service_key || fallback.service_key,
+ resource: details?.resource || fallback.resource,
+ tool_name: details?.tool_name || fallback.tool_name || null,
+ name: details?.name || null,
+ network: minNetwork,
+ price_atomic: Number.isFinite(minAtomic) ? minAtomic : null,
+ price_label: minLabel,
+ asset,
+ available,
+ };
+}
+
+// Percentage change of cur vs prev (cheapest atomic price). Null when there's no
+// comparable baseline (first observation, or either side unpriced/unavailable).
+export function pctChange(prev, cur) {
+ if (prev == null || cur == null || prev <= 0) return null;
+ return Number((((cur - prev) / prev) * 100).toFixed(2));
+}
+
+async function recordCall(runId, { serviceName, endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${serviceName}, ${endpointUrl},
+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${USDC_MINT()}, ${txSig || null},
+ ${responseData ? JSON.stringify(responseData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${'discovery'})
+ `;
+ } catch (err) {
+ log.warn('pricing_tracker_log_insert_failed', { message: err?.message });
+ }
+}
+
+// Persist one observation: append to history, upsert the current snapshot, and
+// return the derived change/alert state for the log row.
+async function persistObservation(runId, tracked, record) {
+ // Prior cheapest price for this service (the last current snapshot).
+ let prevAtomic = null;
+ try {
+ const [prev] = await sql`
+ SELECT price_atomic FROM x402_service_price_current WHERE service_key = ${record.service_key}
+ `;
+ prevAtomic = prev?.price_atomic != null ? Number(prev.price_atomic) : null;
+ } catch { /* table absent on cold start — no baseline */ }
+
+ const change = record.available ? pctChange(prevAtomic, record.price_atomic) : null;
+ const increaseAlert = change != null && change > INCREASE_ALERT_PCT;
+ const dropOpportunity = change != null && change <= -DROP_OPPORTUNITY_PCT;
+
+ await sql`
+ INSERT INTO x402_service_price_history
+ (run_id, service_key, resource, tool_name, name, network,
+ price_atomic, price_label, asset, available, prev_price_atomic, pct_change)
+ VALUES
+ (${runId}, ${record.service_key}, ${record.resource}, ${record.tool_name}, ${record.name},
+ ${record.network}, ${record.price_atomic}, ${record.price_label}, ${record.asset},
+ ${record.available}, ${prevAtomic}, ${change})
+ `;
+
+ await sql`
+ INSERT INTO x402_service_price_current
+ (service_key, resource, tool_name, name, network, price_atomic, price_label,
+ asset, available, prev_price_atomic, pct_change, price_increase_alert,
+ price_drop_opportunity, checks, first_seen, last_checked, run_id)
+ VALUES
+ (${record.service_key}, ${record.resource}, ${record.tool_name}, ${record.name},
+ ${record.network}, ${record.price_atomic}, ${record.price_label}, ${record.asset},
+ ${record.available}, ${prevAtomic}, ${change}, ${increaseAlert},
+ ${dropOpportunity}, ${1}, now(), now(), ${runId})
+ ON CONFLICT (service_key) DO UPDATE SET
+ resource = EXCLUDED.resource,
+ tool_name = EXCLUDED.tool_name,
+ name = COALESCE(EXCLUDED.name, x402_service_price_current.name),
+ network = EXCLUDED.network,
+ prev_price_atomic = x402_service_price_current.price_atomic,
+ price_atomic = EXCLUDED.price_atomic,
+ price_label = EXCLUDED.price_label,
+ asset = EXCLUDED.asset,
+ available = EXCLUDED.available,
+ pct_change = EXCLUDED.pct_change,
+ price_increase_alert = EXCLUDED.price_increase_alert,
+ price_drop_opportunity = EXCLUDED.price_drop_opportunity,
+ checks = x402_service_price_current.checks + 1,
+ last_checked = now(),
+ run_id = EXCLUDED.run_id
+ `;
+
+ return { prevAtomic, change, increaseAlert, dropOpportunity };
+}
+
+// Surface a price hike to ops: a log warning + a short-lived Redis flag the
+// status surface can poll. Best-effort — never throws into the loop.
+async function raisePriceAlert(redis, record, change) {
+ log.warn('x402_price_increase_alert', {
+ service_key: record.service_key,
+ resource: record.resource,
+ tool_name: record.tool_name,
+ price_atomic: record.price_atomic,
+ pct_change: change,
+ });
+ if (!redis) return;
+ try {
+ await redis.set(
+ `x402:price-alert:${record.service_key}`,
+ JSON.stringify({ price_atomic: record.price_atomic, pct_change: change, ts: Date.now() }),
+ { ex: 7 * 86400 },
+ );
+ } catch { /* non-fatal */ }
+}
+
+/**
+ * Run the tracker. Self-contained: reuses the loop's Solana context when given,
+ * else bootstraps its own so it can be invoked directly (manual test). Records
+ * its own per-call log rows, so it returns { recorded: true } and the loop skips
+ * its generic summary row.
+ *
+ * @param {object} [ctx] loop context: { runId, origin, buyer, conn, blockhash, mintInfo, redis, remainingCap }
+ * @returns {Promise<object>} loop-compatible outcome
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';
+ const endpointUrl = `${origin}/api/mcp-bazaar`;
+ const redis = ctx.redis || null;
+ const usdcMint = USDC_MINT();
+ let remainingCap = ctx.remainingCap ?? Number.POSITIVE_INFINITY;
+
+ const fail = (reason, extra = {}) => ({
+ ok: false, recorded: true, skipped: true, success: false,
+ amountAtomic: 0, txSig: null, note: reason, ...extra,
+ });
+
+ // ── Wallet pre-flight: exit gracefully (logged) if unconfigured ───────────
+ let buyer = ctx.buyer;
+ if (!buyer) {
+ try { buyer = loadSeedKeypair(); } catch (err) {
+ log.info('pricing_tracker_skipped', { reason: err.message });
+ return fail(err.message);
+ }
+ }
+
+ try {
+ await ensureSchema();
+ } catch (err) {
+ log.warn('pricing_tracker_schema_failed', { message: err?.message });
+ return fail(`schema_failed: ${err?.message}`);
+ }
+
+ let tracked;
+ try {
+ tracked = await selectTrackedServices(BATCH);
+ } catch (err) {
+ log.warn('pricing_tracker_select_failed', { message: err?.message });
+ return fail(`select_failed: ${err?.message}`);
+ }
+ if (!tracked.length) {
+ // Nothing discovered to track yet — the Bazaar Discovery Warmup populates
+ // x402_bazaar_catalog. Record a skip summary (loop adds the row).
+ return { ok: true, recorded: false, skipped: true, success: true, amountAtomic: 0, txSig: null, note: 'no_tracked_services' };
+ }
+
+ // ── Solana payment context (reuse the loop's, else build our own) ─────────
+ let conn = ctx.conn;
+ let blockhash = ctx.blockhash;
+ let mintInfo = ctx.mintInfo;
+ if (!conn || !blockhash || !mintInfo) {
+ try {
+ conn = conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ const [bh, mi] = await Promise.all([
+ blockhash ? Promise.resolve({ blockhash }) : conn.getLatestBlockhash('confirmed'),
+ mintInfo ? Promise.resolve(mintInfo) : getMint(conn, new PublicKey(usdcMint)),
+ ]);
+ blockhash = blockhash || bh.blockhash;
+ mintInfo = mintInfo || mi;
+ } catch (err) {
+ log.warn('pricing_tracker_solana_preflight_failed', { message: err?.message });
+ return fail(`solana_preflight_failed: ${err?.message}`);
+ }
+ }
+
+ let spentAtomic = 0;
+ let paid = 0;
+ let checked = 0;
+ let alerts = 0;
+ let opportunities = 0;
+ let lastTxSig = null;
+ const summaries = [];
+
+ for (let i = 0; i < tracked.length; i++) {
+ if (remainingCap <= 0) {
+ log.info('pricing_tracker_cap_reached', { spent_atomic: spentAtomic });
+ break;
+ }
+ const t = tracked[i];
+ const serviceName = `Price Tracker: ${t.tool_name ? `${t.resource}#${t.tool_name}` : t.resource}`;
+ const t0 = Date.now();
+
+ let result;
+ try {
+ result = await payX402({
+ url: endpointUrl,
+ method: 'POST',
+ body: detailsBody(t.resource, t.tool_name, i + 1),
+ conn, buyer, blockhash, mintInfo,
+ remainingCap,
+ // Distinct priority fee per call so several same-amount payments on the
+ // one shared blockhash compile to distinct signatures.
+ nonce: i + 1,
+ });
+ } catch (err) {
+ await recordCall(runId, {
+ serviceName, endpointUrl, amountAtomic: 0, txSig: null,
+ responseData: { service_key: t.service_key },
+ durationMs: Date.now() - t0, success: false,
+ errorMsg: err?.message || 'fetch_failed', valueExtracted: null,
+ });
+ summaries.push({ service: t.service_key, error: err?.message || 'fetch_failed' });
+ continue;
+ }
+
+ const statusLabel = result.paid ? 'paid' : result.free ? 'free' : result.skipped ? 'skip' : 'error';
+ if (result.paid) {
+ spentAtomic += result.amountAtomic;
+ remainingCap -= result.amountAtomic;
+ paid += 1;
+ lastTxSig = result.txSig || lastTxSig;
+ }
+
+ const { details, rpcError } = extractDetails(result.responseBody);
+ let valueExtracted = null;
+ let errorMsg = result.errorMsg;
+
+ if (result.success && details) {
+ const record = priceRecordFromDetails(details, t);
+ let change = null, increaseAlert = false, dropOpportunity = false;
+ try {
+ ({ change, increaseAlert, dropOpportunity } = await persistObservation(runId, t, record));
+ checked += 1;
+ } catch (err) {
+ errorMsg = `db_persist_failed: ${err?.message}`;
+ log.warn('pricing_tracker_persist_failed', { service: t.service_key, message: err?.message });
+ }
+ if (increaseAlert) { alerts += 1; await raisePriceAlert(redis, record, change); }
+ if (dropOpportunity) opportunities += 1;
+
+ valueExtracted = {
+ service_key: record.service_key,
+ price_atomic: record.price_atomic,
+ price_label: record.price_label,
+ network: record.network,
+ available: record.available,
+ pct_change: change,
+ price_increase_alert: increaseAlert,
+ price_drop_opportunity: dropOpportunity,
+ };
+ summaries.push({ service: t.service_key, ...valueExtracted });
+ } else {
+ if (!errorMsg) errorMsg = rpcError ? 'rpc_error' : 'no_details_data';
+ summaries.push({ service: t.service_key, status: statusLabel, error: errorMsg });
+ }
+
+ await recordCall(runId, {
+ serviceName,
+ endpointUrl,
+ amountAtomic: result.amountAtomic,
+ txSig: result.txSig,
+ responseData: { service_key: t.service_key, status: statusLabel, rpc_error: result.responseBody?.error || null },
+ durationMs: Date.now() - t0,
+ success: result.success && !!details && !errorMsg,
+ errorMsg: result.success && details && !errorMsg ? null : errorMsg,
+ valueExtracted,
+ });
+ }
+
+ log.info('pricing_tracker_complete', {
+ run_id: runId,
+ tracked: tracked.length,
+ checked,
+ paid,
+ alerts,
+ opportunities,
+ spent_usdc: (spentAtomic / 1e6).toFixed(4),
+ });
+
+ return {
+ ok: true,
+ recorded: true,
+ skipped: false,
+ success: checked > 0 || paid > 0,
+ amountAtomic: spentAtomic,
+ txSig: lastTxSig,
+ signalData: { tracked: tracked.length, checked, paid, alerts, opportunities },
+ note: `priced ${checked}/${tracked.length} (alerts=${alerts}, drops=${opportunities})`,
+ checked,
+ paid,
+ summaries,
+ };
+}
+
+// ── Report reader (consumed by GET /api/x402/service-pricing-report) ──────────
+// Aggregates the current tracked-price snapshot into the cost-model dashboard
+// shape: every tracked service, the active increase alerts, and the drop
+// opportunities. Returns an empty-but-ok shape when the tracker has never run.
+export async function readPricingReport({ limit = 200 } = {}) {
+ const cap = Math.min(Math.max(Number(limit) || 200, 1), 500);
+ let rows = [];
+ try {
+ rows = await sql`
+ SELECT service_key, resource, tool_name, name, network, price_atomic,
+ price_label, asset, available, prev_price_atomic, pct_change,
+ price_increase_alert, price_drop_opportunity, checks,
+ first_seen, last_checked
+ FROM x402_service_price_current
+ ORDER BY last_checked DESC
+ LIMIT ${cap}
+ `;
+ } catch (err) {
+ if (/does not exist/i.test(err?.message || '')) {
+ return { tracked_count: 0, alert_count: 0, opportunity_count: 0, unavailable_count: 0, services: [], alerts: [], opportunities: [] };
+ }
+ throw err;
+ }
+
+ const services = rows.map((r) => ({
+ service_key: r.service_key,
+ resource: r.resource,
+ tool_name: r.tool_name || null,
+ name: r.name || null,
+ network: r.network || null,
+ price_atomic: r.price_atomic != null ? Number(r.price_atomic) : null,
+ price_usdc: r.price_atomic != null ? Number(r.price_atomic) / 1e6 : null,
+ price_label: r.price_label || null,
+ asset: r.asset || null,
+ available: r.available,
+ prev_price_atomic: r.prev_price_atomic != null ? Number(r.prev_price_atomic) : null,
+ pct_change: r.pct_change != null ? Number(r.pct_change) : null,
+ price_increase_alert: r.price_increase_alert,
+ price_drop_opportunity: r.price_drop_opportunity,
+ checks: Number(r.checks || 0),
+ first_seen: r.first_seen,
+ last_checked: r.last_checked,
+ }));
+
+ return {
+ tracked_count: services.length,
+ alert_count: services.filter((s) => s.price_increase_alert).length,
+ opportunity_count: services.filter((s) => s.price_drop_opportunity).length,
+ unavailable_count: services.filter((s) => !s.available).length,
+ services,
+ alerts: services.filter((s) => s.price_increase_alert),
+ opportunities: services.filter((s) => s.price_drop_opportunity),
+ thresholds: { increase_alert_pct: INCREASE_ALERT_PCT, drop_opportunity_pct: DROP_OPPORTUNITY_PCT },
+ };
+}
diff --git a/api/_mcpbazaar/tools.js b/api/_mcpbazaar/tools.js
index 220bb6497..14204a336 100644
--- a/api/_mcpbazaar/tools.js
+++ b/api/_mcpbazaar/tools.js
@@ -222,4 +222,76 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'bazaar_service_details',
+ title: 'Live price details for one x402 service',
+ annotations: DISCOVERY_ANNOTATIONS,
+ description:
+ "Resolve the current live price of a single x402 service by its resource URL (and tool_name for MCP services). Returns the cheapest price across networks plus a per-network breakdown (amount in atomic units, asset, recipient) and whether the service is still listed and payable. Purpose-built for price tracking and cost-model maintenance — call it on a schedule to watch a dependency's price over time and detect hikes or drops. Use get_service instead when you also need the input/output schema and a ready pay link.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ resource_url: { type: 'string', format: 'uri', description: 'The service resource URL.' },
+ tool_name: { type: 'string', description: 'For MCP services, the tool name on that resource.' },
+ },
+ required: ['resource_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(auth);
+ const baz = new Bazaar({});
+ const item = await baz.get(args.resource_url, { toolName: args.tool_name });
+ const service_key = args.tool_name ? `${args.resource_url}#${args.tool_name}` : args.resource_url;
+
+ // A service that has dropped off every facilitator is itself a tracking
+ // signal (a dependency went away / was unpriced) — return available:false
+ // with a stable shape rather than an error so the tracker records the gap.
+ if (!item) {
+ return {
+ content: [
+ { type: 'text', text: `x402 service ${service_key} is not currently listed on any facilitator.` },
+ ],
+ structuredContent: {
+ service_key,
+ resource: args.resource_url,
+ tool_name: args.tool_name || undefined,
+ available: false,
+ networks: [],
+ prices: [],
+ min_price_atomic: null,
+ min_price_label: null,
+ },
+ };
+ }
+
+ const prices = item.accepts.map((a) => ({
+ network: a.network,
+ amount_atomic: a.amountAtomic ?? null,
+ price: a.priceLabel || null,
+ asset: a.asset || null,
+ pay_to: a.payTo || null,
+ scheme: a.scheme || null,
+ }));
+ const lines = [
+ `${item.serviceName || item.resource}`,
+ `Current price: ${item.minPriceLabel || 'see options'}`,
+ ...prices.map((p) => ` • ${p.price || `${p.amount_atomic} atomic`} on ${p.network}`),
+ ];
+ return {
+ content: [{ type: 'text', text: lines.join('\n') }],
+ structuredContent: {
+ service_key,
+ type: item.type,
+ resource: item.resource,
+ tool_name: item.toolName || undefined,
+ name: item.serviceName || undefined,
+ available: true,
+ networks: item.networks,
+ min_price_atomic: item.minPriceAtomic ?? null,
+ min_price_label: item.minPriceLabel || undefined,
+ prices,
+ },
+ };
+ },
+ },
];
diff --git a/api/ops/health.js b/api/ops/health.js
index dab28dd8f..b2604eec6 100644
--- a/api/ops/health.js
+++ b/api/ops/health.js
@@ -158,6 +158,24 @@ export default wrap(async (req, res) => {
// A confirmed double-settlement means the x402 anti-replay guard is broken.
const idempotencyAudit = await loadIdempotencyAudit();
+ // API-key bypass security test — latest verdict written daily by the autonomous
+ // loop (api/_lib/x402/pipelines/api-key-bypass-audit.js). A confirmed leak means
+ // the X-API-Key bypass lane is granting free access to a missing/invalid key —
+ // paid endpoints can be drained for free.
+ const apiKeyBypassAudit = await loadApiKeyBypassAudit();
+
+ // Builder-code attribution — latest per-endpoint verdict written every 6h by the
+ // autonomous loop (api/_lib/x402/pipelines/builder-code-attribution.js). A gap
+ // (a priced endpoint that stopped declaring three_d_agent, or a failed attributed
+ // settlement) means on-chain volume is settling UNATTRIBUTED — lost builder rewards.
+ const builderAttribution = await loadBuilderAttribution();
+
+ // Spend-reservation leak rate — swept count written every 15 min by the
+ // autonomous loop (api/_lib/x402/pipelines/spend-reservation-leak-detector.js).
+ // A sustained rate of orphaned reservations means a reserve→finalize path is
+ // crashing and silently starving agent spend caps.
+ const reservationLeaks = await loadReservationLeaks();
+
// Categorize probe results
const byCategory = {};
for (const r of probeResults) {
@@ -177,7 +195,18 @@ export default wrap(async (req, res) => {
// A confirmed double-settlement (ok:false) degrades health; a never-run audit
// (ok:null) is unknown, not failing.
const idempotencyOk = idempotencyAudit.ok !== false;
- const overallOk = allProbesOk && allCronsOk && breakerOk && walletOk && idempotencyOk;
+ // An attribution gap (ok:false) degrades health — lost builder rewards; a
+ // never-run/stale tracker (ok:null) is unknown, not failing.
+ const attributionOk = builderAttribution.ok !== false;
+ // A confirmed bypass leak / broken bypass (ok:false) degrades health — the
+ // paywall is granting free access or rejecting valid keys; a never-run/stale
+ // audit (ok:null) is unknown, not failing.
+ const apiKeyBypassOk = apiKeyBypassAudit.ok !== false;
+ // A systemic reservation-leak rate (ok:false) degrades health — agent spend caps
+ // are being starved by orphaned reservations; a never-run/clean sweep (ok:null/
+ // ok:true) is fine.
+ const reservationLeaksOk = reservationLeaks.ok !== false;
+ const overallOk = allProbesOk && allCronsOk && breakerOk && walletOk && idempotencyOk && attributionOk && apiKeyBypassOk && reservationLeaksOk;
const failingProbes = probeResults.filter((r) => !r.ok);
const failingCrons = heartbeats.filter((h) => h.stale || h.ok === false);
@@ -199,9 +228,57 @@ export default wrap(async (req, res) => {
circuitBreaker,
walletBalance,
idempotencyAudit,
+ apiKeyBypassAudit,
+ builderAttribution,
+ reservationLeaks,
});
});
+// Read the latest builder-code attribution verdict written every 6h by the
+// autonomous loop (api/_lib/x402/pipelines/builder-code-attribution.js). ok:false
+// when a priced endpoint is currently missing/mismatched on its three_d_agent
+// declaration (a gap, so its settled volume earns no rewards) or the attributed
+// settlement proof failed. A stale or never-run tracker is unknown (ok:null) so
+// health doesn't trip on a cold or paused feature.
+const ATTRIBUTION_STALE_AFTER_MS = 8 * 60 * 60 * 1000; // 8h (6h cadence + slack)
+
+async function loadBuilderAttribution() {
+ try {
+ const rows = await sql`
+ SELECT endpoint, challenged, matches, gap, declared_code, expected_code,
+ settled, echo_accepted, tx_signature, error,
+ extract(epoch FROM checked_at) * 1000 AS checked_at_ms
+ FROM builder_code_attribution
+ ORDER BY checked_at DESC
+ `;
+ if (!rows.length) return { ok: null, reason: 'no_data' };
+ const now = Date.now();
+ const newest = Math.max(...rows.map((r) => Number(r.checked_at_ms) || 0));
+ const stale = !newest || now - newest > ATTRIBUTION_STALE_AFTER_MS;
+ const gaps = rows.filter((r) => r.gap);
+ // A settlement proof row (settled column true on the endpoint we pay) that
+ // flipped echo_accepted=false means an attributed payment failed to settle.
+ const settleRow = rows.find((r) => r.settled || /dance-tip/.test(r.endpoint));
+ const settleFailed = settleRow ? settleRow.settled && settleRow.echo_accepted === false : false;
+ const ok = stale ? null : gaps.length === 0 && !settleFailed;
+ return {
+ ok,
+ expectedCode: rows[0]?.expected_code || null,
+ endpointsChallenged: rows.filter((r) => r.challenged).length,
+ attributed: rows.filter((r) => r.matches).length,
+ gaps: gaps.map((g) => ({ endpoint: g.endpoint, declaredCode: g.declared_code, error: g.error })),
+ settleTx: settleRow?.tx_signature || null,
+ lastChecked: newest || null,
+ stale,
+ };
+ } catch (err) {
+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {
+ return { ok: null, reason: 'table_absent' };
+ }
+ return { ok: null, reason: `query_failed:${err?.message || 'unknown'}` };
+ }
+}
+
// Read the latest payment-proof idempotency audit verdict written daily by the
// autonomous loop (api/_lib/x402/pipelines/payment-proof-idempotency-audit.js).
// ok:false ONLY on a confirmed double-settlement (the anti-replay guard failed);
@@ -247,6 +324,54 @@ async function loadIdempotencyAudit() {
}
}
+// Read the latest API-key bypass security-test verdict written daily by the
+// autonomous loop (api/_lib/x402/pipelines/api-key-bypass-audit.js). ok:false ONLY
+// on a confirmed bypass leak (free access granted to a missing/invalid key) or a
+// broken bypass (valid keys rejected); a stale, never-run, or inconclusive audit
+// is unknown (ok:null), not failing, so health doesn't trip on a cold/paused feature.
+const API_KEY_BYPASS_STALE_AFTER_MS = 48 * 60 * 60 * 1000; // 48h (daily cadence + slack)
+
+async function loadApiKeyBypassAudit() {
+ try {
+ const [row] = await sql`
+ SELECT route, verdict, pass, leak, leaks, valid_key_source,
+ paid_settled, amount_atomic,
+ extract(epoch FROM ts) * 1000 AS checked_at_ms
+ FROM x402_api_key_bypass_audit
+ ORDER BY ts DESC
+ LIMIT 1
+ `;
+ if (!row) return { ok: null, reason: 'no_data' };
+ const checkedAt = row.checked_at_ms ? Number(row.checked_at_ms) : null;
+ const stale = checkedAt === null || Date.now() - checkedAt > API_KEY_BYPASS_STALE_AFTER_MS;
+ // A confirmed leak or broken bypass fails health. A stale/inconclusive audit
+ // is unknown (loop paused, or a valid key couldn't be acquired) → ok:null.
+ const ok =
+ row.verdict === 'bypass_leak' || row.verdict === 'bypass_broken'
+ ? false
+ : stale || row.verdict === 'inconclusive'
+ ? null
+ : true;
+ return {
+ ok,
+ verdict: row.verdict,
+ pass: row.pass,
+ leak: row.leak,
+ leaks: row.leaks,
+ route: row.route,
+ validKeySource: row.valid_key_source,
+ paidSettled: row.paid_settled,
+ lastChecked: checkedAt,
+ stale,
+ };
+ } catch (err) {
+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {
+ return { ok: null, reason: 'table_absent' };
+ }
+ return { ok: null, reason: `query_failed:${err?.message || 'unknown'}` };
+ }
+}
+
// Read the latest agent-wallet balance sample written every 10 min by the
// autonomous loop (api/_lib/x402/wallet-balance-monitor.js). A sample older than
// the staleness window means the monitor stopped writing; ok:null when it has
@@ -290,6 +415,53 @@ async function loadWalletBalance() {
}
}
+// Read the spend-reservation leak rate written every 15 min by the autonomous
+// loop (api/_lib/x402/pipelines/spend-reservation-leak-detector.js). A reservation
+// claims agent spend-cap headroom that a crash between reserve and finalize/release
+// can orphan; the detector sweeps and frees them. A few swept leaks is normal noise
+// (an occasional crashed request), but a SUSTAINED rate means a reserve→finalize
+// path is breaking and silently starving agent spend caps — that degrades health.
+// Never-run / table-absent → ok:null so health doesn't fail on a cold feature.
+const LEAK_WINDOW_MS = 60 * 60 * 1000; // count leaks swept in the last hour
+// At/above this many leaks swept in the window, treat it as a systemic leak.
+const LEAK_DEGRADE_THRESHOLD = Math.max(
+ 1,
+ Number(process.env.X402_RESERVATION_LEAK_HEALTH_THRESHOLD || 25),
+);
+
+async function loadReservationLeaks() {
+ try {
+ const [row] = await sql`
+ SELECT count(*)::int AS swept_recent,
+ coalesce(sum(usd), 0)::float8 AS usd_freed,
+ coalesce(sum(sol_amount), 0)::float8 AS sol_freed,
+ count(DISTINCT agent_id)::int AS agents_affected,
+ extract(epoch FROM max(swept_at)) * 1000 AS last_swept_ms
+ FROM spend_reservation_leaks
+ WHERE swept_at > now() - ${`${Math.round(LEAK_WINDOW_MS / 1000)} seconds`}::interval
+ `;
+ const sweptRecent = Number(row?.swept_recent || 0);
+ const lastSwept = row?.last_swept_ms ? Number(row.last_swept_ms) : null;
+ // Below threshold (including zero) is healthy; at/above is a systemic leak.
+ const ok = sweptRecent >= LEAK_DEGRADE_THRESHOLD ? false : true;
+ return {
+ ok,
+ sweptRecent,
+ windowHours: Math.round(LEAK_WINDOW_MS / 3600000),
+ threshold: LEAK_DEGRADE_THRESHOLD,
+ usdFreed: Number(row?.usd_freed || 0),
+ solFreed: Number(row?.sol_freed || 0),
+ agentsAffected: Number(row?.agents_affected || 0),
+ lastSwept,
+ };
+ } catch (err) {
+ if (/does not exist|relation .* does not exist/i.test(err?.message || '')) {
+ return { ok: null, reason: 'table_absent' };
+ }
+ return { ok: null, reason: `query_failed:${err?.message || 'unknown'}` };
+ }
+}
+
// Read the latest per-network circuit-breaker snapshot. The hourly breaker
// upserts one row per network into x402_circuit_breaker; a row older than the
// staleness window means the loop stopped writing. Returns ok:null when the
diff --git a/api/x402/admin/subscriptions.js b/api/x402/admin/subscriptions.js
index 22ba54c58..50c7d990c 100644
--- a/api/x402/admin/subscriptions.js
+++ b/api/x402/admin/subscriptions.js
@@ -10,8 +10,23 @@ import { cors, json, error, method, readJson, wrap } from '../../_lib/http.js';
import { requireAdmin } from '../../_lib/admin.js';
import { parse } from '../../_lib/validate.js';
import { logAudit } from '../../_lib/audit.js';
+import { constantTimeEquals } from '../../_lib/crypto.js';
import { createSubscription, listSubscriptions } from '../../_lib/x402/api-keys.js';
+// Internal-service read access. Server-side jobs (the x402 autonomous loop's
+// Subscription Status Health Check) enumerate subscriptions over HTTP with the
+// shared INTERNAL_API_KEY rather than a browser session. The bypass is GET-only
+// (read), constant-time compared, and never grants the mutating POST path —
+// issuing a key still requires a real admin session. Returns false (no bypass)
+// when the header is absent or the key is unconfigured, so the requireAdmin gate
+// always runs for ordinary callers.
+function isInternalServiceRequest(req) {
+ const provided = req.headers['x-api-key'] || req.headers['X-API-Key'];
+ const expected = process.env.INTERNAL_API_KEY;
+ if (!provided || !expected) return false;
+ return constantTimeEquals(String(provided), String(expected));
+}
+
const createSchema = z.object({
name: z.string().trim().min(1).max(120),
rate_limit_per_minute: z.number().int().min(1).max(100_000).optional().default(60),
@@ -28,6 +43,14 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
+ // Internal-service read bypass (GET only) — see isInternalServiceRequest.
+ if (req.method === 'GET' && isInternalServiceRequest(req)) {
+ const includeInactive =
+ req.query?.includeInactive === '1' || req.query?.includeInactive === 'true';
+ const rows = await listSubscriptions({ includeInactive });
+ return json(res, 200, { data: rows, caller: 'internal-service' });
+ }
+
const admin = await requireAdmin(req, res);
if (!admin) return;
diff --git a/api/x402/network-cost.js b/api/x402/network-cost.js
new file mode 100644
index 000000000..219f41759
--- /dev/null
+++ b/api/x402/network-cost.js
@@ -0,0 +1,114 @@
+// GET /api/x402/network-cost — Cross-Chain Payment Cost recommendation feed.
+//
+// Free operational read (parity with /api/x402-status): surfaces the live cost
+// of settling an identical $0.001 USDC payment on Solana vs Base, as measured by
+// the `cross-chain-cost-comparison` autonomous-loop entry
+// (api/_lib/x402/pipelines/cross-chain-cost.js). That loop hourly settles the
+// real Solana leg, reads its on-chain fee, prices the equivalent Base settlement
+// from the live Base gas price, and writes a snapshot to
+// cross_chain_cost_comparison. This endpoint is the downstream consumer: it
+// returns the latest snapshot, a rolling gas-premium average over the requested
+// window, and the recommended (cheapest) settlement network so the app can steer
+// users to the cheaper rail and inform default-network pricing.
+//
+// Query: ?window=<hours> (default 168, max 720) — the rolling stats window.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let windowHours = 168;
+ try {
+ const u = new URL(req.url, 'http://localhost');
+ const w = Number(u.searchParams.get('window'));
+ if (Number.isFinite(w) && w > 0) windowHours = Math.min(Math.max(w, 1), 720);
+ } catch { /* default window */ }
+
+ try {
+ const latestRows = await sql`
+ SELECT * FROM cross_chain_cost_comparison
+ ORDER BY checked_at DESC
+ LIMIT 1
+ `;
+ const latest = latestRows[0] || null;
+
+ const stats = await sql`
+ SELECT
+ count(*) AS samples,
+ avg(gas_premium_ratio) FILTER (WHERE gas_premium_ratio IS NOT NULL) AS avg_gas_premium_ratio,
+ avg(solana_gas_usd) FILTER (WHERE solana_gas_usd IS NOT NULL) AS avg_solana_gas_usd,
+ avg(base_gas_usd) FILTER (WHERE base_gas_usd IS NOT NULL) AS avg_base_gas_usd,
+ count(*) FILTER (WHERE cheapest_network = 'solana') AS solana_wins,
+ count(*) FILTER (WHERE cheapest_network = 'base') AS base_wins
+ FROM cross_chain_cost_comparison
+ WHERE checked_at >= now() - (${windowHours} || ' hours')::interval
+ `;
+ const s = stats[0] || {};
+
+ const num = (v) => (v == null ? null : Number(v));
+ const samples = Number(s.samples || 0);
+
+ // The recommendation: the latest snapshot's cheapest network is authoritative
+ // (it reflects current gas), backed by the window's win-count majority.
+ const recommended = latest?.cheapest_network
+ || (Number(s.base_wins || 0) > Number(s.solana_wins || 0) ? 'base' : 'solana');
+
+ return json(res, 200, {
+ ok: true,
+ recommended_network: samples > 0 ? recommended : null,
+ latest: latest
+ ? {
+ checked_at: latest.checked_at,
+ amount_usd: num(latest.amount_usd),
+ solana: {
+ advertised: latest.solana_advertised,
+ settled: latest.solana_settled,
+ gas_usd: num(latest.solana_gas_usd),
+ total_usd: num(latest.solana_total_usd),
+ fee_lamports: latest.solana_fee_lamports != null ? Number(latest.solana_fee_lamports) : null,
+ fee_source: latest.solana_fee_source,
+ tx: latest.solana_tx,
+ },
+ base: {
+ advertised: latest.base_advertised,
+ gas_usd: num(latest.base_gas_usd),
+ total_usd: num(latest.base_total_usd),
+ gas_price_gwei: latest.base_gas_price_wei != null ? Number(latest.base_gas_price_wei) / 1e9 : null,
+ gas_units: latest.base_gas_units != null ? Number(latest.base_gas_units) : null,
+ settled: false, // no autonomous EVM payer — gas is priced from live network data
+ },
+ gas_premium_ratio: num(latest.gas_premium_ratio),
+ cheapest_network: latest.cheapest_network,
+ sol_price_usd: num(latest.sol_price_usd),
+ eth_price_usd: num(latest.eth_price_usd),
+ }
+ : null,
+ window_hours: windowHours,
+ rolling: {
+ samples,
+ avg_gas_premium_ratio: num(s.avg_gas_premium_ratio),
+ avg_solana_gas_usd: num(s.avg_solana_gas_usd),
+ avg_base_gas_usd: num(s.avg_base_gas_usd),
+ solana_cheapest_count: Number(s.solana_wins || 0),
+ base_cheapest_count: Number(s.base_wins || 0),
+ },
+ generated_at: new Date().toISOString(),
+ });
+ } catch (err) {
+ // Table absent (loop never ran) or DB hiccup — report empty-but-ok so the
+ // dashboard shows "no data yet" instead of an error void.
+ const noData = /does not exist/i.test(err?.message || '');
+ return json(res, noData ? 200 : 503, {
+ ok: noData,
+ recommended_network: null,
+ latest: null,
+ rolling: { samples: 0 },
+ note: noData ? 'no_samples_yet' : undefined,
+ error: noData ? undefined : 'network_cost_read_failed',
+ generated_at: new Date().toISOString(),
+ });
+ }
+});
diff --git a/api/x402/service-pricing-report.js b/api/x402/service-pricing-report.js
new file mode 100644
index 000000000..f65a3afc3
--- /dev/null
+++ b/api/x402/service-pricing-report.js
@@ -0,0 +1,52 @@
+// GET /api/x402/service-pricing-report — x402 Service Pricing Tracker feed.
+//
+// Free operational read (parity with /api/x402/glb-optimization-report and
+// /api/x402/mcp-perf): surfaces what the `x402-pricing-tracker` autonomous-loop
+// entry (api/_lib/x402/autonomous-registry.js) has measured. That loop pays a
+// real $0.001 x402 call to /api/mcp-bazaar (bazaar_service_details) for the
+// stalest tracked external services every 6 hours and records each one's current
+// live cheapest price, the change vs the last check, and alert state into
+// x402_service_price_current. This endpoint is the downstream consumer: it
+// reports the full tracked catalog, the active price-increase alerts (cost-model
+// action items: a dependency raised its price > 20%), and the price-drop
+// opportunities (a dependency got cheaper — lean on it more).
+//
+// Query: ?limit=<n> (default 200, max 500) — cap on tracked services returned.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { readPricingReport } from '../_lib/x402/pipelines/x402-pricing-tracker.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let limit = 200;
+ try {
+ const u = new URL(req.url, 'http://localhost');
+ const n = Number(u.searchParams.get('limit'));
+ if (Number.isFinite(n) && n > 0) limit = Math.min(Math.max(n, 1), 500);
+ } catch { /* default limit */ }
+
+ try {
+ const report = await readPricingReport({ limit });
+ // 200 always — the dashboard renders the state itself; a non-2xx here would
+ // be indistinguishable from the endpoint being down.
+ return json(res, 200, { ...report, generated_at: new Date().toISOString() });
+ } catch (err) {
+ // Table absent (loop never ran) or DB hiccup — report empty-but-ok so the
+ // dashboard shows "no data yet" instead of an error void.
+ const noData = /does not exist/i.test(err?.message || '');
+ return json(res, noData ? 200 : 503, {
+ ok: noData,
+ tracked_count: 0,
+ alert_count: 0,
+ opportunity_count: 0,
+ unavailable_count: 0,
+ services: [],
+ alerts: [],
+ opportunities: [],
+ generated_at: new Date().toISOString(),
+ ...(noData ? {} : { error: 'pricing_report_unavailable' }),
+ });
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index e4df17a30..0244e509f 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,48 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-27",
+ "title": "Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit",
+ "summary": "When another agent pays a three.ws endpoint, the network can credit that volume back to three.ws as a builder reward — but only if the endpoint stamps its on-chain attribution code on the payment. If a single paid endpoint ever quietly drops that stamp, every dollar it settles still works for the buyer yet earns three.ws nothing, and until now nothing would have noticed. The platform now watches for exactly that. Every six hours an autonomous agent walks a representative set of paid endpoints and, for each, makes a free request to read its payment terms and confirm the attribution code is present and correct. Any endpoint missing or mismatching its code is flagged as a gap — real revenue at risk of going uncredited. The tracker then goes one step further and makes one real $0.001 payment to the cheapest endpoint with its own attribution stamp attached, confirming end-to-end that an attributed payment actually settles on-chain — the very transaction the reward program reads. The results feed the platform's internal health check, so operators are alerted to a lost-rewards gap within hours instead of discovering it when a payout comes up short. The whole sweep costs a fraction of a cent a day.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "API Key Bypass Security Test — the platform audits its own paywall for free-access leaks every day",
+ "summary": "Some callers are allowed to skip the per-call payment on three.ws's paid APIs: internal services and partners who hold a valid API key. That bypass is a trapdoor — if a code change ever widened it so a missing or wrong key also slipped through, anyone could drain the paid endpoints for free, and nobody would notice. The platform now watches that trapdoor continuously. Once a day an autonomous agent runs a full bypass drill against the live payment endpoints: it mints a real, short-lived partner key and confirms it grants free access exactly as intended; it presents a made-up invalid key and confirms access is denied; it knocks with no key at all and confirms the normal payment wall still appears; then it revokes its test key and confirms that very same key is now rejected. It runs the drill against two endpoints that share the bypass logic but invoke it differently, so a change that breaks one path can't hide behind the other. To close the loop it makes one real on-chain $0.001 payment through the no-key wall to prove that paying still works end to end. If the wall ever lets a missing or invalid key through, that's a free-access leak: the platform records it, raises a critical operations alert, and flags it on the internal health check so it can be shut immediately. The test key always self-expires within minutes and is revoked the moment the drill finishes, so the audit can never leave a live key behind.",
+ "tags": ["security", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "External Service Uptime Monitor — the platform checks every outside service is alive before it pays one",
+ "summary": "three.ws doesn't only get paid by other agents — it also pays outside x402 services for things like market data and intelligence. Those services live in a registry the platform builds automatically as it discovers them. If one quietly goes dark, a payment pipeline can waste a turn — or worse, start a payment — on a dead endpoint. The platform now guards against that. Every 15 minutes an autonomous agent walks the full list of external services it depends on and gives each a quick, free knock on the door: a lightweight request that asks 'are you there?' without ever sending money. A service that answers with a payment request is live and healthy; one that's reachable but answering oddly is flagged; one returning server errors or failing to respond at all is marked down. The platform tracks how many checks in a row each service has failed, and when something has been down long enough, paying pipelines automatically skip it instead of throwing good money at a dead address — then start using it again the moment it recovers. The whole sweep is free and never touches the payment wallet, and every check is logged so operations can see at a glance which outside services are up, which are flaky, and which have gone away.",
+ "tags": ["infra", "improvement"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Subscription Status Health Check — the platform warns API subscribers before their key expires",
+ "summary": "Partners and agents who pay for ongoing access to three.ws's paid APIs hold a subscription key that lets them skip the per-call payment until it expires or is revoked. When one of those keys quietly lapses, the integration on the other side suddenly starts getting charged per call or rejected outright — a surprise outage that looks like our fault. The platform now prevents that. Once a day an autonomous agent enumerates every active subscription, checks each one's status, and works out how many days are left before it expires. Any key inside its final week triggers a heads-up email to the subscriber — once per expiry window, so a renewal re-arms the warning rather than spamming — telling them exactly when access ends and how to renew before it does. Every subscription's current state (active, expiring soon, expired, or revoked) is recorded so the admin dashboard can badge keys that need attention and operations can catch a lapse before it interrupts anyone. The whole sweep is read-only and runs on the platform's own internal access, so it costs nothing and never touches the payment wallet.",
+ "tags": ["feature", "improvement"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Cross-Chain Payment Cost Comparison — the platform measures which network is cheaper to pay on, live",
+ "summary": "three.ws settles agent payments on both Solana and Base, and the cheaper rail isn't always obvious — gas prices move all day. The platform now measures it directly. Every hour an autonomous agent makes one real on-chain $0.001 USDC payment on Solana and reads the actual fee that transaction paid, then prices the exact same payment on Base from the live Base gas price and the real cost of a USDC transfer there. It converts both to dollars using live SOL and ETH prices, works out the all-in cost on each network, and tracks the gas premium between them over time — how many times more (or less) expensive Base is than Solana right now. The latest reading and a rolling average are published at /api/x402/network-cost, along with a clear recommendation of the cheaper network to settle on, so the platform can steer payments to the cheaper rail and keep default pricing honest. Each measurement settles on Solana with a real transaction signature and is logged like every other autonomous payment; the hourly pace keeps the cost to a few cents a day.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Sniper Intel Enrichment — the trading engine pays its own intelligence feed to sharpen every snipe",
+ "summary": "The platform's auto-sniper decides whether to buy a freshly launched coin in milliseconds, and it now pays for a better read before it commits. On a 15-minute cycle an autonomous agent takes the coins the sniper is actively watching — the ones it currently holds and the freshest high-conviction candidates — and, for each, makes one real on-chain x402 payment to the platform's own Crypto Intel feed for a live market signal: bullish, bearish, or neutral, with a confidence and a headline. That signal becomes a small, capped adjustment to the bar a coin must clear to get bought: a bearish read makes the sniper more cautious, a bullish read slightly more willing, and a neutral read changes nothing. It's the platform's most direct self-loop — the trading engine paying the platform's intelligence API to make better decisions, every payment settling on Solana with a real transaction signature. There's a built-in honesty guard: the intelligence feed only answers for coins it can actually price, so a brand-new memecoin with no real market simply returns no data and is never charged or given a borrowed signal. The adjustment is always small and fails open, so it can only ever nudge a decision — never block a trade on its own.",
+ "tags": ["feature", "infra"]
+ },
+ {
+ "date": "2026-06-27",
+ "title": "Rig Complexity Scorer — the platform pays to grade how heavy each avatar is to run",
+ "summary": "A 3D avatar that looks identical to another can be ten times heavier to render — more bones, more geometry, bigger textures — and that difference is invisible until it stutters on someone's phone. three.ws now measures it. An autonomous agent works through the avatars in the gallery, and for each one makes one real on-chain x402 payment to the platform's own model-inspection service to read the avatar's actual structure: bone count, vertex and triangle counts, texture sizes, and file weight. From those it computes a single 0-100 complexity score and a tier — light, standard, heavy, or extreme — plus a performance warning flag that trips when any one dimension (a half-million vertices, an 8K texture, a 75 MB file) is heavy enough to hurt on mobile. Each result is stored against the avatar so the marketplace can tier listing prices by how demanding a model is and show a 'performance-heavy' badge before a buyer commits. It only scores avatars it hasn't seen or that changed since the last check, so once the gallery is graded the ongoing cost falls to nearly nothing; every paid call settles on Solana with a real transaction signature and is logged like every other autonomous payment.",
+ "tags": ["feature", "infra"]
+ },
{
"date": "2026-06-27",
"title": "VRM 1.0 Compatibility Checker — the platform pays to tell you which avatars can upgrade",
diff --git a/public/changelog.json b/public/changelog.json
index 4fa645f3e..17a69c31f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:16:44.088Z",
+ "generated_at": "2026-06-27T23:37:46.077Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -150,6 +150,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "API Key Bypass Security Test — the platform audits its own paywall for free-access leaks every day",
+ "summary": "Some callers are allowed to skip the per-call payment on three.ws's paid APIs: internal services and partners who hold a valid API key. That bypass is a trapdoor — if a code change ever widened it so a missing or wrong key also slipped through, anyone could drain the paid endpoints for free, and nobody would notice. The platform now watches that trapdoor continuously. Once a day an autonomous agent runs a full bypass drill against the live payment endpoints: it mints a real, short-lived partner key and confirms it grants free access exactly as intended; it presents a made-up invalid key and confirms access is denied; it knocks with no key at all and confirms the normal payment wall still appears; then it revokes its test key and confirms that very same key is now rejected. It runs the drill against two endpoints that share the bypass logic but invoke it differently, so a change that breaks one path can't hide behind the other. To close the loop it makes one real on-chain $0.001 payment through the no-key wall to prove that paying still works end to end. If the wall ever lets a missing or invalid key through, that's a free-access leak: the platform records it, raises a critical operations alert, and flags it on the internal health check so it can be shut immediately. The test key always self-expires within minutes and is revoked the moment the drill finishes, so the audit can never leave a live key behind.",
+ "link": null,
+ "tags": [
+ "security",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -193,6 +204,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit",
+ "summary": "When another agent pays a three.ws endpoint, the network can credit that volume back to three.ws as a builder reward — but only if the endpoint stamps its on-chain attribution code on the payment. If a single paid endpoint ever quietly drops that stamp, every dollar it settles still works for the buyer yet earns three.ws nothing, and until now nothing would have noticed. The platform now watches for exactly that. Every six hours an autonomous agent walks a representative set of paid endpoints and, for each, makes a free request to read its payment terms and confirm the attribution code is present and correct. Any endpoint missing or mismatching its code is flagged as a gap — real revenue at risk of going uncredited. The tracker then goes one step further and makes one real $0.001 payment to the cheapest endpoint with its own attribution stamp attached, confirming end-to-end that an attributed payment actually settles on-chain — the very transaction the reward program reads. The results feed the platform's internal health check, so operators are alerted to a lost-rewards gap within hours instead of discovering it when a payout comes up short. The whole sweep costs a fraction of a cent a day.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -215,6 +237,17 @@
"security"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Cross-Chain Payment Cost Comparison — the platform measures which network is cheaper to pay on, live",
+ "summary": "three.ws settles agent payments on both Solana and Base, and the cheaper rail isn't always obvious — gas prices move all day. The platform now measures it directly. Every hour an autonomous agent makes one real on-chain $0.001 USDC payment on Solana and reads the actual fee that transaction paid, then prices the exact same payment on Base from the live Base gas price and the real cost of a USDC transfer there. It converts both to dollars using live SOL and ETH prices, works out the all-in cost on each network, and tracks the gas premium between them over time — how many times more (or less) expensive Base is than Solana right now. The latest reading and a rolling average are published at /api/x402/network-cost, along with a clear recommendation of the cheaper network to settle on, so the platform can steer payments to the cheaper rail and keep default pricing honest. Each measurement settles on Solana with a real transaction signature and is logged like every other autonomous payment; the hourly pace keeps the cost to a few cents a day.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -235,6 +268,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "External Service Uptime Monitor — the platform checks every outside service is alive before it pays one",
+ "summary": "three.ws doesn't only get paid by other agents — it also pays outside x402 services for things like market data and intelligence. Those services live in a registry the platform builds automatically as it discovers them. If one quietly goes dark, a payment pipeline can waste a turn — or worse, start a payment — on a dead endpoint. The platform now guards against that. Every 15 minutes an autonomous agent walks the full list of external services it depends on and gives each a quick, free knock on the door: a lightweight request that asks 'are you there?' without ever sending money. A service that answers with a payment request is live and healthy; one that's reachable but answering oddly is flagged; one returning server errors or failing to respond at all is marked down. The platform tracks how many checks in a row each service has failed, and when something has been down long enough, paying pipelines automatically skip it instead of throwing good money at a dead address — then start using it again the moment it recovers. The whole sweep is free and never touches the payment wallet, and every check is logged so operations can see at a glance which outside services are up, which are flaky, and which have gone away.",
+ "link": null,
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -516,6 +560,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Rig Complexity Scorer — the platform pays to grade how heavy each avatar is to run",
+ "summary": "A 3D avatar that looks identical to another can be ten times heavier to render — more bones, more geometry, bigger textures — and that difference is invisible until it stutters on someone's phone. three.ws now measures it. An autonomous agent works through the avatars in the gallery, and for each one makes one real on-chain x402 payment to the platform's own model-inspection service to read the avatar's actual structure: bone count, vertex and triangle counts, texture sizes, and file weight. From those it computes a single 0-100 complexity score and a tier — light, standard, heavy, or extreme — plus a performance warning flag that trips when any one dimension (a half-million vertices, an 8K texture, a 75 MB file) is heavy enough to hurt on mobile. Each result is stored against the avatar so the marketplace can tier listing prices by how demanding a model is and show a 'performance-heavy' badge before a buyer commits. It only scores avatars it hasn't seen or that changed since the last check, so once the gallery is graded the ongoing cost falls to nearly nothing; every paid call settles on Solana with a real transaction signature and is logged like every other autonomous payment.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -558,6 +613,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Sniper Intel Enrichment — the trading engine pays its own intelligence feed to sharpen every snipe",
+ "summary": "The platform's auto-sniper decides whether to buy a freshly launched coin in milliseconds, and it now pays for a better read before it commits. On a 15-minute cycle an autonomous agent takes the coins the sniper is actively watching — the ones it currently holds and the freshest high-conviction candidates — and, for each, makes one real on-chain x402 payment to the platform's own Crypto Intel feed for a live market signal: bullish, bearish, or neutral, with a confidence and a headline. That signal becomes a small, capped adjustment to the bar a coin must clear to get bought: a bearish read makes the sniper more cautious, a bullish read slightly more willing, and a neutral read changes nothing. It's the platform's most direct self-loop — the trading engine paying the platform's intelligence API to make better decisions, every payment settling on Solana with a real transaction signature. There's a built-in honesty guard: the intelligence feed only answers for coins it can actually price, so a brand-new memecoin with no real market simply returns no data and is never charged or given a borrowed signal. The adjustment is always small and fails open, so it can only ever nudge a decision — never block a trade on its own.",
+ "link": null,
+ "tags": [
+ "feature",
+ "infra"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
@@ -590,6 +656,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-27",
+ "type": "update",
+ "title": "Subscription Status Health Check — the platform warns API subscribers before their key expires",
+ "summary": "Partners and agents who pay for ongoing access to three.ws's paid APIs hold a subscription key that lets them skip the per-call payment until it expires or is revoked. When one of those keys quietly lapses, the integration on the other side suddenly starts getting charged per call or rejected outright — a surprise outage that looks like our fault. The platform now prevents that. Once a day an autonomous agent enumerates every active subscription, checks each one's status, and works out how many days are left before it expires. Any key inside its final week triggers a heads-up email to the subscriber — once per expiry window, so a renewal re-arms the warning rather than spamming — telling them exactly when access ends and how to renew before it does. Every subscription's current state (active, expiring soon, expired, or revoked) is recorded so the admin dashboard can badge keys that need attention and operations can catch a lapse before it interrupts anyone. The whole sweep is read-only and runs on the platform's own internal access, so it costs nothing and never touches the payment wallet.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-27",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ac8ac32f2..e877961a4 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -118,6 +118,14 @@
<category>feature</category>
<description>three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate.</description>
</item>
+ <item>
+ <title>API Key Bypass Security Test — the platform audits its own paywall for free-access leaks every day</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:API Key Bypass Security Test — the platform audits its own paywall for free-access leaks every day</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>Some callers are allowed to skip the per-call payment on three.ws's paid APIs: internal services and partners who hold a valid API key. That bypass is a trapdoor — if a code change ever widened it so a missing or wrong key also slipped through, anyone could drain the paid endpoints for free, and nobody would notice. The platform now watches that trapdoor continuously. Once a day an autonomous agent runs a full bypass drill against the live payment endpoints: it mints a real, short-lived partner key and confirms it grants free access exactly as intended; it presents a made-up invalid key and confirms access is denied; it knocks with no key at all and confirms the normal payment wall still appears; then it revokes its test key and confirms that very same key is now rejected. It runs the drill against two endpoints that share the bypass logic but invoke it differently, so a change that breaks one path can't hide behind the other. To close the loop it makes one real on-chain $0.001 payment through the no-key wall to prove that paying still works end to end. If the wall ever lets a missing or invalid key through, that's a free-access leak: the platform records it, raises a critical operations alert, and flags it on the internal health check so it can be shut immediately. The test key always self-expires within minutes and is revoked the moment the drill finishes, so the audit can never leave a live key behind.</description>
+ </item>
<item>
<title>Autonomous agent reputation refresh — trust scores that keep themselves current</title>
<link>https://three.ws/changelog</link>
@@ -150,6 +158,14 @@
<category>feature</category>
<description>The platform now runs a nightly optimization sweep across the 50 most-viewed public avatars. Each model is analyzed for geometry and texture inefficiencies — Draco/Meshopt compression opportunities, oversized textures ready for KTX2 transcoding, non-indexed primitives, and redundant materials. Results are stored per-avatar so we can surface actionable improvement suggestions to creators. The pipeline runs autonomously via the x402 agent spend loop, paying $0.001 USDC per nightly batch.</description>
</item>
+ <item>
+ <title>Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>When another agent pays a three.ws endpoint, the network can credit that volume back to three.ws as a builder reward — but only if the endpoint stamps its on-chain attribution code on the payment. If a single paid endpoint ever quietly drops that stamp, every dollar it settles still works for the buyer yet earns three.ws nothing, and until now nothing would have noticed. The platform now watches for exactly that. Every six hours an autonomous agent walks a representative set of paid endpoints and, for each, makes a free request to read its payment terms and confirm the attribution code is present and correct. Any endpoint missing or mismatching its code is flagged as a gap — real revenue at risk of going uncredited. The tracker then goes one step further and makes one real $0.001 payment to the cheapest endpoint with its own attribution stamp attached, confirming end-to-end that an attributed payment actually settles on-chain — the very transaction the reward program reads. The results feed the platform's internal health check, so operators are alerted to a lost-rewards gap within hours instead of discovering it when a payout comes up short. The whole sweep costs a fraction of a cent a day.</description>
+ </item>
<item>
<title>Capabilities dashboard — live command center for all 4 autonomous features</title>
<link>https://three.ws/dashboard/capabilities</link>
@@ -166,6 +182,14 @@
<category>improvement</category>
<description>Users who hit the sign-in rate limit (e.g. shared office/home network) now see a lightweight proof-of-work puzzle instead of a hard countdown. Solve it in a second or two and you can keep signing in immediately — no waiting, no support ticket. Built on Altcha (open source, MIT-licensed, no tracking or third-party service).</description>
</item>
+ <item>
+ <title>Cross-Chain Payment Cost Comparison — the platform measures which network is cheaper to pay on, live</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Cross-Chain Payment Cost Comparison — the platform measures which network is cheaper to pay on, live</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>three.ws settles agent payments on both Solana and Base, and the cheaper rail isn't always obvious — gas prices move all day. The platform now measures it directly. Every hour an autonomous agent makes one real on-chain $0.001 USDC payment on Solana and reads the actual fee that transaction paid, then prices the exact same payment on Base from the live Base gas price and the real cost of a USDC transfer there. It converts both to dollars using live SOL and ETH prices, works out the all-in cost on each network, and tracks the gas premium between them over time — how many times more (or less) expensive Base is than Solana right now. The latest reading and a rolling average are published at /api/x402/network-cost, along with a clear recommendation of the cheaper network to settle on, so the platform can steer payments to the cheaper rail and keep default pricing honest. Each measurement settles on Solana with a real transaction signature and is logged like every other autonomous payment; the hourly pace keeps the cost to a few cents a day.</description>
+ </item>
<item>
<title>Cross-Network Payment Circuit Breaker — hourly proof the payment stack is alive</title>
<link>https://three.ws/changelog</link>
@@ -182,6 +206,14 @@
<category>feature</category>
<description>Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu.</description>
</item>
+ <item>
+ <title>External Service Uptime Monitor — the platform checks every outside service is alive before it pays one</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:External Service Uptime Monitor — the platform checks every outside service is alive before it pays one</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>three.ws doesn't only get paid by other agents — it also pays outside x402 services for things like market data and intelligence. Those services live in a registry the platform builds automatically as it discovers them. If one quietly goes dark, a payment pipeline can waste a turn — or worse, start a payment — on a dead endpoint. The platform now guards against that. Every 15 minutes an autonomous agent walks the full list of external services it depends on and gives each a quick, free knock on the door: a lightweight request that asks 'are you there?' without ever sending money. A service that answers with a payment request is live and healthy; one that's reachable but answering oddly is flagged; one returning server errors or failing to respond at all is marked down. The platform tracks how many checks in a row each service has failed, and when something has been down long enough, paying pipelines automatically skip it instead of throwing good money at a dead address — then start using it again the moment it recovers. The whole sweep is free and never touches the payment wallet, and every check is logged so operations can see at a glance which outside services are up, which are flaky, and which have gone away.</description>
+ </item>
<item>
<title>Fixed /play getting stuck on &quot;too many requests&quot;</title>
<link>https://three.ws/play</link>
@@ -390,6 +422,14 @@
<category>feature</category>
<description>Every agent and skill review is now permanently anchored on Solana via a platform-signed SPL-Memo attestation (threews.review.v1) the moment it's submitted. The review's rating and a SHA-256 hash of the text go on-chain — tamper-evident, publicly verifiable on Solscan. These attestations feed directly into the agent reputation score's on-chain identity pillar, so a well-reviewed agent earns higher trust points automatically. Users with MetaMask connected can also add a second, user-signed anchor on Base via the ERC-8004 ReputationRegistry for cross-chain provenance — a one-click &quot;Anchor on Base&quot; step appears after submitting a review. Both layers together make every review a real, verifiable act — not just a database row.</description>
</item>
+ <item>
+ <title>Rig Complexity Scorer — the platform pays to grade how heavy each avatar is to run</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Rig Complexity Scorer — the platform pays to grade how heavy each avatar is to run</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A 3D avatar that looks identical to another can be ten times heavier to render — more bones, more geometry, bigger textures — and that difference is invisible until it stutters on someone's phone. three.ws now measures it. An autonomous agent works through the avatars in the gallery, and for each one makes one real on-chain x402 payment to the platform's own model-inspection service to read the avatar's actual structure: bone count, vertex and triangle counts, texture sizes, and file weight. From those it computes a single 0-100 complexity score and a tier — light, standard, heavy, or extreme — plus a performance warning flag that trips when any one dimension (a half-million vertices, an 8K texture, a 75 MB file) is heavy enough to hurt on mobile. Each result is stored against the avatar so the marketplace can tier listing prices by how demanding a model is and show a 'performance-heavy' badge before a buyer commits. It only scores avatars it hasn't seen or that changed since the last check, so once the gallery is graded the ongoing cost falls to nearly nothing; every paid call settles on Solana with a real transaction signature and is logged like every other autonomous payment.</description>
+ </item>
<item>
<title>Scene Capture auto-processing — upload a video, get a 3D point cloud back</title>
<link>https://three.ws/capture</link>
@@ -422,6 +462,14 @@
<category>fix</category>
<description>Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic.</description>
</item>
+ <item>
+ <title>Sniper Intel Enrichment — the trading engine pays its own intelligence feed to sharpen every snipe</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Sniper Intel Enrichment — the trading engine pays its own intelligence feed to sharpen every snipe</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The platform's auto-sniper decides whether to buy a freshly launched coin in milliseconds, and it now pays for a better read before it commits. On a 15-minute cycle an autonomous agent takes the coins the sniper is actively watching — the ones it currently holds and the freshest high-conviction candidates — and, for each, makes one real on-chain x402 payment to the platform's own Crypto Intel feed for a live market signal: bullish, bearish, or neutral, with a confidence and a headline. That signal becomes a small, capped adjustment to the bar a coin must clear to get bought: a bearish read makes the sniper more cautious, a bullish read slightly more willing, and a neutral read changes nothing. It's the platform's most direct self-loop — the trading engine paying the platform's intelligence API to make better decisions, every payment settling on Solana with a real transaction signature. There's a built-in honesty guard: the intelligence feed only answers for coins it can actually price, so a brand-new memecoin with no real market simply returns no data and is never charged or given a borrowed signal. The adjustment is always small and fails open, so it can only ever nudge a decision — never block a trade on its own.</description>
+ </item>
<item>
<title>Solana Agent Registration Health Check — the on-chain identity rails watch themselves</title>
<link>https://three.ws/changelog</link>
@@ -446,6 +494,14 @@
<category>feature</category>
<description>The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object.</description>
</item>
+ <item>
+ <title>Subscription Status Health Check — the platform warns API subscribers before their key expires</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-27:Subscription Status Health Check — the platform warns API subscribers before their key expires</guid>
+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Partners and agents who pay for ongoing access to three.ws's paid APIs hold a subscription key that lets them skip the per-call payment until it expires or is revoked. When one of those keys quietly lapses, the integration on the other side suddenly starts getting charged per call or rejected outright — a surprise outage that looks like our fault. The platform now prevents that. Once a day an autonomous agent enumerates every active subscription, checks each one's status, and works out how many days are left before it expires. Any key inside its final week triggers a heads-up email to the subscriber — once per expiry window, so a renewal re-arms the warning rather than spamming — telling them exactly when access ends and how to renew before it does. Every subscription's current state (active, expiring soon, expired, or revoked) is recorded so the admin dashboard can badge keys that need attention and operations can catch a lapse before it interrupts anyone. The whole sweep is read-only and runs on the platform's own internal access, so it costs nothing and never touches the payment wallet.</description>
+ </item>
<item>
<title>Task input on Agent Screen — send your agent a task and watch it work</title>
<link>https://three.ws/agent-screen</link>
diff --git a/public/features.json b/public/features.json
index 534e8f4cd..4472d9642 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-27T23:16:43.955Z",
+ "generated_at": "2026-06-27T23:37:46.063Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/test-cross-chain-cost.mjs b/scripts/test-cross-chain-cost.mjs
new file mode 100644
index 000000000..f5235c14f
--- /dev/null
+++ b/scripts/test-cross-chain-cost.mjs
@@ -0,0 +1,85 @@
+#!/usr/bin/env node
+// scripts/test-cross-chain-cost.mjs
+//
+// Manual exercise of the Cross-Chain Payment Cost Comparison pipeline
+// (api/_lib/x402/pipelines/cross-chain-cost.js).
+//
+// Runs the real run(ctx) against the configured origin. With a funded
+// X402_SEED/AGENT_SOLANA_SECRET_BASE58 it settles a real $0.001 USDC payment on
+// Solana, reads its on-chain fee, prices the equivalent Base settlement from the
+// live Base gas price + live SOL/ETH prices, persists a snapshot to
+// cross_chain_cost_comparison and prints the outcome the loop would log. Without
+// a wallet it exercises the graceful wallet-unconfigured path.
+//
+// Usage: node scripts/test-cross-chain-cost.mjs
+// Env: APP_ORIGIN (default https://three.ws), plus the loop's payment env.
+
+import { run } from '../api/_lib/x402/pipelines/cross-chain-cost.js';
+import { logger } from '../api/_lib/usage.js';
+
+const log = logger('test-cross-chain-cost');
+const origin = process.env.APP_ORIGIN || 'https://three.ws';
+
+// Capture DB writes without needing a live Postgres for a dry exercise: a tagged-
+// template stub that logs the snapshot it would persist. Set USE_REAL_DB=1 to
+// route through the real sql client instead and verify the row actually lands.
+let sql;
+if (process.env.USE_REAL_DB === '1') {
+ ({ sql } = await import('../api/_lib/db.js'));
+} else {
+ const captured = [];
+ sql = (strings, ...values) => {
+ const text = strings.join('?');
+ if (/INSERT INTO cross_chain_cost_comparison/i.test(text)) {
+ captured.push(values);
+ console.log('\n[db] would INSERT cross_chain_cost_comparison snapshot:');
+ console.log(' amount_atomic =', values[1]);
+ console.log(' solana_advertised =', values[2]);
+ console.log(' base_advertised =', values[3]);
+ console.log(' solana_settled =', values[4]);
+ console.log(' solana_fee_lamports =', values[6], '(', values[7], ')');
+ console.log(' solana_gas_usd =', values[8]);
+ console.log(' base_gas_price_wei =', values[9]);
+ console.log(' base_gas_usd =', values[11]);
+ console.log(' sol_price_usd =', values[12]);
+ console.log(' eth_price_usd =', values[13]);
+ console.log(' solana_total_usd =', values[15]);
+ console.log(' base_total_usd =', values[16]);
+ console.log(' gas_premium_ratio =', values[17]);
+ console.log(' cheapest_network =', values[18]);
+ }
+ return Promise.resolve([]);
+ };
+}
+
+// Solana payment context — only built when a payer keypair is configured.
+let buyer = null, conn = null, blockhash = null, mintInfo = null;
+try {
+ const { bootstrapSolanaContext } = await import('../api/_lib/x402/pay.js');
+ ({ buyer, conn, blockhash, mintInfo } = await bootstrapSolanaContext());
+ console.log('payer:', buyer.publicKey.toBase58());
+} catch (err) {
+ console.log('no payer configured (testing wallet-unconfigured path):', err?.message);
+}
+
+const ctx = {
+ origin, buyer, conn, blockhash, mintInfo,
+ remainingCap: 1_000_000, sql, log,
+ runId: '00000000-0000-0000-0000-0000000000ce',
+};
+
+console.log('\n→ running cross-chain-cost.run() against', origin, '…');
+const outcome = await run(ctx);
+
+console.log('\n=== outcome (what the loop records to x402_autonomous_log) ===');
+console.log(JSON.stringify({
+ success: outcome.success,
+ amountAtomic: outcome.amountAtomic,
+ txSig: outcome.txSig,
+ network: outcome.network,
+ errorMsg: outcome.errorMsg,
+ note: outcome.note,
+ signalData: outcome.signalData,
+}, null, 2));
+
+process.exit(0);
diff --git a/scripts/test-reservation-leak-detector.mjs b/scripts/test-reservation-leak-detector.mjs
new file mode 100644
index 000000000..7874dfb57
--- /dev/null
+++ b/scripts/test-reservation-leak-detector.mjs
@@ -0,0 +1,194 @@
+// Manual test for the Spend Reservation Leak Detector autonomous pipeline.
+//
+// Exercises run() directly. No payment is involved (the endpoint is free DB
+// maintenance), so nothing that would cost money in production is stubbed.
+//
+// node scripts/test-reservation-leak-detector.mjs
+//
+// Offline (no DATABASE_URL) it runs against a captured-SQL stub to verify the
+// control flow: schema DDL, the two leak scans, the clean-sweep summary, the
+// x402_autonomous_log row (with value_extracted), the Redis alert clear, and the
+// schema-failure error path — all without a database.
+//
+// With DATABASE_URL set it additionally seeds a REAL leaked USD reservation
+// (agent_custody_events, status 'pending') and a REAL leaked SOL reservation
+// (agent_actions, payload.status 'reserved'), both backdated past the leak window,
+// runs run(), and asserts each was released/deleted, a spend_reservation_leaks row
+// was written, and a summary row landed in x402_autonomous_log.
+
+import { randomUUID } from 'node:crypto';
+
+import {
+ run,
+ RESERVATION_LEAK_REDIS_ALERT_KEY,
+ RESERVATION_LEAK_REDIS_LATEST_KEY,
+ RESERVATION_LEAK_AGE_SECONDS,
+} from '../api/_lib/x402/pipelines/spend-reservation-leak-detector.js';
+
+let failures = 0;
+function check(label, cond, detail) {
+ const ok = !!cond;
+ if (!ok) failures++;
+ console.log(`${ok ? ' ✓' : ' ✗'} ${label}${detail ? ` — ${detail}` : ''}`);
+}
+
+// Captured-SQL stub. Answers the two leak scans from `custodyRows` / `solRows`,
+// everything else (DDL, INSERTs) resolves []. `failOn` rejects any statement whose
+// normalized text matches, to exercise error paths.
+function makeSqlStub({ custodyRows = [], solRows = [], failOn = null } = {}) {
+ const captured = [];
+ const sql = (strings, ...vals) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ captured.push({ text, vals });
+ if (failOn && failOn.test(text)) return Promise.reject(new Error('stub_db_down'));
+ if (/FROM agent_custody_events/i.test(text)) return Promise.resolve(custodyRows);
+ if (/FROM agent_actions/i.test(text)) return Promise.resolve(solRows);
+ return Promise.resolve([]);
+ };
+ return { sql, captured };
+}
+
+function makeRedisStub() {
+ const store = new Map();
+ const ops = [];
+ return {
+ store, ops,
+ set: async (k, v) => { ops.push(['set', k]); store.set(k, v); },
+ del: async (k) => { ops.push(['del', k]); store.delete(k); },
+ get: async (k) => store.get(k) ?? null,
+ };
+}
+
+async function main() {
+ console.log('\n1. Constants');
+ check('leak age default 3600s', RESERVATION_LEAK_AGE_SECONDS === 3600, String(RESERVATION_LEAK_AGE_SECONDS));
+ check('alert key', RESERVATION_LEAK_REDIS_ALERT_KEY === 'x402:reservation-leak:alert');
+
+ console.log('\n2. Clean sweep (no leaks) → success, log row, alert cleared');
+ {
+ const { sql, captured } = makeSqlStub();
+ const redis = makeRedisStub();
+ const out = await run({ sql, redis, runId: randomUUID() });
+ check('success true', out.success === true);
+ check('recorded true (own row)', out.recorded === true);
+ check('amountAtomic 0 (free)', out.amountAtomic === 0);
+ check('leaked_total 0', out.valueExtracted.leaked_total === 0);
+ check('note no leaks', out.note === 'no leaked reservations', out.note);
+ check('issued CREATE TABLE spend_reservation_leaks', captured.some((c) => /CREATE TABLE IF NOT EXISTS spend_reservation_leaks/i.test(c.text)));
+ check('ensured value_extracted column', captured.some((c) => /ADD COLUMN IF NOT EXISTS value_extracted/i.test(c.text)));
+ check('scanned agent_custody_events', captured.some((c) => /FROM agent_custody_events/i.test(c.text)));
+ check('scanned agent_actions', captured.some((c) => /FROM agent_actions/i.test(c.text)));
+ const logRow = captured.find((c) => /INSERT INTO x402_autonomous_log/i.test(c.text));
+ check('issued x402_autonomous_log INSERT', !!logRow);
+ check('log row success=true', logRow?.vals?.includes(true));
+ check('log row pipeline=finance', logRow?.vals?.includes('finance'));
+ check('log row value_extracted carries summary', (logRow?.vals || []).some((v) => typeof v === 'string' && /"leaked_total":0/.test(v)));
+ check('redis latest written', redis.store.has(RESERVATION_LEAK_REDIS_LATEST_KEY));
+ check('redis alert cleared (del)', redis.ops.some((o) => o[0] === 'del' && o[1] === RESERVATION_LEAK_REDIS_ALERT_KEY));
+ }
+
+ console.log('\n3. SOL leak found → recorded-then-released, alert raised');
+ {
+ // Only the SOL scan returns a leak (the SOL release path is internal to this
+ // module's flow via the real releaseSpend, but recordLeak runs through the
+ // stub; release of a captured-stub row is a no-op DELETE the stub resolves).
+ const solRows = [{
+ id: 4242, agent_id: 'agentSOL', type: 'pumpfun.buy',
+ sol_amount: 0.25, mint: 'THREEsynthetic1111', age_seconds: 7200,
+ created_at: new Date(Date.now() - 7200_000).toISOString(),
+ }];
+ const { sql, captured } = makeSqlStub({ solRows });
+ const redis = makeRedisStub();
+ const out = await run({ sql, redis, runId: randomUUID() });
+ check('success true', out.success === true);
+ check('leaked_total 1', out.valueExtracted.leaked_total === 1, String(out.valueExtracted.leaked_total));
+ check('sol_freed 0.25', out.valueExtracted.sol_freed === 0.25, String(out.valueExtracted.sol_freed));
+ check('agents_affected 1', out.valueExtracted.agents_affected === 1);
+ const leakInsert = captured.find((c) => /INSERT INTO spend_reservation_leaks/i.test(c.text));
+ check('recorded leak BEFORE delete', !!leakInsert);
+ check('leak row action=deleted', leakInsert?.vals?.includes('deleted'));
+ check('leak row source=agent_action', leakInsert?.vals?.includes('agent_action'));
+ check('note summarizes freed SOL', /0\.25 SOL/.test(out.note), out.note);
+ check('redis alert raised (set)', redis.store.has(RESERVATION_LEAK_REDIS_ALERT_KEY));
+ }
+
+ console.log('\n4. Schema DDL failure → graceful error outcome, no crash');
+ {
+ const { sql, captured } = makeSqlStub({ failOn: /CREATE TABLE IF NOT EXISTS spend_reservation_leaks/i });
+ const out = await run({ sql, redis: makeRedisStub(), runId: randomUUID() });
+ check('success false', out.success === false);
+ check('recorded true (still logged)', out.recorded === true);
+ check('errorMsg flags schema', /schema_failed/.test(out.errorMsg || ''), out.errorMsg);
+ check('attempted a log row anyway', captured.some((c) => /INSERT INTO x402_autonomous_log/i.test(c.text)));
+ }
+
+ console.log('\n5. A failing scan never crashes the tick (other source still runs)');
+ {
+ const { sql } = makeSqlStub({ failOn: /FROM agent_custody_events/i });
+ const out = await run({ sql, redis: makeRedisStub(), runId: randomUUID() });
+ check('success true (degraded, not crashed)', out.success === true);
+ check('leaked_total 0', out.valueExtracted.leaked_total === 0);
+ check('custody scanned 0 (failed source)', out.valueExtracted.scanned.custody_pending === 0);
+ }
+
+ // ── Optional real DB round-trip ────────────────────────────────────────────
+ if (process.env.DATABASE_URL || process.env.POSTGRES_URL || process.env.NEON_DATABASE_URL) {
+ console.log('\n6. real DB: seed leaks → run() → released + recorded');
+ const { sql } = await import('../api/_lib/db.js');
+ const runId = randomUUID();
+ const agentId = `leaktest-${runId.slice(0, 8)}`;
+ // Seed a leaked USD reservation: a pending spend backdated past the window.
+ const ageInterval = `${RESERVATION_LEAK_AGE_SECONDS + 600} seconds`;
+ const [custodyRow] = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, event_type, category, network, asset, usd, status, created_at)
+ VALUES (${agentId}, 'spend', 'x402', 'mainnet', 'USDC', 0.05, 'pending',
+ now() - ${ageInterval}::interval)
+ RETURNING id
+ `;
+ // Seed a leaked SOL reservation: a reserved action backdated past the window.
+ const [actionRow] = await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill, created_at)
+ VALUES (${agentId}, 'pumpfun.buy',
+ ${JSON.stringify({ solAmount: 0.1, mint: 'THREEsynthetic1111', status: 'reserved' })}::jsonb,
+ 'pumpfun', now() - ${ageInterval}::interval)
+ RETURNING id
+ `;
+
+ const out = await run({ sql, redis: null, runId });
+ check('run success', out.success === true);
+ check('swept ≥ 2', out.valueExtracted.leaked_total >= 2, String(out.valueExtracted.leaked_total));
+
+ const [cust] = await sql`SELECT status, reason FROM agent_custody_events WHERE id = ${custodyRow.id}`;
+ check('custody reservation released (failed)', cust?.status === 'failed', cust?.status);
+ check('release reason recorded', cust?.reason === 'leak_detector_swept', cust?.reason);
+
+ const act = await sql`SELECT id FROM agent_actions WHERE id = ${actionRow.id}`;
+ check('SOL reservation deleted', act.length === 0);
+
+ const leaks = await sql`SELECT source, action, usd, sol_amount FROM spend_reservation_leaks WHERE run_id = ${runId} ORDER BY source`;
+ check('two leak rows recorded', leaks.length === 2, JSON.stringify(leaks));
+ check('custody leak released', leaks.some((l) => l.source === 'custody_event' && l.action === 'released'));
+ check('sol leak deleted', leaks.some((l) => l.source === 'agent_action' && l.action === 'deleted'));
+
+ const logRows = await sql`SELECT success, pipeline, value_extracted FROM x402_autonomous_log WHERE run_id = ${runId}`;
+ check('log row persisted', logRows.length === 1, String(logRows.length));
+ check('log row value_extracted stored', logRows[0]?.value_extracted?.leaked_total >= 2);
+
+ // Cleanup so repeated runs stay clean.
+ await sql`DELETE FROM spend_reservation_leaks WHERE run_id = ${runId}`;
+ await sql`DELETE FROM x402_autonomous_log WHERE run_id = ${runId}`;
+ await sql`DELETE FROM agent_custody_events WHERE id = ${custodyRow.id}`;
+ console.log(' (seeded rows cleaned up)');
+ } else {
+ console.log('\n6. real DB round-trip skipped (no DATABASE_URL)');
+ }
+
+ console.log(`\n${failures === 0 ? 'PASS' : 'FAIL'} — ${failures} failed check(s)\n`);
+ process.exit(failures === 0 ? 0 : 1);
+}
+
+main().catch((err) => {
+ console.error('test crashed:', err);
+ process.exit(1);
+});
diff --git a/scripts/test-service-uptime-monitor.mjs b/scripts/test-service-uptime-monitor.mjs
new file mode 100644
index 000000000..9cce7c7cc
--- /dev/null
+++ b/scripts/test-service-uptime-monitor.mjs
@@ -0,0 +1,257 @@
+// Manual test for the External x402 Service Uptime Monitor autonomous pipeline.
+//
+// Exercises run() end-to-end against REAL local HTTP stubs that stand in for
+// external x402 services (one returns 402 = live paywall, one 5xx = down, one
+// HEAD-405-then-GET-402, and one unroutable port = timeout/unreachable), plus a
+// captured-SQL stub standing in for Postgres. Nothing the pipeline does in
+// production is mocked away — the probe is an UNPAID HEAD/OPTIONS/GET, so no
+// payment is ever involved. Verifies classification, the x402_service_uptime
+// upsert, a per-probe x402_autonomous_log row, the Redis dead/latest writes, the
+// consumer helpers (isServiceLive / classifyProbe), and every error path.
+//
+// node scripts/test-service-uptime-monitor.mjs
+//
+// With DATABASE_URL set it additionally probes a real stub, persists rows into
+// x402_service_uptime + x402_autonomous_log, and reads them back.
+
+import { createServer } from 'node:http';
+import { randomUUID } from 'node:crypto';
+
+import {
+ run,
+ probeService,
+ classifyProbe,
+ collectExternalTargets,
+ isServiceLive,
+ SERVICE_UPTIME,
+} from '../api/_lib/x402/pipelines/service-uptime-monitor.js';
+
+let failures = 0;
+function check(label, cond, detail) {
+ const ok = !!cond;
+ if (!ok) failures++;
+ console.log(`${ok ? ' ✓' : ' ✗'} ${label}${detail ? ` — ${detail}` : ''}`);
+}
+
+// SQL stub: captures statements; answers the bazaar-catalog SELECT from
+// `catalogRows`, the uptime upsert's RETURNING from a per-resource streak map,
+// and isServiceLive's SELECT from `uptimeRows`.
+function makeSqlStub({ catalogRows = [], uptimeRows = {} } = {}) {
+ const captured = [];
+ const streaks = new Map();
+ const sql = (strings, ...vals) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ captured.push({ text, vals });
+ if (/FROM x402_bazaar_catalog/i.test(text)) return Promise.resolve(catalogRows);
+ if (/INSERT INTO x402_service_uptime/i.test(text)) {
+ // vals[0] = resource, vals[3] = alive (per the INSERT column order)
+ const resource = vals[0];
+ const alive = vals[3];
+ const prev = streaks.get(resource) || 0;
+ const next = alive ? 0 : prev + 1;
+ streaks.set(resource, next);
+ return Promise.resolve([{ consecutive_failures: next }]);
+ }
+ if (/SELECT alive, consecutive_failures FROM x402_service_uptime/i.test(text)) {
+ const resource = vals[0];
+ const row = uptimeRows[resource];
+ return Promise.resolve(row ? [row] : []);
+ }
+ return Promise.resolve([]);
+ };
+ return { sql, captured, streaks };
+}
+
+function makeRedisStub() {
+ const store = new Map();
+ const ops = [];
+ let counter = 0;
+ return {
+ store, ops,
+ set: async (k, v) => { ops.push(['set', k]); store.set(k, v); },
+ del: async (k) => { ops.push(['del', k]); store.delete(k); },
+ incrby: async (k, n) => { counter += n; return counter; },
+ };
+}
+
+// One-route stub. `handler(method)` returns { status } for a given HTTP method,
+// letting a single server return 405 for HEAD but 402 for GET, etc.
+async function stubService(handler) {
+ const server = createServer((req, res) => {
+ const { status, body } = handler(req.method) || { status: 200 };
+ res.statusCode = status;
+ res.setHeader('content-type', 'application/json');
+ res.end(body ? JSON.stringify(body) : (req.method === 'HEAD' ? null : '{}'));
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address();
+ return { url: `http://127.0.0.1:${port}/svc`, close: () => new Promise((r) => server.close(r)) };
+}
+
+async function main() {
+ console.log('\n1. Constants + classification');
+ check('endpoint label', SERVICE_UPTIME.endpoint.includes('HEAD/OPTIONS'));
+ check('price 0 (free probe)', SERVICE_UPTIME.priceAtomic === 0);
+ check('402 → live_paywall', classifyProbe(402).classification === 'live_paywall' && classifyProbe(402).alive === true);
+ check('200 → live_free', classifyProbe(200).classification === 'live_free' && classifyProbe(200).alive === true);
+ check('503 → server_error (down)', classifyProbe(503).classification === 'server_error' && classifyProbe(503).alive === false);
+ check('404 → reachable_unexpected (up)', classifyProbe(404).classification === 'reachable_unexpected' && classifyProbe(404).alive === true);
+ check('null → unreachable (down)', classifyProbe(null, 'timeout').classification === 'unreachable' && classifyProbe(null).alive === false);
+
+ console.log('\n2. probeService — HEAD 402 (live x402 endpoint)');
+ {
+ const svc = await stubService(() => ({ status: 402, body: { accepts: [] } }));
+ const v = await probeService(svc.url);
+ await svc.close();
+ check('method HEAD', v.method === 'HEAD', v.method);
+ check('alive live_paywall', v.alive && v.classification === 'live_paywall');
+ check('latency recorded', Number.isFinite(v.latency_ms));
+ }
+
+ console.log('\n3. probeService — HEAD 405 falls back to GET 402');
+ {
+ const svc = await stubService((m) => (m === 'HEAD' ? { status: 405 } : { status: 402, body: { accepts: [] } }));
+ const v = await probeService(svc.url);
+ await svc.close();
+ check('fell back past HEAD', v.method !== 'HEAD', v.method);
+ check('verdict live_paywall', v.alive && v.classification === 'live_paywall');
+ }
+
+ console.log('\n4. probeService — 5xx is down');
+ {
+ const svc = await stubService(() => ({ status: 503 }));
+ const v = await probeService(svc.url);
+ await svc.close();
+ check('not alive', v.alive === false);
+ check('server_error', v.classification === 'server_error', v.classification);
+ }
+
+ console.log('\n5. probeService — unroutable host is unreachable');
+ {
+ const v = await probeService('http://127.0.0.1:1/svc');
+ check('not alive', v.alive === false);
+ check('unreachable', v.classification === 'unreachable', v.classification);
+ }
+
+ console.log('\n6. collectExternalTargets — catalog ∪ excludes own host');
+ {
+ const { sql } = makeSqlStub({
+ catalogRows: [
+ { category: 'trading', resources: [
+ { resource: 'https://ext-a.example/x402', tool_name: 'a', networks: ['solana'] },
+ { resource: 'https://three.ws/api/x402/dance-tip', tool_name: 'self', networks: ['solana'] }, // excluded
+ ] },
+ { category: 'llm', resources: [
+ { resource: 'https://ext-b.example/pay', tool_name: 'b', networks: ['base'] },
+ { resource: 'not-a-url', tool_name: 'bad' }, // excluded
+ ] },
+ ],
+ });
+ const targets = await collectExternalTargets({ sql, origin: 'https://three.ws' });
+ const urls = targets.map((t) => t.resource).sort();
+ check('two external targets', targets.length === 2, JSON.stringify(urls));
+ check('own host excluded', !urls.some((u) => u.includes('three.ws')));
+ check('non-url excluded', !urls.includes('not-a-url'));
+ }
+
+ console.log('\n7. run() — mixed live + down sweep records + stores');
+ {
+ const live = await stubService(() => ({ status: 402, body: { accepts: [] } }));
+ const dead = await stubService(() => ({ status: 500 }));
+ const { sql, captured } = makeSqlStub({
+ catalogRows: [
+ { category: 'trading', resources: [
+ { resource: live.url, tool_name: 'live', networks: ['solana'] },
+ { resource: dead.url, tool_name: 'dead', networks: ['solana'] },
+ ] },
+ ],
+ });
+ const redis = makeRedisStub();
+ const out = await run({ origin: 'https://three.ws', sql, redis, runId: randomUUID() });
+ await live.close(); await dead.close();
+
+ check('amountAtomic 0 (never pays)', out.amountAtomic === 0);
+ check('probed 2', out.responseData.probed === 2, String(out.responseData.probed));
+ check('alive 1', out.responseData.alive === 1, String(out.responseData.alive));
+ check('down 1', out.responseData.down === 1, String(out.responseData.down));
+ check('success true (not all down)', out.success === true);
+ check('errorMsg flags down', /services_down:1/.test(out.errorMsg || ''), out.errorMsg);
+ check('CREATE TABLE x402_service_uptime', captured.some((c) => /CREATE TABLE IF NOT EXISTS x402_service_uptime/i.test(c.text)));
+ check('upsert issued (2x)', captured.filter((c) => /INSERT INTO x402_service_uptime/i.test(c.text)).length === 2);
+ check('per-probe log rows (2x)', captured.filter((c) => /INSERT INTO x402_autonomous_log/i.test(c.text)).length === 2);
+ check('log pipeline=reliability', captured.some((c) => /INSERT INTO x402_autonomous_log/i.test(c.text) && c.vals.includes('reliability')));
+ check('redis dead list written', redis.store.has(SERVICE_UPTIME.redisDeadKey));
+ check('redis latest written', redis.store.has(SERVICE_UPTIME.redisLatestKey));
+ }
+
+ console.log('\n8. run() — no external services → graceful skip, no spend');
+ {
+ const { sql } = makeSqlStub({ catalogRows: [] });
+ const out = await run({ origin: 'https://three.ws', sql, redis: makeRedisStub() });
+ check('skipped', out.skipped === true);
+ check('note no_external_services', out.note === 'no_external_services', out.note);
+ check('amountAtomic 0', out.amountAtomic === 0);
+ }
+
+ console.log('\n9. isServiceLive — unknown allows, dead-beyond-threshold blocks');
+ {
+ const { sql } = makeSqlStub({
+ uptimeRows: {
+ 'https://up.example/x': { alive: true, consecutive_failures: 0 },
+ 'https://flap.example/x': { alive: false, consecutive_failures: 1 },
+ 'https://dead.example/x': { alive: false, consecutive_failures: 5 },
+ },
+ });
+ check('unknown → true', (await isServiceLive(sql, 'https://new.example/x')) === true);
+ check('alive → true', (await isServiceLive(sql, 'https://up.example/x')) === true);
+ check('one failure (< threshold) → true', (await isServiceLive(sql, 'https://flap.example/x')) === true);
+ check('hard-dead → false', (await isServiceLive(sql, 'https://dead.example/x')) === false);
+ }
+
+ console.log('\n10. DB upsert failure mid-run does not crash');
+ {
+ const live = await stubService(() => ({ status: 402, body: { accepts: [] } }));
+ const sql = (strings, ...vals) => {
+ const text = strings.join('?');
+ if (/FROM x402_bazaar_catalog/i.test(text)) return Promise.resolve([{ category: 't', resources: [{ resource: live.url, tool_name: 'l', networks: ['solana'] }] }]);
+ if (/INSERT INTO x402_service_uptime/i.test(text)) return Promise.reject(new Error('db down'));
+ return Promise.resolve([]);
+ };
+ const out = await run({ origin: 'https://three.ws', sql, redis: makeRedisStub() });
+ await live.close();
+ check('still resolves (no throw)', out.responseData.probed === 1);
+ check('probe still alive', out.responseData.alive === 1);
+ }
+
+ // Optional real DB round-trip.
+ if (process.env.DATABASE_URL || process.env.POSTGRES_URL) {
+ console.log('\n11. real DB upsert + read-back');
+ const live = await stubService(() => ({ status: 402, body: { accepts: [] } }));
+ const { sql } = await import('../api/_lib/db.js');
+ const runId = randomUUID();
+ // Seed the catalog with our stub so collectExternalTargets finds it.
+ await sql`CREATE TABLE IF NOT EXISTS x402_bazaar_catalog (id bigserial PRIMARY KEY, run_id uuid, ts timestamptz DEFAULT now(), category text, resources jsonb DEFAULT '[]'::jsonb)`;
+ await sql`INSERT INTO x402_bazaar_catalog (run_id, category, resources) VALUES (${runId}, ${'manual-test'}, ${JSON.stringify([{ resource: live.url, tool_name: 'live', networks: ['solana'] }])})`;
+ const out = await run({ origin: 'https://three.ws', sql, redis: null, runId });
+ await live.close();
+ const rows = await sql`SELECT alive, classification FROM x402_service_uptime WHERE resource = ${live.url}`;
+ check('uptime row persisted', rows.length === 1, JSON.stringify(rows[0]));
+ check('classified live_paywall', rows[0]?.classification === 'live_paywall');
+ const logRows = await sql`SELECT pipeline, amount_atomic FROM x402_autonomous_log WHERE run_id = ${runId} AND service_name LIKE 'Uptime:%'`;
+ check('autonomous_log row written', logRows.length >= 1);
+ check('amount 0 in log', Number(logRows[0]?.amount_atomic) === 0);
+ check('outcome alive', out.responseData.alive === 1);
+ // Cleanup the synthetic catalog row.
+ await sql`DELETE FROM x402_bazaar_catalog WHERE run_id = ${runId}`;
+ } else {
+ console.log('\n11. real DB round-trip skipped (no DATABASE_URL)');
+ }
+
+ console.log(`\n${failures === 0 ? 'PASS' : 'FAIL'} — ${failures} failed check(s)\n`);
+ process.exit(failures === 0 ? 0 : 1);
+}
+
+main().catch((err) => {
+ console.error('test crashed:', err);
+ process.exit(1);
+});
diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.js
index 75fd8924a..ad2695bc6 100644
--- a/tests/api/mcp-bazaar.test.js
+++ b/tests/api/mcp-bazaar.test.js
@@ -90,6 +90,7 @@ describe('x402 Bazaar MCP', () => {
'search_services',
'browse_services',
'get_service',
+ 'bazaar_service_details',
]);
});
@@ -148,6 +149,35 @@ describe('x402 Bazaar MCP', () => {
expect(r.result.isError).toBe(true);
});
+ it('bazaar_service_details returns the live cheapest price across networks', async () => {
+ bazState.get.mockResolvedValue(
+ item({
+ accepts: [
+ { network: 'eip155:8453', priceLabel: '$0.002', amountAtomic: 2000, asset: '0xUSDC', payTo: '0xR', scheme: 'exact' },
+ { network: 'solana:mainnet', priceLabel: '$0.001', amountAtomic: 1000, asset: 'SolUSDC', payTo: 'SoR', scheme: 'exact' },
+ ],
+ }),
+ );
+ const r = await call('bazaar_service_details', { resource_url: 'https://api.weather.test/now' });
+ const sc = r.result.structuredContent;
+ expect(sc.available).toBe(true);
+ expect(sc.service_key).toBe('https://api.weather.test/now');
+ expect(sc.min_price_atomic).toBe(1000);
+ expect(sc.prices).toHaveLength(2);
+ expect(sc.prices[1]).toMatchObject({ network: 'solana:mainnet', amount_atomic: 1000, price: '$0.001' });
+ });
+
+ it('bazaar_service_details reports an unlisted service as available:false (not an error)', async () => {
+ bazState.get.mockResolvedValue(null);
+ const r = await call('bazaar_service_details', { resource_url: 'https://gone.test', tool_name: 'x' });
+ const sc = r.result.structuredContent;
+ expect(r.result.isError).toBeUndefined();
+ expect(sc.available).toBe(false);
+ expect(sc.service_key).toBe('https://gone.test#x');
+ expect(sc.min_price_atomic).toBeNull();
+ expect(sc.prices).toEqual([]);
+ });
+
it('honors the rate limit', async () => {
rlState.bazaar = { success: false, reset: Date.now() + 30000 };
const r = await call('search_services', { query: 'weather' });
diff --git a/tests/x402-bazaar-catalog-refresh.test.js b/tests/x402-bazaar-catalog-refresh.test.js
new file mode 100644
index 000000000..e7cff65f5
--- /dev/null
+++ b/tests/x402-bazaar-catalog-refresh.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect } from 'vitest';
+
+import {
+ CATALOG_TYPES,
+ catalogHash,
+ diffCatalog,
+ BAZAAR_CATALOG_REFRESH,
+ run,
+} from '../api/_lib/x402/pipelines/bazaar-catalog-refresh.js';
+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';
+
+const mapOf = (...svcs) => new Map(svcs.map((s) => [s.key, s]));
+const svc = (over = {}) => ({
+ key: 'https://api.example.com/weather',
+ resource: 'https://api.example.com/weather',
+ tool_name: null,
+ name: 'Weather',
+ price_atomic: 1000,
+ networks: ['eip155:8453'],
+ ...over,
+});
+
+describe('bazaar catalog refresh — catalog hash', () => {
+ it('is stable regardless of service order', () => {
+ const a = catalogHash([svc({ key: 'a' }), svc({ key: 'b' })]);
+ const b = catalogHash([svc({ key: 'b' }), svc({ key: 'a' })]);
+ expect(a).toBe(b);
+ });
+
+ it('changes when a service is added or removed', () => {
+ const before = catalogHash([svc({ key: 'a' })]);
+ const after = catalogHash([svc({ key: 'a' }), svc({ key: 'b' })]);
+ expect(before).not.toBe(after);
+ });
+
+ it('changes on a reprice', () => {
+ const before = catalogHash([svc({ key: 'a', price_atomic: 1000 })]);
+ const after = catalogHash([svc({ key: 'a', price_atomic: 2000 })]);
+ expect(before).not.toBe(after);
+ });
+});
+
+describe('bazaar catalog refresh — day-over-day diff', () => {
+ it('detects added services (opportunity alerts)', () => {
+ const prev = mapOf(svc({ key: 'a', resource: 'a' }));
+ const today = mapOf(svc({ key: 'a', resource: 'a' }), svc({ key: 'b', resource: 'b' }));
+ const { added, removed, repriced } = diffCatalog(prev, today);
+ expect(added.map((s) => s.key)).toEqual(['b']);
+ expect(removed).toHaveLength(0);
+ expect(repriced).toHaveLength(0);
+ });
+
+ it('detects removed services (dependency alerts)', () => {
+ const prev = mapOf(svc({ key: 'a', resource: 'a' }), svc({ key: 'b', resource: 'b' }));
+ const today = mapOf(svc({ key: 'a', resource: 'a' }));
+ const { added, removed } = diffCatalog(prev, today);
+ expect(removed.map((s) => s.key)).toEqual(['b']);
+ expect(added).toHaveLength(0);
+ });
+
+ it('detects price changes', () => {
+ const prev = mapOf(svc({ key: 'a', resource: 'a', price_atomic: 1000 }));
+ const today = mapOf(svc({ key: 'a', resource: 'a', price_atomic: 2500 }));
+ const { repriced } = diffCatalog(prev, today);
+ expect(repriced).toEqual([
+ { key: 'a', resource: 'a', old_price_atomic: 1000, new_price_atomic: 2500 },
+ ]);
+ });
+
+ it('reports no change when the catalog is identical', () => {
+ const prev = mapOf(svc({ key: 'a', resource: 'a' }), svc({ key: 'b', resource: 'b' }));
+ const today = mapOf(svc({ key: 'a', resource: 'a' }), svc({ key: 'b', resource: 'b' }));
+ const { added, removed, repriced } = diffCatalog(prev, today);
+ expect(added).toHaveLength(0);
+ expect(removed).toHaveLength(0);
+ expect(repriced).toHaveLength(0);
+ });
+
+ it('treats null vs a concrete price as a reprice', () => {
+ const prev = mapOf(svc({ key: 'a', resource: 'a', price_atomic: null }));
+ const today = mapOf(svc({ key: 'a', resource: 'a', price_atomic: 1000 }));
+ expect(diffCatalog(prev, today).repriced).toHaveLength(1);
+ });
+});
+
+describe('bazaar catalog refresh — registry wiring', () => {
+ it('censuses both service kinds (http + mcp)', () => {
+ expect(CATALOG_TYPES).toEqual(['http', 'mcp']);
+ });
+
+ it('is registered as an enabled, daily, run()-style discovery entry', () => {
+ const entry = getFullRegistry().find((e) => e.id === 'bazaar-catalog-refresh');
+ expect(entry).toBeTruthy();
+ expect(entry.enabled).toBe(true);
+ expect(entry.pipeline).toBe('discovery');
+ expect(entry.cooldown_s).toBe(86400);
+ expect(entry.price_atomic).toBe(1000);
+ expect(entry.path).toBe('/api/mcp-bazaar');
+ expect(typeof entry.run).toBe('function');
+ });
+
+ it('exposes its constants (endpoint, price, cooldown)', () => {
+ expect(BAZAAR_CATALOG_REFRESH.endpoint).toBe('/api/mcp-bazaar');
+ expect(BAZAAR_CATALOG_REFRESH.priceAtomic).toBe(1000);
+ expect(BAZAAR_CATALOG_REFRESH.cooldownSeconds).toBe(86400);
+ expect(BAZAAR_CATALOG_REFRESH.enrichMax).toBeGreaterThan(0);
+ });
+});
+
+describe('bazaar catalog refresh — graceful degradation', () => {
+ it('never throws when the DB/wallet are unconfigured; returns a skipped outcome', async () => {
+ const out = await run({ runId: '00000000-0000-0000-0000-000000000009' });
+ expect(out).toMatchObject({ success: false, skipped: true });
+ expect(out.amountAtomic).toBe(0);
+ expect(typeof out.errorMsg).toBe('string');
+ });
+});
diff --git a/tests/x402-charity-split-audit.run.test.js b/tests/x402-charity-split-audit.run.test.js
new file mode 100644
index 000000000..c59397032
--- /dev/null
+++ b/tests/x402-charity-split-audit.run.test.js
@@ -0,0 +1,209 @@
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
+import http from 'node:http';
+import {
+ Keypair,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync,
+ createTransferCheckedInstruction,
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+// End-to-end orchestration test of the Charity Split Audit run(): the free
+// merchant-config sweep, the real production-checkout canary (prepare → sign →
+// encode → settle), and the on-chain verification of the charity leg — all
+// driven against a mock checkout/dance-tip server with the DB and the chain read
+// stubbed at their boundaries. No external services, no on-chain spend; the
+// transaction is really built and signed locally, exactly like circuit-breaker's
+// test, so this exercises the true code path end to end.
+
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const buyer = Keypair.generate();
+const payTo = Keypair.generate().publicKey;
+const feePayer = Keypair.generate().publicKey;
+const BASE = '1000'; // $0.001 USDC atomics
+const BPS = 500; // 5% → split = 50
+const SPLIT = 50;
+process.env.X402_CHARITY_AUDIT_BPS = String(BPS);
+// Canary cause wallet = the buyer (default self-route); split lands on buyer ATA.
+const charityAta = getAssociatedTokenAddressSync(new PublicKey(USDC), buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID).toBase58();
+const payToAta = getAssociatedTokenAddressSync(new PublicKey(USDC), payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID).toBase58();
+
+const DUMMY_BLOCKHASH = '4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi';
+const SETTLED_SIG = '5'.repeat(64);
+
+// ── Stub the DB at its boundary. Route by SQL text; record the audit rows. ──
+const auditRows = [];
+const logRows = [];
+let merchantRows = [];
+function fakeSql(strings, ...vals) {
+ const text = strings.join(' ');
+ if (text.includes('from x402_merchant_settings')) return Promise.resolve(merchantRows);
+ if (text.includes('INSERT INTO charity_split_audit')) {
+ // Column order mirrors recordAuditRow's VALUES list.
+ auditRows.push({ merchant_id: vals[1], kind: vals[2], config_valid: vals[8], broken_reason: vals[9], expected_split: vals[11], routed_split: vals[12], charity_routed: vals[13], tx: vals[14] });
+ return Promise.resolve([]);
+ }
+ if (text.includes('INSERT INTO x402_autonomous_log')) {
+ logRows.push({ service: vals[2], amount_atomic: vals[5], tx: vals[7], value_extracted: vals[9], success: vals[11], error: vals[12] });
+ return Promise.resolve([]);
+ }
+ return Promise.resolve([]); // CREATE TABLE / ALTER / INDEX
+}
+vi.mock('../api/_lib/db.js', () => ({ sql: (s, ...v) => fakeSql(s, ...v) }));
+
+// ── Mock checkout + dance-tip endpoints ──────────────────────────────────────
+function solanaAccept() {
+ return { scheme: 'exact', network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', asset: USDC, payTo: payTo.toBase58(), amount: BASE, maxTimeoutSeconds: 60, extra: { name: 'USDC', decimals: 6, feePayer: feePayer.toBase58() } };
+}
+
+// Build a real, signable v0 tx with the base + charity transfer legs — what the
+// production /api/x402-checkout prepare returns. buyer is the transfer authority,
+// so the pipeline's vtx.sign([buyer]) succeeds.
+function buildPreparedTx(tips) {
+ const mint = new PublicKey(USDC);
+ const senderAta = getAssociatedTokenAddressSync(mint, buyer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const ixs = [
+ createTransferCheckedInstruction(senderAta, mint, getAssociatedTokenAddressSync(mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID), buyer.publicKey, BigInt(BASE), 6, [], TOKEN_PROGRAM_ID),
+ ];
+ for (const t of tips || []) {
+ ixs.push(createTransferCheckedInstruction(senderAta, mint, getAssociatedTokenAddressSync(mint, new PublicKey(t.to), false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID), buyer.publicKey, BigInt(t.amount), 6, [], TOKEN_PROGRAM_ID));
+ }
+ const msg = new TransactionMessage({ payerKey: feePayer, recentBlockhash: DUMMY_BLOCKHASH, instructions: ixs }).compileToV0Message();
+ return Buffer.from(new VersionedTransaction(msg).serialize()).toString('base64');
+}
+
+let server, origin;
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const url = new URL(req.url, 'http://x');
+ let body = '';
+ req.on('data', (c) => (body += c));
+ req.on('end', () => {
+ const send = (code, obj, headers = {}) => { res.writeHead(code, { 'content-type': 'application/json', ...headers }); res.end(JSON.stringify(obj)); };
+ // dance-tip: 402 challenge, or 200 settled when carrying X-PAYMENT.
+ if (url.pathname === '/api/x402/dance-tip') {
+ if (req.headers['x-payment']) {
+ const xpr = Buffer.from(JSON.stringify({ transaction: SETTLED_SIG })).toString('base64');
+ return send(200, { ok: true, ticketId: 't1' }, { 'x-payment-response': xpr });
+ }
+ return send(402, { accepts: [solanaAccept()] });
+ }
+ // checkout prepare / encode.
+ if (url.pathname === '/api/x402-checkout') {
+ const action = url.searchParams.get('action');
+ const parsed = body ? JSON.parse(body) : {};
+ if (action === 'prepare') return send(200, { network: 'solana', tx_base64: buildPreparedTx(parsed.tips), recent_blockhash: DUMMY_BLOCKHASH });
+ if (action === 'encode') return send(200, { x_payment: Buffer.from('paymentpayload').toString('base64') });
+ }
+ send(404, { error: 'not_found' });
+ });
+ });
+ await new Promise((r) => server.listen(0, r));
+ origin = `http://127.0.0.1:${server.address().port}`;
+});
+afterAll(() => server?.close());
+
+// Fake Solana connection — only getParsedTransaction is used (ctx.conn supplied,
+// so bootstrap is skipped). Return the settled tx with both transfer legs.
+const fakeConn = {
+ getParsedTransaction: async () => ({
+ transaction: { message: { instructions: [
+ { program: 'spl-token', parsed: { type: 'transferChecked', info: { destination: payToAta, tokenAmount: { amount: BASE } } } },
+ { program: 'spl-token', parsed: { type: 'transferChecked', info: { destination: charityAta, tokenAmount: { amount: String(SPLIT) } } } },
+ ] } },
+ meta: { innerInstructions: [], err: null },
+ }),
+};
+
+const { run } = await import('../api/_lib/x402/pipelines/charity-split-audit.js');
+
+describe('charity-split-audit run() — full orchestration', () => {
+ it('sweeps configs, settles the canary, verifies the charity leg on-chain, and logs', async () => {
+ auditRows.length = 0; logRows.length = 0;
+ merchantRows = [
+ { owner_user_id: 'good', charity_name: 'Good Cause', charity_chain: 'solana', charity_address: Keypair.generate().publicKey.toBase58(), charity_bps: 250, payout_solana: Keypair.generate().publicKey.toBase58(), payout_evm: null },
+ { owner_user_id: 'broken', charity_name: 'Oops', charity_chain: 'solana', charity_address: null, charity_bps: 300, payout_solana: Keypair.generate().publicKey.toBase58(), payout_evm: null },
+ ];
+
+ const out = await run({ origin, buyer, conn: fakeConn, remainingCap: 1_000_000, runId: '00000000-0000-0000-0000-000000000001' });
+
+ // Loop-facing contract.
+ expect(out.success).toBe(true);
+ expect(out.amountAtomic).toBe(Number(BASE) + SPLIT); // base + split billed to the cap
+ expect(out.txSig).toBe(SETTLED_SIG);
+ expect(out.merchantsAudited).toBe(2);
+ expect(out.brokenCount).toBe(1);
+ expect(out.canary.charityRouted).toBe(true);
+ expect(out.signalData.canary_charity_routed).toBe(true);
+
+ // A log row was written (the pipeline's own summary) — DoD: "verify log row created".
+ expect(logRows.length).toBe(1);
+ expect(logRows[0].service).toBe('Charity Split Audit');
+ expect(logRows[0].success).toBe(true);
+ const ve = JSON.parse(logRows[0].value_extracted);
+ expect(ve.merchants_audited).toBe(2);
+ expect(ve.broken_count).toBe(1);
+ expect(ve.canary.split_atomic).toBe(SPLIT);
+ expect(ve.canary.charity_routed).toBe(true);
+
+ // Per-merchant + canary rows stored to charity_split_audit — DoD: "data stored".
+ const good = auditRows.find((r) => r.merchant_id === 'good');
+ const broken = auditRows.find((r) => r.merchant_id === 'broken');
+ const canary = auditRows.find((r) => r.merchant_id === 'canary');
+ expect(good.config_valid).toBe(true);
+ expect(good.expected_split).toBe(25_000); // $1.00 @ 2.5%
+ expect(broken.config_valid).toBe(false);
+ expect(broken.broken_reason).toBe('missing_charity_address');
+ expect(canary.kind).toBe('canary');
+ expect(canary.charity_routed).toBe(true);
+ expect(canary.routed_split).toBe(SPLIT);
+ expect(canary.tx).toBe(SETTLED_SIG);
+ });
+
+ it('flags an unrouted charity leg when the split never lands on-chain', async () => {
+ auditRows.length = 0; logRows.length = 0;
+ merchantRows = [];
+ const noLegConn = {
+ getParsedTransaction: async () => ({
+ transaction: { message: { instructions: [
+ { program: 'spl-token', parsed: { type: 'transferChecked', info: { destination: payToAta, tokenAmount: { amount: BASE } } } },
+ ] } },
+ meta: { innerInstructions: [], err: null },
+ }),
+ };
+ const out = await run({ origin, buyer, conn: noLegConn, remainingCap: 1_000_000 });
+ expect(out.canary.charityRouted).toBe(false);
+ expect(out.success).toBe(false); // a dropped donation is the alert signal
+ expect(out.errorMsg).toBe('canary_charity_not_routed');
+ expect(logRows[0].success).toBe(false);
+ });
+
+ it('still settles + still records a log row when the wallet is unconfigured (no canary)', async () => {
+ auditRows.length = 0; logRows.length = 0;
+ merchantRows = [];
+ // No ctx.buyer and no seed env → canary skips; the sweep + log row still run.
+ const prev = process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ const prevAgent = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ const prevNodeEnv = process.env.NODE_ENV;
+ delete process.env.X402_SEED_SOLANA_SECRET_BASE58;
+ delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;
+ process.env.NODE_ENV = 'production'; // block the local test-wallet fallback
+ try {
+ const out = await run({ origin, conn: fakeConn, remainingCap: 1_000_000 });
+ expect(out.amountAtomic).toBe(0);
+ expect(out.canary.attempted).toBe(false);
+ expect(logRows.length).toBe(1); // log row always written
+ } finally {
+ if (prev) process.env.X402_SEED_SOLANA_SECRET_BASE58 = prev;
+ if (prevAgent) process.env.X402_AGENT_SOLANA_SECRET_BASE58 = prevAgent;
+ process.env.NODE_ENV = prevNodeEnv;
+ }
+ });
+});
diff --git a/tests/x402-charity-split-audit.test.js b/tests/x402-charity-split-audit.test.js
new file mode 100644
index 000000000..1535e5f1c
--- /dev/null
+++ b/tests/x402-charity-split-audit.test.js
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+
+// Pure-logic integration test for the Charity Split Audit pipeline. The split
+// arithmetic, the broken-merchant-config classifier, and the on-chain transfer
+// collector are the giving-integrity heart of "ensures donation promises are
+// kept" — exercise them with no DB and no chain.
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+process.env.X402_ASSET_MINT_SOLANA = USDC;
+
+const {
+ computeSplit,
+ isValidAddress,
+ classifyCharityConfig,
+ collectTokenTransfers,
+} = await import('../api/_lib/x402/pipelines/charity-split-audit.js');
+
+const solAddr = () => Keypair.generate().publicKey.toBase58();
+const EVM = '0x1111111111111111111111111111111111111111';
+
+describe('computeSplit — floor(amount × bps / 10000)', () => {
+ it('matches the checkout tip math exactly at the atom', () => {
+ expect(computeSplit(1000, 500)).toBe(50n); // $0.001 @ 5%
+ expect(computeSplit(1_000_000, 250)).toBe(25_000n); // $1.00 @ 2.5%
+ expect(computeSplit(1_000_000, 10000)).toBe(1_000_000n); // 100%
+ });
+ it('floors rather than rounds — never overpays the cause', () => {
+ // 999 × 5% = 49.95 → 49, not 50.
+ expect(computeSplit(999, 500)).toBe(49n);
+ // A share too small for the base rounds the split to zero.
+ expect(computeSplit(100, 1)).toBe(0n);
+ });
+});
+
+describe('isValidAddress — chain-matched', () => {
+ it('accepts a base58 address only on solana', () => {
+ const a = solAddr();
+ expect(isValidAddress('solana', a)).toBe(true);
+ expect(isValidAddress('base', a)).toBe(false);
+ });
+ it('accepts a 0x address only on base', () => {
+ expect(isValidAddress('base', EVM)).toBe(true);
+ expect(isValidAddress('solana', EVM)).toBe(false);
+ });
+ it('rejects empty / unknown chain', () => {
+ expect(isValidAddress('solana', '')).toBe(false);
+ expect(isValidAddress(null, solAddr())).toBe(false);
+ });
+});
+
+describe('classifyCharityConfig — broken donation promises', () => {
+ const validSol = () => ({
+ owner_user_id: 'u1',
+ charity_chain: 'solana',
+ charity_address: solAddr(),
+ charity_bps: 500,
+ payout_solana: solAddr(),
+ payout_evm: null,
+ });
+
+ it('passes a fully-configured solana charity', () => {
+ const c = classifyCharityConfig(validSol());
+ expect(c.configValid).toBe(true);
+ expect(c.reason).toBeNull();
+ expect(c.expectedSplitAtomic).toBe(50_000); // $1.00 @ 5%
+ });
+
+ it('flags a missing cause address', () => {
+ const c = classifyCharityConfig({ ...validSol(), charity_address: null });
+ expect(c.configValid).toBe(false);
+ expect(c.reason).toBe('missing_charity_address');
+ expect(c.expectedSplitAtomic).toBeNull();
+ });
+
+ it('flags a cause address that does not match its chain', () => {
+ const c = classifyCharityConfig({ ...validSol(), charity_address: EVM });
+ expect(c.reason).toBe('invalid_solana_charity_address');
+ });
+
+ it('flags a zero share', () => {
+ const c = classifyCharityConfig({ ...validSol(), charity_bps: 0 });
+ expect(c.reason).toBe('zero_bps');
+ });
+
+ it('flags a share over 100%', () => {
+ const c = classifyCharityConfig({ ...validSol(), charity_bps: 10001 });
+ expect(c.reason).toBe('bps_over_100pct');
+ });
+
+ it('flags a missing payout (nowhere for the base payment to land)', () => {
+ const c = classifyCharityConfig({ ...validSol(), payout_solana: null });
+ expect(c.reason).toBe('missing_payout');
+ });
+
+ it('flags cause == payout — the tip the checkout silently drops', () => {
+ const shared = solAddr();
+ const c = classifyCharityConfig({
+ ...validSol(),
+ charity_address: shared,
+ payout_solana: shared,
+ });
+ expect(c.reason).toBe('charity_equals_payout');
+ });
+
+ it('picks the chain-correct payout column', () => {
+ const c = classifyCharityConfig({
+ owner_user_id: 'u2',
+ charity_chain: 'base',
+ charity_address: EVM,
+ charity_bps: 100,
+ payout_evm: '0x2222222222222222222222222222222222222222',
+ payout_solana: solAddr(),
+ });
+ expect(c.configValid).toBe(true);
+ expect(c.payout).toBe('0x2222222222222222222222222222222222222222');
+ });
+});
+
+describe('collectTokenTransfers — on-chain verification', () => {
+ const charityAta = solAddr();
+ const payToAta = solAddr();
+
+ function parsedTx({ withCharity = true } = {}) {
+ const ixs = [
+ {
+ program: 'spl-token',
+ parsed: { type: 'transferChecked', info: { destination: payToAta, tokenAmount: { amount: '1000' } } },
+ },
+ ];
+ if (withCharity) {
+ ixs.push({
+ program: 'spl-token',
+ parsed: { type: 'transferChecked', info: { destination: charityAta, tokenAmount: { amount: '50' } } },
+ });
+ }
+ return { transaction: { message: { instructions: ixs } }, meta: { innerInstructions: [] } };
+ }
+
+ it('finds both the base and charity legs with exact atomics', () => {
+ const legs = collectTokenTransfers(parsedTx());
+ expect(legs).toContainEqual({ destination: payToAta, amount: '1000' });
+ expect(legs).toContainEqual({ destination: charityAta, amount: '50' });
+ });
+
+ it('omits the charity leg when it was never appended (regression signal)', () => {
+ const legs = collectTokenTransfers(parsedTx({ withCharity: false }));
+ expect(legs.some((l) => l.destination === charityAta)).toBe(false);
+ });
+
+ it('collects legs from inner instructions too', () => {
+ const tx = {
+ transaction: { message: { instructions: [] } },
+ meta: {
+ innerInstructions: [
+ { instructions: [{ program: 'spl-token', parsed: { type: 'transfer', info: { destination: charityAta, amount: '50' } } }] },
+ ],
+ },
+ };
+ expect(collectTokenTransfers(tx)).toContainEqual({ destination: charityAta, amount: '50' });
+ });
+
+ it('ignores non-token-transfer instructions', () => {
+ const tx = {
+ transaction: { message: { instructions: [
+ { program: 'system', parsed: { type: 'createAccount', info: {} } },
+ { program: 'spl-token', parsed: { type: 'initializeAccount', info: { account: charityAta } } },
+ ] } },
+ meta: { innerInstructions: [] },
+ };
+ expect(collectTokenTransfers(tx)).toEqual([]);
+ });
+});
diff --git a/tests/x402-pricing-tracker.test.js b/tests/x402-pricing-tracker.test.js
new file mode 100644
index 000000000..9302f5b60
--- /dev/null
+++ b/tests/x402-pricing-tracker.test.js
@@ -0,0 +1,75 @@
+import { describe, it, expect } from 'vitest';
+import {
+ pctChange,
+ priceRecordFromDetails,
+ extractDetails,
+} from '../api/_lib/x402/pipelines/x402-pricing-tracker.js';
+
+describe('pctChange', () => {
+ it('computes a percentage hike', () => {
+ expect(pctChange(1000, 1300)).toBe(30);
+ });
+ it('computes a percentage drop', () => {
+ expect(pctChange(1000, 800)).toBe(-20);
+ });
+ it('returns null with no comparable baseline', () => {
+ expect(pctChange(null, 1000)).toBeNull();
+ expect(pctChange(0, 1000)).toBeNull();
+ expect(pctChange(1000, null)).toBeNull();
+ });
+});
+
+describe('priceRecordFromDetails', () => {
+ const fallback = { service_key: 'r#t', resource: 'r', tool_name: 't' };
+
+ it('selects the cheapest price across networks', () => {
+ const rec = priceRecordFromDetails(
+ {
+ service_key: 'r#t',
+ resource: 'https://svc.test',
+ tool_name: 't',
+ name: 'Svc',
+ available: true,
+ min_price_atomic: 2000,
+ prices: [
+ { network: 'eip155:8453', amount_atomic: 2000, asset: 'A', price: '$0.002' },
+ { network: 'solana:mainnet', amount_atomic: 1500, asset: 'B', price: '$0.0015' },
+ ],
+ },
+ fallback,
+ );
+ expect(rec.price_atomic).toBe(1500);
+ expect(rec.network).toBe('solana:mainnet');
+ expect(rec.price_label).toBe('$0.0015');
+ expect(rec.available).toBe(true);
+ });
+
+ it('marks an unlisted service unavailable with a null price', () => {
+ const rec = priceRecordFromDetails(
+ { service_key: 'r#t', resource: 'r', tool_name: 't', available: false, prices: [], min_price_atomic: null },
+ fallback,
+ );
+ expect(rec.available).toBe(false);
+ expect(rec.price_atomic).toBeNull();
+ });
+
+ it('falls back to the tracked identity when the payload omits it', () => {
+ const rec = priceRecordFromDetails({ available: true, prices: [{ network: 'x', amount_atomic: 1000 }] }, fallback);
+ expect(rec.service_key).toBe('r#t');
+ expect(rec.resource).toBe('r');
+ expect(rec.price_atomic).toBe(1000);
+ });
+});
+
+describe('extractDetails', () => {
+ it('pulls structuredContent out of a JSON-RPC tools/call body', () => {
+ const { details, rpcError } = extractDetails({ result: { structuredContent: { available: true, min_price_atomic: 1000 } } });
+ expect(details.min_price_atomic).toBe(1000);
+ expect(rpcError).toBeNull();
+ });
+ it('surfaces a JSON-RPC error and a null details payload', () => {
+ const { details, rpcError } = extractDetails({ error: { code: -32000, message: 'rate_limited' } });
+ expect(details).toBeNull();
+ expect(rpcError).toMatchObject({ code: -32000 });
+ });
+});
diff --git a/tests/x402-subscription-health.test.js b/tests/x402-subscription-health.test.js
new file mode 100644
index 000000000..360b61881
--- /dev/null
+++ b/tests/x402-subscription-health.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+
+const { __test } = await import('../api/_lib/x402/pipelines/subscription-health.js');
+const { classify, contactEmail, EXPIRY_WARN_DAYS } = __test;
+
+const NOW = Date.parse('2026-06-27T00:00:00Z');
+const inDays = (n) => new Date(NOW + n * 86_400_000).toISOString();
+
+describe('subscription-health classify()', () => {
+ it('flags a revoked key regardless of expiry', () => {
+ const v = classify({ revoked_at: inDays(-1), expires_at: inDays(100) }, NOW);
+ expect(v.status).toBe('revoked');
+ expect(v.daysToExpiry).toBeNull();
+ });
+
+ it('treats a null expiry as active with no countdown', () => {
+ const v = classify({ revoked_at: null, expires_at: null }, NOW);
+ expect(v.status).toBe('active');
+ expect(v.daysToExpiry).toBeNull();
+ });
+
+ it('marks an already-past expiry as expired', () => {
+ const v = classify({ expires_at: inDays(-2) }, NOW);
+ expect(v.status).toBe('expired');
+ expect(v.daysToExpiry).toBeLessThanOrEqual(0);
+ });
+
+ it('marks a key inside the warning window as expiring_soon', () => {
+ const v = classify({ expires_at: inDays(3) }, NOW);
+ expect(v.status).toBe('expiring_soon');
+ expect(v.daysToExpiry).toBe(3);
+ });
+
+ it('marks a key at the warning boundary as expiring_soon', () => {
+ const v = classify({ expires_at: inDays(EXPIRY_WARN_DAYS) }, NOW);
+ expect(v.status).toBe('expiring_soon');
+ });
+
+ it('marks a key beyond the warning window as active', () => {
+ const v = classify({ expires_at: inDays(EXPIRY_WARN_DAYS + 5) }, NOW);
+ expect(v.status).toBe('active');
+ expect(v.daysToExpiry).toBe(EXPIRY_WARN_DAYS + 5);
+ });
+});
+
+describe('subscription-health contactEmail()', () => {
+ it('returns null when meta is missing or has no contact', () => {
+ expect(contactEmail(null)).toBeNull();
+ expect(contactEmail({})).toBeNull();
+ expect(contactEmail({ tier: 'gold' })).toBeNull();
+ });
+
+ it('reads the common contact keys', () => {
+ expect(contactEmail({ email: '[email protected]' })).toBe('[email protected]');
+ expect(contactEmail({ contact_email: '[email protected]' })).toBe('[email protected]');
+ expect(contactEmail({ notify_email: '[email protected]' })).toBe('[email protected]');
+ expect(contactEmail({ contact: '[email protected]' })).toBe('[email protected]');
+ expect(contactEmail({ contact: { email: '[email protected]' } })).toBe('[email protected]');
+ });
+
+ it('rejects a malformed address', () => {
+ expect(contactEmail({ email: 'not-an-email' })).toBeNull();
+ expect(contactEmail({ email: ' ' })).toBeNull();
+ });
+
+ it('trims surrounding whitespace', () => {
+ expect(contactEmail({ email: ' [email protected] ' })).toBe('[email protected]');
+ });
+});