Skip to content

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

feat(multiplayer): room rate model

nirholas95d0a10713be
diff --git a/multiplayer/src/activities.js b/multiplayer/src/activities.js
index cb425376e..4431e2ff9 100644
--- a/multiplayer/src/activities.js
+++ b/multiplayer/src/activities.js
@@ -22,7 +22,13 @@ import { treeInRange, rockInRange, firepitInRange, rodPickupInRange } from './wo
// Per-swing cadence on the real clock (ms). The handlers tolerate a profile whose
// `cd` map predates these keys — `now < undefined` is false, so a missing key just
// means "ready now", and the first action arms it.
-export const ACTIVITY_COOLDOWN_MS = { chop: 1300, mine: 1500, cook: 900, pickupRod: 8000 };
+// `fish` lives here too even though WalkRoom owns the cast handler: it is the same
+// kind of number (a per-swing floor on the real clock), and keeping all five in one
+// exported table is what lets rate-model.js compute attempts-per-hour for every
+// gather activity without a second copy of any cadence.
+export const ACTIVITY_COOLDOWN_MS = {
+ chop: 1300, mine: 1500, cook: 900, pickupRod: 8000, fish: 1500,
+};
// The two gather activities differ only in tool, node, resource and the mining-only
// coal bonus — so one config table drives both through the shared core below.
diff --git a/multiplayer/src/rate-model.js b/multiplayer/src/rate-model.js
new file mode 100644
index 000000000..86d112858
--- /dev/null
+++ b/multiplayer/src/rate-model.js
@@ -0,0 +1,671 @@
+// Rate model for the /play coin worlds: the exact expected value of every action
+// the world offers, in closed form.
+//
+// WHY THIS EXISTS
+// Every yield rule in this game is already a pure function of skill level and node
+// tuning (`gatherChance`, `gatherDoubleChance`, `coalBonusChance`, `cookBurnChance`,
+// `fishCatchChance`, `fishDoubleChance` in items.js), and every cadence is a
+// constant (`ACTIVITY_COOLDOWN_MS` in activities.js). That combination means the
+// expected units, cash and XP per hour for any activity at any level are not a
+// thing you have to measure by grinding. They are computable exactly, in one pass,
+// with no simulation and no sampling error.
+//
+// This module does that computation. It imports the same tables the authoritative
+// server rolls against and never restates a number, so the model cannot drift away
+// from the game: change a price in shop.js or a curve in items.js and every rate
+// below moves with it on the next request.
+//
+// EXACTNESS
+// Where the game's XP award wraps a uniform integer roll in Math.round, the naive
+// expectation (substituting the mean of the roll) is wrong, because rounding is not
+// linear. Every expectation here sums over the roll's actual support instead, so the
+// XP numbers are exact rather than approximately right. `tests/rate-model.test.js`
+// pins that claim by replaying the real handler arithmetic under a seeded RNG and
+// checking the closed form falls inside the sampling interval.
+//
+// SCOPE
+// Pure functions over static tables. No room, no profile, no network, no clock. The
+// only modelling assumptions are stated in ASSUMPTIONS below and surfaced verbatim
+// through /api/play/solver, because a rate quoted without its assumptions is a lie.
+
+import { ACTIVITY_COOLDOWN_MS } from './activities.js';
+import {
+ gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,
+ fishCatchChance, fishDoubleChance, itemLabel,
+ MOB_STATS, LOOT_TABLES, ITEMS,
+} from './items.js';
+import { SELL_PRICES, BUY_CATALOG, sellPrice } from './shop.js';
+import { TREES, ROCKS, FISHING_SPOTS } from './world-features.js';
+import { WHEEL_SEGMENTS, FREE_SPIN_COOLDOWN_MS } from './spin-wheel.js';
+import { LEVEL_CAP, xpForLevel, INV_SIZE, MAX_STACK } from './economy.js';
+
+const MS_PER_HOUR = 3_600_000;
+
+// The modelling assumptions, in the order they bite. Published with every result so
+// a reader can see exactly where the numbers stop being a guarantee.
+export const ASSUMPTIONS = [
+ 'Uninterrupted action: the model prices a full hour of swings at the cadence the server enforces, with no walking, no travel between nodes and no downtime.',
+ 'Pack space is available. The real handlers refuse a gather into a full inventory, so a run that never banks or sells will fall short of these rates.',
+ 'Items are valued at the general store sell price. Nothing here is priced against a player market, because the world has no player market.',
+ 'Skill level is held fixed for the hour. In practice XP earned during the hour raises the rate, so a sustained session slightly beats the number shown for its starting level.',
+ 'Mount drops are reported as odds only. They have no sell price, so they never inflate a cash figure.',
+];
+
+// --- exact expectations over the game's own integer rolls ---------------------
+
+// The gather handler awards `Math.round((base + Math.floor(rng() * span) + lvl * 0.3) * mult)`.
+// Math.round is not linear, so E[round(X)] is not round(E[X]): the expectation has
+// to sum over the roll's real support. `span` values are small (5 and 6), so the
+// exact sum is as cheap as the wrong shortcut would have been.
+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;
+}
+
+function round2(n) {
+ return Math.round(n * 100) / 100;
+}
+
+function clampLevel(level) {
+ const lvl = Math.max(1, Math.min(LEVEL_CAP, Math.floor(Number(level) || 1)));
+ return lvl;
+}
+
+// How long an empty pack lasts at a given production rate. The "uninterrupted hour"
+// assumption is the weakest one in the model, so rather than hand-wave it, every row
+// carries the exact hour at which it stops being true. `distinctItems` matters
+// because each item type needs its own stack of slots (mining fills two, wood one).
+function packHours(unitsPerHour, distinctItems) {
+ if (unitsPerHour <= 0) return null;
+ const capacity = (INV_SIZE * MAX_STACK) / Math.max(1, distinctItems);
+ return Math.round((capacity / unitsPerHour) * 100) / 100;
+}
+
+// --- gathering: chop and mine -------------------------------------------------
+
+// Static description of the two gather families, mirroring activities.js's GATHER
+// table. Kept as a lookup rather than duplicated per function so adding a third
+// gather activity upstream is a one-line change here.
+const GATHER_FAMILIES = {
+ chop: {
+ skill: 'woodcutting', tool: 'axe', item: 'wood', nodes: TREES,
+ xpBase: 9, xpSpan: 5, coal: false, verb: 'Chop',
+ },
+ mine: {
+ skill: 'mining', tool: 'pickaxe', item: 'stone', nodes: ROCKS,
+ xpBase: 9, xpSpan: 5, coal: true, verb: 'Mine',
+ },
+};
+
+export function gatherFamilies() {
+ return Object.keys(GATHER_FAMILIES);
+}
+
+// Expected per-hour yield of chopping one tree or mining one rock at `level`.
+//
+// Per attempt the server rolls: a success check at `gatherChance`, then a double
+// check at `gatherDoubleChance`, then (mining only) an independent coal check at
+// `coalBonusChance`. A failed swing still pays 2 XP, which is why the XP rate is
+// never zero even on a brutally difficult node.
+export function gatherRate(family, level, node) {
+ const cfg = GATHER_FAMILIES[family];
+ if (!cfg) throw new Error(`unknown gather family: ${family}`);
+ const lvl = clampLevel(level);
+ const difficulty = node.difficulty || 1;
+ const cooldownMs = ACTIVITY_COOLDOWN_MS[family];
+ const attemptsPerHour = MS_PER_HOUR / cooldownMs;
+
+ const success = gatherChance(lvl, difficulty);
+ const double = gatherDoubleChance(lvl, difficulty);
+ const unitsPerSuccess = 1 + double;
+ const unitsPerHour = attemptsPerHour * success * unitsPerSuccess;
+
+ // Coal rides on a successful strike only, so its rate carries the success factor.
+ const coalChance = cfg.coal ? coalBonusChance(lvl, node.coal || 1) : 0;
+ const coalPerHour = attemptsPerHour * success * coalChance;
+
+ // XP: 2 on a miss, the rounded roll times the units on a hit, plus a flat 6 for
+ // a coal bonus that actually landed.
+ const xpPerSuccessUnit = expectedRoundedXp(cfg.xpBase, cfg.xpSpan, lvl, difficulty);
+ const xpPerHour = attemptsPerHour * (
+ (1 - success) * 2
+ + success * (xpPerSuccessUnit * unitsPerSuccess + coalChance * 6)
+ );
+
+ const cashPerHour = unitsPerHour * sellPrice(cfg.item) + coalPerHour * sellPrice('coal');
+
+ return {
+ key: `${family}:${node.id}`,
+ family,
+ skill: cfg.skill,
+ tool: cfg.tool,
+ item: cfg.item,
+ label: `${cfg.verb} ${node.id}`,
+ node: { id: node.id, difficulty, coalWeight: cfg.coal ? (node.coal || 1) : null },
+ level: lvl,
+ cadenceMs: cooldownMs,
+ attemptsPerHour: round2(attemptsPerHour),
+ successPct: round2(success * 100),
+ doublePct: round2(double * 100),
+ coalPct: cfg.coal ? round2(coalChance * 100) : null,
+ unitsPerHour: round2(unitsPerHour),
+ coalPerHour: cfg.coal ? round2(coalPerHour) : null,
+ cashPerHour: round2(cashPerHour),
+ xpPerHour: round2(xpPerHour),
+ // A gather node produces from the world, so its rate stands on its own.
+ sustainable: true,
+ requires: null,
+ packHours: packHours(unitsPerHour + coalPerHour, cfg.coal ? 2 : 1),
+ };
+}
+
+// --- fishing ------------------------------------------------------------------
+
+// Expected per-hour yield of casting at one pond. Same shape as gatherRate, but the
+// catch curve is scaled by the spot's `quality` multiplier rather than divided by a
+// difficulty, so richer water is strictly better on both axes.
+export function fishRate(level, spot) {
+ const lvl = clampLevel(level);
+ const quality = spot.quality || 1;
+ const cooldownMs = ACTIVITY_COOLDOWN_MS.fish;
+ const attemptsPerHour = MS_PER_HOUR / cooldownMs;
+
+ const success = fishCatchChance(lvl, quality);
+ const double = fishDoubleChance(lvl, quality);
+ const perSuccess = 1 + double;
+ const unitsPerHour = attemptsPerHour * success * perSuccess;
+
+ const xpPerSuccessUnit = expectedRoundedXp(10, 6, lvl, quality);
+ const xpPerHour = attemptsPerHour * ((1 - success) * 2 + success * xpPerSuccessUnit * perSuccess);
+
+ return {
+ key: `fish:${spot.id}`,
+ family: 'fish',
+ skill: 'fishing',
+ tool: 'rod',
+ item: 'fish',
+ label: `Fish ${spot.id}`,
+ node: { id: spot.id, quality },
+ level: lvl,
+ cadenceMs: cooldownMs,
+ attemptsPerHour: round2(attemptsPerHour),
+ successPct: round2(success * 100),
+ doublePct: round2(double * 100),
+ coalPct: null,
+ unitsPerHour: round2(unitsPerHour),
+ coalPerHour: null,
+ cashPerHour: round2(unitsPerHour * sellPrice('fish')),
+ xpPerHour: round2(xpPerHour),
+ sustainable: true,
+ requires: null,
+ packHours: packHours(unitsPerHour, 1),
+ };
+}
+
+// --- cooking ------------------------------------------------------------------
+
+// Cooking is a converter, not a producer: every attempt burns one raw fish whether
+// or not it succeeds, and pays out a cooked fish on the non-burn branch. So its
+// standalone "cash per hour" is a VALUE-ADD rate (what the conversion earns over
+// simply selling the raw fish), and it is only reachable if something upstream is
+// supplying fish at that pace. `fishCookLoop` below solves for that honestly.
+export function cookRate(level) {
+ const lvl = clampLevel(level);
+ const cooldownMs = ACTIVITY_COOLDOWN_MS.cook;
+ const attemptsPerHour = MS_PER_HOUR / cooldownMs;
+ const burn = cookBurnChance(lvl);
+ const cookedPerHour = attemptsPerHour * (1 - burn);
+
+ // 14 + floor(rng()*5) has an exact mean of 16; the level term is floored once,
+ // outside the roll, so it is not part of the expectation.
+ const xpPerCook = 16 + Math.floor(lvl * 0.3);
+ const xpPerHour = attemptsPerHour * (burn * 3 + (1 - burn) * xpPerCook);
+
+ const valueAddPerAttempt = (1 - burn) * sellPrice('cookedFish') - sellPrice('fish');
+
+ return {
+ key: 'cook:firepit',
+ family: 'cook',
+ skill: 'cooking',
+ tool: null,
+ item: 'cookedFish',
+ label: 'Cook at a roast pit',
+ node: { id: 'firepit', difficulty: 1 },
+ level: lvl,
+ cadenceMs: cooldownMs,
+ attemptsPerHour: round2(attemptsPerHour),
+ successPct: round2((1 - burn) * 100),
+ burnPct: round2(burn * 100),
+ doublePct: 0,
+ coalPct: null,
+ unitsPerHour: round2(cookedPerHour),
+ coalPerHour: null,
+ fishConsumedPerHour: round2(attemptsPerHour),
+ cashPerHour: round2(attemptsPerHour * valueAddPerAttempt),
+ xpPerHour: round2(xpPerHour),
+ // Cooking consumes a raw fish per attempt, so this rate is a CEILING that
+ // assumes a supply nobody can actually deliver while also standing at the
+ // fire. It is excluded from every ranking and from payback for exactly that
+ // reason; `fishCookLoop` is the honest, self-supplied version of this row.
+ sustainable: false,
+ requires: `${round2(attemptsPerHour)} raw fish per hour, which no single player can catch and cook at the same time`,
+ packHours: packHours(cookedPerHour, 1),
+ };
+}
+
+// --- the fish-and-cook loop ---------------------------------------------------
+
+// The single most valuable thing this model computes, because it is the one number
+// a player cannot eyeball: cooking pays three times what raw fish pays, but you
+// cannot cook and fish at the same time, so the real question is how to SPLIT an
+// hour between the two.
+//
+// Let R be fish caught per hour of pure fishing and C attempts per hour of pure
+// cooking. Spending fraction t of the hour fishing produces t*R fish and consumes
+// (1 - t)*C. Supply meets demand at t = C / (R + C), and at that split nothing
+// queues and nothing idles. Everything else follows.
+export function fishCookLoop(fishingLevel, cookingLevel, spot) {
+ const fish = fishRate(fishingLevel, spot);
+ const cook = cookRate(cookingLevel);
+
+ const R = fish.unitsPerHour;
+ const C = cook.attemptsPerHour;
+ const fishShare = C / (R + C);
+ const cookShare = 1 - fishShare;
+
+ const fishPerHour = fishShare * R;
+ const cookedPerHour = fishPerHour * (1 - cookBurnChance(clampLevel(cookingLevel)));
+ const cashPerHour = cookedPerHour * sellPrice('cookedFish');
+
+ // The honest comparison: the same hour spent fishing only and selling raw.
+ const rawOnlyCashPerHour = fish.cashPerHour;
+ const xpPerHour = fishShare * fish.xpPerHour + cookShare * cook.xpPerHour;
+
+ return {
+ key: 'loop:fish-cook',
+ family: 'loop',
+ label: `Fish ${spot.id} and cook`,
+ spot: { id: spot.id, quality: spot.quality || 1 },
+ fishingLevel: clampLevel(fishingLevel),
+ cookingLevel: clampLevel(cookingLevel),
+ fishSharePct: round2(fishShare * 100),
+ cookSharePct: round2(cookShare * 100),
+ fishPerHour: round2(fishPerHour),
+ cookedPerHour: round2(cookedPerHour),
+ cashPerHour: round2(cashPerHour),
+ rawOnlyCashPerHour: round2(rawOnlyCashPerHour),
+ upliftPct: rawOnlyCashPerHour > 0
+ ? round2(((cashPerHour - rawOnlyCashPerHour) / rawOnlyCashPerHour) * 100)
+ : 0,
+ xpPerHour: round2(xpPerHour),
+ // Self-supplied by construction: the split is chosen so nothing queues.
+ sustainable: true,
+ requires: null,
+ packHours: packHours(cookedPerHour, 1),
+ };
+}
+
+// --- combat -------------------------------------------------------------------
+
+// Expected cash from one kill: the mob's flat gold plus every loot line valued at
+// its sell price. Each loot entry is an INDEPENDENT roll (see rollLoot), so the
+// expectations add without any inclusion-exclusion correction. Quantities are
+// uniform over [min, max], so their mean is the midpoint.
+export function combatValue(kind) {
+ const stats = MOB_STATS[kind];
+ const table = LOOT_TABLES[kind];
+ if (!stats || !table) throw new Error(`unknown mob: ${kind}`);
+
+ let lootCash = 0;
+ const drops = [];
+ let mountPct = 0;
+ for (const entry of table) {
+ const min = entry.min ?? 1;
+ const max = entry.max ?? min;
+ const meanQty = (min + max) / 2;
+ const unit = sellPrice(entry.item);
+ const cash = entry.chance * meanQty * unit;
+ lootCash += cash;
+ if (ITEMS[entry.item]?.mount) mountPct += entry.chance * 100;
+ drops.push({
+ item: entry.item,
+ label: itemLabel(entry.item),
+ chancePct: round2(entry.chance * 100),
+ meanQty: round2(meanQty),
+ unitPrice: unit,
+ expectedCash: round2(cash),
+ mount: !!ITEMS[entry.item]?.mount,
+ });
+ }
+
+ const totalCash = stats.gold + lootCash;
+ return {
+ kind,
+ label: kind.charAt(0).toUpperCase() + kind.slice(1),
+ hp: stats.hp,
+ damage: stats.dmg,
+ hostile: stats.hostile !== false,
+ xp: stats.xp,
+ gold: stats.gold,
+ lootCash: round2(lootCash),
+ totalCash: round2(totalCash),
+ cashPerHp: stats.hp > 0 ? round2(totalCash / stats.hp) : 0,
+ xpPerHp: stats.hp > 0 ? round2(stats.xp / stats.hp) : 0,
+ mountPct: round2(mountPct),
+ drops: drops.sort((a, b) => b.expectedCash - a.expectedCash || b.chancePct - a.chancePct),
+ };
+}
+
+export function combatLadder() {
+ return Object.keys(MOB_STATS).map(combatValue).sort((a, b) => b.totalCash - a.totalCash);
+}
+
+// --- the wheel ----------------------------------------------------------------
+
+// Fortune's Folly in store-price terms. The wedges are uniform by design (see the
+// header note in spin-wheel.js), but this sums each wedge's own declared oddsPct
+// rather than assuming 1/n, so a future re-weighting stays correct here for free.
+export function wheelValue() {
+ const total = WHEEL_SEGMENTS.reduce((sum, s) => sum + s.oddsPct, 0);
+ const valued = WHEEL_SEGMENTS.map((seg) => ({
+ seg,
+ p: seg.oddsPct / total,
+ value: seg.kind === 'gold' ? seg.gold : seg.qty * sellPrice(seg.item),
+ }));
+
+ const ev = valued.reduce((sum, v) => sum + v.p * v.value, 0);
+ const variance = valued.reduce((sum, v) => sum + v.p * (v.value - ev) ** 2, 0);
+ const values = valued.map((v) => v.value);
+
+ // A free spin every 12 hours is 2 per day, so the free lane's daily worth is
+ // exact rather than a rule of thumb.
+ const freeSpinsPerDay = 24 / (FREE_SPIN_COOLDOWN_MS / MS_PER_HOUR);
+
+ return {
+ wedges: WHEEL_SEGMENTS.length,
+ evCash: round2(ev),
+ stdevCash: round2(Math.sqrt(variance)),
+ bestCash: Math.max(...values),
+ worstCash: Math.min(...values),
+ freeSpinsPerDay: round2(freeSpinsPerDay),
+ evPerDayCash: round2(ev * freeSpinsPerDay),
+ // Odds of landing at or above the mean, which is what "did I do well" means
+ // on a table this skewed by one jackpot wedge.
+ aboveEvPct: round2(valued.filter((v) => v.value >= ev).reduce((s, v) => s + v.p, 0) * 100),
+ };
+}
+
+// --- ladders, payback and break-even -----------------------------------------
+
+// Every gatherable node in the world, priced at one level and ranked by cash. This
+// is what answers "which rock should I actually stand at", a question the world
+// gives no in-game way to settle: rock-4 is the hardest to crack but has the
+// richest coal seam, and only the arithmetic says which effect wins.
+export function activityLadder(level) {
+ const lvl = clampLevel(level);
+ const rows = [
+ ...TREES.map((t) => gatherRate('chop', lvl, t)),
+ ...ROCKS.map((r) => gatherRate('mine', lvl, r)),
+ ...FISHING_SPOTS.map((s) => fishRate(lvl, s)),
+ cookRate(lvl),
+ ];
+ // Unsustainable rows (cooking, which needs a fish supply) always sort last, no
+ // matter how large their ceiling is. Ranking a rate nobody can hold above one
+ // anybody can would make the whole table advice you cannot follow.
+ return rows.sort((a, b) => {
+ if (a.sustainable !== b.sustainable) return a.sustainable ? -1 : 1;
+ return b.cashPerHour - a.cashPerHour;
+ });
+}
+
+// The best node per family at a level, keyed by family.
+export function bestPerFamily(level) {
+ const out = {};
+ for (const row of activityLadder(level)) {
+ if (!out[row.family] || row.cashPerHour > out[row.family].cashPerHour) out[row.family] = row;
+ }
+ return out;
+}
+
+// The highest cash rate a player can actually hold at this level, and the highest XP
+// rate, considered separately because they are rarely the same activity.
+export function sustainableBest(level) {
+ const lvl = clampLevel(level);
+ const rows = activityLadder(lvl).filter((r) => r.sustainable);
+ rows.push(fishCookLoop(lvl, lvl, bestFishingSpot()));
+ const cash = rows.reduce((a, b) => (b.cashPerHour > a.cashPerHour ? b : a));
+ const xp = rows.reduce((a, b) => (b.xpPerHour > a.xpPerHour ? b : a));
+ return { cash, xp };
+}
+
+// How long the store's catalog takes to afford at a given cash rate, in the units a
+// player actually thinks in: minutes, and swings.
+export function catalogPayback(cashPerHour, attemptsPerHour) {
+ return BUY_CATALOG.map((entry) => {
+ const hours = cashPerHour > 0 ? entry.price / cashPerHour : Infinity;
+ return {
+ item: entry.item,
+ label: itemLabel(entry.item),
+ qty: entry.qty,
+ price: entry.price,
+ unitPrice: round2(entry.price / entry.qty),
+ hours: Number.isFinite(hours) ? Math.round(hours * 1000) / 1000 : null,
+ minutes: round2(hours * 60),
+ attempts: Number.isFinite(hours) ? Math.ceil(hours * attemptsPerHour) : null,
+ };
+ }).sort((a, b) => a.minutes - b.minutes);
+}
+
+// The level at which one activity's cash rate overtakes another's, or null if it
+// never does inside the level cap. Scanning every level is exact and costs nothing,
+// so there is no reason to approximate it with a solved inequality that would go
+// stale the moment a curve upstream changes shape.
+export function breakEvenLevel(rateA, rateB) {
+ let previous = null;
+ for (let lvl = 1; lvl <= LEVEL_CAP; lvl += 1) {
+ const ahead = rateA(lvl).cashPerHour > rateB(lvl).cashPerHour;
+ if (previous !== null && ahead !== previous) return lvl;
+ previous = ahead;
+ }
+ return null;
+}
+
+// Hours of a given XP rate to climb from one level to the next.
+export function timeToLevel(fromLevel, toLevel, xpPerHour) {
+ const from = clampLevel(fromLevel);
+ const to = clampLevel(toLevel);
+ if (to <= from || xpPerHour <= 0) return null;
+ const xp = xpForLevel(to) - xpForLevel(from);
+ // Early levels take well under a minute at the top rates, so two decimal places on
+ // `hours` would round most of the curve to zero. Minutes stay at two, which is the
+ // precision a reader can actually use.
+ const hours = xp / xpPerHour;
+ return { xp, hours: Math.round(hours * 10000) / 10000, minutes: round2(hours * 60) };
+}
+
+// A cash-per-hour and xp-per-hour curve across every level, for one activity. Emitted
+// as parallel arrays so the whole 99-level sweep for every node in the world stays
+// small enough to ship in one response and drive an instant client-side slider.
+export function levelCurve(builder) {
+ const cash = [];
+ const xp = [];
+ for (let lvl = 1; lvl <= LEVEL_CAP; lvl += 1) {
+ const r = builder(lvl);
+ cash.push(Math.round(r.cashPerHour * 10) / 10);
+ xp.push(Math.round(r.xpPerHour * 10) / 10);
+ }
+ return { cash, xp };
+}
+
+// Every curve the world has, keyed the same way activityLadder keys its rows, so a
+// client can join the two without a lookup table of its own.
+export function allCurves() {
+ const series = [];
+ for (const tree of TREES) {
+ series.push({ key: `chop:${tree.id}`, family: 'chop', label: `Chop ${tree.id}`, ...levelCurve((l) => gatherRate('chop', l, tree)) });
+ }
+ for (const rock of ROCKS) {
+ series.push({ key: `mine:${rock.id}`, family: 'mine', label: `Mine ${rock.id}`, ...levelCurve((l) => gatherRate('mine', l, rock)) });
+ }
+ for (const spot of FISHING_SPOTS) {
+ series.push({ key: `fish:${spot.id}`, family: 'fish', label: `Fish ${spot.id}`, ...levelCurve((l) => fishRate(l, spot)) });
+ }
+ series.push({ key: 'cook:firepit', family: 'cook', label: 'Cook at a roast pit', ...levelCurve(cookRate) });
+ series.push({
+ key: 'loop:fish-cook',
+ family: 'loop',
+ label: 'Fish and cook loop',
+ ...levelCurve((l) => fishCookLoop(l, l, bestFishingSpot())),
+ });
+ return series;
+}
+
+// The pond with the highest quality multiplier. Quality raises both catch rate and
+// double-haul odds, so it dominates at every level and there is no crossover to hunt.
+export function bestFishingSpot() {
+ return FISHING_SPOTS.reduce((best, s) => ((s.quality || 1) > (best.quality || 1) ? s : best), FISHING_SPOTS[0]);
+}
+
+// --- derived findings ---------------------------------------------------------
+
+// Conclusions the arithmetic reaches on its own. Every string below is assembled
+// from numbers computed above, never asserted: if the tuning upstream changes so a
+// finding stops being true, the finding stops being emitted rather than going
+// quietly stale. This is the part a wiki cannot keep honest.
+export function findings(level) {
+ const lvl = clampLevel(level);
+ const ladder = activityLadder(lvl);
+ const out = [];
+
+ // 1. Within a family, does the tougher node actually pay? Nodes advertise their
+ // difficulty through slower yields and (for rock) a richer coal seam, and only
+ // the arithmetic settles whether the trade is worth taking.
+ for (const family of ['chop', 'mine']) {
+ const rows = ladder.filter((r) => r.family === family);
+ if (rows.length < 2) continue;
+ const easiest = rows.reduce((a, b) => (b.node.difficulty < a.node.difficulty ? b : a));
+ const hardest = rows.reduce((a, b) => (b.node.difficulty > a.node.difficulty ? b : a));
+ if (hardest.node.difficulty === easiest.node.difficulty) continue;
+ const better = hardest.cashPerHour > easiest.cashPerHour;
+ const gapPct = round2(Math.abs(hardest.cashPerHour - easiest.cashPerHour) / easiest.cashPerHour * 100);
+ out.push({
+ id: `node-tradeoff:${family}`,
+ kind: better ? 'reward' : 'trap',
+ title: better
+ ? `The hardest ${family === 'chop' ? 'tree' : 'rock'} is worth the extra swings`
+ : `The hardest ${family === 'chop' ? 'tree' : 'rock'} is not worth standing at`,
+ detail: better
+ ? `${hardest.node.id} (difficulty ${hardest.node.difficulty}) pays ${hardest.cashPerHour} cash per hour against ${easiest.node.id}'s ${easiest.cashPerHour}, so the tougher node clears its own penalty by ${gapPct}%.`
+ : `${hardest.node.id} (difficulty ${hardest.node.difficulty}) pays ${hardest.cashPerHour} cash per hour, ${gapPct}% BELOW ${easiest.node.id} at ${easiest.cashPerHour}. Its richer yield does not cover the slower success rate, so the easy node wins outright.`,
+ nodes: [easiest.node.id, hardest.node.id],
+ });
+ }
+
+ // 2. Cooking's uplift over selling raw, at the split that keeps both sides busy.
+ const loop = fishCookLoop(lvl, lvl, bestFishingSpot());
+ out.push({
+ id: 'cook-uplift',
+ kind: loop.upliftPct > 0 ? 'reward' : 'trap',
+ title: loop.upliftPct > 0
+ ? `Cooking beats selling raw by ${loop.upliftPct}%`
+ : 'Cooking does not pay at this level',
+ detail: `Splitting the hour ${loop.fishSharePct}% fishing and ${loop.cookSharePct}% cooking keeps both sides fed and earns ${loop.cashPerHour} cash per hour, against ${loop.rawOnlyCashPerHour} for an hour of pure fishing sold raw. At cooking level ${lvl} the burn rate is ${round2(cookBurnChance(lvl) * 100)}%, which is already priced into that figure.`,
+ });
+
+ // 3. What the store's whole catalog costs in playtime. When this collapses to a
+ // couple of minutes it is a balance signal, not a compliment, so say which it is.
+ const { cash: bestRow } = sustainableBest(lvl);
+ const catalogCost = BUY_CATALOG.reduce((sum, e) => sum + e.price, 0);
+ const catalogMinutes = bestRow.cashPerHour > 0 ? round2((catalogCost / bestRow.cashPerHour) * 60) : null;
+ if (catalogMinutes !== null) {
+ out.push({
+ id: 'catalog-cost',
+ kind: catalogMinutes < 15 ? 'trap' : 'reward',
+ title: catalogMinutes < 15
+ ? `The entire store is ${catalogMinutes} minutes of play`
+ : `Clearing the store takes ${catalogMinutes} minutes`,
+ detail: `Every one of the ${BUY_CATALOG.length} catalog entries bought once costs ${catalogCost} cash. At the best sustainable rate for level ${lvl} (${bestRow.label}, ${bestRow.cashPerHour} per hour) that is ${catalogMinutes} minutes.${catalogMinutes < 15 ? ' Cash stops being a constraint almost immediately, so the store is a convenience rather than a goal.' : ''}`,
+ });
+ }
+
+ // 4. The free spin, priced in the only unit that means anything: playtime.
+ const wheel = wheelValue();
+ const spinMinutes = bestRow.cashPerHour > 0 ? round2((wheel.evCash / bestRow.cashPerHour) * 60) : null;
+ out.push({
+ id: 'wheel-worth',
+ kind: 'context',
+ title: `A free spin is worth ${wheel.evCash} cash on average`,
+ detail: `Valuing every wedge at its store price, the wheel returns ${wheel.evCash} cash per spin with a standard deviation of ${wheel.stdevCash}, driven almost entirely by the single ${wheel.bestCash}-cash jackpot wedge. Only ${wheel.aboveEvPct}% of outcomes land at or above the average. Two free spins a day come to ${wheel.evPerDayCash} cash, or about ${spinMinutes} minutes of ${bestRow.label.toLowerCase()}.`,
+ });
+
+ // 5. Combat measured against gathering, per hour is impossible to state honestly
+ // (kill speed depends on weapon, aim and respawn), so state it per kill and let
+ // the reader supply their own kill rate.
+ const troll = combatValue('troll');
+ const killsPerHourToMatch = troll.totalCash > 0
+ ? round2(bestRow.cashPerHour / troll.totalCash)
+ : null;
+ out.push({
+ id: 'combat-vs-gathering',
+ kind: 'context',
+ title: `Combat needs ${killsPerHourToMatch} troll kills an hour to match gathering`,
+ detail: `A troll is the richest kill in the world at ${troll.totalCash} expected cash (${troll.gold} flat plus ${troll.lootCash} of loot at store prices) and ${troll.xp} combat XP, with a ${troll.mountPct}% chance of a mount. To earn what ${bestRow.label.toLowerCase()} earns you would need ${killsPerHourToMatch} of them per hour, one every ${round2(3600 / killsPerHourToMatch)} seconds, through ${troll.hp} HP each.`,
+ });
+
+ return out;
+}
+
+// The full model at one level. This is the shape /api/play/solver serves.
+export function solveAt(level) {
+ const lvl = clampLevel(level);
+ const ladder = activityLadder(lvl);
+ const best = bestPerFamily(lvl);
+ const spot = bestFishingSpot();
+ const loop = fishCookLoop(lvl, lvl, spot);
+
+ // Payback is quoted against the best cash rate a player can actually HOLD, which
+ // deliberately excludes cooking's supply-fed ceiling. Quoting payback against a
+ // rate nobody can sustain would make every price in the store look free.
+ const { cash: topCashRow, xp: topXpRow } = sustainableBest(lvl);
+ const topCash = topCashRow.cashPerHour;
+ const topAttempts = topCashRow.family === 'loop'
+ ? best.fish.attemptsPerHour
+ : topCashRow.attemptsPerHour;
+
+ const wheel = wheelValue();
+
+ return {
+ level: lvl,
+ levelCap: LEVEL_CAP,
+ assumptions: ASSUMPTIONS,
+ cadenceMs: { ...ACTIVITY_COOLDOWN_MS },
+ sellPrices: { ...SELL_PRICES },
+ activities: ladder,
+ best,
+ loop,
+ bestRate: {
+ label: topCashRow.label,
+ key: topCashRow.key,
+ cashPerHour: round2(topCash),
+ attemptsPerHour: topAttempts,
+ },
+ bestXpRate: { label: topXpRow.label, key: topXpRow.key, xpPerHour: topXpRow.xpPerHour },
+ findings: findings(lvl),
+ payback: catalogPayback(topCash, topAttempts),
+ wheel: {
+ ...wheel,
+ // A free spin's worth expressed in the only currency a player has intuition
+ // for: how long they would have had to swing for the same cash.
+ minutesOfBestRate: topCash > 0 ? round2((wheel.evCash / topCash) * 60) : null,
+ },
+ combat: combatLadder(),
+ nextLevel: lvl < LEVEL_CAP
+ ? {
+ level: lvl + 1,
+ ...timeToLevel(lvl, lvl + 1, topXpRow.xpPerHour),
+ via: topXpRow.label,
+ }
+ : null,
+ };
+}
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 6d8b8b7ac..58b849ace 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -63,7 +63,7 @@ import {
fishingSpotInRange, treeInRange, rockInRange, firepitInRange,
DANGER_ZONES, SPAWN_POINT, dangerZoneAt, isSafeZone, isDangerZone, randomPointInZone,
} from '../world-features.js';
-import { registerActivityHandlers } from '../activities.js';
+import { registerActivityHandlers, ACTIVITY_COOLDOWN_MS } from '../activities.js';
import { registerSpinHandlers } from '../spin-wheel.js';
import {
selectTarget, rollDamage, applyDamage, addHeat, decayHeat, heatStars,
@@ -265,11 +265,11 @@ const MOTION_VALUES = new Set(['idle', 'walk', 'run']);
// them in this free-roam world — so they live off the synced WalkState schema
// (kept in this.econ) and stream to the owning client via targeted messages.
// This keeps the shared /walk schema untouched and peers' wire cost at zero.
-const FISH_COOLDOWN_MS = 1500; // per-cast reel time (cadence on the real clock)
-const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spam
-const CHOP_COOLDOWN_MS = 1300; // per-swing axe cadence
-const MINE_COOLDOWN_MS = 1500; // per-strike pickaxe cadence (ore is slower)
-const COOK_COOLDOWN_MS = 900; // pace between fish on the fire
+// Per-cast reel time. Read from the shared cadence table in activities.js (which the
+// chop/mine/cook handlers already arm from) so there is exactly one copy of every
+// gather cadence in the codebase.
+const FISH_COOLDOWN_MS = ACTIVITY_COOLDOWN_MS.fish;
+const CONSUME_COOLDOWN_MS = 1100; // pace between bites, no instant heal-spam
// Per-action rate ceilings (messages/sec/client) — a flooding client is dropped.
// vsync rides at the same 15Hz the move netcode uses; allow 2× for jitter, like
// MOVES_PER_SEC_LIMIT. enter/exit are deliberate, rare actions.
diff --git a/tests/rate-model.test.js b/tests/rate-model.test.js
new file mode 100644
index 000000000..5a4401480
--- /dev/null
+++ b/tests/rate-model.test.js
@@ -0,0 +1,510 @@
+// Tests for multiplayer/src/rate-model.js, the closed-form economic model of the
+// /play coin worlds.
+//
+// The model makes an unusually strong claim: that its rates are EXACT, not
+// estimated. A test that re-derived the same formula would be worthless here, since
+// it would agree with the model even when both were wrong. So the central tests
+// below drive the REAL production handlers (`handleGather`, `handleCook` from
+// activities.js) against a seeded RNG for tens of thousands of swings and check that
+// the observed mean lands inside the sampling interval around the closed form.
+//
+// That makes the simulation 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. If someone changes a handler without changing the model, or
+// a curve without changing the handler, this goes red.
+//
+// The remaining tests pin structural invariants (odds sum to one, unsustainable
+// rates never win a ranking) that a sampling test cannot see.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+import {
+ gatherRate, fishRate, cookRate, fishCookLoop, combatValue, wheelValue,
+ activityLadder, sustainableBest, catalogPayback, breakEvenLevel, timeToLevel,
+ allCurves, solveAt, findings, bestFishingSpot, ASSUMPTIONS,
+} from '../multiplayer/src/rate-model.js';
+import { handleGather, handleCook, ACTIVITY_COOLDOWN_MS } from '../multiplayer/src/activities.js';
+import { newProfile, addItem, LEVEL_CAP } from '../multiplayer/src/economy.js';
+import { TREES, ROCKS, FISHING_SPOTS } from '../multiplayer/src/world-features.js';
+import { SELL_PRICES, BUY_CATALOG } from '../multiplayer/src/shop.js';
+import { WHEEL_SEGMENTS } from '../multiplayer/src/spin-wheel.js';
+import { MOB_STATS, LOOT_TABLES } from '../multiplayer/src/items.js';
+
+// mulberry32: a small, fast, well-distributed PRNG. Seeded so a failure is
+// reproducible rather than a flake somebody reruns until it passes.
+function seededRandom(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6D2B79F5) >>> 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// A room stub exposing exactly the surface the activity handlers reach for. Nothing
+// is faked about the economics: addItem, the probability rolls and the XP arithmetic
+// all run the real code. Only the transport (client.send) and persistence are inert.
+function stubRoom(profile, sessionId = 's1') {
+ const observed = { xp: 0, notices: [] };
+ const room = {
+ state: { players: new Map([[sessionId, { x: 0, z: 0 }]]) },
+ econ: new Map([[sessionId, profile]]),
+ _actionOk: () => true,
+ _grantXp: (_client, _profile, _skill, amount) => { observed.xp += amount; },
+ _sendInv: () => {},
+ _persistEcon: () => {},
+ _questEvent: () => {},
+ };
+ const client = { sessionId, send: (kind, payload) => observed.notices.push({ kind, ...payload }) };
+ return { room, client, observed };
+}
+
+// Put the player on top of a node so the handler's range check passes, and equip the
+// tool the activity demands. The starter hotbar is [rod, axe, pickaxe, sword, pistol].
+const TOOL_SLOT = { chop: 1, mine: 2 };
+
+function countOf(profile, item) {
+ let n = 0;
+ for (const slot of profile.inv) if (slot.item === item) n += slot.qty;
+ for (const slot of profile.hotbar) if (slot.item === item) n += slot.qty;
+ return n;
+}
+
+// Run `attempts` real gather swings and report the observed per-attempt means.
+function simulateGather(family, level, node, attempts, seed) {
+ const profile = newProfile('sim');
+ profile.levels.woodcutting = level;
+ profile.levels.mining = level;
+ profile.activeSlot = TOOL_SLOT[family];
+ const { room, client, observed } = stubRoom(profile);
+ room.state.players.get('s1').x = node.x;
+ room.state.players.get('s1').z = node.z;
+
+ const rng = seededRandom(seed);
+ const spy = vi.spyOn(Math, 'random').mockImplementation(rng);
+ try {
+ for (let i = 0; i < attempts; i += 1) {
+ // The pack is emptied every swing so a full inventory never truncates a
+ // yield: the model documents "pack space is available" as an assumption,
+ // and the simulation has to honour the same assumption to be comparable.
+ profile.inv = profile.inv.map(() => ({ item: '', qty: 0 }));
+ handleGather(room, client, family);
+ const item = family === 'chop' ? 'wood' : 'stone';
+ observed.units = (observed.units || 0) + countOf(profile, item);
+ observed.coal = (observed.coal || 0) + countOf(profile, 'coal');
+ }
+ } finally {
+ spy.mockRestore();
+ }
+ return {
+ unitsPerAttempt: (observed.units || 0) / attempts,
+ coalPerAttempt: (observed.coal || 0) / attempts,
+ xpPerAttempt: observed.xp / attempts,
+ };
+}
+
+function simulateCook(level, attempts, seed) {
+ const profile = newProfile('sim');
+ profile.levels.cooking = level;
+ const { room, client, observed } = stubRoom(profile);
+ // Firepits sit at fixed world coordinates; stand on the first one.
+ const rng = seededRandom(seed);
+ const spy = vi.spyOn(Math, 'random').mockImplementation(rng);
+ let cooked = 0;
+ try {
+ for (let i = 0; i < attempts; i += 1) {
+ profile.inv = profile.inv.map(() => ({ item: '', qty: 0 }));
+ addItem(profile, 'fish', 1);
+ handleCook(room, client);
+ cooked += countOf(profile, 'cookedFish');
+ }
+ } finally {
+ spy.mockRestore();
+ }
+ return { cookedPerAttempt: cooked / attempts, xpPerAttempt: observed.xp / attempts };
+}
+
+describe('rate-model: the closed form matches the real handlers', () => {
+ // 40k swings puts the standard error on a Bernoulli mean near 0.0025, so a 3%
+ // relative tolerance is several standard errors wide: comfortably immune to
+ // sampling noise, and far too tight to survive an actual formula error.
+ const ATTEMPTS = 40_000;
+ const TOLERANCE = 0.03;
+
+ it.each([
+ ['chop', 1],
+ ['chop', 42],
+ ['mine', 1],
+ ['mine', 42],
+ ])('%s at level %i matches a seeded simulation of the production handler', (family, level) => {
+ const node = family === 'chop' ? TREES[0] : ROCKS[0];
+ const model = gatherRate(family, level, node);
+ const sim = simulateGather(family, level, node, ATTEMPTS, 0xC0FFEE + level);
+
+ const modelUnitsPerAttempt = model.unitsPerHour / model.attemptsPerHour;
+ const modelXpPerAttempt = model.xpPerHour / model.attemptsPerHour;
+
+ expect(sim.unitsPerAttempt).toBeGreaterThan(modelUnitsPerAttempt * (1 - TOLERANCE));
+ expect(sim.unitsPerAttempt).toBeLessThan(modelUnitsPerAttempt * (1 + TOLERANCE));
+ expect(sim.xpPerAttempt).toBeGreaterThan(modelXpPerAttempt * (1 - TOLERANCE));
+ expect(sim.xpPerAttempt).toBeLessThan(modelXpPerAttempt * (1 + TOLERANCE));
+ });
+
+ it('models the mining coal bonus at the rate the handler actually rolls it', () => {
+ const node = ROCKS[3]; // the richest coal seam, so the bonus is far from zero
+ const model = gatherRate('mine', 30, node);
+ const sim = simulateGather('mine', 30, node, ATTEMPTS, 0xBEEF);
+ const modelCoalPerAttempt = model.coalPerHour / model.attemptsPerHour;
+
+ expect(modelCoalPerAttempt).toBeGreaterThan(0);
+ expect(sim.coalPerAttempt).toBeGreaterThan(modelCoalPerAttempt * (1 - TOLERANCE));
+ expect(sim.coalPerAttempt).toBeLessThan(modelCoalPerAttempt * (1 + TOLERANCE));
+ });
+
+ it.each([1, 25])('cooking at level %i matches the handler burn rate and XP', (level) => {
+ const model = cookRate(level);
+ const sim = simulateCook(level, ATTEMPTS, 0xFEED + level);
+ const modelCookedPerAttempt = model.unitsPerHour / model.attemptsPerHour;
+ const modelXpPerAttempt = model.xpPerHour / model.attemptsPerHour;
+
+ expect(sim.cookedPerAttempt).toBeGreaterThan(modelCookedPerAttempt * (1 - TOLERANCE));
+ expect(sim.cookedPerAttempt).toBeLessThan(modelCookedPerAttempt * (1 + TOLERANCE));
+ expect(sim.xpPerAttempt).toBeGreaterThan(modelXpPerAttempt * (1 - TOLERANCE));
+ expect(sim.xpPerAttempt).toBeLessThan(modelXpPerAttempt * (1 + TOLERANCE));
+ });
+
+ it('uses the exact rounded-XP expectation, not the mean of the roll', () => {
+ // round((9 + k + lvl*0.3) * 1.2) over k in 0..4 is where substituting the mean
+ // of k would silently differ. This asserts the model sits on the exact sum, so
+ // the shortcut cannot be reintroduced without the test noticing.
+ const node = { id: 't', difficulty: 1.2 };
+ const level = 7;
+ let exact = 0;
+ for (let k = 0; k < 5; k += 1) exact += Math.round((9 + k + level * 0.3) * 1.2);
+ exact /= 5;
+ const naive = Math.round((9 + 2 + level * 0.3) * 1.2);
+ expect(exact).not.toBe(naive);
+
+ const model = gatherRate('chop', level, node);
+ const perAttempt = model.xpPerHour / model.attemptsPerHour;
+ // Reconstruct the model's own decomposition from the exact term and confirm it
+ // is the exact one that reproduces the published rate.
+ const { successPct, doublePct } = model;
+ const p = successPct / 100;
+ const d = doublePct / 100;
+ const rebuiltExact = (1 - p) * 2 + p * exact * (1 + d);
+ const rebuiltNaive = (1 - p) * 2 + p * naive * (1 + d);
+ expect(perAttempt).toBeCloseTo(rebuiltExact, 6);
+ expect(perAttempt).not.toBeCloseTo(rebuiltNaive, 6);
+ });
+});
+
+describe('rate-model: cadence and pricing come from the game tables', () => {
+ it('divides by the server-enforced cadence, never a hardcoded one', () => {
+ for (const family of ['chop', 'mine']) {
+ const r = gatherRate(family, 1, family === 'chop' ? TREES[0] : ROCKS[0]);
+ expect(r.cadenceMs).toBe(ACTIVITY_COOLDOWN_MS[family]);
+ expect(r.attemptsPerHour).toBeCloseTo(3_600_000 / ACTIVITY_COOLDOWN_MS[family], 2);
+ }
+ expect(fishRate(1, FISHING_SPOTS[0]).cadenceMs).toBe(ACTIVITY_COOLDOWN_MS.fish);
+ expect(cookRate(1).cadenceMs).toBe(ACTIVITY_COOLDOWN_MS.cook);
+ });
+
+ it('values every yield at the store sell price rather than a copy of it', () => {
+ const r = gatherRate('chop', 1, TREES[0]);
+ expect(r.cashPerHour).toBeCloseTo(r.unitsPerHour * SELL_PRICES.wood, 1);
+
+ const mine = gatherRate('mine', 40, ROCKS[1]);
+ expect(mine.cashPerHour).toBeCloseTo(
+ mine.unitsPerHour * SELL_PRICES.stone + mine.coalPerHour * SELL_PRICES.coal,
+ 1,
+ );
+ });
+
+ it('prices the wheel from the wedge table, with odds that sum to one', () => {
+ const w = wheelValue();
+ expect(w.wedges).toBe(WHEEL_SEGMENTS.length);
+ expect(WHEEL_SEGMENTS.reduce((s, x) => s + x.oddsPct, 0)).toBe(100);
+
+ const manual = WHEEL_SEGMENTS.reduce((sum, seg) => {
+ const value = seg.kind === 'gold' ? seg.gold : seg.qty * (SELL_PRICES[seg.item] || 0);
+ return sum + (seg.oddsPct / 100) * value;
+ }, 0);
+ expect(w.evCash).toBeCloseTo(Math.round(manual * 100) / 100, 2);
+ expect(w.bestCash).toBeGreaterThan(w.evCash);
+ expect(w.worstCash).toBeLessThan(w.evCash);
+ expect(w.stdevCash).toBeGreaterThan(0);
+ });
+
+ it('sums combat loot as independent rolls against the live loot table', () => {
+ for (const kind of Object.keys(MOB_STATS)) {
+ const v = combatValue(kind);
+ const manual = LOOT_TABLES[kind].reduce((sum, e) => {
+ const min = e.min ?? 1;
+ const max = e.max ?? min;
+ return sum + e.chance * ((min + max) / 2) * (SELL_PRICES[e.item] || 0);
+ }, 0);
+ expect(v.lootCash).toBeCloseTo(Math.round(manual * 100) / 100, 2);
+ expect(v.totalCash).toBeCloseTo(Math.round((manual + MOB_STATS[kind].gold) * 100) / 100, 2);
+ expect(v.xp).toBe(MOB_STATS[kind].xp);
+ }
+ });
+
+ it('never lets a mount inflate a cash figure', () => {
+ const troll = combatValue('troll');
+ const mounts = troll.drops.filter((d) => d.mount);
+ expect(mounts.length).toBeGreaterThan(0);
+ for (const m of mounts) expect(m.expectedCash).toBe(0);
+ expect(troll.mountPct).toBeGreaterThan(0);
+ });
+});
+
+describe('rate-model: rankings only ever recommend rates a player can hold', () => {
+ it('marks cooking unsustainable and states what it would need', () => {
+ const cook = cookRate(1);
+ expect(cook.sustainable).toBe(false);
+ expect(cook.requires).toContain('raw fish per hour');
+ expect(cook.fishConsumedPerHour).toBeCloseTo(cook.attemptsPerHour, 2);
+ });
+
+ it('sorts every unsustainable row below every sustainable one, however large', () => {
+ const ladder = activityLadder(1);
+ const cook = ladder.find((r) => r.family === 'cook');
+ // The premise of the test: cooking's ceiling genuinely beats the top real rate,
+ // so a naive sort by cashPerHour would put it first.
+ expect(cook.cashPerHour).toBeGreaterThan(ladder[0].cashPerHour);
+ expect(ladder[ladder.length - 1].family).toBe('cook');
+ const firstUnsustainable = ladder.findIndex((r) => !r.sustainable);
+ expect(ladder.slice(firstUnsustainable).every((r) => !r.sustainable)).toBe(true);
+ });
+
+ it('never quotes payback against a rate that is not sustainable', () => {
+ for (const level of [1, 20, 60, 99]) {
+ const model = solveAt(level);
+ const cook = model.activities.find((r) => r.family === 'cook');
+ expect(model.bestRate.cashPerHour).toBeLessThan(cook.cashPerHour);
+ expect(model.bestRate.cashPerHour).toBeGreaterThan(0);
+ }
+ });
+
+ it('balances the fish-and-cook loop so neither side idles', () => {
+ const spot = bestFishingSpot();
+ const loop = fishCookLoop(20, 20, spot);
+ const fish = fishRate(20, spot);
+ const cook = cookRate(20);
+
+ // Fish produced at the chosen split must equal fish consumed at that split.
+ const produced = (loop.fishSharePct / 100) * fish.unitsPerHour;
+ const consumed = (loop.cookSharePct / 100) * cook.attemptsPerHour;
+ expect(produced).toBeCloseTo(consumed, 4);
+ expect(loop.fishSharePct + loop.cookSharePct).toBeCloseTo(100, 6);
+ expect(loop.sustainable).toBe(true);
+ });
+
+ it('beats selling raw, which is the entire reason to cook', () => {
+ for (const level of [1, 30, 99]) {
+ const loop = fishCookLoop(level, level, bestFishingSpot());
+ expect(loop.cashPerHour).toBeGreaterThan(loop.rawOnlyCashPerHour);
+ expect(loop.upliftPct).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('rate-model: monotonicity and bounds', () => {
+ it('never lets a higher skill level earn less on the same node', () => {
+ for (const node of [...TREES, ...ROCKS]) {
+ const family = TREES.includes(node) ? 'chop' : 'mine';
+ let previous = 0;
+ for (let lvl = 1; lvl <= LEVEL_CAP; lvl += 1) {
+ const r = gatherRate(family, lvl, node);
+ expect(r.cashPerHour).toBeGreaterThanOrEqual(previous - 1e-9);
+ previous = r.cashPerHour;
+ }
+ }
+ });
+
+ it('clamps a level outside the cap instead of extrapolating past it', () => {
+ expect(gatherRate('chop', 0, TREES[0]).level).toBe(1);
+ expect(gatherRate('chop', -5, TREES[0]).level).toBe(1);
+ expect(gatherRate('chop', 1e6, TREES[0]).level).toBe(LEVEL_CAP);
+ expect(solveAt(1e6).level).toBe(LEVEL_CAP);
+ });
+
+ it('keeps success probabilities inside the curves own clamps', () => {
+ for (const lvl of [1, 50, LEVEL_CAP]) {
+ for (const node of ROCKS) {
+ const r = gatherRate('mine', lvl, node);
+ expect(r.successPct).toBeGreaterThan(0);
+ expect(r.successPct).toBeLessThanOrEqual(97);
+ expect(r.doublePct).toBeLessThanOrEqual(40);
+ expect(r.coalPct).toBeLessThanOrEqual(55);
+ }
+ }
+ });
+
+ it('reports the exact hour an empty pack stops the quoted rate', () => {
+ const r = gatherRate('chop', 1, TREES[0]);
+ expect(r.packHours).toBeGreaterThan(0);
+ expect(r.packHours).toBeCloseTo((24 * 999) / r.unitsPerHour, 1);
+ });
+});
+
+describe('rate-model: payback, break-even and progression', () => {
+ it('covers the whole buy catalog and orders it by time to afford', () => {
+ const rows = catalogPayback(1000, 2769);
+ expect(rows).toHaveLength(BUY_CATALOG.length);
+ for (let i = 1; i < rows.length; i += 1) {
+ expect(rows[i].minutes).toBeGreaterThanOrEqual(rows[i - 1].minutes);
+ }
+ const sword = rows.find((r) => r.item === 'sword');
+ expect(sword.minutes).toBeCloseTo((sword.price / 1000) * 60, 4);
+ expect(sword.attempts).toBe(Math.ceil((sword.price / 1000) * 2769));
+ });
+
+ it('reports per-unit price so bundles can be compared honestly', () => {
+ const rows = catalogPayback(1000, 1000);
+ const ammo = rows.find((r) => r.item === 'ammo');
+ const entry = BUY_CATALOG.find((e) => e.item === 'ammo');
+ expect(ammo.qty).toBe(entry.qty);
+ expect(ammo.unitPrice).toBeCloseTo(entry.price / entry.qty, 2);
+ });
+
+ it('returns null when two rates never cross inside the level cap', () => {
+ const same = (lvl) => gatherRate('chop', lvl, TREES[0]);
+ expect(breakEvenLevel(same, same)).toBeNull();
+ });
+
+ it('finds the crossing level when two rates do swap', () => {
+ const a = (lvl) => gatherRate('chop', lvl, TREES[0]);
+ const b = (lvl) => fishRate(lvl, FISHING_SPOTS[0]);
+ const crossing = breakEvenLevel(a, b);
+ if (crossing !== null) {
+ const before = a(crossing - 1).cashPerHour > b(crossing - 1).cashPerHour;
+ const after = a(crossing).cashPerHour > b(crossing).cashPerHour;
+ expect(before).not.toBe(after);
+ }
+ });
+
+ it('prices the next level off the real XP curve', () => {
+ const t = timeToLevel(1, 2, 3600);
+ expect(t.xp).toBe(50);
+ expect(t.hours).toBeCloseTo(50 / 3600, 4);
+ expect(timeToLevel(5, 5, 100)).toBeNull();
+ expect(timeToLevel(1, 2, 0)).toBeNull();
+ });
+});
+
+describe('rate-model: derived findings', () => {
+ it('derives every finding from computed numbers at the requested level', () => {
+ const list = findings(1);
+ expect(list.length).toBeGreaterThanOrEqual(4);
+ for (const f of list) {
+ expect(f.id).toBeTruthy();
+ expect(['trap', 'reward', 'context']).toContain(f.kind);
+ expect(f.title.length).toBeGreaterThan(0);
+ expect(f.detail.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('states the node tradeoff in the direction the arithmetic actually points', () => {
+ const list = findings(1);
+ for (const family of ['chop', 'mine']) {
+ const f = list.find((x) => x.id === `node-tradeoff:${family}`);
+ expect(f).toBeTruthy();
+ const rows = activityLadder(1).filter((r) => r.family === family);
+ const easiest = rows.reduce((a, b) => (b.node.difficulty < a.node.difficulty ? b : a));
+ const hardest = rows.reduce((a, b) => (b.node.difficulty > a.node.difficulty ? b : a));
+ const hardestWins = hardest.cashPerHour > easiest.cashPerHour;
+ expect(f.kind).toBe(hardestWins ? 'reward' : 'trap');
+ }
+ });
+
+ it('re-derives its findings per level rather than caching one answer', () => {
+ const low = findings(1).find((f) => f.id === 'cook-uplift');
+ const high = findings(80).find((f) => f.id === 'cook-uplift');
+ expect(low.detail).not.toBe(high.detail);
+ });
+});
+
+describe('rate-model: curves and the full solve', () => {
+ it('emits one full-length curve per node in the world plus the loop', () => {
+ const curves = allCurves();
+ const expected = TREES.length + ROCKS.length + FISHING_SPOTS.length + 2;
+ expect(curves).toHaveLength(expected);
+ for (const c of curves) {
+ expect(c.cash).toHaveLength(LEVEL_CAP);
+ expect(c.xp).toHaveLength(LEVEL_CAP);
+ expect(c.cash.every((n) => Number.isFinite(n))).toBe(true);
+ }
+ });
+
+ it('keys every curve to a row the ladder also emits', () => {
+ const ladderKeys = new Set(activityLadder(1).map((r) => r.key));
+ for (const c of allCurves()) {
+ if (c.family === 'loop') continue;
+ expect(ladderKeys.has(c.key)).toBe(true);
+ }
+ });
+
+ it('agrees with the single-level solve at the same level', () => {
+ const curves = allCurves();
+ const level = 33;
+ const model = solveAt(level);
+ for (const row of model.activities) {
+ const curve = curves.find((c) => c.key === row.key);
+ expect(curve.cash[level - 1]).toBeCloseTo(Math.round(row.cashPerHour * 10) / 10, 6);
+ }
+ });
+
+ it('publishes its assumptions with every solve', () => {
+ const model = solveAt(10);
+ expect(model.assumptions).toEqual(ASSUMPTIONS);
+ expect(ASSUMPTIONS.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it('picks the highest-quality pond, which dominates at every level', () => {
+ const best = bestFishingSpot();
+ for (const spot of FISHING_SPOTS) {
+ expect(best.quality).toBeGreaterThanOrEqual(spot.quality || 1);
+ }
+ for (const lvl of [1, 50, 99]) {
+ for (const spot of FISHING_SPOTS) {
+ expect(fishRate(lvl, best).cashPerHour).toBeGreaterThanOrEqual(fishRate(lvl, spot).cashPerHour);
+ }
+ }
+ });
+
+ it('reports no next level at the cap instead of dividing by a missing one', () => {
+ expect(solveAt(LEVEL_CAP).nextLevel).toBeNull();
+ expect(solveAt(LEVEL_CAP - 1).nextLevel.level).toBe(LEVEL_CAP);
+ });
+
+ it('separates the best cash rate from the best XP rate', () => {
+ const model = solveAt(LEVEL_CAP);
+ expect(model.bestRate.key).toBeTruthy();
+ expect(model.bestXpRate.key).toBeTruthy();
+ expect(model.bestXpRate.xpPerHour).toBeGreaterThanOrEqual(
+ sustainableBest(LEVEL_CAP).cash.xpPerHour,
+ );
+ });
+});
+
+describe('rate-model: sanity against the world tables', () => {
+ let warn;
+ beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); });
+ afterEach(() => { warn.mockRestore(); });
+
+ it('rates every node the world actually defines, and no others', () => {
+ const ladder = activityLadder(1);
+ for (const t of TREES) expect(ladder.some((r) => r.key === `chop:${t.id}`)).toBe(true);
+ for (const r of ROCKS) expect(ladder.some((x) => x.key === `mine:${r.id}`)).toBe(true);
+ for (const s of FISHING_SPOTS) expect(ladder.some((x) => x.key === `fish:${s.id}`)).toBe(true);
+ expect(ladder).toHaveLength(TREES.length + ROCKS.length + FISHING_SPOTS.length + 1);
+ });
+
+ it('rejects an unknown gather family and an unknown mob loudly', () => {
+ expect(() => gatherRate('smelt', 1, TREES[0])).toThrow(/unknown gather family/);
+ expect(() => combatValue('dragon')).toThrow(/unknown mob/);
+ });
+});
diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.js
index a27860516..1993e8b15 100644
--- a/walk-sdk/src/companion.js
+++ b/walk-sdk/src/companion.js
@@ -41,6 +41,8 @@ import { resolveConfig, resolveAvatarEntry } from './config.js';
const CANVAS_W = 200;
const CANVAS_H = 280;
+// Identifies this widget's claim on the corner in window.twsCornerStack.
+const CORNER_RESERVE_KEY = 'walk-companion';
const CURSOR_IDLE_MS = 450; // cursor still longer than this → stop walking
const GAZE_IDLE_MS = 4000; // cursor still longer than this → gaze drifts back to the clip
const GAZE_PX_PER_M = 260; // page pixels per scene metre when aiming the head at the cursor
@@ -121,6 +123,29 @@ class WalkCompanion {
this._onVisibility = this._onVisibility.bind(this);
this._onPageHide = this._onPageHide.bind(this);
this._tick = this._tick.bind(this);
+ this._syncCornerReserve = this._syncCornerReserve.bind(this);
+ }
+
+ /**
+ * Tell the host page's corner stack how much of the bottom-right corner this
+ * companion occupies, so its cards ("Getting started", feature discovery)
+ * stack above the avatar instead of underneath it.
+ *
+ * Measured from computed style rather than getBoundingClientRect(): the host
+ * animates in with a translateY, and a rect read mid-transition would report
+ * a short-changed height that the stack would then settle into.
+ *
+ * Optional by design. The SDK ships standalone, so a page without the corner
+ * stack simply skips this.
+ */
+ _syncCornerReserve() {
+ const stack = typeof window !== 'undefined' ? window.twsCornerStack : null;
+ if (!stack || typeof stack.reserve !== 'function' || !this.host) return;
+ const cs = getComputedStyle(this.host);
+ const bottom = parseFloat(cs.bottom) || 0;
+ const height = parseFloat(cs.height) || 0;
+ if (height <= 0) return;
+ stack.reserve(CORNER_RESERVE_KEY, bottom + height);
}
async mount() {
@@ -161,6 +186,9 @@ class WalkCompanion {
this._picker?.destroy();
this._picker = null;
this._teardownScene();
+ window.removeEventListener('resize', this._syncCornerReserve);
+ window.removeEventListener('tws-corner-stack:ready', this._syncCornerReserve);
+ window.twsCornerStack?.release?.(CORNER_RESERVE_KEY);
if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
this.host = null;
}
@@ -197,6 +225,16 @@ class WalkCompanion {
// Clicking the avatar detaches it into Playground mode.
this.canvas.addEventListener('click', () => this.owner._detachToPlayground(this));
requestAnimationFrame(() => host.classList.add('is-in'));
+ // Claim the corner before anything else settles there, and re-measure on
+ // resize: the narrow-viewport rule shrinks the companion to 148x208.
+ // Bound here rather than in _bindEvents() so the claim survives the
+ // avatar-failed-to-load path, where the host stays on the page.
+ this._syncCornerReserve();
+ window.addEventListener('resize', this._syncCornerReserve);
+ // If the corner stack has not booted yet, claim the corner the moment it
+ // does. Without this the companion could win the load race and silently
+ // keep no reservation at all.
+ window.addEventListener('tws-corner-stack:ready', this._syncCornerReserve);
}
_showError() {