Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): add multiple autonomous probes for monitoring and validation
nirholas8176c5ef4612
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d70df3ef6..fe3ecc835 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`+- **Charity Split Audit — the platform proves donation promises are actually kept on-chain** — Merchants on the three.ws payment console can pledge a charity split: a set share of every payment they take is donated to a cause, added automatically to the buyer's transaction at checkout. That's a promise made to buyers — and a promise nobody was checking. The platform now audits it every week. First it reviews every merchant who has turned on giving and confirms the promise is actually deliverable: a real, correctly-formatted cause wallet for the chosen network, a non-zero share, a place for the merchant's own funds to land, and a cause wallet that isn't accidentally set to the merchant's own payout (a misconfiguration that would silently cancel the donation). Any broken setup is flagged before a buyer is ever told their payment gave to a cause that could never receive it. Then it proves the giving machinery itself still works end to end: an autonomous agent makes one real payment through the exact same checkout code a buyer uses, with a charity split attached, and reads the settled transaction back from the blockchain to confirm the cause's cut landed — to the exact amount the split formula promised. If a code change ever caused the donation to be dropped, mis-sized, or mis-routed, the audit catches it and alerts operations. The canary donation routes to a platform-controlled wallet, so the check costs a fraction of a cent and never sends funds astray. `[feature, 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]`@@ -65,6 +66,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`+- **Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving** — Every autonomous payment an agent makes first sets aside room under its own daily spending limit, then settles the payment and either confirms or releases that reservation. If the process is interrupted between those two steps — a crash, a timeout, an error on a path that forgot to clean up — the reservation is orphaned: it keeps holding spending room against money that never actually moved. Enough orphans and an agent's daily cap is quietly exhausted by ghosts, so genuine payments start getting rejected for 'daily limit reached' even though the wallet is full and barely anything was spent. The platform now sweeps for these leaks automatically. Every fifteen minutes an autonomous agent scans both spending ledgers — USD payment caps and SOL trading caps — for any reservation older than an hour that was never finalized (in a healthy system reservations clear in seconds, so an hour is unmistakably stuck), frees the wrongly-held headroom through the same release path a correct cleanup would have used, and records exactly what it reclaimed so there's a permanent audit trail. A sudden spike in leaks is surfaced to the platform's health check, pointing operators straight at whichever code path is failing to clean up after itself. The sweep is a free database maintenance pass — it moves no funds and runs even when the spend wallet is offline, which is precisely when a starved cap most needs unsticking. `[fix, 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]`@@ -77,6 +79,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Walk-Browse the Marketplace is now monochrome and agent-readable** — The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner. (`/marketplace-walk`) `[improvement]`- **Wallet sign-in fixed and a cleaner, monochrome login** — Restored Ethereum (SIWE) and Solana (SIWS) wallet sign-in and the active-sessions controls, which had been unreachable due to missing API route mappings. Also refined the sign-in and sign-up screens to a crisp monochrome palette — neutral chain icons, calmer focus and hover states — for a faster, more focused first impression. `[fix, improvement]`- **x402 payments dashboards refined to the monochrome system** — The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console. (`/dashboard/x402`) `[improvement]`+- **x402 Service Pricing Tracker — the platform watches its suppliers' prices and flags every hike** — three.ws pays other agents' paid APIs over the x402 protocol to do real work — discovery, data, inference — and those services can quietly change their prices. The platform now tracks them. Every six hours an autonomous agent takes the external services we've actually discovered and depend on, and for each one makes a real on-chain $0.001 payment to read its current live price across every payment network, settling on the cheapest. It compares that to the last price it recorded and keeps a running history per service, so a supplier's cost is never a mystery. If a service's cheapest price jumps more than 20%, it raises a cost-model alert so we can revisit our own pricing or switch to a cheaper alternative; if a price drops, it flags an opportunity to lean on that service more. The full tracked catalog — current prices, recent changes, active hike alerts, and price-drop opportunities — is published at a new public, no-cost feed at /api/x402/service-pricing-report. It rotates through the suppliers a few at a time, so the whole catalog refreshes about daily for a fraction of a cent, and every check settles on Solana with a real transaction signature and is logged like every other autonomous payment. `[feature, infra]`## 2026-06-26diff --git a/agents/x402-buildout/self/api-key-health.md b/agents/x402-buildout/self/api-key-health.mdnew file mode 100644index 000000000..434ad0430--- /dev/null+++ b/agents/x402-buildout/self/api-key-health.md@@ -0,0 +1,41 @@+# 075: API Key: Validity Health Check++## Objective+Build a real, wired x402 use case that calls the `/api/x402/api-key-health` 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/api-key-health`+- **Method:** POST+- **Body:** `{"scope":"autonomous_loop"}`++## What to Build+Pay x402 to verify the autonomous loop API key is valid and has the necessary scopes. Extract { valid: bool, scopes: [], expires_at }. Run hourly. Alert 24h before expiry.++## 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/api-key-health`+ - `body`: `{"scope":"autonomous_loop"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/auth-session-health.md b/agents/x402-buildout/self/auth-session-health.mdnew file mode 100644index 000000000..ae951c93b--- /dev/null+++ b/agents/x402-buildout/self/auth-session-health.md@@ -0,0 +1,41 @@+# 083: Auth: Session Lifecycle Health++## Objective+Build a real, wired x402 use case that calls the `/api/x402/auth-health` 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/auth-health`+- **Method:** POST+- **Body:** `{"mode":"session_lifecycle"}`++## What to Build+Pay x402 to exercise the auth session lifecycle: create, validate, refresh, expire. Extract { all_pass: bool, failed_step, latency_ms }. Runs every 30 minutes as a security-critical 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/auth-health`+ - `body`: `{"mode":"session_lifecycle"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/cross-chain-bridge-status.md b/agents/x402-buildout/self/cross-chain-bridge-status.mdnew file mode 100644index 000000000..0175960a6--- /dev/null+++ b/agents/x402-buildout/self/cross-chain-bridge-status.md@@ -0,0 +1,41 @@+# 078: Cross-Chain: Bridge Status Monitor++## Objective+Build a real, wired x402 use case that calls the `/api/x402/cross-chain` 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/cross-chain`+- **Method:** POST+- **Body:** `{"mode":"bridge_status"}`++## What to Build+Pay x402 to get current bridge status between Solana and other chains. Extract { bridges: [{chain, status, latency_ms}] }. Any bridge with status=down is logged as a platform risk.++## 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/cross-chain`+ - `body`: `{"mode":"bridge_status"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/forge-image-canary.md b/agents/x402-buildout/self/forge-image-canary.mdnew file mode 100644index 000000000..cd6bc40cd--- /dev/null+++ b/agents/x402-buildout/self/forge-image-canary.md@@ -0,0 +1,41 @@+# 073: Forge: Image Generation Canary++## 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":"image","prompt":"A simple blue circle."}`++## What to Build+Pay x402 for a minimal image generation to verify the image pipeline is alive. Extract { generated: bool, url, latency_ms }. Tests the full AI generation + CDN upload path.++## 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":"image","prompt":"A simple blue circle."}`+ - `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 committeddiff --git a/agents/x402-buildout/self/json-api-schema-check.md b/agents/x402-buildout/self/json-api-schema-check.mdnew file mode 100644index 000000000..8ddb95c96--- /dev/null+++ b/agents/x402-buildout/self/json-api-schema-check.md@@ -0,0 +1,41 @@+# 082: JSON API: Schema Conformance Check++## Objective+Build a real, wired x402 use case that calls the `/api/x402/schema-check` 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/schema-check`+- **Method:** POST+- **Body:** `{"api":"changelog_json"}`++## What to Build+Pay x402 to hit the public changelog JSON API and validate the response schema matches the spec. Extract { valid: bool, version, entry_count }. Catches breaking schema changes before users notice.++## 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/schema-check`+ - `body`: `{"api":"changelog_json"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/llm-proxy-latency.md b/agents/x402-buildout/self/llm-proxy-latency.mdnew file mode 100644index 000000000..64c2ef577--- /dev/null+++ b/agents/x402-buildout/self/llm-proxy-latency.md@@ -0,0 +1,41 @@+# 076: LLM Proxy: Latency Benchmark++## Objective+Build a real, wired x402 use case that calls the `/api/x402/llm-proxy` 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/llm-proxy`+- **Method:** POST+- **Body:** `{"model":"fast","prompt":"Count to 3.","max_tokens":10}`++## What to Build+Pay x402 to send a minimal prompt through the LLM proxy and measure response latency. Extract { latency_ms, tokens_used, model }. Run every 10 minutes. Alert if p95 latency exceeds 3 seconds.++## 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/llm-proxy`+ - `body`: `{"model":"fast","prompt":"Count to 3.","max_tokens":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 committeddiff --git a/agents/x402-buildout/self/llm-proxy-quality.md b/agents/x402-buildout/self/llm-proxy-quality.mdnew file mode 100644index 000000000..9531744ea--- /dev/null+++ b/agents/x402-buildout/self/llm-proxy-quality.md@@ -0,0 +1,41 @@+# 077: LLM Proxy: Output Quality Probe++## Objective+Build a real, wired x402 use case that calls the `/api/x402/llm-proxy` 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/llm-proxy`+- **Method:** POST+- **Body:** `{"model":"reasoning","prompt":"What is 7 + 8? Reply with only the number.","max_tokens":5}`++## What to Build+Pay x402 to verify the LLM proxy returns a correct, deterministic response. Extract { output, correct: bool }. If output !== "15", mark as quality_failure and alert immediately.++## 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/llm-proxy`+ - `body`: `{"model":"reasoning","prompt":"What is 7 + 8? Reply with only the number.","max_tokens":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 committeddiff --git a/agents/x402-buildout/self/notification-delivery-probe.md b/agents/x402-buildout/self/notification-delivery-probe.mdnew file mode 100644index 000000000..64b45dd27--- /dev/null+++ b/agents/x402-buildout/self/notification-delivery-probe.md@@ -0,0 +1,41 @@+# 079: Notification: Delivery Probe++## Objective+Build a real, wired x402 use case that calls the `/api/x402/notify` 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/notify`+- **Method:** POST+- **Body:** `{"channel":"canary","message":"x402 loop heartbeat","priority":"low"}`++## What to Build+Pay x402 to send a canary notification through the platform notification system. Verify delivery confirmation within 2 seconds. Extract { delivered: bool, channel, 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/notify`+ - `body`: `{"channel":"canary","message":"x402 loop heartbeat","priority":"low"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/rate-limit-probe.md b/agents/x402-buildout/self/rate-limit-probe.mdnew file mode 100644index 000000000..d5f20ee1c--- /dev/null+++ b/agents/x402-buildout/self/rate-limit-probe.md@@ -0,0 +1,41 @@+# 074: Rate Limit: Threshold Probe++## Objective+Build a real, wired x402 use case that calls the `/api/x402/rate-limit-probe` 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/rate-limit-probe`+- **Method:** POST+- **Body:** `{"endpoint":"/api/x402/crypto-intel"}`++## What to Build+Pay x402 to get the current rate limit status for the crypto-intel endpoint. Extract { remaining_calls, reset_at, limit }. Use to throttle the autonomous loop dynamically based on available capacity.++## 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/rate-limit-probe`+ - `body`: `{"endpoint":"/api/x402/crypto-intel"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/rss-feed-validity.md b/agents/x402-buildout/self/rss-feed-validity.mdnew file mode 100644index 000000000..568c06316--- /dev/null+++ b/agents/x402-buildout/self/rss-feed-validity.md@@ -0,0 +1,41 @@+# 081: RSS Feed: Changelog XML Validity++## Objective+Build a real, wired x402 use case that calls the `/api/x402/feed-health` 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/feed-health`+- **Method:** POST+- **Body:** `{"feed":"changelog_rss"}`++## What to Build+Pay x402 to fetch and validate the changelog RSS feed. Verify it parses as valid XML, has correct item count, and the latest entry matches the DB. Extract { valid: bool, item_count, latest_title }.++## 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/feed-health`+ - `body`: `{"feed":"changelog_rss"}`+ - `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 committeddiff --git a/agents/x402-buildout/self/telegram-bot-health.md b/agents/x402-buildout/self/telegram-bot-health.mdnew file mode 100644index 000000000..a9c92c211--- /dev/null+++ b/agents/x402-buildout/self/telegram-bot-health.md@@ -0,0 +1,41 @@+# 080: Telegram Bot: Changelog Bot Health++## Objective+Build a real, wired x402 use case that calls the `/api/x402/telegram-health` 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/telegram-health`+- **Method:** POST+- **Body:** `{"bot":"changelog"}`++## What to Build+Pay x402 to ping the changelog Telegram bot and verify it can reach the Telegram API. Extract { reachable: bool, bot_id, latency_ms }. If unreachable, alert ops — new changelog entries wont reach holders.++## 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/telegram-health`+ - `body`: `{"bot":"changelog"}`+ - `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 committeddiff --git a/api/_lib/migrations/20260629120000_payment_reconciliation.sql b/api/_lib/migrations/20260629120000_payment_reconciliation.sqlindex 7a403f491..0d6802396 100644--- a/api/_lib/migrations/20260629120000_payment_reconciliation.sql+++ b/api/_lib/migrations/20260629120000_payment_reconciliation.sql@@ -37,6 +37,29 @@ CREATE INDEX IF NOT EXISTS payment_reconciliation_open_idxCREATE INDEX IF NOT EXISTS payment_reconciliation_sig_idxON payment_reconciliation (tx_signature);+-- The autonomous log is created lazily by api/cron/x402-autonomous-loop.js on+-- first run; mirror its canonical definition here so this migration is+-- self-contained on a fresh env (matches the file header's intent). Idempotent.+CREATE TABLE IF NOT EXISTS x402_autonomous_log (+ id bigserial PRIMARY KEY,+ run_id uuid NOT NULL,+ ts timestamptz DEFAULT now(),+ endpoint_type text NOT NULL CHECK (endpoint_type IN ('self', 'external')),+ service_name text NOT NULL,+ endpoint_url text NOT NULL,+ network text NOT NULL DEFAULT 'solana:mainnet',+ amount_atomic bigint NOT NULL DEFAULT 0,+ asset text,+ tx_signature text,+ response_data jsonb,+ signal_data jsonb,+ value_extracted jsonb,+ duration_ms int,+ success boolean NOT NULL,+ error_msg text,+ pipeline text+);+-- The autonomous log predates the value_extracted column the reconciliation-- summary is written into (shared across run()-style pipelines; idempotent).ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb;diff --git a/api/_lib/x402/pipelines/builder-code-attribution.js b/api/_lib/x402/pipelines/builder-code-attribution.jsindex b34f4bd69..513bbffe1 100644--- a/api/_lib/x402/pipelines/builder-code-attribution.js+++ b/api/_lib/x402/pipelines/builder-code-attribution.js@@ -379,6 +379,9 @@ export async function run(ctx = {}) {let amountAtomic = 0;let txSig = null;let settleResp = null;+ // settleExecuted = we actually had a wallet and ran the attributed payment.+ // Distinguishes "couldn't run the proof (no wallet)" from "proof failed".+ let settleExecuted = false;if (settleRow) {let solana = null;@@ -395,6 +398,7 @@ export async function run(ctx = {}) {}if (solana) {+ settleExecuted = true;const r = await settleAttributed({row: settleRow,buyer: solana.buyer,@@ -423,11 +427,13 @@ export async function run(ctx = {}) {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.+ // The settlement proof is meaningful only when we actually ran it (had a+ // declaring endpoint AND a wallet). A run that couldn't even attempt the proof+ // (no wallet, no declaring endpoint to pay) isn't a failure — only an executed+ // proof that came back echo_accepted=false is an attributed-settle FAILURE.const settleAttempted = !!settleRow;const settleProven = !!(settleRow && settleRow.echo_accepted);- const proofOk = !settleAttempted || settleProven;+ const proofOk = !settleExecuted || settleProven;await writeAlert(redis, attributionOk && proofOk ? null : {run_id: runId,@@ -459,7 +465,7 @@ export async function run(ctx = {}) {}const note = attributionOk- ? `${signalData.attributed}/${challenged.length} attributed${settleProven ? `, settle ${txSig ? 'proven' : 'ok'}` : settleAttempted ? ', SETTLE_FAILED' : ''}`+ ? `${signalData.attributed}/${challenged.length} attributed${settleProven ? `, settle ${txSig ? 'proven' : 'ok'}` : settleExecuted ? ', SETTLE_FAILED' : ''}`: `ATTRIBUTION_GAP ${gaps.length}: ${signalData.gap_endpoints.join(',')}`;return {diff --git a/api/_lib/x402/pipelines/spend-reservation-leak-detector.js b/api/_lib/x402/pipelines/spend-reservation-leak-detector.jsindex 3782fe7f9..3dc4a8e1d 100644--- a/api/_lib/x402/pipelines/spend-reservation-leak-detector.js+++ b/api/_lib/x402/pipelines/spend-reservation-leak-detector.js@@ -339,8 +339,8 @@ export async function run(ctx = {}) {// 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 custody = await sweepCustodyLeaks(db, runId, releaseUsd);+ const solActions = await sweepSolActionLeaks(db, runId, releaseSol);const allSwept = [...custody.swept, ...solActions.swept];const agents = new Set(allSwept.map((l) => l.agent_id).filter(Boolean));diff --git a/api/ops/health.js b/api/ops/health.jsindex b2604eec6..114ad6e95 100644--- a/api/ops/health.js+++ b/api/ops/health.js@@ -258,8 +258,13 @@ async function loadBuilderAttribution() {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;+ // The settlement-proof target is the dance-tip row. It FAILED only when the+ // tracker matched its attribution (so it actually attempted an attributed+ // payment) yet the echo was not accepted for a reason other than a missing+ // wallet — i.e. the attributed payment was rejected/never settled on-chain.+ const settleRow = rows.find((r) => /dance-tip/.test(r.endpoint));+ const settleFailed = !!(settleRow && settleRow.matches && settleRow.echo_accepted === false+ && !/^wallet_unconfigured/.test(settleRow.error || ''));const ok = stale ? null : gaps.length === 0 && !settleFailed;return {ok,diff --git a/data/changelog.json b/data/changelog.jsonindex 0244e509f..6f988c045 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$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": "Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving",+ "summary": "Every autonomous payment an agent makes first sets aside room under its own daily spending limit, then settles the payment and either confirms or releases that reservation. If the process is interrupted between those two steps — a crash, a timeout, an error on a path that forgot to clean up — the reservation is orphaned: it keeps holding spending room against money that never actually moved. Enough orphans and an agent's daily cap is quietly exhausted by ghosts, so genuine payments start getting rejected for 'daily limit reached' even though the wallet is full and barely anything was spent. The platform now sweeps for these leaks automatically. Every fifteen minutes an autonomous agent scans both spending ledgers — USD payment caps and SOL trading caps — for any reservation older than an hour that was never finalized (in a healthy system reservations clear in seconds, so an hour is unmistakably stuck), frees the wrongly-held headroom through the same release path a correct cleanup would have used, and records exactly what it reclaimed so there's a permanent audit trail. A sudden spike in leaks is surfaced to the platform's health check, pointing operators straight at whichever code path is failing to clean up after itself. The sweep is a free database maintenance pass — it moves no funds and runs even when the spend wallet is offline, which is precisely when a starved cap most needs unsticking.",+ "tags": ["fix", "infra"]+ },+ {+ "date": "2026-06-27",+ "title": "x402 Service Pricing Tracker — the platform watches its suppliers' prices and flags every hike",+ "summary": "three.ws pays other agents' paid APIs over the x402 protocol to do real work — discovery, data, inference — and those services can quietly change their prices. The platform now tracks them. Every six hours an autonomous agent takes the external services we've actually discovered and depend on, and for each one makes a real on-chain $0.001 payment to read its current live price across every payment network, settling on the cheapest. It compares that to the last price it recorded and keeps a running history per service, so a supplier's cost is never a mystery. If a service's cheapest price jumps more than 20%, it raises a cost-model alert so we can revisit our own pricing or switch to a cheaper alternative; if a price drops, it flags an opportunity to lean on that service more. The full tracked catalog — current prices, recent changes, active hike alerts, and price-drop opportunities — is published at a new public, no-cost feed at /api/x402/service-pricing-report. It rotates through the suppliers a few at a time, so the whole catalog refreshes about daily for a fraction of a cent, and every check settles on Solana with a real transaction signature and is logged like every other autonomous payment.",+ "tags": ["feature", "infra"]+ },+ {+ "date": "2026-06-27",+ "title": "Charity Split Audit — the platform proves donation promises are actually kept on-chain",+ "summary": "Merchants on the three.ws payment console can pledge a charity split: a set share of every payment they take is donated to a cause, added automatically to the buyer's transaction at checkout. That's a promise made to buyers — and a promise nobody was checking. The platform now audits it every week. First it reviews every merchant who has turned on giving and confirms the promise is actually deliverable: a real, correctly-formatted cause wallet for the chosen network, a non-zero share, a place for the merchant's own funds to land, and a cause wallet that isn't accidentally set to the merchant's own payout (a misconfiguration that would silently cancel the donation). Any broken setup is flagged before a buyer is ever told their payment gave to a cause that could never receive it. Then it proves the giving machinery itself still works end to end: an autonomous agent makes one real payment through the exact same checkout code a buyer uses, with a charity split attached, and reads the settled transaction back from the blockchain to confirm the cause's cut landed — to the exact amount the split formula promised. If a code change ever caused the donation to be dropped, mis-sized, or mis-routed, the audit catches it and alerts operations. The canary donation routes to a platform-controlled wallet, so the check costs a fraction of a cent and never sends funds astray.",+ "tags": ["feature", "security"]+ },{"date": "2026-06-27","title": "Builder Code Attribution Tracker — the platform proves every paid endpoint earns it on-chain credit",diff --git a/public/changelog.json b/public/changelog.jsonindex 17a69c31f..3127e7d09 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:37:46.077Z",+ "generated_at": "2026-06-27T23:46:49.134Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -237,6 +237,17 @@"security"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Charity Split Audit — the platform proves donation promises are actually kept on-chain",+ "summary": "Merchants on the three.ws payment console can pledge a charity split: a set share of every payment they take is donated to a cause, added automatically to the buyer's transaction at checkout. That's a promise made to buyers — and a promise nobody was checking. The platform now audits it every week. First it reviews every merchant who has turned on giving and confirms the promise is actually deliverable: a real, correctly-formatted cause wallet for the chosen network, a non-zero share, a place for the merchant's own funds to land, and a cause wallet that isn't accidentally set to the merchant's own payout (a misconfiguration that would silently cancel the donation). Any broken setup is flagged before a buyer is ever told their payment gave to a cause that could never receive it. Then it proves the giving machinery itself still works end to end: an autonomous agent makes one real payment through the exact same checkout code a buyer uses, with a charity split attached, and reads the settled transaction back from the blockchain to confirm the cause's cut landed — to the exact amount the split formula promised. If a code change ever caused the donation to be dropped, mis-sized, or mis-routed, the audit catches it and alerts operations. The canary donation routes to a platform-controlled wallet, so the check costs a fraction of a cent and never sends funds astray.",+ "link": null,+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-06-27","type": "update",@@ -635,6 +646,17 @@"infra"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving",+ "summary": "Every autonomous payment an agent makes first sets aside room under its own daily spending limit, then settles the payment and either confirms or releases that reservation. If the process is interrupted between those two steps — a crash, a timeout, an error on a path that forgot to clean up — the reservation is orphaned: it keeps holding spending room against money that never actually moved. Enough orphans and an agent's daily cap is quietly exhausted by ghosts, so genuine payments start getting rejected for 'daily limit reached' even though the wallet is full and barely anything was spent. The platform now sweeps for these leaks automatically. Every fifteen minutes an autonomous agent scans both spending ledgers — USD payment caps and SOL trading caps — for any reservation older than an hour that was never finalized (in a healthy system reservations clear in seconds, so an hour is unmistakably stuck), frees the wrongly-held headroom through the same release path a correct cleanup would have used, and records exactly what it reclaimed so there's a permanent audit trail. A sudden spike in leaks is surfaced to the platform's health check, pointing operators straight at whichever code path is failing to clean up after itself. The sweep is a free database maintenance pass — it moves no funds and runs even when the spend wallet is offline, which is precisely when a starved cap most needs unsticking.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -764,6 +786,17 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "x402 Service Pricing Tracker — the platform watches its suppliers' prices and flags every hike",+ "summary": "three.ws pays other agents' paid APIs over the x402 protocol to do real work — discovery, data, inference — and those services can quietly change their prices. The platform now tracks them. Every six hours an autonomous agent takes the external services we've actually discovered and depend on, and for each one makes a real on-chain $0.001 payment to read its current live price across every payment network, settling on the cheapest. It compares that to the last price it recorded and keeps a running history per service, so a supplier's cost is never a mystery. If a service's cheapest price jumps more than 20%, it raises a cost-model alert so we can revisit our own pricing or switch to a cheaper alternative; if a price drops, it flags an opportunity to lean on that service more. The full tracked catalog — current prices, recent changes, active hike alerts, and price-drop opportunities — is published at a new public, no-cost feed at /api/x402/service-pricing-report. It rotates through the suppliers a few at a time, so the whole catalog refreshes about daily for a fraction of a cent, and every check settles on Solana with a real transaction signature and is logged like every other autonomous payment.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-06-26","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex e877961a4..da1998ad9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -182,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>Charity Split Audit — the platform proves donation promises are actually kept on-chain</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:Charity Split Audit — the platform proves donation promises are actually kept on-chain</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Merchants on the three.ws payment console can pledge a charity split: a set share of every payment they take is donated to a cause, added automatically to the buyer's transaction at checkout. That's a promise made to buyers — and a promise nobody was checking. The platform now audits it every week. First it reviews every merchant who has turned on giving and confirms the promise is actually deliverable: a real, correctly-formatted cause wallet for the chosen network, a non-zero share, a place for the merchant's own funds to land, and a cause wallet that isn't accidentally set to the merchant's own payout (a misconfiguration that would silently cancel the donation). Any broken setup is flagged before a buyer is ever told their payment gave to a cause that could never receive it. Then it proves the giving machinery itself still works end to end: an autonomous agent makes one real payment through the exact same checkout code a buyer uses, with a charity split attached, and reads the settled transaction back from the blockchain to confirm the cause's cut landed — to the exact amount the split formula promised. If a code change ever caused the donation to be dropped, mis-sized, or mis-routed, the audit catches it and alerts operations. The canary donation routes to a platform-controlled wallet, so the check costs a fraction of a cent and never sends funds astray.</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>@@ -478,6 +486,14 @@<category>feature</category><description>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.</description></item>+ <item>+ <title>Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:Spend Reservation Leak Detector — the platform keeps agent spending caps from silently starving</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every autonomous payment an agent makes first sets aside room under its own daily spending limit, then settles the payment and either confirms or releases that reservation. If the process is interrupted between those two steps — a crash, a timeout, an error on a path that forgot to clean up — the reservation is orphaned: it keeps holding spending room against money that never actually moved. Enough orphans and an agent's daily cap is quietly exhausted by ghosts, so genuine payments start getting rejected for 'daily limit reached' even though the wallet is full and barely anything was spent. The platform now sweeps for these leaks automatically. Every fifteen minutes an autonomous agent scans both spending ledgers — USD payment caps and SOL trading caps — for any reservation older than an hour that was never finalized (in a healthy system reservations clear in seconds, so an hour is unmistakably stuck), frees the wrongly-held headroom through the same release path a correct cleanup would have used, and records exactly what it reclaimed so there's a permanent audit trail. A sudden spike in leaks is surfaced to the platform's health check, pointing operators straight at whichever code path is failing to clean up after itself. The sweep is a free database maintenance pass — it moves no funds and runs even when the spend wallet is offline, which is precisely when a starved cap most needs unsticking.</description>+ </item><item><title>SSE Streaming MCP Health — continuous proof the paid MCP transport delivers cleanly</title><link>https://three.ws/changelog</link>@@ -574,6 +590,14 @@<category>improvement</category><description>The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console.</description></item>+ <item>+ <title>x402 Service Pricing Tracker — the platform watches its suppliers' prices and flags every hike</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-27:x402 Service Pricing Tracker — the platform watches its suppliers' prices and flags every hike</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>three.ws pays other agents' paid APIs over the x402 protocol to do real work — discovery, data, inference — and those services can quietly change their prices. The platform now tracks them. Every six hours an autonomous agent takes the external services we've actually discovered and depend on, and for each one makes a real on-chain $0.001 payment to read its current live price across every payment network, settling on the cheapest. It compares that to the last price it recorded and keeps a running history per service, so a supplier's cost is never a mystery. If a service's cheapest price jumps more than 20%, it raises a cost-model alert so we can revisit our own pricing or switch to a cheaper alternative; if a price drops, it flags an opportunity to lean on that service more. The full tracked catalog — current prices, recent changes, active hike alerts, and price-drop opportunities — is published at a new public, no-cost feed at /api/x402/service-pricing-report. It rotates through the suppliers a few at a time, so the whole catalog refreshes about daily for a fraction of a cent, and every check settles on Solana with a real transaction signature and is logged like every other autonomous payment.</description>+ </item><item><title>Agent Payment Sessions</title><link>https://three.ws/payments</link>diff --git a/public/features.json b/public/features.jsonindex 4472d9642..9f80daa25 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T23:37:46.063Z",+ "generated_at": "2026-06-27T23:46:49.111Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/test-reservation-leak-detector.mjs b/scripts/test-reservation-leak-detector.mjsindex 7874dfb57..fd8c49845 100644--- a/scripts/test-reservation-leak-detector.mjs+++ b/scripts/test-reservation-leak-detector.mjs@@ -99,7 +99,14 @@ async function main() {}];const { sql, captured } = makeSqlStub({ solRows });const redis = makeRedisStub();- const out = await run({ sql, redis, runId: randomUUID() });+ const releasedSol = [];+ const out = await run({+ sql, redis, runId: randomUUID(),+ // Inject no-op releasers so the offline path doesn't hit the module DB.+ releaseSpend: async (id) => { releasedSol.push(id); },+ releaseSpendReservation: async () => {},+ });+ check('releaseSpend called for the leaked id', releasedSol.includes(4242));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));diff --git a/tests/x402-builder-code-attribution.test.js b/tests/x402-builder-code-attribution.test.jsnew file mode 100644index 000000000..26fbd8222--- /dev/null+++ b/tests/x402-builder-code-attribution.test.js@@ -0,0 +1,205 @@+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import http from 'node:http';+import { Keypair } from '@solana/web3.js';++// The payTo / feePayer keys and the USDC mint must be valid base58 pubkeys+// because the settlement-proof step builds + signs a REAL Solana transfer+// locally via buildPaymentTx. Nothing is broadcast — the mock server below+// never touches a chain — so this is a true integration test of the+// probe → attribution-verify → attributed-pay → settle → store path with no+// on-chain spend.+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_MINT_SOLANA = USDC;+process.env.X402_BUILDER_CODE_APP = 'three_d_agent';+process.env.X402_BUILDER_CODE_WALLET = '3d_agent';++const { run } = await import('../api/_lib/x402/pipelines/builder-code-attribution.js');++const APP_CODE = 'three_d_agent';+const payToSol = Keypair.generate().publicKey.toBase58();+const feePayer = Keypair.generate().publicKey.toBase58();+const AMOUNT = '1000'; // $0.001 USDC atomics++function builderCodeExtension(a) {+ return { info: { a }, schema: { type: 'object' } };+}++function challenge(pathname, { code = APP_CODE } = {}) {+ const extensions = { bazaar: { info: {} } };+ // `code === null` simulates an endpoint that dropped the declaration entirely.+ if (code !== null) extensions['builder-code'] = builderCodeExtension(code);+ return {+ x402Version: 2,+ error: 'payment required',+ resource: `http://127.0.0.1${pathname}`,+ accepts: [{+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ asset: USDC,+ payTo: payToSol,+ amount: AMOUNT,+ extra: { name: 'USDC', decimals: 6, feePayer },+ }],+ extensions,+ };+}++// Per-test knobs.+let perPathCode; // { [pathStartsWith]: code|null } overrides the declared app code+let settleMode; // 'ok' | 'reject' | 'echo'+let server;+let origin;++function codeForPath(pathname) {+ for (const [prefix, code] of Object.entries(perPathCode)) {+ if (pathname.startsWith(prefix)) return code;+ }+ return APP_CODE;+}++beforeAll(async () => {+ server = http.createServer((req, res) => {+ const pathname = req.url.split('?')[0];+ const xPayment = req.headers['x-payment'];++ if (!xPayment) {+ // x402 challenge — advertise the configured builder-code declaration.+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify(challenge(pathname, { code: codeForPath(pathname) })));+ return;+ }++ // Paid request — only the dance-tip settlement proof reaches here.+ const payload = JSON.parse(Buffer.from(xPayment, 'base64').toString('utf8'));+ const echoed = payload?.extensions?.['builder-code']?.a;+ if (settleMode === 'reject' || echoed !== APP_CODE) {+ // Mirrors the resource server's anti-tamper rejection.+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ error: 'builder_code_tampered' }));+ return;+ }+ const settled = { success: true, transaction: 'BC_TESTSIG_123', network: payload.network, payer: 'PayerPubkey111' };+ // `echo` mode also reflects the builder-code block back on the response.+ if (settleMode === 'echo') settled.extensions = { 'builder-code': { a: APP_CODE, w: '3d_agent' } };+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json');+ res.setHeader('x-payment-response', Buffer.from(JSON.stringify(settled)).toString('base64'));+ res.end(JSON.stringify({ ok: true, ticketId: 'tkt_bc' }));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ origin = `http://127.0.0.1:${server.address().port}`;+});++afterAll(() => new Promise((resolve) => server.close(resolve)));++beforeEach(() => { perPathCode = {}; settleMode = 'ok'; process.env.X402_BUILDER_CODE_APP = 'three_d_agent'; });++function makeSqlStub() {+ const calls = [];+ const sql = (strings, ...values) => {+ calls.push({ text: strings.join('?'), values });+ return Promise.resolve([]);+ };+ return { sql, calls };+}++function baseCtx(sqlStub, over = {}) {+ return {+ origin,+ buyer: Keypair.generate(),+ conn: { getAccountInfo: async () => null }, // receiver ATA missing → create ix+ blockhash: '11111111111111111111111111111111',+ mintInfo: { decimals: 6 },+ remainingCap: 5_000_000,+ sql: sqlStub.sql,+ redis: null,+ log: { info() {}, warn() {} },+ runId: '00000000-0000-0000-0000-000000000000',+ ...over,+ };+}++describe('builder-code-attribution run()', () => {+ it('verifies every endpoint declares three_d_agent and proves an attributed settlement', async () => {+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.success).toBe(true);+ expect(out.errorMsg).toBeNull();+ expect(out.signalData.attribution_ok).toBe(true);+ expect(out.signalData.gaps).toBe(0);+ expect(out.signalData.settle_proven).toBe(true);+ expect(out.amountAtomic).toBe(Number(AMOUNT));+ expect(out.txSig).toBe('BC_TESTSIG_123');+ // Every probed endpoint matched and was persisted to builder_code_attribution.+ const upserts = sqlStub.calls.filter((c) => /insert into\s+builder_code_attribution/i.test(c.text));+ expect(upserts.length).toBe(out.signalData.endpoints_probed);+ expect(sqlStub.calls.some((c) => c.values.includes('BC_TESTSIG_123'))).toBe(true);+ });++ it('flags an attribution gap when an endpoint drops the builder-code declaration', async () => {+ perPathCode = { '/api/x402/crypto-intel': null };+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.success).toBe(false);+ expect(out.signalData.attribution_ok).toBe(false);+ expect(out.signalData.gaps).toBe(1);+ expect(out.signalData.gap_endpoints).toContain('/api/x402/crypto-intel');+ expect(out.errorMsg).toMatch(/attribution_gap/);+ });++ it('flags a gap when an endpoint declares the wrong app code', async () => {+ perPathCode = { '/api/x402/fact-check': 'someone_else' };+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.success).toBe(false);+ expect(out.signalData.gaps).toBe(1);+ expect(out.signalData.gap_endpoints).toContain('/api/x402/fact-check');+ });++ it('fails the proof (not a gap) when the attributed payment is rejected', async () => {+ settleMode = 'reject';+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.signalData.attribution_ok).toBe(true); // declarations all present+ expect(out.signalData.settle_proven).toBe(false);+ expect(out.success).toBe(false);+ expect(out.errorMsg).toMatch(/attributed_settle_failed/);+ expect(out.amountAtomic).toBe(0); // nothing settled+ });++ it('records when the X-PAYMENT-RESPONSE echoes the builder-code block', async () => {+ settleMode = 'echo';+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.success).toBe(true);+ expect(out.signalData.response_attributed).toBe(true);+ });++ it('skips entirely (no spend) when X402_BUILDER_CODE_APP is unset', async () => {+ process.env.X402_BUILDER_CODE_APP = '';+ const sqlStub = makeSqlStub();+ const out = await run(baseCtx(sqlStub));++ expect(out.skipped).toBe(true);+ expect(out.success).toBe(false);+ expect(out.errorMsg).toBe('builder_code_app_unset');+ expect(out.amountAtomic).toBe(0);+ // Nothing probed, nothing persisted.+ expect(sqlStub.calls.length).toBe(0);+ });++ it('does not crash when DB persistence fails (the sweep still returns its verdict)', async () => {+ const sql = () => Promise.reject(new Error('db down'));+ const out = await run(baseCtx({ sql, calls: [] }));+ // Persistence failure is swallowed; the attribution verdict is still produced.+ expect(out.signalData.attribution_ok).toBe(true);+ expect(out.success).toBe(true);+ });+});diff --git a/tests/x402-spend-reservation-leak-detector.test.js b/tests/x402-spend-reservation-leak-detector.test.jsnew file mode 100644index 000000000..94d5978e6--- /dev/null+++ b/tests/x402-spend-reservation-leak-detector.test.js@@ -0,0 +1,148 @@+import { describe, it, expect } from 'vitest';++import { getSelfRegistry } from '../api/_lib/x402/autonomous-registry.js';+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';++// Captured-SQL mock: answers the two leak scans from the given rows, resolves []+// for DDL/INSERTs, and can be made to reject a matching statement (error paths).+function mockSql({ custodyRows = [], solRows = [], failOn = null } = {}) {+ const calls = [];+ const fn = (strings, ...values) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim();+ calls.push({ text, values });+ if (failOn && failOn.test(text)) return Promise.reject(new Error('mock_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([]);+ };+ fn.calls = calls;+ return fn;+}++function mockRedis() {+ 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); },+ };+}++const noopReleasers = { releaseSpend: async () => {}, releaseSpendReservation: async () => {} };++describe('autonomous registry — spend-reservation-leak-detector entry', () => {+ const entry = getSelfRegistry().find((e) => e.id === 'spend-reservation-leak-detector');++ it('exists, enabled, finance pipeline, free, 15-min cooldown', () => {+ expect(entry).toBeTruthy();+ expect(entry.enabled).toBe(true);+ expect(entry.pipeline).toBe('finance');+ expect(entry.price_atomic).toBe(0);+ expect(entry.cooldown_s).toBe(900);+ expect(entry.cooldown_seconds).toBe(900);+ expect(typeof entry.run).toBe('function');+ });+});++describe('spend-reservation-leak-detector run()', () => {+ it('clean sweep: success, free, own log row, alert cleared', async () => {+ const sql = mockSql();+ const redis = mockRedis();+ const out = await run({ sql, redis, ...noopReleasers });++ expect(out.success).toBe(true);+ expect(out.recorded).toBe(true);+ expect(out.amountAtomic).toBe(0);+ expect(out.valueExtracted.leaked_total).toBe(0);+ expect(out.note).toBe('no leaked reservations');++ const texts = sql.calls.map((c) => c.text);+ expect(texts.some((t) => /CREATE TABLE IF NOT EXISTS spend_reservation_leaks/i.test(t))).toBe(true);+ expect(texts.some((t) => /ADD COLUMN IF NOT EXISTS value_extracted/i.test(t))).toBe(true);+ expect(texts.some((t) => /FROM agent_custody_events/i.test(t))).toBe(true);+ expect(texts.some((t) => /FROM agent_actions/i.test(t))).toBe(true);++ const logRow = sql.calls.find((c) => /INSERT INTO x402_autonomous_log/i.test(c.text));+ expect(logRow).toBeTruthy();+ expect(logRow.values).toContain('finance');+ expect(logRow.values).toContain(true); // success+ expect(redis.store.has(RESERVATION_LEAK_REDIS_LATEST_KEY)).toBe(true);+ expect(redis.ops.some((o) => o[0] === 'del' && o[1] === RESERVATION_LEAK_REDIS_ALERT_KEY)).toBe(true);+ });++ it('USD leak: releases the reservation, records evidence, raises alert', async () => {+ const custodyRows = [{+ id: 7, agent_id: 'agentUSD', asset: 'USDC', usd: 0.05, category: 'x402',+ age_seconds: 5400, created_at: new Date().toISOString(),+ }];+ const released = [];+ const sql = mockSql({ custodyRows });+ const redis = mockRedis();+ const out = await run({+ sql, redis, ...noopReleasers,+ releaseSpendReservation: async (id, reason) => { released.push([id, reason]); },+ });++ expect(out.valueExtracted.leaked_total).toBe(1);+ expect(out.valueExtracted.usd_freed).toBe(0.05);+ expect(out.valueExtracted.agents_affected).toBe(1);+ expect(released).toEqual([[7, 'leak_detector_swept']]);++ const leakInsert = sql.calls.find((c) => /INSERT INTO spend_reservation_leaks/i.test(c.text));+ expect(leakInsert).toBeTruthy();+ expect(leakInsert.values).toContain('custody_event');+ expect(leakInsert.values).toContain('released');+ expect(redis.store.has(RESERVATION_LEAK_REDIS_ALERT_KEY)).toBe(true);+ });++ it('SOL leak: records evidence BEFORE releasing (delete is destructive)', async () => {+ const solRows = [{+ id: 99, agent_id: 'agentSOL', type: 'pumpfun.buy', sol_amount: 0.25,+ mint: 'THREEsynthetic1111', age_seconds: 7200, created_at: new Date().toISOString(),+ }];+ const order = [];+ const sql = (strings, ...values) => {+ const text = strings.join('?').replace(/\s+/g, ' ').trim();+ if (/INSERT INTO spend_reservation_leaks/i.test(text)) order.push('record');+ if (/FROM agent_actions/i.test(text)) return Promise.resolve(solRows);+ if (/FROM agent_custody_events/i.test(text)) return Promise.resolve([]);+ return Promise.resolve([]);+ };+ const out = await run({+ sql, redis: mockRedis(), ...noopReleasers,+ releaseSpend: async () => { order.push('release'); },+ });++ expect(out.valueExtracted.leaked_total).toBe(1);+ expect(out.valueExtracted.sol_freed).toBe(0.25);+ // The evidence must be persisted before the row is deleted.+ expect(order).toEqual(['record', 'release']);+ });++ it('schema DDL failure: graceful error outcome, still records a log row', async () => {+ const sql = mockSql({ failOn: /CREATE TABLE IF NOT EXISTS spend_reservation_leaks/i });+ const out = await run({ sql, redis: mockRedis(), ...noopReleasers });+ expect(out.success).toBe(false);+ expect(out.recorded).toBe(true);+ expect(out.errorMsg).toMatch(/schema_failed/);+ expect(sql.calls.some((c) => /INSERT INTO x402_autonomous_log/i.test(c.text))).toBe(true);+ });++ it('a failing scan never crashes the tick', async () => {+ const sql = mockSql({ failOn: /FROM agent_custody_events/i });+ const out = await run({ sql, redis: mockRedis(), ...noopReleasers });+ expect(out.success).toBe(true);+ expect(out.valueExtracted.scanned.custody_pending).toBe(0);+ });++ it('exposes stable constants', () => {+ expect(RESERVATION_LEAK_AGE_SECONDS).toBe(3600);+ expect(RESERVATION_LEAK_REDIS_ALERT_KEY).toBe('x402:reservation-leak:alert');+ });+});