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.

perf(economy-lab): settle a refused hour in one step and retire the lab audit

nirholas7a3bb08f9185
diff --git a/api/_lib/x402/runway-sim.js b/api/_lib/x402/runway-sim.js
index 6d646c462..caedbb8c8 100644
--- a/api/_lib/x402/runway-sim.js
+++ b/api/_lib/x402/runway-sim.js
@@ -146,6 +146,24 @@ export function simulateRunway(input = {}) {
const hourOfDay = (startHourOfDay + h) % 24;
let hourBudget = budgetAt(lamports, hourOfDay);
+ // A refusal mutates nothing: not the balance, not the day's meter. So the
+ // first refusal inside an hour decides every remaining attempt in that
+ // hour, and the rest of the loop can be settled in one step instead of one
+ // iteration each. This is an exact shortcut, not an approximation, and it
+ // is what keeps the starved case (where every attempt refuses, and the fee
+ // wallet under its floor right now is exactly that case) from costing a
+ // slider drag hundreds of milliseconds.
+ //
+ // Declared per hour rather than per attempt on purpose: a closure built
+ // inside the attempt loop doubled the cost of the admit path it was not
+ // even helping.
+ const batchAfter = (i) => {
+ const left = demandPerHour - i - 1;
+ const allowance = MAX_ATTEMPTS - attempts;
+ if (left > allowance) { truncated = true; return allowance; }
+ return left;
+ };
+
for (let i = 0; i < demandPerHour; i++) {
if (attempts >= MAX_ATTEMPTS) { truncated = true; break; }
attempts++;
@@ -156,11 +174,13 @@ export function simulateRunway(input = {}) {
// settle and lands just under it. That is production's comparison,
// reproduced rather than rounded away.
if (lamports < floorLamports) {
- hourRefusedFloor++;
+ const batch = 1 + batchAfter(i);
+ hourRefusedFloor += batch;
+ attempts += batch - 1;
lastReason = `fee_wallet_below_floor:${lamports}<${floorLamports}`;
if (floorBreachHour === null) floorBreachHour = h;
if (firstRefusalHour === null) firstRefusalHour = h;
- continue;
+ break;
}
// (1b) With a floor at or near zero the floor check stops binding and
@@ -168,11 +188,13 @@ export function simulateRunway(input = {}) {
// account does not hold. Same bucket as the floor (both are "the wallet
// is out of SOL"), distinct reason so the cause stays legible.
if (lamports < feeLamports) {
- hourRefusedFloor++;
+ const batch = 1 + batchAfter(i);
+ hourRefusedFloor += batch;
+ attempts += batch - 1;
lastReason = `insufficient_lamports_for_fee:${lamports}<${feeLamports}`;
if (floorBreachHour === null) floorBreachHour = h;
if (firstRefusalHour === null) firstRefusalHour = h;
- continue;
+ break;
}
// (2) Wallet fee governor, recomputed per settle from the live balance
@@ -184,10 +206,12 @@ export function simulateRunway(input = {}) {
spentTodayLamports: spentToday, budgetLamports, nextFeeLamports: feeLamports,
});
if (!verdict.ok) {
- hourRefusedGovernor++;
+ const batch = 1 + batchAfter(i);
+ hourRefusedGovernor += batch;
+ attempts += batch - 1;
lastReason = verdict.reason;
if (firstRefusalHour === null) firstRefusalHour = h;
- continue;
+ break;
}
}
diff --git a/prompts/swarm-100/route-economy-lab.md b/prompts/swarm-100/route-economy-lab.md
deleted file mode 100644
index 10de39081..000000000
--- a/prompts/swarm-100/route-economy-lab.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Route audit: /economy-lab (Runway Lab)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. This route's declared entry (path, description, added date):
-
- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/economy-lab')console.log(JSON.stringify(g,null,2))"
-
-2. Find the serving implementation: grep "/economy-lab" in vercel.json (the live
- route table server/index.mjs boots from), then list matching files in
- pages/ and src/. STRUCTURE.md maps every surface to its directory if the
- grep is ambiguous.
-3. Production right now:
-
- curl -so /dev/null -w '%{http_code}\n' https://three.ws/economy-lab
-
-4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).
-
-## Task: audit this one route end to end, then fix everything found
-
-Route: /economy-lab ("Runway Lab", section "labs").
-Declared purpose: A live digital twin of the three.ws x402 payment rail. Runs the exact admission-control code the production settle path runs, seeded with live production balances, so you can drag a knob and watch settlement survive or starve, then get the exact command that fixes it.
-
-Drive the page in a real headless browser. Playwright is already a dev
-dependency; keep your probe script in the session scratchpad, never in the
-repo.
-
-1. Load http://localhost:3000/economy-lab. Record the HTTP status, every console
- error and warning, and every failed network request.
-2. Exercise it like a first-time user: click the primary actions, run the
- primary flow if one exists, follow the page's internal links. Every button
- must do something real; every link must resolve. If the page renders data,
- prove in the network log that it came from a live endpoint, not a baked-in
- fallback array.
-3. States: verify populated, empty, loading, and error states are designed and
- reachable. Block the page's primary fetch in Playwright and confirm an
- actionable error state appears, not a blank void or a raw exception.
-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no
- overlapping or clipped controls.
-5. Accessibility basics: one h1; interactive elements are real buttons or
- links with visible focus states; images carry alt text; form fields have
- labels.
-6. Head: a specific title tag and meta description that match the declared
- purpose above.
-7. Fix every defect at its root in the page's real source files and re-run the
- probe until clean. Defects in shared modules are in scope when this route
- exercises them.
-
-## Definition of done
-
-- [ ] Local load of /economy-lab: HTTP 200, zero console errors, zero unhandled
- failed requests (a third-party outage must land in a designed fallback,
- not a broken page).
-- [ ] No dead interactive element on the page: no stub href="#", no button
- without a handler, no link to a missing path.
-- [ ] Empty, loading, error, and populated states verified.
-- [ ] 320 / 768 / 1440 px renders verified clean.
-- [ ] Title and meta description present and specific.
-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.
-- [ ] Production status from step 0 recorded in the report; if production
- needs a deploy to pick up a fix, the report says so (deploys stay
- owner-gated).
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/route-economy-lab.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/src/economy-lab.js b/src/economy-lab.js
index 9d3a2c703..70e425ada 100644
--- a/src/economy-lab.js
+++ b/src/economy-lab.js
@@ -94,16 +94,27 @@ function initTooltips() {
const tip = $('el-tip');
if (!tip) return;
let current = null;
+ // A tip opened by hover is transient; one opened by a click is pinned until
+ // the reader dismisses it. Without that distinction a click could never open
+ // anything: the pointer's own mouseenter opened the tip first, so the click
+ // behind it always read as "already open, close it", and on touch (which
+ // synthesizes the same enter) the tip flashed and vanished.
+ let pinned = null;
const close = () => {
if (!current) return;
current.setAttribute('aria-expanded', 'false');
current.removeAttribute('aria-describedby');
current = null;
+ pinned = null;
tip.dataset.open = 'false';
tip.hidden = true;
};
+ const closeTransient = (btn) => {
+ if (pinned !== btn) close();
+ };
+
const open = (btn) => {
const text = btn.dataset.tip;
if (!text) return;
@@ -111,7 +122,6 @@ function initTooltips() {
tip.textContent = text;
tip.hidden = false;
tip.dataset.open = 'true';
- tip.id = 'el-tip';
btn.setAttribute('aria-expanded', 'true');
btn.setAttribute('aria-describedby', 'el-tip');
@@ -128,13 +138,13 @@ function initTooltips() {
for (const btn of document.querySelectorAll('.el-help')) {
btn.setAttribute('aria-expanded', 'false');
btn.addEventListener('mouseenter', () => open(btn));
- btn.addEventListener('mouseleave', close);
+ btn.addEventListener('mouseleave', () => closeTransient(btn));
btn.addEventListener('focus', () => open(btn));
- btn.addEventListener('blur', close);
+ btn.addEventListener('blur', () => closeTransient(btn));
btn.addEventListener('click', (e) => {
e.preventDefault();
- if (current === btn) close();
- else open(btn);
+ if (pinned === btn) close();
+ else { open(btn); pinned = btn; }
});
}
// Capture phase: site-wide scripts (nav, command palette) also listen for
@@ -814,6 +824,9 @@ function renderApply() {
}
// ── Observed panel ─────────────────────────────────────────────────────────
+// Built once from the seed. Everything in it is a measurement except the single
+// "Model, your config" cell, so rebuilding the whole panel (bars, examples and
+// all) on every slider frame was work that could only produce identical markup.
function renderObserved(summary) {
const o = seed.observed;
const host = $('el-observed');
@@ -822,6 +835,12 @@ function renderObserved(summary) {
return;
}
+ const modelled = $('el-obs-modelled');
+ if (modelled) {
+ modelled.textContent = `${fmtInt(summary.steadySettlesPerDay)}/day`;
+ return;
+ }
+
const total = Math.max(1, ...o.refusals.map((r) => r.count));
const causeLabel = {
governor: 'Out of daily fee budget',
@@ -854,7 +873,7 @@ function renderObserved(summary) {
<ul class="el-compare">
<li><span>Settles landed (24h)</span><strong>${fmtInt(o.settled)}</strong></li>
<li><span>Model, live config</span><strong>${liveEquilibrium === null ? 'not read' : fmtInt(liveEquilibrium)}/day</strong></li>
- <li><span>Model, your config</span><strong>${fmtInt(summary.steadySettlesPerDay)}/day</strong></li>
+ <li><span>Model, your config</span><strong id="el-obs-modelled">${fmtInt(summary.steadySettlesPerDay)}/day</strong></li>
<li><span>Capacity admission rate</span><strong>${fmtPct(o.capacity_admission_rate)}</strong></li>
<li><span>Demand arriving</span><strong>${fmtInt(o.demand_per_hour)}/hour</strong></li>
<li><span>Fee per settle</span><strong>${fmtInt(o.fee_lamports_observed)} lamports</strong></li>
@@ -935,6 +954,10 @@ function showLoading() {
$('el-retry').hidden = true;
$('el-stats').innerHTML = '<div class="el-stat el-skeleton" aria-hidden="true"></div>'.repeat(6);
$('el-live-note').hidden = true;
+ // Dropped rather than left standing: the observed panel is keyed off the
+ // seed, and its build-once path would otherwise keep the previous read's
+ // measurements alongside the new one's numbers.
+ $('el-observed').innerHTML = '';
setControlsEnabled(false);
}
diff --git a/tests/x402-runway-sim.test.js b/tests/x402-runway-sim.test.js
index 75907fcbf..fa1b94fce 100644
--- a/tests/x402-runway-sim.test.js
+++ b/tests/x402-runway-sim.test.js
@@ -271,6 +271,31 @@ describe('simulateRunway — input hardening', () => {
expect(summary.admissionRate).toBe(0);
});
+ // The refusal path settles a whole hour in one step once the first attempt is
+ // refused (nothing a refusal touches can change the next attempt's outcome).
+ // These pin that the shortcut is exact: same attempt counts, same per-hour
+ // breakdown, same MAX_ATTEMPTS ceiling as counting one at a time.
+ it('accounts for every attempt in an hour that refuses from the first settle', () => {
+ const { summary, series } = simulateRunway({
+ startLamports: 0, floorLamports: 2_000_000, runwayDays: 3,
+ minBudgetLamports: 10_000_000, feeLamports: 5_000, demandPerHour: 137, hours: 5,
+ });
+ expect(summary.demanded).toBe(137 * 5);
+ expect(summary.refusedFloor).toBe(137 * 5);
+ expect(summary.admitted).toBe(0);
+ expect(series).toHaveLength(5);
+ for (const s of series) expect(s.refusedFloor).toBe(137);
+ });
+
+ it('still stops at MAX_ATTEMPTS when the refusal path is batched', () => {
+ const { summary } = simulateRunway({
+ startLamports: 0, floorLamports: 2_000_000, runwayDays: 3,
+ minBudgetLamports: 10_000_000, feeLamports: 5_000, demandPerHour: 200_000, hours: 24,
+ });
+ expect(summary.demanded).toBe(MAX_ATTEMPTS);
+ expect(summary.truncated).toBe(true);
+ });
+
it('never lets the balance go negative', () => {
const { summary } = simulateRunway({
startLamports: 12_000, floorLamports: 0, runwayDays: 0.5,