Skip to content

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

fix(economy): reclaim idle SOL from platform agent wallets so the fee wallet self-heals

nirholasd6a7bf2a4d46
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f5001a15..f04c8131a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-28
- **Coin pages are back, and they can no longer be taken down by an expired market-data key** — Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else. (`/coins`) `[fix, infra]`
+- **The agent economy now refills its own fuel tank instead of quietly running dry** — The live activity feed on /pulse had gone almost silent, and the cause turned out to be a plumbing problem rather than a lack of money. The platform funds its agents by sending them SOL to trade and launch with, but that path only ever ran one way. Agents kept what they were given plus whatever their trades returned, and the small shared wallet that pays the network fee on every agent-to-agent payment had no way to get any of it back. It eventually fell a fraction of a cent below the minimum it needs to sign a transaction, and every paid request across the platform started failing, even though the wider fleet was holding plenty. The funding cycle is now a full loop: when the fee wallet runs short, the platform automatically pulls idle SOL back from its own agent wallets to cover the gap. Agents that are actively trading keep their trading capital, agents holding an open position are left alone entirely, and wallets belonging to real users are never touched. We also added an audit tool that reports where every lamport in the fleet is sitting and where it has been moving. (`/pulse`) `[fix, infra]`
## 2026-07-27
diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.js
index c2d12412e..5ede2b1e3 100644
--- a/api/_lib/economy-sweepback.js
+++ b/api/_lib/economy-sweepback.js
@@ -418,6 +418,223 @@ export async function reclaimIdleSol({ connection, network = 'mainnet', dryRun =
};
}
+// ── platform AGENT wallet reclaim ────────────────────────────────────────────
+//
+// reclaimIdleSol above walks the SOLANA_SIGNERS registry — the eight engine
+// wallets. Agent custody wallets are a different universe and were structurally
+// invisible to every return path: `fundAgentForLaunch` moves SOL master → agent
+// one way, and nothing ever moved it back. Snipes recycle ~97% of their capital
+// but the proceeds land in the AGENT wallet, so each cycle ratcheted SOL further
+// from the engines until the master could not pay a 5,036-lamport settle fee.
+// Audited 2026-07-28: 7.2 of the fleet's 7.53 SOL sat in agent wallets while the
+// engines held 0.31 and the whole x402 rail 503'd. This closes that loop.
+//
+// The ownership boundary is the load-bearing part. Only wallets belonging to
+// PLATFORM-OWNED agents may be swept — the `three-ws` house account and the
+// `*@agents.three.ws` circulation bots, which api/_lib/launcher-engine.js
+// documents as "platform-created bot accounts … never real end users". A
+// customer's agent is never touched, and the SQL gate plus a redundant in-JS
+// re-check make that true even if the query is later edited.
+
+/** House account that owns the platform's own (non-bot) agents. */
+export const PLATFORM_AGENT_OWNER_EMAIL = '[email protected]';
+/** Email suffix of the platform-created circulation bot accounts. */
+export const PLATFORM_AGENT_EMAIL_SUFFIX = '@agents.three.ws';
+
+/** Floor left on an idle platform agent — enough to sign its own transactions. */
+const AGENT_IDLE_FLOOR_SOL = num('AGENT_RECLAIM_IDLE_FLOOR_SOL', 0.005);
+/** A trading agent keeps this many trades' worth of working capital. */
+const AGENT_ACTIVE_TRADE_MULTIPLE = num('AGENT_RECLAIM_TRADE_MULTIPLE', 2);
+/** Wallets touched per run — keeps the cron bounded and its fee cost predictable. */
+const AGENT_RECLAIM_MAX_WALLETS = num('AGENT_RECLAIM_MAX_WALLETS', 40);
+
+/**
+ * Operating floor for one platform agent. An agent running an ENABLED sniper
+ * strategy keeps enough for `AGENT_RECLAIM_TRADE_MULTIPLE` trades at its own
+ * configured size, so reclaim can never starve a working trader; an agent with
+ * no enabled strategy keeps only transaction-fee headroom. Pure.
+ *
+ * @param {{enabled?:boolean, perTradeSol?:number}} strategy
+ * @returns {number} floor in SOL
+ */
+export function agentReclaimFloorSol(strategy = {}) {
+ if (!strategy.enabled) return AGENT_IDLE_FLOOR_SOL;
+ const perTrade = Number(strategy.perTradeSol);
+ if (!Number.isFinite(perTrade) || perTrade <= 0) return AGENT_IDLE_FLOOR_SOL;
+ return round(Math.max(AGENT_IDLE_FLOOR_SOL, perTrade * AGENT_ACTIVE_TRADE_MULTIPLE));
+}
+
+/**
+ * Size the per-agent reclaim. Pure, so the safety invariants are unit-testable
+ * without a database or an RPC.
+ *
+ * Invariants:
+ * · a non-platform owner is NEVER planned, whatever the balance
+ * · an agent with committed capital (an open position) is never planned
+ * · a planned agent always retains at least its floor (via reclaimableSol)
+ *
+ * @param {Array<{agentId:string,name:string,address:string,owner:string,sol:number,openPositions?:number,strategy?:{enabled?:boolean,perTradeSol?:number}}>} candidates
+ * @param {{minSweepSol?:number, maxWallets?:number}} [opts]
+ * @returns {{plan:Array<{agentId:string,name:string,address:string,sol:number,floorSol:number}>, skipped:Array<{name:string,reason:string}>, totalSol:number}}
+ */
+export function planAgentReclaim(candidates, opts = {}) {
+ const minSweep = Number.isFinite(opts.minSweepSol) ? opts.minSweepSol : MIN_SWEEP_SOL;
+ const maxWallets = Number.isFinite(opts.maxWallets) ? opts.maxWallets : AGENT_RECLAIM_MAX_WALLETS;
+ const plan = [];
+ const skipped = [];
+ let total = 0;
+ for (const c of candidates) {
+ if (!isPlatformOwnedAgent(c.owner)) {
+ skipped.push({ name: c.name, reason: 'not_platform_owned' });
+ continue;
+ }
+ if (Number(c.openPositions) > 0) {
+ skipped.push({ name: c.name, reason: 'capital_committed' });
+ continue;
+ }
+ if (c.address === ECONOMY_MASTER_ADDRESS) {
+ skipped.push({ name: c.name, reason: 'is_master' });
+ continue;
+ }
+ const floorSol = agentReclaimFloorSol(c.strategy);
+ const reclaimable = reclaimableSol(c.sol, floorSol, minSweep);
+ if (reclaimable <= 0) {
+ skipped.push({ name: c.name, reason: 'at_or_below_floor' });
+ continue;
+ }
+ if (plan.length >= maxWallets) {
+ skipped.push({ name: c.name, reason: 'run_cap_reached' });
+ continue;
+ }
+ plan.push({ agentId: c.agentId, name: c.name, address: c.address, sol: reclaimable, floorSol });
+ total = round(total + reclaimable);
+ }
+ return { plan, skipped, totalSol: total };
+}
+
+/**
+ * True only for the platform's own agent-owner accounts. Anything else — a real
+ * signup, a wallet-auth account, an unknown value — is a customer and is out.
+ * @param {string|null|undefined} ownerEmail
+ */
+export function isPlatformOwnedAgent(ownerEmail) {
+ if (!ownerEmail || typeof ownerEmail !== 'string') return false;
+ const email = ownerEmail.trim().toLowerCase();
+ return email === PLATFORM_AGENT_OWNER_EMAIL || email.endsWith(PLATFORM_AGENT_EMAIL_SUFFIX);
+}
+
+/**
+ * Pull idle SOL out of PLATFORM-OWNED agent custody wallets back to the economy
+ * master, so the fee wallet refills itself from capital the platform already owns
+ * instead of waiting on an external top-up. Destination is the same hard-locked
+ * ECONOMY_MASTER_ADDRESS constant every other sweep uses; no parameter redirects it.
+ *
+ * @param {object} args
+ * @param {import('@solana/web3.js').Connection} args.connection
+ * @param {'mainnet'|'devnet'} [args.network]
+ * @param {boolean} [args.dryRun]
+ * @param {number} [args.maxWallets]
+ * @returns {Promise<{master:string, reclaimedSol:number, moves:Array, skipped:Array, failed:Array, readErrors:Array}>}
+ */
+export async function reclaimIdleAgentSol({ connection, network = 'mainnet', dryRun = false, maxWallets } = {}) {
+ const { PublicKey } = await import('@solana/web3.js');
+ const { sql } = await import('./db.js');
+ const master = ECONOMY_MASTER_ADDRESS;
+ const moves = [];
+ const failed = [];
+ const readErrors = [];
+
+ // Ownership is enforced in SQL first so a customer's agent never even leaves
+ // the database, and again in planAgentReclaim() so an edit here cannot widen
+ // the blast radius on its own.
+ const rows = await sql`
+ SELECT a.id AS agent_id,
+ a.name AS name,
+ a.meta->>'solana_address' AS address,
+ a.meta->>'encrypted_solana_secret' AS secret,
+ LOWER(u.email) AS owner,
+ s.enabled AS strategy_enabled,
+ s.per_trade_lamports AS per_trade_lamports,
+ (SELECT COUNT(*) FROM agent_sniper_positions p
+ WHERE p.agent_id = a.id AND p.status IN ('open', 'closing'))::int AS open_positions
+ FROM agent_identities a
+ JOIN users u ON u.id = a.user_id
+ LEFT JOIN agent_sniper_strategies s ON s.agent_id = a.id AND s.network = ${network}
+ WHERE a.deleted_at IS NULL
+ AND a.meta->>'solana_address' IS NOT NULL
+ AND a.meta->>'encrypted_solana_secret' IS NOT NULL
+ AND (LOWER(u.email) = ${PLATFORM_AGENT_OWNER_EMAIL}
+ OR LOWER(u.email) LIKE ${'%' + PLATFORM_AGENT_EMAIL_SUFFIX})
+ `;
+
+ const candidates = [];
+ for (const r of rows) {
+ let sol;
+ try {
+ sol = round((await connection.getBalance(new PublicKey(r.address), 'confirmed')) / LAMPORTS_PER_SOL);
+ } catch (e) {
+ readErrors.push({ name: r.name, address: r.address, reason: `rpc_error: ${e?.message}` });
+ continue;
+ }
+ candidates.push({
+ agentId: r.agent_id,
+ name: r.name || 'Agent',
+ address: r.address,
+ owner: r.owner,
+ secret: r.secret,
+ sol,
+ openPositions: r.open_positions,
+ strategy: {
+ enabled: Boolean(r.strategy_enabled),
+ perTradeSol: r.per_trade_lamports != null ? Number(r.per_trade_lamports) / LAMPORTS_PER_SOL : 0,
+ },
+ });
+ }
+ // Biggest balances first: the run cap should spend its budget where the SOL is.
+ candidates.sort((a, b) => b.sol - a.sol);
+
+ const { plan, skipped, totalSol } = planAgentReclaim(candidates, { maxWallets });
+ if (dryRun) {
+ return { master, reclaimedSol: totalSol, moves: plan.map((p) => ({ ...p, dryRun: true })), skipped, failed, readErrors };
+ }
+
+ const secrets = new Map(candidates.map((c) => [c.agentId, c.secret]));
+ const { recoverSolanaAgentKeypair } = await import('./agent-wallet.js');
+ for (const p of plan) {
+ try {
+ const keypair = await recoverSolanaAgentKeypair(secrets.get(p.agentId), {
+ agentId: p.agentId,
+ reason: 'economy_reclaim',
+ meta: { to: master, sol: p.sol },
+ });
+ if (keypair.publicKey.toBase58() !== p.address) {
+ failed.push({ name: p.name, address: p.address, sol: p.sol, reason: 'keypair_address_mismatch' });
+ continue;
+ }
+ const signature = await sendSol({
+ connection,
+ fromKeypair: keypair,
+ to: master,
+ lamports: Math.round(p.sol * LAMPORTS_PER_SOL),
+ memo: `three.ws reclaim ${p.name} → economy-master`,
+ network,
+ });
+ moves.push({ ...p, signature });
+ } catch (e) {
+ failed.push({ name: p.name, address: p.address, sol: p.sol, reason: e?.message || 'send_failed' });
+ }
+ }
+
+ return {
+ master,
+ reclaimedSol: round(moves.reduce((s, m) => s + m.sol, 0)),
+ moves,
+ skipped,
+ failed,
+ readErrors,
+ };
+}
+
function round(n) {
return Math.round(n * 1e9) / 1e9;
}
diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.js
index 8c8aff4fb..cc6e7473f 100644
--- a/api/cron/treasury-topup.js
+++ b/api/cron/treasury-topup.js
@@ -35,7 +35,7 @@ import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';
import { sweepTopUps, RESERVE_SOL, RUN_CAP_SOL, PER_TOPUP_MAX_SOL, ECONOMY_MASTER_ADDRESS } from '../_lib/economy-master.js';
import { recordSweep } from '../_lib/economy-ledger.js';
import { refuelMasterFromUsdc } from '../_lib/economy-fuel.js';
-import { reclaimIdleSol } from '../_lib/economy-sweepback.js';
+import { reclaimIdleSol, reclaimIdleAgentSol } from '../_lib/economy-sweepback.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
// How high to lift an engine when it falls below its floor, unless the spec
@@ -174,6 +174,30 @@ export default wrapCron(async (req, res) => {
);
}
+ // Self-healing, step 1b (the other half of the fleet's SOL): the engine reclaim
+ // above only walks the SOLANA_SIGNERS registry. Most of the platform's SOL lives
+ // one layer down, in PLATFORM-OWNED agent custody wallets, which had no return
+ // path at all — master → agent funding is one-way and snipe proceeds settle back
+ // into the agent, never the master. Without this the fleet can hold plenty of SOL
+ // while the fee wallet starves under its settle floor (audited 2026-07-28: 7.2 of
+ // 7.53 SOL stranded in agent wallets, engines at 0.31, rail fully 503). Customer
+ // agents are never touched — see reclaimIdleAgentSol's ownership gate.
+ let agentReclaim = { reclaimedSol: 0, moves: [], skipped: [], failed: [] };
+ if (totalDeficitSol > 0 && reclaim.reclaimedSol < totalDeficitSol) {
+ try {
+ agentReclaim = await reclaimIdleAgentSol({ connection, network: 'mainnet', dryRun });
+ } catch (e) {
+ agentReclaim = { reclaimedSol: 0, moves: [], skipped: [], failed: [], error: e?.message || 'agent_reclaim_failed' };
+ }
+ }
+ if (agentReclaim.reclaimedSol > 0 && !dryRun) {
+ await sendOpsAlert(
+ `♻️ Economy master reclaimed idle agent SOL`,
+ `pulled ${agentReclaim.reclaimedSol} SOL back from ${agentReclaim.moves.length} platform agent wallet(s) to cover a ${totalDeficitSol.toFixed(3)} SOL deficit.`,
+ { signature: `economy-agent-reclaim:${agentReclaim.moves.map((m) => m.address).join(',')}` },
+ );
+ }
+
// 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 funding
@@ -212,6 +236,7 @@ export default wrapCron(async (req, res) => {
master_deficit_sol: Number(masterDeficitSol.toFixed(6)),
master_operating_sol: masterOperatingSol,
reclaim,
+ agent_reclaim: agentReclaim,
fuel,
master_aliased: masterAliased,
read_errors: errors,
@@ -306,6 +331,7 @@ export default wrapCron(async (req, res) => {
master_sol: result.masterSol ?? null,
master_deficit_sol: Number(masterDeficitSol.toFixed(6)),
reclaim,
+ agent_reclaim: agentReclaim,
fuel,
master_aliased: masterAliased,
read_errors: errors,
diff --git a/data/changelog.json b/data/changelog.json
index a9031f9f9..75e11aed6 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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-28",
+ "title": "The agent economy now refills its own fuel tank instead of quietly running dry",
+ "summary": "The live activity feed on /pulse had gone almost silent, and the cause turned out to be a plumbing problem rather than a lack of money. The platform funds its agents by sending them SOL to trade and launch with, but that path only ever ran one way. Agents kept what they were given plus whatever their trades returned, and the small shared wallet that pays the network fee on every agent-to-agent payment had no way to get any of it back. It eventually fell a fraction of a cent below the minimum it needs to sign a transaction, and every paid request across the platform started failing, even though the wider fleet was holding plenty. The funding cycle is now a full loop: when the fee wallet runs short, the platform automatically pulls idle SOL back from its own agent wallets to cover the gap. Agents that are actively trading keep their trading capital, agents holding an open position are left alone entirely, and wallets belonging to real users are never touched. We also added an audit tool that reports where every lamport in the fleet is sitting and where it has been moving.",
+ "tags": [
+ "fix",
+ "infra"
+ ],
+ "link": "/pulse"
+ },
{
"date": "2026-07-28",
"title": "Coin pages are back, and they can no longer be taken down by an expired market-data key",
diff --git a/docs/economy-master.md b/docs/economy-master.md
index 9f65a8252..c9a996ed1 100644
--- a/docs/economy-master.md
+++ b/docs/economy-master.md
@@ -105,6 +105,74 @@ when there was nothing to collect. Dust guard: a sweep below
`ECONOMY_SWEEPBACK_MIN_SOL` (default 0.01 SOL) is skipped so fees never exceed
the return.
+## Agent-wallet reclaim: the other half of the fleet's SOL
+
+Sweepback and `reclaimIdleSol` both walk the **`SOLANA_SIGNERS` registry** — the
+eight engine wallets. That is not where most of the platform's SOL lives.
+`fundAgentForLaunch` ([`api/_lib/launcher-funding.js`](../api/_lib/launcher-funding.js))
+moves SOL master → **agent custody wallet** one way, and nothing ever moved it
+back: snipes recycle ~97 % of their capital, but the proceeds settle into the
+*agent's* wallet, so every cycle ratcheted SOL further from the engines.
+
+A full fleet audit on 2026-07-28 measured the result: **7.2 of the fleet's
+7.53 SOL sat in agent wallets while the eight engines held 0.31**, the master was
+25,461 lamports under its 0.004 SOL settle floor, and every x402 settle returned
+`fee_wallet_below_floor`. Nothing had leaked — fee burn over the whole week was
+0.141 SOL and lifetime sniper P&L was −0.15 SOL. The capital was simply somewhere
+the return path could not reach.
+
+`reclaimIdleAgentSol()` closes that loop. It runs inside
+[`/api/cron/treasury-topup`](../api/cron/treasury-topup.js) as self-healing step
+1b, only when there is a real deficit that the engine reclaim did not already
+cover, and reports under `agent_reclaim` in the cron's JSON.
+
+**The ownership boundary is the load-bearing guard.** Only wallets belonging to
+platform-owned agents are ever eligible:
+
+| Owner account | Swept? |
+| --- | --- |
+| `[email protected]` (the house account) | yes |
+| `*@agents.three.ws` (platform-created circulation bots) | yes |
+| Any signup account, wallet-auth account, or other email | **never** |
+
+That gate is enforced twice — once in SQL so a customer's agent never leaves the
+database, and again in `planAgentReclaim()` via `isPlatformOwnedAgent()` so a
+later edit to the query cannot widen the blast radius on its own. The destination
+is the same `ECONOMY_MASTER_ADDRESS` module constant every other sweep uses, never
+a parameter.
+
+Three more guards bound what it takes:
+
+- **Working capital is protected.** An agent with an *enabled* sniper strategy
+ keeps `AGENT_RECLAIM_TRADE_MULTIPLE` (default 2) times its own configured
+ per-trade size, so reclaim can never starve an agent that is actively trading.
+ An agent with no enabled strategy keeps only `AGENT_RECLAIM_IDLE_FLOOR_SOL`
+ (default 0.005) of transaction-fee headroom.
+- **Committed capital is untouchable.** Any agent holding an `open` or `closing`
+ sniper position is skipped outright (`capital_committed`).
+- **Bounded and non-oscillating.** At most `AGENT_RECLAIM_MAX_WALLETS` (default
+ 40) wallets per run, biggest balances first, and each sweep is sized by the same
+ `reclaimableSol()` invariant the engine reclaim uses — the agent is always left
+ at floor *plus* a buffer, so a topup can never immediately re-fund a wallet
+ reclaim just emptied.
+
+Sweeps below `ECONOMY_SWEEPBACK_MIN_SOL` (0.01 SOL) are skipped as dust.
+
+To see what a run would do without moving anything:
+
+```bash
+curl -s -H "Authorization: Bearer $CRON_SECRET" \
+ 'https://three.ws/api/cron/treasury-topup?dry=1' | jq .agent_reclaim
+```
+
+To audit where the fleet's SOL actually is at any time, including the split
+between platform and customer wallets:
+
+```bash
+node scripts/audit-wallet-flows.mjs # balances + reconciliation
+node scripts/audit-wallet-flows.mjs --trace <pubkey> # per-wallet flow trace
+```
+
## Fuel: refilling the root from revenue
Topup and sweepback only move SOL that already exists in the fleet. But the
diff --git a/public/changelog.json b/public/changelog.json
index b3a82d24a..a6b98012a 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-28T01:50:53.710Z",
+ "generated_at": "2026-07-28T16:26:43.334Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -17,6 +17,17 @@
"infra"
]
},
+ {
+ "date": "2026-07-28",
+ "type": "update",
+ "title": "The agent economy now refills its own fuel tank instead of quietly running dry",
+ "summary": "The live activity feed on /pulse had gone almost silent, and the cause turned out to be a plumbing problem rather than a lack of money. The platform funds its agents by sending them SOL to trade and launch with, but that path only ever ran one way. Agents kept what they were given plus whatever their trades returned, and the small shared wallet that pays the network fee on every agent-to-agent payment had no way to get any of it back. It eventually fell a fraction of a cent below the minimum it needs to sign a transaction, and every paid request across the platform started failing, even though the wider fleet was holding plenty. The funding cycle is now a full loop: when the fee wallet runs short, the platform automatically pulls idle SOL back from its own agent wallets to cover the gap. Agents that are actively trading keep their trading capital, agents holding an open position are left alone entirely, and wallets belonging to real users are never touched. We also added an audit tool that reports where every lamport in the fleet is sitting and where it has been moving.",
+ "link": "/pulse",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-27",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c8b36c42a..5f4773753 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>Every coin profile page was returning an error. The market-data provider we read prices and coin details from gives us a monthly call allowance, and once it ran out, every request we sent with our key was refused. The awkward part: the exact same request sent without the key was still being answered. We were effectively locking ourselves out. The pages are live again, and the fix is permanent rather than a one-off: when the key gets refused, we now set it aside for a while and retry the same request without it, so the pages keep serving and recover on their own when the allowance resets. We also repaired a 3D model service that was crash-looping because it tried to download a small config file from a public model host on every start and kept getting throttled. That file now ships with our own model storage, so the service starts without depending on anyone else.</description>
</item>
+ <item>
+ <title>The agent economy now refills its own fuel tank instead of quietly running dry</title>
+ <link>https://three.ws/pulse</link>
+ <guid isPermaLink="false">2026-07-28:The agent economy now refills its own fuel tank instead of quietly running dry</guid>
+ <pubDate>Tue, 28 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The live activity feed on /pulse had gone almost silent, and the cause turned out to be a plumbing problem rather than a lack of money. The platform funds its agents by sending them SOL to trade and launch with, but that path only ever ran one way. Agents kept what they were given plus whatever their trades returned, and the small shared wallet that pays the network fee on every agent-to-agent payment had no way to get any of it back. It eventually fell a fraction of a cent below the minimum it needs to sign a transaction, and every paid request across the platform started failing, even though the wider fleet was holding plenty. The funding cycle is now a full loop: when the fee wallet runs short, the platform automatically pulls idle SOL back from its own agent wallets to cover the gap. Agents that are actively trading keep their trading capital, agents holding an open position are left alone entirely, and wallets belonging to real users are never touched. We also added an audit tool that reports where every lamport in the fleet is sitting and where it has been moving.</description>
+ </item>
<item>
<title>3D generations that run long now hand back a handle instead of an error</title>
<link>https://three.ws/docs/mcp-studio</link>
diff --git a/public/features.json b/public/features.json
index f44fe53e6..5271fd7f9 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-28T01:50:53.698Z",
+ "generated_at": "2026-07-28T16:26:43.328Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/economy-sweepback.test.js b/tests/economy-sweepback.test.js
index a48ee6dae..712d7a22b 100644
--- a/tests/economy-sweepback.test.js
+++ b/tests/economy-sweepback.test.js
@@ -10,6 +10,10 @@ import {
reclaimableSol,
MIN_SWEEP_SOL,
DRAIN_HEADROOM_LAMPORTS,
+ planAgentReclaim,
+ agentReclaimFloorSol,
+ isPlatformOwnedAgent,
+ PLATFORM_AGENT_OWNER_EMAIL,
} from '../api/_lib/economy-sweepback.js';
// reclaimableSol: the emergency consolidation's sizing. The load-bearing property
@@ -189,3 +193,92 @@ test('ledger rows: hash-chainable with the same hashEntry the topup uses', () =>
prev = hash;
}
});
+
+// ── platform agent reclaim ───────────────────────────────────────────────────
+// The agent-wallet reclaim closes the one-way master → agent funding path that
+// stranded 7.2 of the fleet's 7.53 SOL while the fee wallet sat under its settle
+// floor. Its safety story is entirely in these pure functions: who may be swept,
+// and how much must be left behind.
+
+const PLATFORM = PLATFORM_AGENT_OWNER_EMAIL;
+const BOT = '[email protected]';
+
+test('isPlatformOwnedAgent accepts only house and bot accounts', () => {
+ assert.equal(isPlatformOwnedAgent(PLATFORM), true);
+ assert.equal(isPlatformOwnedAgent(BOT), true);
+ assert.equal(isPlatformOwnedAgent('[email protected]'), true); // case-insensitive
+ // Customers, in every shape they appear in the users table.
+ assert.equal(isPlatformOwnedAgent('[email protected]'), false);
+ assert.equal(isPlatformOwnedAgent('[email protected]'), false);
+ assert.equal(isPlatformOwnedAgent('[email protected]'), false);
+ // Near-miss domains must not squeak through a suffix check.
+ assert.equal(isPlatformOwnedAgent('[email protected]'), false);
+ assert.equal(isPlatformOwnedAgent(null), false);
+ assert.equal(isPlatformOwnedAgent(''), false);
+ assert.equal(isPlatformOwnedAgent(undefined), false);
+});
+
+test('agentReclaimFloorSol leaves a working trader its trade capital', () => {
+ // An enabled strategy keeps 2x its own per-trade size, so reclaim can never
+ // starve an agent that is actively trading.
+ assert.ok(agentReclaimFloorSol({ enabled: true, perTradeSol: 0.05 }) >= 0.1);
+ assert.ok(agentReclaimFloorSol({ enabled: true, perTradeSol: 0.207 }) >= 0.414);
+ // No enabled strategy → only fee headroom is retained.
+ const idle = agentReclaimFloorSol({ enabled: false, perTradeSol: 0.5 });
+ assert.ok(idle > 0 && idle < 0.05);
+ // Malformed strategy rows fall back to the idle floor, never to zero.
+ assert.ok(agentReclaimFloorSol({ enabled: true, perTradeSol: 0 }) > 0);
+ assert.ok(agentReclaimFloorSol({ enabled: true, perTradeSol: NaN }) > 0);
+ assert.ok(agentReclaimFloorSol({}) > 0);
+});
+
+test('planAgentReclaim never plans a customer wallet, whatever the balance', () => {
+ const { plan, skipped } = planAgentReclaim([
+ { agentId: 'a', name: 'Customer Sniper', address: 'Cust111', owner: '[email protected]', sol: 2.13 },
+ { agentId: 'b', name: 'Customer Agent', address: 'Cust222', owner: '[email protected]', sol: 0.136 },
+ ]);
+ assert.equal(plan.length, 0);
+ assert.equal(skipped.length, 2);
+ assert.ok(skipped.every((s) => s.reason === 'not_platform_owned'));
+});
+
+test('planAgentReclaim skips agents with capital committed to open positions', () => {
+ const { plan, skipped } = planAgentReclaim([
+ { agentId: 'a', name: 'Swarm 1', address: 'S1', owner: PLATFORM, sol: 5, openPositions: 1 },
+ ]);
+ assert.equal(plan.length, 0);
+ assert.equal(skipped[0].reason, 'capital_committed');
+});
+
+test('planAgentReclaim leaves every swept agent at or above its floor', () => {
+ const candidates = [
+ { agentId: 'a', name: 'three', address: 'T1', owner: PLATFORM, sol: 0.35147, strategy: { enabled: true, perTradeSol: 0.05 } },
+ { agentId: 'b', name: 'Atlas #22', address: 'A1', owner: BOT, sol: 0.07839, strategy: { enabled: false } },
+ { agentId: 'c', name: 'Swarm 2', address: 'S2', owner: PLATFORM, sol: 0.0354, strategy: { enabled: true, perTradeSol: 0.207 } },
+ ];
+ const { plan } = planAgentReclaim(candidates);
+ for (const p of plan) {
+ const c = candidates.find((x) => x.address === p.address);
+ assert.ok(c.sol - p.sol >= p.floorSol, `${p.name} would drop below its floor`);
+ }
+ // Swarm 2 trades 0.207 SOL a pop and holds 0.0354 — far under floor, never swept.
+ assert.equal(plan.find((p) => p.name === 'Swarm 2'), undefined);
+ // The genuinely idle bot wallet is the kind of stranded capital this exists for.
+ assert.ok(plan.some((p) => p.name === 'Atlas #22'));
+});
+
+test('planAgentReclaim honours the dust guard and the per-run wallet cap', () => {
+ const dust = planAgentReclaim([
+ { agentId: 'a', name: 'Persona', address: 'P1', owner: BOT, sol: 0.0051, strategy: { enabled: false } },
+ ]);
+ assert.equal(dust.plan.length, 0);
+ assert.equal(dust.skipped[0].reason, 'at_or_below_floor');
+
+ const many = Array.from({ length: 10 }, (_, i) => ({
+ agentId: `a${i}`, name: `Persona ${i}`, address: `P${i}`, owner: BOT, sol: 1, strategy: { enabled: false },
+ }));
+ const capped = planAgentReclaim(many, { maxWallets: 3 });
+ assert.equal(capped.plan.length, 3);
+ assert.equal(capped.skipped.filter((s) => s.reason === 'run_cap_reached').length, 7);
+ assert.ok(capped.totalSol > 0);
+});