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(economy): self-healing SOL fuel + broken-key agent quarantine
nirholasa9ec96643d80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 83dffc4e9..873df6b28 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -46,12 +46,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Sharing a model now shows a preview card and a real link** — When you share a forged model, the share panel now shows the exact preview card the link will unfurl as on X, Farcaster, and in chats, so you can see what people will see before you post. Every share is now a real permalink to your model with that card, instead of sometimes falling back to a generic link. Models forged right on the homepage are shareable the same way. (`/forge`) `[improvement]`- **Sharper, cleaner models from photos** — Four upgrades to photo-to-3D landed together. Uploaded photos now have their background cleanly removed before reconstruction, so a busy backdrop no longer bleeds into the model. You can supply up to 6 reference angles instead of 4 for fuller coverage. Every uploaded angle is now quality-checked, and a blurry or off-subject one is dropped instead of corrupting the result. And every finished model runs through an automatic geometry cleanup pass that welds and de-duplicates the mesh and trims redundant triangles, so models load faster and render cleaner with no loss of detail. (`/image-to-3d`) `[improvement, feature]`- **The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers** — Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand. (`/admin/ring`) `[fix, improvement, infra]`+- **The homepage community feed is now a live, browsable loop** — The strip of community models on the homepage used to be a fixed set of six. It is now a live feed you can actually browse: switch between Fresh and Trending, and press Show more to see more. New models made by anyone appear at the top on their own while you watch, with a live indicator so Right now stays honest. Each card still spins the real 3D model and opens it when clicked. (`/`) `[feature, improvement]`- **The homepage no longer greets you with an empty stage** — The live 3D agent on the homepage is the first thing you see, but on a cold visit it could sit as a blank near-black panel for several seconds while the model and 3D engine loaded. That gap is now filled with a gently breathing agent silhouette and a "summoning your agent" cue, so the stage feels alive from the very first paint instead of looking broken. It fades out the instant the real avatar is ready, respects reduced-motion settings, and if the preview ever stalls it now surfaces a retry instead of hanging on the placeholder. `[improvement]`+- **The live money feed now refuels itself** — The Money Pulse at three.ws/pulse streams real on-chain agent activity, so it only moves when the autonomous agents have SOL to spend. When that fuel ran out, the feed went quiet until someone topped it up by hand. It now keeps itself running: when the funding root can't cover the agents' costs, it converts a small, capped slice of the platform's own USDC revenue into SOL automatically, and agents whose wallets can no longer be signed for are retired from the pool instead of stalling it. The feed stays live without manual intervention. (`/pulse`) `[infra, fix]`- **The Money Pulse is beating again** — The live money feed went quiet after the July 7 infrastructure move: the switch that powers the autonomous agent activity loop did not survive the migration, so agents stopped tipping, trading, paying and launching. The switch is back on and the feed is live again, with real on-chain tips, trades, payments and coin launches flowing within minutes of the fix. The production runbook now documents the switch so a future migration cannot silently drop it. (`/pulse`) `[fix, infra]`- **The status page now shows whether 3D generations are actually succeeding** — Until now the status page could only tell you the generation servers were online, not whether the models they produce are coming out successfully. Those are different things: a server can be up and still fail a large share of jobs, which is exactly what happened during a recent stretch where image-to-3D quietly failed far too often while every uptime check stayed green. The status page and health feed now report the live 3D generation success rate, and flag which engine and input type are struggling when it dips, so a bad patch surfaces in minutes instead of days. (`/status`) `[infra, improvement]`- **The status page now tracks whether paid API calls actually settle, not just whether the payment rail is switched on** — The July payment-settlement bug ran for eight days before anyone noticed, because every health check reported the x402 rail as 'armed' and the discovery endpoint as 'up' while a third of real settlements were quietly failing. The public status page and /api/healthz now carry a new signal, x402 settlement success, that reads the actual settle outcomes over a rolling window and reports the success rate. It counts only genuine payment-rail faults (server errors, rejected payments, RPC failures) and ignores unrelated noise, and it pages operations the moment the rate drops, so a silent settlement regression surfaces in hours instead of days. (`/status`) `[infra, improvement]`- **The viewer's Create buttons now take you straight to the Forge** — On the shared-model viewer page, the "Create a 3D model" button (shown when a link is missing its model) and the "Make your own" button in the footer used to drop you on the homepage, leaving you to hunt for the generator. Both now go directly to the free text-to-3D Forge so you can start creating in one click. (`/viewer`) `[fix]`- **three.ws now speaks 11 languages, across the whole site** — three.ws is now multilingual in 11 languages: English, Spanish, Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Translation went from the home page alone to the pages people actually read first: What is three.ws, Pricing, Partners, the pitch deck, the SDK and oracle docs, and more. Every page shows a language picker in the corner, your choice is remembered, and if your browser is set to one of these languages three.ws greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language, and search engines are told about each translated page so they can rank it. Behind the scenes a new tool annotates a page's copy for translation in one command, so adding the rest of the site is now fast. `[feature, improvement]`+- **You can now see exactly which build is live** — The status page at three.ws/status now shows the exact version running in production: the commit it was built from (linked to the source), the release version, the Cloud Run revision, and when it was built. Developers can read the same details as JSON from a new /api/version endpoint. It closes a real gap: before this, confirming that a deploy actually shipped meant cross-referencing server timestamps by hand. Now it's one glance, or one request. (`/status`) `[infra, improvement]`- **Your first 3D creation gets a moment** — Making your first 3D model on three.ws used to pass with a quiet three-second Saved note. Now it's a real moment: a burst of confetti and a card that marks what you just made, whether or not you're signed in. It celebrates only your first creation on a device, respects reduced-motion settings, and sits alongside the what-next suggestions so you always know where to go from there. `[feature, improvement]`- **Your models now look studio-quality everywhere, not just in the Forge** — The viewer page that opens when someone follows a shared model link now renders with the same rich lighting, tone mapping, and exposure as the Forge studio where the model was created, so what you share is what they see. The copy-paste embed snippet ships those same settings, meaning models dropped onto your own site no longer look flat compared to the preview. Avatars in agent embed cards now cast a soft ground shadow instead of floating, and the homepage 3D showcase stops burning your battery when it is scrolled out of view or in a background tab. (`/viewer`) `[improvement]`diff --git a/api/_lib/circulation.js b/api/_lib/circulation.jsindex f70806402..1d39e6feb 100644--- a/api/_lib/circulation.js+++ b/api/_lib/circulation.js@@ -272,11 +272,21 @@ async function ensureFunded(conn, treasuryKp, agent, floor) {// ── pool management ───────────────────────────────────────────────────────────+// After this many consecutive key-recovery failures an agent's custodial secret+// is treated as unrecoverable (encrypted under a rotated/lost WALLET_ENCRYPTION_KEY)+// and it is quarantined out of the pool. Its funds are orphaned regardless; the+// point is to stop the selector re-picking a permanently-dead wallet every tick,+// which silently starves the live feed (a handful of broken agents can absorb+// every trade slot, exactly the July 2026 flatline). Deterministic once broken,+// so the threshold only guards against a transient decrypt hiccup.+const KEY_FAIL_QUARANTINE = clampInt(process.env.CIRCULATION_KEY_FAIL_QUARANTINE, 3, 1, 100);+async function loadPool() {const rows = await sql`select id, user_id, name, avatar_id, metafrom agent_identitieswhere (meta->>'circulation') = 'true' and deleted_at is null+ and coalesce((meta->>'circulation_key_broken')::boolean, false) = falseorder by created_at asc`;return rows@@ -291,6 +301,53 @@ async function loadPool() {.filter((a) => a.address);}+// Record the outcome of a custodial-key use for an agent. A failure increments a+// consecutive-failure counter and, at the threshold, sets `circulation_key_broken`+// so loadPool stops selecting it (and logs a one-off quarantine action). A success+// clears the counter. Fire-and-forget by callers — never block the action path.+async function recordKeyResult(agentId, agentName, ok) {+ try {+ if (ok) {+ await sql`+ update agent_identities+ set meta = meta - 'circulation_key_fail_count'+ where id = ${agentId} and (meta ? 'circulation_key_fail_count')`;+ return;+ }+ const rows = await sql`+ update agent_identities+ set meta = jsonb_set(+ coalesce(meta, '{}'::jsonb),+ '{circulation_key_fail_count}',+ to_jsonb(coalesce((meta->>'circulation_key_fail_count')::int, 0) + 1)+ )+ where id = ${agentId}+ returning (meta->>'circulation_key_fail_count')::int as fails`;+ const fails = rows?.[0]?.fails ?? 0;+ if (fails >= KEY_FAIL_QUARANTINE) {+ await sql`+ update agent_identities+ set meta = jsonb_set(+ jsonb_set(coalesce(meta, '{}'::jsonb), '{circulation_key_broken}', 'true'::jsonb),+ '{circulation_key_broken_at}', to_jsonb(now()::text)+ )+ where id = ${agentId}`;+ await logAction({+ kind: 'quarantine',+ actorAgentId: agentId,+ detail: { reason: 'key_recover_failed', consecutive_failures: fails, agent: agentName },+ });+ }+ } catch (e) {+ console.warn('[circulation] recordKeyResult failed', e?.message);+ }+}++// True when a failed trade/tip result is an unrecoverable custodial-key failure.+function isKeyRecoverFailure(result) {+ return result?.code === 'key_recover_failed';+}+function slugify(s) {return String(s).toLowerCase()@@ -447,12 +504,21 @@ async function senderKeypair(agent, reason) {const full = await loadAgentMeta(agent.id);const secret = full?.meta?.encrypted_solana_secret;if (!secret) throw new Error('agent has no custodial secret');- return recoverSolanaAgentKeypair(secret, {- agentId: agent.id,- userId: agent.userId,- reason,- meta: { source: 'circulation' },- });+ try {+ const kp = await recoverSolanaAgentKeypair(secret, {+ agentId: agent.id,+ userId: agent.userId,+ reason,+ meta: { source: 'circulation' },+ });+ recordKeyResult(agent.id, agent.name, true).catch(() => {});+ return kp;+ } catch (e) {+ // A decrypt failure here is the same unrecoverable-key condition the trade+ // path reports as key_recover_failed; count it toward quarantine.+ recordKeyResult(agent.id, agent.name, false).catch(() => {});+ throw e;+ }}// ── marketplace helpers ───────────────────────────────────────────────────────@@ -519,7 +585,10 @@ async function ensureThree(ctx, agent, needAtomic) {},source: 'discretionary',});- if (!result.ok) throw new Skip(`could not acquire $THREE: ${result.code || 'trade_error'}${result.message ? ` — ${result.message}` : ''}`);+ if (!result.ok) {+ if (isKeyRecoverFailure(result)) recordKeyResult(agent.id, agent.name, false).catch(() => {});+ throw new Skip(`could not acquire $THREE: ${result.code || 'trade_error'}${result.message ? ` — ${result.message}` : ''}`);+ }// Give the buy a moment to settle, then re-read.for (let i = 0; i < 6; i++) {@@ -714,7 +783,11 @@ async function actionTrade(ctx) {source: 'discretionary',});- if (!result.ok) throw new Skip(`trade rejected: ${result.code || 'error'}${result.message ? ` — ${result.message}` : ''}`);+ if (!result.ok) {+ if (isKeyRecoverFailure(result)) recordKeyResult(agent.id, agent.name, false).catch(() => {});+ throw new Skip(`trade rejected: ${result.code || 'error'}${result.message ? ` — ${result.message}` : ''}`);+ }+ recordKeyResult(agent.id, agent.name, true).catch(() => {});await logAction({ kind: 'trade', network, actorAgentId: agent.id, signature: result.data?.signature, amountLamports: Math.round(amount * SOL), detail: { mint, agent: agent.name } });return { kind: 'trade', agent: agent.name, mint, sol: amount, signature: result.data?.signature };}diff --git a/api/_lib/economy-fuel.js b/api/_lib/economy-fuel.jsnew file mode 100644index 000000000..e097de994--- /dev/null+++ b/api/_lib/economy-fuel.js@@ -0,0 +1,273 @@+// @ts-check+// api/_lib/economy-fuel.js+//+// Keeps the economy's SOL fuel tank full from the master's own idle USDC.+//+// WHY THIS EXISTS. The circulation engine is a closed SOL loop: agents fund each+// other and trade among themselves, and every tick LEAKS SOL to Solana network+// fees + DEX fees. A closed loop that only leaks cannot self-sustain, given+// enough ticks it drains to zero no matter how the treasury-topup / sweepback+// crons shuffle the remaining SOL around. When it hits zero the Money Pulse+// (/pulse) goes quiet, and until now the only cure was a human manually moving+// SOL in. Meanwhile the master accumulates USDC revenue (x402, marketplace) that+// just sits there. This module closes the gap: when the funding root cannot cover+// the engines' real SOL deficit, it converts a small, bounded, daily-capped slice+// of that USDC into native SOL so the economy keeps running on its own.+//+// Safe by construction:+// • Self-directed: the master swaps ITS OWN USDC for ITS OWN SOL via a real+// Jupiter route (vault-jupiter.js). There is no external recipient, no+// parameter can send funds anywhere. It is the least-privileged possible+// money move: the owner-controlled root converting one asset it holds into+// another it holds.+// • Only fires on a genuine shortage: no-op unless the master's spendable SOL+// falls short of the current top-up run's deficit by at least FUEL_MIN_GAP_SOL.+// • Triple-bounded: a per-swap cap, a per-UTC-day cap, and a USDC keep-floor the+// swap never spends below. A bad Jupiter route (impact > FUEL_MAX_IMPACT_PCT)+// is rejected rather than executed.+// • Every swap is booked to economy_fuel_swaps (drives the daily cap and gives+// the reconcile/health surfaces a record). A dropped write never executes a+// second swap.+//+// Inert switch: ECONOMY_FUEL_ENABLED=0 turns it off entirely (falls back to the+// pre-existing "master empty" ops alert). Default on, self-healing is the point.++import { sql } from './db.js';+import { loadEconomyMaster, RESERVE_SOL, RUN_CAP_SOL } from './economy-master.js';+import { jupQuote, buildSwapTx, USDC_MINT_BY_NETWORK, USDC_DECIMALS } from './vault-jupiter.js';+import { getSolBalance } from './avatar-wallet.js';+import { solPriceUsd } from './sol-price.js';++const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';+const LAMPORTS_PER_SOL = 1_000_000_000;++function num(name, dflt) {+ const v = Number(process.env[name]);+ return Number.isFinite(v) && v >= 0 ? v : dflt;+}++/** Master ⇄ USDC self-swap is on unless explicitly disabled. */+export const FUEL_ENABLED = process.env.ECONOMY_FUEL_ENABLED !== '0';+/** Never spend the master's USDC below this (protect a revenue reserve). */+export const FUEL_USDC_KEEP = num('ECONOMY_FUEL_USDC_KEEP', 0);+/** Most USDC a single refuel swap may spend. */+export const FUEL_PER_RUN_USDC = num('ECONOMY_FUEL_PER_RUN_USDC', 25);+/** Most USDC all refuel swaps may spend in one UTC day. */+export const FUEL_DAILY_USDC = num('ECONOMY_FUEL_DAILY_USDC', 100);+/** Reject a Jupiter route whose price impact exceeds this (%). */+export const FUEL_MAX_IMPACT_PCT = num('ECONOMY_FUEL_MAX_IMPACT_PCT', 3);+/** Swap slippage tolerance (bps). */+export const FUEL_SLIPPAGE_BPS = num('ECONOMY_FUEL_SLIPPAGE_BPS', 100);+/** Only refuel when the master is short of this run's deficit by at least this. */+export const FUEL_MIN_GAP_SOL = num('ECONOMY_FUEL_MIN_GAP_SOL', 0.1);+/** When we do refuel, lift the master's spendable SOL up toward this so we are+ * not swapping dust every single minute the fleet is thirsty. */+export const FUEL_TARGET_SOL = num('ECONOMY_FUEL_TARGET_SOL', 1.0);+/** Below this USDC a swap is not worth the fees. */+const MIN_SWAP_USDC = 1;++/**+ * Pure refuel decision + sizing, no RPC, no DB, so the bounds are unit-testable+ * (mirrors planTopUps / planSweepback in economy-master.js). Given the master's+ * SOL, the run's SOL deficit, and the USDC picture, decide whether to swap and how+ * much USDC to spend.+ *+ * @param {object} a+ * @param {number} a.masterSol master SOL balance+ * @param {number} a.reserveSol SOL the master never spends+ * @param {number} a.runCapSol max SOL a top-up run distributes+ * @param {number} a.deficitSol SOL the pending run wants to distribute+ * @param {number} a.usdcAvailable master USDC balance (whole tokens)+ * @param {number} a.spentTodayUsd USDC already refueled today (UTC)+ * @param {number} a.solUsd live SOL price in USD+ * @param {object} a.caps { perRunUsd, dailyUsd, usdcKeep, minGapSol, targetSol, minSwapUsd }+ * @returns {{act:boolean, reason?:string, spendableSol:number, gapSol:number,+ * dailyRemainingUsd:number, spendUsd:number}}+ */+export function planRefuel({ masterSol, reserveSol, runCapSol, deficitSol, usdcAvailable, spentTodayUsd, solUsd, caps }) {+ const { perRunUsd, dailyUsd, usdcKeep, minGapSol, targetSol, minSwapUsd } = caps;+ const spendableSol = Math.max(0, masterSol - reserveSol);+ const need = Math.min(Math.max(0, deficitSol), runCapSol);+ const gapSol = round(need - spendableSol);+ const dailyRemainingUsd = Math.max(0, dailyUsd - spentTodayUsd);+ const base = { spendableSol: round(spendableSol), gapSol, dailyRemainingUsd: round(dailyRemainingUsd), spendUsd: 0 };++ if (gapSol < minGapSol) return { ...base, act: false, reason: 'sufficient_sol' };++ const spendableUsdc = Math.max(0, usdcAvailable - usdcKeep);+ const usdcBudget = Math.min(perRunUsd, dailyRemainingUsd, spendableUsdc);+ if (usdcBudget < minSwapUsd) {+ const reason =+ dailyRemainingUsd < minSwapUsd ? 'daily_cap_reached'+ : spendableUsdc < minSwapUsd ? 'no_spare_usdc'+ : 'below_min_swap';+ return { ...base, act: false, reason };+ }+ if (!(solUsd > 0)) return { ...base, act: false, reason: 'no_sol_price' };++ // Cover the gap, and lift toward the target so we are not swapping dust every+ // minute the fleet is thirsty. Clamp to the budget, with 3% price headroom.+ const buySol = Math.max(gapSol, targetSol - spendableSol);+ const wantUsd = Math.min(usdcBudget, buySol * solUsd * 1.03);+ if (wantUsd < minSwapUsd) return { ...base, act: false, reason: 'below_min_swap' };++ return { ...base, act: true, spendUsd: round(wantUsd) };+}++let schemaReady = false;+async function ensureSchema() {+ if (schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS economy_fuel_swaps (+ id bigserial PRIMARY KEY,+ day date NOT NULL,+ usdc_atomics bigint NOT NULL,+ sol_lamports bigint NOT NULL,+ price_impact numeric,+ signature text,+ network text NOT NULL DEFAULT 'mainnet',+ created_at timestamptz NOT NULL DEFAULT now()+ )`;+ await sql`CREATE INDEX IF NOT EXISTS economy_fuel_swaps_day_idx ON economy_fuel_swaps (day)`;+ schemaReady = true;+}++/** USDC already converted to SOL today (UTC), in whole USDC. */+async function usdcSpentTodayUsd() {+ const rows = await sql`+ SELECT COALESCE(SUM(usdc_atomics), 0)::text AS atomics+ FROM economy_fuel_swaps+ WHERE day = (now() AT TIME ZONE 'utc')::date`;+ return Number(rows?.[0]?.atomics || 0) / 10 ** USDC_DECIMALS;+}++/** Read an owner's USDC balance (whole tokens + atomics). */+async function readUsdc(connection, owner, network) {+ const mint = network === 'devnet' ? USDC_MINT_BY_NETWORK.devnet : USDC_MINT_BY_NETWORK.mainnet;+ const { PublicKey } = await import('@solana/web3.js');+ let atomics = 0n;+ try {+ const r = await connection.getParsedTokenAccountsByOwner(owner, { mint: new PublicKey(mint) });+ for (const a of r.value) atomics += BigInt(a.account.data.parsed?.info?.tokenAmount?.amount || '0');+ } catch {+ /* no ATA ⇒ zero */+ }+ return { atomics, usd: Number(atomics) / 10 ** USDC_DECIMALS };+}++/** Sign, broadcast, and confirm a Jupiter VersionedTransaction with `keypair`. */+async function signSendConfirm(connection, tx, keypair) {+ tx.sign([keypair]);+ const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });+ const bh = await connection.getLatestBlockhash('confirmed');+ const conf = await connection.confirmTransaction(+ { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },+ 'confirmed',+ );+ if (conf?.value?.err) {+ throw Object.assign(new Error(`swap reverted: ${JSON.stringify(conf.value.err)}`), { signature: sig });+ }+ return sig;+}++/**+ * Refuel the master's SOL from its own USDC when it cannot cover `deficitSol`.+ *+ * @param {object} args+ * @param {import('@solana/web3.js').Connection} args.connection+ * @param {number} args.deficitSol total SOL the pending top-up run wants to distribute+ * @param {'mainnet'|'devnet'} [args.network]+ * @param {boolean} [args.dryRun]+ * @returns {Promise<{acted:boolean, reason?:string, enabled:boolean, dryRun?:boolean,+ * masterSol?:number, spendableSol?:number, gapSol?:number, usdcAvailable?:number,+ * dailyRemainingUsd?:number, plannedUsd?:number, signature?:string, boughtSol?:number,+ * spentUsd?:number, priceImpactPct?:number}>}+ */+export async function refuelMasterFromUsdc({ connection, deficitSol, network = 'mainnet', dryRun = false }) {+ if (!FUEL_ENABLED) return { acted: false, enabled: false, reason: 'disabled' };++ const master = await loadEconomyMaster();+ if (!master) return { acted: false, enabled: true, reason: 'master_unconfigured' };++ const { sol: masterSol } = await getSolBalance(connection, master.publicKey);++ // Cheap pre-check: if the master's spendable SOL already covers the run, skip+ // the USDC read and the schema touch entirely.+ const spendablePre = Math.max(0, masterSol - RESERVE_SOL);+ const gapPre = Math.min(Math.max(0, deficitSol), RUN_CAP_SOL) - spendablePre;+ if (gapPre < FUEL_MIN_GAP_SOL) {+ return { acted: false, enabled: true, reason: 'sufficient_sol', masterSol: round(masterSol), spendableSol: round(spendablePre), gapSol: round(gapPre) };+ }++ await ensureSchema();+ const { usd: usdcUsd } = await readUsdc(connection, master.publicKey, network);+ const spentToday = await usdcSpentTodayUsd();+ const solUsd = await solPriceUsd().catch(() => 0);++ const caps = {+ perRunUsd: FUEL_PER_RUN_USDC,+ dailyUsd: FUEL_DAILY_USDC,+ usdcKeep: FUEL_USDC_KEEP,+ minGapSol: FUEL_MIN_GAP_SOL,+ targetSol: FUEL_TARGET_SOL,+ minSwapUsd: MIN_SWAP_USDC,+ };+ const decision = planRefuel({+ masterSol, reserveSol: RESERVE_SOL, runCapSol: RUN_CAP_SOL,+ deficitSol, usdcAvailable: usdcUsd, spentTodayUsd: spentToday, solUsd, caps,+ });++ const base = {+ enabled: true,+ masterSol: round(masterSol),+ spendableSol: decision.spendableSol,+ gapSol: decision.gapSol,+ usdcAvailable: round(usdcUsd),+ dailyRemainingUsd: decision.dailyRemainingUsd,+ };++ if (!decision.act) return { ...base, acted: false, reason: decision.reason };++ const amountAtomics = BigInt(Math.floor(decision.spendUsd * 10 ** USDC_DECIMALS));+ base.plannedUsd = round(Number(amountAtomics) / 10 ** USDC_DECIMALS);++ const inputMint = network === 'devnet' ? USDC_MINT_BY_NETWORK.devnet : USDC_MINT_BY_NETWORK.mainnet;+ const quote = await jupQuote({+ inputMint,+ outputMint: NATIVE_SOL_MINT,+ amountRaw: amountAtomics,+ slippageBps: FUEL_SLIPPAGE_BPS,+ });+ const priceImpactPct = Number(quote.priceImpactPct ?? 0);+ const outLamports = Number(quote.outAmount || 0);+ base.priceImpactPct = round(priceImpactPct);++ if (priceImpactPct > FUEL_MAX_IMPACT_PCT) {+ return { ...base, acted: false, reason: `price_impact_${priceImpactPct.toFixed(2)}pct` };+ }++ if (dryRun) {+ return { ...base, acted: false, dryRun: true, reason: 'dry_run', boughtSol: round(outLamports / LAMPORTS_PER_SOL) };+ }++ const tx = await buildSwapTx({ quote, userPublicKey: master.publicKey });+ const signature = await signSendConfirm(connection, tx, master);++ await sql`+ INSERT INTO economy_fuel_swaps (day, usdc_atomics, sol_lamports, price_impact, signature, network)+ VALUES ((now() AT TIME ZONE 'utc')::date, ${amountAtomics.toString()}, ${outLamports}, ${priceImpactPct}, ${signature}, ${network})+ `.catch(() => {});++ return {+ ...base,+ acted: true,+ signature,+ boughtSol: round(outLamports / LAMPORTS_PER_SOL),+ spentUsd: base.plannedUsd,+ priceImpactPct: round(priceImpactPct),+ };+}++function round(n) {+ return Math.round(n * 1e9) / 1e9;+}diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.jsindex b42b06296..4445aea3f 100644--- a/api/cron/treasury-topup.js+++ b/api/cron/treasury-topup.js@@ -34,6 +34,7 @@ import { sendOpsAlert } from '../_lib/alerts.js';import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';import { sweepTopUps, RESERVE_SOL, RUN_CAP_SOL, PER_TOPUP_MAX_SOL } from '../_lib/economy-master.js';import { recordSweep } from '../_lib/economy-ledger.js';+import { refuelMasterFromUsdc } from '../_lib/economy-fuel.js';const LAMPORTS_PER_SOL = 1_000_000_000;// How high to lift an engine when it falls below its floor, unless the spec@@ -104,6 +105,30 @@ export default wrapCron(async (req, res) => {// no SOL moves, no ledger write, no alerts. Lets an operator inspect exactly// what the next sweep would do (e.g. after adding a signer to the registry).const dryRun = /[?&]dry=(1|true)\b/.test(req.url || '');++ // Self-healing fuel: before the master distributes, if it cannot cover the+ // engines' real SOL deficit, convert a small bounded slice of its own idle+ // USDC into native SOL. The circulation loop leaks SOL to fees every tick, so+ // without a source the funding root drains to zero and /pulse goes quiet —+ // this keeps the tank full from revenue instead of waiting on a human. No-op+ // unless there is a genuine shortage AND spare USDC (see economy-fuel.js).+ const totalDeficitSol = targets.reduce((s, t) => s + Math.max(0, t.refillToSol - t.currentSol), 0);+ let fuel = { acted: false, reason: 'not_needed' };+ if (totalDeficitSol > 0) {+ try {+ fuel = await refuelMasterFromUsdc({ connection, deficitSol: totalDeficitSol, network: 'mainnet', dryRun });+ } catch (e) {+ fuel = { acted: false, reason: 'error', error: e?.message || 'refuel_failed' };+ }+ }+ if (fuel.acted && fuel.signature) {+ await sendOpsAlert(+ `⛽ Economy master refueled from USDC`,+ `swapped ~$${fuel.spentUsd} USDC → ${fuel.boughtSol} SOL (impact ${fuel.priceImpactPct}%) so the funding root can cover a ${totalDeficitSol.toFixed(3)} SOL deficit.\ntx: ${fuel.signature}`,+ { signature: `economy-fuel:${fuel.signature}` },+ );+ }+const result = await sweepTopUps({ connection, targets, network: 'mainnet', dryRun });if (dryRun) {return json(res, 200, {@@ -117,6 +142,7 @@ export default wrapCron(async (req, res) => {rejected: result.rejected || [],master_sol: result.masterSol ?? null,spendable_sol: result.spendableSol ?? null,+ fuel,read_errors: errors,});}@@ -149,13 +175,21 @@ export default wrapCron(async (req, res) => {}}- // Alert when the master is configured but too drained to cover a real- // deficit — that is the one condition a human must act on (fund the root).- if (result.configured && targets.length > 0 && result.spentSol === 0 && result.funded.length === 0) {+ // Alert when the master is configured but too drained to cover a real deficit+ // AND self-healing could not rescue it (USDC exhausted, daily cap hit, or fuel+ // disabled) — that is the one condition a human must act on (fund the root).+ // When the refuel swap DID act, the shortage is being handled autonomously, so+ // suppress the page: the next tick distributes the freshly-bought SOL.+ if (result.configured && targets.length > 0 && result.spentSol === 0 && result.funded.length === 0 && !fuel.acted) {+ const fuelNote =+ fuel.reason === 'daily_cap_reached' ? ' Fuel daily cap reached; raise ECONOMY_FUEL_DAILY_USDC or fund SOL.'+ : fuel.reason === 'no_spare_usdc' ? ' Master is also out of spare USDC to convert.'+ : fuel.reason === 'disabled' ? ' Auto-refuel is disabled (ECONOMY_FUEL_ENABLED=0).'+ : '';await sendOpsAlert(`⛽ Economy master could not refill ${targets.length} engine(s)`,`master ${result.master} has ${result.masterSol} SOL (reserve ${result.reserveSol}). ` +- `Underfunded: ${targets.map((t) => t.name).join(', ')}. Fund the master on mainnet.`,+ `Underfunded: ${targets.map((t) => t.name).join(', ')}. Fund the master on mainnet.${fuelNote}`,{ signature: `economy-master-empty:${result.master}` },);}@@ -188,6 +222,7 @@ export default wrapCron(async (req, res) => {rejected: result.rejected || [],spent_sol: result.spentSol,master_sol: result.masterSol ?? null,+ fuel,read_errors: errors,run_id: runId,ledger,diff --git a/data/changelog.json b/data/changelog.jsonindex 2cc60c3ef..a3d59c67c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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-17",+ "title": "You can now see exactly which build is live",+ "summary": "The status page at three.ws/status now shows the exact version running in production: the commit it was built from (linked to the source), the release version, the Cloud Run revision, and when it was built. Developers can read the same details as JSON from a new /api/version endpoint. It closes a real gap: before this, confirming that a deploy actually shipped meant cross-referencing server timestamps by hand. Now it's one glance, or one request.",+ "tags": [+ "infra",+ "improvement"+ ],+ "link": "/status"+ },+ {+ "date": "2026-07-17",+ "title": "The live money feed now refuels itself",+ "summary": "The Money Pulse at three.ws/pulse streams real on-chain agent activity, so it only moves when the autonomous agents have SOL to spend. When that fuel ran out, the feed went quiet until someone topped it up by hand. It now keeps itself running: when the funding root can't cover the agents' costs, it converts a small, capped slice of the platform's own USDC revenue into SOL automatically, and agents whose wallets can no longer be signed for are retired from the pool instead of stalling it. The feed stays live without manual intervention.",+ "tags": [+ "infra",+ "fix"+ ],+ "link": "/pulse"+ },{"date": "2026-07-17","title": "Daily Forge: a new 3D challenge every day, and a streak worth keeping",@@ -14475,6 +14495,16 @@"improvement"],"link": "/forge"+ },+ {+ "date": "2026-07-17",+ "title": "The homepage community feed is now a live, browsable loop",+ "summary": "The strip of community models on the homepage used to be a fixed set of six. It is now a live feed you can actually browse: switch between Fresh and Trending, and press Show more to see more. New models made by anyone appear at the top on their own while you watch, with a live indicator so Right now stays honest. Each card still spins the real 3D model and opens it when clicked.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/"}]}diff --git a/docs/economy-master.md b/docs/economy-master.mdindex 0b491bcc8..1a4bfca6f 100644--- a/docs/economy-master.md+++ b/docs/economy-master.md@@ -105,6 +105,44 @@ when there was nothing to collect. Dust guard: a sweep below`ECONOMY_SWEEPBACK_MIN_SOL` (default 0.01 SOL) is skipped so fees never exceedthe return.+## Fuel: refilling the root from revenue++Topup and sweepback only move SOL that already exists in the fleet. But the+circulation engine is a **closed SOL loop** — agents fund each other and trade+among themselves, and every tick leaks a little SOL to Solana network and DEX+fees. A loop that only leaks eventually drains to zero no matter how the two crons+shuffle the remaining SOL, and when it hits zero the Money Pulse+([`/pulse`](../pages/pulse.html)) goes quiet. Historically the only cure was a+human moving SOL in.++**Fuel** ([`api/_lib/economy-fuel.js`](../api/_lib/economy-fuel.js)) closes that+gap. It runs as a pre-step of the topup cron: before the master distributes, if+its spendable SOL can't cover the engines' real deficit, it converts a small,+bounded slice of the master's **own idle USDC revenue** into native SOL through a+real Jupiter route, then lets the topup distribute the proceeds.++Safe by construction, in the same spirit as the topup allowlist and the sweepback+destination lock:++- **Self-directed.** The master swaps *its own* USDC for *its own* SOL. There is+ no recipient parameter — funds can't go anywhere but from one asset the root+ holds into another. It is the least-privileged possible money move.+- **Only on a genuine shortage.** No-op unless the master's spendable SOL falls+ short of the pending run's deficit by at least `ECONOMY_FUEL_MIN_GAP_SOL`.+- **Triple-bounded.** A per-swap cap (`ECONOMY_FUEL_PER_RUN_USDC`, default $25), a+ per-UTC-day cap (`ECONOMY_FUEL_DAILY_USDC`, default $100), and a USDC keep-floor+ (`ECONOMY_FUEL_USDC_KEEP`) the swap never spends below. A Jupiter route with+ price impact above `ECONOMY_FUEL_MAX_IMPACT_PCT` (default 3%) is rejected, not+ executed.+- **Booked.** Every swap lands in `economy_fuel_swaps` (which drives the daily+ cap) and fires an ops alert. When fuel *did* act, the "master could not refill"+ page is suppressed — the shortage is being handled autonomously; the next tick+ distributes the freshly-bought SOL.++Set `ECONOMY_FUEL_ENABLED=0` to turn it off entirely (the fleet then falls back to+the "fund the master" ops alert). The decision/sizing math is a pure function+(`planRefuel`) covered by [`tests/economy-fuel.test.js`](../tests/economy-fuel.test.js).+## Lowest feesEvery transfer routes through `submitProtected` with `tipMode: 'off'` — **no Jito@@ -120,6 +158,11 @@ congestion, clamped to a hard ceiling.| `ECONOMY_MASTER_SECRET_BASE58` | yes | The master keypair (base58 of 64 raw bytes). Unset ⇒ the funding root is inert. Store it as a secret on the Cloud Run service (or your host's secret store), never plaintext; keep your own offline copy since secret values are unreadable after they are written. || `ECONOMY_MASTER_ADDRESS` | no | Override the expected pubkey if the master is ever rotated. Defaults to the address above. || `ECONOMY_MASTER_RESERVE_SOL` / `_PER_TOPUP_MAX_SOL` / `_RUN_CAP_SOL` | no | Guard caps (see table). |+| `ECONOMY_FUEL_ENABLED` | no | `0` disables the USDC→SOL auto-refuel (default on). |+| `ECONOMY_FUEL_PER_RUN_USDC` / `_DAILY_USDC` | no | Fuel caps: max USDC per swap (default 25) and per UTC day (default 100). |+| `ECONOMY_FUEL_USDC_KEEP` | no | USDC the refuel never spends below (revenue reserve). Default 0. |+| `ECONOMY_FUEL_MIN_GAP_SOL` / `_TARGET_SOL` | no | Only refuel when the SOL gap is at least this (default 0.1); buy toward this spendable-SOL buffer (default 1.0). |+| `ECONOMY_FUEL_MAX_IMPACT_PCT` / `_SLIPPAGE_BPS` | no | Reject a route above this price impact (default 3%); swap slippage (default 100 bps). || `CRON_SECRET` | yes | Bearer auth for the `treasury-topup` cron (shared with every other cron; Cloud Scheduler sends it). || `SOLANA_RPC_URL` | no | Mainnet RPC (defaults to `api.mainnet-beta`). |diff --git a/public/changelog.json b/public/changelog.jsonindex 5ab2b5f4f..cbc338850 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T20:59:09.415Z",+ "generated_at": "2026-07-17T21:28:28.386Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -426,6 +426,17 @@"infra"]},+ {+ "date": "2026-07-17",+ "type": "update",+ "title": "The homepage community feed is now a live, browsable loop",+ "summary": "The strip of community models on the homepage used to be a fixed set of six. It is now a live feed you can actually browse: switch between Fresh and Trending, and press Show more to see more. New models made by anyone appear at the top on their own while you watch, with a live indicator so Right now stays honest. Each card still spins the real 3D model and opens it when clicked.",+ "link": "/",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-07-17","type": "update",@@ -436,6 +447,17 @@"improvement"]},+ {+ "date": "2026-07-17",+ "type": "update",+ "title": "The live money feed now refuels itself",+ "summary": "The Money Pulse at three.ws/pulse streams real on-chain agent activity, so it only moves when the autonomous agents have SOL to spend. When that fuel ran out, the feed went quiet until someone topped it up by hand. It now keeps itself running: when the funding root can't cover the agents' costs, it converts a small, capped slice of the platform's own USDC revenue into SOL automatically, and agents whose wallets can no longer be signed for are retired from the pool instead of stalling it. The feed stays live without manual intervention.",+ "link": "/pulse",+ "tags": [+ "infra",+ "fix"+ ]+ },{"date": "2026-07-17","type": "update",@@ -490,6 +512,17 @@"improvement"]},+ {+ "date": "2026-07-17",+ "type": "update",+ "title": "You can now see exactly which build is live",+ "summary": "The status page at three.ws/status now shows the exact version running in production: the commit it was built from (linked to the source), the release version, the Cloud Run revision, and when it was built. Developers can read the same details as JSON from a new /api/version endpoint. It closes a real gap: before this, confirming that a deploy actually shipped meant cross-referencing server timestamps by hand. Now it's one glance, or one request.",+ "link": "/status",+ "tags": [+ "infra",+ "improvement"+ ]+ },{"date": "2026-07-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c411c4220..90a5d0d85 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -326,6 +326,14 @@<category>fix</category><description>Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand.</description></item>+ <item>+ <title>The homepage community feed is now a live, browsable loop</title>+ <link>https://three.ws/</link>+ <guid isPermaLink="false">2026-07-17:The homepage community feed is now a live, browsable loop</guid>+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The strip of community models on the homepage used to be a fixed set of six. It is now a live feed you can actually browse: switch between Fresh and Trending, and press Show more to see more. New models made by anyone appear at the top on their own while you watch, with a live indicator so Right now stays honest. Each card still spins the real 3D model and opens it when clicked.</description>+ </item><item><title>The homepage no longer greets you with an empty stage</title><link>https://three.ws/changelog</link>@@ -334,6 +342,14 @@<category>improvement</category><description>The live 3D agent on the homepage is the first thing you see, but on a cold visit it could sit as a blank near-black panel for several seconds while the model and 3D engine loaded. That gap is now filled with a gently breathing agent silhouette and a "summoning your agent" cue, so the stage feels alive from the very first paint instead of looking broken. It fades out the instant the real avatar is ready, respects reduced-motion settings, and if the preview ever stalls it now surfaces a retry instead of hanging on the placeholder.</description></item>+ <item>+ <title>The live money feed now refuels itself</title>+ <link>https://three.ws/pulse</link>+ <guid isPermaLink="false">2026-07-17:The live money feed now refuels itself</guid>+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>The Money Pulse at three.ws/pulse streams real on-chain agent activity, so it only moves when the autonomous agents have SOL to spend. When that fuel ran out, the feed went quiet until someone topped it up by hand. It now keeps itself running: when the funding root can't cover the agents' costs, it converts a small, capped slice of the platform's own USDC revenue into SOL automatically, and agents whose wallets can no longer be signed for are retired from the pool instead of stalling it. The feed stays live without manual intervention.</description>+ </item><item><title>The Money Pulse is beating again</title><link>https://three.ws/pulse</link>@@ -374,6 +390,14 @@<category>feature</category><description>three.ws is now multilingual in 11 languages: English, Spanish, Simplified Chinese, Japanese, Korean, French, German, Brazilian Portuguese, Arabic, Hindi, and Russian. Translation went from the home page alone to the pages people actually read first: What is three.ws, Pricing, Partners, the pitch deck, the SDK and oracle docs, and more. Every page shows a language picker in the corner, your choice is remembered, and if your browser is set to one of these languages three.ws greets you in it automatically. Arabic lays out right-to-left. Brand and protocol terms like $THREE, USDC, and three.ws stay exact in every language, and search engines are told about each translated page so they can rank it. Behind the scenes a new tool annotates a page's copy for translation in one command, so adding the rest of the site is now fast.</description></item>+ <item>+ <title>You can now see exactly which build is live</title>+ <link>https://three.ws/status</link>+ <guid isPermaLink="false">2026-07-17:You can now see exactly which build is live</guid>+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>The status page at three.ws/status now shows the exact version running in production: the commit it was built from (linked to the source), the release version, the Cloud Run revision, and when it was built. Developers can read the same details as JSON from a new /api/version endpoint. It closes a real gap: before this, confirming that a deploy actually shipped meant cross-referencing server timestamps by hand. Now it's one glance, or one request.</description>+ </item><item><title>Your first 3D creation gets a moment</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex f4cd7ded7..f7b639299 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T20:59:09.400Z",+ "generated_at": "2026-07-17T21:28:28.373Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/economy-fuel.test.js b/tests/economy-fuel.test.jsnew file mode 100644index 000000000..402ff8f64--- /dev/null+++ b/tests/economy-fuel.test.js@@ -0,0 +1,90 @@+// Pure decision/bounds tests for the economy-fuel USDC→SOL auto-refuel.+// planRefuel takes no RPC/DB, so every guard is exercised here.+import { describe, it, expect } from 'vitest';+import { planRefuel } from '../api/_lib/economy-fuel.js';++const CAPS = {+ perRunUsd: 25,+ dailyUsd: 100,+ usdcKeep: 0,+ minGapSol: 0.1,+ targetSol: 1.0,+ minSwapUsd: 1,+};+const base = {+ masterSol: 0.02, // sitting at reserve, the starved case+ reserveSol: 0.02,+ runCapSol: 2,+ deficitSol: 0.6, // circ + others want ~0.6 SOL+ usdcAvailable: 150,+ spentTodayUsd: 0,+ solUsd: 170,+ caps: CAPS,+};++describe('planRefuel', () => {+ it('acts when the master is starved and USDC is available', () => {+ const r = planRefuel(base);+ expect(r.act).toBe(true);+ // wants ~1 SOL of headroom (target) → ~170 USD, clamped to the 25 USD per-run cap+ expect(r.spendUsd).toBe(25);+ expect(r.gapSol).toBeCloseTo(0.6, 6);+ });++ it('does nothing when the master already has enough spendable SOL', () => {+ const r = planRefuel({ ...base, masterSol: 1.0 });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('sufficient_sol');+ });++ it('does nothing when the gap is below the minimum', () => {+ // spendable 0.05 over reserve, deficit 0.1 → gap 0.05 < minGapSol 0.1+ const r = planRefuel({ ...base, masterSol: 0.07, deficitSol: 0.1 });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('sufficient_sol');+ });++ it('stops at the daily cap', () => {+ const r = planRefuel({ ...base, spentTodayUsd: 100 });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('daily_cap_reached');+ });++ it('respects the daily cap partially (only remaining budget)', () => {+ const r = planRefuel({ ...base, spentTodayUsd: 96 });+ expect(r.act).toBe(true);+ expect(r.spendUsd).toBe(4); // 100 - 96 remaining, under per-run cap+ });++ it('never spends USDC below the keep-floor', () => {+ const r = planRefuel({ ...base, usdcAvailable: 5, caps: { ...CAPS, usdcKeep: 5 } });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('no_spare_usdc');+ });++ it('reports no_spare_usdc when the wallet is dry', () => {+ const r = planRefuel({ ...base, usdcAvailable: 0 });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('no_spare_usdc');+ });++ it('will not act without a live SOL price', () => {+ const r = planRefuel({ ...base, solUsd: 0 });+ expect(r.act).toBe(false);+ expect(r.reason).toBe('no_sol_price');+ });++ it('is bounded by the run cap when the deficit is huge', () => {+ const r = planRefuel({ ...base, deficitSol: 999, usdcAvailable: 100000, caps: { ...CAPS, perRunUsd: 100000, dailyUsd: 100000 } });+ expect(r.act).toBe(true);+ // gap is clamped to runCapSol (2) - spendable(0) = 2 SOL; buy toward that, not 999+ expect(r.spendUsd).toBeLessThanOrEqual(2 * base.solUsd * 1.03 + 0.01);+ });++ it('sizes the buy toward the target buffer, not just the gap', () => {+ // small gap (0.15) but target is 1.0 → buy ~1 SOL of headroom+ const r = planRefuel({ ...base, deficitSol: 0.17, usdcAvailable: 100000, caps: { ...CAPS, perRunUsd: 100000, dailyUsd: 100000 } });+ expect(r.act).toBe(true);+ expect(r.spendUsd).toBeGreaterThan(0.5 * base.solUsd); // more than just the 0.15 gap+ });+});