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): economy lab, solver, pay simulator and money flow map
nirholas195505b61ac9
diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.jsindex 41d4fb43a..d15db5300 100644--- a/api/_lib/economy-sweepback.js+++ b/api/_lib/economy-sweepback.js@@ -651,16 +651,31 @@ export async function reclaimIdleAgentSol({ connection, network = 'mainnet', dryconst secrets = new Map(candidates.map((c) => [c.agentId, c.secret]));const { recoverSolanaAgentKeypair } = await import('./agent-wallet.js');for (const p of plan) {+ // Recovery and broadcast are reported SEPARATELY on purpose. Sharing one+ // catch made an undecryptable wallet secret surface as a failed send, and+ // the alert then read "N failed send(s): The operation failed for an+ // operation-specific reason": a WebCrypto AES-GCM OperationError wearing+ // a Solana costume. That sent operators after RPC health and funding for a+ // key problem no amount of either could fix.+ let keypair;try {- const keypair = await recoverSolanaAgentKeypair(secrets.get(p.agentId), {+ 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;- }+ } catch (e) {+ failed.push({+ name: p.name, address: p.address, sol: p.sol, stage: 'recover',+ reason: `secret_undecryptable: ${e?.message || 'unknown'}`,+ });+ continue;+ }+ if (keypair.publicKey.toBase58() !== p.address) {+ failed.push({ name: p.name, address: p.address, sol: p.sol, stage: 'recover', reason: 'keypair_address_mismatch' });+ continue;+ }+ try {const signature = await sendSol({connection,fromKeypair: keypair,@@ -671,7 +686,7 @@ export async function reclaimIdleAgentSol({ connection, network = 'mainnet', dry});moves.push({ ...p, signature });} catch (e) {- failed.push({ name: p.name, address: p.address, sol: p.sol, reason: e?.message || 'send_failed' });+ failed.push({ name: p.name, address: p.address, sol: p.sol, stage: 'send', reason: e?.message || 'send_failed' });}}diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.jsindex 9c1fae084..fe0ddfc0b 100644--- a/api/cron/treasury-topup.js+++ b/api/cron/treasury-topup.js@@ -239,15 +239,31 @@ export default wrapCron(async (req, res) => {const legErrors = [reclaim.error, agentReclaim.error].filter(Boolean);const blocked = readErrors.length + failedSends.length + legErrors.length > 0;const sample = readErrors[0]?.reason || failedSends[0]?.reason || legErrors[0] || '';+ // A recovery failure and a broadcast failure are both "failed" but have+ // nothing else in common. Undecryptable secrets are a KEY problem: the SOL+ // in those wallets is unreachable until the right WALLET_ENCRYPTION_KEY is+ // present, and no RPC tier or deposit changes that. Counting them as failed+ // sends is what pointed the 2026-07-31 investigation at RPC health for an+ // AES-GCM OperationError.+ const undecryptable = failedSends.filter((f) => String(f?.reason || '').startsWith('secret_undecryptable'));+ const sendFailures = failedSends.filter((f) => f?.stage === 'send');if (blocked) {+ const strandedSol = undecryptable.reduce((s, f) => s + (Number(f?.sol) || 0), 0);await sendOpsAlert('♻️ Economy self-heal BLOCKED: reclaim could not run',`Deficit ${totalDeficitSol.toFixed(4)} SOL, reclaimed only ${reclaimedTotal} SOL. ` +- `${readErrors.length} balance read error(s), ${failedSends.length} failed send(s)` ++ `${readErrors.length} balance read error(s), ${sendFailures.length} failed send(s), ` ++ `${undecryptable.length} undecryptable wallet secret(s)` +`${legErrors.length ? `, ${legErrors.length} leg error(s)` : ''}. First: ${String(sample).slice(0, 180)}. ` +'An `rpc_error` here means the Solana RPC tier is exhausted, NOT that the wallets are dry: ' +'idle SOL may still be sitting in agent wallets that could not be read. Check ' +- 'healthz rpc_lanes and the provider quotas before sending any funds.',+ 'healthz rpc_lanes and the provider quotas before sending any funds.' ++ (undecryptable.length+ ? ` ${strandedSol.toFixed(4)} SOL is stranded behind secrets this deploy cannot decrypt ` ++ `(${undecryptable.map((f) => f.name).slice(0, 4).join(', ')}). That is a KEY problem, not an RPC or ` ++ 'funding one: verify WALLET_ENCRYPTION_KEY matches the key those wallets were encrypted with. ' ++ 'Reclaim will keep skipping them until it does, so exclude that SOL from any runway estimate.'+ : ''),{ signature: 'economy-selfheal-blocked', severity: 'warn' },);} else {diff --git a/api/x402/runway-lab.js b/api/x402/runway-lab.jsindex e7987de72..c4f037941 100644--- a/api/x402/runway-lab.js+++ b/api/x402/runway-lab.js@@ -129,20 +129,34 @@ async function observeWindow() {const attempts = Number(totals?.attempts ?? 0);const settled = Number(totals?.settled ?? 0);const feeMedian = Number(totals?.fee_median ?? 0);+ const refusalList = [...buckets.values()].sort((a, b) => b.count - a.count);+ // Capacity refusals only: what the rail could not AFFORD, as opposed to what+ // it correctly declined. This is the number the projection is comparable to.+ const capacityRefused = refusalList+ .filter((b) => CAPACITY_CAUSES.has(b.cause))+ .reduce((n, b) => n + b.count, 0);+ const capacityAttempts = settled + capacityRefused;return {window_hours: WINDOW_HOURS,attempts,settled,refused: attempts - settled,+ capacity_refused: capacityRefused,+ // Share of settles the rail could afford, excluding duplicates and the+ // dust guard. Compare THIS against the simulated admission rate.+ capacity_admission_rate: capacityAttempts > 0 ? settled / capacityAttempts : null,admission_rate: attempts > 0 ? settled / attempts : null,fee_total_lamports: Number(totals?.fee_total ?? 0),// Median over landed settles is the honest per-settle cost: the mean is// dragged by the occasional multi-signature transaction.fee_lamports_observed: feeMedian > 0 ? feeMedian : MIN_FEE_LAMPORTS,fee_source: feeMedian > 0 ? 'observed_median_24h' : 'base_fee_default',- demand_per_hour: Math.round(attempts / WINDOW_HOURS),- refusals: [...buckets.values()].sort((a, b) => b.count - a.count),+ // Real arrival rate, so the projection starts from measured demand rather+ // than a guess. Duplicates are excluded: they are retries of a settle that+ // already landed, not new demand on the rail.+ demand_per_hour: Math.round(capacityAttempts / WINDOW_HOURS),+ refusals: refusalList,};}diff --git a/docs/economy-solver.md b/docs/economy-solver.mdnew file mode 100644index 000000000..bd46e2717--- /dev/null+++ b/docs/economy-solver.md@@ -0,0 +1,227 @@+# The economy solver++The [in-game economy reference](in-game-economy.md) publishes **what** the `/play`+world charges. The solver publishes **what those numbers mean**: the exact expected+cash, XP and goods per hour of every action in the world, at every skill level.++- **Live page:** [three.ws/play/solver](https://three.ws/play/solver)+- **Endpoint:** `GET /api/play/solver`+- **Model:** [`multiplayer/src/rate-model.js`](https://github.com/nirholas/three.ws/blob/main/multiplayer/src/rate-model.js)++---++## Why this is computable at all++Most games make you measure. You grind for an hour, count what you got, and post an+average on a wiki that is stale by the next balance patch.++The `/play` world does not need that, because of how it is built:++- Every yield rule is a **pure function** of your skill level and the node you are+ standing at. `gatherChance`, `gatherDoubleChance`, `coalBonusChance`,+ `cookBurnChance`, `fishCatchChance` and `fishDoubleChance` all live in+ `multiplayer/src/items.js` and take no state beyond their arguments.+- Every swing has a **fixed cadence** the server enforces, in+ `ACTIVITY_COOLDOWN_MS` (`multiplayer/src/activities.js`).+- Every item has **one price**, in `multiplayer/src/shop.js`.++Given those three facts, expected value per hour is arithmetic. There is nothing to+sample and no error bar. The solver does that arithmetic against the same modules+the authoritative server rolls against, so it cannot drift: change a price or a+curve upstream and every rate moves with it on the next request.++---++## What it solves++### Per-node rates++Every tree, rock and pond in the world, priced separately. Nodes differ: a tree's+`difficulty` divides its success chance, a rock also carries a `coal` weight that+raises its bonus-coal odds, and a pond's `quality` multiplies both catch rate and+double-haul odds.++That produces a question the game gives you no way to answer in-world: **is the+harder node worth standing at?** A tougher rock yields less often but drops coal+more readily, and coal is worth three times stone. Only the arithmetic settles it.++The solver settles it, and publishes the answer as a finding.++### The fish-and-cook split++Cooked fish sells for three times raw fish. But cooking consumes a raw fish per+attempt and you cannot fish and cook at the same time, so the real question is how+to divide an hour between them.++Let `R` be fish caught per hour of pure fishing and `C` cooking attempts per hour.+Spending fraction `t` of the hour fishing produces `t·R` fish and consumes+`(1 − t)·C`. Supply meets demand at:++```+t = C / (R + C)+```++At that split nothing queues and nothing idles, and it is the only split where that+is true. Everything else follows: cooked fish per hour, cash per hour, and the+uplift over simply selling raw.++### Payback in playtime++Every store entry priced against the best rate you can actually hold, in minutes+and in swings. Bundles report their per-unit price, because a sticker price on a+stack of twelve is not comparable to one on a single item.++### The wheel, in store prices++Valuing each wedge at what the general store would pay for it turns Fortune's Folly+from a mystery into a number: expected value, standard deviation, and the share of+outcomes that land at or above the mean. On a table with one jackpot wedge, the+average outcome is not the typical one, and the solver says so.++### Combat, per kill++Priced per kill rather than per hour, deliberately. Kill speed depends on your+weapon, your aim and how fast the world respawns, none of which is a constant the+model can honestly assume. So it publishes expected cash per kill (flat gold plus+every loot line at store prices) and lets you supply your own kill rate.++Loot rolls are independent, so the expectations simply add. Mounts have no sell+price and never inflate a cash figure, but their odds are reported.++---++## Two things the model refuses to do++**It never ranks a rate you cannot hold.** Cooking's standalone ceiling is the+largest number in the table, and it is unreachable: it needs thousands of raw fish+an hour delivered by someone who is not you. Every row carries a `sustainable` flag,+unsustainable rows always sort last regardless of size, and payback is never quoted+against one. Ranking a number nobody can hold above one anybody can would make the+whole table advice you cannot follow.++**It never hides its assumptions.** Every response ships the list, because a rate+quoted without its assumptions is a lie:++1. Uninterrupted action, with no walking, travel or downtime.+2. Pack space is available. Every row also reports the exact hour an empty pack+ fills at its rate, so you can see where that assumption breaks.+3. Items are valued at the store sell price. The world has no player market.+4. Skill level is held fixed for the hour, so a sustained session slightly beats the+ number shown for its starting level.+5. Mount drops are reported as odds only.++---++## Exactness++The game's XP award wraps `Math.round` around a uniform integer roll:++```js+const xp = Math.round((9 + Math.floor(Math.random() * 5) + lvl * 0.3) * difficulty) * got;+```++Rounding is not linear, so `E[round(X)] ≠ round(E[X])`. Substituting the mean of the+roll gives an answer that is close and wrong. The model sums over the roll's real+support instead:++```js+function expectedRoundedXp(base, span, level, mult) {+ let total = 0;+ for (let k = 0; k < span; k += 1) total += Math.round((base + k + level * 0.3) * mult);+ return total / span;+}+```++The spans are 5 and 6, so the exact sum costs the same as the shortcut would have.++That claim is pinned by test, not by assertion.+[`tests/rate-model.test.js`](https://github.com/nirholas/three.ws/blob/main/tests/rate-model.test.js)+drives the **real production handlers** (`handleGather`, `handleCook` from+`activities.js`) against a seeded PRNG for 40,000 swings and checks the observed+mean lands inside the sampling interval around the closed form. The simulation is an+independent second implementation: the analytic path reads the probability curves,+the empirical path runs the actual game code, and the two have to meet. Change a+handler without changing the model, or a curve without changing the handler, and it+goes red.++---++## Using the endpoint++```bash+curl -s 'https://three.ws/api/play/solver?level=30&curves=0' | jq '.bestRate, .loop'+```++```json+{+ "label": "Fish pond-west and cook",+ "key": "loop:fish-cook",+ "cashPerHour": 12723.19,+ "attemptsPerHour": 2400+}+{+ "key": "loop:fish-cook",+ "family": "loop",+ "label": "Fish pond-west and cook",+ "fishSharePct": 68.83,+ "cookSharePct": 31.17,+ "cookedPerHour": 1413.69,+ "cashPerHour": 12723.19,+ "rawOnlyCashPerHour": 6825.6,+ "upliftPct": 86.4,+ "sustainable": true+}+```++### Query parameters++| Parameter | Default | Meaning |+| --- | --- | --- |+| `level` | `1` | Skill level to solve at, 1 to 99. Out-of-range values are clamped rather than rejected, and the response sets `levelClamped: true` so you can tell. |+| `curves` | on | Set `curves=0` to drop the 99-level sweep. The sweep is about 20 KB and exists so a client can move a level control without a round trip. |++### Response shape++| Field | What it holds |+| --- | --- |+| `level`, `levelCap` | The solved level, and the game's cap. |+| `activities[]` | Every node in the world at this level: hit rate, units, coal, cash and XP per hour, plus `sustainable`, `requires` and `packHours`. |+| `best` | The top row per family, keyed by `chop`, `mine`, `fish`, `cook`. |+| `bestRate`, `bestXpRate` | The highest cash and XP rates a player can actually hold. Reported separately because they are rarely the same activity. |+| `loop` | The fish-and-cook split, its cash rate, and the uplift over selling raw. |+| `findings[]` | Conclusions derived from the numbers above. Each has `id`, `kind` (`trap`, `reward` or `context`), `title` and `detail`. |+| `payback[]` | Every store entry in minutes and swings at `bestRate`. |+| `wheel` | Expected value, standard deviation, best and worst wedge, and the free lane's daily worth. |+| `combat[]` | Per-kill XP, gold, loot value and mount odds for every mob, with its drop table. |+| `nextLevel` | XP, hours and minutes to the next level at the best XP rate. `null` at the cap. |+| `curves[]` | Per-node `cash` and `xp` arrays of length 99, one entry per level. |+| `assumptions[]`, `method` | The model's own caveats and its audit trail of source modules. |++Cached `public, max-age=300, s-maxage=3600, stale-while-revalidate=86400`. The body+is static config that only changes when the game's tables change, which ships as a+deploy.++---++## Where the code lives++| Piece | File |+| --- | --- |+| The model | `multiplayer/src/rate-model.js` |+| The endpoint | `api/play/solver.js` |+| The page | `pages/play/solver.html`, `src/play-solver.js`, `src/play-solver.css` |+| Model tests, including the simulation cross-check | `tests/rate-model.test.js` |+| Endpoint contract tests | `tests/api/play-solver.test.js` |+| Yield curves the model reads | `multiplayer/src/items.js` |+| Cadences the model divides by | `multiplayer/src/activities.js` |+| Prices the model values yields at | `multiplayer/src/shop.js` |+| Per-node tuning | `multiplayer/src/world-features.js` |++## Next++- **[The in-game economy](in-game-economy.md)** is the raw reference: every catalog,+ gate, settlement path and the JSON wire format.+- **[Earn and spend in /play](tutorials/earn-and-spend-in-play.md)** walks the loop+ by hand, in the world.+- **[three.ws/play/solver](https://three.ws/play/solver)** is the interactive version+ of everything above.diff --git a/docs/money-flow-map.md b/docs/money-flow-map.mdnew file mode 100644index 000000000..f882ca390--- /dev/null+++ b/docs/money-flow-map.md@@ -0,0 +1,229 @@+# Money Flow Map++**[`/flow`](https://three.ws/flow)** draws the *shape* of the three.ws agent+economy: who paid whom, for which skill, and how much.++Every other economy surface here is a ranking. [`/pulse`](https://three.ws/pulse)+streams events, [`/agent-economy-volume`](https://three.ws/agent-economy-volume)+totals them per agent, [`/admin/economy`](https://three.ws/admin/economy) reads+the funding chain. None of them can show **topology**, and topology is what+diagnoses the platform's real failure mode.++An agent that earns steadily and never spends again looks perfect on a top-earners+list. On a graph it is unmistakable: arrows arrive, none leave. That is capital+dispersion, money entering the fleet and never circulating back out, and it is+the difference between an economy and a drain.++---++## What an edge is++Two sources, both already-public on-chain movements, each with an+explorer-verifiable signature:++| Edge | Direction | Source | Carries |+|---|---|---|---|+| **Skill payment** | payer agent → payee wallet | `agent_custody_events`, `category='x402'` | `meta.to` (payee), `meta.service` (the skill bought) |+| **Tip** | payer wallet → recipient agent | `agent_custody_events`, `event_type='tip'` | `meta.from` (payer) |++There is no third, inferred edge type. If the platform is quiet the map is+honestly empty rather than padded with estimates.++**Marketplace purchases are deliberately excluded.** They settle in `$THREE`+from a human buyer, so they are not agent-to-agent, and folding them in would+silently mix a second denomination into the USD totals.++---++## Who gets named++The privacy contract is identical to the live feed on the side we own: no+deleted agents, no private agents, and no agent that set `pulse_opt_out`.++For the **counterparty** side the rule is stricter than it looks:++- A counterparty wallet is **named** only when it resolves to a public,+ non-opted-out agent identity.+- Anything else stays an **address-only node**, drawn with a dashed ring. The+ address itself is already public on-chain, and `/api/pulse` already exposes it+ as `counterparty`, so this reveals nothing new.++The payload carries `meta.to_agent` (a payee's name) for some payments. The map+never uses it. Names come only from a DB identity that passed the gate, so a+private agent cannot be named by a field written at payment time.++---++## Roles++A node's role comes from how lopsided its flow is, not from how big it is. The+thresholds live in [`src/flow-map-core.js`](../src/flow-map-core.js) as+`SOURCE_RATIO`, `SINK_RATIO` and `HUB_PARTNERS`.++| Role | Rule | Reads as |+|---|---|---|+| **Source** | ≥85% of its value went out | Where money enters the loop |+| **Sink** | ≤15% of its value went out | Capital stops circulating here |+| **Hub** | Two-way, ≥4 distinct partners | The load-bearing middle |+| **Relay** | Two-way, few partners | Earns and spends on a couple of routes |+| **Quiet** | No settled value at all | Present, but moved nothing |++Two decisions in there matter more than the numbers:++**`quiet` is checked first.** A node with zero flow has an undefined out-share.+Left to the ratio, `0/0` reads as "earns and never spends" and it would be+reported as a sink, inflating the dispersion number with nodes that did nothing.++**A hub is defined by reach, not by volume.** One agent paying another a hundred+times is a strong *edge*, not a hub. Counting distinct partners keeps "hub"+meaning what an operator expects it to mean.++---++## Stuck capital++The headline number. It is the share of all value received that ended up sitting+in sinks:++```+stuck = Σ (in − out) over sink nodes ÷ Σ in over all nodes+```++A closed loop trends toward **0%**: everything paid out comes back around. A+fleet quietly draining its treasury into agent wallets trends toward **100%**.+The tile turns amber past 40% and names the wallet holding the most.++This is the same failure this platform has actually hit. The x402 "the wallets+are dry" outages were never a leak; they were one-way dispersion into agent+wallets. On a leaderboard that is invisible. Here it is the first thing you see.++---++## The API++```bash+curl -s 'https://three.ws/api/pulse?view=graph&window=30d' | jq '.data.totals'+```++| Param | Values | Default |+|---|---|---|+| `window` | `24h`, `7d`, `30d`, `90d` | `30d` |+| `network` | `mainnet`, `devnet` | `mainnet` |++```jsonc+{+ "data": {+ "network": "mainnet",+ "window": "30d",+ "generated_at": "2026-07-31T06:00:00.000Z",+ "nodes": [+ {+ "id": "a:34d88eda-…", // "a:<agent id>" or "w:<wallet address>"+ "kind": "agent", // "agent" (named) | "wallet" (address only)+ "name": "Quill #22",+ "url": "/agent/34d88eda-…",+ "avatar_thumbnail_url": "https://…",+ "address": "2tXMdgPay…",+ "explorer": "https://solscan.io/account/…",+ "in_usd": 12.4, "out_usd": 3.1,+ "in_sol": 0.17, "out_sol": 0.04,+ "in_count": 9, "out_count": 2,+ "partners_in": 4, "partners_out": 1+ }+ ],+ "edges": [+ {+ "from": "a:00bf4380-…",+ "to": "w:BoG5QNQC…",+ "count": 7,+ "usd": 3.08,+ "sol": 0.042,+ "kinds": ["payment"],+ "services": ["fact-check", "market-scan"],+ "last_ts": "2026-07-30T05:03:11.691Z",+ "last_signature": "5xK…",+ "explorer": "https://solscan.io/tx/…"+ }+ ],+ "services": [{ "name": "lore-pack", "count": 39, "usd": 15.6 }],+ "totals": { "nodes": 108, "edges": 400, "transfers": 1177, "usd": 370.64, "named_agents": 94 },+ "truncated": true,+ "max_edges": 400+ }+}+```++Two fields worth reading before you trust a number:++- **`services` is computed separately from `edges`.** One edge can cover several+ skills, so folding its USD into each of them would report more revenue per+ service than actually settled.+- **`truncated`** is `true` when the window holds more routes than the cap. The+ cap keeps the largest by value, and the page says so rather than presenting a+ partial graph as the whole economy.++Cached for 60s server-side; the page refreshes every 60s and stops polling+entirely in a hidden tab.++---++## Reading the page++- **Dot size** is value handled (area, not radius, so a node ten times richer is+ not a hundred times the ink).+- **Moving dots** travel payer to payee. Direction is the whole point: a static+ undirected line cannot tell an earner from a payer.+- **A dashed ring** means an address-only counterparty.+- **Line colour** separates skill payments from tips, and line weight is value.++Filters: window, transfer kind, free-text search over name and address, and the+legend doubles as a per-role toggle. Filtering never leaves an edge with an+undrawn end, and a search keeps the matched wallet's whole neighbourhood, so you+never get a line into nowhere.++Keyboard: <kbd>/</kbd> focuses search, <kbd>r</kbd> refreshes, <kbd>Esc</kbd>+clears the selection. Scroll or the <kbd>+</kbd>/<kbd>−</kbd>/<kbd>⤢</kbd>+buttons zoom; drag pans.++**Accessibility is structural.** A canvas is unreachable by keyboard and screen+readers, so the table under the graph is not a fallback bolted on afterwards: it+renders from the same filtered data, every row is focusable, and selecting a row+selects the node. Role is always carried by text as well as colour.++---++## Extending it++All judgement lives in [`src/flow-map-core.js`](../src/flow-map-core.js), which+is pure: no DOM, no fetch, no globals. [`src/flow-map.js`](../src/flow-map.js) is+the canvas and DOM layer only.++```js+import { annotate, classifyRole, dispersion, rankSinks } from '../src/flow-map-core.js';++const graph = annotate(payload.data);+dispersion(graph); // → 0.62 (62% of received value is not circulating)+rankSinks(graph, 3); // → the three wallets holding the most stuck capital+classifyRole(graph.nodes[0]).hint;+```++The layout is a deterministic force simulation: same payload and seed, same+arrangement, asserted in+[`tests/flow-map-core.test.js`](../tests/flow-map-core.test.js). That is not+cosmetic. An operator comparing two windows needs to see the *topology* move,+not the layout reshuffle underneath them.++Adding a role, a metric, or a new edge source means editing the core and+covering it there. Keep the ordering discipline in `classifyRole`: a rule goes+**above** any rule it would invalidate.++---++## Related++- [Money Pulse](money-feed.md): the event stream these edges are aggregated from.+- [Economy health dashboard](economy-health-dashboard.md): the operator view of+ the funding chain that feeds these wallets.+- [Circulation engine](circulation-engine.md): what generates most of this+ activity.+- [Agent economy volume](agent-economy-volume.md): the per-agent totals, ranked.diff --git a/pages/conversions.html b/pages/conversions.htmlnew file mode 100644index 000000000..99e0d5214--- /dev/null+++ b/pages/conversions.html@@ -0,0 +1,204 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard: make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Trial Conversions · three.ws</title>+ <meta name="description" content="Every free trial you hold and every trial running on the skills you sell, with the runs left, the price to convert, and the revenue sitting in the queue." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ :root {+ --bg: #0d0d0d;+ --bg-2: #141414;+ --card: #181818;+ --line: rgba(255,255,255,0.07);+ --line-2: rgba(255,255,255,0.12);+ --text: #e7e9ee;+ --muted: rgba(231,233,238,0.55);+ --dim: rgba(231,233,238,0.35);+ --green: #4ade80;+ --amber: #f5a524;+ --red: #f87171;+ --violet: #a78bfa;+ --cyan: #57c7ff;+ --radius: 12px;+ --skeleton-base: rgba(255,255,255,0.04);+ --skeleton-sheen: rgba(255,255,255,0.08);+ --focus: #57c7ff;+ }+ [data-theme='light'] {+ --bg:#f5f5f5;--bg-2:#fff;--card:#fff;--line:rgba(0,0,0,.07);--line-2:rgba(0,0,0,.12);+ --text:#111;--muted:rgba(0,0,0,.58);--dim:rgba(0,0,0,.38);+ --skeleton-base:rgba(0,0,0,.04);--skeleton-sheen:rgba(0,0,0,.08);+ --green:#16a34a;--amber:#b45309;--red:#dc2626;--violet:#7c3aed;--cyan:#0369a1;+ }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ html, body { background: var(--bg); color: var(--text); font-family: 'Inter', system-ui, sans-serif; min-height: 100vh; }+ a { color: inherit; text-decoration: none; }+ :focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 6px; }++ .page-shell { max-width: 1100px; margin: 0 auto; padding: 0 20px 96px; }+ .page-hero { padding: 48px 0 24px; }+ .page-hero h1 { font-size: 28px; font-weight: 700; letter-spacing: -.02em; }+ .page-hero p { color: var(--muted); margin-top: 8px; font-size: 14px; max-width: 62ch; line-height: 1.55; }++ /* ── Role switch ─────────────────────────────────────────────── */+ .role-switch { display: inline-flex; gap: 4px; padding: 4px; background: var(--bg-2); border: 1px solid var(--line-2); border-radius: 10px; margin: 20px 0 32px; }+ .role-tab { appearance: none; background: none; border: 0; color: var(--muted); font: inherit; font-size: 13px; font-weight: 500; padding: 8px 16px; border-radius: 7px; cursor: pointer; transition: background .15s, color .15s; }+ .role-tab:hover { color: var(--text); }+ .role-tab[aria-selected='true'] { background: var(--card); color: var(--text); box-shadow: 0 1px 2px rgba(0,0,0,.25); }+ [data-theme='light'] .role-tab[aria-selected='true'] { box-shadow: 0 1px 2px rgba(0,0,0,.08); }+ .role-tab:active { transform: translateY(1px); }++ /* ── Stats ───────────────────────────────────────────────────── */+ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 32px; }+ .stat-card { background: var(--card); border: 1px solid var(--line-2); border-radius: var(--radius); padding: 18px; }+ .stat-val { font-size: 26px; font-weight: 700; letter-spacing: -.03em; font-variant-numeric: tabular-nums; }+ .stat-lbl { font-size: 12px; color: var(--muted); margin-top: 4px; }+ .stat-card.is-hot .stat-val { color: var(--amber); }+ .stat-card.is-money .stat-val { color: var(--green); }+ .stat-unit { font-size: 13px; font-weight: 600; color: var(--muted); margin-left: 4px; }++ /* ── Rows ────────────────────────────────────────────────────── */+ .cv-list { display: flex; flex-direction: column; gap: 10px; }+ .cv-row { background: var(--card); border: 1px solid var(--line-2); border-radius: var(--radius); padding: 16px; display: grid; grid-template-columns: 1fr auto; gap: 16px; align-items: center; transition: border-color .15s, transform .15s; }+ .cv-row:hover { border-color: rgba(255,255,255,.22); }+ [data-theme='light'] .cv-row:hover { border-color: rgba(0,0,0,.22); }+ .cv-main { min-width: 0; }+ .cv-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+ .cv-skill { font-size: 15px; font-weight: 600; letter-spacing: -.01em; }+ .cv-agent { font-size: 12px; color: var(--muted); margin-top: 3px; }+ .cv-agent a:hover { color: var(--text); text-decoration: underline; }++ .pill { font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 20px; border: 1px solid transparent; white-space: nowrap; }+ .pill-fresh { color: var(--cyan); border-color: color-mix(in srgb, var(--cyan) 40%, transparent); background: color-mix(in srgb, var(--cyan) 10%, transparent); }+ .pill-low { color: var(--amber); border-color: color-mix(in srgb, var(--amber) 45%, transparent); background: color-mix(in srgb, var(--amber) 12%, transparent); }+ .pill-out { color: var(--red); border-color: color-mix(in srgb, var(--red) 45%, transparent); background: color-mix(in srgb, var(--red) 12%, transparent); }++ /* Runs-left meter: the whole point of a metered trial, made visible.+ The track is a fixed width and the pips divide it, so a one-run+ grant reads as a full bar rather than a stray dash, and a ten-run+ grant reads as ten segments without running off the card. */+ .meter { display: flex; gap: 3px; margin-top: 10px; width: 100%; max-width: 190px; }+ .meter-pip { flex: 1 1 0; min-width: 4px; height: 6px; border-radius: 3px; background: var(--line-2); }+ .meter-pip.is-left { background: var(--cyan); }+ .meter-pip.is-left.is-low { background: var(--amber); }+ /* Spent: no pip is filled, so the track itself has to carry the state. */+ .meter.is-spent .meter-pip { background: color-mix(in srgb, var(--red) 28%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--red) 45%, transparent); }+ .meter-count { font-size: 12px; color: var(--muted); margin-top: 8px; font-variant-numeric: tabular-nums; }+ .meter-count strong { color: var(--text); font-weight: 600; }++ .cv-side { text-align: right; display: flex; flex-direction: column; align-items: flex-end; gap: 8px; }+ .cv-price { font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; }+ .cv-price small { font-size: 11px; font-weight: 500; color: var(--muted); margin-left: 3px; }+ .cv-priceless { font-size: 12px; color: var(--dim); }++ .btn { display: inline-flex; align-items: center; gap: 6px; font: inherit; font-size: 13px; font-weight: 600; padding: 8px 14px; border-radius: 8px; border: 1px solid var(--line-2); background: var(--bg-2); color: var(--text); cursor: pointer; transition: background .15s, border-color .15s, transform .12s; white-space: nowrap; }+ .btn:hover { border-color: rgba(255,255,255,.28); background: rgba(255,255,255,.05); }+ [data-theme='light'] .btn:hover { border-color: rgba(0,0,0,.28); background: rgba(0,0,0,.03); }+ .btn:active { transform: translateY(1px); }+ .btn-primary { background: var(--text); color: var(--bg); border-color: transparent; }+ .btn-primary:hover { background: var(--text); opacity: .88; }++ /* Seller metrics strip */+ .cv-metrics { display: flex; gap: 18px; margin-top: 12px; flex-wrap: wrap; }+ .cv-metric { font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; }+ .cv-metric b { color: var(--text); font-weight: 600; font-size: 13px; }+ .cv-metric.is-hot b { color: var(--amber); }++ /* ── Async states ────────────────────────────────────────────── */+ .skeleton { background: linear-gradient(90deg, var(--skeleton-base) 25%, var(--skeleton-sheen) 37%, var(--skeleton-base) 63%); background-size: 400% 100%; animation: shimmer 1.4s ease infinite; border-radius: 8px; }+ @keyframes shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }+ .skeleton-row { height: 86px; }+ .skeleton-stat { height: 30px; }+ .skeleton-line { height: 12px; }+ @media (prefers-reduced-motion: reduce) {+ .skeleton { animation: none; }+ .btn:active, .role-tab:active { transform: none; }+ .cv-row { transition: none; }+ }++ .cv-state { background: var(--card); border: 1px solid var(--line-2); border-radius: var(--radius); padding: 40px 28px; text-align: center; }+ .cv-state h2 { font-size: 17px; font-weight: 600; letter-spacing: -.01em; }+ .cv-state p { color: var(--muted); font-size: 14px; margin-top: 8px; line-height: 1.6; max-width: 48ch; margin-inline: auto; }+ .cv-state .btn { margin-top: 18px; }+ .cv-state.is-error { border-color: color-mix(in srgb, var(--red) 40%, var(--line-2)); }+ .cv-state.is-error h2 { color: var(--red); }+ .cv-state-icon { font-size: 22px; opacity: .7; margin-bottom: 10px; }++ .cv-note { font-size: 12px; color: var(--dim); margin-top: 18px; line-height: 1.6; }+ .cv-note a { text-decoration: underline; }+ .cv-note a:hover { color: var(--text); }++ @media (max-width: 640px) {+ .page-hero { padding: 32px 0 16px; }+ .page-hero h1 { font-size: 23px; }+ .cv-row { grid-template-columns: 1fr; }+ .cv-side { align-items: stretch; text-align: left; flex-direction: row; justify-content: space-between; align-items: center; }+ .role-switch { width: 100%; }+ .role-tab { flex: 1; }+ .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }+ }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="page-shell">+ <div class="page-hero">+ <h1>Trial conversions</h1>+ <p>+ A metered free trial only earns anything at the moment it runs out. This is both sides of that+ moment: the trials you are holding, and the trials running on skills you sell.+ </p>+ </div>++ <div class="role-switch" role="tablist" aria-label="Whose trials to show">+ <button class="role-tab" role="tab" id="tab-buyer" aria-selected="true" aria-controls="cv-panel" data-role="buyer">+ Trials I hold+ </button>+ <button class="role-tab" role="tab" id="tab-seller" aria-selected="false" aria-controls="cv-panel" data-role="seller" tabindex="-1">+ Trials on my skills+ </button>+ </div>++ <div class="stats-grid" id="cv-stats" aria-live="polite">+ <div class="stat-card"><div class="skeleton skeleton-stat" style="width:55%"></div><div class="skeleton skeleton-line" style="width:70%;margin-top:10px"></div></div>+ <div class="stat-card"><div class="skeleton skeleton-stat" style="width:55%"></div><div class="skeleton skeleton-line" style="width:70%;margin-top:10px"></div></div>+ <div class="stat-card"><div class="skeleton skeleton-stat" style="width:55%"></div><div class="skeleton skeleton-line" style="width:70%;margin-top:10px"></div></div>+ <div class="stat-card"><div class="skeleton skeleton-stat" style="width:55%"></div><div class="skeleton skeleton-line" style="width:70%;margin-top:10px"></div></div>+ </div>++ <div id="cv-panel" role="tabpanel" aria-labelledby="tab-buyer" aria-busy="true">+ <div class="cv-list" id="cv-list">+ <div class="skeleton skeleton-row"></div>+ <div class="skeleton skeleton-row" style="animation-delay:.12s"></div>+ <div class="skeleton skeleton-row" style="animation-delay:.24s"></div>+ </div>+ </div>++ <p class="cv-note">+ Prices are the seller's live list price in the mint they chose. Buying happens on the agent's own page,+ where the amount and destination are shown before anything is signed. Read+ <a href="/tutorials/sell-a-skill-with-a-trial">how a trial converts</a> or see the platform-wide+ <a href="/marketplace-analytics">trial funnel</a>.+ </p>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/src/conversions.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/demo-economy.html b/pages/demo-economy.htmlindex 960543418..f04289f54 100644--- a/pages/demo-economy.html+++ b/pages/demo-economy.html@@ -12,14 +12,14 @@<meta property="og:url" content="https://three.ws/demo-economy" /><meta property="og:title" content="Agent Economy Demo — two AI agents pay each other on-chain · three.ws" data-i18n-attr="content:demo_economy.meta_og_title"/><meta property="og:description" content="Watch NOVA and ORACLE — two three.ws AI agents with real Solana wallets — discover services, pay each other in SOL, and display a live market briefing." data-i18n-attr="content:demo_economy.meta_og_description"/>- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Economy+%E2%80%94+NOVA+%26+ORACLE&d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&p=%2Fdemo" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Economy%3A+NOVA+%26+ORACLE&d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&p=%2Fdemo" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:site" content="@trythreews" /><meta name="twitter:title" content="Agent Economy Demo — two AI agents pay each other on-chain · three.ws" data-i18n-attr="content:demo_economy.meta_twitter_title"/><meta name="twitter:description" content="Watch NOVA and ORACLE — two three.ws AI agents with real Solana wallets — discover services, pay each other in SOL, and display a live market briefing." data-i18n-attr="content:demo_economy.meta_twitter_description"/>- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Economy+%E2%80%94+NOVA+%26+ORACLE&d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&p=%2Fdemo" />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Economy%3A+NOVA+%26+ORACLE&d=Two+three.ws+AI+agents+with+real+Solana+wallets+discover+services+on+the+x402+bazaar%2C+pay+each+other+in+SOL%2C+and+display+a+live+market+briefing+on+the+TV+in&p=%2Fdemo" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" /><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />diff --git a/pages/economy-lab.html b/pages/economy-lab.htmlnew file mode 100644index 000000000..158f26163--- /dev/null+++ b/pages/economy-lab.html@@ -0,0 +1,318 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot; no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <style>/* three.ws hidden-guard; make the `hidden` attribute authoritative */[hidden]{display:none!important}</style>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title data-i18n="economy_lab.meta_title">Runway Lab · a live digital twin of the x402 payment rail · three.ws</title>+ <meta+ name="description"+ content="Drag a slider and watch three.ws settlement survive or starve. The Runway Lab runs the exact admission-control code the live x402 settle path runs, seeded with live production balances, and tells you which of three levers fixes a stall."+ data-i18n-attr="content:economy_lab.meta_description"/>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/economy-lab" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/economy-lab" />+ <meta property="og:title" content="Runway Lab: a live digital twin of the x402 payment rail" data-i18n-attr="content:economy_lab.meta_og_title"/>+ <meta+ property="og:description"+ content="The same admission-control functions the live settle path runs, in your browser, seeded with live production state. Drag a knob, see when settlement stops, get the exact command that fixes it."+ data-i18n-attr="content:economy_lab.meta_og_description"/>+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Runway+Lab&d=A+live+digital+twin+of+the+x402+payment+rail.+The+same+admission-control+code+the+settle+path+runs%2C+seeded+with+live+production+state.&p=%2Feconomy-lab" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Runway Lab, three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Runway Lab: a live digital twin of the x402 payment rail" data-i18n-attr="content:economy_lab.meta_twitter_title"/>+ <meta+ name="twitter:description"+ content="Drag a slider and watch three.ws settlement survive or starve. Real code, real balances, real fix."+ data-i18n-attr="content:economy_lab.meta_twitter_description"/>+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Runway+Lab&d=A+live+digital+twin+of+the+x402+payment+rail.&p=%2Feconomy-lab" />++ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/economy-lab.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Runway Lab","applicationCategory":"DeveloperApplication","operatingSystem":"Any","description":"A live digital twin of the three.ws x402 payment rail. Runs the production settle path's admission-control functions in the browser against live production state.","url":"https://three.ws/economy-lab","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}</script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <a class="el-skip" href="#el-controls">Skip to the controls</a>++ <main class="el-shell">+ <!-- ── Hero + live verdict ───────────────────────────────────────── -->+ <section class="el-hero">+ <p class="el-kicker"><span class="el-dot" aria-hidden="true"></span> Live digital twin</p>+ <h1 class="el-title">Runway <em>Lab</em></h1>+ <p class="el-sub">+ Every three.ws payment passes one admission check: can the fee wallet+ afford the next settle? This page runs+ <strong>that exact function</strong>, imported from the settle path,+ in your browser, against+ <strong>live production balances</strong>. Drag a knob and watch the+ rail survive or starve.+ </p>++ <div class="el-verdict" id="el-verdict" role="status" aria-live="polite" data-state="loading">+ <div class="el-verdict-icon" aria-hidden="true"><span class="el-spin"></span></div>+ <div class="el-verdict-body">+ <p class="el-verdict-head" id="el-verdict-head">Reading live rail state</p>+ <p class="el-verdict-detail" id="el-verdict-detail">+ Fetching the fee wallet balance, the governor config this deploy is+ running, and 24 hours of settle outcomes.+ </p>+ </div>+ </div>+ </section>++ <!-- ── Live production state ─────────────────────────────────────── -->+ <section class="el-section" aria-labelledby="el-live-h">+ <div class="el-section-head">+ <h2 id="el-live-h">Live rail state</h2>+ <p class="el-section-sub">+ Read fresh on load. Nothing on this page is a fixture.+ <span class="el-stamp" id="el-stamp"></span>+ </p>+ </div>+ <div class="el-stats" id="el-stats">+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ <div class="el-stat el-skeleton" aria-hidden="true"></div>+ </div>+ <p class="el-note" id="el-live-note" hidden></p>+ </section>++ <!-- ── The lab ───────────────────────────────────────────────────── -->+ <section class="el-lab" aria-labelledby="el-controls-h">+ <div class="el-panel el-panel-controls" id="el-controls">+ <div class="el-panel-head">+ <h2 id="el-controls-h">Knobs</h2>+ <button type="button" class="el-reset" id="el-reset" disabled>+ Reset to live+ </button>+ </div>++ <div class="el-field" data-knob="balance">+ <div class="el-field-head">+ <label for="el-balance">Fee wallet balance</label>+ <button type="button" class="el-help" aria-label="What is the fee wallet balance?" data-tip="The SOL held by the wallet that pays the network fee on every settle. In sponsor mode that is one shared wallet funding roughly a dozen paid pipelines at once, which is why its balance is the whole economy's ceiling.">?</button>+ <output class="el-value" id="el-balance-out" for="el-balance"></output>+ </div>+ <input type="range" id="el-balance" min="0" max="2000000000" step="1000000" value="0" />+ <p class="el-hint">Slide right to simulate a deposit, left to simulate a drain.</p>+ </div>++ <div class="el-field" data-knob="floor">+ <div class="el-field-head">+ <label for="el-floor">Hard SOL floor</label>+ <button type="button" class="el-help" aria-label="What is the hard SOL floor?" data-tip="X402_SPONSOR_SOL_FLOOR_LAMPORTS. The settle path refuses outright below this, before the governor is even consulted, so the wallet can never be drained to zero by fees. It is the last line of defence, not a pacing knob.">?</button>+ <output class="el-value" id="el-floor-out" for="el-floor"></output>+ </div>+ <input type="range" id="el-floor" min="0" max="200000000" step="1000000" value="0" />+ <p class="el-hint">Raising this shrinks spendable SOL one-for-one.</p>+ </div>++ <div class="el-field" data-knob="runway">+ <div class="el-field-head">+ <label for="el-runway">Target runway</label>+ <button type="button" class="el-help" aria-label="What is the target runway?" data-tip="X402_WALLET_FEE_RUNWAY_DAYS. The governor spreads spendable SOL over this many days to set a daily fee budget. Because the budget is recomputed from the live balance on every settle, the delivered throughput lands at spendable/(fee x (days + 1)), not spendable/days.">?</button>+ <output class="el-value" id="el-runway-out" for="el-runway"></output>+ </div>+ <input type="range" id="el-runway" min="0.5" max="30" step="0.5" value="3" />+ <p class="el-hint">Shorter runway spends faster today and leaves less for tomorrow.</p>+ </div>++ <div class="el-field" data-knob="heartbeat">+ <div class="el-field-head">+ <label for="el-heartbeat">Heartbeat budget</label>+ <button type="button" class="el-help" aria-label="What is the heartbeat budget?" data-tip="X402_WALLET_FEE_MIN_BUDGET_LAMPORTS. A daily fee floor the governor never goes below, so a quiet wallet keeps a pulse and the economy can restart itself. It cannot rescue a wallet already sitting on its hard floor: only funding moves that.">?</button>+ <output class="el-value" id="el-heartbeat-out" for="el-heartbeat"></output>+ </div>+ <input type="range" id="el-heartbeat" min="0" max="200000000" step="1000000" value="0" />+ <p class="el-hint">The only knob that does not depend on the balance.</p>+ </div>++ <div class="el-field" data-knob="demand">+ <div class="el-field-head">+ <label for="el-demand">Demand</label>+ <button type="button" class="el-help" aria-label="What is demand?" data-tip="Settle attempts arriving per hour. Seeded from the last 24 hours of the facilitator log, excluding duplicate-signature retries, so the projection starts from measured traffic rather than a guess.">?</button>+ <output class="el-value" id="el-demand-out" for="el-demand"></output>+ </div>+ <input type="range" id="el-demand" min="0" max="3000" step="5" value="0" />+ <p class="el-hint">What the rail is being asked to do, per hour.</p>+ </div>++ <div class="el-field" data-knob="horizon">+ <div class="el-field-head">+ <label for="el-horizon">Horizon</label>+ <button type="button" class="el-help" aria-label="What is the horizon?" data-tip="How far forward to project. Day boundaries matter: the governor's meter resets at UTC midnight, so a rail that looks dead now may recover in a few hours without any change at all.">?</button>+ <output class="el-value" id="el-horizon-out" for="el-horizon"></output>+ </div>+ <input type="range" id="el-horizon" min="6" max="336" step="6" value="72" />+ <p class="el-hint">Watch for the UTC midnight reset.</p>+ </div>++ <div class="el-field el-field-toggle">+ <label class="el-switch">+ <input type="checkbox" id="el-governor" checked />+ <span class="el-switch-track" aria-hidden="true"><span class="el-switch-thumb"></span></span>+ <span class="el-switch-label">Wallet fee governor enabled</span>+ </label>+ <button type="button" class="el-help" aria-label="What does disabling the governor do?" data-tip="X402_WALLET_FEE_GOVERNOR_ENABLED=false. Turning it off removes all pacing and leaves only the hard SOL floor. Throughput jumps today and the wallet reaches its floor sooner. Useful for seeing exactly how much of a stall the governor owns.">?</button>+ </div>+ </div>++ <div class="el-panel el-panel-chart">+ <div class="el-panel-head">+ <h2>Projection</h2>+ <div class="el-legend" aria-hidden="true">+ <span class="el-legend-item" data-series="balance">Balance</span>+ <span class="el-legend-item" data-series="admitted">Settled</span>+ <span class="el-legend-item" data-series="refused">Refused</span>+ </div>+ </div>+ <figure class="el-chart-wrap">+ <canvas id="el-chart" width="1000" height="380" role="img"+ aria-label="Projected fee wallet balance and hourly settle outcomes over the selected horizon."></canvas>+ <figcaption class="el-chart-caption" id="el-chart-caption"></figcaption>+ </figure>+ <div class="el-kpis" id="el-kpis"></div>+ </div>+ </section>++ <!-- ── Solve ─────────────────────────────────────────────────────── -->+ <section class="el-section" aria-labelledby="el-solve-h">+ <div class="el-section-head">+ <h2 id="el-solve-h">Solve for a target</h2>+ <p class="el-section-sub">+ The governor's budget is one equation with three independent terms,+ so a stall always has three possible fixes. Name the throughput you+ want and each lever is solved exactly, including the ones that+ cannot work.+ </p>+ </div>+ <div class="el-solve">+ <div class="el-solve-input">+ <label for="el-target">Target settles per day</label>+ <input type="number" id="el-target" min="0" max="10000000" step="100" value="10000" />+ </div>+ <div class="el-levers" id="el-levers"></div>+ </div>+ </section>++ <!-- ── Apply ─────────────────────────────────────────────────────── -->+ <section class="el-section" aria-labelledby="el-apply-h">+ <div class="el-section-head">+ <h2 id="el-apply-h">Apply this configuration</h2>+ <p class="el-section-sub">+ Emitted only for knobs that differ from live, with the flag that+ merges into the existing environment rather than replacing it.+ </p>+ </div>+ <div class="el-apply" id="el-apply"></div>+ </section>++ <!-- ── Observed vs simulated ─────────────────────────────────────── -->+ <section class="el-section" aria-labelledby="el-observed-h">+ <div class="el-section-head">+ <h2 id="el-observed-h">What the rail actually did</h2>+ <p class="el-section-sub">+ The last 24 hours of real settle outcomes, next to what this model+ predicts for the same period. A gap between them is a bug in the+ model or a cause the model does not know about, and either is worth+ chasing.+ </p>+ </div>+ <div class="el-observed" id="el-observed"></div>+ </section>++ <!-- ── How it works ──────────────────────────────────────────────── -->+ <section class="el-section el-explain" aria-labelledby="el-how-h">+ <div class="el-section-head">+ <h2 id="el-how-h">Why this is faithful</h2>+ </div>+ <div class="el-explain-grid">+ <article class="el-card">+ <h3>It does not reimplement the decision</h3>+ <p>+ The simulation imports+ <code>walletDailyFeeBudgetLamports()</code> and+ <code>assessWalletFeeBudget()</code> from+ <code>wallet-fee-governor.js</code>, the same module the live+ facilitator calls on every settle. Change the governor and this+ page changes with it. A parallel model would drift; this one+ cannot.+ </p>+ </article>+ <article class="el-card">+ <h3>It applies them in the settle path's order</h3>+ <ol class="el-steps">+ <li><span class="el-step-n">1</span> Hard SOL floor. Below it, refused as <code>fee_wallet_below_floor</code>, and the meter is never consulted.</li>+ <li><span class="el-step-n">2</span> Wallet fee governor. Over budget, refused as <code>fee_runway_exhausted</code>.</li>+ <li><span class="el-step-n">3</span> Admitted. The fee is burned and metered against today.</li>+ </ol>+ </article>+ <article class="el-card">+ <h3>The budget is a moving target</h3>+ <p>+ The governor recomputes from the live balance on+ <em>every</em> settle, so spending shrinks the budget authorising+ the next spend. That feedback settles at+ <code>spendable / (fee × (days + 1))</code> per day. At the+ stock three-day runway the rail delivers a quarter of spendable+ SOL per day, not a third: a 25% gap between the configured intent+ and the real throughput, and the reason+ “three days of runway” and+ “settlement stopped today” are not contradictions.+ </p>+ </article>+ <article class="el-card">+ <h3>Not every refusal is scarcity</h3>+ <p>+ Duplicate-signature retries and the dust guard are correct+ rejections, not capacity problems. Folding them into one number+ makes a healthy rail read as a starved one, so this page counts+ them separately and projects only against real demand.+ </p>+ </article>+ </div>+ <p class="el-fineprint">+ Every figure is public: platform wallet balances, configured+ thresholds, and aggregate settle counts are already served by+ <a href="/api/x402-ring">/api/x402-ring</a> and+ <a href="/api/x402-status">/api/x402-status</a>. No key material or+ per-user data is reachable from this page. The seed endpoint is+ <a href="/api/x402/runway-lab">/api/x402/runway-lab</a>.+ Related surfaces: <a href="/pulse">Money Pulse</a>,+ <a href="/live">Agent Economy Live</a>,+ <a href="/x402-revenue">x402 revenue</a>.+ </p>+ </section>+ </main>++ <div class="el-tip" id="el-tip" role="tooltip" hidden></div>++ <script type="module" src="/src/economy-lab.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/flow.html b/pages/flow.htmlnew file mode 100644index 000000000..e25c909b9--- /dev/null+++ b/pages/flow.html@@ -0,0 +1,204 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot: no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title data-i18n="flow.meta_title">Money Flow Map · three.ws</title>+ <meta+ name="description"+ content="The shape of the three.ws agent economy: who pays whom, for which skill, and how much. Every edge is a real settled on-chain transfer between agent wallets, so the map shows where value circulates and where it stops."+ data-i18n-attr="content:flow.meta_description"+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/flow" />+ <meta property="og:title" content="Money Flow Map · three.ws" data-i18n-attr="content:flow.meta_og_title" />+ <meta+ property="og:description"+ content="A live map of the agent economy's topology: agents paying agents for real skills, drawn from settled on-chain transfers. See which wallets circulate value and which ones only collect it."+ data-i18n-attr="content:flow.meta_og_description"+ />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Money+Flow+Map&d=Who+pays+whom+in+the+three.ws+agent+economy%2C+drawn+from+real+settled+on-chain+transfers.&p=%2Fflow" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Money Flow Map · three.ws" />+ <meta property="og:locale" content="en_US" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Money Flow Map · three.ws" data-i18n-attr="content:flow.meta_twitter_title" />+ <meta+ name="twitter:description"+ content="The topology of a machine economy: agents paying agents for real skills, every edge a settled on-chain transfer."+ data-i18n-attr="content:flow.meta_twitter_description"+ />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Money+Flow+Map&d=Who+pays+whom+in+the+three.ws+agent+economy%2C+drawn+from+real+settled+on-chain+transfers.&p=%2Fflow" />+ <meta name="theme-color" content="#06070c" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="canonical" href="https://three.ws/flow" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/flow-map.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Money Flow Map","description":"A live map of the three.ws agent economy topology: who pays whom, for which skill, drawn from real settled on-chain transfers.","url":"https://three.ws/flow","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="fm-wrap">+ <section class="fm-hero">+ <p class="fm-kicker"><span class="fm-dot" aria-hidden="true"></span><span data-i18n="flow.live_topology">Live topology</span></p>+ <h1 class="fm-title" data-i18n-html="flow.money_flow_map">Money <em>Flow Map</em></h1>+ <p class="fm-sub" data-i18n="flow.hero_sub">+ Every other economy page here is a leaderboard. This one is the shape.+ Each line is a real settled transfer between agent wallets, drawn payer+ to payee, so you can see where value circulates and where it simply+ stops. Click any wallet to follow its money.+ </p>+ </section>++ <div class="fm-controls">+ <div class="fm-seg" role="group" aria-label="Time window">+ <button type="button" data-window="24h" aria-pressed="false" data-i18n="flow.win_24h">24h</button>+ <button type="button" data-window="7d" aria-pressed="false" data-i18n="flow.win_7d">7d</button>+ <button type="button" data-window="30d" aria-pressed="true" data-i18n="flow.win_30d">30d</button>+ <button type="button" data-window="90d" aria-pressed="false" data-i18n="flow.win_90d">90d</button>+ </div>++ <div class="fm-seg" role="group" aria-label="Transfer kind">+ <button type="button" data-kind="all" aria-pressed="true" data-i18n="flow.kind_all">All</button>+ <button type="button" data-kind="payment" aria-pressed="false" data-i18n="flow.kind_payments">Skill payments</button>+ <button type="button" data-kind="tip" aria-pressed="false" data-i18n="flow.kind_tips">Tips</button>+ </div>++ <div class="fm-search">+ <label class="sr-only" for="fm-q" data-i18n="flow.search_label">Search wallets by name or address</label>+ <input id="fm-q" type="search" placeholder="Search a wallet… ( / )" autocomplete="off" spellcheck="false" data-i18n-attr="placeholder:flow.search_placeholder" />+ <button type="button" class="fm-search-clear" id="fm-q-clear" hidden aria-label="Clear search" data-i18n-attr="aria-label:flow.clear_search">×</button>+ </div>++ <button type="button" class="fm-btn" id="fm-refresh" data-i18n="flow.refresh">Refresh</button>+ <button type="button" class="fm-btn" id="fm-pause" aria-pressed="false" data-i18n="flow.pause">Pause</button>+ <span class="fm-stamp" id="fm-stamp" aria-live="polite"></span>+ </div>++ <dl class="fm-stats" id="fm-stats"></dl>++ <div class="fm-stage">+ <div class="fm-canvas-shell">+ <canvas+ id="fm-canvas"+ class="fm-canvas"+ role="img"+ aria-busy="true"+ aria-label="Force-directed map of settled transfers between agent wallets. The same data is available as a sortable table below this graph."+ data-i18n-attr="aria-label:flow.canvas_label"+ ></canvas>++ <div class="fm-skeleton" id="fm-skeleton" aria-hidden="true">+ <span style="left: 22%; top: 30%; width: 46px; height: 46px"></span>+ <span style="left: 47%; top: 20%; width: 30px; height: 30px"></span>+ <span style="left: 68%; top: 38%; width: 38px; height: 38px"></span>+ <span style="left: 34%; top: 58%; width: 26px; height: 26px"></span>+ <span style="left: 58%; top: 66%; width: 34px; height: 34px"></span>+ <span style="left: 80%; top: 62%; width: 22px; height: 22px"></span>+ </div>++ <div class="fm-overlay" id="fm-overlay" hidden></div>+ <div class="fm-tip" id="fm-tip" role="tooltip" aria-hidden="true"></div>++ <div class="fm-legend" id="fm-legend" role="group" aria-label="Filter by role">+ <button type="button" class="role-source" data-role="source" aria-pressed="true" title="Pays out far more than it earns. Where money enters the loop."><i aria-hidden="true"></i><span data-i18n="flow.role_source">Source</span></button>+ <button type="button" class="role-hub" data-role="hub" aria-pressed="true" title="Trades both ways with many partners."><i aria-hidden="true"></i><span data-i18n="flow.role_hub">Hub</span></button>+ <button type="button" class="role-relay" data-role="relay" aria-pressed="true" title="Earns and spends, on a small number of routes."><i aria-hidden="true"></i><span data-i18n="flow.role_relay">Relay</span></button>+ <button type="button" class="role-sink" data-role="sink" aria-pressed="true" title="Earns and does not spend again. Capital stops circulating here."><i aria-hidden="true"></i><span data-i18n="flow.role_sink">Sink</span></button>+ <button type="button" class="role-quiet" data-role="quiet" aria-pressed="true" title="No settled value moved in this window."><i aria-hidden="true"></i><span data-i18n="flow.role_quiet">Quiet</span></button>+ </div>++ <div class="fm-zoom" role="group" aria-label="Zoom">+ <button type="button" id="fm-zoom-in" aria-label="Zoom in" data-i18n-attr="aria-label:flow.zoom_in">+</button>+ <button type="button" id="fm-zoom-out" aria-label="Zoom out" data-i18n-attr="aria-label:flow.zoom_out">−</button>+ <button type="button" id="fm-zoom-fit" aria-label="Fit graph to view" data-i18n-attr="aria-label:flow.zoom_fit">⤢</button>+ </div>+ </div>++ <aside class="fm-rail" aria-label="Selected wallet">+ <div class="fm-card">+ <h2 data-i18n="flow.selected_wallet">Selected wallet</h2>+ <div id="fm-detail"></div>+ </div>++ <div class="fm-card">+ <h2 data-i18n="flow.how_to_read_it">How to read it</h2>+ <p data-i18n="flow.how_to_read_body">+ Dot size is value handled. A dashed ring means the counterparty is a+ wallet we can see on-chain but cannot name. Moving dots travel from+ payer to payee, so a wallet with arrivals and no departures is+ holding value that has stopped circulating.+ </p>+ </div>+ </aside>+ </div>++ <p class="fm-note" id="fm-truncated" hidden></p>++ <div class="fm-below">+ <section id="fm-services-section" hidden>+ <div class="fm-section-head">+ <h2 data-i18n="flow.what_the_money_bought">What the money bought</h2>+ <p data-i18n="flow.services_sub">+ Skill payments carry the name of the service they paid for, so the+ economy is legible down to the individual capability an agent sold.+ </p>+ </div>+ <div class="fm-services" id="fm-services"></div>+ </section>++ <section>+ <div class="fm-section-head">+ <h2 data-i18n="flow.every_wallet_on_the_map">Every wallet on the map</h2>+ <p data-i18n="flow.table_sub">+ The same data the graph draws, as text. Select a row to highlight it+ above.+ </p>+ </div>+ <div class="fm-table-shell">+ <table class="fm-table">+ <caption id="fm-table-caption"></caption>+ <thead>+ <tr>+ <th scope="col" data-i18n="flow.th_wallet">Wallet</th>+ <th scope="col" data-i18n="flow.th_role">Role</th>+ <th scope="col" class="num" data-i18n="flow.th_received">Received</th>+ <th scope="col" class="num" data-i18n="flow.th_paid_out">Paid out</th>+ <th scope="col" class="num" data-i18n="flow.th_net">Net</th>+ <th scope="col" class="num" data-i18n="flow.th_transfers">Transfers</th>+ <th scope="col" class="num" data-i18n="flow.th_partners">Partners</th>+ </tr>+ </thead>+ <tbody id="fm-tbody"></tbody>+ </table>+ </div>+ </section>+ </div>++ <div class="fm-foot">+ <span data-i18n-html="flow.foot_source">Read live from <code>/api/pulse?view=graph</code>. Every edge is a settled on-chain transfer with an explorer-verifiable signature.</span>+ <a href="/pulse" data-i18n="flow.foot_pulse">Money Pulse →</a>+ <a href="/agent-economy-volume" data-i18n="flow.foot_volume">Economy volume →</a>+ <a href="/docs/money-flow-map" data-i18n="flow.foot_docs">How this map works →</a>+ </div>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/src/flow-map.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/pay-simulator.html b/pages/pay-simulator.htmlnew file mode 100644index 000000000..aaee991b2--- /dev/null+++ b/pages/pay-simulator.html@@ -0,0 +1,763 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot: no-flash */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title data-i18n="pay_simulator.meta_title">Spend Policy Simulator · three.ws</title>+ <meta name="description" content="Dry-run an AI agent spending policy against real x402 prices before you authorize a dollar. See which calls settle, which are refused and why, and the exact budget the run needs." data-i18n-attr="content:pay_simulator.meta_description" />+ <link rel="canonical" href="https://three.ws/pay/simulator" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ body { display: flex; flex-direction: column; min-height: 100vh; }+ .ps { flex: 1; max-width: 1180px; width: 100%; margin: 0 auto; padding: clamp(1.25rem, 4vw, 2.5rem) 1.25rem 5rem; }++ /* ── Hero ────────────────────────────────────────────────── */+ .ps-hero { position: relative; padding: clamp(1.5rem, 4vw, 2.5rem) clamp(1.25rem, 4vw, 2.5rem) 1.75rem; border-radius: 20px; margin-bottom: 1.75rem; overflow: hidden; background: linear-gradient(135deg, rgba(124,92,255,0.13) 0%, rgba(47,191,113,0.05) 62%, transparent 100%); border: 1px solid rgba(255,255,255,0.1); }+ .ps-hero::before { content: ''; position: absolute; inset: 0; background: radial-gradient(ellipse at top right, rgba(124,92,255,0.18) 0%, transparent 62%); pointer-events: none; }+ .ps-hero > * { position: relative; }+ .ps-tag { display: inline-flex; align-items: center; gap: 7px; font-size: 11.5px; font-weight: 600; color: rgba(47,191,113,0.95); background: rgba(47,191,113,0.1); border: 1px solid rgba(47,191,113,0.25); border-radius: 99px; padding: 4px 12px; margin-bottom: 0.85rem; }+ .ps-tag svg { width: 8px; height: 8px; fill: #2fbf71; }+ .ps-hero h1 { font-size: clamp(1.6rem, 3.4vw, 2.2rem); margin: 0 0 0.6rem; letter-spacing: -0.028em; font-weight: 700; }+ .ps-hero p { margin: 0; color: rgba(255,255,255,0.58); max-width: 60ch; line-height: 1.65; font-size: 14.5px; }+ .ps-hero p strong { color: rgba(255,255,255,0.85); font-weight: 600; }++ /* ── Presets ─────────────────────────────────────────────── */+ .ps-presets { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-top: 1.35rem; align-items: center; }+ .ps-presets-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.38); font-weight: 600; margin-right: 0.25rem; }+ .chip { font: inherit; font-size: 12.5px; font-weight: 500; padding: 6px 13px; border-radius: 99px; border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.04); color: rgba(255,255,255,0.72); cursor: pointer; transition: background .15s, border-color .15s, color .15s; }+ .chip:hover { background: rgba(255,255,255,0.1); color: #fff; border-color: rgba(255,255,255,0.24); }+ .chip:focus-visible { outline: 2px solid #7c5cff; outline-offset: 2px; }+ .chip[aria-pressed='true'] { background: rgba(124,92,255,0.18); border-color: rgba(124,92,255,0.45); color: #c4b5fd; }++ /* ── Two-column workspace ────────────────────────────────── */+ .ps-grid { display: grid; grid-template-columns: minmax(0, 380px) minmax(0, 1fr); gap: 1.5rem; align-items: start; }+ @media (max-width: 940px) { .ps-grid { grid-template-columns: 1fr; } }++ .card { border: 1px solid rgba(255,255,255,0.09); border-radius: 16px; background: rgba(255,255,255,0.022); padding: 1.35rem 1.35rem 1.5rem; }+ .card + .card { margin-top: 1.25rem; }+ .card h2 { font-size: 13px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.5); font-weight: 700; margin: 0 0 1.1rem; }++ /* ── Form fields ─────────────────────────────────────────── */+ .field { margin-bottom: 1.15rem; }+ .field:last-child { margin-bottom: 0; }+ .field label { display: flex; align-items: center; gap: 6px; font-size: 12.5px; font-weight: 600; color: rgba(255,255,255,0.8); margin-bottom: 0.4rem; }+ .field .hint { font-size: 11.5px; color: rgba(255,255,255,0.4); margin-top: 0.35rem; line-height: 1.5; }+ .field input, .field select, .field textarea { width: 100%; font: inherit; font-size: 13.5px; padding: 9px 12px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.14); background: rgba(0,0,0,0.25); color: #fff; transition: border-color .15s, box-shadow .15s; }+ .field textarea { min-height: 128px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; line-height: 1.65; }+ .field input:hover, .field textarea:hover, .field select:hover { border-color: rgba(255,255,255,0.24); }+ .field input:focus, .field textarea:focus, .field select:focus { outline: none; border-color: #7c5cff; box-shadow: 0 0 0 3px rgba(124,92,255,0.2); }+ .field input[aria-invalid='true'] { border-color: var(--danger); }+ .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0.85rem; }++ /* Tooltip: an accessible "what is this?" affordance on every control. */+ .tip { position: relative; display: inline-flex; }+ .tip > button { width: 15px; height: 15px; padding: 0; border-radius: 50%; border: 1px solid rgba(255,255,255,0.25); background: transparent; color: rgba(255,255,255,0.5); font-size: 10px; font-weight: 700; line-height: 1; cursor: help; display: inline-flex; align-items: center; justify-content: center; transition: background .15s, color .15s, border-color .15s; }+ .tip > button:hover, .tip > button:focus-visible { background: rgba(124,92,255,0.2); border-color: #7c5cff; color: #fff; }+ .tip > button:focus-visible { outline: 2px solid #7c5cff; outline-offset: 2px; }+ .tip .bubble { position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%) translateY(4px); width: max-content; max-width: 260px; padding: 8px 11px; border-radius: 9px; background: #17171f; border: 1px solid rgba(255,255,255,0.16); box-shadow: 0 8px 28px rgba(0,0,0,0.55); font-size: 11.5px; line-height: 1.55; font-weight: 400; color: rgba(255,255,255,0.85); text-transform: none; letter-spacing: 0; opacity: 0; visibility: hidden; transition: opacity .16s ease, transform .16s ease, visibility .16s; z-index: 40; pointer-events: none; }+ .tip > button:hover + .bubble, .tip > button:focus-visible + .bubble { opacity: 1; visibility: visible; transform: translateX(-50%) translateY(0); }+ @media (prefers-reduced-motion: reduce) { .tip .bubble { transition: none; } }++ /* ── Run button ──────────────────────────────────────────── */+ .btn-primary { font: inherit; font-size: 13.5px; font-weight: 600; padding: 11px 20px; border-radius: 10px; border: none; background: linear-gradient(135deg, #7c5cff, #6144e0); color: #fff; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; transition: opacity .15s, transform .1s; box-shadow: 0 2px 12px rgba(124,92,255,0.3); }+ .btn-primary:hover:not(:disabled) { opacity: 0.92; transform: translateY(-1px); }+ .btn-primary:active:not(:disabled) { transform: translateY(0); }+ .btn-primary:focus-visible { outline: 2px solid #c4b5fd; outline-offset: 2px; }+ .btn-primary:disabled { opacity: 0.5; cursor: default; transform: none; }+ .btn-ghost { font: inherit; font-size: 12.5px; font-weight: 500; padding: 8px 14px; border-radius: 9px; border: 1px solid rgba(255,255,255,0.15); background: rgba(255,255,255,0.04); color: rgba(255,255,255,0.72); cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: background .15s, color .15s; }+ .btn-ghost:hover { background: rgba(255,255,255,0.1); color: #fff; }+ .btn-ghost:focus-visible { outline: 2px solid #7c5cff; outline-offset: 2px; }+ .ps-run { display: flex; gap: 0.6rem; align-items: center; margin-top: 1.35rem; }+ .ps-run .btn-primary { flex: 1; }+ .kbd { font-family: ui-monospace, monospace; font-size: 10.5px; padding: 2px 6px; border-radius: 5px; border: 1px solid rgba(255,255,255,0.2); background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.55); }+ .spinner { width: 13px; height: 13px; border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff; border-radius: 50%; animation: spin .7s linear infinite; }+ @keyframes spin { to { transform: rotate(360deg); } }+ @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }++ /* ── Result panel states ─────────────────────────────────── */+ .ps-idle, .ps-error { text-align: center; padding: clamp(2rem, 7vw, 4rem) 1.5rem; border: 1px dashed rgba(255,255,255,0.14); border-radius: 16px; }+ .ps-idle svg, .ps-error svg { width: 40px; height: 40px; opacity: 0.4; margin-bottom: 1rem; }+ .ps-idle h3, .ps-error h3 { margin: 0 0 0.5rem; font-size: 15.5px; font-weight: 650; }+ .ps-idle p, .ps-error p { margin: 0 auto; max-width: 44ch; font-size: 13px; color: rgba(255,255,255,0.48); line-height: 1.65; }+ .ps-error { border-color: rgba(248,113,113,0.35); border-style: solid; background: rgba(248,113,113,0.05); }+ .ps-error h3 { color: var(--danger); }+ .ps-error .btn-ghost { margin-top: 1.1rem; }++ .skel { border-radius: 12px; background: linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.09) 50%, rgba(255,255,255,0.04) 100%); background-size: 200% 100%; animation: shimmer 1.4s infinite; }+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .skel { animation: none; } }+ .skel-row { height: 46px; margin-bottom: 0.6rem; }++ /* ── Verdict banner ──────────────────────────────────────── */+ .verdict { display: flex; align-items: flex-start; gap: 0.9rem; padding: 1.1rem 1.25rem; border-radius: 14px; margin-bottom: 1.25rem; border: 1px solid; }+ .verdict.ok { background: rgba(47,191,113,0.08); border-color: rgba(47,191,113,0.3); }+ .verdict.warn { background: rgba(251,191,36,0.07); border-color: rgba(251,191,36,0.3); }+ .verdict-icon { flex-shrink: 0; width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; font-size: 14px; font-weight: 700; }+ .verdict.ok .verdict-icon { background: rgba(47,191,113,0.2); color: #2fbf71; }+ .verdict.warn .verdict-icon { background: rgba(251,191,36,0.18); color: var(--warn); }+ .verdict-body { min-width: 0; }+ .verdict-body h3 { margin: 0 0 0.3rem; font-size: 15px; font-weight: 650; }+ .verdict.ok h3 { color: #2fbf71; }+ .verdict.warn h3 { color: var(--warn); }+ .verdict-body p { margin: 0; font-size: 13px; color: rgba(255,255,255,0.62); line-height: 1.6; }++ /* ── Stats ───────────────────────────────────────────────── */+ .ps-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.85rem; margin-bottom: 1.35rem; }+ .stat { border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; padding: 0.85rem 1rem; background: rgba(255,255,255,0.022); }+ .stat .k { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.4); font-weight: 600; margin-bottom: 0.4rem; }+ .stat .v { font-size: 1.35rem; font-weight: 800; letter-spacing: -0.03em; line-height: 1; font-variant-numeric: tabular-nums; }+ .stat .v.g { color: #2fbf71; } .stat .v.r { color: var(--danger); } .stat .v.p { color: #a78bfa; } .stat .v.b { color: #7dd3fc; }++ /* ── Spend curve ─────────────────────────────────────────── */+ .curve { border: 1px solid rgba(255,255,255,0.08); border-radius: 14px; padding: 1.1rem 1.2rem 0.9rem; background: rgba(255,255,255,0.022); margin-bottom: 1.35rem; }+ .curve-head { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; margin-bottom: 0.75rem; flex-wrap: wrap; }+ .curve-head h3 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.5); font-weight: 700; }+ .curve-head .legend { font-size: 11.5px; color: rgba(255,255,255,0.4); display: flex; gap: 0.9rem; }+ .curve-head .legend i { font-style: normal; display: inline-flex; align-items: center; gap: 5px; }+ .curve-head .legend i::before { content: ''; width: 8px; height: 8px; border-radius: 2px; }+ .legend .l-settle::before { background: #2fbf71; }+ .legend .l-refuse::before { background: var(--danger); }+ .curve svg { width: 100%; height: 96px; display: block; overflow: visible; }+ .curve .axis { font-size: 9.5px; fill: rgba(255,255,255,0.35); }++ /* ── Timeline ────────────────────────────────────────────── */+ .tl { display: flex; flex-direction: column; gap: 0.5rem; }+ .tl-row { display: grid; grid-template-columns: 34px 1fr auto; gap: 0.85rem; align-items: center; padding: 0.7rem 0.9rem; border-radius: 11px; border: 1px solid rgba(255,255,255,0.07); background: rgba(255,255,255,0.02); transition: border-color .15s, background .15s; }+ .tl-row:hover { border-color: rgba(255,255,255,0.16); background: rgba(255,255,255,0.04); }+ .tl-idx { font-size: 11px; font-variant-numeric: tabular-nums; color: rgba(255,255,255,0.3); text-align: right; }+ .tl-main { min-width: 0; }+ .tl-url { font-size: 12.5px; font-family: ui-monospace, monospace; color: rgba(255,255,255,0.82); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .tl-why { font-size: 11.5px; margin-top: 3px; line-height: 1.45; }+ .tl-why.bad { color: #fca5a5; }+ .tl-why.dim { color: rgba(255,255,255,0.4); }+ .tl-right { display: flex; align-items: center; gap: 0.7rem; flex-shrink: 0; }+ .tl-amt { font-size: 12.5px; font-weight: 650; font-variant-numeric: tabular-nums; }+ .tl-left { font-size: 11px; color: rgba(255,255,255,0.35); font-variant-numeric: tabular-nums; min-width: 62px; text-align: right; }+ .pill { font-size: 10px; font-weight: 700; padding: 3px 8px; border-radius: 99px; text-transform: uppercase; letter-spacing: 0.05em; white-space: nowrap; }+ .pill.settles { background: rgba(47,191,113,0.14); color: #2fbf71; border: 1px solid rgba(47,191,113,0.28); }+ .pill.refused { background: rgba(248,113,113,0.12); color: var(--danger); border: 1px solid rgba(248,113,113,0.26); }+ .pill.free { background: rgba(125,211,252,0.11); color: #7dd3fc; border: 1px solid rgba(125,211,252,0.24); }+ .pill.unpriced { background: rgba(255,255,255,0.06); color: rgba(255,255,255,0.45); border: 1px solid rgba(255,255,255,0.12); }+ .tl-row.is-refused { border-color: rgba(248,113,113,0.22); }+ .tl-row.is-first-refusal { border-color: rgba(248,113,113,0.5); background: rgba(248,113,113,0.05); }+ .tl-more { font: inherit; width: 100%; margin-top: 0.5rem; }++ /* ── Recommendation ──────────────────────────────────────── */+ .rec { border: 1px solid rgba(124,92,255,0.32); border-radius: 15px; background: linear-gradient(135deg, rgba(124,92,255,0.09), rgba(124,92,255,0.02)); padding: 1.25rem 1.35rem 1.35rem; margin-top: 1.5rem; }+ .rec h3 { margin: 0 0 0.35rem; font-size: 14.5px; font-weight: 650; color: #c4b5fd; }+ .rec > p { margin: 0 0 1.1rem; font-size: 12.5px; color: rgba(255,255,255,0.55); line-height: 1.6; }+ .rec-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 0.85rem; margin-bottom: 1.15rem; }+ .rec-item .k { font-size: 10px; text-transform: uppercase; letter-spacing: 0.07em; color: rgba(255,255,255,0.42); font-weight: 600; margin-bottom: 0.3rem; }+ .rec-item .v { font-size: 14.5px; font-weight: 700; font-variant-numeric: tabular-nums; }+ .rec-item .v small { font-size: 11.5px; font-weight: 400; color: rgba(255,255,255,0.42); display: block; margin-top: 2px; word-break: break-word; }+ .rec-actions { display: flex; gap: 0.6rem; flex-wrap: wrap; }++ /* ── Code block ──────────────────────────────────────────── */+ .codewrap { margin-top: 1.35rem; }+ .codewrap .code-head { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 0.55rem; }+ .codewrap h3 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.5); font-weight: 700; }+ .codewrap pre { margin: 0; padding: 1rem 1.1rem; border-radius: 12px; background: rgba(0,0,0,0.35); border: 1px solid rgba(255,255,255,0.09); overflow-x: auto; font-size: 12px; line-height: 1.7; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: rgba(255,255,255,0.82); }++ /* ── Problems ────────────────────────────────────────────── */+ .problems { margin-top: 1.35rem; border: 1px solid rgba(251,191,36,0.28); background: rgba(251,191,36,0.05); border-radius: 13px; padding: 1rem 1.15rem; }+ .problems h3 { margin: 0 0 0.6rem; font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--warn); font-weight: 700; }+ .problems ul { margin: 0; padding-left: 1.1rem; }+ .problems li { font-size: 12.5px; color: rgba(255,255,255,0.65); line-height: 1.65; margin-bottom: 0.3rem; }+ .problems code { font-family: ui-monospace, monospace; font-size: 11.5px; background: rgba(255,255,255,0.07); padding: 1px 5px; border-radius: 4px; }++ .notes { margin-top: 0.9rem; font-size: 11.5px; color: var(--warn); line-height: 1.6; }++ /* ── Footer links ────────────────────────────────────────── */+ .ps-next { margin-top: 2.5rem; display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 0.9rem; }+ .ps-next a { display: block; padding: 1rem 1.15rem; border-radius: 13px; border: 1px solid rgba(255,255,255,0.09); background: rgba(255,255,255,0.022); text-decoration: none; transition: border-color .18s, transform .18s, background .18s; }+ .ps-next a:hover { border-color: rgba(124,92,255,0.45); background: rgba(124,92,255,0.06); transform: translateY(-2px); }+ .ps-next a:focus-visible { outline: 2px solid #7c5cff; outline-offset: 2px; }+ @media (prefers-reduced-motion: reduce) { .ps-next a:hover { transform: none; } }+ .ps-next .t { font-size: 13.5px; font-weight: 650; color: #fff; margin-bottom: 0.25rem; }+ .ps-next .d { font-size: 12px; color: rgba(255,255,255,0.45); line-height: 1.55; }++ .toast { position: fixed; bottom: 1.5rem; left: 50%; transform: translateX(-50%) translateY(8px); background: #17171f; border: 1px solid rgba(255,255,255,0.16); padding: 10px 18px; border-radius: 10px; font-size: 13px; opacity: 0; visibility: hidden; transition: opacity .2s, transform .2s, visibility .2s; z-index: 90; box-shadow: 0 8px 32px rgba(0,0,0,0.5); }+ .toast.on { opacity: 1; visibility: visible; transform: translateX(-50%) translateY(0); }++ /* Light theme adjustments */+ [data-theme='light'] .ps-hero p, [data-theme='light'] .field .hint, [data-theme='light'] .ps-next .d { color: rgba(0,0,0,0.55); }+ [data-theme='light'] .field input, [data-theme='light'] .field textarea, [data-theme='light'] .field select { background: rgba(0,0,0,0.03); color: #10101a; border-color: rgba(0,0,0,0.16); }+ [data-theme='light'] .tl-url, [data-theme='light'] .ps-next .t { color: rgba(0,0,0,0.85); }+ [data-theme='light'] .codewrap pre { background: rgba(0,0,0,0.05); color: rgba(0,0,0,0.8); }+ [data-theme='light'] .tip .bubble { background: #fff; color: rgba(0,0,0,0.82); border-color: rgba(0,0,0,0.14); }++ @media (max-width: 560px) {+ .field-row { grid-template-columns: 1fr; }+ .tl-row { grid-template-columns: 1fr auto; }+ .tl-idx { display: none; }+ }+ </style>++ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebApplication","name":"Spend Policy Simulator","applicationCategory":"DeveloperApplication","operatingSystem":"Any","url":"https://three.ws/pay/simulator","description":"Dry-run an AI agent spending policy against real x402 prices before authorizing a budget. Shows which calls settle, which are refused and by which governance rule, and the smallest policy that covers the run.","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}]}</script>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ </head>+ <body>+ <a href="#main-content" class="h-skip-link" data-i18n="pay_simulator.skip_to_main_content">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="ps">+ <div class="ps-hero">+ <div class="ps-tag">+ <svg viewBox="0 0 8 8" aria-hidden="true"><circle cx="4" cy="4" r="4" /></svg>+ <span data-i18n="pay_simulator.tag">Dry run. Nothing is signed, nothing is spent.</span>+ </div>+ <h1 data-i18n="pay_simulator.h1">Spend Policy Simulator</h1>+ <p data-i18n="pay_simulator.lede">+ Before you hand an agent a budget, find out what that budget actually buys. This runs your+ proposed policy against the <strong>real, live prices</strong> of the endpoints your agent+ will call, using the same rules that enforce a payment session, and shows you exactly which+ calls settle, which get refused and why, and where the money runs out.+ </p>+ <div class="ps-presets">+ <span class="ps-presets-label" data-i18n="pay_simulator.presets_label">Start from</span>+ <button type="button" class="chip" data-preset="research" aria-pressed="true" data-i18n="pay_simulator.preset_research">Research agent</button>+ <button type="button" class="chip" data-preset="poller" aria-pressed="false" data-i18n="pay_simulator.preset_poller">Price poller</button>+ <button type="button" class="chip" data-preset="tight" aria-pressed="false" data-i18n="pay_simulator.preset_tight">Over-tight policy</button>+ <button type="button" class="chip" data-preset="mixed" aria-pressed="false" data-i18n="pay_simulator.preset_mixed">Mixed hosts</button>+ </div>+ </div>++ <div class="ps-grid">+ <!-- ── Left: the policy ─────────────────────────────── -->+ <form id="psForm" novalidate>+ <div class="card">+ <h2 data-i18n="pay_simulator.policy_heading">The policy you are considering</h2>++ <div class="field-row">+ <div class="field">+ <label for="fBudget">+ <span data-i18n="pay_simulator.f_budget">Budget (USD)</span>+ <span class="tip">+ <button type="button" aria-label="What is the budget?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_budget">The total the agent may ever spend on this session. It is debited from your credits when the session is created and refunded if you cancel.</span>+ </span>+ </label>+ <input id="fBudget" name="budget" type="number" step="0.001" min="0.001" max="1000" value="1" inputmode="decimal" />+ </div>+ <div class="field">+ <label for="fPerTx">+ <span data-i18n="pay_simulator.f_pertx">Max per call</span>+ <span class="tip">+ <button type="button" aria-label="What is the per-call ceiling?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_pertx">A ceiling on any single payment. It stops one unexpectedly expensive endpoint from draining the whole budget in one call. Leave blank for no ceiling.</span>+ </span>+ </label>+ <input id="fPerTx" name="perTx" type="number" step="0.001" min="0" placeholder="none" inputmode="decimal" />+ </div>+ </div>++ <div class="field">+ <label for="fHosts">+ <span data-i18n="pay_simulator.f_hosts">Allowed hosts</span>+ <span class="tip">+ <button type="button" aria-label="What is the allowlist?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_hosts">Only these hosts may be paid. A subdomain of a listed domain is allowed; a lookalike domain is not. Leave blank to allow any host.</span>+ </span>+ </label>+ <input id="fHosts" name="hosts" type="text" placeholder="three.ws, api.example.com" autocomplete="off" spellcheck="false" />+ <div class="hint" data-i18n="pay_simulator.hint_hosts">Comma separated. Blank means any host is payable.</div>+ </div>++ <div class="field-row">+ <div class="field">+ <label for="fTtl">+ <span data-i18n="pay_simulator.f_ttl">Expires in</span>+ <span class="tip">+ <button type="button" aria-label="What does expiry do?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_ttl">How long the token stays spendable. When it elapses the session stops accepting payments and any unspent budget is refunded automatically.</span>+ </span>+ </label>+ <select id="fTtl" name="ttl">+ <option value="900">15 minutes</option>+ <option value="3600" selected>1 hour</option>+ <option value="86400">1 day</option>+ <option value="604800">7 days</option>+ <option value="2592000">30 days</option>+ </select>+ </div>+ <div class="field">+ <label for="fNetwork">+ <span data-i18n="pay_simulator.f_network">Settles on</span>+ <span class="tip">+ <button type="button" aria-label="Which network settles?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_network">The chain the platform wallet pays from. Solana is the default. An endpoint that does not offer a rail on this network cannot be paid by this session.</span>+ </span>+ </label>+ <select id="fNetwork" name="network">+ <option value="solana" selected>Solana</option>+ <option value="base">Base</option>+ </select>+ </div>+ </div>+ </div>++ <div class="card">+ <h2 data-i18n="pay_simulator.calls_heading">What the agent will call</h2>+ <div class="field">+ <label for="fCalls">+ <span data-i18n="pay_simulator.f_calls">Endpoints, one per line</span>+ <span class="tip">+ <button type="button" aria-label="How do I write the call list?">?</button>+ <span class="bubble" role="tooltip" data-i18n="pay_simulator.tip_calls">One https URL per line. Add "x12" to repeat a call twelve times, and "@0.05" to assume a price instead of probing the live one. Each unique endpoint is probed once, unpaid.</span>+ </span>+ </label>+ <textarea id="fCalls" name="calls" spellcheck="false" autocomplete="off" aria-describedby="callsHint"></textarea>+ <div class="hint" id="callsHint" data-i18n="pay_simulator.hint_calls">+ <code>https://api.example.com/data x12</code> repeats a call.+ <code>@0.05</code> assumes a price rather than probing it.+ </div>+ </div>++ <div class="ps-run">+ <button type="submit" class="btn-primary" id="btnRun">+ <span id="runLabel" data-i18n="pay_simulator.run">Run the dry run</span>+ </button>+ <span class="kbd" aria-hidden="true" id="runKbd">Ctrl ↵</span>+ </div>+ <div class="hint" style="margin-top:0.7rem" data-i18n="pay_simulator.hint_free">+ No account needed. No wallet is touched, no session is created, and no credits move.+ </div>+ </div>+ </form>++ <!-- ── Right: the result ────────────────────────────── -->+ <section id="psResult" aria-live="polite" aria-busy="false">+ <div class="ps-idle" id="psIdle">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">+ <path d="M3 3v18h18" stroke-linecap="round" />+ <path d="M7 15l4-5 3 3 5-7" stroke-linecap="round" stroke-linejoin="round" />+ </svg>+ <h3 data-i18n="pay_simulator.idle_h">Nothing simulated yet</h3>+ <p data-i18n="pay_simulator.idle_p">+ A preset is already loaded. Press the button and the platform will probe each endpoint+ for its live 402 price, then replay your policy over the result.+ </p>+ </div>+ </section>+ </div>++ <div class="ps-next">+ <a href="/payments">+ <div class="t" data-i18n="pay_simulator.next_sessions">Create a session</div>+ <div class="d" data-i18n="pay_simulator.next_sessions_d">Turn the recommended policy into a real budget envelope with a bearer token.</div>+ </a>+ <a href="/docs/payment-sessions">+ <div class="t" data-i18n="pay_simulator.next_docs">How sessions work</div>+ <div class="d" data-i18n="pay_simulator.next_docs_d">Custody, authority, and execution: why the agent never holds a key.</div>+ </a>+ <a href="/docs/tutorials/agent-spending-envelope">+ <div class="t" data-i18n="pay_simulator.next_tutorial">Full walkthrough</div>+ <div class="d" data-i18n="pay_simulator.next_tutorial_d">From first session to a running agent, end to end.</div>+ </a>+ </div>+ </main>++ <div class="toast" id="toast" role="status"></div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>++ <script type="module">+ const $ = (id) => document.getElementById(id);+ const esc = (s) =>+ String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);++ // ── Presets ──────────────────────────────────────────────+ // Every preset points at endpoints that are live right now, so the very+ // first run returns real prices instead of a contrived example.+ const PRESETS = {+ research: {+ budget: '0.05', perTx: '', hosts: 'three.ws', ttl: '3600', network: 'solana',+ calls: 'https://three.ws/api/x402/model-check\nhttps://three.ws/api/x402/runway-lab\nhttps://three.ws/api/x402/model-check x5',+ },+ poller: {+ budget: '0.01', perTx: '0.002', hosts: 'three.ws', ttl: '900', network: 'solana',+ calls: 'https://three.ws/api/x402/model-check x30',+ },+ tight: {+ budget: '0.002', perTx: '0.0005', hosts: 'example.com', ttl: '900', network: 'solana',+ calls: 'https://three.ws/api/x402/model-check x4',+ },+ mixed: {+ budget: '2.5', perTx: '1', hosts: 'three.ws', ttl: '86400', network: 'solana',+ calls: 'https://three.ws/api/x402/model-check x3\nhttps://api.example.com/premium @1.20\nhttps://api.example.com/cheap @0.02 x6',+ },+ };++ function applyPreset(name) {+ const p = PRESETS[name];+ if (!p) return;+ $('fBudget').value = p.budget;+ $('fPerTx').value = p.perTx;+ $('fHosts').value = p.hosts;+ $('fTtl').value = p.ttl;+ $('fNetwork').value = p.network;+ $('fCalls').value = p.calls;+ for (const chip of document.querySelectorAll('[data-preset]')) {+ chip.setAttribute('aria-pressed', String(chip.dataset.preset === name));+ }+ }++ for (const chip of document.querySelectorAll('[data-preset]')) {+ chip.addEventListener('click', () => applyPreset(chip.dataset.preset));+ }++ // ── Call-list parsing ────────────────────────────────────+ // `https://host/path x12 @0.05`: repetition and an assumed price, in the+ // order a person would naturally type them, either order accepted.+ function parseCallLines(text) {+ const calls = [];+ for (const raw of String(text).split('\n')) {+ const line = raw.trim();+ if (!line || line.startsWith('#')) continue;+ const parts = line.split(/\s+/);+ const url = parts.shift();+ const call = { url };+ for (const token of parts) {+ const rep = /^x(\d+)$/i.exec(token);+ if (rep) { call.times = Number(rep[1]); continue; }+ const price = /^@\$?([0-9]*\.?[0-9]+)$/.exec(token);+ if (price) { call.price_usd = Number(price[1]); continue; }+ }+ calls.push(call);+ }+ return calls;+ }++ const money = (n) =>+ n == null ? '-' : n === 0 ? '$0' : n < 0.01 ? `$${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')}` : `$${n.toFixed(2)}`;++ function toast(msg) {+ const t = $('toast');+ t.textContent = msg;+ t.classList.add('on');+ clearTimeout(toast._t);+ toast._t = setTimeout(() => t.classList.remove('on'), 2200);+ }++ // ── Spend curve ──────────────────────────────────────────+ // The remaining balance after each step. Drawn from the response rather+ // than recomputed, so the picture cannot disagree with the verdict.+ function curveSvg(timeline, budget) {+ const pts = timeline.filter((s) => s.remaining_after_usd != null);+ if (pts.length < 2) return '';+ const W = 600, H = 80, PAD = 4;+ const x = (i) => PAD + (i * (W - PAD * 2)) / (pts.length - 1);+ const y = (v) => H - PAD - (Math.max(0, v) / budget) * (H - PAD * 2);+ const line = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(p.remaining_after_usd).toFixed(1)}`).join(' ');+ const area = `${line} L${x(pts.length - 1).toFixed(1)},${H - PAD} L${x(0).toFixed(1)},${H - PAD} Z`;+ const dots = pts+ .map((p, i) => {+ const refused = p.outcome === 'refused';+ return `<circle cx="${x(i).toFixed(1)}" cy="${y(p.remaining_after_usd).toFixed(1)}" r="${refused ? 3.2 : 2}" fill="${refused ? 'var(--danger)' : '#2fbf71'}"><title>${esc(`#${p.index + 1} ${p.outcome} · ${money(p.amount_usd)} · ${money(p.remaining_after_usd)} left`)}</title></circle>`;+ })+ .join('');+ return `+ <svg viewBox="0 0 ${W} ${H + 14}" role="img" aria-label="Remaining budget after each call" preserveAspectRatio="none">+ <defs><linearGradient id="cg" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#2fbf71" stop-opacity="0.28" />+ <stop offset="100%" stop-color="#2fbf71" stop-opacity="0" />+ </linearGradient></defs>+ <line x1="${PAD}" y1="${H - PAD}" x2="${W - PAD}" y2="${H - PAD}" stroke="rgba(255,255,255,0.12)" stroke-width="1" />+ <path d="${area}" fill="url(#cg)" />+ <path d="${line}" fill="none" stroke="#2fbf71" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round" />+ ${dots}+ <text class="axis" x="${PAD}" y="${H + 11}">${esc(money(budget))} at start</text>+ <text class="axis" x="${W - PAD}" y="${H + 11}" text-anchor="end">${esc(money(pts[pts.length - 1].remaining_after_usd))} left</text>+ </svg>`;+ }++ const RULE_LABEL = {+ insufficient_budget: 'ran out of budget',+ per_tx_exceeded: 'over the per-call ceiling',+ allowlist_blocked: 'host not on the allowlist',+ session_expired: 'session had expired',+ session_inactive: 'session was not active',+ };++ let expanded = false;+ let lastData = null;++ function renderTimeline(data) {+ const rows = expanded ? data.timeline : data.timeline.slice(0, 12);+ const html = rows+ .map((s) => {+ const cls = s.outcome === 'refused' ? (s.index === data.verdict.first_refusal_index ? ' is-first-refusal' : ' is-refused') : '';+ const why =+ s.outcome === 'refused'+ ? `<div class="tl-why bad">${esc(s.reason)}</div>`+ : s.outcome === 'unpriced'+ ? `<div class="tl-why dim">${esc(s.pricing.error_message || 'Could not be priced')}</div>`+ : s.outcome === 'free'+ ? `<div class="tl-why dim">Answered without a 402, so no payment and no policy check.</div>`+ : s.pricing.network+ ? `<div class="tl-why dim">${esc(String(s.pricing.network).split(':')[0])} · ${esc(s.pricing.source)}</div>`+ : `<div class="tl-why dim">${esc(s.pricing.source)}</div>`;+ const rep = s.of ? ` <span style="opacity:.4">${s.repetition}/${s.of}</span>` : '';+ return `+ <div class="tl-row${cls}">+ <div class="tl-idx">${s.index + 1}</div>+ <div class="tl-main">+ <div class="tl-url" title="${esc(s.url)}">${esc(s.url)}${rep}</div>+ ${why}+ </div>+ <div class="tl-right">+ <span class="tl-amt">${esc(money(s.amount_usd))}</span>+ <span class="tl-left">${s.remaining_after_usd == null ? '' : esc(money(s.remaining_after_usd)) + ' left'}</span>+ <span class="pill ${s.outcome}">${esc(s.outcome)}</span>+ </div>+ </div>`;+ })+ .join('');+ const more =+ data.timeline.length > 12+ ? `<button type="button" class="btn-ghost tl-more" id="tlMore">${expanded ? 'Show fewer' : `Show all ${data.timeline.length} calls`}</button>`+ : '';+ return `<div class="tl">${html}</div>${more}`;+ }++ function render(data) {+ lastData = data;+ const v = data.verdict;+ const rec = data.recommended_policy;+ const ok = v.feasible;++ const ruleSummary = Object.entries(v.refusals_by_rule)+ .map(([code, n]) => `${n} ${n === 1 ? 'call' : 'calls'} ${RULE_LABEL[code] || code}`)+ .join(', ');++ const verdictText = ok+ ? `All ${v.calls_total} ${v.calls_total === 1 ? 'call' : 'calls'} settle for ${money(v.spend_usd)}, leaving ${money(v.remaining_usd)} of the ${money(data.policy.budget_usd)} budget unused.`+ : `${ruleSummary || `${v.calls_unpriced} could not be priced`}. The run spends ${money(v.spend_usd)} of ${money(data.policy.budget_usd)} before it stalls.`;++ const notes = data.policy.notes.length+ ? `<div class="notes">${data.policy.notes.map((n) => esc(n)).join(' · ')}</div>`+ : '';++ const problems = data.problems.length+ ? `<div class="problems">+ <h3>Endpoints that could not be priced</h3>+ <ul>${data.problems.map((p) => `<li><code>${esc(p.url)}</code> ${esc(p.message)}</li>`).join('')}</ul>+ </div>`+ : '';++ const curve = curveSvg(data.timeline, data.policy.budget_usd);++ $('psResult').innerHTML = `+ <div class="verdict ${ok ? 'ok' : 'warn'}">+ <div class="verdict-icon" aria-hidden="true">${ok ? '✓' : '!'}</div>+ <div class="verdict-body">+ <h3>${ok ? 'This policy covers the run' : 'This policy would stop the agent'}</h3>+ <p>${esc(verdictText)}</p>+ ${notes}+ </div>+ </div>++ <div class="ps-stats">+ <div class="stat"><div class="k">Settles</div><div class="v g">${v.calls_settled}</div></div>+ <div class="stat"><div class="k">Refused</div><div class="v ${v.calls_refused ? 'r' : ''}">${v.calls_refused}</div></div>+ <div class="stat"><div class="k">Total cost</div><div class="v p">${esc(money(v.spend_usd))}</div></div>+ <div class="stat"><div class="k">Budget used</div><div class="v b">${v.budget_used_pct}%</div></div>+ </div>++ ${curve ? `<div class="curve">+ <div class="curve-head">+ <h3>Remaining budget, call by call</h3>+ <div class="legend"><i class="l-settle">settles</i><i class="l-refuse">refused</i></div>+ </div>+ ${curve}+ </div>` : ''}++ <div id="tlHost">${renderTimeline(data)}</div>++ ${problems}++ <div class="rec">+ <h3>The smallest policy that covers this run</h3>+ <p>Derived from the prices just measured: the summed cost, the largest single payment, and every host the run actually touches.</p>+ <div class="rec-grid">+ <div class="rec-item"><div class="k">Budget</div><div class="v">${esc(money(rec.budget_usd))}<small>${esc(money(rec.exact_cost_usd))} exact, rounded up</small></div></div>+ <div class="rec-item"><div class="k">Max per call</div><div class="v">${esc(money(rec.max_per_tx_usd))}<small>largest payment in the run</small></div></div>+ <div class="rec-item"><div class="k">Allowed hosts</div><div class="v" style="font-size:12.5px">${rec.allowed_hosts.length ? rec.allowed_hosts.map((h) => esc(h)).join('<br>') : '-'}${rec.missing_hosts.length ? `<small style="color:var(--warn)">missing from your allowlist: ${rec.missing_hosts.map((h) => esc(h)).join(', ')}</small>` : ''}</div></div>+ </div>+ <div class="rec-actions">+ <button type="button" class="btn-primary" id="btnApply">Apply and re-run</button>+ <a class="btn-ghost" href="/payments">Create this session</a>+ </div>+ </div>++ <div class="codewrap">+ <div class="code-head">+ <h3>The create call this becomes</h3>+ <button type="button" class="btn-ghost" id="btnCopy">Copy</button>+ </div>+ <pre id="codeBlock">${esc(curlFor(rec))}</pre>+ </div>`;++ $('psResult').setAttribute('aria-busy', 'false');+ wireResultHandlers();+ }++ function curlFor(rec) {+ const body = {+ budget_usd: rec.budget_usd,+ max_per_tx_usd: rec.max_per_tx_usd,+ allowed_hosts: rec.allowed_hosts,+ expiry_seconds: rec.expiry_seconds,+ network: rec.network,+ };+ return `curl -X POST https://three.ws/api/pay/session \\\n -H 'content-type: application/json' \\\n -H 'cookie: __Host-sid=<your session cookie>' \\\n -d '${JSON.stringify(body)}'`;+ }++ function wireResultHandlers() {+ const more = $('tlMore');+ if (more) {+ more.addEventListener('click', () => {+ expanded = !expanded;+ $('tlHost').innerHTML = renderTimeline(lastData);+ wireResultHandlers();+ if (!expanded) $('tlHost').scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ });+ }+ const apply = $('btnApply');+ if (apply) {+ apply.addEventListener('click', () => {+ const rec = lastData.recommended_policy;+ $('fBudget').value = rec.budget_usd;+ $('fPerTx').value = rec.max_per_tx_usd ?? '';+ $('fHosts').value = rec.allowed_hosts.join(', ');+ for (const chip of document.querySelectorAll('[data-preset]')) chip.setAttribute('aria-pressed', 'false');+ run();+ });+ }+ const copy = $('btnCopy');+ if (copy) {+ copy.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText($('codeBlock').textContent);+ toast('Copied');+ } catch {+ toast('Could not copy. Select the text instead.');+ }+ });+ }+ }++ function showLoading(count) {+ $('psResult').setAttribute('aria-busy', 'true');+ const rows = Array.from({ length: Math.min(6, Math.max(3, count)) }, () => '<div class="skel skel-row"></div>').join('');+ $('psResult').innerHTML = `+ <div class="skel" style="height:74px;margin-bottom:1.25rem"></div>+ <div class="ps-stats">${Array.from({ length: 4 }, () => '<div class="skel" style="height:66px"></div>').join('')}</div>+ <div class="skel" style="height:130px;margin-bottom:1.35rem"></div>+ ${rows}`;+ }++ function showError(message, detail) {+ $('psResult').setAttribute('aria-busy', 'false');+ $('psResult').innerHTML = `+ <div class="ps-error">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">+ <circle cx="12" cy="12" r="9" /><path d="M12 7v6" stroke-linecap="round" /><circle cx="12" cy="16.5" r="0.9" fill="currentColor" stroke="none" />+ </svg>+ <h3>${esc(message)}</h3>+ <p>${esc(detail || 'Check the endpoint list and try again.')}</p>+ <button type="button" class="btn-ghost" id="btnRetry">Try again</button>+ </div>`;+ $('btnRetry')?.addEventListener('click', run);+ }++ // ── Run ──────────────────────────────────────────────────+ let inFlight = null;++ async function run() {+ const calls = parseCallLines($('fCalls').value);+ if (!calls.length) {+ $('fCalls').setAttribute('aria-invalid', 'true');+ $('fCalls').focus();+ showError('No endpoints to simulate', 'Add at least one https URL, one per line, then run again.');+ return;+ }+ $('fCalls').removeAttribute('aria-invalid');++ const payload = {+ policy: {+ budget_usd: Number($('fBudget').value) || 0,+ max_per_tx_usd: $('fPerTx').value === '' ? null : Number($('fPerTx').value),+ allowed_hosts: $('fHosts').value,+ expiry_seconds: Number($('fTtl').value),+ network: $('fNetwork').value,+ },+ calls,+ };++ // A second submit while one is in flight aborts the first, so a+ // slow probe can never overwrite a newer result.+ inFlight?.abort();+ const controller = new AbortController();+ inFlight = controller;++ $('btnRun').disabled = true;+ $('runLabel').innerHTML = '<span class="spinner" aria-hidden="true"></span> Probing live prices';+ showLoading(calls.reduce((n, c) => n + (c.times || 1), 0));++ try {+ const res = await fetch('/api/pay/simulate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ signal: controller.signal,+ });+ const data = await res.json().catch(() => null);+ if (!res.ok || !data?.ok) {+ showError(+ data?.error?.message || data?.message || `Simulation failed (HTTP ${res.status})`,+ res.status === 429 ? 'Too many simulations from this address. Wait a moment and try again.' : null,+ );+ return;+ }+ expanded = false;+ render(data);+ } catch (err) {+ if (err.name === 'AbortError') return;+ showError('Could not reach the simulator', err.message);+ } finally {+ if (inFlight === controller) inFlight = null;+ $('btnRun').disabled = false;+ $('runLabel').textContent = 'Run the dry run';+ }+ }++ $('psForm').addEventListener('submit', (e) => {+ e.preventDefault();+ run();+ });++ // Ctrl/Cmd+Enter runs from anywhere on the page.+ document.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {+ e.preventDefault();+ run();+ }+ });+ if (navigator.platform?.toLowerCase().includes('mac')) $('runKbd').textContent = '⌘ ↵';++ applyPreset('research');+ </script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/play/solver.html b/pages/play/solver.htmlnew file mode 100644index 000000000..7436e4134--- /dev/null+++ b/pages/play/solver.html@@ -0,0 +1,129 @@+<!doctype html>+<html lang="en">+ <head>+ <script>+ /* three.ws theme boot (no-flash); runtime in /theme-switcher.js */ (function () {+ try {+ var m = localStorage.getItem('twx_theme');+ var l =+ m === 'auto'+ ? window.matchMedia &&+ window.matchMedia('(prefers-color-scheme: light)').matches+ : m === 'light';+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');+ } catch (e) {+ document.documentElement.setAttribute('data-theme', 'dark');+ }+ })();+ </script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>The economy solver · three.ws</title>+ <meta+ name="description"+ content="The /play world economy, solved. Exact expected cash and XP per hour for every tree, rock and pond at every skill level, the optimal fish-and-cook time split, what the store costs in minutes and swings, the wheel's true expected value, and per-kill combat worth. Computed in closed form from the game's own tables, never measured."+ />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/play/solver" />+ <meta property="og:title" content="The economy solver · three.ws" />+ <meta+ property="og:description"+ content="Exact expected cash and XP per hour for every node in the world at every level, solved in closed form from the game's own tables. Move the level and watch the whole world reprice."+ />+ <meta+ property="og:image"+ content="https://three.ws/api/page-og?s=crypto&t=The+economy+solver&d=Exact+expected+cash+and+XP+per+hour+for+every+node+in+the+%2Fplay+world+at+every+skill+level%2C+solved+in+closed+form+from+the+game%27s+own+tables&p=%2Fplay%2Fsolver"+ />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="The economy solver · three.ws" />+ <meta+ name="twitter:description"+ content="Every node in the /play world, priced exactly, at every level. Closed form, not measured."+ />+ <meta+ name="twitter:image"+ content="https://three.ws/api/page-og?s=crypto&t=The+economy+solver&d=Exact+expected+cash+and+XP+per+hour+for+every+node+in+the+%2Fplay+world+at+every+skill+level%2C+solved+in+closed+form+from+the+game%27s+own+tables&p=%2Fplay%2Fsolver"+ />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/ui-juice.css" />+ <link rel="stylesheet" href="/src/play-solver.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <link rel="canonical" href="https://three.ws/play/solver" />+ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "WebApplication",+ "name": "The economy solver",+ "applicationCategory": "GameApplication",+ "operatingSystem": "Any modern browser",+ "description": "An exact, closed-form model of the three.ws /play world economy: expected cash and XP per hour for every gatherable node at every skill level, the optimal fish-and-cook split, store payback in minutes, wheel expected value, and per-kill combat worth.",+ "url": "https://three.ws/play/solver",+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }+ }+ </script>+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <meta property="og:locale" content="en_US" />+ <meta property="og:image:alt" content="The three.ws /play economy solver" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="ps-shell">+ <div class="ps-glow" aria-hidden="true"></div>++ <section class="ps-hero">+ <p class="ps-kicker">The /play world economy, solved</p>+ <h1 class="ps-title">What is an hour <em>actually</em> worth?</h1>+ <p class="ps-sub">+ Every yield rule in the open world is a pure function of your skill level and the+ node you are standing at, and every swing has a fixed cadence the server enforces.+ That means the expected cash, XP and goods per hour are not something you have to+ grind out and average. They are solvable, exactly, in one pass.+ </p>+ <p class="ps-sub">+ So we solved them. Move the level below and the entire world reprices: every tree,+ every rock, every pond, the wheel, the store and each mob in it.+ </p>+ <div class="ps-hero-actions">+ <a class="ps-btn ps-btn-primary" href="/play">Enter the world</a>+ <a class="ps-btn" href="/play/economy">See the raw price tables</a>+ <a class="ps-btn" href="/docs/economy-solver">How the model works</a>+ </div>+ </section>++ <p id="ps-status" class="ps-sr" role="status" aria-live="polite"></p>+ <div id="ps-content"></div>++ <p class="ps-fineprint">+ Served by <code>/api/play/solver</code>, which imports the authoritative game modules+ rather than restating them: the yield curves from+ <code>items.js</code>, the cadences from <code>activities.js</code>, the prices from+ <code>shop.js</code> and the per-node tuning from <code>world-features.js</code>. No+ number on this page was measured, sampled or transcribed, so it cannot drift from what+ the server actually does. The model's assumptions are published with every result and+ listed at the bottom of this page, because a rate quoted without its assumptions is a+ lie. Cash is a game resource that never leaves the world; only boutique unlocks and+ paid spins touch the chain.+ </p>+ </main>++ <script type="module" src="/src/play-solver.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/scripts/verify-economy-lab.mjs b/scripts/verify-economy-lab.mjsnew file mode 100644index 000000000..27d5c57cb--- /dev/null+++ b/scripts/verify-economy-lab.mjs@@ -0,0 +1,154 @@+#!/usr/bin/env node+/**+ * Browser verification for /economy-lab (the Runway Lab).+ *+ * Loads the page against a running server, asserts the live seed rendered, then+ * drives the real controls and asserts the projection responds: a starved rail+ * must recover when the fee wallet is funded, and the apply panel must emit a+ * command only for knobs that actually differ from live.+ *+ * Fails on ANY console error or page error, because a chart that silently+ * throws still looks like a chart.+ *+ * node scripts/verify-economy-lab.mjs [baseUrl] # default http://localhost:3000+ *+ * Screenshots land in reports/economy-lab/ (gitignored) for a visual check.+ */++import { mkdirSync } from 'node:fs';+import { resolve } from 'node:path';+import { chromium } from 'playwright';++const BASE = process.argv[2] || process.env.BASE_URL || 'http://localhost:3000';+const OUT = resolve(process.cwd(), 'reports/economy-lab');++const problems = [];+const ok = (label) => console.log(` ok ${label}`);+const bad = (label, detail) => {+ problems.push(`${label}${detail ? `: ${detail}` : ''}`);+ console.log(` FAIL ${label}${detail ? ` (${detail})` : ''}`);+};++function assert(cond, label, detail) {+ if (cond) ok(label);+ else bad(label, detail);+}++const run = async () => {+ mkdirSync(OUT, { recursive: true });+ const browser = await chromium.launch();+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });++ const consoleErrors = [];+ page.on('console', (m) => {+ if (m.type() === 'error') consoleErrors.push(m.text());+ });+ page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`));++ console.log(`\n/economy-lab against ${BASE}\n`);+ const res = await page.goto(`${BASE}/economy-lab`, { waitUntil: 'domcontentloaded', timeout: 60_000 });+ assert(res?.status() === 200, 'page returns 200', `got ${res?.status()}`);++ // The verdict banner leaves the loading state only once the live seed lands.+ await page.waitForFunction(+ () => document.getElementById('el-verdict')?.dataset.state !== 'loading',+ null,+ { timeout: 90_000 },+ ).catch(() => {});++ const state = await page.getAttribute('#el-verdict', 'data-state');+ assert(['healthy', 'throttled', 'starved'].includes(state), 'live seed resolved a verdict', `state=${state}`);++ const statCount = await page.locator('#el-stats .el-stat').count();+ assert(statCount === 6, 'live state panel rendered six readings', `got ${statCount}`);++ const skeletons = await page.locator('#el-stats .el-skeleton').count();+ assert(skeletons === 0, 'skeletons were replaced by real values');++ const kpiCount = await page.locator('#el-kpis .el-kpi').count();+ assert(kpiCount === 6, 'projection KPIs rendered', `got ${kpiCount}`);++ const drew = await page.evaluate(() => {+ const c = document.getElementById('el-chart');+ const ctx = c.getContext('2d');+ const d = ctx.getImageData(0, 0, c.width, c.height).data;+ for (let i = 3; i < d.length; i += 4) if (d[i] !== 0) return true;+ return false;+ });+ assert(drew, 'chart painted pixels');++ const leverCount = await page.locator('#el-levers .el-lever').count();+ assert(leverCount === 3, 'three levers solved', `got ${leverCount}`);++ // Untouched, the apply panel must offer nothing: every knob matches live.+ const applyEmpty = await page.locator('#el-apply .el-empty').count();+ assert(applyEmpty === 1, 'no command offered while the config matches live');++ assert(await page.locator('#el-reset').isDisabled(), 'reset is disabled until something changes');++ await page.screenshot({ path: `${OUT}/01-live.png`, fullPage: true });++ // Drive a real change: widen the heartbeat and confirm the command appears.+ await page.evaluate(() => {+ const el = document.getElementById('el-heartbeat');+ el.value = String(Number(el.max));+ el.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await page.waitForTimeout(250);+ const cmd = await page.locator('#el-apply .el-cmd').textContent().catch(() => '');+ assert(/X402_WALLET_FEE_MIN_BUDGET_LAMPORTS=/.test(cmd || ''), 'heartbeat change emits its env var');+ assert(/--update-env-vars/.test(cmd || ''), 'command uses the merging flag');+ assert(!/--set-env-vars/.test(cmd || ''), 'command never uses the replacing flag');+ assert(!(await page.locator('#el-reset').isDisabled()), 'reset enables once a knob is dirty');++ // Funding must move the projection: a rail limited by its floor recovers.+ const before = await page.locator('#el-kpis .el-kpi').first().locator('.el-kpi-value').textContent();+ await page.evaluate(() => {+ const el = document.getElementById('el-balance');+ el.value = String(Number(el.max));+ el.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await page.waitForTimeout(250);+ const after = await page.locator('#el-kpis .el-kpi').first().locator('.el-kpi-value').textContent();+ const n = (s) => Number(String(s).replace(/[^0-9]/g, '')) || 0;+ assert(n(after) > n(before), 'funding the wallet raises projected throughput', `${before} -> ${after}`);++ await page.screenshot({ path: `${OUT}/02-funded.png`, fullPage: true });++ // Reset restores every knob and clears the command.+ await page.click('#el-reset');+ await page.waitForTimeout(250);+ assert((await page.locator('#el-apply .el-empty').count()) === 1, 'reset clears the pending command');++ // Tooltips: keyboard focus alone must open one, and Escape must close it.+ await page.locator('.el-help').first().focus();+ await page.waitForTimeout(150);+ assert(await page.locator('#el-tip').isVisible(), 'tooltip opens on keyboard focus');+ await page.keyboard.press('Escape');+ await page.waitForTimeout(150);+ assert(!(await page.locator('#el-tip').isVisible()), 'Escape closes the tooltip');++ // Narrow viewport: the page must never scroll horizontally.+ await page.setViewportSize({ width: 360, height: 900 });+ await page.waitForTimeout(400);+ const overflow = await page.evaluate(() =>+ document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert(overflow <= 1, 'no horizontal overflow at 360px', `${overflow}px`);+ await page.screenshot({ path: `${OUT}/03-mobile.png`, fullPage: true });++ assert(consoleErrors.length === 0, 'no console or page errors', consoleErrors.slice(0, 3).join(' | '));++ await browser.close();++ console.log(`\nscreenshots: ${OUT}`);+ if (problems.length) {+ console.error(`\n${problems.length} check(s) failed:\n${problems.map((p) => ` - ${p}`).join('\n')}\n`);+ process.exit(1);+ }+ console.log('\nall checks passed\n');+};++run().catch((err) => {+ console.error(`verification could not run: ${err.message}`);+ process.exit(1);+});diff --git a/src/conversions.js b/src/conversions.jsnew file mode 100644index 000000000..e939e76dd--- /dev/null+++ b/src/conversions.js@@ -0,0 +1,348 @@+/**+ * /conversions: both sides of the moment a metered trial runs out.+ *+ * Reads GET /api/marketplace/trial-status, which answers from two fixed+ * perspectives: the trials the signed-in user holds, and the trials running on+ * skills their agents sell. Nothing here initiates a payment. The convert CTA+ * links to the agent's own page, where the existing purchase flow shows the+ * amount and destination before anything is signed.+ */++const ENDPOINT = '/api/marketplace/trial-status';+const ROLES = ['buyer', 'seller'];++const els = {+ tabs: /** @type {HTMLButtonElement[]} */ ([]),+ panel: null,+ list: null,+ stats: null,+};++/** Per-role response cache, so flipping the tabs back is instant and quiet. */+const cache = new Map();+/** Guards against a slow first request painting over a newer one. */+let requestSeq = 0;++// ── helpers ───────────────────────────────────────────────────────────────────++function esc(value) {+ return String(value ?? '').replace(+ /[&<>"']/g,+ (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch],+ );+}++function plural(n, one, many) {+ return `${n} ${n === 1 ? one : many}`;+}++/** "3 hours ago" without pulling a date library in for one label. */+function relativeTime(iso) {+ if (!iso) return '';+ const then = Date.parse(iso);+ if (!Number.isFinite(then)) return '';+ const mins = Math.round((Date.now() - then) / 60000);+ if (mins < 1) return 'just now';+ if (mins < 60) return `${mins}m ago`;+ const hours = Math.round(mins / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.round(hours / 24);+ if (days < 30) return `${days}d ago`;+ return new Date(then).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });+}++function mintLabel(mint) {+ if (!mint) return '';+ // The platform's own mint is the common case and deserves its ticker.+ if (mint === 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump') return '$THREE';+ return `${mint.slice(0, 4)}…${mint.slice(-4)}`;+}++function priceHtml(price) {+ if (!price) return '<span class="cv-priceless">No price set</span>';+ return `<span class="cv-price">${esc(price.display)}<small>${esc(mintLabel(price.mint))}</small></span>`;+}++const STATE_PILL = {+ fresh: { cls: 'pill-fresh', label: 'Fresh' },+ 'running-low': { cls: 'pill-low', label: 'Running low' },+ exhausted: { cls: 'pill-out', label: 'Trial spent' },+};++/**+ * The runs-left meter. A metered trial that renders as a bare number teaches+ * nothing; pips make "one run left" read at a glance. Capped so a generous+ * grant does not produce a hundred pips.+ */+function meterHtml(remaining, granted) {+ const total = Math.max(1, Math.min(10, Number(granted) || Number(remaining) || 1));+ const left = Math.max(0, Math.min(total, Number(remaining) || 0));+ const low = left <= Math.max(1, Math.floor(total / 3));+ const pips = Array.from({ length: total }, (_, i) => {+ const filled = i < left;+ return `<span class="meter-pip${filled ? ' is-left' : ''}${filled && low ? ' is-low' : ''}"></span>`;+ }).join('');+ const label = granted ? `${left} of ${granted} free runs left` : `${plural(left, 'free run', 'free runs')} left`;+ const count = left === 0 ? 'Every free run spent' : `<strong>${left}</strong> of ${esc(granted ?? left)} free runs left`;+ return `+ <div class="meter${left === 0 ? ' is-spent' : ''}" role="img" aria-label="${esc(label)}">${pips}</div>+ <div class="meter-count">${count}</div>`;+}++// ── renderers ─────────────────────────────────────────────────────────────────++function renderStats(cards) {+ els.stats.innerHTML = cards+ .map(+ (c) => `+ <div class="stat-card${c.tone ? ` is-${c.tone}` : ''}">+ <div class="stat-val">${esc(c.value)}${c.unit ? `<span class="stat-unit">${esc(c.unit)}</span>` : ''}</div>+ <div class="stat-lbl">${esc(c.label)}</div>+ </div>`,+ )+ .join('');+}++function renderBuyer(data) {+ const s = data.summary;+ renderStats([+ { value: s.active, label: 'Active trials' },+ { value: s.runningLow, label: 'Running low', tone: s.runningLow ? 'hot' : null },+ { value: s.exhausted, label: 'Spent, ready to buy', tone: s.exhausted ? 'hot' : null },+ { value: s.fresh, label: 'Barely touched' },+ ]);++ if (!data.trials.length) {+ return emptyState({+ icon: '◎',+ title: 'No trials running',+ body: 'Skills with a free trial let you run them a few times before you decide. Browse the marketplace and start one; it shows up here with the runs you have left.',+ cta: { href: '/marketplace', label: 'Browse the marketplace' },+ });+ }++ els.list.innerHTML = data.trials+ .map((t) => {+ const pill = STATE_PILL[t.state] || STATE_PILL.fresh;+ const cta =+ t.state === 'exhausted'+ ? `<a class="btn btn-primary" href="${esc(t.agentUrl)}">Buy it</a>`+ : `<a class="btn" href="${esc(t.agentUrl)}">Open agent</a>`;+ return `+ <article class="cv-row">+ <div class="cv-main">+ <div class="cv-title">+ <span class="cv-skill">${esc(t.skill)}</span>+ <span class="pill ${pill.cls}">${esc(pill.label)}</span>+ </div>+ <div class="cv-agent">from <a href="${esc(t.agentUrl)}">${esc(t.agentName)}</a> · started ${esc(relativeTime(t.startedAt))}</div>+ ${meterHtml(t.trialRemaining, t.trialUses)}+ </div>+ <div class="cv-side">+ ${priceHtml(t.price)}+ ${cta}+ </div>+ </article>`;+ })+ .join('');+}++function renderSeller(data) {+ const s = data.summary;+ renderStats([+ { value: s.warmLeads, label: 'Buyers out of free runs', tone: s.warmLeads ? 'hot' : null },+ { value: s.lastRun, label: 'On their last run' },+ { value: s.sold, label: 'Converted to sales' },+ {+ value: s.potential.display,+ unit: mintLabel(data.queue.find((q) => q.price)?.price.mint),+ label: 'Sitting in the queue',+ tone: 'money',+ },+ ]);++ if (!data.queue.length) {+ return emptyState({+ icon: '◇',+ title: 'No trials running on your skills',+ body: 'Attach a free trial to a priced skill and buyers can run it a few times before paying. Every trial you grant shows up here with how close it is to converting.',+ cta: { href: '/tutorials/sell-a-skill-with-a-trial', label: 'Set up a skill with a trial' },+ });+ }++ els.list.innerHTML = data.queue+ .map((q) => {+ const rate = q.sold + q.activeTrials > 0 ? Math.round(q.conversionRate * 100) : 0;+ return `+ <article class="cv-row">+ <div class="cv-main">+ <div class="cv-title">+ <span class="cv-skill">${esc(q.skill)}</span>+ ${q.exhausted ? `<span class="pill pill-out">${esc(plural(q.exhausted, 'buyer waiting', 'buyers waiting'))}</span>` : ''}+ </div>+ <div class="cv-agent">on <a href="/agent/${esc(q.agentId)}">${esc(q.agentName)}</a> · last activity ${esc(relativeTime(q.lastActivity))}</div>+ <div class="cv-metrics">+ <span class="cv-metric"><b>${esc(q.activeTrials)}</b> trials running</span>+ <span class="cv-metric${q.lastRun ? ' is-hot' : ''}"><b>${esc(q.lastRun)}</b> on last run</span>+ <span class="cv-metric"><b>${esc(q.sold)}</b> sold</span>+ <span class="cv-metric"><b>${rate}%</b> convert</span>+ </div>+ </div>+ <div class="cv-side">+ ${priceHtml(q.price)}+ <a class="btn" href="${esc(q.pricingUrl)}">Edit pricing</a>+ </div>+ </article>`;+ })+ .join('');+}++function emptyState({ icon, title, body, cta }) {+ els.list.innerHTML = `+ <div class="cv-state">+ <div class="cv-state-icon" aria-hidden="true">${esc(icon)}</div>+ <h2>${esc(title)}</h2>+ <p>${esc(body)}</p>+ ${cta ? `<a class="btn btn-primary" href="${esc(cta.href)}">${esc(cta.label)}</a>` : ''}+ </div>`;+}++function signedOutState() {+ renderStats([]);+ els.list.innerHTML = `+ <div class="cv-state">+ <div class="cv-state-icon" aria-hidden="true">◔</div>+ <h2>Sign in to see your trials</h2>+ <p>Trials are tied to your account on both sides: the ones you are holding and the ones running on skills your agents sell.</p>+ <a class="btn btn-primary" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a>+ </div>`;+}++function errorState(message, role) {+ renderStats([]);+ els.list.innerHTML = `+ <div class="cv-state is-error">+ <div class="cv-state-icon" aria-hidden="true">⚠</div>+ <h2>Could not load your trials</h2>+ <p>${esc(message)}</p>+ <button class="btn" type="button" id="cv-retry">Try again</button>+ </div>`;+ els.list.querySelector('#cv-retry')?.addEventListener('click', () => load(role, { force: true }));+}++function loadingState() {+ els.panel.setAttribute('aria-busy', 'true');+ els.list.innerHTML = `+ <div class="skeleton skeleton-row"></div>+ <div class="skeleton skeleton-row" style="animation-delay:.12s"></div>+ <div class="skeleton skeleton-row" style="animation-delay:.24s"></div>`;+}++// ── data ──────────────────────────────────────────────────────────────────────++async function load(role, { force = false } = {}) {+ if (!force && cache.has(role)) {+ paint(role, cache.get(role));+ return;+ }+ const seq = ++requestSeq;+ loadingState();++ let res;+ try {+ res = await fetch(`${ENDPOINT}?role=${encodeURIComponent(role)}`, {+ credentials: 'include',+ headers: { Accept: 'application/json' },+ });+ } catch {+ if (seq !== requestSeq) return;+ els.panel.setAttribute('aria-busy', 'false');+ return errorState('The request did not reach the server. Check your connection and try again.', role);+ }+ if (seq !== requestSeq) return;+ els.panel.setAttribute('aria-busy', 'false');++ if (res.status === 401) return signedOutState();+ if (res.status === 429) {+ return errorState('Too many requests from this address. Wait a moment and try again.', role);+ }+ if (!res.ok) {+ let detail = `The server returned HTTP ${res.status}.`;+ try {+ const body = await res.json();+ if (body?.error_description) detail = body.error_description;+ } catch {+ /* a non-JSON error body is still an error; the status carries the meaning */+ }+ return errorState(detail, role);+ }++ let payload;+ try {+ payload = (await res.json())?.data;+ } catch {+ return errorState('The server sent a response this page could not read.', role);+ }+ if (!payload) return errorState('The server sent an empty response.', role);++ cache.set(role, payload);+ paint(role, payload);+}++function paint(role, payload) {+ els.panel.setAttribute('aria-busy', 'false');+ if (role === 'seller') renderSeller(payload);+ else renderBuyer(payload);+}++// ── tabs ──────────────────────────────────────────────────────────────────────++function selectRole(role, { push = true } = {}) {+ if (!ROLES.includes(role)) role = 'buyer';+ for (const tab of els.tabs) {+ const on = tab.dataset.role === role;+ tab.setAttribute('aria-selected', on ? 'true' : 'false');+ tab.tabIndex = on ? 0 : -1;+ if (on) els.panel.setAttribute('aria-labelledby', tab.id);+ }+ if (push) {+ const url = new URL(location.href);+ if (role === 'buyer') url.searchParams.delete('role');+ else url.searchParams.set('role', role);+ history.replaceState({}, '', url);+ }+ load(role);+}++function wireTabs() {+ for (const tab of els.tabs) {+ tab.addEventListener('click', () => selectRole(tab.dataset.role));+ }+ // Arrow-key navigation is what makes a tablist a tablist for keyboard users.+ document.querySelector('.role-switch')?.addEventListener('keydown', (e) => {+ const idx = els.tabs.findIndex((t) => t.getAttribute('aria-selected') === 'true');+ let next = null;+ if (e.key === 'ArrowRight') next = (idx + 1) % els.tabs.length;+ else if (e.key === 'ArrowLeft') next = (idx - 1 + els.tabs.length) % els.tabs.length;+ else if (e.key === 'Home') next = 0;+ else if (e.key === 'End') next = els.tabs.length - 1;+ if (next === null) return;+ e.preventDefault();+ els.tabs[next].focus();+ selectRole(els.tabs[next].dataset.role);+ });+}++function init() {+ els.tabs = Array.from(document.querySelectorAll('.role-tab'));+ els.panel = document.getElementById('cv-panel');+ els.list = document.getElementById('cv-list');+ els.stats = document.getElementById('cv-stats');+ if (!els.panel || !els.list || !els.stats || !els.tabs.length) return;++ wireTabs();+ selectRole(new URL(location.href).searchParams.get('role') || 'buyer', { push: false });+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/src/economy-lab.css b/src/economy-lab.cssnew file mode 100644index 000000000..6a4ed848c--- /dev/null+++ b/src/economy-lab.css@@ -0,0 +1,800 @@+/* Runway Lab (/economy-lab).+ *+ * Self-contained page styling. Colour comes from a small token set that flips+ * on [data-theme="light"] so the page reads in both themes without a second+ * stylesheet, and every interactive control carries hover, active, and+ * focus-visible states. Layout is fluid: one column under 900px, two above,+ * and the chart scales with its container rather than a fixed pixel width.+ */++.el-shell {+ --el-bg: #08090c;+ --el-surface: #0f1117;+ --el-surface-2: #151823;+ --el-line: #232735;+ --el-line-2: #313648;+ --el-ink: #eef1f7;+ --el-muted: #98a0b3;+ --el-faint: #6a7183;+ --el-accent: #6ee7b7;+ --el-accent-ink: #04241a;+ --el-warn: #fbbf24;+ --el-danger: #fb7185;+ --el-info: #7dd3fc;+ --el-r: 14px;+ --el-r-sm: 9px;++ max-width: 1240px;+ margin: 0 auto;+ padding: clamp(1.25rem, 3vw, 2.5rem) clamp(1rem, 3vw, 2rem) 5rem;+ color: var(--el-ink);+ font-size: 15px;+ line-height: 1.6;+}++:root[data-theme='light'] .el-shell {+ --el-bg: #ffffff;+ --el-surface: #ffffff;+ --el-surface-2: #f5f7fa;+ --el-line: #e2e6ee;+ --el-line-2: #cdd4e0;+ --el-ink: #10131a;+ --el-muted: #566076;+ --el-faint: #79839a;+ --el-accent: #0f9d6e;+ --el-accent-ink: #ffffff;+ --el-warn: #b7791f;+ --el-danger: #c53148;+ --el-info: #1d7fb5;+}++.el-shell :is(h1, h2, h3) {+ margin: 0;+ line-height: 1.15;+ letter-spacing: -0.02em;+}++.el-shell code {+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ font-size: 0.88em;+ background: var(--el-surface-2);+ border: 1px solid var(--el-line);+ border-radius: 5px;+ padding: 0.1em 0.4em;+ word-break: break-word;+}++.el-shell a {+ color: var(--el-accent);+ text-underline-offset: 3px;+}+.el-shell a:hover { text-decoration-thickness: 2px; }++.el-skip {+ position: absolute;+ left: -9999px;+ top: 0;+ background: var(--el-accent);+ color: var(--el-accent-ink);+ padding: 0.6rem 1rem;+ border-radius: 0 0 var(--el-r-sm) 0;+ font-weight: 600;+ z-index: 60;+}+.el-skip:focus { left: 0; }++/* ── Hero ──────────────────────────────────────────────────────────────── */+.el-hero { margin-bottom: clamp(1.5rem, 4vw, 2.75rem); }++.el-kicker {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0 0 0.75rem;+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--el-muted);+}++.el-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--el-accent);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--el-accent) 60%, transparent);+ animation: el-pulse 2.4s ease-out infinite;+}++@keyframes el-pulse {+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--el-accent) 55%, transparent); }+ 70% { box-shadow: 0 0 0 9px color-mix(in srgb, var(--el-accent) 0%, transparent); }+ 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--el-accent) 0%, transparent); }+}++.el-title {+ font-size: clamp(2.1rem, 6vw, 3.6rem);+ font-weight: 700;+}+.el-title em {+ font-style: normal;+ background: linear-gradient(100deg, var(--el-accent), var(--el-info));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+}++.el-sub {+ max-width: 62ch;+ margin: 0.85rem 0 0;+ color: var(--el-muted);+ font-size: clamp(0.98rem, 1.6vw, 1.09rem);+}+.el-sub strong { color: var(--el-ink); font-weight: 600; }++/* ── Verdict banner ────────────────────────────────────────────────────── */+.el-verdict {+ display: flex;+ gap: 1rem;+ align-items: flex-start;+ margin-top: 1.6rem;+ padding: 1.05rem 1.2rem;+ border: 1px solid var(--el-line);+ border-left-width: 4px;+ border-radius: var(--el-r);+ background: var(--el-surface);+ transition: border-color 0.25s ease, background 0.25s ease;+}+.el-verdict[data-state='healthy'] { border-left-color: var(--el-accent); }+.el-verdict[data-state='throttled'] { border-left-color: var(--el-warn); }+.el-verdict[data-state='starved'] { border-left-color: var(--el-danger); }+.el-verdict[data-state='error'] { border-left-color: var(--el-danger); }+.el-verdict[data-state='loading'] { border-left-color: var(--el-line-2); }++.el-verdict-icon {+ flex: none;+ width: 34px;+ height: 34px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: var(--el-surface-2);+ font-size: 1.05rem;+ line-height: 1;+}+.el-verdict[data-state='healthy'] .el-verdict-icon { color: var(--el-accent); }+.el-verdict[data-state='throttled'] .el-verdict-icon { color: var(--el-warn); }+.el-verdict[data-state='starved'] .el-verdict-icon,+.el-verdict[data-state='error'] .el-verdict-icon { color: var(--el-danger); }++.el-spin {+ width: 15px;+ height: 15px;+ border: 2px solid var(--el-line-2);+ border-top-color: var(--el-accent);+ border-radius: 50%;+ animation: el-spin 0.85s linear infinite;+}+@keyframes el-spin { to { transform: rotate(360deg); } }++.el-verdict-head { margin: 0; font-weight: 650; font-size: 1.02rem; }+.el-verdict-detail { margin: 0.3rem 0 0; color: var(--el-muted); font-size: 0.93rem; }++/* ── Sections ──────────────────────────────────────────────────────────── */+.el-section { margin-top: clamp(2.25rem, 5vw, 3.5rem); }+.el-section-head { margin-bottom: 1rem; }+.el-section-head h2 { font-size: clamp(1.15rem, 2.4vw, 1.45rem); font-weight: 650; }+.el-section-sub {+ max-width: 68ch;+ margin: 0.4rem 0 0;+ color: var(--el-muted);+ font-size: 0.93rem;+}++.el-stamp {+ display: inline-block;+ margin-left: 0.4rem;+ color: var(--el-faint);+ font-variant-numeric: tabular-nums;+}++/* ── Stat grid ─────────────────────────────────────────────────────────── */+.el-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(168px, 1fr));+ gap: 0.7rem;+}++.el-stat {+ min-height: 92px;+ padding: 0.85rem 0.95rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r-sm);+ background: var(--el-surface);+}+.el-stat-label {+ display: flex;+ align-items: center;+ gap: 0.35rem;+ margin: 0;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--el-faint);+}+.el-stat-value {+ margin: 0.35rem 0 0;+ font-size: 1.32rem;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+ word-break: break-word;+}+.el-stat-sub { margin: 0.2rem 0 0; font-size: 0.8rem; color: var(--el-muted); }+.el-stat[data-tone='warn'] .el-stat-value { color: var(--el-warn); }+.el-stat[data-tone='bad'] .el-stat-value { color: var(--el-danger); }+.el-stat[data-tone='good'] .el-stat-value { color: var(--el-accent); }++.el-skeleton {+ background: linear-gradient(100deg, var(--el-surface) 30%, var(--el-surface-2) 50%, var(--el-surface) 70%);+ background-size: 220% 100%;+ animation: el-shimmer 1.4s ease-in-out infinite;+ border-color: transparent;+}+@keyframes el-shimmer { to { background-position: -120% 0; } }++.el-note {+ margin: 0.8rem 0 0;+ padding: 0.7rem 0.9rem;+ border: 1px solid var(--el-warn);+ border-radius: var(--el-r-sm);+ background: color-mix(in srgb, var(--el-warn) 9%, transparent);+ color: var(--el-ink);+ font-size: 0.89rem;+}++/* ── Lab layout ────────────────────────────────────────────────────────── */+.el-lab {+ display: grid;+ grid-template-columns: minmax(0, 340px) minmax(0, 1fr);+ gap: 1rem;+ margin-top: clamp(2.25rem, 5vw, 3.5rem);+ align-items: start;+}++@media (max-width: 900px) {+ .el-lab { grid-template-columns: minmax(0, 1fr); }+}++.el-panel {+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+ padding: 1.1rem 1.15rem 1.25rem;+}++.el-panel-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ margin-bottom: 1rem;+}+.el-panel-head h2 { font-size: 1rem; font-weight: 650; }++.el-reset {+ border: 1px solid var(--el-line-2);+ background: transparent;+ color: var(--el-muted);+ border-radius: 999px;+ padding: 0.3rem 0.75rem;+ font-size: 0.79rem;+ font-weight: 600;+ cursor: pointer;+ transition: border-color 0.16s ease, color 0.16s ease, background 0.16s ease;+}+.el-reset:hover:not(:disabled) { color: var(--el-ink); border-color: var(--el-accent); }+.el-reset:active:not(:disabled) { transform: translateY(1px); }+.el-reset:disabled { opacity: 0.4; cursor: default; }++/* ── Fields ────────────────────────────────────────────────────────────── */+.el-field { margin-bottom: 1.15rem; }+.el-field:last-child { margin-bottom: 0; }++.el-field-head {+ display: flex;+ align-items: baseline;+ gap: 0.45rem;+ margin-bottom: 0.45rem;+}+.el-field-head label {+ font-size: 0.87rem;+ font-weight: 600;+ cursor: pointer;+}+.el-value {+ margin-left: auto;+ font-size: 0.87rem;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+ color: var(--el-accent);+}+.el-field[data-dirty='true'] .el-value::after {+ content: '';+ display: inline-block;+ width: 5px;+ height: 5px;+ margin-left: 0.35rem;+ vertical-align: 0.15em;+ border-radius: 50%;+ background: var(--el-warn);+}++.el-hint {+ margin: 0.35rem 0 0;+ font-size: 0.78rem;+ color: var(--el-faint);+}++/* Range inputs: styled in both engines, with a visible focus ring. */+.el-field input[type='range'] {+ -webkit-appearance: none;+ appearance: none;+ width: 100%;+ height: 22px;+ background: transparent;+ cursor: pointer;+}+.el-field input[type='range']::-webkit-slider-runnable-track {+ height: 5px;+ border-radius: 999px;+ background: var(--el-line-2);+}+.el-field input[type='range']::-moz-range-track {+ height: 5px;+ border-radius: 999px;+ background: var(--el-line-2);+}+.el-field input[type='range']::-webkit-slider-thumb {+ -webkit-appearance: none;+ appearance: none;+ width: 17px;+ height: 17px;+ margin-top: -6px;+ border-radius: 50%;+ background: var(--el-accent);+ border: 2px solid var(--el-bg);+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.35);+ transition: transform 0.14s ease;+}+.el-field input[type='range']::-moz-range-thumb {+ width: 17px;+ height: 17px;+ border-radius: 50%;+ background: var(--el-accent);+ border: 2px solid var(--el-bg);+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.35);+ transition: transform 0.14s ease;+}+.el-field input[type='range']:hover::-webkit-slider-thumb { transform: scale(1.14); }+.el-field input[type='range']:hover::-moz-range-thumb { transform: scale(1.14); }+.el-field input[type='range']:active::-webkit-slider-thumb { transform: scale(0.95); }+.el-field input[type='range']:active::-moz-range-thumb { transform: scale(0.95); }++.el-shell :is(input, button, [tabindex]):focus-visible {+ outline: 2px solid var(--el-info);+ outline-offset: 2px;+ border-radius: 4px;+}++/* Toggle */+.el-field-toggle {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding-top: 0.4rem;+ border-top: 1px solid var(--el-line);+ margin-top: 1.25rem;+}+.el-switch {+ display: inline-flex;+ align-items: center;+ gap: 0.6rem;+ cursor: pointer;+ font-size: 0.87rem;+ font-weight: 600;+}+.el-switch input { position: absolute; opacity: 0; width: 0; height: 0; }+.el-switch-track {+ width: 38px;+ height: 21px;+ border-radius: 999px;+ background: var(--el-line-2);+ position: relative;+ transition: background 0.2s ease;+ flex: none;+}+.el-switch-thumb {+ position: absolute;+ top: 3px;+ left: 3px;+ width: 15px;+ height: 15px;+ border-radius: 50%;+ background: var(--el-bg);+ transition: transform 0.2s cubic-bezier(0.3, 1.4, 0.5, 1);+}+.el-switch input:checked + .el-switch-track { background: var(--el-accent); }+.el-switch input:checked + .el-switch-track .el-switch-thumb { transform: translateX(17px); }+.el-switch input:focus-visible + .el-switch-track {+ outline: 2px solid var(--el-info);+ outline-offset: 2px;+}++/* ── Help buttons + tooltip ────────────────────────────────────────────── */+.el-help {+ flex: none;+ width: 16px;+ height: 16px;+ padding: 0;+ display: grid;+ place-items: center;+ border-radius: 50%;+ border: 1px solid var(--el-line-2);+ background: transparent;+ color: var(--el-faint);+ font-size: 0.66rem;+ font-weight: 700;+ line-height: 1;+ cursor: help;+ transition: color 0.16s ease, border-color 0.16s ease;+}+.el-help:hover,+.el-help[aria-expanded='true'] {+ color: var(--el-accent);+ border-color: var(--el-accent);+}++.el-tip {+ position: fixed;+ z-index: 80;+ max-width: min(320px, calc(100vw - 2rem));+ padding: 0.7rem 0.85rem;+ border: 1px solid var(--el-line-2);+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2, #151823);+ color: var(--el-ink, #eef1f7);+ font-size: 0.83rem;+ line-height: 1.5;+ box-shadow: 0 12px 34px rgba(0, 0, 0, 0.4);+ opacity: 0;+ transform: translateY(4px);+ transition: opacity 0.14s ease, transform 0.14s ease;+ pointer-events: none;+}+.el-tip[data-open='true'] { opacity: 1; transform: translateY(0); }++/* ── Chart ─────────────────────────────────────────────────────────────── */+.el-panel-chart { min-width: 0; }++.el-legend { display: flex; gap: 0.85rem; font-size: 0.76rem; color: var(--el-muted); }+.el-legend-item { display: inline-flex; align-items: center; gap: 0.35rem; }+.el-legend-item::before {+ content: '';+ width: 9px;+ height: 9px;+ border-radius: 2px;+}+.el-legend-item[data-series='balance']::before { background: var(--el-info); }+.el-legend-item[data-series='admitted']::before { background: var(--el-accent); }+.el-legend-item[data-series='refused']::before { background: var(--el-danger); }++.el-chart-wrap { margin: 0; }+#el-chart {+ display: block;+ width: 100%;+ height: auto;+ aspect-ratio: 1000 / 380;+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2);+ border: 1px solid var(--el-line);+}+.el-chart-caption {+ margin: 0.6rem 0 0;+ font-size: 0.81rem;+ color: var(--el-muted);+}++.el-kpis {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(132px, 1fr));+ gap: 0.6rem;+ margin-top: 1rem;+}+.el-kpi {+ padding: 0.7rem 0.8rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2);+}+.el-kpi-label {+ margin: 0;+ font-size: 0.7rem;+ font-weight: 600;+ letter-spacing: 0.07em;+ text-transform: uppercase;+ color: var(--el-faint);+}+.el-kpi-value {+ margin: 0.25rem 0 0;+ font-size: 1.1rem;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}+.el-kpi[data-tone='good'] .el-kpi-value { color: var(--el-accent); }+.el-kpi[data-tone='warn'] .el-kpi-value { color: var(--el-warn); }+.el-kpi[data-tone='bad'] .el-kpi-value { color: var(--el-danger); }+.el-kpi-delta { margin: 0.15rem 0 0; font-size: 0.76rem; color: var(--el-muted); }++/* ── Solve ─────────────────────────────────────────────────────────────── */+.el-solve {+ display: grid;+ grid-template-columns: minmax(0, 240px) minmax(0, 1fr);+ gap: 1rem;+ align-items: start;+}+@media (max-width: 780px) {+ .el-solve { grid-template-columns: minmax(0, 1fr); }+}++.el-solve-input {+ padding: 1rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+}+.el-solve-input label {+ display: block;+ margin-bottom: 0.45rem;+ font-size: 0.83rem;+ font-weight: 600;+}+.el-solve-input input {+ width: 100%;+ padding: 0.55rem 0.7rem;+ border: 1px solid var(--el-line-2);+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2);+ color: var(--el-ink);+ font: inherit;+ font-variant-numeric: tabular-nums;+}++.el-levers {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));+ gap: 0.7rem;+}+.el-lever {+ display: flex;+ flex-direction: column;+ padding: 0.95rem 1rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+ transition: border-color 0.18s ease, transform 0.18s ease;+}+.el-lever[data-usable='true']:hover { border-color: var(--el-accent); transform: translateY(-2px); }+.el-lever[data-usable='false'] { opacity: 0.6; }+.el-lever-name {+ margin: 0;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--el-faint);+}+.el-lever-value {+ margin: 0.3rem 0 0;+ font-size: 1.25rem;+ font-weight: 650;+ font-variant-numeric: tabular-nums;+}+.el-lever-note { margin: 0.35rem 0 0.85rem; font-size: 0.82rem; color: var(--el-muted); }+.el-lever-apply {+ margin-top: auto;+ align-self: flex-start;+ border: 1px solid var(--el-line-2);+ background: transparent;+ color: var(--el-ink);+ border-radius: 999px;+ padding: 0.35rem 0.85rem;+ font-size: 0.79rem;+ font-weight: 600;+ cursor: pointer;+ transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease;+}+.el-lever-apply:hover { background: var(--el-accent); color: var(--el-accent-ink); border-color: var(--el-accent); }+.el-lever-apply:active { transform: translateY(1px); }++/* ── Apply / command ───────────────────────────────────────────────────── */+.el-apply {+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+ padding: 1rem 1.1rem;+}+.el-diff { list-style: none; margin: 0 0 0.9rem; padding: 0; display: grid; gap: 0.4rem; }+.el-diff li {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.5rem;+ font-size: 0.86rem;+ font-variant-numeric: tabular-nums;+}+.el-diff code { flex: none; }+.el-diff-from { color: var(--el-faint); text-decoration: line-through; }+.el-diff-to { color: var(--el-accent); font-weight: 650; }++.el-cmd {+ position: relative;+ margin: 0;+ padding: 0.85rem 3rem 0.85rem 0.9rem;+ border: 1px solid var(--el-line-2);+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2);+ overflow-x: auto;+ font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ font-size: 0.8rem;+ line-height: 1.65;+ white-space: pre;+}+.el-copy {+ position: absolute;+ top: 0.55rem;+ right: 0.55rem;+ border: 1px solid var(--el-line-2);+ background: var(--el-surface);+ color: var(--el-muted);+ border-radius: var(--el-r-sm);+ padding: 0.25rem 0.6rem;+ font-size: 0.74rem;+ font-weight: 600;+ cursor: pointer;+ transition: color 0.16s ease, border-color 0.16s ease;+}+.el-copy:hover { color: var(--el-accent); border-color: var(--el-accent); }+.el-copy[data-copied='true'] { color: var(--el-accent); border-color: var(--el-accent); }++.el-empty {+ margin: 0;+ color: var(--el-muted);+ font-size: 0.9rem;+}+.el-warnbox {+ margin: 0.9rem 0 0;+ padding: 0.7rem 0.85rem;+ border: 1px solid var(--el-line-2);+ border-left: 3px solid var(--el-warn);+ border-radius: var(--el-r-sm);+ background: var(--el-surface-2);+ font-size: 0.84rem;+ color: var(--el-muted);+}++/* ── Observed ──────────────────────────────────────────────────────────── */+.el-observed {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 0.7rem;+}+.el-obs-card {+ padding: 1rem 1.1rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+}+.el-obs-card h3 { font-size: 0.94rem; font-weight: 650; margin-bottom: 0.6rem; }+.el-bars { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.55rem; }+.el-bar-row { font-size: 0.84rem; }+.el-bar-head {+ display: flex;+ justify-content: space-between;+ gap: 0.6rem;+ margin-bottom: 0.25rem;+ font-variant-numeric: tabular-nums;+}+.el-bar-cause { font-weight: 600; }+.el-bar-track {+ height: 6px;+ border-radius: 999px;+ background: var(--el-surface-2);+ overflow: hidden;+}+.el-bar-fill {+ height: 100%;+ border-radius: 999px;+ background: var(--el-line-2);+ transform-origin: left center;+ animation: el-grow 0.5s cubic-bezier(0.2, 0.9, 0.3, 1) both;+}+.el-bar-row[data-cause='governor'] .el-bar-fill { background: var(--el-warn); }+.el-bar-row[data-cause='floor'] .el-bar-fill { background: var(--el-danger); }+.el-bar-row[data-cause='duplicate'] .el-bar-fill { background: var(--el-info); }+.el-bar-example {+ margin: 0.25rem 0 0;+ font-size: 0.74rem;+ color: var(--el-faint);+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ word-break: break-all;+}+@keyframes el-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }++.el-compare { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.5rem; }+.el-compare li {+ display: flex;+ justify-content: space-between;+ gap: 0.75rem;+ padding-bottom: 0.5rem;+ border-bottom: 1px solid var(--el-line);+ font-size: 0.87rem;+ font-variant-numeric: tabular-nums;+}+.el-compare li:last-child { border-bottom: 0; padding-bottom: 0; }+.el-compare dt, .el-compare span:first-child { color: var(--el-muted); }+.el-compare strong { font-weight: 650; }++/* ── Explainer ─────────────────────────────────────────────────────────── */+.el-explain-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));+ gap: 0.7rem;+}+.el-card {+ padding: 1.1rem 1.15rem;+ border: 1px solid var(--el-line);+ border-radius: var(--el-r);+ background: var(--el-surface);+}+.el-card h3 { font-size: 0.95rem; font-weight: 650; margin-bottom: 0.5rem; }+.el-card p { margin: 0; color: var(--el-muted); font-size: 0.89rem; }++.el-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.6rem; }+.el-steps li {+ display: flex;+ gap: 0.6rem;+ align-items: flex-start;+ color: var(--el-muted);+ font-size: 0.87rem;+}+.el-step-n {+ flex: none;+ width: 20px;+ height: 20px;+ display: grid;+ place-items: center;+ border-radius: 50%;+ background: var(--el-surface-2);+ border: 1px solid var(--el-line-2);+ color: var(--el-ink);+ font-size: 0.72rem;+ font-weight: 700;+}++.el-fineprint {+ margin: 1.1rem 0 0;+ color: var(--el-faint);+ font-size: 0.83rem;+ max-width: 78ch;+}++@media (prefers-reduced-motion: reduce) {+ .el-shell *,+ .el-tip {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+}diff --git a/src/economy-lab.js b/src/economy-lab.jsnew file mode 100644index 000000000..7b1290978--- /dev/null+++ b/src/economy-lab.js@@ -0,0 +1,802 @@+// src/economy-lab.js: the Runway Lab (/economy-lab).+//+// A digital twin of the x402 settle path's admission control. The page imports+// api/_lib/x402/runway-sim.js, which in turn imports the very functions the+// live facilitator calls on every settle (wallet-fee-governor.js), so the+// projection cannot drift from production the way a parallel model would.+//+// Both modules are dependency-free and reach no node: built-in, which is what+// makes this cross-boundary import legal here; scripts/check-browser-graph.mjs+// fails the build the moment that stops being true.+//+// Live state comes from GET /api/x402/runway-lab. Everything else happens in+// the browser: no writes, no wallet connection, no config is changed from this+// page. Applying a configuration is a command the operator runs themselves.++import {+ simulateRunway,+ solveForThroughput,+ equilibriumSettlesPerDay,+ envDiff,+ LAMPORTS_PER_SOL,+} from '../api/_lib/x402/runway-sim.js';++const $ = (id) => document.getElementById(id);++const KNOBS = {+ balance: { el: null, out: null, live: 0, fmt: (v) => `${fmtSol(v)} SOL` },+ floor: { el: null, out: null, live: 0, fmt: (v) => `${fmtSol(v)} SOL` },+ runway: { el: null, out: null, live: 3, fmt: (v) => `${v} day${Number(v) === 1 ? '' : 's'}` },+ heartbeat: { el: null, out: null, live: 0, fmt: (v) => `${fmtSol(v)} SOL/day` },+ demand: { el: null, out: null, live: 0, fmt: (v) => `${fmtInt(v)}/hour` },+ horizon: { el: null, out: null, live: 72, fmt: (v) => (v >= 48 ? `${Math.round(v / 24)} days` : `${v} hours`) },+};++let seed = null;+let feeLamports = 5000;++// ── Formatting ─────────────────────────────────────────────────────────────+function fmtSol(lamports, max = 4) {+ const n = Number(lamports) / LAMPORTS_PER_SOL;+ if (!Number.isFinite(n)) return '0';+ if (n === 0) return '0';+ if (n < 0.0001) return n.toExponential(2);+ return n.toLocaleString('en-US', { maximumFractionDigits: max });+}++function fmtInt(n) {+ return Number.isFinite(Number(n)) ? Math.round(Number(n)).toLocaleString('en-US') : '0';+}++function fmtPct(n, digits = 1) {+ return Number.isFinite(Number(n)) ? `${(Number(n) * 100).toFixed(digits)}%` : 'not read';+}++// A projection hour turned into a human clock reading, anchored on the UTC hour+// the seed was taken. "in 14h (03:00 UTC)" is actionable in a way that "hour+// 14" is not.+function fmtWhen(hour) {+ if (hour === null || hour === undefined) return 'not reached';+ const utc = ((seed?.meter?.utc_hour ?? 0) + hour) % 24;+ const clock = `${String(utc).padStart(2, '0')}:00 UTC`;+ if (hour === 0) return `immediately (${clock})`;+ if (hour < 48) return `in ${hour}h (${clock})`;+ return `in ${Math.floor(hour / 24)}d ${hour % 24}h (${clock})`;+}++function shortAddr(a) {+ return a && a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || 'not configured';+}++// ── Accessible tooltips ────────────────────────────────────────────────────+// Hover, focus, and touch all open; Escape and blur close. The tip is a single+// fixed node repositioned per trigger so it can never be clipped by a panel's+// overflow, and it is flipped above the trigger when it would leave the+// viewport.+function initTooltips() {+ const tip = $('el-tip');+ if (!tip) return;+ let current = null;++ const close = () => {+ if (!current) return;+ current.setAttribute('aria-expanded', 'false');+ current.removeAttribute('aria-describedby');+ current = null;+ tip.dataset.open = 'false';+ tip.hidden = true;+ };++ const open = (btn) => {+ const text = btn.dataset.tip;+ if (!text) return;+ current = btn;+ 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');++ const r = btn.getBoundingClientRect();+ const t = tip.getBoundingClientRect();+ let left = r.left + r.width / 2 - t.width / 2;+ left = Math.max(12, Math.min(left, window.innerWidth - t.width - 12));+ let top = r.bottom + 9;+ if (top + t.height > window.innerHeight - 12) top = r.top - t.height - 9;+ tip.style.left = `${Math.round(left)}px`;+ tip.style.top = `${Math.round(Math.max(12, top))}px`;+ };++ for (const btn of document.querySelectorAll('.el-help')) {+ btn.setAttribute('aria-expanded', 'false');+ btn.addEventListener('mouseenter', () => open(btn));+ btn.addEventListener('mouseleave', close);+ btn.addEventListener('focus', () => open(btn));+ btn.addEventListener('blur', close);+ btn.addEventListener('click', (e) => {+ e.preventDefault();+ if (current === btn) close();+ else open(btn);+ });+ }+ // Capture phase: site-wide scripts (nav, command palette) also listen for+ // Escape and some stop propagation, which would leave a tooltip stuck open+ // for keyboard users with no way to dismiss it.+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); }, true);+ window.addEventListener('scroll', close, { passive: true });+ window.addEventListener('resize', close);+}++// ── Seed ───────────────────────────────────────────────────────────────────+async function loadSeed() {+ const res = await fetch('/api/x402/runway-lab', { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`seed request failed: ${res.status}`);+ const data = await res.json();+ if (!data?.ok) throw new Error('seed request returned an error payload');+ return data;+}++function applySeedToKnobs() {+ const cfg = seed.config;+ const bal = seed.fee_wallet.sol_lamports;+ feeLamports = seed.observed?.fee_lamports_observed || 5000;++ KNOBS.balance.live = bal ?? cfg.floor_lamports;+ KNOBS.floor.live = cfg.floor_lamports;+ KNOBS.runway.live = cfg.runway_days;+ KNOBS.heartbeat.live = cfg.min_budget_lamports;+ KNOBS.demand.live = Math.max(1, seed.observed?.demand_per_hour ?? 60);+ KNOBS.horizon.live = 72;++ // Ranges are derived from the live values so every knob has useful travel on+ // both sides of where production actually sits, rather than a fixed scale+ // that pins the handle at one end.+ //+ // The lamport knobs use step="1". A coarser step would silently round the+ // live balance to the nearest slider notch, and on a wallet holding 0.023 SOL+ // a 0.001 SOL notch is a 5% error in the seed. Keyboard usability is restored+ // by lamportKeySteps() below rather than by giving up precision.+ setRange(KNOBS.balance.el, 0, Math.max(2 * LAMPORTS_PER_SOL, KNOBS.balance.live * 4), 1);+ setRange(KNOBS.floor.el, 0, Math.max(200_000_000, KNOBS.floor.live * 4), 1);+ setRange(KNOBS.heartbeat.el, 0, Math.max(200_000_000, KNOBS.heartbeat.live * 8), 1);+ setRange(KNOBS.demand.el, 0, Math.max(3000, KNOBS.demand.live * 6), 5);++ $('el-governor').checked = cfg.governor_enabled;+ for (const key of Object.keys(KNOBS)) KNOBS[key].el.value = String(KNOBS[key].live);+ // The input clamps and snaps on assignment, so the resolved value is the real+ // baseline. Comparing against the requested value instead would leave every+ // knob permanently "dirty" and the reset button permanently enabled.+ for (const key of Object.keys(KNOBS)) KNOBS[key].live = Number(KNOBS[key].el.value);+}++function setRange(el, min, max, step) {+ el.min = String(min);+ el.max = String(Math.ceil(max));+ el.step = String(step);+}++// A step of 1 lamport makes arrow keys useless on a range spanning billions.+// Give the lamport sliders a keyboard grammar sized to the money: 0.001 SOL per+// arrow press, 0.05 SOL per page, and the ends for Home/End.+function lamportKeySteps(el) {+ el.addEventListener('keydown', (e) => {+ const jump = { ArrowLeft: -1, ArrowDown: -1, ArrowRight: 1, ArrowUp: 1, PageDown: -50, PageUp: 50 }[e.key];+ if (jump === undefined) return;+ e.preventDefault();+ const next = Number(el.value) + jump * 1_000_000;+ el.value = String(Math.min(Number(el.max), Math.max(Number(el.min), next)));+ el.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++function readKnobs() {+ return {+ startLamports: Number(KNOBS.balance.el.value),+ floorLamports: Number(KNOBS.floor.el.value),+ runwayDays: Number(KNOBS.runway.el.value),+ minBudgetLamports: Number(KNOBS.heartbeat.el.value),+ demandPerHour: Number(KNOBS.demand.el.value),+ hours: Number(KNOBS.horizon.el.value),+ governorEnabled: $('el-governor').checked,+ };+}++function isDirty() {+ if ($('el-governor').checked !== seed.config.governor_enabled) return true;+ return Object.keys(KNOBS).some((k) => Number(KNOBS[k].el.value) !== Number(KNOBS[k].live));+}++// ── Live state panel ───────────────────────────────────────────────────────+function renderLiveState() {+ const w = seed.fee_wallet;+ const cfg = seed.config;+ const o = seed.observed;+ const spendable = w.spendable_lamports;+ const spent = seed.meter?.spent_today_lamports;++ const budgetNow = spendable === null+ ? null+ : Math.max(cfg.governor_enabled ? cfg.min_budget_lamports : 0, Math.floor(spendable / cfg.runway_days));+ const headroom = budgetNow === null || spent === null ? null : budgetNow - spent;++ const cards = [+ {+ label: 'Fee wallet',+ value: shortAddr(w.address),+ sub: w.role ? `${w.role} role` : 'unresolved',+ },+ {+ label: 'Balance',+ value: w.balance_read ? `${fmtSol(w.sol_lamports)} SOL` : 'not read',+ sub: w.balance_read ? `floor ${fmtSol(cfg.floor_lamports)} SOL` : 'RPC unavailable',+ tone: !w.balance_read ? '' : w.sol_lamports < cfg.floor_lamports ? 'bad' : 'good',+ },+ {+ label: 'Spendable',+ value: spendable === null ? 'not read' : `${fmtSol(spendable)} SOL`,+ sub: 'balance above the hard floor',+ tone: spendable === null ? '' : spendable <= 0 ? 'bad' : spendable < cfg.min_budget_lamports ? 'warn' : 'good',+ },+ {+ label: 'Today’s headroom',+ value: headroom === null ? 'not read' : `${fmtSol(headroom)} SOL`,+ sub: spent === null ? 'ledger unread' : `${fmtSol(spent)} spent of ${fmtSol(budgetNow)} budget`,+ tone: headroom === null ? '' : headroom <= 0 ? 'bad' : headroom < budgetNow * 0.2 ? 'warn' : 'good',+ },+ {+ label: 'Settles / day',+ value: seed.projected_settles_per_day === null ? 'not read' : fmtInt(seed.projected_settles_per_day),+ sub: 'at this balance and config',+ tone: seed.projected_settles_per_day === null ? '' : seed.projected_settles_per_day < 1000 ? 'warn' : 'good',+ },+ {+ label: 'Admitted (24h)',+ value: o ? fmtPct(o.capacity_admission_rate) : 'not read',+ sub: o ? `${fmtInt(o.settled)} settled, ${fmtInt(o.capacity_refused)} could not be afforded` : 'ledger unread',+ tone: !o || o.capacity_admission_rate === null ? '' : o.capacity_admission_rate > 0.9 ? 'good' : o.capacity_admission_rate > 0.5 ? 'warn' : 'bad',+ },+ ];++ $('el-stats').innerHTML = cards.map((c) => `+ <div class="el-stat"${c.tone ? ` data-tone="${c.tone}"` : ''}>+ <p class="el-stat-label">${esc(c.label)}</p>+ <p class="el-stat-value">${esc(c.value)}</p>+ <p class="el-stat-sub">${esc(c.sub)}</p>+ </div>`).join('');++ $('el-stamp').textContent = `Read ${new Date(seed.generated_at).toLocaleTimeString()}`;++ const notes = [];+ if (!w.balance_read) notes.push('The fee wallet balance could not be read from Solana RPC, so the projection is seeded from the configured floor. Nothing here should be read as a starvation signal.');+ if (seed.db_error) notes.push('The facilitator ledger could not be read, so observed demand, fee size, and refusal causes are unavailable. The knobs still work against the live balance and config.');+ if (!seed.self_facilitator_enabled) notes.push('The self-hosted facilitator is disabled on this deploy, so settlement routes externally and this governor is not in the path.');+ const note = $('el-live-note');+ note.hidden = notes.length === 0;+ note.textContent = notes.join(' ');+}++// ── Verdict ────────────────────────────────────────────────────────────────+function renderVerdict(summary) {+ const box = $('el-verdict');+ const icon = box.querySelector('.el-verdict-icon');+ const dirty = isDirty();+ const scope = dirty ? 'With your changes' : 'As configured right now';++ const limiterText = {+ floor: 'the hard SOL floor is refusing settles: the wallet has nothing spendable left, and no config change moves this. Only funding does.',+ governor: 'the wallet fee governor is pacing the rail: there is SOL above the floor, but the daily fee budget is spent.',+ demand: 'nothing in the rail is holding it back. Every attempt lands, so throughput is set by how much demand arrives.',+ none: 'no settles were attempted over this horizon, so there is nothing to admit or refuse.',+ }[summary.limiter];++ const state = summary.verdict;+ box.dataset.state = state;+ icon.textContent = state === 'healthy' ? '✓' : state === 'throttled' ? '!' : '×';++ const head = {+ healthy: `${scope}, settlement is healthy`,+ throttled: `${scope}, settlement is throttled`,+ starved: `${scope}, settlement is starved`,+ }[state];++ $('el-verdict-head').textContent = head;+ $('el-verdict-detail').textContent =+ `${fmtInt(summary.admitted)} of ${fmtInt(summary.demanded)} settles land over the next ${fmtWhenSpan(summary.hoursSimulated)}: ${limiterText}` ++ (summary.firstRefusalHour !== null ? ` First refusal ${fmtWhen(summary.firstRefusalHour)}.` : '');+}++function fmtWhenSpan(hours) {+ return hours >= 48 ? `${Math.round(hours / 24)} days` : `${hours} hours`;+}++// ── KPIs ───────────────────────────────────────────────────────────────────+function renderKpis(summary, knobs) {+ const liveProjection = seed.projected_settles_per_day;+ const steady = summary.steadySettlesPerDay;+ const delta = liveProjection ? steady - liveProjection : null;++ const kpis = [+ {+ label: 'Settles / day',+ value: fmtInt(steady),+ tone: steady <= 0 ? 'bad' : steady < 1000 ? 'warn' : 'good',+ delta: delta === null ? 'steady state' : delta === 0 ? 'same as live' : `${delta > 0 ? '+' : ''}${fmtInt(delta)} vs live`,+ },+ {+ label: 'Admission rate',+ value: fmtPct(summary.admissionRate, 0),+ tone: summary.admissionRate > 0.9 ? 'good' : summary.admissionRate > 0.5 ? 'warn' : 'bad',+ delta: `${fmtInt(summary.refused)} refused`,+ },+ {+ label: 'First refusal',+ value: summary.firstRefusalHour === null ? 'never' : fmtWhen(summary.firstRefusalHour).replace(/ \(.*\)/, ''),+ tone: summary.firstRefusalHour === null ? 'good' : summary.firstRefusalHour < 6 ? 'bad' : 'warn',+ delta: summary.firstRefusalHour === null ? 'holds the whole horizon' : 'throughput breaks here',+ },+ {+ label: 'Hits the floor',+ value: summary.floorBreachHour === null ? 'never' : fmtWhen(summary.floorBreachHour).replace(/ \(.*\)/, ''),+ tone: summary.floorBreachHour === null ? 'good' : 'bad',+ delta: summary.floorBreachHour === null ? 'stays above the floor' : 'funding required',+ },+ {+ label: 'SOL burned',+ value: `${fmtSol(summary.feesBurnedLamports)} SOL`,+ delta: `at ${fmtInt(feeLamports)} lamports/settle`,+ },+ {+ label: 'Ending balance',+ value: `${fmtSol(summary.endLamports)} SOL`,+ tone: summary.endLamports < knobs.floorLamports ? 'bad' : 'good',+ delta: `from ${fmtSol(summary.startLamports)} SOL`,+ },+ ];++ $('el-kpis').innerHTML = kpis.map((k) => `+ <div class="el-kpi"${k.tone ? ` data-tone="${k.tone}"` : ''}>+ <p class="el-kpi-label">${esc(k.label)}</p>+ <p class="el-kpi-value">${esc(k.value)}</p>+ <p class="el-kpi-delta">${esc(k.delta)}</p>+ </div>`).join('');+}++// ── Chart ──────────────────────────────────────────────────────────────────+// Balance as a filled area against the left axis, hourly admitted and refused+// counts as stacked columns against the right, the hard floor as a dashed rule,+// and a tick per UTC midnight so the governor's daily reset is visible as the+// structural feature it is.+function drawChart(series, knobs) {+ const canvas = $('el-chart');+ const dpr = Math.min(2, window.devicePixelRatio || 1);+ const cssW = canvas.clientWidth || 1000;+ const cssH = Math.round((cssW * 380) / 1000);+ canvas.width = Math.round(cssW * dpr);+ canvas.height = Math.round(cssH * dpr);+ const ctx = canvas.getContext('2d');+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, cssW, cssH);++ const css = getComputedStyle(document.querySelector('.el-shell'));+ const col = (name, fallback) => (css.getPropertyValue(name) || fallback).trim();+ const line = col('--el-line', '#232735');+ const faint = col('--el-faint', '#6a7183');+ const accent = col('--el-accent', '#6ee7b7');+ const danger = col('--el-danger', '#fb7185');+ const info = col('--el-info', '#7dd3fc');++ const padL = 58;+ const padR = 52;+ const padT = 16;+ const padB = 28;+ const w = cssW - padL - padR;+ const h = cssH - padT - padB;+ if (w <= 0 || h <= 0 || !series.length) return;++ const maxBal = Math.max(knobs.floorLamports * 1.15, ...series.map((s) => s.lamports), 1);+ const maxCount = Math.max(1, ...series.map((s) => s.admitted + s.refusedFloor + s.refusedGovernor));+ const x = (i) => padL + (series.length === 1 ? w / 2 : (i / (series.length - 1)) * w);+ const yBal = (v) => padT + h - (v / maxBal) * h;+ const yCount = (v) => padT + h - (v / maxCount) * h;++ // Grid+ ctx.strokeStyle = line;+ ctx.lineWidth = 1;+ ctx.font = '11px ui-sans-serif, system-ui, sans-serif';+ ctx.fillStyle = faint;+ for (let g = 0; g <= 4; g++) {+ const yy = padT + (h / 4) * g;+ ctx.beginPath();+ ctx.moveTo(padL, yy);+ ctx.lineTo(padL + w, yy);+ ctx.stroke();+ ctx.textAlign = 'right';+ ctx.fillText(`${fmtSol(maxBal * (1 - g / 4), 3)}`, padL - 8, yy + 4);+ ctx.textAlign = 'left';+ ctx.fillText(fmtInt(maxCount * (1 - g / 4)), padL + w + 8, yy + 4);+ }++ // UTC midnight markers+ const startHour = seed?.meter?.utc_hour ?? 0;+ ctx.save();+ ctx.setLineDash([2, 4]);+ ctx.strokeStyle = faint;+ for (let i = 0; i < series.length; i++) {+ if ((startHour + i) % 24 !== 0 || i === 0) continue;+ ctx.beginPath();+ ctx.moveTo(x(i), padT);+ ctx.lineTo(x(i), padT + h);+ ctx.stroke();+ ctx.fillStyle = faint;+ ctx.textAlign = 'center';+ ctx.fillText('00 UTC', x(i), padT + 10);+ }+ ctx.restore();++ // Hourly outcome columns+ const barW = Math.max(1, Math.min(14, w / series.length - 1));+ for (let i = 0; i < series.length; i++) {+ const s = series[i];+ const refused = s.refusedFloor + s.refusedGovernor;+ const bx = x(i) - barW / 2;+ if (s.admitted > 0) {+ ctx.fillStyle = accent;+ const bh = padT + h - yCount(s.admitted);+ ctx.fillRect(bx, yCount(s.admitted), barW, bh);+ }+ if (refused > 0) {+ ctx.fillStyle = danger;+ const top = yCount(s.admitted + refused);+ const bh = yCount(s.admitted) - top;+ ctx.fillRect(bx, top, barW, Math.max(1, bh));+ }+ }++ // Hard floor rule+ ctx.save();+ ctx.setLineDash([5, 4]);+ ctx.strokeStyle = danger;+ ctx.lineWidth = 1.25;+ ctx.beginPath();+ ctx.moveTo(padL, yBal(knobs.floorLamports));+ ctx.lineTo(padL + w, yBal(knobs.floorLamports));+ ctx.stroke();+ ctx.restore();+ ctx.fillStyle = danger;+ ctx.textAlign = 'left';+ ctx.fillText('hard floor', padL + 4, yBal(knobs.floorLamports) - 5);++ // Balance area + line+ ctx.beginPath();+ ctx.moveTo(x(0), padT + h);+ for (let i = 0; i < series.length; i++) ctx.lineTo(x(i), yBal(series[i].lamports));+ ctx.lineTo(x(series.length - 1), padT + h);+ ctx.closePath();+ const grad = ctx.createLinearGradient(0, padT, 0, padT + h);+ grad.addColorStop(0, hexWithAlpha(info, 0.28));+ grad.addColorStop(1, hexWithAlpha(info, 0));+ ctx.fillStyle = grad;+ ctx.fill();++ ctx.beginPath();+ for (let i = 0; i < series.length; i++) {+ const px = x(i);+ const py = yBal(series[i].lamports);+ if (i === 0) ctx.moveTo(px, py);+ else ctx.lineTo(px, py);+ }+ ctx.strokeStyle = info;+ ctx.lineWidth = 2;+ ctx.stroke();++ // Axis labels+ ctx.fillStyle = faint;+ ctx.textAlign = 'left';+ ctx.fillText('SOL', 6, padT + 10);+ ctx.textAlign = 'right';+ ctx.fillText('settles/h', cssW - 6, padT + 10);+}++function hexWithAlpha(color, alpha) {+ const c = color.trim();+ if (/^#([0-9a-f]{6})$/i.test(c)) {+ const n = parseInt(c.slice(1), 16);+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;+ }+ return c;+}++// ── Solve panel ────────────────────────────────────────────────────────────+function renderLevers() {+ const knobs = readKnobs();+ const target = Math.max(0, Number($('el-target').value) || 0);+ const s = solveForThroughput({+ targetSettlesPerDay: target,+ startLamports: knobs.startLamports,+ floorLamports: knobs.floorLamports,+ runwayDays: knobs.runwayDays,+ minBudgetLamports: knobs.minBudgetLamports,+ feeLamports,+ });++ // A lever is only real if the wallet can actually fund the target down to its+ // floor. Widening the governor on a wallet with nothing spendable changes+ // nothing, and saying so is the point of this panel.+ const spendable = Math.max(0, knobs.startLamports - knobs.floorLamports);+ const fundable = spendable / feeLamports >= target;++ const levers = [+ {+ key: 'fund',+ name: 'Fund the wallet',+ value: s.alreadyMet ? 'not needed' : s.fund ? `+${fmtSol(s.fund.lamports)} SOL` : 'not needed',+ note: s.alreadyMet+ ? 'The current configuration already reaches this target.'+ : `Deposit to reach ${fmtInt(target)} settles/day while keeping the ${knobs.runwayDays}-day runway.`,+ usable: !s.alreadyMet && !!s.fund,+ apply: s.fund ? () => setKnob('balance', knobs.startLamports + s.fund.lamports) : null,+ },+ {+ key: 'runway',+ name: 'Shorten the runway',+ value: s.alreadyMet ? 'not needed' : s.runwayDays ? `${s.runwayDays} days` : 'cannot work',+ note: s.alreadyMet+ ? 'The current configuration already reaches this target.'+ : s.runwayDays+ ? 'Spends the same SOL faster. Reaches the target today at the cost of tomorrow.'+ : 'There is not enough spendable SOL to reach this target at any runway setting.',+ usable: !s.alreadyMet && !!s.runwayDays,+ apply: s.runwayDays ? () => setKnob('runway', s.runwayDays) : null,+ },+ {+ key: 'heartbeat',+ name: 'Raise the heartbeat',+ value: s.alreadyMet ? 'not needed' : `${fmtSol(s.minBudget.lamports)} SOL/day`,+ note: s.alreadyMet+ ? 'The current configuration already reaches this target.'+ : fundable+ ? 'Independent of the balance, so it works even on a nearly empty wallet.'+ : 'Raising this alone will not help: the wallet does not hold enough spendable SOL, so the hard floor refuses first.',+ usable: !s.alreadyMet && fundable,+ apply: () => setKnob('heartbeat', s.minBudget.lamports),+ },+ ];++ const host = $('el-levers');+ host.innerHTML = levers.map((l) => `+ <div class="el-lever" data-usable="${l.usable}">+ <p class="el-lever-name">${esc(l.name)}</p>+ <p class="el-lever-value">${esc(l.value)}</p>+ <p class="el-lever-note">${esc(l.note)}</p>+ ${l.usable ? `<button type="button" class="el-lever-apply" data-lever="${l.key}">Try it</button>` : ''}+ </div>`).join('');++ for (const btn of host.querySelectorAll('.el-lever-apply')) {+ const lever = levers.find((l) => l.key === btn.dataset.lever);+ if (lever?.apply) btn.addEventListener('click', () => { lever.apply(); render(); });+ }+}++function setKnob(key, value) {+ const k = KNOBS[key];+ const max = Number(k.el.max);+ if (value > max) setRange(k.el, Number(k.el.min), value * 1.2, Number(k.el.step));+ k.el.value = String(value);+}++// ── Apply panel ────────────────────────────────────────────────────────────+function renderApply() {+ const knobs = readKnobs();+ const changes = envDiff(+ {+ runwayDays: seed.config.runway_days,+ minBudgetLamports: seed.config.min_budget_lamports,+ floorLamports: seed.config.floor_lamports,+ governorEnabled: seed.config.governor_enabled,+ },+ {+ runwayDays: knobs.runwayDays,+ minBudgetLamports: knobs.minBudgetLamports,+ floorLamports: knobs.floorLamports,+ governorEnabled: knobs.governorEnabled,+ },+ );++ const host = $('el-apply');+ const balanceChanged = knobs.startLamports !== KNOBS.balance.live;+ const fundingNote = balanceChanged+ ? `<p class="el-warnbox">This projection also assumes a fee wallet balance of ${esc(fmtSol(knobs.startLamports))} SOL (live is ${esc(fmtSol(KNOBS.balance.live))} SOL). Moving funds is not something this page does or should do: it is a signed transfer an operator makes deliberately.</p>`+ : '';++ if (!changes.length) {+ host.innerHTML = `<p class="el-empty">No configuration change. Every knob matches what this deploy is running.</p>${fundingNote}`;+ return;+ }++ const cmd = [+ 'gcloud run services update three-ws-api \\',+ ' --region us-central1 --project aerial-vehicle-466722-p5 \\',+ ` --update-env-vars ${changes.map((c) => `${c.env}=${c.to}`).join(',')}`,+ ].join('\n');++ host.innerHTML = `+ <ul class="el-diff">+ ${changes.map((c) => `+ <li>+ <code>${esc(c.env)}</code>+ <span class="el-diff-from">${esc(c.from)}</span>+ <span aria-hidden="true">→</span>+ <span class="el-diff-to">${esc(c.to)}</span>+ </li>`).join('')}+ </ul>+ <div style="position:relative">+ <pre class="el-cmd"><code>${esc(cmd)}</code></pre>+ <button type="button" class="el-copy" id="el-copy">Copy</button>+ </div>+ <p class="el-warnbox">+ <code>--update-env-vars</code> merges into the existing environment.+ <code>--set-env-vars</code> would replace the whole set and drop every+ other variable on the service.+ </p>+ ${fundingNote}`;++ $('el-copy').addEventListener('click', async (e) => {+ const btn = e.currentTarget;+ try {+ await navigator.clipboard.writeText(cmd);+ btn.dataset.copied = 'true';+ btn.textContent = 'Copied';+ } catch {+ // Clipboard blocked (insecure context or denied permission): select the+ // command so the keyboard shortcut still works.+ const range = document.createRange();+ range.selectNodeContents(host.querySelector('.el-cmd code'));+ const sel = window.getSelection();+ sel.removeAllRanges();+ sel.addRange(range);+ btn.textContent = 'Selected';+ }+ setTimeout(() => { btn.dataset.copied = 'false'; btn.textContent = 'Copy'; }, 2200);+ });+}++// ── Observed panel ─────────────────────────────────────────────────────────+function renderObserved(summary) {+ const o = seed.observed;+ const host = $('el-observed');+ if (!o) {+ host.innerHTML = '<div class="el-obs-card"><p class="el-empty">The facilitator ledger could not be read, so there are no observed outcomes to compare against.</p></div>';+ return;+ }++ const total = Math.max(1, ...o.refusals.map((r) => r.count));+ const causeLabel = {+ governor: 'Out of daily fee budget',+ floor: 'Fee wallet under its floor',+ duplicate: 'Already settled (retry)',+ dust_guard: 'Below the minimum settle',+ unspecified: 'No reason recorded',+ other: 'Other',+ };++ const liveEquilibrium = seed.projected_settles_per_day;++ host.innerHTML = `+ <div class="el-obs-card">+ <h3>Refusals, last ${o.window_hours}h</h3>+ ${o.refusals.length === 0+ ? '<p class="el-empty">Nothing was refused in this window.</p>'+ : `<ul class="el-bars">${o.refusals.map((r) => `+ <li class="el-bar-row" data-cause="${esc(r.cause)}">+ <div class="el-bar-head">+ <span class="el-bar-cause">${esc(causeLabel[r.cause] || r.cause)}</span>+ <span>${fmtInt(r.count)}</span>+ </div>+ <div class="el-bar-track"><div class="el-bar-fill" style="width:${((r.count / total) * 100).toFixed(1)}%"></div></div>+ ${r.example ? `<p class="el-bar-example">${esc(r.example)}</p>` : ''}+ </li>`).join('')}</ul>`}+ </div>+ <div class="el-obs-card">+ <h3>Measured against modelled</h3>+ <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>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>+ <li><span>SOL burned (24h)</span><strong>${fmtSol(o.fee_total_lamports)} SOL</strong></li>+ </ul>+ </div>`;+}++// ── Render ─────────────────────────────────────────────────────────────────+let rafId = 0;+function render() {+ cancelAnimationFrame(rafId);+ rafId = requestAnimationFrame(() => {+ const knobs = readKnobs();+ const { series, summary } = simulateRunway({+ ...knobs,+ feeLamports,+ spentTodayLamports: seed.meter?.spent_today_lamports ?? 0,+ startHourOfDay: seed.meter?.utc_hour ?? 0,+ });++ for (const key of Object.keys(KNOBS)) {+ const k = KNOBS[key];+ k.out.value = k.fmt(Number(k.el.value));+ k.el.closest('.el-field').dataset.dirty = String(Number(k.el.value) !== Number(k.live));+ }+ $('el-reset').disabled = !isDirty();++ renderVerdict(summary);+ renderKpis(summary, knobs);+ drawChart(series, knobs);+ renderLevers();+ renderApply();+ renderObserved(summary);++ const eq = equilibriumSettlesPerDay({+ spendableLamports: Math.max(0, knobs.startLamports - knobs.floorLamports),+ feeLamports,+ runwayDays: knobs.runwayDays,+ minBudgetLamports: knobs.governorEnabled ? knobs.minBudgetLamports : Number.MAX_SAFE_INTEGER,+ });+ $('el-chart-caption').textContent =+ `Balance (line, left axis) against hourly settles admitted and refused (columns, right axis) over ${fmtWhenSpan(summary.hoursSimulated)}. ` ++ `This configuration sustains ${fmtInt(eq)} settles per day.` ++ (summary.truncated ? ' The horizon was truncated to keep the projection responsive.' : '');+ });+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}++// ── Boot ───────────────────────────────────────────────────────────────────+function fail(message) {+ const box = $('el-verdict');+ box.dataset.state = 'error';+ box.querySelector('.el-verdict-icon').textContent = '×';+ $('el-verdict-head').textContent = 'Could not read the live rail';+ $('el-verdict-detail').textContent =+ `${message} The lab needs live state to be honest, so it will not fall back to invented numbers. Retry, or read the raw seed at /api/x402/runway-lab.`;+ $('el-stats').innerHTML = '';+}++async function boot() {+ for (const key of Object.keys(KNOBS)) {+ KNOBS[key].el = $(`el-${key}`);+ KNOBS[key].out = $(`el-${key}-out`);+ }+ initTooltips();++ try {+ seed = await loadSeed();+ } catch (err) {+ fail(err?.message ? `${err.message}.` : 'The seed request failed.');+ return;+ }++ applySeedToKnobs();+ renderLiveState();++ for (const key of Object.keys(KNOBS)) KNOBS[key].el.addEventListener('input', render);+ $('el-governor').addEventListener('change', render);+ $('el-target').addEventListener('input', () => { renderLevers(); });+ $('el-reset').addEventListener('click', () => {+ for (const key of Object.keys(KNOBS)) KNOBS[key].el.value = String(KNOBS[key].live);+ $('el-governor').checked = seed.config.governor_enabled;+ render();+ });+ window.addEventListener('resize', () => render(), { passive: true });++ render();+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);+else boot();diff --git a/src/flow-map.css b/src/flow-map.cssindex a7f2c4d1b..e1b5d05f9 100644--- a/src/flow-map.css+++ b/src/flow-map.css@@ -249,6 +249,20 @@ body {font-variant-numeric: tabular-nums;}+/* Label text that only assistive tech needs. Defined here because the shared+ stylesheets do not ship a screen-reader utility class. */+.fm-wrap .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ overflow: hidden;+ clip-path: inset(50%);+ white-space: nowrap;+ border: 0;+}+/* Focus rings, once, for every interactive thing on the page. */.fm-wrap :is(button, input, a, [tabindex]):focus-visible {outline: 2px solid var(--fm-accent);diff --git a/src/play-solver.css b/src/play-solver.cssnew file mode 100644index 000000000..e7221c230--- /dev/null+++ b/src/play-solver.css@@ -0,0 +1,925 @@+/* The economy solver (/play/solver). Self-contained (ps- prefix), driven by the+ shared theme tokens so it tracks light and dark without a second palette.++ Palette intent: the sibling /play/economy page is gold and jade, because it is+ about money and the chain. This page is about ANALYSIS, so it reads cyan and+ indigo, and its per-activity hues (wood green, stone grey, water blue, fire+ orange, and violet for the composite loop) are chosen to stay distinguishable+ both from each other and against either background. Those five are also the+ chart legend, so they are declared once here and read back by name. */++.ps-shell {+ --ps-accent: #45cfe0;+ --ps-accent-2: #7f8cf5;+ --ps-grad: linear-gradient(135deg, var(--ps-accent) 0%, var(--ps-accent-2) 100%);++ --ps-chop: #57b87c;+ --ps-mine: #8f9ab4;+ --ps-fish: #43a5ea;+ --ps-cook: #e8944a;+ --ps-loop: #a97bf0;++ --ps-good: #57b87c;+ --ps-warn: #e8a33f;++ position: relative;+ max-width: 1180px;+ margin: 0 auto;+ padding: clamp(20px, 5vw, 56px) clamp(16px, 4vw, 32px) 96px;+ font-family: var(--font-body, system-ui, sans-serif);+ color: var(--ink, #d8d8d8);+}++.ps-glow {+ position: absolute;+ inset: -10% auto auto auto;+ left: max(-20%, calc((100% - 100vw) / 2 + 12px));+ right: max(-20%, calc((100% - 100vw) / 2 + 12px));+ height: 380px;+ mask-image: linear-gradient(to right, transparent, #000 32px, #000 calc(100% - 32px), transparent);+ -webkit-mask-image: linear-gradient(+ to right,+ transparent,+ #000 32px,+ #000 calc(100% - 32px),+ transparent+ );+ background:+ radial-gradient(+ 60% 80% at 18% 0%,+ color-mix(in srgb, var(--ps-accent) 14%, transparent),+ transparent 70%+ ),+ radial-gradient(+ 52% 72% at 82% 6%,+ color-mix(in srgb, var(--ps-accent-2) 15%, transparent),+ transparent 70%+ );+ filter: blur(20px);+ pointer-events: none;+ z-index: 0;+ opacity: 0.85;+}+.ps-shell > *:not(.ps-glow) {+ position: relative;+ z-index: 1;+}++/* --- hero ---------------------------------------------------------------- */++.ps-hero {+ max-width: 78ch;+ margin-bottom: clamp(28px, 5vw, 48px);+}+.ps-kicker {+ margin: 0 0 var(--space-sm, 10px);+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--ps-accent);+}+.ps-title {+ margin: 0 0 var(--space-md, 16px);+ font-size: clamp(2rem, 6vw, 3.4rem);+ line-height: 1.05;+ letter-spacing: -0.02em;+ font-weight: var(--weight-bold, 700);+ color: var(--ink-bright, #fff);+}+.ps-title em {+ font-style: normal;+ background: var(--ps-grad);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+}+.ps-sub {+ margin: 0 0 var(--space-md, 16px);+ font-size: var(--text-base, 1rem);+ line-height: 1.65;+ color: var(--ink-dim, #9aa1ad);+}+.ps-hero-actions {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-sm, 10px);+ margin-top: var(--space-lg, 26px);+}++.ps-btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 10px 18px;+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ color: var(--ink, #d8d8d8);+ font-size: var(--text-ui, 0.875rem);+ font-weight: var(--weight-medium, 500);+ text-decoration: none;+ cursor: pointer;+ transition:+ background 0.16s ease,+ border-color 0.16s ease,+ transform 0.16s ease;+}+.ps-btn:hover {+ background: var(--surface-3, rgba(255, 255, 255, 0.08));+ border-color: color-mix(in srgb, var(--ps-accent) 45%, transparent);+ transform: translateY(-1px);+}+.ps-btn:active {+ transform: translateY(0);+}+.ps-btn:focus-visible {+ outline: 2px solid var(--ps-accent);+ outline-offset: 2px;+}+.ps-btn-primary {+ background: var(--ps-grad);+ border-color: transparent;+ color: #06131a;+ font-weight: var(--weight-semibold, 600);+}+.ps-btn-primary:hover {+ background: var(--ps-grad);+ filter: brightness(1.08);+}++/* --- the level control --------------------------------------------------- */++.ps-control {+ padding: clamp(16px, 3vw, 24px);+ margin-bottom: clamp(20px, 3vw, 32px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ backdrop-filter: blur(8px);+}+.ps-control-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-md, 16px);+ margin-bottom: var(--space-sm, 10px);+}+.ps-control-label {+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-faint, #6e7583);+}+.ps-readout {+ font-size: clamp(1.8rem, 5vw, 2.6rem);+ font-weight: var(--weight-bold, 700);+ line-height: 1;+ font-variant-numeric: tabular-nums;+ background: var(--ps-grad);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+}++.ps-slider {+ -webkit-appearance: none;+ appearance: none;+ width: 100%;+ height: 26px;+ background: transparent;+ cursor: pointer;+ touch-action: pan-y;+}+.ps-slider::-webkit-slider-runnable-track {+ height: 6px;+ border-radius: var(--radius-pill, 999px);+ background: linear-gradient(+ 90deg,+ color-mix(in srgb, var(--ps-accent) 60%, transparent),+ color-mix(in srgb, var(--ps-accent-2) 60%, transparent)+ );+}+.ps-slider::-moz-range-track {+ height: 6px;+ border-radius: var(--radius-pill, 999px);+ background: linear-gradient(+ 90deg,+ color-mix(in srgb, var(--ps-accent) 60%, transparent),+ color-mix(in srgb, var(--ps-accent-2) 60%, transparent)+ );+}+.ps-slider::-webkit-slider-thumb {+ -webkit-appearance: none;+ appearance: none;+ width: 20px;+ height: 20px;+ margin-top: -7px;+ border-radius: 50%;+ border: 2px solid var(--ps-accent);+ background: var(--bg, #0a0a0a);+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.35);+ transition: transform 0.14s ease;+}+.ps-slider::-moz-range-thumb {+ width: 20px;+ height: 20px;+ border-radius: 50%;+ border: 2px solid var(--ps-accent);+ background: var(--bg, #0a0a0a);+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.35);+ transition: transform 0.14s ease;+}+.ps-slider:hover::-webkit-slider-thumb,+.ps-slider:active::-webkit-slider-thumb {+ transform: scale(1.15);+}+.ps-slider:hover::-moz-range-thumb,+.ps-slider:active::-moz-range-thumb {+ transform: scale(1.15);+}+.ps-slider:focus-visible {+ outline: none;+}+.ps-slider:focus-visible::-webkit-slider-thumb {+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--ps-accent) 40%, transparent);+}+.ps-slider:focus-visible::-moz-range-thumb {+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--ps-accent) 40%, transparent);+}++.ps-chips {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ margin-top: var(--space-sm, 10px);+}+.ps-chips-label {+ font-size: var(--text-2xs, 0.6875rem);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint, #6e7583);+ margin-right: 4px;+}+.ps-chip {+ padding: 4px 12px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-pill, 999px);+ background: transparent;+ color: var(--ink-dim, #9aa1ad);+ font-size: var(--text-sm, 0.764rem);+ font-variant-numeric: tabular-nums;+ cursor: pointer;+ transition:+ background 0.14s ease,+ color 0.14s ease,+ border-color 0.14s ease;+}+.ps-chip:hover {+ color: var(--ink-bright, #fff);+ border-color: color-mix(in srgb, var(--ps-accent) 50%, transparent);+}+.ps-chip:focus-visible {+ outline: 2px solid var(--ps-accent);+ outline-offset: 2px;+}+.ps-chip.is-on {+ background: color-mix(in srgb, var(--ps-accent) 18%, transparent);+ border-color: var(--ps-accent);+ color: var(--ink-bright, #fff);+}+.ps-control-note {+ margin: var(--space-sm, 10px) 0 0;+ font-size: var(--text-sm, 0.764rem);+ line-height: 1.55;+ color: var(--ink-faint, #6e7583);+}++/* While an unvisited level is in flight, the tables keep the previous level's+ numbers but say so, rather than blanking or silently mismatching the chart. */+.ps-stale .ps-stats,+.ps-stale .ps-section:not(#curves) {+ opacity: 0.55;+ transition: opacity 0.18s ease;+}++/* --- stat tiles ---------------------------------------------------------- */++.ps-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(200px, 100%), 1fr));+ gap: var(--space-sm, 10px);+ margin-bottom: clamp(24px, 4vw, 40px);+}+.ps-stats-tight {+ margin-bottom: 0;+}+.ps-stat {+ padding: var(--space-md, 16px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ transition:+ border-color 0.16s ease,+ transform 0.16s ease;+}+.ps-stat:hover {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ transform: translateY(-1px);+}+.ps-stat-value {+ font-size: var(--text-xl, 1.618rem);+ font-weight: var(--weight-bold, 700);+ line-height: 1.15;+ font-variant-numeric: tabular-nums;+ color: var(--ink-bright, #fff);+}+.ps-stat-cash .ps-stat-value {+ color: var(--ps-accent);+}+.ps-stat-xp .ps-stat-value {+ color: var(--ps-accent-2);+}+.ps-stat-good .ps-stat-value {+ color: var(--ps-good);+}+.ps-stat-label {+ margin-top: 4px;+ font-size: var(--text-sm, 0.764rem);+ font-weight: var(--weight-medium, 500);+ color: var(--ink, #d8d8d8);+}+.ps-stat-hint {+ margin-top: 2px;+ font-size: var(--text-2xs, 0.6875rem);+ line-height: 1.45;+ color: var(--ink-faint, #6e7583);+}++/* --- sections ------------------------------------------------------------ */++.ps-section {+ margin-bottom: clamp(32px, 6vw, 64px);+ scroll-margin-top: 80px;+}+.ps-h2 {+ margin: 0 0 var(--space-sm, 10px);+ font-size: var(--text-xl, 1.618rem);+ line-height: 1.2;+ letter-spacing: -0.01em;+ font-weight: var(--weight-semibold, 600);+ color: var(--ink-bright, #fff);+}+.ps-h3 {+ margin: var(--space-lg, 26px) 0 var(--space-xs, 6px);+ font-size: var(--text-md, 0.8125rem);+ font-weight: var(--weight-semibold, 600);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint, #6e7583);+}+.ps-blurb {+ max-width: 78ch;+ margin: 0 0 var(--space-md, 16px);+ font-size: var(--text-ui, 0.875rem);+ line-height: 1.65;+ color: var(--ink-dim, #9aa1ad);+}+.ps-blurb strong {+ color: var(--ink, #d8d8d8);+ font-weight: var(--weight-semibold, 600);+}+.ps-list {+ max-width: 78ch;+ margin: 0;+ padding-left: 1.2em;+ font-size: var(--text-ui, 0.875rem);+ line-height: 1.7;+ color: var(--ink-dim, #9aa1ad);+}+.ps-list li + li {+ margin-top: 6px;+}+.ps-list code {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 0.92em;+ color: var(--ps-accent);+ margin-right: 4px;+}++/* --- findings ------------------------------------------------------------ */++.ps-findings {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr));+ gap: var(--space-sm, 10px);+}+.ps-finding {+ position: relative;+ padding: var(--space-md, 16px);+ padding-left: calc(var(--space-md, 16px) + 4px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-md, 10px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ overflow: hidden;+ transition:+ border-color 0.16s ease,+ transform 0.16s ease;+}+.ps-finding::before {+ content: '';+ position: absolute;+ inset: 0 auto 0 0;+ width: 3px;+ background: var(--ink-faint, #6e7583);+}+.ps-finding-trap::before {+ background: var(--ps-warn);+}+.ps-finding-reward::before {+ background: var(--ps-good);+}+.ps-finding-context::before {+ background: var(--ps-accent);+}+.ps-finding:hover {+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14));+ transform: translateY(-1px);+}+.ps-finding-kind {+ margin: 0 0 6px;+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-faint, #6e7583);+}+.ps-finding-trap .ps-finding-kind {+ color: var(--ps-warn);+}+.ps-finding-reward .ps-finding-kind {+ color: var(--ps-good);+}+.ps-finding-context .ps-finding-kind {+ color: var(--ps-accent);+}+.ps-finding-title {+ margin: 0 0 6px;+ font-size: var(--text-base, 1rem);+ line-height: 1.35;+ font-weight: var(--weight-semibold, 600);+ color: var(--ink-bright, #fff);+}+.ps-finding-detail {+ margin: 0;+ font-size: var(--text-md, 0.8125rem);+ line-height: 1.6;+ color: var(--ink-dim, #9aa1ad);+}++/* --- chart --------------------------------------------------------------- */++.ps-chart-head {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-md, 16px);+ margin-bottom: var(--space-sm, 10px);+}+.ps-toggle {+ display: inline-flex;+ padding: 3px;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+}+.ps-toggle-btn {+ padding: 6px 14px;+ border: 0;+ border-radius: var(--radius-pill, 999px);+ background: transparent;+ color: var(--ink-dim, #9aa1ad);+ font-size: var(--text-sm, 0.764rem);+ font-weight: var(--weight-medium, 500);+ cursor: pointer;+ transition:+ background 0.14s ease,+ color 0.14s ease;+}+.ps-toggle-btn:hover {+ color: var(--ink-bright, #fff);+}+.ps-toggle-btn:focus-visible {+ outline: 2px solid var(--ps-accent);+ outline-offset: 2px;+}+.ps-toggle-btn.is-on {+ background: color-mix(in srgb, var(--ps-accent) 20%, transparent);+ color: var(--ink-bright, #fff);+}++.ps-legend {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-sm, 10px);+ margin: 0;+ padding: 0;+ list-style: none;+}+.ps-legend-item {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: var(--text-sm, 0.764rem);+ color: var(--ink-dim, #9aa1ad);+}+.ps-swatch {+ width: 10px;+ height: 10px;+ border-radius: 3px;+ flex: none;+ background: var(--ink-faint, #6e7583);+}+.ps-swatch-chop {+ background: var(--ps-chop);+}+.ps-swatch-mine {+ background: var(--ps-mine);+}+.ps-swatch-fish {+ background: var(--ps-fish);+}+.ps-swatch-cook {+ background: var(--ps-cook);+}+.ps-swatch-loop {+ background: var(--ps-loop);+}++.ps-chart-wrap {+ padding: var(--space-sm, 10px);+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-lg, 14px);+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+}+.ps-chart {+ display: block;+ width: 100%;+ height: auto;+ overflow: visible;+}+.ps-chart-interactive {+ cursor: ew-resize;+ touch-action: pan-y;+}+.ps-grid {+ stroke: var(--stroke, rgba(255, 255, 255, 0.08));+ stroke-width: 1;+}+.ps-axis {+ fill: var(--ink-faint, #6e7583);+ font-size: 11px;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-variant-numeric: tabular-nums;+}+.ps-marker {+ stroke: var(--ps-accent);+ stroke-width: 1.5;+ stroke-dasharray: 3 3;+ opacity: 0.8;+}+.ps-line {+ stroke-width: 2;+ stroke-linejoin: round;+ stroke-linecap: round;+ opacity: 0.9;+}+.ps-line-chop {+ stroke: var(--ps-chop);+}+.ps-line-mine {+ stroke: var(--ps-mine);+}+.ps-line-fish {+ stroke: var(--ps-fish);+}+.ps-line-cook {+ stroke: var(--ps-cook);+}+.ps-line-loop {+ stroke: var(--ps-loop);+ stroke-width: 3;+}+.ps-dot {+ stroke: var(--bg, #0a0a0a);+ stroke-width: 1.5;+}+.ps-dot-chop {+ fill: var(--ps-chop);+}+.ps-dot-mine {+ fill: var(--ps-mine);+}+.ps-dot-fish {+ fill: var(--ps-fish);+}+.ps-dot-cook {+ fill: var(--ps-cook);+}+.ps-dot-loop {+ fill: var(--ps-loop);+}++/* --- the fish and cook split -------------------------------------------- */++.ps-split {+ display: flex;+ height: 44px;+ margin-bottom: var(--space-md, 16px);+ border-radius: var(--radius-md, 10px);+ overflow: hidden;+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+}+.ps-split-fish,+.ps-split-cook {+ display: flex;+ align-items: center;+ justify-content: center;+ min-width: 0;+ transition: width 0.24s cubic-bezier(0.4, 0, 0.2, 1);+}+.ps-split-fish {+ background: color-mix(in srgb, var(--ps-fish) 32%, transparent);+ border-right: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+}+.ps-split-cook {+ background: color-mix(in srgb, var(--ps-cook) 32%, transparent);+}+.ps-split-label {+ padding: 0 8px;+ font-size: var(--text-sm, 0.764rem);+ font-weight: var(--weight-semibold, 600);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ color: var(--ink-bright, #fff);+}++/* --- tables -------------------------------------------------------------- */++.ps-tablewrap {+ overflow-x: auto;+ border-radius: var(--radius-md, 10px);+}+.ps-tablewrap:focus-visible {+ outline: 2px solid var(--ps-accent);+ outline-offset: 2px;+}+.ps-table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--text-md, 0.8125rem);+}+.ps-table th {+ padding: 8px 12px;+ text-align: left;+ font-size: var(--text-2xs, 0.6875rem);+ font-weight: var(--weight-semibold, 600);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint, #6e7583);+ border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.1));+ white-space: nowrap;+}+.ps-table tbody th {+ font-size: var(--text-md, 0.8125rem);+ font-weight: var(--weight-medium, 500);+ letter-spacing: 0;+ text-transform: none;+ color: var(--ink, #d8d8d8);+ border-bottom: 1px solid+ color-mix(in srgb, var(--stroke, rgba(255, 255, 255, 0.1)) 55%, transparent);+}+.ps-table td {+ padding: 10px 12px;+ border-bottom: 1px solid+ color-mix(in srgb, var(--stroke, rgba(255, 255, 255, 0.1)) 55%, transparent);+ color: var(--ink, #d8d8d8);+ vertical-align: middle;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}+.ps-table tbody tr:last-child th,+.ps-table tbody tr:last-child td {+ border-bottom: 0;+}+.ps-table tbody tr {+ transition: background 0.14s ease;+}+.ps-table tbody tr:hover {+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+}+.ps-r {+ text-align: right;+}+.ps-cell-name {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ white-space: nowrap;+}+.ps-row-capped th,+.ps-row-capped td {+ color: var(--ink-faint, #6e7583);+}+.ps-tag {+ padding: 2px 8px;+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-pill, 999px);+ font-size: var(--text-2xs, 0.6875rem);+ letter-spacing: 0.04em;+ color: var(--ps-warn);+ cursor: help;+}++/* --- loading and error --------------------------------------------------- */++.ps-skeleton {+ display: grid;+ gap: var(--space-md, 16px);+}+.ps-skel-control,+.ps-skel-stat,+.ps-skel-chart,+.ps-skel-bar {+ border-radius: var(--radius-md, 10px);+ background: linear-gradient(+ 90deg,+ var(--surface-1, rgba(255, 255, 255, 0.03)) 0%,+ var(--surface-3, rgba(255, 255, 255, 0.08)) 50%,+ var(--surface-1, rgba(255, 255, 255, 0.03)) 100%+ );+ background-size: 200% 100%;+ animation: ps-shimmer 1.4s ease-in-out infinite;+}+.ps-skel-control {+ height: 128px;+}+.ps-skel-stat {+ height: 92px;+}+.ps-skel-chart {+ height: 300px;+ border-radius: var(--radius-lg, 14px);+}+.ps-skel-rows {+ display: grid;+ gap: 8px;+}+.ps-skel-bar {+ height: 34px;+}+@keyframes ps-shimmer {+ from {+ background-position: 200% 0;+ }+ to {+ background-position: -200% 0;+ }+}++.ps-error {+ padding: clamp(24px, 5vw, 40px);+ border: 1px solid color-mix(in srgb, var(--ps-warn) 40%, transparent);+ border-radius: var(--radius-lg, 14px);+ background: color-mix(in srgb, var(--ps-warn) 6%, transparent);+}+.ps-error-title {+ margin: 0 0 var(--space-xs, 6px);+ font-size: var(--text-lg, 1.236rem);+ font-weight: var(--weight-semibold, 600);+ color: var(--ink-bright, #fff);+}+.ps-error-body {+ max-width: 68ch;+ margin: 0 0 var(--space-md, 16px);+ font-size: var(--text-ui, 0.875rem);+ line-height: 1.6;+ color: var(--ink-dim, #9aa1ad);+}+.ps-error-actions {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-sm, 10px);+}++/* --- fine print and utilities ------------------------------------------- */++.ps-fineprint {+ max-width: 82ch;+ margin: clamp(32px, 6vw, 64px) 0 0;+ padding-top: var(--space-lg, 26px);+ border-top: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ font-size: var(--text-sm, 0.764rem);+ line-height: 1.7;+ color: var(--ink-faint, #6e7583);+}+.ps-fineprint code {+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 0.94em;+ color: var(--ink-dim, #9aa1ad);+}+.ps-fineprint a {+ color: var(--ps-accent);+ text-decoration: none;+ border-bottom: 1px solid color-mix(in srgb, var(--ps-accent) 40%, transparent);+}+.ps-fineprint a:hover {+ border-bottom-color: var(--ps-accent);+}++/* Screen-reader-only, used by the live region that announces each solve. */+.ps-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* --- light theme --------------------------------------------------------- */++:root[data-theme='light'] .ps-shell {+ --ps-accent: #0e8c9e;+ --ps-accent-2: #4a58c8;+ --ps-chop: #2f8a52;+ --ps-mine: #5c6880;+ --ps-fish: #1d76bb;+ --ps-cook: #c26a1c;+ --ps-loop: #7a4ac8;+ --ps-good: #2f8a52;+ --ps-warn: #a8700c;+}+:root[data-theme='light'] .ps-btn-primary {+ color: #fff;+}+:root[data-theme='light'] .ps-slider::-webkit-slider-thumb,+:root[data-theme='light'] .ps-slider::-moz-range-thumb {+ background: #fff;+}+:root[data-theme='light'] .ps-dot {+ stroke: #fff;+}++/* --- motion and narrow screens ------------------------------------------ */++@media (prefers-reduced-motion: reduce) {+ .ps-skel-control,+ .ps-skel-stat,+ .ps-skel-chart,+ .ps-skel-bar {+ animation: none;+ }+ .ps-btn,+ .ps-stat,+ .ps-finding,+ .ps-split-fish,+ .ps-split-cook,+ .ps-slider::-webkit-slider-thumb,+ .ps-slider::-moz-range-thumb {+ transition: none;+ }+ .ps-btn:hover,+ .ps-stat:hover,+ .ps-finding:hover {+ transform: none;+ }+}++@media (max-width: 640px) {+ .ps-control-head {+ align-items: center;+ }+ .ps-chart-head {+ flex-direction: column;+ align-items: flex-start;+ }+ /* A 900-unit-wide chart squeezed to 320px makes every curve unreadable, so it+ gets a taller aspect and the labels thin out rather than collide. */+ .ps-chart {+ min-height: 220px;+ }+ .ps-split {+ height: 52px;+ }+ .ps-split-label {+ font-size: var(--text-2xs, 0.6875rem);+ }+}diff --git a/src/play-solver.js b/src/play-solver.jsnew file mode 100644index 000000000..c1aed7ea8--- /dev/null+++ b/src/play-solver.js@@ -0,0 +1,638 @@+/**+ * /play/solver: the solved economy of the /play open world.+ *+ * The companion page to /play/economy. That one publishes WHAT the world charges;+ * this one publishes what those numbers mean, by pricing every action in the world+ * at every skill level.+ *+ * GET /api/play/solver the whole model, plus a 99-level sweep for every node+ *+ * Two design decisions drive this file:+ *+ * 1. THE LEVEL CONTROL NEVER WAITS ON THE NETWORK. The endpoint ships the full+ * per-level curve for every node in one response (about 20 KB), so dragging the+ * slider redraws from memory. A page that round-tripped per level would feel+ * broken at exactly the moment it is most interesting to play with.+ *+ * 2. NOTHING IS COMPUTED HERE. Every number rendered below comes off the wire from+ * the model, which imports the game's own tables. Recomputing a rate client-side+ * would create a second source of truth and reintroduce precisely the drift the+ * whole design exists to prevent. The only arithmetic in this file is layout:+ * turning numbers into pixel coordinates for the chart.+ *+ * The response is static config, so there is no meaningful "empty" state: it either+ * loads or the request failed, and a failure gets a real error state with a retry.+ */++const ENDPOINT = '/api/play/solver';++const fmtInt = (n) => new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(n);+const fmt1 = (n) => new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 }).format(n);+const fmt2 = (n) => new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 }).format(n);++// Family colours double as the chart legend, so they live in one place and are read+// back out of CSS custom properties at draw time to stay theme-correct.+const FAMILY = {+ chop: { label: 'Woodcutting', varName: '--ps-chop' },+ mine: { label: 'Mining', varName: '--ps-mine' },+ fish: { label: 'Fishing', varName: '--ps-fish' },+ cook: { label: 'Cooking', varName: '--ps-cook' },+ loop: { label: 'Fish and cook', varName: '--ps-loop' },+};++/** Minutes rendered the way a person would say them. */+function duration(minutes) {+ if (minutes === null || minutes === undefined || !Number.isFinite(minutes)) return 'never';+ if (minutes < 1) return `${fmt1(minutes * 60)}s`;+ if (minutes < 90) return `${fmt1(minutes)} min`;+ const hours = minutes / 60;+ if (hours < 48) return `${fmt1(hours)} hr`;+ return `${fmt1(hours / 24)} days`;+}++function el(tag, props = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (v === null || v === undefined || v === false) continue;+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else n.setAttribute(k, v === true ? '' : String(v));+ }+ for (const kid of [].concat(kids)) {+ if (kid === null || kid === undefined || kid === false) continue;+ n.append(kid.nodeType ? kid : document.createTextNode(String(kid)));+ }+ return n;+}++function svg(tag, props = {}, kids = []) {+ const n = document.createElementNS('http://www.w3.org/2000/svg', tag);+ for (const [k, v] of Object.entries(props)) {+ if (v === null || v === undefined || v === false) continue;+ n.setAttribute(k, String(v));+ }+ for (const kid of [].concat(kids)) if (kid) n.append(kid);+ return n;+}++function stat(value, label, hint, tone) {+ return el('div', { class: `ps-stat${tone ? ` ps-stat-${tone}` : ''}` }, [+ el('div', { class: 'ps-stat-value', text: value }),+ el('div', { class: 'ps-stat-label', text: label }),+ hint ? el('div', { class: 'ps-stat-hint', text: hint }) : null,+ ]);+}++/** Overflow that scrolls inside its own box, reachable by keyboard. */+function scroller(node, label) {+ return el(+ 'div',+ { class: 'ps-tablewrap', tabindex: '0', role: 'region', 'aria-label': label },+ [node],+ );+}++function table(headings, rows, { label, align = [] } = {}) {+ const thead = el('thead', {}, [+ el(+ 'tr',+ {},+ headings.map((h, i) =>+ el('th', { scope: 'col', class: align[i] === 'right' ? 'ps-r' : null, text: h }),+ ),+ ),+ ]);+ const tbody = el(+ 'tbody',+ {},+ rows.map((cells) =>+ el(+ 'tr',+ { class: cells.rowClass || null },+ (cells.cells || cells).map((c, i) =>+ el(+ i === 0 ? 'th' : 'td',+ {+ scope: i === 0 ? 'row' : null,+ class: align[i] === 'right' ? 'ps-r' : null,+ },+ [c],+ ),+ ),+ ),+ ),+ );+ return scroller(el('table', { class: 'ps-table' }, [thead, tbody]), label);+}++function section(id, title, blurb, kids) {+ return el('section', { class: 'ps-section', id }, [+ el('h2', { class: 'ps-h2', text: title }),+ blurb ? el('p', { class: 'ps-blurb' }, [blurb]) : null,+ ...[].concat(kids),+ ]);+}++/* --- the chart ------------------------------------------------------------+ * A dependency-free SVG line chart. The repo has no shared chart helper and the+ * one charting dependency present is a candlestick library aimed at price series,+ * so a purpose-built 60-line renderer is both smaller and a better fit than+ * bending either to a level-versus-rate plot.+ *+ * viewBox coordinates with preserveAspectRatio="none" would distort stroke widths,+ * so the chart draws into a fixed logical box and scales with CSS width while+ * keeping its own aspect ratio. Every series is also published as a table below,+ * so the information is never trapped in the graphic.+ */+const CHART = { w: 900, h: 320, padL: 62, padR: 16, padT: 16, padB: 34 };++function chartFor(curves, metric, level, onScrub) {+ const series = curves.filter((c) => c.family !== 'cook');+ const levels = series[0] ? series[0][metric].length : 0;+ if (!levels) return el('div');++ const max = series.reduce(+ (m, s) => Math.max(m, s[metric].reduce((a, b) => Math.max(a, b), 0)),+ 0,+ );+ const plotW = CHART.w - CHART.padL - CHART.padR;+ const plotH = CHART.h - CHART.padT - CHART.padB;+ const x = (i) => CHART.padL + (i / (levels - 1)) * plotW;+ const y = (v) => CHART.padT + plotH - (max > 0 ? v / max : 0) * plotH;++ const grid = [];+ const ticks = 4;+ for (let t = 0; t <= ticks; t += 1) {+ const value = (max / ticks) * t;+ const gy = y(value);+ grid.push(svg('line', { x1: CHART.padL, x2: CHART.w - CHART.padR, y1: gy, y2: gy, class: 'ps-grid' }));+ grid.push(+ svg('text', { x: CHART.padL - 8, y: gy + 4, class: 'ps-axis', 'text-anchor': 'end' }, [+ document.createTextNode(fmtInt(value)),+ ]),+ );+ }+ for (const lv of [1, 25, 50, 75, levels]) {+ grid.push(+ svg('text', { x: x(lv - 1), y: CHART.h - 10, class: 'ps-axis', 'text-anchor': 'middle' }, [+ document.createTextNode(String(lv)),+ ]),+ );+ }++ const lines = series.map((s) => {+ const points = s[metric].map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');+ return svg('polyline', {+ points,+ class: `ps-line ps-line-${s.family}`,+ 'data-key': s.key,+ fill: 'none',+ });+ });++ // The level marker is the whole point of the chart: it ties the tables below to+ // a position on every curve at once.+ const markerX = x(level - 1);+ const marker = svg('line', {+ x1: markerX, x2: markerX, y1: CHART.padT, y2: CHART.padT + plotH, class: 'ps-marker',+ });+ const dots = series.map((s) =>+ svg('circle', { cx: markerX, cy: y(s[metric][level - 1]), r: 4, class: `ps-dot ps-dot-${s.family}` }),+ );++ const node = svg(+ 'svg',+ {+ viewBox: `0 0 ${CHART.w} ${CHART.h}`,+ class: 'ps-chart',+ role: 'img',+ 'aria-label': `${metric === 'cash' ? 'Cash' : 'Experience'} per hour against skill level, for every gatherable node in the world. The full figures are in the activity table below.`,+ },+ [...grid, marker, ...lines, ...dots],+ );++ // Pointer scrubbing sets the level, so the chart is an input as well as an+ // output. Keyboard users get the same control from the slider, which is why the+ // SVG itself is not focusable: it would be a duplicate tab stop with no new+ // capability.+ if (onScrub) {+ const scrub = (event) => {+ const rect = node.getBoundingClientRect();+ const px = ((event.clientX - rect.left) / rect.width) * CHART.w;+ const ratio = (px - CHART.padL) / plotW;+ onScrub(Math.max(1, Math.min(levels, Math.round(ratio * (levels - 1)) + 1)));+ };+ node.addEventListener('pointerdown', (e) => {+ node.setPointerCapture(e.pointerId);+ scrub(e);+ });+ node.addEventListener('pointermove', (e) => {+ if (e.buttons) scrub(e);+ });+ node.classList.add('ps-chart-interactive');+ }+ return node;+}++function legend(curves) {+ const families = [...new Set(curves.filter((c) => c.family !== 'cook').map((c) => c.family))];+ return el(+ 'ul',+ { class: 'ps-legend' },+ families.map((f) =>+ el('li', { class: 'ps-legend-item' }, [+ el('span', { class: `ps-swatch ps-swatch-${f}`, 'aria-hidden': 'true' }),+ FAMILY[f]?.label || f,+ ]),+ ),+ );+}++/* --- sections ------------------------------------------------------------- */++function headline(model) {+ const best = model.bestRate;+ const bestXp = model.bestXpRate;+ const next = model.nextLevel;+ const catalogCost = model.payback.reduce((s, p) => s + p.price, 0);+ const catalogMinutes = best.cashPerHour > 0 ? (catalogCost / best.cashPerHour) * 60 : null;++ return el('div', { class: 'ps-stats' }, [+ stat(`${fmtInt(best.cashPerHour)}`, 'Best cash per hour', best.label, 'cash'),+ stat(`${fmtInt(bestXp.xpPerHour)}`, 'Best XP per hour', bestXp.label, 'xp'),+ stat(+ next ? duration(next.minutes) : 'At the cap',+ next ? `To level ${next.level}` : 'Level 99',+ next ? `${fmtInt(next.xp)} XP via ${next.via.toLowerCase()}` : 'Nothing left to earn',+ ),+ stat(duration(catalogMinutes), 'To buy the whole store', `${fmtInt(catalogCost)} cash across ${model.payback.length} entries`),+ ]);+}++function findingsSection(model) {+ const cards = model.findings.map((f) =>+ el('article', { class: `ps-finding ps-finding-${f.kind}` }, [+ el('p', { class: 'ps-finding-kind', text: f.kind === 'trap' ? 'Watch out' : f.kind === 'reward' ? 'Worth doing' : 'For scale' }),+ el('h3', { class: 'ps-finding-title', text: f.title }),+ el('p', { class: 'ps-finding-detail', text: f.detail }),+ ]),+ );+ return section(+ 'findings',+ 'What the arithmetic concludes',+ 'These are not editorial notes. Each one is assembled from the numbers computed for the level you selected, so if the game is retuned and a conclusion stops being true, it stops being shown rather than going quietly stale.',+ el('div', { class: 'ps-findings' }, cards),+ );+}++function chartSection(model, curves, state, rerender) {+ const toggle = el('div', { class: 'ps-toggle', role: 'group', 'aria-label': 'Chart metric' }, [+ el('button', {+ type: 'button',+ class: `ps-toggle-btn${state.metric === 'cash' ? ' is-on' : ''}`,+ 'aria-pressed': state.metric === 'cash' ? 'true' : 'false',+ text: 'Cash per hour',+ onclick: () => { state.metric = 'cash'; rerender(); },+ }),+ el('button', {+ type: 'button',+ class: `ps-toggle-btn${state.metric === 'xp' ? ' is-on' : ''}`,+ 'aria-pressed': state.metric === 'xp' ? 'true' : 'false',+ text: 'XP per hour',+ onclick: () => { state.metric = 'xp'; rerender(); },+ }),+ ]);++ return section(+ 'curves',+ 'Every node, every level',+ 'One line per gatherable node in the world, across all 99 levels. Drag anywhere on the chart to move the level. Cooking is charted as part of the fish-and-cook loop rather than on its own, because its standalone rate needs a fish supply no single player can deliver.',+ [+ el('div', { class: 'ps-chart-head' }, [toggle, legend(curves)]),+ el('div', { class: 'ps-chart-wrap' }, [+ // The marker follows `state.level`, not the loaded model's level, so it+ // tracks a drag frame-for-frame while the tables catch up behind it.+ chartFor(curves, state.metric, state.level, (lvl) => {+ if (lvl !== state.level) { state.level = lvl; rerender(); }+ }),+ ]),+ ],+ );+}++function ladderSection(model) {+ const rows = model.activities.map((a) => ({+ rowClass: a.sustainable ? null : 'ps-row-capped',+ cells: [+ el('div', { class: 'ps-cell-name' }, [+ el('span', { class: `ps-swatch ps-swatch-${a.family}`, 'aria-hidden': 'true' }),+ el('span', { text: a.label }),+ a.sustainable+ ? null+ : el('span', { class: 'ps-tag', title: a.requires, text: 'needs a supply' }),+ ]),+ a.node.difficulty ? fmt1(a.node.difficulty) : a.node.quality ? `${fmt1(a.node.quality)} quality` : 'n/a',+ `${fmt1(a.successPct)}%`,+ fmt1(a.unitsPerHour),+ a.coalPerHour ? fmt1(a.coalPerHour) : 'n/a',+ fmtInt(a.cashPerHour),+ fmtInt(a.xpPerHour),+ a.packHours ? `${fmt1(a.packHours)} hr` : 'n/a',+ ],+ }));++ return section(+ 'ladder',+ 'The activity ladder',+ 'Every node priced at the selected level, ranked by cash. Rates that cannot be sustained always sort last regardless of size: ranking a number nobody can hold above one anybody can would make the table advice you cannot follow.',+ table(+ ['Activity', 'Node', 'Hit rate', 'Units per hour', 'Coal per hour', 'Cash per hour', 'XP per hour', 'Pack lasts'],+ rows,+ {+ label: 'Expected yield per hour for every gatherable node',+ align: ['', '', 'right', 'right', 'right', 'right', 'right', 'right'],+ },+ ),+ );+}++function loopSection(model) {+ const loop = model.loop;+ const bar = el('div', { class: 'ps-split', role: 'img', 'aria-label': `${fmt1(loop.fishSharePct)} percent of the hour fishing, ${fmt1(loop.cookSharePct)} percent cooking` }, [+ el('div', { class: 'ps-split-fish', style: `width:${loop.fishSharePct}%` }, [+ el('span', { class: 'ps-split-label', text: `Fish ${fmt1(loop.fishSharePct)}%` }),+ ]),+ el('div', { class: 'ps-split-cook', style: `width:${loop.cookSharePct}%` }, [+ el('span', { class: 'ps-split-label', text: `Cook ${fmt1(loop.cookSharePct)}%` }),+ ]),+ ]);++ return section(+ 'loop',+ 'The one split worth getting right',+ 'Cooked fish sells for three times what raw fish sells for, but you cannot fish and cook at the same time. So the real question is how to divide an hour between them. Supply meets demand at exactly one split, and at that split nothing queues and nothing idles.',+ [+ bar,+ el('div', { class: 'ps-stats ps-stats-tight' }, [+ stat(fmtInt(loop.cashPerHour), 'Cash per hour, split', `at the ${fmt1(loop.fishSharePct)} to ${fmt1(loop.cookSharePct)} balance`, 'cash'),+ stat(fmtInt(loop.rawOnlyCashPerHour), 'Cash per hour, raw only', 'a full hour fishing, sold uncooked'),+ stat(`+${fmt1(loop.upliftPct)}%`, 'What cooking is worth', 'the return on learning to cook', 'good'),+ stat(fmt1(loop.cookedPerHour), 'Cooked fish per hour', `from ${fmt1(loop.fishPerHour)} caught`),+ ]),+ ],+ );+}++function paybackSection(model) {+ const rows = model.payback.map((p) => [+ p.qty > 1 ? `${p.label} (${p.qty})` : p.label,+ fmtInt(p.price),+ p.qty > 1 ? fmt2(p.unitPrice) : 'n/a',+ duration(p.minutes),+ p.attempts === null ? 'never' : fmtInt(p.attempts),+ ]);++ return section(+ 'payback',+ 'What the store costs in playtime',+ el('span', {}, [+ 'Every catalog entry priced against the best rate you can actually hold at this level (',+ el('strong', { text: model.bestRate.label.toLowerCase() }),+ `, ${fmtInt(model.bestRate.cashPerHour)} cash per hour). Bundles show their per-unit price, because a sticker price on a stack of twelve is not comparable to one on a single item.`,+ ]),+ table(+ ['Item', 'Price', 'Per unit', 'Time to afford', 'Swings'],+ rows,+ { label: 'Time and swings to afford each store item', align: ['', 'right', 'right', 'right', 'right'] },+ ),+ );+}++function wheelSection(model) {+ const w = model.wheel;+ return section(+ 'wheel',+ "Fortune's Folly, priced",+ 'Valuing every wedge at what the store would pay for it turns the wheel from a mystery into a number. The spread is almost entirely one jackpot wedge, which is why the average outcome is not the typical one.',+ el('div', { class: 'ps-stats ps-stats-tight' }, [+ stat(fmt1(w.evCash), 'Average spin', `across ${w.wedges} wedges`, 'cash'),+ stat(`±${fmt1(w.stdevCash)}`, 'Standard deviation', `best ${fmtInt(w.bestCash)}, worst ${fmtInt(w.worstCash)}`),+ stat(`${fmt1(w.aboveEvPct)}%`, 'Land at or above average', 'the jackpot drags the mean up'),+ stat(duration(w.minutesOfBestRate), 'A free spin, in playtime', `${fmtInt(w.evPerDayCash)} cash a day from ${fmt1(w.freeSpinsPerDay)} free spins`),+ ]),+ );+}++function combatSection(model) {+ const rows = model.combat.map((m) => [+ el('div', { class: 'ps-cell-name' }, [+ el('span', { text: m.label }),+ m.hostile ? null : el('span', { class: 'ps-tag', text: 'passive' }),+ ]),+ fmtInt(m.hp),+ fmtInt(m.xp),+ fmtInt(m.gold),+ fmt1(m.lootCash),+ fmt1(m.totalCash),+ m.mountPct > 0 ? `${fmt1(m.mountPct)}%` : 'none',+ ]);++ return section(+ 'combat',+ 'What a kill is worth',+ 'Combat is priced per kill rather than per hour, because kill speed depends on your weapon, your aim and how fast the world respawns, none of which is a constant the model can honestly assume. Loot is valued at store prices and every drop line is an independent roll, so the expectations simply add. Mounts have no sell price and never inflate a cash figure.',+ table(+ ['Enemy', 'HP', 'XP', 'Cash', 'Loot value', 'Total per kill', 'Mount chance'],+ rows,+ { label: 'Expected value of one kill, per enemy', align: ['', 'right', 'right', 'right', 'right', 'right', 'right'] },+ ),+ );+}++function methodSection(model) {+ return section(+ 'method',+ 'How this is computed, and where it stops being true',+ null,+ [+ el('p', { class: 'ps-blurb', text: model.method.summary }),+ el('p', { class: 'ps-blurb', text: model.method.exactness }),+ el('h3', { class: 'ps-h3', text: 'Read from' }),+ el('ul', { class: 'ps-list' }, model.method.source.map((s) => el('li', {}, [el('code', { text: s.split(':')[0] }), s.slice(s.indexOf(':') + 1)]))),+ el('h3', { class: 'ps-h3', text: 'Assumptions' }),+ el('ol', { class: 'ps-list ps-list-numbered' }, model.assumptions.map((a) => el('li', { text: a }))),+ ],+ );+}++/* --- the level control ---------------------------------------------------- */++function levelControl(state, model, rerender) {+ const slider = el('input', {+ type: 'range',+ min: '1',+ max: String(model.levelCap),+ value: String(state.level),+ class: 'ps-slider',+ id: 'ps-level',+ 'aria-describedby': 'ps-level-readout',+ });+ slider.addEventListener('input', () => {+ state.level = Number(slider.value);+ rerender({ keepFocus: 'slider' });+ });++ const chips = [1, 3, 10, 30, 60, model.levelCap].map((lv) =>+ el('button', {+ type: 'button',+ class: `ps-chip${state.level === lv ? ' is-on' : ''}`,+ 'aria-pressed': state.level === lv ? 'true' : 'false',+ text: lv === model.levelCap ? `${lv} (cap)` : String(lv),+ onclick: () => { state.level = lv; rerender(); },+ }),+ );++ return el('div', { class: 'ps-control' }, [+ el('div', { class: 'ps-control-head' }, [+ el('label', { class: 'ps-control-label', for: 'ps-level', text: 'Skill level' }),+ el('output', { class: 'ps-readout', id: 'ps-level-readout', for: 'ps-level', text: String(state.level) }),+ ]),+ slider,+ el('div', { class: 'ps-chips' }, [+ el('span', { class: 'ps-chips-label', text: 'Jump to' }),+ ...chips,+ ]),+ el('p', {+ class: 'ps-control-note',+ text: 'The model holds every skill at this level at once, so the ladder compares like with like. In a real session your skills diverge, and each row tracks whichever skill it names.',+ }),+ ]);+}++/* --- states --------------------------------------------------------------- */++function skeleton() {+ const bar = (w) => el('div', { class: 'ps-skel-bar', style: `width:${w}` });+ return el('div', { class: 'ps-skeleton', 'aria-hidden': 'true' }, [+ el('div', { class: 'ps-skel-control' }),+ el('div', { class: 'ps-stats' }, [0, 1, 2, 3].map(() => el('div', { class: 'ps-skel-stat' }))),+ el('div', { class: 'ps-skel-chart' }),+ el('div', { class: 'ps-skel-rows' }, [bar('92%'), bar('78%'), bar('85%'), bar('64%'), bar('71%')]),+ ]);+}++function errorState(message, retry) {+ return el('div', { class: 'ps-error', role: 'alert' }, [+ el('h2', { class: 'ps-error-title', text: 'The solver could not load' }),+ el('p', { class: 'ps-error-body', text: message }),+ el('div', { class: 'ps-error-actions' }, [+ el('button', { type: 'button', class: 'ps-btn ps-btn-primary', text: 'Try again', onclick: retry }),+ el('a', { class: 'ps-btn', href: '/play/economy', text: 'See the raw price tables' }),+ el('a', { class: 'ps-btn', href: '/play', text: 'Enter the world' }),+ ]),+ ]);+}++/* --- boot ----------------------------------------------------------------- */++const root = document.getElementById('ps-content');+const status = document.getElementById('ps-status');++// One fetch holds the whole model plus the 99-level sweep. `models` caches the+// per-level solve so re-rendering a level already visited costs nothing; the curves+// are shared across all of them.+const state = { level: 1, metric: 'cash', curves: null, models: new Map() };++function setStatus(text) {+ if (status) status.textContent = text;+}++async function loadLevel(level) {+ if (state.models.has(level)) return state.models.get(level);+ const url = state.curves ? `${ENDPOINT}?level=${level}&curves=0` : `${ENDPOINT}?level=${level}`;+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`The solver endpoint answered ${res.status}.`);+ const body = await res.json();+ if (body.curves) state.curves = body.curves;+ state.models.set(body.level, body);+ return body;+}++// A drag fires `input` on every pixel. Each unvisited level needs one solve from the+// server, so requests are coalesced: the chart and the level readout move on the+// current frame, and the tables re-solve once the control settles.+let pending = null;+function requestLevel(level, opts) {+ if (state.models.has(level)) { render(opts); return; }+ clearTimeout(pending);+ pending = setTimeout(() => {+ loadLevel(level)+ .then(() => { if (state.level === level) render(opts); })+ .catch((err) => setStatus(`Could not solve level ${level}: ${err.message}`));+ }, 120);+ // Draw the frame anyway so the chart marker and the readout stay live.+ render(opts);+}++function render(opts = {}) {+ // While an unvisited level is in flight, the tables keep showing the last solved+ // level rather than blanking. `stale` marks that explicitly instead of letting the+ // page quietly present one level's chart beside another level's numbers.+ const exact = state.models.get(state.level);+ const model = exact || state.lastModel;+ if (!model) return;+ state.lastModel = model;+ const stale = !exact;++ const rerender = (o) => requestLevel(state.level, o);++ root.replaceChildren(+ levelControl(state, model, rerender),+ headline(model),+ findingsSection(model),+ chartSection(model, state.curves || [], state, rerender),+ ladderSection(model),+ loopSection(model),+ paybackSection(model),+ wheelSection(model),+ combatSection(model),+ methodSection(model),+ );++ root.classList.toggle('ps-stale', stale);++ // Dragging the slider re-creates it, so focus has to be restored or the control+ // dies under the user's finger after one step.+ if (opts.keepFocus === 'slider') {+ const slider = document.getElementById('ps-level');+ if (slider) slider.focus();+ }+ setStatus(+ stale+ ? `Solving level ${state.level}.`+ : `Solved at level ${model.level}. Best sustainable rate: ${model.bestRate.label}, ${fmtInt(model.bestRate.cashPerHour)} cash per hour.`,+ );+}++async function boot() {+ root.replaceChildren(skeleton());+ setStatus('Solving the world economy.');+ try {+ await loadLevel(state.level);+ render();+ } catch (err) {+ const offline = typeof navigator !== 'undefined' && navigator.onLine === false;+ const message = offline+ ? 'You appear to be offline. The solver reads live from the game server, so it needs a connection.'+ : `${err.message} The model is static config, so this is a transport problem rather than missing data. Retrying usually clears it.`;+ root.replaceChildren(errorState(message, boot));+ setStatus(message);+ }+}++// The solver is deep-linkable by level, so a shared URL lands on the same numbers.+const initial = Number(new URLSearchParams(location.search).get('level'));+if (Number.isFinite(initial) && initial >= 1) state.level = Math.min(99, Math.floor(initial));++boot();diff --git a/tests/api/play-solver.test.js b/tests/api/play-solver.test.jsnew file mode 100644index 000000000..d54787719--- /dev/null+++ b/tests/api/play-solver.test.js@@ -0,0 +1,200 @@+// Unit tests for GET /api/play/solver, the solved economy of the /play worlds.+//+// The model itself is proven in tests/rate-model.test.js (including a seeded+// simulation of the real handlers). These tests cover the HTTP contract on top of+// it: query handling, the cache posture that makes a public reference cheap, and+// the guarantee that the served body is the model's own output rather than a+// reshaped copy that could drift from it.+//+// game-token.js is mocked because spin-wheel.js pulls it in transitively for the+// paid-spin path this endpoint never touches, and it constructs Solana clients and+// reads wallet env at import time.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../multiplayer/src/game-token.js', () => ({+ buildSpinPayment: vi.fn(),+ verifySpinPayment: vi.fn(),+ isWalletAddress: () => true,+ tokenConfigured: vi.fn(() => true),+ TOKEN_DECIMALS: 6,+ TOKEN_SYMBOL: '$THREE',+}));++const rlState = { success: true, limit: 60, remaining: 59, reset: 0 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const handler = (await import('../../api/play/solver.js')).default;+const { solveAt, allCurves, ASSUMPTIONS } = await import('../../multiplayer/src/rate-model.js');+const { LEVEL_CAP } = await import('../../multiplayer/src/economy.js');+const { TREES, ROCKS, FISHING_SPOTS } = await import('../../multiplayer/src/world-features.js');++function mockRes() {+ const chunks = [];+ return {+ statusCode: 0,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ writeHead(status, headers) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers || {})) this.setHeader(k, v);+ return this;+ },+ end(body) { if (body) chunks.push(body); return this; },+ get body() { return chunks.join(''); },+ get parsed() { return JSON.parse(chunks.join('')); },+ };+}++const mockReq = (url = '/api/play/solver', method = 'GET') => ({+ method,+ url,+ headers: { host: 'three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+});++async function get(url) {+ const res = mockRes();+ await handler(mockReq(url), res);+ return res;+}++beforeEach(() => {+ rlState.success = true;+});++describe('GET /api/play/solver: contract', () => {+ it('serves the model at level 1 by default', async () => {+ const res = await get('/api/play/solver');+ expect(res.statusCode).toBe(200);+ expect(res.parsed.level).toBe(1);+ expect(res.parsed.requestedLevel).toBeNull();+ expect(res.parsed.levelClamped).toBe(false);+ });++ it('serves exactly what the model computes, not a reshaped copy', async () => {+ const res = await get('/api/play/solver?level=37&curves=0');+ const model = solveAt(37);+ // Every key the model produces has to survive to the wire unchanged, or the+ // endpoint has quietly become a second source of truth.+ for (const key of Object.keys(model)) {+ expect(res.parsed[key]).toEqual(model[key]);+ }+ });++ it('clamps an out-of-range level rather than rejecting it, and says so', async () => {+ const high = await get('/api/play/solver?level=5000');+ expect(high.statusCode).toBe(200);+ expect(high.parsed.level).toBe(LEVEL_CAP);+ expect(high.parsed.levelClamped).toBe(true);+ expect(high.parsed.requestedLevel).toBe('5000');++ const low = await get('/api/play/solver?level=0');+ expect(low.parsed.level).toBe(1);+ expect(low.parsed.levelClamped).toBe(true);++ const negative = await get('/api/play/solver?level=-12');+ expect(negative.parsed.level).toBe(1);+ expect(negative.parsed.levelClamped).toBe(true);+ });++ it('falls back to level 1 on a level that is not a number', async () => {+ const res = await get('/api/play/solver?level=banana');+ expect(res.statusCode).toBe(200);+ expect(res.parsed.level).toBe(1);+ });++ it('does not flag an in-range level as clamped', async () => {+ const res = await get('/api/play/solver?level=42');+ expect(res.parsed.level).toBe(42);+ expect(res.parsed.levelClamped).toBe(false);+ });++ it('includes the full level sweep by default and drops it on curves=0', async () => {+ const withCurves = await get('/api/play/solver?level=5');+ expect(Array.isArray(withCurves.parsed.curves)).toBe(true);+ expect(withCurves.parsed.curves).toHaveLength(allCurves().length);+ for (const c of withCurves.parsed.curves) {+ expect(c.cash).toHaveLength(LEVEL_CAP);+ expect(c.xp).toHaveLength(LEVEL_CAP);+ }++ const without = await get('/api/play/solver?level=5&curves=0');+ expect(without.parsed.curves).toBeUndefined();+ });++ it('rates every node the world defines', async () => {+ const res = await get('/api/play/solver?curves=0');+ const keys = res.parsed.activities.map((a) => a.key);+ for (const t of TREES) expect(keys).toContain(`chop:${t.id}`);+ for (const r of ROCKS) expect(keys).toContain(`mine:${r.id}`);+ for (const s of FISHING_SPOTS) expect(keys).toContain(`fish:${s.id}`);+ });++ it('publishes its assumptions and its method alongside the numbers', async () => {+ const res = await get('/api/play/solver?curves=0');+ expect(res.parsed.assumptions).toEqual(ASSUMPTIONS);+ expect(res.parsed.method.summary).toMatch(/closed-form/i);+ expect(res.parsed.method.source.length).toBeGreaterThanOrEqual(5);+ // The source list has to name real modules, since it is the audit trail for+ // the drift-free claim.+ for (const line of res.parsed.method.source) {+ expect(line).toMatch(/^multiplayer\/src\/[a-z-]+\.js:/);+ }+ });++ it('never recommends a rate the ladder marks unsustainable', async () => {+ for (const level of [1, 50, 99]) {+ const res = await get(`/api/play/solver?level=${level}&curves=0`);+ const cook = res.parsed.activities.find((a) => a.family === 'cook');+ expect(cook.sustainable).toBe(false);+ expect(res.parsed.bestRate.cashPerHour).toBeLessThan(cook.cashPerHour);+ }+ });++ it('moves every headline number when the level moves', async () => {+ const low = (await get('/api/play/solver?level=1&curves=0')).parsed;+ const high = (await get('/api/play/solver?level=90&curves=0')).parsed;+ expect(high.bestRate.cashPerHour).toBeGreaterThan(low.bestRate.cashPerHour);+ expect(high.bestXpRate.xpPerHour).toBeGreaterThan(low.bestXpRate.xpPerHour);+ expect(high.payback[0].minutes).toBeLessThan(low.payback[0].minutes);+ });+});++describe('GET /api/play/solver: caching and transport', () => {+ it('caches hard at the edge, because the body is pure static config', async () => {+ const res = await get('/api/play/solver');+ const cc = res.getHeader('cache-control');+ expect(cc).toMatch(/public/);+ expect(cc).toMatch(/s-maxage=\d+/);+ expect(cc).toMatch(/stale-while-revalidate=\d+/);+ });++ it('answers a CORS preflight and allows cross-origin reads', async () => {+ const res = mockRes();+ await handler(mockReq('/api/play/solver', 'OPTIONS'), res);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ });++ it('rejects a write method', async () => {+ const res = mockRes();+ await handler(mockReq('/api/play/solver', 'POST'), res);+ expect(res.statusCode).toBe(405);+ });++ it('rate limits like any other public endpoint', async () => {+ rlState.success = false;+ const res = await get('/api/play/solver');+ expect(res.statusCode).toBe(429);+ });++ it('serves identical curves across requests, so the cache key stays stable', async () => {+ const a = await get('/api/play/solver?level=1');+ const b = await get('/api/play/solver?level=1');+ expect(a.body).toBe(b.body);+ });+});