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
fix(economy): alert when the treasury self-heal cannot run
nirholas86ac702279d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ca208444..59b293e18 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Payment Sessions, the developer platform, and the media APIs are now documented** — Three new developer guides: Payment Sessions (fund a capped spend envelope from prepaid credits and let an agent pay x402 services with a bearer token, no private key involved), the developer platform (API keys, usage metrics, signed webhooks, the one-call MCP connection test, and the public tool and skills catalogs), and the media and render API (avatar image renders, posed clip renders, the runtime GLB optimizer, the open model proxy, and the free vision and speech-to-text endpoints). Every endpoint ships with a runnable example. (`/docs/payment-sessions`) `[docs]`- **Runnable examples for the x402 fetch wrapper, the MCP server, and the avatar SDK** — Three example sets you can run as-is against live three.ws services: a zero-spend x402 discovery probe plus a key-gated real paid call, curl and plain Node walkthroughs of the full MCP session lifecycle including a free tool call, and a build-free HTML page that renders a live 3D avatar straight from the CDN. `[docs, sdk]`- **The pages that shipped without docs now have them** — Thirteen surfaces that launched with no guide are now fully documented: the Agent-Forged Gallery, Generation Watch, the KOL Tracker, the Character and Object Libraries, the Minted gallery, the Reasoning Ledger, the 3D history timeline, Daily Match, Agent Symphony, the notifications center, the creator portfolio, and the Token Screener. Each guide explains what the page shows, where every number comes from, and the public API behind it, and all of them are linked from the Start Here page. (`/docs/start-here`) `[docs]`+- **The treasury self-repair now reports when it cannot repair** — The platform keeps its automated payments funded by pulling idle funds back from its own agent wallets. When that repair could not run, it said nothing at all: no log line, no alert. A recent stall lasted about eleven hours for exactly that reason, with funds available the whole time and no way to see the repair was blocked. It now raises an alert, and distinguishes the two cases that look identical but need opposite responses: the network providers were unreachable (free to fix, nothing to fund), or every source really is empty (the only case that needs a top-up). `[infra, improvement]`## 2026-07-29diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.jsindex 40a1d7608..9ddf914c9 100644--- a/api/cron/treasury-topup.js+++ b/api/cron/treasury-topup.js@@ -81,8 +81,15 @@ export default wrapCron(async (req, res) => {// (~10k repeats each) while misreporting the count of genuinely dry engines.const masterAliased = [];// Fallback env vars can resolve two registry entries to the SAME wallet- // (e.g. x402-ring-payer falling back to the agent key) — top it up once.- const seenPubkeys = new Set();+ // (e.g. x402-ring-payer falling back to the agent key, or the circulation+ // treasury sharing the pump-cron-relayer key). Top a shared wallet up ONCE,+ // but judge it against the STRICTEST of its specs. First-spec-wins dedupe+ // silently dropped the later, higher floor: production 2026-07-30 had the+ // circulation treasury (floor 0.2, refill 0.5) deduped behind+ // pump-cron-relayer (floor 0.01), so the shared wallet at 0.012 SOL was+ // never a refill target, the deficit read zero, fuel never fired, and the+ // Money Pulse ran free-actions-only while the master held idle USDC.+ const byPubkey = new Map();for (const spec of SOLANA_SIGNERS) {if (spec.isMaster || spec.network === 'devnet') continue;const resolved = await resolveSignerPubkey(spec);@@ -95,22 +102,32 @@ export default wrapCron(async (req, res) => {masterAliased.push(spec.name);continue;}- if (seenPubkeys.has(resolved.pubkey)) continue;- seenPubkeys.add(resolved.pubkey);+ const refillToSol = spec.refillTo ?? spec.minSol * DEFAULT_REFILL_MULTIPLE;+ const merged = byPubkey.get(resolved.pubkey);+ if (!merged) {+ byPubkey.set(resolved.pubkey, { names: [spec.name], minSol: spec.minSol, refillToSol });+ } else {+ merged.names.push(spec.name);+ merged.minSol = Math.max(merged.minSol, spec.minSol);+ merged.refillToSol = Math.max(merged.refillToSol, refillToSol);+ }+ }+ for (const [pubkey, merged] of byPubkey) {+ const name = merged.names.join('+');let lamports;try {- lamports = await connection.getBalance(new PublicKey(resolved.pubkey), 'confirmed');+ lamports = await connection.getBalance(new PublicKey(pubkey), 'confirmed');} catch (e) {- errors.push({ name: spec.name, pubkey: resolved.pubkey, reason: `rpc_error: ${e.message}` });+ errors.push({ name, pubkey, reason: `rpc_error: ${e.message}` });continue;}const sol = lamports / LAMPORTS_PER_SOL;- if (sol >= spec.minSol) continue;+ if (sol >= merged.minSol) continue;targets.push({- name: spec.name,- pubkey: resolved.pubkey,+ name,+ pubkey,currentSol: Number(sol.toFixed(6)),- refillToSol: spec.refillTo ?? spec.minSol * DEFAULT_REFILL_MULTIPLE,+ refillToSol: merged.refillToSol,});}@@ -199,6 +216,51 @@ export default wrapCron(async (req, res) => {);}+ // A self-heal that CANNOT heal has to say so. Both reclaim legs return their+ // readErrors and failed sends in the HTTP response, and this cron's response+ // goes to Cloud Scheduler, which discards it, so until now a reclaim that was+ // blocked left no log line, no ledger row (the agent leg writes none on+ // failure, unlike the engine leg's `inflow_failed`) and no alert. On+ // 2026-07-29 that silence cost ~11 hours: every Solana RPC lane was in quota+ // cooldown, so the balance reads failed, no candidate was ever planned, and+ // 0.12 SOL sat reclaimable in agent wallets while the sponsor stayed under its+ // settle floor and every 402 challenge dropped its Solana accept.+ //+ // Two outcomes look identical from the master's balance and have OPPOSITE+ // remediations, so name which one happened:+ // blocked : we could not read or could not send. Nothing to fund; the RPC+ // tier is the problem. Free to fix, no owner money.+ // nothing : every source is genuinely at or below its floor. This is the+ // only case that needs the owner to send SOL.+ const reclaimedTotal = Number((reclaim.reclaimedSol + agentReclaim.reclaimedSol).toFixed(6));+ if (!dryRun && totalDeficitSol > 0 && reclaimedTotal < totalDeficitSol) {+ const readErrors = [...(reclaim.readErrors || []), ...(agentReclaim.readErrors || [])];+ const failedSends = [...(reclaim.failed || []), ...(agentReclaim.failed || [])];+ const legErrors = [reclaim.error, agentReclaim.error].filter(Boolean);+ const blocked = readErrors.length + failedSends.length + legErrors.length > 0;+ const sample = readErrors[0]?.reason || failedSends[0]?.reason || legErrors[0] || '';+ if (blocked) {+ await sendOpsAlert(+ '♻️ Economy self-heal BLOCKED: reclaim could not run',+ `Deficit ${totalDeficitSol.toFixed(4)} SOL, reclaimed only ${reclaimedTotal} SOL. ` ++ `${readErrors.length} balance read error(s), ${failedSends.length} failed send(s)` ++ `${legErrors.length ? `, ${legErrors.length} leg error(s)` : ''}. First: ${String(sample).slice(0, 180)}. ` ++ 'An `rpc_error` here means the Solana RPC tier is exhausted, NOT that the wallets are dry: ' ++ 'idle SOL may still be sitting in agent wallets that could not be read. Check ' ++ 'healthz rpc_lanes and the provider quotas before sending any funds.',+ { signature: 'economy-selfheal-blocked', severity: 'warn' },+ );+ } else {+ await sendOpsAlert(+ '⛽ Economy self-heal found nothing to reclaim',+ `Deficit ${totalDeficitSol.toFixed(4)} SOL and every reclaim source is at or below its floor ` ++ `(${(reclaim.skipped || []).length + (agentReclaim.skipped || []).length} source(s) skipped). ` ++ 'This is the case that genuinely needs funding: send SOL to the economy master.',+ { signature: 'economy-selfheal-nothing-to-reclaim', severity: 'warn' },+ );+ }+ }+// Self-healing, step 2 (revenue): if reclaim did not close the gap, convert a// small bounded slice of the master's own idle USDC into native SOL. The// circulation loop leaks SOL to fees every tick, so without a source the fundingdiff --git a/data/changelog.json b/data/changelog.jsonindex 649bee5d6..15b8824f3 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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-07-30",+ "title": "The treasury self-repair now reports when it cannot repair",+ "summary": "The platform keeps its automated payments funded by pulling idle funds back from its own agent wallets. When that repair could not run, it said nothing at all: no log line, no alert. A recent stall lasted about eleven hours for exactly that reason, with funds available the whole time and no way to see the repair was blocked. It now raises an alert, and distinguishes the two cases that look identical but need opposite responses: the network providers were unreachable (free to fix, nothing to fund), or every source really is empty (the only case that needs a top-up).",+ "tags": [+ "infra",+ "improvement"+ ]+ },{"date": "2026-07-30","title": "An underfunded trading bot now sits out instead of failing every trade",diff --git a/public/changelog.json b/public/changelog.jsonindex dce32425e..c30bbaad6 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T03:10:26.050Z",+ "generated_at": "2026-07-30T03:18:32.767Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -58,6 +58,17 @@"docs"]},+ {+ "date": "2026-07-30",+ "type": "update",+ "title": "The treasury self-repair now reports when it cannot repair",+ "summary": "The platform keeps its automated payments funded by pulling idle funds back from its own agent wallets. When that repair could not run, it said nothing at all: no log line, no alert. A recent stall lasted about eleven hours for exactly that reason, with funds available the whole time and no way to see the repair was blocked. It now raises an alert, and distinguishes the two cases that look identical but need opposite responses: the network providers were unreachable (free to fix, nothing to fund), or every source really is empty (the only case that needs a top-up).",+ "link": null,+ "tags": [+ "infra",+ "improvement"+ ]+ },{"date": "2026-07-29","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex f1348cf6f..b0b3e1bce 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>docs</category><description>Thirteen surfaces that launched with no guide are now fully documented: the Agent-Forged Gallery, Generation Watch, the KOL Tracker, the Character and Object Libraries, the Minted gallery, the Reasoning Ledger, the 3D history timeline, Daily Match, Agent Symphony, the notifications center, the creator portfolio, and the Token Screener. Each guide explains what the page shows, where every number comes from, and the public API behind it, and all of them are linked from the Start Here page.</description></item>+ <item>+ <title>The treasury self-repair now reports when it cannot repair</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-30:The treasury self-repair now reports when it cannot repair</guid>+ <pubDate>Thu, 30 Jul 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>The platform keeps its automated payments funded by pulling idle funds back from its own agent wallets. When that repair could not run, it said nothing at all: no log line, no alert. A recent stall lasted about eleven hours for exactly that reason, with funds available the whole time and no way to see the repair was blocked. It now raises an alert, and distinguishes the two cases that look identical but need opposite responses: the network providers were unreachable (free to fix, nothing to fund), or every source really is empty (the only case that needs a top-up).</description>+ </item><item><title>Generation Watch</title><link>https://three.ws/watch</link>diff --git a/public/features.json b/public/features.jsonindex dbfb11cd7..b00397ffd 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T03:10:26.042Z",+ "generated_at": "2026-07-30T03:18:32.760Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/treasury-selfheal-visibility.test.js b/tests/treasury-selfheal-visibility.test.jsnew file mode 100644index 000000000..8f09f84ac--- /dev/null+++ b/tests/treasury-selfheal-visibility.test.js@@ -0,0 +1,195 @@+// A self-heal that cannot heal has to say so, and it has to say WHICH failure+// it hit, because the two have opposite remediations.+//+// On 2026-07-29 the sponsor sat under its SOL settle floor for ~11 hours while+// 0.12 SOL sat reclaimable in platform agent wallets. Every Solana RPC lane was+// in quota cooldown, so reclaim's balance reads failed and no candidate was ever+// planned. Both reclaim legs return their readErrors and failed sends in the+// cron's HTTP response, and that response goes to Cloud Scheduler, which+// discards it: no log line, no alert, and (for the agent leg) no ledger row+// either. Six hours of app logs mentioned neither "reclaim" nor "rpc_error".+//+// So the operator-visible difference this pins down:+// BLOCKED: could not read or could not send. The RPC tier is the problem and+// it is free to fix. Sending funds would be the wrong move, and may+// not even be needed: idle SOL may be sitting in unreadable wallets.+// NOTHING: every source is genuinely at or below its floor. This is the only+// case that needs the owner to spend money.+//+// Runs the real handler WITHOUT ?dry=1 (the alerts only fire on a live tick),+// with every money path mocked so nothing moves.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const { MASTER, ENGINE } = vi.hoisted(() => ({+ MASTER: 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW',+ ENGINE: 'EngineEngineEngineEngineEngineEngineEngine1',+}));++// Mutable per-test reclaim outcomes.+const legs = vi.hoisted(() => ({+ engine: { reclaimedSol: 0, moves: [], skipped: [], failed: [], readErrors: [] },+ agent: { reclaimedSol: 0, moves: [], skipped: [], failed: [], readErrors: [] },+}));++vi.mock('../api/_lib/solana-signers.js', () => ({+ SOLANA_SIGNERS: [+ { name: 'economy-master', env: 'ECONOMY_MASTER_SECRET_BASE58', isMaster: true, minSol: 0.05, network: 'mainnet' },+ ],+ resolveSignerPubkey: vi.fn(async () => ({ configured: true, pubkey: MASTER })),+}));++vi.mock('../api/_lib/economy-master.js', () => ({+ ECONOMY_MASTER_ADDRESS: MASTER,+ RESERVE_SOL: 0.05,+ RUN_CAP_SOL: 0.5,+ PER_TOPUP_MAX_SOL: 0.2,+ sweepTopUps: vi.fn(async () => ({+ configured: true, plan: [], skipped: [], rejected: [], funded: [], failed: [],+ spentSol: 0, masterSol: 0.0038, spendableSol: 0,+ })),+}));++vi.mock('../api/_lib/economy-ledger.js', () => ({ recordSweep: vi.fn(async () => ({ wrote: 0 })) }));+vi.mock('../api/_lib/economy-fuel.js', () => ({+ refuelMasterFromUsdc: vi.fn(async () => ({ acted: false, reason: 'no_spare_usdc' })),+}));+vi.mock('../api/_lib/economy-usdc-topup.js', () => ({+ topUpUsdcEngines: vi.fn(async () => ({ acted: false, reason: 'not_needed' })),+}));+vi.mock('../api/_lib/economy-sweepback.js', () => ({+ reclaimIdleSol: vi.fn(async () => legs.engine),+ reclaimIdleAgentSol: vi.fn(async () => legs.agent),+}));++const sendOpsAlert = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('../api/_lib/alerts.js', () => ({ sendOpsAlert }));++vi.mock('../api/_lib/solana/connection.js', () => ({+ // The master sits under RESERVE_SOL + operating headroom, so there is a real+ // deficit and both reclaim legs are reached. This is the 07-29 balance.+ solanaConnection: () => ({ getBalance: vi.fn(async () => 3_843_137) }),+}));++import handler from '../api/cron/treasury-topup.js';++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: null,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this.writableEnded = true; },+ writableEnded: false,+ headersSent: false,+ };+}++async function runTick() {+ const res = mockRes();+ await handler(+ {+ method: 'POST',+ url: '/api/cron/treasury-topup',+ headers: { authorization: 'Bearer test-cron-secret' },+ socket: { remoteAddress: '127.0.0.1' },+ },+ res,+ );+ return JSON.parse(res._body);+}++const alertTitles = () => sendOpsAlert.mock.calls.map((c) => String(c[0]));+const alertFor = (needle) => sendOpsAlert.mock.calls.find((c) => String(c[0]).includes(needle));++beforeEach(() => {+ process.env.CRON_SECRET = 'test-cron-secret';+ sendOpsAlert.mockClear();+ legs.engine = { reclaimedSol: 0, moves: [], skipped: [], failed: [], readErrors: [] };+ legs.agent = { reclaimedSol: 0, moves: [], skipped: [], failed: [], readErrors: [] };+});++describe('treasury-topup surfaces a self-heal that could not run', () => {+ it('reports BLOCKED, and does not ask for money, when the RPC reads failed', () => {+ legs.agent = {+ reclaimedSol: 0, moves: [], skipped: [], failed: [],+ readErrors: [+ { name: 'Atlas #22', reason: 'rpc_error: solana rpc 429 @ https://mainnet.helius-rpc.com' },+ { name: 'Echo #22', reason: 'rpc_error: solana rpc 403 @ https://solana-rpc.publicnode.com' },+ ],+ };+ return runTick().then(() => {+ const call = alertFor('BLOCKED');+ expect(call, `no BLOCKED alert in ${JSON.stringify(alertTitles())}`).toBeTruthy();+ expect(call[1]).toMatch(/2 balance read error\(s\)/);+ expect(call[1]).toMatch(/helius-rpc\.com/);+ // The whole point: an rpc_error must not read as "the wallets are dry".+ expect(call[1]).toMatch(/NOT that the wallets are dry/);+ expect(call[2]).toMatchObject({ signature: 'economy-selfheal-blocked' });+ // And it must NOT tell the operator to send funds.+ expect(alertTitles().join(' ')).not.toMatch(/nothing to reclaim/);+ });+ });++ it('reports BLOCKED when the reads worked but every send failed', async () => {+ legs.agent = {+ reclaimedSol: 0, moves: [], skipped: [], failed: [+ { name: 'Atlas #22', sol: 0.068, reason: 'blockhash not found' },+ ],+ readErrors: [],+ };+ await runTick();+ const call = alertFor('BLOCKED');+ expect(call).toBeTruthy();+ expect(call[1]).toMatch(/1 failed send\(s\)/);+ expect(call[1]).toMatch(/blockhash not found/);+ });++ it('reports NOTHING TO RECLAIM, the only case that needs owner funding', async () => {+ legs.engine = {+ reclaimedSol: 0, moves: [], failed: [], readErrors: [],+ skipped: [{ name: 'pump-x402-launcher', reason: 'at_or_below_floor' }],+ };+ legs.agent = {+ reclaimedSol: 0, moves: [], failed: [], readErrors: [],+ skipped: [+ { name: 'three', reason: 'at_or_below_floor' },+ { name: 'Swarm 5', reason: 'capital_committed' },+ ],+ };+ await runTick();+ const call = alertFor('nothing to reclaim');+ expect(call, `no funding alert in ${JSON.stringify(alertTitles())}`).toBeTruthy();+ expect(call[1]).toMatch(/3 source\(s\) skipped/);+ expect(call[1]).toMatch(/send SOL to the economy master/);+ expect(call[2]).toMatchObject({ signature: 'economy-selfheal-nothing-to-reclaim' });+ expect(alertTitles().join(' ')).not.toMatch(/BLOCKED/);+ });++ it('stays quiet when the reclaim actually covered the deficit', async () => {+ // 0.2 SOL against a ~0.196 SOL deficit: healed, so neither alert fires.+ legs.agent = { reclaimedSol: 0.2, moves: [{ name: 'Atlas #22', address: 'x', sol: 0.2 }], skipped: [], failed: [], readErrors: [] };+ await runTick();+ expect(alertTitles().join(' ')).not.toMatch(/BLOCKED|nothing to reclaim/);+ });++ it('never fires on a dry run: a preview must not page anyone', async () => {+ legs.agent = {+ reclaimedSol: 0, moves: [], skipped: [], failed: [],+ readErrors: [{ name: 'Atlas #22', reason: 'rpc_error: solana rpc 429' }],+ };+ const res = mockRes();+ await handler(+ {+ method: 'POST',+ url: '/api/cron/treasury-topup?dry=1',+ headers: { authorization: 'Bearer test-cron-secret' },+ socket: { remoteAddress: '127.0.0.1' },+ },+ res,+ );+ expect(JSON.parse(res._body).dry_run).toBe(true);+ expect(alertTitles().join(' ')).not.toMatch(/BLOCKED|nothing to reclaim/);+ });+});