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(vision): charge the body read against the same deadline the model chain uses

nirholasc7c8b4211e4b
diff --git a/api/_lib/tts-gemini.js b/api/_lib/tts-gemini.js
index 2c52ee04e..0d29ce644 100644
--- a/api/_lib/tts-gemini.js
+++ b/api/_lib/tts-gemini.js
@@ -1,11 +1,11 @@
// @ts-check
-// Gemini native TTS lane — 30 prebuilt voices, controllable by prompt.
+// Gemini native TTS lane: 30 prebuilt voices, controllable by prompt.
//
// Two rungs, in this order:
// 1. Vertex AI (`GOOGLE_CLOUD_PROJECT`) authenticated with the GCP service
// account and billed to the platform's Google credits. This is the lane
// that actually runs in production: same anchor doctrine as
-// api/_lib/vertex-gemini.js — no third-party quota, no API key to rot,
+// api/_lib/vertex-gemini.js (no third-party quota, no API key to rot,
// standing owner-approved spend (docs/ops/gcp-credits-plan.md).
// 2. The Generative Language API with `GEMINI_API_KEY`, for local dev and as
// a backstop when the Vertex token mint fails.
@@ -95,11 +95,24 @@ export function isGeminiVoice(id) {
const SAMPLE_RATE_HZ = 24_000;
const DEFAULT_TIMEOUT_MS = 45_000;
-// The preview TTS models are not served from every Vertex region; us-central1
-// is the one that has carried them since launch. Env-tunable so a region move
-// needs no code change.
-function vertexLocation() {
- return process.env.GOOGLE_CLOUD_LOCATION_TTS || 'us-central1';
+// The preview TTS models are not served from every Vertex region, and Google
+// moves which ones carry a preview model without notice. Rather than bet the
+// lane on one region, try each in turn: an explicit env pin first, then the
+// two that have carried these models since launch. A region that does not host
+// the model answers 404, which costs one round trip and falls through.
+function vertexLocations() {
+ const pinned = process.env.GOOGLE_CLOUD_LOCATION_TTS;
+ const ordered = pinned ? [pinned, 'us-central1', 'global'] : ['us-central1', 'global'];
+ return [...new Set(ordered)];
+}
+
+function vertexUrl(location, project, modelId) {
+ const host =
+ location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;
+ return (
+ `https://${host}/v1/projects/${project}/locations/${location}` +
+ `/publishers/google/models/${modelId}:generateContent`
+ );
}
/** True when either rung can serve. Read per call so late-injected env works. */
@@ -205,20 +218,31 @@ export async function synthesizeGeminiTts({
// ── Rung 1: Vertex AI on platform credits ────────────────────────────────
if (process.env.GOOGLE_CLOUD_PROJECT) {
const project = process.env.GOOGLE_CLOUD_PROJECT;
- const location = vertexLocation();
+ let token = null;
try {
- const token = await getGcpAccessToken();
- pcm = await callGemini({
- url:
- `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` +
- `/locations/${location}/publishers/google/models/${modelId}:generateContent`,
- headers: { authorization: `Bearer ${token}` },
- body,
- timeoutMs,
- });
- lane = 'vertex';
+ token = await getGcpAccessToken();
} catch (e) {
- laneErrors.push(`vertex: ${e?.code || 'error'} ${e?.message || ''}`.trim());
+ laneErrors.push({ code: 'no_credentials', text: `vertex: no_credentials ${e?.message || ''}`.trim() });
+ }
+ for (const location of token ? vertexLocations() : []) {
+ try {
+ pcm = await callGemini({
+ url: vertexUrl(location, project, modelId),
+ headers: { authorization: `Bearer ${token}` },
+ body,
+ timeoutMs,
+ });
+ lane = `vertex:${location}`;
+ break;
+ } catch (e) {
+ laneErrors.push({
+ code: e?.code || 'error',
+ text: `vertex/${location}: ${e?.code || 'error'} ${e?.message || ''}`.trim(),
+ });
+ // An auth or quota failure will repeat in every region; only a
+ // missing-model 404 is worth retrying elsewhere.
+ if (e?.code === 'invalid_key' || e?.code === 'rate_limited') break;
+ }
}
}
@@ -234,13 +258,24 @@ export async function synthesizeGeminiTts({
});
lane = 'api-key';
} catch (e) {
- laneErrors.push(`api-key: ${e?.code || 'error'} ${e?.message || ''}`.trim());
+ laneErrors.push({
+ code: e?.code || 'error',
+ text: `api-key: ${e?.code || 'error'} ${e?.message || ''}`.trim(),
+ });
}
}
if (!pcm) {
if (!laneErrors.length) throw tagged('Gemini TTS is not configured', 'not_configured');
- throw tagged(`Gemini TTS failed — ${laneErrors.join('; ')}`, 'provider_error');
+ // When every rung failed the same way the cause is the request, not the
+ // infrastructure: keep that code so the caller can answer 422 (blocked
+ // prompt) or 429 (quota) instead of a blanket 502.
+ const codes = new Set(laneErrors.map((e) => e.code));
+ const code = codes.size === 1 ? [...codes][0] : 'provider_error';
+ throw tagged(
+ `Gemini TTS failed: ${laneErrors.map((e) => e.text).join('; ')}`,
+ code === 'no_credentials' || code === 'error' ? 'provider_error' : code,
+ );
}
return {
diff --git a/api/vision.js b/api/vision.js
index fc86f7ed3..0b15cad3c 100644
--- a/api/vision.js
+++ b/api/vision.js
@@ -25,10 +25,21 @@ export const maxDuration = 60;
// bounding the in-memory buffer per request.
const MAX_IMAGE_BYTES = 12 * 1024 * 1024;
const VISION_TIMEOUT_MS = 20_000;
-// Overall budget for the whole provider chain (free NIM models + paid backstop),
-// kept well under the function wall-clock limit so describeImage returns a clean
-// 504 instead of being hard-killed by the platform ("Task timed out after 30s").
+// Overall budget for the WHOLE request, not just the provider chain. It used to
+// bound only describeImage, which meant the real wall clock was this plus
+// whatever the body read took first, up to READ_BODY_TIMEOUT_MS (15s) for a
+// 12 MB upload on a slow link, so ~39s worst case. That overruns a 30s gateway
+// timeout, and the caller gets an opaque 504 from the edge instead of the clean,
+// diagnosable one this endpoint is careful to produce (2026-08-07: two 504s on
+// agent uploads with no matching app-level error, the signature of the request
+// dying above the handler).
+//
+// Charging the upload against the same budget keeps the endpoint's total under
+// the gateway's, so a slow upload eats into model time rather than adding to it.
const VISION_DEADLINE_MS = 24_000;
+// Floor for the model chain after a slow upload: below this even the fastest
+// lane cannot answer, so it is better to say so than to burn the remainder.
+const VISION_MIN_CHAIN_MS = 4_000;
const ACCEPTED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
const DEFAULT_PROMPT =
@@ -40,6 +51,7 @@ function isAcceptedImageType(ct) {
}
export default wrap(async function handler(req, res) {
+ const startedAt = Date.now();
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -113,6 +125,20 @@ export default wrap(async function handler(req, res) {
return error(res, e?.status || 400, 'bad_request', e?.message || 'could not read request body');
}
+ // What is left of the request budget after auth, rate limiting, and the body
+ // read. describeImage caps each provider attempt at min(timeoutMs, remaining),
+ // so handing it the true remainder is what keeps the endpoint's own 504 ahead
+ // of the gateway's.
+ const chainBudgetMs = VISION_DEADLINE_MS - (Date.now() - startedAt);
+ if (chainBudgetMs < VISION_MIN_CHAIN_MS) {
+ return error(
+ res,
+ 504,
+ 'deadline_exceeded',
+ 'Reading the image used the request budget before a model could run. Send a smaller image, or an imageUrl instead of inline bytes.',
+ );
+ }
+
try {
const out = await describeImage({
prompt: String(prompt).slice(0, 2000),
@@ -120,8 +146,8 @@ export default wrap(async function handler(req, res) {
imageBase64,
mimeType,
maxTokens: Math.min(Math.max(maxTokens, 16), 2048),
- timeoutMs: VISION_TIMEOUT_MS,
- deadlineMs: VISION_DEADLINE_MS,
+ timeoutMs: Math.min(VISION_TIMEOUT_MS, chainBudgetMs),
+ deadlineMs: chainBudgetMs,
track: { userId, tool: 'api/vision' },
});
return json(
diff --git a/pages/dev-citizen-harness.html b/pages/dev-citizen-harness.html
deleted file mode 100644
index 6ca7baa18..000000000
--- a/pages/dev-citizen-harness.html
+++ /dev/null
@@ -1,66 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="robots" content="noindex, nofollow" />
- <title>Citizen layer harness</title>
- <style>
- body { background: #0b0b0b; color: #e7e7ea; font: 14px system-ui, sans-serif; padding: 24px; }
- button { padding: 8px 14px; margin-right: 8px; border-radius: 8px; border: 1px solid #26262b; background: #16161a; color: #e7e7ea; cursor: pointer; }
- pre { background: #121216; padding: 12px; border-radius: 8px; overflow: auto; max-height: 40vh; }
- </style>
- </head>
- <body>
- <h1>Citizen layer harness</h1>
- <p>Exercises the real citizen identity layer against the real gallery API, with no 3D world.</p>
- <button id="load">1. Load citizen pool</button>
- <button id="profile">2. Open citizen profile</button>
- <button id="talk">3. Talk 1-on-1</button>
- <pre id="out">ready</pre>
- <script type="module">
- import { loadCitizenPool, isCitizen, openCitizenProfile, talkToCitizen } from '/src/game/npc/citizens.js';
-
- const out = document.getElementById('out');
- const say = (o) => { out.textContent = typeof o === 'string' ? o : JSON.stringify(o, null, 2); };
- const world = { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', name: 'three.ws', symbol: 'three' };
- let pool = [];
- let citizen = null;
-
- const makeCitizen = (record) => ({
- record,
- name: record.name,
- said: [],
- held: 0,
- say(t) { this.said.push(t); },
- hold() { this.held++; },
- release() { this.held--; },
- });
-
- document.getElementById('load').onclick = async () => {
- pool = await loadCitizenPool();
- const named = pool.filter(isCitizen);
- citizen = named.length ? makeCitizen(named[0]) : null;
- window.__harness = { pool, named, citizen };
- say({
- poolSize: pool.length,
- named: named.length,
- withAgent: named.filter((r) => r.agentId).length,
- withBio: named.filter((r) => r.description).length,
- sample: named.slice(0, 3).map((r) => ({ name: r.name, agentId: r.agentId, bio: (r.description || '').slice(0, 60) })),
- });
- };
-
- document.getElementById('profile').onclick = () => {
- if (!citizen) return say('load the pool first');
- openCitizenProfile(citizen, { world });
- say('profile opened for ' + citizen.name);
- };
-
- document.getElementById('talk').onclick = async () => {
- if (!citizen) return say('load the pool first');
- await talkToCitizen(citizen, { world });
- say('talk opened for ' + citizen.name);
- };
- </script>
- </body>
-</html>
diff --git a/pages/play.html b/pages/play.html
index 2ccac7b88..f4b797795 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -99,7 +99,15 @@
try {
var p = new URLSearchParams(location.search);
if (!p.get('coin')) return;
- var trim = function (s, max) { return (s || '').trim().replace(/\s+/g, ' ').slice(0, max); };
+ /* Bound the length a shared link can inject, and cut on a word boundary
+ so an over-long community name doesn't leave a dangling letter. */
+ var trim = function (s, max) {
+ var v = (s || '').trim().replace(/\s+/g, ' ');
+ if (v.length <= max) return v;
+ var cut = v.slice(0, max);
+ var sp = cut.lastIndexOf(' ');
+ return (sp > max * 0.6 ? cut.slice(0, sp) : cut).replace(/[\s.,;:-]+$/, '');
+ };
var name = trim(p.get('name'), 28);
var sym = trim(p.get('symbol'), 12).replace(/^\$/, '').toUpperCase();
/* Only same-origin paths (the /api/img proxy) and https URLs. Anything
diff --git a/public/locales/en.json b/public/locales/en.json
index 5e4bc4af1..893f2f61c 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -15795,14 +15795,24 @@
"avatar": "Avatar",
"avatar_aria": "Change your avatar",
"avatar_title": "Change your avatar (V)",
+ "bank_deposit": "Deposit",
+ "bank_deposit_aria": "Amount to deposit",
+ "bank_deposit_sub": "Deposit: protects cash from a death drop.",
+ "bank_title": "Bank / ATM",
+ "bank_withdraw": "Withdraw",
+ "bank_withdraw_aria": "Amount to withdraw",
+ "bank_withdraw_sub": "Withdraw: moves banked cash back to your purse.",
+ "banked": "Banked (protected)",
"buy": "Buy",
"buy_title": "Buy this coin",
"canvas_label": "The 3D coin community world. Walk with W A S D or the arrow keys, hold Shift to run, Space to jump, drag or use the mouse to look around. Press Enter to open chat, Q for emotes, E to talk to whoever is nearby, and Z to hide the panels.",
+ "cash_on_hand": "Cash on hand",
"chat": "Chat",
"chat_input_aria": "Chat message",
"chat_log_aria": "Chat messages",
"chat_placeholder": "Say something…",
"chat_toggle_aria": "Toggle chat",
+ "close": "Close",
"dance": "Dance",
"dance_aria": "Dance on the floor",
"dance_title": "Sync-dance with everyone on the floor",
@@ -15819,7 +15829,12 @@
"hint": "<kbd>W A S D</kbd> / drag-joystick to move · <kbd>drag</kbd> to look · scroll zoom · <kbd>Enter</kbd> chat · <kbd>Q</kbd> emotes · <kbd>I</kbd> inspect · <kbd>P</kbd> photo · <kbd>Z</kbd> zen",
"jobs": "Jobs",
"jobs_aria": "Open the jobs board",
+ "jobs_sections": "Jobs board sections",
+ "jobs_tab_active": "Active",
+ "jobs_tab_active_n": "Active ({{n}})",
+ "jobs_tab_board": "Board",
"jobs_title": "Jobs Board: dailies, courier runs, and the vault heist",
+ "jobs_title_panel": "Jobs Board",
"leave": "Communities",
"meta_description": "Coin Communities — a browser isometric MMO on three.ws. Join coin communities, gather, fight, trade, and explore a shared world. Sign in with your wallet and play.",
"meta_og_description": "A browser isometric MMO on three.ws — join coin communities, gather, fight, trade, explore.",
@@ -15832,6 +15847,9 @@
"send": "Send",
"shop": "Shop",
"shop_aria": "Open cosmetics shop",
+ "shop_h": "Cosmetics",
+ "shop_panel_aria": "Cosmetics shop",
+ "shop_sub": "Preview live on your avatar",
"shop_title": "Cosmetics: try looks on your avatar",
"show_ui": "Show UI",
"show_ui_aria": "Show controls",
@@ -15845,12 +15863,23 @@
"status_retry_aria": "Connection {{state}}. Activate to reconnect.",
"status_retry_title": "Reconnect",
"status_unavailable": "multiplayer unavailable",
+ "store_buy": "Buy",
+ "store_mode": "Store mode",
+ "store_sell": "Sell",
+ "store_title": "General Store",
"voice": "Voice",
"voice_aria": "Voice chat",
"voice_title": "Join voice: talk to people near you",
"wardrobe": "My Fits",
"wardrobe_aria": "Open my cosmetics wardrobe",
+ "wardrobe_close_aria": "Close wardrobe",
+ "wardrobe_h": "My Cosmetics",
+ "wardrobe_panel_aria": "My Cosmetics wardrobe",
"wardrobe_title": "My Cosmetics: equip your owned looks",
+ "wheel_free": "Free spin",
+ "wheel_paid": "Paid spin",
+ "wheel_sub": "Fortune's Folly · Mainland",
+ "wheel_title": "Wheel of Fortune",
"zen": "Zen",
"zen_aria": "Zen mode",
"zen_title": "Zen mode: hide every panel, just the world (Z)"
diff --git a/scripts/event-dependency-failover.mjs b/scripts/event-dependency-failover.mjs
index 7ca83686c..402f595cb 100644
--- a/scripts/event-dependency-failover.mjs
+++ b/scripts/event-dependency-failover.mjs
@@ -278,9 +278,12 @@ async function checkLlm(base) {
rungsTotal: rungs.length,
rungsLive: rungs.filter((x) => x.ok).length,
rungs,
- failoverProven: turn.ok && turn.value.fallbacks.length > 0,
+ // A turn with zero demotions is the lead provider working, not a failover
+ // that failed to happen. Both are healthy; only a turn that never produced
+ // content is a failure, so the proof flag follows delivery, not demotions.
+ failoverProven: turn.ok,
failoverDetail: turn.ok
- ? `answered in ${turn.ms}ms after ${turn.value.fallbacks.length} live demotion(s); paid tier ${paidLive} live (${paid.ok ? paid.value.overall : 'unprobed'})`
+ ? `answered in ${turn.ms}ms after ${turn.value.fallbacks.length} live demotion(s)${turn.value.fallbacks.length ? ` (${turn.value.fallbacks.join(' -> ')})` : ', lead provider served directly'}; paid tier ${paidLive} live (${paid.ok ? paid.value.overall : 'unprobed'})`
: turn.error,
pass: turn.ok,
});
@@ -305,7 +308,7 @@ async function run() {
for (const rung of r.rungs) {
console.log(` ${rung.ok ? 'up ' : 'down'} ${String(rung.rung).padEnd(38)} ${rung.ok ? `${rung.ms}ms` : rung.error}`);
}
- console.log(` failover proven: ${r.failoverProven ? 'yes' : 'NO'} — ${r.failoverDetail}\n`);
+ console.log(` failover proven: ${r.failoverProven ? 'yes' : 'NO'} (${r.failoverDetail})\n`);
}
if (jsonPath) {
@@ -313,7 +316,7 @@ async function run() {
console.log(`report → ${jsonPath}`);
}
- console.log(pass ? 'All event-path dependencies survive losing their primary.' : 'At least one dependency has no proven failover — see FAIL above.');
+ console.log(pass ? 'All event-path dependencies survive losing their primary.' : 'At least one dependency has no proven failover, see FAIL above.');
process.exit(pass ? 0 : 1);
}
diff --git a/scripts/play-perf-audit.mjs b/scripts/play-perf-audit.mjs
index d11596801..5fd5a3d58 100644
--- a/scripts/play-perf-audit.mjs
+++ b/scripts/play-perf-audit.mjs
@@ -122,7 +122,9 @@ const frameStats = async (reset = false) => {
};
console.log(at(), 'goto', TARGET.slice(0, 120));
-await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 60000 });
+// Generous: an unbundled dev server serves the world as ~1500 separate module
+// requests, and a software rasterizer makes the first paint slow on top of that.
+await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 180000 });
try {
await page.waitForSelector('.pi-btn-primary', { timeout: 25000 });
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 5b59dff90..f4b2744c7 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -998,6 +998,36 @@ export class CoinCommunities {
this._tickDanceFloor(dt);
}
+ // One decode and one GPU upload of the coin's artwork, shared by every surface
+ // that shows it: the totem's two faces and the jumbotron's art panel.
+ //
+ // Each surface used to run its own TextureLoader against the same URL. The
+ // HTTP cache deduped the download, so this looked free, but it isn't: the
+ // browser decoded the image twice and three.js uploaded two independent
+ // textures to the GPU. Token art routinely runs past half a megabyte (the
+ // flagship $THREE image is 567 KB), and that second decode + upload lands
+ // squarely inside world entry, where the frame budget is already spent.
+ //
+ // The promise is memoized per URL for the life of the world and dropped in
+ // leave(), so the next coin loads its own art and this one's texture is freed
+ // with the meshes that carry it.
+ _loadCoinArt(url) {
+ if (!url) return Promise.resolve(null);
+ if (this._coinArt?.url === url) return this._coinArt.promise;
+ const promise = new Promise((resolve) => {
+ new TextureLoader().load(
+ url,
+ (tex) => { tex.colorSpace = SRGBColorSpace; resolve(tex); },
+ undefined,
+ // Blocked or broken art is not fatal: the totem keeps its gold disc and
+ // the jumbotron keeps its text. Resolve null so callers just skip.
+ () => resolve(null),
+ );
+ });
+ this._coinArt = { url, promise };
+ return promise;
+ }
+
// Central coin totem — the community's banner in 3D.
_buildTotem(coin) {
const g = new Group();
@@ -1014,13 +1044,15 @@ export class CoinCommunities {
spin.add(disc);
this._totemDisc = disc;
if (coin.image) {
- new TextureLoader().load(coin.image, (tex) => {
- tex.colorSpace = SRGBColorSpace;
+ this._loadCoinArt(coin.image).then((tex) => {
+ // Left the world (or hopped coins) while the art was decoding: `spin` is
+ // detached and already disposed, so anything added now would leak.
+ if (!tex || this._coinSpin !== spin) return;
const face = new Mesh(new CircleGeometry(1.9, 40), new MeshBasicMaterial({ map: tex }));
face.position.set(0, 0, 0.18); spin.add(face);
const back = new Mesh(new CircleGeometry(1.9, 40), new MeshBasicMaterial({ map: tex }));
back.position.set(0, 0, -0.18); back.rotation.y = Math.PI; spin.add(back);
- }, undefined, () => { /* image blocked — totem still shows */ });
+ });
}
g.add(spin);
this._coinSpin = spin;
@@ -1075,13 +1107,14 @@ export class CoinCommunities {
// the totem) overlaid on the panel's left third, so compositing the image
// into the canvas can never taint it.
if (coin.image) {
- new TextureLoader().load(coin.image, (imgTex) => {
- imgTex.colorSpace = SRGBColorSpace;
+ this._loadCoinArt(coin.image).then((imgTex) => {
+ // Same guard as the totem: never graft art onto a disposed screen.
+ if (!imgTex || this._screen !== g) return;
imgTex.anisotropy = screenAnisotropy();
const art = new Mesh(new PlaneGeometry(8.4, 8.4), screenMaterial(imgTex));
art.position.set(-6.7, 11, 0.04); g.add(art);
this._screenArt = art;
- }, undefined, () => { /* image blocked — panel still shows text */ });
+ });
}
// A LIVE bar that pulses along the panel's base (animated in _tickEnv) — the
@@ -2094,6 +2127,11 @@ export class CoinCommunities {
this._screen = null; this._screenCanvas = null; this._screenTex = null;
this._screenArt = null; this._screenPulse = null;
}
+ // The shared coin-art texture is disposed with the meshes above (both the
+ // totem and the screen carry it, and a second dispose() on an already-freed
+ // texture is a no-op). Drop the memo so the next coin loads its own art
+ // rather than inheriting a disposed texture from this world.
+ this._coinArt = null;
if (this._chartScreen) { this._chartScreen.dispose(); this._chartScreen = null; }
if (this._oracleRibbon) { this._oracleRibbon.dispose(); this._oracleRibbon = null; }
if (this._agentDesks?.length) {
diff --git a/tests/sniper-solvency.test.js b/tests/sniper-solvency.test.js
index 6a85b2a83..3842ec8e6 100644
--- a/tests/sniper-solvency.test.js
+++ b/tests/sniper-solvency.test.js
@@ -1,4 +1,4 @@
-// Unit tests for api/_lib/sniper-solvency.js — the fleet's "can it afford to
+// Unit tests for api/_lib/sniper-solvency.js: the fleet's "can it afford to
// trade at all?" verdict.
//
// The incident this pins down: from 2026-07-29 to 2026-08-08 the sniper fleet
@@ -12,7 +12,7 @@
// The load-bearing invariant here is the LAST describe block: solvency must be
// decided by resolveEntrySize, the same function the executor uses to size or
// skip a real entry. If these two ever disagree, the status page starts claiming
-// wallets are tradeable that the executor silently skips — the original bug,
+// wallets are tradeable that the executor silently skips: the original bug,
// one level up.
//
// Pure functions, no mocks needed.
@@ -22,6 +22,7 @@ import {
walletTradeState,
summarizeFleetSolvency,
describeSolvency,
+ deriveSniperState,
MASTER_COVER_BUFFER_SOL,
} from '../api/_lib/sniper-solvency.js';
import { resolveEntrySize, MIN_OPERATIONAL_WALLET_SOL } from '../api/_lib/agent-trade-guards.js';
@@ -146,6 +147,40 @@ describe('describeSolvency', () => {
});
});
+describe('deriveSniperState', () => {
+ const healthy = { alive: true, feedLive: true, feedSilent: false };
+
+ it('reports live only when the process, the feed, and the money are all fine', () => {
+ expect(deriveSniperState({ ...healthy, solvencyState: 'funded' })).toBe('live');
+ });
+
+ it('does NOT report live for a starved fleet (the ten-day bug)', () => {
+ // Exactly the observed production state: heartbeat fresh, feed connected,
+ // strategies armed, wallets empty. This used to return 'live'.
+ expect(deriveSniperState({ ...healthy, solvencyState: 'starved' })).toBe('starved');
+ });
+
+ it('ranks a dead process above every other signal', () => {
+ expect(deriveSniperState({ alive: false, feedLive: false, feedSilent: true, solvencyState: 'starved' })).toBe('down');
+ });
+
+ it('ranks starvation above a feed problem (the more actionable diagnosis)', () => {
+ expect(deriveSniperState({ alive: true, feedLive: false, feedSilent: true, solvencyState: 'starved' })).toBe('starved');
+ });
+
+ it('degrades on a silent feed or a partially starved fleet', () => {
+ expect(deriveSniperState({ ...healthy, feedSilent: true, solvencyState: 'funded' })).toBe('degraded');
+ expect(deriveSniperState({ ...healthy, solvencyState: 'degraded' })).toBe('degraded');
+ });
+
+ it('never downgrades on an unmeasured fleet', () => {
+ // Older worker builds publish no solvency at all; absence must not read as
+ // insolvency, or every pre-upgrade deploy would page as broken.
+ expect(deriveSniperState({ ...healthy, solvencyState: 'unknown' })).toBe('live');
+ expect(deriveSniperState(healthy)).toBe('live');
+ });
+});
+
describe('solvency agrees with the executor (no second source of truth)', () => {
// Sweep the whole interesting range and assert the two never disagree about
// whether a wallet can trade. This is the drift guard: solvency must ask