The engine, line by line
Every figure on this site is computed by the published simulation kit, reached through the adapter below.
Part one
What the adapter reaches in the kit
- @rtb/foundation/engine/decks/default-deck-data
- @rtb/foundation/engine/math/percentile
- @rtb/foundation/engine/math/random
- @rtb/foundation/engine/simulation
- @rtb/foundation/engine/simulation/resampling/moving-block.sequencer
- @rtb/foundation/engine/simulation/resampling/sequencer-registry
Part two
snsw-engine.js
- 01what is reused from v7 unchanged line 64
- 02the decks line 83
- 03limits the board sets line 94
- 04policies: (t, T, wealth, ctx) -> the exposure the rule asks for line 116
- 05stated stress and return shift: cards solved from their real return line 154
- 06one year, by the kit line 190
- 07the run line 210
- 08the optimizer line 322
- 09what the page prints about the record line 387
snsw-engine.js · 398 lines · md5 0a1a5d88c62141fcd72222b0bf4514e6 · 2 not shown (line 12, 103)
// SaveNowSpendWhen Arrival — the real record. This file is an ADAPTER, not an engine.//// The Arrival board was written against the designer's prototype engine (pulled/roth-engine.js),// which draws its market from a declared mean and spread. This module exports every name that// board uses, with the same shapes, but every simulated number comes from the published kit,// reached through the package boundary (@rtb/foundation), dealt the real 1970–2024 record// (S&P 500 total return, CPI-U, 3-month T-bill) by block bootstrap. It is built on the v7 adapter// (./roth-engine.v7.js) and adds five things v7 does not do://// 1. LEVERAGE OUTSIDE A ROTH. LIMITS.cap up to 2 is HELD, not just drawn. A year held above 100%// is earned by the kit's own arithmetic (runSinglePath → transitionWealth →[this line carries wording the site no longer uses and is not shown here]// borrow, so every run that ever holds more than 100% carries meta.leveraged = true and the// page labels it "outside a Roth". This labels the open question of where leverage lives; it// does not decide it.// 2. LIQUIDATION. The kit floors wealth at 0 AFTER adding the year's contribution:// max(0, W·(1+r) + c). The prototype floors BEFORE adding it: max(0, W·(1+r)) + c. The kit is// the engine, so its order is used. LIMITS.liquidate is accepted for the board's sake and does// nothing here: the kit always floors at 0, so a loss never carries debt.// 3. A CRASH OF A SET SIZE (shock.marketDrawdown, shockYear). In the shock year the path's own// card is replaced by a copy whose market return is solved so its real (inflation-adjusted)// return is exactly −marketDrawdown; that year's inflation and T-bill are kept. This is a// stated stress, not a market model, and meta.stress says so.// 4. A RETURN SHIFT (shift: d). Every card's market return is re-solved so its real return is the// record's plus d. meta.shift records it. "The record, d points a year better or worse" — the// page never states an assumed average.// 5. A FEE ON THE WHOLE ACCOUNT (fee: f, e.g. 0.01), added 2026-10-13 for the Instagram fee post.// A shift of −f lowers STOCK returns only, which understates a fee charged on assets under// management (the industry reading of "one percent a year"). With fee: f the year's balance,// after its return and before that year's contribution lands, is multiplied by (1 − f):// W' = c + max(0, W·(1+r) ) · (1 − f), written as c + max(0, step − c)·(1 − f) over the kit's// floored step max(0, W·(1+r) + c), so the kit's own liquidation order is untouched. meta.fee// records it; fee 0 is bit-identical to no fee.// 6. THE LIFECYCLE RULE COUNTS THE PAY ACTUALLY DEPOSITED (2026-10-17): `ctx.deposits` is the year-by-year// contribution with any shock's income cut, and `policies.lifecycle` discounts it, so a pay stop or cut// lowers the stock share it asks for. Before, it summed a constant and kept asking for the same share// after the saver stopped working. Law 10. Flat saver, no cut: bit-identical to before.//// Plus optimizePts(arch, pol, { objective }) — any percentile 'p1'…'p99' of the ending balance// ('p10' is the prototype's score; 'p50', the median, is what the handoff says the search is scored// on) or 'meanLog' (growth) — and optimizePtsSteps, the same search one simulate() at a time.//// Items 3 and 4 are the two card primitives the requirement asks the kit's publisher to publish// (a card with a chosen real return, a deck shifted by d). Until the kit publishes them these// copies stand in, and snsw-engine.vitest.ts pins them; when it does, they are deleted here.//// This copy differs from the deposited one in exactly one respect: the kit arrives by bare// specifier (kit-boundary.vitest.ts holds that), where the deposit carried a landed copy of the kit.//// Real terms: the kit deflates every card by that year's CPI (Fisher), so every balance here is in// today's dollars.import * as V7 from './roth-engine.v7.js';import { FULL_HISTORY_DECK } from '@rtb/foundation/engine/decks/default-deck-data';import {runSinglePath,buildDeckFisherTable,computeDeckStatistics,DEFAULT_CONSTRAINTS,} from '@rtb/foundation/engine/simulation';import { SeededRandom } from '@rtb/foundation/engine/math/random';import { percentileFromSorted } from '@rtb/foundation/engine/math/percentile';// ---- what is reused from v7 unchanged --------------------------------------------------------export const RECORD = V7.RECORD;export const METHODS = V7.METHODS;export const DEFAULT_METHOD = V7.DEFAULT_METHOD;export const METHOD_LABEL = V7.METHOD_LABEL;export const BLOCK_LENGTH = V7.BLOCK_LENGTH;export const cardMatrix = V7.cardMatrix;export const cardsForYears = V7.cardsForYears;export const STRESS_PRESETS = V7.STRESS_PRESETS;export const fmt = V7.fmt;export const addPoint = V7.addPoint;export const GLIDE_STAGES = V7.GLIDE_STAGES;export const linePath = V7.linePath;export const bandPath = V7.bandPath;export const histogram = V7.histogram;export const goalFor = V7.goalFor;export const wealthBucket = V7.wealthBucket;export const BUCKETS = V7.BUCKETS;// ---- the decks -----------------------------------------------------------------------------// v7's five real decks, plus `base` — the name the Arrival board reads (E.MARKET.base) — which is// the full 1970–2024 record itself, the same object as MARKET.history. Its mu / sigma / safe are// computed from the cards by the kit (see v7's describeDeck); none is written down here.export const DEFAULT_DECK_ID = V7.DEFAULT_DECK_ID;// v7's real windows of the record in calendar order (no draw), added 2026-10-13 for the Instagram// reassurance post: every forty-year stretch the record holds, dealt as it happened.export const windows = V7.windows;export const MARKET = Object.freeze({ base: V7.MARKET[V7.DEFAULT_DECK_ID], ...V7.MARKET });export const DECKS = V7.DECKS;// ---- limits the board sets -------------------------------------------------------------------// Same shape and same defaults as the prototype: 100% held, no borrowing spread, liquidate off.// The Arrival board sets cap 2, borrowSpread 0.03, liquidate true before it runs anything.// cap — the most a run HOLDS (and the most the glide editor draws). Above 1 is borrowing.// borrowSpread — what borrowing costs over the T-bill, per year, passed to the kit as// constraints.marginSpread.// liquidate — accepted; the kit always floors wealth at 0 (see note 2 at the top).export const LIMITS = { cap: 1, borrowSpread: 0, liquidate: false };// The words the page puts beside any run with meta.leveraged = true (CONTRACT.md item 1).[this line carries wording the site no longer uses and is not shown here]export const LIQUIDATION_NOTE ='The kit always floors wealth at 0, after adding that year\'s savings — a loss never carries debt into the next year.';// The kit's constraints for the current limits. Only marginSpread changes the arithmetic, and only// for years held above 100%; maxAllocation is carried so the constraints say what was allowed.export function constraintsFor(limits = LIMITS) {return Object.freeze({ ...DEFAULT_CONSTRAINTS, maxAllocation: limits.cap, marginSpread: limits.borrowSpread || 0 });}export const clamp01 = (v) => Math.min(LIMITS.cap, Math.max(0, v));const holdable = (f) => Math.min(LIMITS.cap, Math.max(0, f));// ---- policies: (t, T, wealth, ctx) -> the exposure the rule asks for ------------------------export const policies = {level: (f = 0.6) => () => f,glide: (start = 0.9, end = 0.3) => (t, T) => start + (end - start) * (t / Math.max(1, T - 1)),// Ayres–Nalebuff lifecycle: risky DOLLARS = k × (wealth + present value of future savings),// capped at `cap`. The run holds min(asked, LIMITS.cap), so cap 2 is only held when the board// has raised LIMITS.cap to 2 — outside a Roth.lifecycle: (k = 0.7, disc = 0.02, cap = 1) => (t, T, w, ctx) => {// Since 2026-10-17 the present value sums the pay ACTUALLY deposited year by year (`ctx.deposits`: the// contribution schedule with any shock's income cut applied), so a saver whose pay stops or is cut is// asked for less, not the same. A flat saver with no cut sums the same constant as before, bit for bit.let pv = 0; for (let s = t; s < T; s++) pv += (ctx.deposits ? ctx.deposits[s] : ctx.contribution) / Math.pow(1 + disc, s - t);return Math.min(cap, Math.max(0, (k * (w + pv)) / Math.max(1, w)));},openLoop: (blocks) => (t, T) => blocks[Math.min(blocks.length - 1, Math.floor((t / T) * blocks.length))],};policies.yearly = (arr) => (t) => arr[Math.min(arr.length - 1, t)];policies.structured = (arr, offsets, goal) => (t, T, w) => clamp01(arr[Math.min(arr.length - 1, t)] + offsets[wealthBucket(w, goal(t))]);policies.heat = (map, goal) => (t, T, w) => map[Math.min(map.length - 1, t)][wealthBucket(w, goal(t))];// Same as v7's, but clamped to THIS module's LIMITS.cap (v7's clamps to its own, which stays 1).export function interpPts(pts, T) {const s = [...pts].sort((a, b) => a.t - b.t); const out = new Array(T);for (let t = 0; t < T; t++) {if (t <= s[0].t) out[t] = s[0].v; else if (t >= s[s.length - 1].t) out[t] = s[s.length - 1].v;else { let i = 0; while (s[i + 1].t < t) i++; const a = s[i], b = s[i + 1]; out[t] = b.t === a.t ? b.v : a.v + (b.v - a.v) * ((t - a.t) / (b.t - a.t)); }out[t] = clamp01(out[t]);}return out;}export function buildPolicy(pol, arch) {const T = arch.horizonYears;if (pol.kind === 'glide') return policies.yearly(interpPts(pol.pts, T));if (pol.kind === 'closed') return policies.structured(interpPts(pol.pts, T), pol.offsets, goalFor(arch, pol.target));if (pol.kind === 'heat') return policies.heat(pol.map, goalFor(arch, pol.target));return policies.level(0.6);}// ---- stated stress and return shift: cards solved from their real return ----------------------// A card stores nominal percents. Its real return is (1 + market/100) / (1 + inflation/100) − 1// (the kit's Fisher step). To give a card a chosen real return R, solve for the nominal market:// market = ((1 + R)·(1 + inflation/100) − 1)·100. Inflation and the T-bill stay the card's own.function withRealEquity(card, real) {return { ...card, marketReturn: ((1 + real) * (1 + card.inflation / 100) - 1) * 100 };}export function stressCard(card, marketDrawdown) {return withRealEquity(card, -marketDrawdown);}export function shiftDeck(cards, d) {if (!d) return cards;const reals = buildDeckFisherTable(cards);return cards.map((card, i) => withRealEquity(card, reals[i].equityReal + d));}// Which deck a run is dealt, and by how much the board has asked to move it. The board's// sensitivity strip passes { ...MARKET.base, mu: MARKET.base.mu + d }; a mean that differs from the// cards' own mean is read as a shift of d, so the strip runs unchanged and moves the record by d// rather than drawing from an assumed average.function resolveMarket(market) {let deck;if (market === undefined || market === null) deck = MARKET[DEFAULT_DECK_ID];else if (typeof market === 'string') deck = MARKET[market] || V7.deckFor(market);else if (market && Array.isArray(market.cards)) deck = market;else if (market && market.id) deck = V7.deckFor(market.id);else throw new Error('snsw-engine: that is not one of the record decks. Pass a deck from MARKET (' + Object.keys(MARKET).join(', ') + ').');let implied = 0;if (typeof deck.mu === 'number') {const ownMean = computeDeckStatistics(deck.cards).avgRealEquityReturn;implied = deck.mu - ownMean;if (Math.abs(implied) < 1e-15) implied = 0;}return { deck, implied };}// ---- one year, by the kit -------------------------------------------------------------------// runSinglePath over a one-card deck — v7's step, with the constraints the current limits give.// A year held above 100% goes through the kit's levered branch (α·eq − (α−1)·(T-bill + spread)),// and the kit floors the result at 0 after adding the year's savings.const FIRST_CARD = [0];function stepYear(wealth, allocation, contribution, card, method, constraints) {const walked = runSinglePath({initialWealth: wealth,annualContributionsByYear: [contribution],allocationsByYear: [allocation],horizonYears: 1,deck: [card],constraints,samplingMethod: method,}, undefined, FIRST_CARD);return walked[1];}export const ELAPSED = { years: 0 };// ---- the run ---------------------------------------------------------------------------------export function simulate(arch, policy, opts = {}) {const {paths = 400, seed = 7, market, method = DEFAULT_METHOD,shock = null, shockYear = null, miss = null, elapsed = ELAPSED.years, shift = 0, fee = 0,} = opts;if (!(typeof fee === 'number' && fee >= 0 && fee < 1)) {throw new Error('snsw-engine: fee is a yearly share of the whole balance, 0 ≤ fee < 1.');}const { deck, implied } = resolveMarket(market);const totalShift = (shift || 0) + implied;const cards = shiftDeck(deck.cards, totalShift);const constraints = constraintsFor(LIMITS);const T = arch.horizonYears;const matrix = cardMatrix(cards.length, T, paths, seed, method);const nPast = Math.max(0, Math.min(T, elapsed | 0));const lived = nPast > 0 ? cards.slice(Math.max(0, cards.length - nPast)) : null;// Two kinds of crisis. With `years`, v7's: the real cards of those years, as they happened.// Without, a stated size: that year's own card, solved to lose exactly marketDrawdown in real terms.const realCrisis = shock && Array.isArray(shock.years) ? cardsForYears(shock.years) : null;const statedCrisis = shock && !realCrisis && typeof shock.marketDrawdown === 'number';if (shock && !realCrisis && !statedCrisis) {throw new Error('snsw-engine: a crash needs either the years it names or a marketDrawdown size.');}const crashLen = realCrisis ? realCrisis.length : statedCrisis ? 1 : 0;// The crash lands only in a year the caller names. The prototype's test is `t === shockYear`, so// a shock passed without a whole-number shockYear crashes nothing there; here `t >= null` would// read null as year 0 and crash the first year instead. So without a named year, no crash.// (The income cut keeps the prototype's own comparison, `t >= shockYear`, unchanged.)const crashAt = Number.isInteger(shockYear) ? shockYear : null;const incomeLen = shock ? (shock.durationYears || crashLen) : 0;// The pay deposited in each year, as the loop below deposits it: the schedule (or the flat contribution) with// the shock's income cut applied in its years. Policies read it to count the saving still to come.const depositAt = (t) => {let c = V7.depositAt(arch, t);if (shock && t >= shockYear && t < shockYear + incomeLen) c *= 1 - (shock.incomeLossFraction || 0);return c;};const deposits = Array.from({ length: T }, (_, t) => depositAt(t));const ctx = { contribution: arch.annualContribution, deposits };const yearly = Array.from({ length: T + 1 }, () => []);const exposure = new Array(T).fill(0);const demand = new Array(T).fill(0);const terminal = new Array(paths);let leveraged = false;for (let p = 0; p < paths; p++) {let w = arch.startingBalance; let sittingOut = 0; let peak = w;yearly[0].push(w);for (let t = 0; t < T; t++) {const asked = policy(t, T, w, ctx);let f = holdable(asked);if (miss && sittingOut > 0) { f = 0; sittingOut--; }if (f > 1) leveraged = true;exposure[t] += f; demand[t] += Math.max(0, asked);let card = lived && t < nPast ? lived[t] : cards[matrix[p][t]];if (shock && crashAt !== null && t >= crashAt && t - crashAt < crashLen) {card = realCrisis ? realCrisis[t - crashAt] : stressCard(card, shock.marketDrawdown);}const contrib = deposits[t];w = stepYear(w, f, contrib, card, method, constraints);if (fee > 0) w = contrib + Math.max(0, w - contrib) * (1 - fee);if (miss) { peak = Math.max(peak, w); if (w < peak * (1 - miss.drawdown) && sittingOut === 0) { sittingOut = miss.years; peak = w; } }yearly[t + 1].push(w);}terminal[p] = w;}// Percentiles are the kit's (Hyndman & Fan type 7), from all paths — as in v7.const sortedY = yearly.map((y) => [...y].sort((a, b) => a - b));const pctGrid = sortedY.map((sy) => Array.from({ length: 101 }, (_, k) => percentileFromSorted(sy, k / 100)));const sortedT = [...terminal].sort((a, b) => a - b);const shareAbove = (t, g) => {const sy = sortedY[Math.min(sortedY.length - 1, t)];let lo = 0, hi = sy.length;while (lo < hi) { const mid = (lo + hi) >> 1; if (sy[mid] < g) lo = mid + 1; else hi = mid; }return (sy.length - lo) / sy.length;};const atYear = (k) => pctGrid.map((row) => row[k]);const stress = !shock ? null : realCrisis? { kind: 'record', years: shock.years.slice(), shockYear, incomeLossFraction: shock.incomeLossFraction || 0, durationYears: incomeLen }: { kind: 'stated', marketDrawdown: shock.marketDrawdown, shockYear, incomeLossFraction: shock.incomeLossFraction || 0, durationYears: incomeLen,what: crashAt === null? 'no crash year was named, so no crash was applied (the prototype does the same)': `one year set to lose ${(shock.marketDrawdown * 100).toFixed(0)}% after inflation — a stated stress, not a year from the record` };return {T, terminal, yearly, pctGrid, shareAbove,quantileAt: (t, k) => pctGrid[Math.min(pctGrid.length - 1, t)][Math.max(0, Math.min(100, Math.round(k * 100)))],p10: atYear(10), p50: atYear(50), p90: atYear(90),exposure: exposure.map((e) => e / paths),demand: demand.map((e) => e / paths),t10: percentileFromSorted(sortedT, 0.1), t50: percentileFromSorted(sortedT, 0.5), t90: percentileFromSorted(sortedT, 0.9),// Any percentile of the ending balance, read exactly as t10 / t50 / t90 are (q in 0..1).quantileT: (q) => percentileFromSorted(sortedT, q),probBelow: (g) => terminal.filter((x) => x < g).length / terminal.length,meanLog: terminal.reduce((s, x) => s + Math.log(Math.max(1, x)), 0) / terminal.length,pastYears: lived ? lived.map((c) => c.year) : null,meta: {deckId: deck.id, deck: deck.deck, years: deck.years, method, methodLabel: METHOD_LABEL[method], seed, paths,real: true, leveraged, stress, shift: totalShift, fee, cap: LIMITS.cap, marginSpread: constraints.marginSpread,floor: LIQUIDATION_NOTE,},};}// ---- the optimizer ---------------------------------------------------------------------------// v7's control-point search, run on this module's simulate (so held leverage and the current// limits apply), with a choice of what it scores:// 'pNN' — the NN-th percentile ending balance, NN a whole number from 1 to 99, read from the// run's sorted ending balances by the kit's percentileFromSorted, exactly as t10 / t50// are. 'p10' is the prototype's hard-wired score; 'p50' (the median) is what the// handoff says the search is scored on.// 'meanLog' — average log ending balance (growth).// Candidate points are proposed with the kit's seeded generator (SeededRandom, the same one v7's// rng() wraps); nothing it draws is a market return.export const OBJECTIVES = ['p10', 'p25', 'p50', 'p75', 'p90', 'meanLog'];const PCT_OBJECTIVE = /^p([1-9][0-9]?)$/;export function parseObjective(objective) {if (objective === 'meanLog') return { kind: 'meanLog' };const m = typeof objective === 'string' ? PCT_OBJECTIVE.exec(objective) : null;if (m) return { kind: 'percentile', pct: Number(m[1]) };throw new Error(`snsw-engine: no objective called '${String(objective)}'. Choose 'p1' to 'p99' (a percentile of the ending balance) or 'meanLog'.`);}// The score a run gets under an objective. p10 and p50 read the run's own t10 / t50 fields, which// are the same percentileFromSorted call with q = 10/100 and 50/100 (a law holds them equal).export function scoreRun(run, objective) {const o = parseObjective(objective);if (o.kind === 'meanLog') return run.meanLog;if (o.pct === 10) return run.t10;if (o.pct === 50) return run.t50;if (o.pct === 90) return run.t90;return run.quantileT(o.pct / 100);}// The search as a generator: it yields once after every simulate() it runs (the first point, then// each trial), so a caller can spread one search over many short turns of the page. Drained in one// go (optimizePts below), it is the same search, draw for draw.export function* optimizePtsSteps(arch, pol, opts = {}) {const {trials = 40, sigmaV = 0.12, sigmaT = 0, moveT = false, seed = 55, market, method = DEFAULT_METHOD,paths = 300, objective = 'p10', shift = 0,} = opts;parseObjective(objective);const T = arch.horizonYears; const sr = new SeededRandom(seed);const step = () => sr.nextGaussian(0, 1);const score = (pts) => scoreRun(simulate(arch, buildPolicy({ ...pol, pts }, arch), { paths, seed: 101, market, method, shift }), objective);let best = { pts: pol.pts.map((p) => ({ ...p })), y: score(pol.pts) }; const hist = [best];yield;for (let i = 0; i < trials; i++) {const src = hist[Math.floor(sr.next() * Math.min(hist.length, 4))];const pts = src.pts.map((p, k) => ({ t: moveT && k > 0 && k < src.pts.length - 1 ? Math.round(Math.min(T - 2, Math.max(1, p.t + sigmaT * step()))) : p.t, v: clamp01(+(p.v + sigmaV * step()).toFixed(2)) }));const y = score(pts); const cand = { pts, y };hist.push(cand); hist.sort((a, b) => b.y - a.y); hist.length = Math.min(hist.length, 8);if (y > best.y) best = cand;yield;}return { ...best, objective };}export function optimizePts(arch, pol, opts = {}) {parseObjective(opts.objective === undefined ? 'p10' : opts.objective);const it = optimizePtsSteps(arch, pol, opts);let r = it.next();while (!r.done) r = it.next();return r.value;}export function runGlideStage(arch, pol, stage, market, objective = 'p10') {const T = arch.horizonYears; const pts = stage.add ? addPoint(pol.pts, T) : pol.pts;const best = optimizePts(arch, { ...pol, pts }, { trials: stage.trials, sigmaV: stage.sigmaV, sigmaT: (stage.sigmaTFrac || 0) * T, moveT: stage.moveT, market, seed: 55 + stage.trials, objective });return { pol: { ...pol, pts: best.pts }, score: best.y };}// ---- what the page prints about the record ---------------------------------------------------// The board reads these instead of typing a market as a number. All computed from the cards.export function deckFacts(market) {const { deck } = resolveMarket(market);return {deck: deck.deck, years: deck.years, n: deck.n,meanReal: deck.mu, spreadReal: deck.sigma, safeReal: deck.safe, cagrReal: deck.cagr,methodLabel: METHOD_LABEL[DEFAULT_METHOD],first: FULL_HISTORY_DECK[0].year, last: FULL_HISTORY_DECK[FULL_HISTORY_DECK.length - 1].year,};}
Part three
roth-engine.v7.js
- 01the record itself line 44
- 02seeded randomness line 70
- 03the decks: real years, nothing else line 85
- 04crises: the real cards of the years they name line 166
- 05policies: (t, T, wealth, ctx) -> the exposure the rule asks for line 201
- 06one year, by the kit line 219
- 07the lived past line 244
- 08the run line 257
- 09Kelly: how much is too much, from the deck's own record line 341
- 1030-year windows of the real record line 368
- 11Q-table state bucket: period tercile × wealth-vs-goal ratio line 401
- 12the one number the board and the test share line 493
- 13control-point glidepaths and structured closed-loop policies line 529
roth-engine.v7.js · 632 lines · md5 43fdfa590fcc7a32327dcd4cda0bcdec · 2 not shown (line 53, 531)
// Roth v7 — the real record. This file is an ADAPTER, not an engine.//// Every number it returns is computed by the published simulator kit, reached through the package// boundary (@rtb/foundation), over the real year-by-year record (S&P 500 total return, CPI-U,// 3-month T-bill; 1970–2024, sources in the kit's own header). Nothing here declares a market:// there is no drawn return, no fitted mean, no volatility written down as a literal. A year the kit// cannot deal is a held mark with a sentence, never a number.//// The shape of this module is v6's, so the board and the view keep working unchanged.// What changed is underneath: every simulated year is one call to the kit's runSinglePath with// horizonYears 1, dealt a real card. Stepping a year at a time is what lets the wealth-dependent// rules (lifecycle sizing, the closed-loop response, the leave-the-plan miss) and the per-year// contribution schedule read the balance the kit just produced — and it reproduces the kit's// multi-year call to the cent, because runSinglePath's per-year arithmetic reads only// deck[cardIndex], the year's allocation and the year's contribution. The parity law in// snsw-engine.vitest.ts holds that claim to the kit's own run.//// This copy differs from the deposited one in exactly one respect: the kit arrives by bare// specifier (kit-boundary.vitest.ts holds that), where the deposit carried a landed copy of the kit.//// Real terms: the kit deflates every card by that year's CPI (Fisher), so every balance here is// in today's dollars.import {FULL_HISTORY_DECK,RECENT_TURBULENT_DECK,createDeckFromYearRange,DECK_AS_OF_YEAR,} from '@rtb/foundation/engine/decks/default-deck-data';import {runSinglePath,samplingMethodToSequencerId,buildDeckFisherTable,computeDeckStatistics,computeDeckRealMarketStats,computePortfolioReturnFromReals,DEFAULT_CONSTRAINTS,} from '@rtb/foundation/engine/simulation';import { createCardSequencer } from '@rtb/foundation/engine/simulation/resampling/sequencer-registry';import { DEFAULT_BLOCK_LENGTH } from '@rtb/foundation/engine/simulation/resampling/moving-block.sequencer';import { SeededRandom } from '@rtb/foundation/engine/math/random';import { percentileFromSorted } from '@rtb/foundation/engine/math/percentile';// ---- the record itself -------------------------------------------------------------------// Derived from the deck, never typed: when the kit ships another year, these move with it.export const RECORD = Object.freeze({start: FULL_HISTORY_DECK[0].year,end: FULL_HISTORY_DECK[FULL_HISTORY_DECK.length - 1].year,asOf: DECK_AS_OF_YEAR,nowYear: DECK_AS_OF_YEAR + 1,});[this line carries wording the site no longer uses and is not shown here]// (§4975). A rule that asks for more than that is drawn as demand, and the demand is// reported beside the holding — it is never earned on.export const HOLDING_CAP = 1;export const CONSTRAINTS = Object.freeze({ ...DEFAULT_CONSTRAINTS, maxAllocation: HOLDING_CAP });// The three ways the kit can deal the record. Block bootstrap keeps runs of years together, so a// crash and its rebound stay next to each other.export const METHODS = ['block-bootstrap', 'bootstrap', 'sequential'];export const DEFAULT_METHOD = 'block-bootstrap';export const BLOCK_LENGTH = DEFAULT_BLOCK_LENGTH;export const METHOD_LABEL = {'block-bootstrap': `block bootstrap · ${DEFAULT_BLOCK_LENGTH}-yr blocks`,bootstrap: 'single years drawn at random',sequential: 'the record in calendar order',};// ---- seeded randomness -------------------------------------------------------------------// One source, the kit's. `rng` is a thin wrapper so the board's search code keeps its calls;// `gauss` is the kit's own normal draw (SeededRandom.nextGaussian). Nothing in this file draws a// market return from it — it proposes search candidates and picks ε-greedy actions, nothing else.export function rng(seed) {const sr = new SeededRandom(seed);return { next: () => sr.next(), gauss: (mean = 0, sd = 1) => sr.nextGaussian(mean, sd) };}export const ARCHETYPES = [{ id: 'early-career', label: 'Early career, long horizon', short: 'Early', summary: 'Just started contributing, decades of human capital ahead, almost nothing saved yet.', ageYears: 25, horizonYears: 40, annualContribution: 10000, startingBalance: 15000, startingAllocation: 0.9 },{ id: 'mid-career', label: 'Mid career, balance building', short: 'Mid', summary: 'Contributing steadily against a balance that has started to matter more than the contributions.', ageYears: 40, horizonYears: 25, annualContribution: 25000, startingBalance: 300000, startingAllocation: 0.7 },{ id: 'near-goal', label: 'Near the goal, short horizon', short: 'Near', summary: 'The balance does the work now; a bad decade cannot be contributed out of.', ageYears: 57, horizonYears: 8, annualContribution: 30000, startingBalance: 900000, startingAllocation: 0.5 },];// ---- the decks: real years, nothing else --------------------------------------------------// Every field below is computed from the cards by the kit's own functions:// mu = mean real market return per year (computeDeckStatistics.avgRealEquityReturn)// sigma = spread of those real returns (computeDeckRealMarketStats.volatility)// safe = mean real 3-month T-bill return (computeDeckStatistics.avgRealBondReturn)// series= each year's real market return (buildDeckFisherTable, calendar order)function describeDeck(id, cards, kind, label, why) {const stats = computeDeckStatistics(cards);const real = computeDeckRealMarketStats(cards);return {id,deck: label,kind,years: `${cards[0].year}–${cards[cards.length - 1].year}`,firstYear: cards[0].year,lastYear: cards[cards.length - 1].year,n: cards.length,series: buildDeckFisherTable(cards).map((c) => c.equityReal),mu: stats.avgRealEquityReturn,sigma: real.volatility,safe: stats.avgRealBondReturn,cagr: real.cagr,worst: real.worst,worstYear: real.worstYear,best: real.best,bestYear: real.bestYear,block: DEFAULT_BLOCK_LENGTH,why,cards, // the kit's own DeckPeriod array — what every run is dealt from};}const RECORD_DECKS = {history: describeDeck('history', FULL_HISTORY_DECK, 'record', `US record ${RECORD.start}–${RECORD.end}`,'Every year from 1970 to 2024 as it happened — the widest real record the kit ships.'),stagflation: describeDeck('stagflation', createDeckFromYearRange(1973, 1982), 'regime', 'stagflation years 1973–1982','Two oil shocks and high inflation: ten years of prices outrunning the market.'),moderation: describeDeck('moderation', createDeckFromYearRange(1983, 2007), 'regime', 'calm years 1983–2007','The long calm — falling inflation and a steady climb. The kindest stretch the record holds.'),postgfc: describeDeck('postgfc', createDeckFromYearRange(2009, 2024), 'regime', 'post-crash years 2009–2024','The years after 2008: near-zero rates and a long recovery.'),turbulent: describeDeck('turbulent', RECENT_TURBULENT_DECK, 'regime', 'turbulent years 2000–2024','Two crashes and a pandemic inside 25 years, dealt in the order they happened.'),};export const DEFAULT_DECK_ID = 'history';export const ALT_DECK_ID = 'stagflation';// MARKET is the five real decks and nothing else. There is no fallback deck and no way to add one// from outside: a name that is not one of these is a mistake, and deckFor says so rather than// quietly dealing a different set of years. (The kit takes the same line with its samplers.)export const MARKET = Object.freeze(RECORD_DECKS);export const DECKS = Object.values(RECORD_DECKS);export function deckFor(id) {const deck = RECORD_DECKS[id];if (deck === undefined) {throw new Error(`roth-v7: there is no deck called '${String(id)}'. The decks are ` +`${Object.keys(RECORD_DECKS).join(', ')} — each one a stretch of the ${RECORD.start}–${RECORD.end} record.`,);}return deck;}// What every run is, unless a caller says otherwise. The board prints this beside the chart rather// than repeating the words in its own markup.export const RUN_DEFAULTS = Object.freeze({seed: 7, paths: 400, method: DEFAULT_METHOD, methodLabel: METHOD_LABEL[DEFAULT_METHOD],deckId: DEFAULT_DECK_ID, record: `${RECORD.start}–${RECORD.end}`, real: true,});function resolveDeck(market) {if (typeof market === 'string') return deckFor(market);if (market && Array.isArray(market.cards)) return market;if (market && market.id) return deckFor(market.id);throw new Error('roth-v7: that is not one of the record decks, so there are no real years to deal. ' +'Pass a deck from MARKET (' + Object.keys(RECORD_DECKS).join(', ') + ').',);}// ---- crises: the real cards of the years they name ----------------------------------------// A preset does not apply a drawdown. It deals the actual cards of 2008 then 2009 (or 2000, 2001,// 2002; or 2020) at the chosen year. `marketDrawdown` is then a MEASUREMENT — what those years did,// compounded, in real terms — not an assumption.const RECORD_BY_YEAR = new Map(FULL_HISTORY_DECK.map((card) => [card.year, card]));export function cardsForYears(years) {return years.map((y) => {const card = RECORD_BY_YEAR.get(y);if (card === undefined) {throw new Error(`roth-v7: ${y} is not in the record (${RECORD.start}–${RECORD.end}), so there is no real card to deal for it.`);}return card;});}function compoundedReal(cards) {const reals = buildDeckFisherTable(cards);return reals.reduce((acc, r) => acc * (1 + r.equityReal), 1);}function stressPreset(id, label, years, incomeLossFraction, cited) {const cards = cardsForYears(years);const compounded = compoundedReal(cards);return {id, label, years, incomeLossFraction, cited,durationYears: years.length,marketDrawdown: 1 - compounded,compounded,what: `${years.join(', ')} dealt as they happened: ${((compounded - 1) * 100).toFixed(1)}% in real terms over ${years.length} year${years.length > 1 ? 's' : ''}.`,};}export const STRESS_PRESETS = [stressPreset('gfc_2008', '2008-style crisis', [2008, 2009], 0.2, 'S&P 500 peak-to-trough −56.8% (Oct 2007 → Mar 2009)'),stressPreset('dotcom_2000', 'Extended bear market', [2000, 2001, 2002], 0.1, 'S&P 500 −49.1% (Mar 2000 → Oct 2002)'),stressPreset('covid_2020', 'COVID-style disruption', [2020], 0.15, 'S&P 500 −33.9% (Feb–Mar 2020)'),];// ---- policies: (t, T, wealth, ctx) -> the exposure the rule asks for ------------------------export const policies = {level: (f = 0.6) => () => f,glide: (start = 0.9, end = 0.3) => (t, T) => start + (end - start) * (t / Math.max(1, T - 1)),// Ayres–Nalebuff lifecycle: target risky DOLLARS = k × (wealth + present value of future// contributions). Early on that asks for more than the account holds; `cap` is what the editor// will DRAW, and the run still only ever holds 100% (see holdable() below).lifecycle: (k = 0.7, disc = 0.02, cap = HOLDING_CAP) => (t, T, w, ctx) => {let pv = 0; for (let s = t; s < T; s++) pv += ctx.contribution / Math.pow(1 + disc, s - t);return Math.min(cap, Math.max(0, (k * (w + pv)) / Math.max(1, w)));},openLoop: (blocks) => (t, T) => blocks[Math.min(blocks.length - 1, Math.floor((t / T) * blocks.length))],qTable: (Q, actions, goal) => (t, T, w) => { const s = qState(t, T, w, goal); let b = 0; for (let a = 1; a < actions.length; a++) if (Q[s][a] > Q[s][b]) b = a; return actions[b]; },};// What the account can actually hold this year. Demand above this is drawn, never earned on.const holdable = (f) => Math.min(HOLDING_CAP, Math.max(0, f));// ---- one year, by the kit -------------------------------------------------------------------// runSinglePath over a one-card deck: identical arithmetic to the kit's multi-year call, which// reads only deck[cardIndex], allocationsByYear[year] and annualContributionsByYear[year].const FIRST_CARD = [0];function stepYear(wealth, allocation, contribution, card, method) {const walked = runSinglePath({initialWealth: wealth,annualContributionsByYear: [contribution],allocationsByYear: [allocation],horizonYears: 1,deck: [card],constraints: CONSTRAINTS,samplingMethod: method,}, undefined, FIRST_CARD);return walked[1];}// The card matrix: which real year each path is dealt in each of its years. Straight from the// kit's sequencer registry, on the kit's seeded generator — the same construction runDeckSimulation// performs, which is why the parity law can hold to the cent.export function cardMatrix(deckLength, years, paths, seed, method = DEFAULT_METHOD) {const sequencer = createCardSequencer(samplingMethodToSequencerId(method));return sequencer.generate(deckLength, years, paths, new SeededRandom(seed), { seed });}// ---- the lived past --------------------------------------------------------------------------// Years already lived are not a simulation: they are the last n real years of the deck, the same// for every path. The fan collapses to a line on the left, and every future re-opens from the// balance the record actually produced.export const ELAPSED = { years: 0 };export function pastCards(market, n) {const deck = resolveDeck(market);return deck.cards.slice(Math.max(0, deck.cards.length - n));}export function pastReturns(market, seed, n) {return buildDeckFisherTable(pastCards(market, n)).map((r) => r.equityReal);}// ---- the run ---------------------------------------------------------------------------------/*** The saving deposited in year t: the saver's own schedule when the arch carries one (its last year repeated past its* end), else the flat contribution. One writer for the rule (2026-10-21): simulate(), windows() and snsw-engine.js* read this, because windows() once kept its own copy, deposited the flat contribution, and replayed a saver with a* schedule as a different saver (windows-schedule.vitest.ts).*/export function depositAt(arch, t) {return arch.contribSchedule ? (arch.contribSchedule[Math.min(arch.contribSchedule.length - 1, t)] || 0) : arch.annualContribution;}export function simulate(arch, policy, opts = {}) {const {paths = 400, seed = 7, market = MARKET[DEFAULT_DECK_ID], method = DEFAULT_METHOD,shock = null, shockYear = null, miss = null, elapsed = ELAPSED.years,} = opts;const deck = resolveDeck(market);const cards = deck.cards;const T = arch.horizonYears;const matrix = cardMatrix(cards.length, T, paths, seed, method);const nPast = Math.max(0, Math.min(T, elapsed | 0));const lived = nPast > 0 ? pastCards(deck, nPast) : null;const shockCards = shock && shock.years ? cardsForYears(shock.years) : null;if (shock && !shockCards) {throw new Error('roth-v7: a crisis has to name its years — v7 deals the real cards of those years rather than applying a drawdown.');}const shockLen = shockCards ? (shock.durationYears || shockCards.length) : 0;const ctx = { contribution: arch.annualContribution };const yearly = Array.from({ length: T + 1 }, () => []);const exposure = new Array(T).fill(0);const demand = new Array(T).fill(0);const terminal = new Array(paths);for (let p = 0; p < paths; p++) {let w = arch.startingBalance; let sittingOut = 0; let peak = w;yearly[0].push(w);for (let t = 0; t < T; t++) {const asked = policy(t, T, w, ctx);let f = holdable(asked);if (miss && sittingOut > 0) { f = 0; sittingOut--; }exposure[t] += f; demand[t] += Math.max(0, asked);let card = lived && t < nPast ? lived[t] : cards[matrix[p][t]];if (shockCards && t >= shockYear && t - shockYear < shockCards.length) card = shockCards[t - shockYear];let contrib = depositAt(arch, t);if (shockCards && t >= shockYear && t < shockYear + shockLen) contrib *= 1 - (shock.incomeLossFraction || 0);w = stepYear(w, f, contrib, card, method);if (miss) { peak = Math.max(peak, w); if (w < peak * (1 - miss.drawdown) && sittingOut === 0) { sittingOut = miss.years; peak = w; } }yearly[t + 1].push(w);}terminal[p] = w;}// Percentiles are the kit's canonical ones (Hyndman & Fan type 7), from ALL paths.const sortedY = yearly.map((y) => [...y].sort((a, b) => a - b));const pctGrid = sortedY.map((sy) => Array.from({ length: 101 }, (_, k) => percentileFromSorted(sy, k / 100)));const sortedT = [...terminal].sort((a, b) => a - b);const shareAbove = (t, g) => {const sy = sortedY[Math.min(sortedY.length - 1, t)];let lo = 0, hi = sy.length;while (lo < hi) { const mid = (lo + hi) >> 1; if (sy[mid] < g) lo = mid + 1; else hi = mid; }return (sy.length - lo) / sy.length;};const atYear = (k) => pctGrid.map((row) => row[k]);return {T, terminal, yearly, pctGrid, shareAbove,quantileAt: (t, k) => pctGrid[Math.min(pctGrid.length - 1, t)][Math.max(0, Math.min(100, Math.round(k * 100)))],p10: atYear(10), p50: atYear(50), p90: atYear(90),exposure: exposure.map((e) => e / paths),demand: demand.map((e) => e / paths),t10: percentileFromSorted(sortedT, 0.1), t50: percentileFromSorted(sortedT, 0.5), t90: percentileFromSorted(sortedT, 0.9),probBelow: (g) => terminal.filter((x) => x < g).length / terminal.length,meanLog: terminal.reduce((s, x) => s + Math.log(Math.max(1, x)), 0) / terminal.length,pastReturns: lived ? buildDeckFisherTable(lived).map((r) => r.equityReal) : null,pastYears: lived ? lived.map((c) => c.year) : null,// what the run was: the board prints this rather than repeating it as textmeta: { deckId: deck.id, deck: deck.deck, years: deck.years, n: deck.n, method, methodLabel: METHOD_LABEL[method], seed, paths, real: true },};}// ---- Kelly: how much is too much, from the deck's own record --------------------------------// Growth per year at a constant exposure f, measured over the deck's real cards: the average of// log(1 + portfolio real return) card by card, with the kit computing the portfolio return.// Kelly itself is (mean − safe) / spread², all three read off the same cards. The band is the// estimate's own uncertainty: with n years of record, the mean is only known to ±sigma/√n, and// n is the deck's card count — not an assumed sample size.export function kellyCurve(market = MARKET[DEFAULT_DECK_ID]) {const deck = resolveDeck(market);const reals = buildDeckFisherTable(deck.cards);const fs = []; for (let f = 0; f <= 2.0001; f += 0.1) fs.push(+f.toFixed(1));const growth = fs.map((f) => {let s = 0;for (const r of reals) s += Math.log(Math.max(1e-6, 1 + computePortfolioReturnFromReals(f, r, DEFAULT_CONSTRAINTS)));return s / reals.length;});const kelly = (deck.mu - deck.safe) / (deck.sigma * deck.sigma);const n = deck.n;const se = deck.sigma / Math.sqrt(n);return {fs, growth, kelly, n,kellyLow: (deck.mu - se - deck.safe) / (deck.sigma ** 2),kellyHigh: (deck.mu + se - deck.safe) / (deck.sigma ** 2),half: kelly / 2,mu: deck.mu, sigma: deck.sigma, safe: deck.safe, deck: deck.deck, years: deck.years,};}// ---- 30-year windows of the real record ------------------------------------------------------// Every 30-year stretch the record contains, one per start year: 1970–1999, 1971–2000, … 1995–2024.// Each window is dealt in calendar order — no resampling, no draw. This is the record answering// "what did thirty years actually do", 26 times.// Each year deposits depositAt(), as simulate() does, and a policy reads the same deposits snsw-engine.js's simulate()// hands it (ctx.deposits), so a rule that counts the saving still to come replays as it runs (2026-10-21; until then// it deposited the flat contribution always; windows-schedule.vitest.ts holds the replay to simulate()'s, to the bit).export function windows(arch, policyA, policyB, seed = 5, windowYears = 30, stride = 1, market = MARKET[DEFAULT_DECK_ID]) {const deck = resolveDeck(market);const cards = deck.cards;const deposits = Array.from({ length: windowYears }, (_, t) => depositAt(arch, t));const run = (policy, start) => {let w = arch.startingBalance; const ctx = { contribution: arch.annualContribution, deposits }; const T = windowYears;for (let t = 0; t < T; t++) {const f = holdable(policy(t, T, w, ctx));w = stepYear(w, f, deposits[t], cards[start + t], 'sequential');}return w;};const out = [];for (let s = 0; s + windowYears <= cards.length; s += stride) {out.push({start: s,startYear: cards[s].year,endYear: cards[s + windowYears - 1].year,label: `${cards[s].year}–${cards[s + windowYears - 1].year}`,a: run(policyA, s),b: run(policyB, s),});}return { windows: out, series: deck.series, deck: deck.deck, years: deck.years, windowYears, basis: `the ${deck.years} record, ${windowYears}-year windows every year` };}// ---- Q-table state bucket: period tercile × wealth-vs-goal ratio -----------------------------export const Q_ACTIONS = [0.2, 0.4, 0.6, 0.8, 1.0];export function qState(t, T, w, goal) {const tb = Math.min(2, Math.floor((3 * t) / T));const ratio = w / Math.max(1, goal(t));const wb = ratio < 0.5 ? 0 : ratio < 0.8 ? 1 : ratio < 1.0 ? 2 : ratio < 1.3 ? 3 : 4;return tb * 5 + wb;}// Monte Carlo control with a tabular Q (first-visit MC, ε-greedy). Reward: log terminal wealth.// Each training episode is dealt a real row of cards by the kit's sequencer; only the ε-greedy// coin is random here.export function trainQ(arch, opts = {}) {const { episodes = 2500, seed = 21, market = MARKET[DEFAULT_DECK_ID], method = DEFAULT_METHOD, eps0 = 0.6, targetTerminal } = opts;const T = arch.horizonYears; const deck = resolveDeck(market); const cards = deck.cards;const r = rng(seed); const ctx = { contribution: arch.annualContribution };const rows = cardMatrix(cards.length, T, episodes, seed, method);const goal = (t) => targetTerminal * Math.pow(t / T, 1.15) + arch.startingBalance * (1 - t / T);const Q = Array.from({ length: 15 }, () => new Array(Q_ACTIONS.length).fill(0));const N = Array.from({ length: 15 }, () => new Array(Q_ACTIONS.length).fill(0));const curve = [];let running = 0;for (let e = 0; e < episodes; e++) {const eps = eps0 * (1 - e / episodes) + 0.05;let w = arch.startingBalance; const visits = [];for (let t = 0; t < T; t++) {const s = qState(t, T, w, goal);let a; if (r.next() < eps) a = Math.floor(r.next() * Q_ACTIONS.length); else { a = 0; for (let k = 1; k < Q_ACTIONS.length; k++) if (Q[s][k] > Q[s][a]) a = k; }visits.push([s, a]);w = stepYear(w, holdable(Q_ACTIONS[a]), ctx.contribution, cards[rows[e][t]], method);}const G = Math.log(Math.max(1, w)) - 0.6 * Math.max(0, Math.log(targetTerminal) - Math.log(Math.max(1, w)));const seen = new Set();for (const [s, a] of visits) { const key = s * 10 + a; if (seen.has(key)) continue; seen.add(key); N[s][a]++; Q[s][a] += (G - Q[s][a]) / N[s][a]; }running += (G - running) / Math.min(e + 1, 100);if (e % Math.ceil(episodes / 40) === 0) curve.push(running);}return { Q, N, goal, curve, policy: policies.qTable(Q, Q_ACTIONS, goal) };}// TPE-style open-loop search over per-block exposure. Objective: P10 terminal (the shortfall side).// Candidate proposals use the kit's seeded generator; every evaluation is a kit run.export function tpeOpenLoop(arch, opts = {}) {const { trials = 64, blocks = 5, seed = 33, market = MARKET[DEFAULT_DECK_ID], method = DEFAULT_METHOD, paths = 400, objective = 'p10' } = opts;const r = rng(seed); const hist = [];const score = (x) => { const s = simulate(arch, policies.openLoop(x), { paths, seed: 101, market, method }); return objective === 'p10' ? s.t10 : objective === 'p50' ? s.t50 : s.meanLog; };for (let i = 0; i < trials; i++) {let x;if (i < 16) x = Array.from({ length: blocks }, () => 0.2 + 0.8 * r.next());else {const sorted = [...hist].sort((a, b) => b.y - a.y); const good = sorted.slice(0, Math.max(3, Math.floor(sorted.length * 0.25)));const c = good[Math.floor(r.next() * good.length)].x; x = c.map((v) => Math.min(1, Math.max(0, v + 0.12 * r.gauss())));}const y = score(x); hist.push({ x, y, i });}const best = hist.reduce((a, b) => (b.y > a.y ? b : a));return { hist, best, policy: policies.openLoop(best.x), blocks: best.x };}// Pairwise sensitivity: what it costs (in P10 ending balance) to get two inputs wrong at once.// v6's last two rows defaulted a made-up mean and volatility. There is no such dial here, so the// two market rows are now the two real choices a reader actually makes: WHICH stretch of the// record to answer from, and HOW the years are dealt. Both variants are real kit runs.export const INPUTS = ['horizon', 'contribution', 'start balance', 'exposure tilt', 'which record', 'how it is dealt'];export function ablation(arch, seed = 44, basePolicy = policies.glide(0.9, 0.3), market = MARKET[DEFAULT_DECK_ID]) {const base = simulate(arch, basePolicy, { paths: 200, seed, market }).t10;const variant = (mask) => {const a = { ...arch }; let pol = basePolicy; let mk = market; let method = DEFAULT_METHOD;if (mask[0]) a.horizonYears = 30;if (mask[1]) a.annualContribution = 7000;if (mask[2]) a.startingBalance = 100000;if (mask[3]) pol = policies.level(0.6);if (mask[4]) mk = MARKET[ALT_DECK_ID];if (mask[5]) method = 'sequential';return simulate(a, pol, { paths: 200, seed, market: mk, method }).t10;};const grid = [];for (let i = 0; i < INPUTS.length; i++) {const row = [];for (let j = 0; j < INPUTS.length; j++) { const mask = new Array(6).fill(false); mask[i] = true; mask[j] = true; row.push(Math.abs(variant(mask) - base) / base); }grid.push(row);}return { grid, base };}export const fmt = {// Choose the unit AFTER rounding, so $999,600 is not printed as $1000k.money: (v) => (Math.round(Math.abs(v) / 1000) >= 1000 ? '$' + (v / 1e6).toFixed(2) + 'M' : '$' + Math.round(v / 1000) + 'k'),pct: (v, d = 0) => (v * 100).toFixed(d) + '%',years: (v) => v.toFixed(1) + ' yr',};// ---- the one number the board and the test share ---------------------------------------------// The first thing the page prints when it opens: the middle ending balance for the mid-career// saver on the board's opening scenario, over the record, seed 7, 400 paths, block bootstrap.// Exported so the page and the parity law read the SAME definition — the test computes// it in node and the browser prints it; if they can disagree, one of them is not the kit.export const ARRIVAL = Object.freeze({ archId: 'mid-career', shape: 'lifecycle', deckId: DEFAULT_DECK_ID, method: DEFAULT_METHOD, seed: 7, paths: 400 });export function arrivalMeasurement() {const arch = ARCHETYPES.find((a) => a.id === ARRIVAL.archId);const run = simulate(arch, policies.lifecycle(0.7, 0.02, LIMITS.cap), {paths: ARRIVAL.paths, seed: ARRIVAL.seed, market: MARKET[ARRIVAL.deckId], method: ARRIVAL.method, elapsed: 0,});return {...ARRIVAL,median: run.t50,text: fmt.money(run.t50),low: run.t10, high: run.t90,says: `Middle ending balance, in today's dollars, over the ${MARKET[ARRIVAL.deckId].years} record.`,};}// SVG helpers — path strings for template binding.export function linePath(values, w, h, yMax, yMin = 0, xN = values.length - 1) {return values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / xN) * w).toFixed(1)},${(h - ((v - yMin) / (yMax - yMin)) * h).toFixed(1)}`).join(' ');}export function bandPath(lo, hi, w, h, yMax, yMin = 0) {const n = lo.length - 1;const up = hi.map((v, i) => `${((i / n) * w).toFixed(1)},${(h - ((v - yMin) / (yMax - yMin)) * h).toFixed(1)}`);const dn = lo.map((v, i) => `${((i / n) * w).toFixed(1)},${(h - ((v - yMin) / (yMax - yMin)) * h).toFixed(1)}`).reverse();return 'M' + up.join(' L') + ' L' + dn.join(' L') + ' Z';}export function histogram(values, bins, lo, hi) {const counts = new Array(bins).fill(0);for (const v of values) { const k = Math.min(bins - 1, Math.max(0, Math.floor(((v - lo) / (hi - lo)) * bins))); counts[k]++; }return counts;}// ---- control-point glidepaths and structured closed-loop policies ----------------------------// The editor's ceiling for DRAWING a rule's demand. What a run holds is capped at 100% either way[this line carries wording the site no longer uses and is not shown here]// year that was earned on.export const LIMITS = { cap: HOLDING_CAP };export const clamp01 = (v) => Math.min(LIMITS.cap, Math.max(0, v));export function interpPts(pts, T) {const s = [...pts].sort((a, b) => a.t - b.t); const out = new Array(T);for (let t = 0; t < T; t++) {if (t <= s[0].t) out[t] = s[0].v; else if (t >= s[s.length - 1].t) out[t] = s[s.length - 1].v;else { let i = 0; while (s[i + 1].t < t) i++; const a = s[i], b = s[i + 1]; out[t] = b.t === a.t ? b.v : a.v + (b.v - a.v) * ((t - a.t) / (b.t - a.t)); }out[t] = clamp01(out[t]);}return out;}export const goalFor = (arch, target) => (t) => target * Math.pow(t / arch.horizonYears, 1.15) + arch.startingBalance * (1 - t / arch.horizonYears);export function wealthBucket(w, g) { const r = w / Math.max(1, g); return r < 0.5 ? 0 : r < 0.8 ? 1 : r < 1.0 ? 2 : r < 1.3 ? 3 : 4; }export const BUCKETS = ['far behind', 'behind', 'on track', 'ahead', 'far ahead'];policies.yearly = (arr) => (t) => arr[Math.min(arr.length - 1, t)];policies.structured = (arr, offsets, goal) => (t, T, w) => clamp01(arr[Math.min(arr.length - 1, t)] + offsets[wealthBucket(w, goal(t))]);policies.heat = (map, goal) => (t, T, w) => map[Math.min(map.length - 1, t)][wealthBucket(w, goal(t))];// Build the policy for a scenario's policy object.export function buildPolicy(pol, arch) {const T = arch.horizonYears;if (pol.kind === 'glide') return policies.yearly(interpPts(pol.pts, T));if (pol.kind === 'closed') return policies.structured(interpPts(pol.pts, T), pol.offsets, goalFor(arch, pol.target));if (pol.kind === 'heat') return policies.heat(pol.map, goalFor(arch, pol.target));return policies.level(0.6);}export function policyMap(pol, arch) { // T×5 exposure surface, for the heatmap viewconst T = arch.horizonYears;if (pol.kind === 'heat') return pol.map;const arr = interpPts(pol.pts, T);return arr.map((v) => [0, 1, 2, 3, 4].map((b) => clamp01(v + (pol.kind === 'closed' ? pol.offsets[b] : 0))));}// Search control points around their current position. moveT lets interior points move in time.export function optimizePts(arch, pol, opts = {}) {const { trials = 40, sigmaV = 0.12, sigmaT = 0, moveT = false, seed = 55, market = MARKET[DEFAULT_DECK_ID], method = DEFAULT_METHOD, paths = 300 } = opts;const T = arch.horizonYears; const r = rng(seed);const score = (pts) => simulate(arch, buildPolicy({ ...pol, pts }, arch), { paths, seed: 101, market, method }).t10;let best = { pts: pol.pts.map((p) => ({ ...p })), y: score(pol.pts) }; const hist = [best];for (let i = 0; i < trials; i++) {const src = hist[Math.floor(r.next() * Math.min(hist.length, 4))]; // sample from the recent good setconst pts = src.pts.map((p, k) => ({ t: moveT && k > 0 && k < src.pts.length - 1 ? Math.round(Math.min(T - 2, Math.max(1, p.t + sigmaT * r.gauss()))) : p.t, v: clamp01(+(p.v + sigmaV * r.gauss()).toFixed(2)) }));const y = score(pts); const cand = { pts, y };hist.push(cand); hist.sort((a, b) => b.y - a.y); hist.length = Math.min(hist.length, 8);if (y > best.y) best = cand;}return best;}export function addPoint(pts, T) { // midpoint of the longest segmentconst s = [...pts].sort((a, b) => a.t - b.t); let bi = 0, bl = -1;for (let i = 0; i < s.length - 1; i++) { const l = s[i + 1].t - s[i].t; if (l > bl) { bl = l; bi = i; } }if (bl < 2) return s;const a = s[bi], b = s[bi + 1]; const t = Math.round((a.t + b.t) / 2);return [...s.slice(0, bi + 1), { t, v: +((a.v + b.v) / 2).toFixed(2) }, ...s.slice(bi + 1)];}export const GLIDE_STAGES = [{ id: 'values', label: 'Coarse — point values', moveT: false, trials: 36, sigmaV: 0.15 },{ id: 'timing', label: 'Timing — move points in time', moveT: true, trials: 36, sigmaV: 0.08, sigmaTFrac: 1 / 8 },{ id: 'refine', label: 'Fine — add a point, refine', add: true, moveT: true, trials: 44, sigmaV: 0.05, sigmaTFrac: 1 / 14 },];export function runGlideStage(arch, pol, stage, market) {const T = arch.horizonYears; let pts = stage.add ? addPoint(pol.pts, T) : pol.pts;const best = optimizePts(arch, { ...pol, pts }, { trials: stage.trials, sigmaV: stage.sigmaV, sigmaT: (stage.sigmaTFrac || 0) * T, moveT: stage.moveT, market, seed: 55 + stage.trials });return { pol: { ...pol, pts: best.pts }, score: best.y };}// Q-table with a chosen time resolution; can warm-start from a coarser Q.export const Q_STAGES = [3, 5, 10];export function trainQAt(arch, opts = {}) {const { tBuckets = 3, episodes = 1200, seed = 21, market = MARKET[DEFAULT_DECK_ID], method = DEFAULT_METHOD, eps0 = 0.5, target, prevQ = null, prevTb = 0 } = opts;const T = arch.horizonYears; const deck = resolveDeck(market); const cards = deck.cards;const r = rng(seed + tBuckets); const goal = goalFor(arch, target);const rows = cardMatrix(cards.length, T, episodes, seed + tBuckets, method);const S = tBuckets * 5; const Q = Array.from({ length: S }, () => new Array(Q_ACTIONS.length).fill(0)); const N = Array.from({ length: S }, () => new Array(Q_ACTIONS.length).fill(0));if (prevQ) for (let s = 0; s < S; s++) { const tb = Math.floor(s / 5), wb = s % 5; const ptb = Math.min(prevTb - 1, Math.floor((tb / tBuckets) * prevTb)); for (let a = 0; a < Q_ACTIONS.length; a++) { Q[s][a] = prevQ[ptb * 5 + wb][a]; N[s][a] = 3; } }const st = (t, w) => Math.min(tBuckets - 1, Math.floor((tBuckets * t) / T)) * 5 + wealthBucket(w, goal(t));let running = 0;for (let e = 0; e < episodes; e++) {const eps = eps0 * (1 - e / episodes) + 0.05; let w = arch.startingBalance; const visits = [];for (let t = 0; t < T; t++) {const s = st(t, w);let a; if (r.next() < eps) a = Math.floor(r.next() * Q_ACTIONS.length); else { a = 0; for (let k = 1; k < Q_ACTIONS.length; k++) if (Q[s][k] > Q[s][a]) a = k; }visits.push([s, a]);w = stepYear(w, holdable(Q_ACTIONS[a]), arch.annualContribution, cards[rows[e][t]], method);}const G = Math.log(Math.max(1, w)) - 0.6 * Math.max(0, Math.log(target) - Math.log(Math.max(1, w))); const seen = new Set();for (const [s, a] of visits) { const key = s * 10 + a; if (seen.has(key)) continue; seen.add(key); N[s][a]++; Q[s][a] += (G - Q[s][a]) / N[s][a]; }running += (G - running) / Math.min(e + 1, 100);}const map = Array.from({ length: T }, (_, t) => [0, 1, 2, 3, 4].map((wb) => { const s = Math.min(tBuckets - 1, Math.floor((tBuckets * t) / T)) * 5 + wb; let a = 0; for (let k = 1; k < Q_ACTIONS.length; k++) if (Q[s][k] > Q[s][a]) a = k; return Q_ACTIONS[a]; }));return { Q, tBuckets, map, running };}// Fit a learned surface back to an editable structure: on-track row → 5 control points; offsets = mean row differences.export function fitStructured(map, T) {const idx = [0, Math.round((T - 1) / 4), Math.round((T - 1) / 2), Math.round((3 * (T - 1)) / 4), T - 1];const pts = idx.map((t) => ({ t, v: +map[t][2].toFixed(2) }));const offsets = [0, 1, 2, 3, 4].map((b) => +(map.reduce((s, row) => s + row[b] - row[2], 0) / T).toFixed(2));return { pts, offsets };}
Part four
The files that compute each printed figure
A figure on a Learn chapter is computed again by the files below, served here exactly as the build used them. Each is listed with its fingerprint, the hash of its bytes; the page checks every file it loads against these before it computes anything, and says so if one differs.
- snsw-ig-controller.v17.js, fingerprint d874b39688ea6d1e769353c9e14c6fe25ec46bde2cc3b1b41f332693dd530407, served at /save-now-spend-when/snsw-ig-controller.v17.js
- snsw-backtests.v2.js, fingerprint fb8d0491c7b78cd122ffad25303a1ee84832d2b4fc6c9269a1e171c680fda321, served at /save-now-spend-when/snsw-backtests.v2.js
- snsw-backtests.v1.js, fingerprint 9535ac59ecacf5683e295721e609bbddf54995f570ec5353700021abc3aecd5f, served at /save-now-spend-when/snsw-backtests.v1.js
A fingerprint is a short code that changes if any byte of the file it names changes.
The figures these pages explain are computed on the instrument.
Notes
About this page
The adapter imports the kit by name and adds only what the site needs. The files are shown as this site keeps them, with the digest of each. The served copy differs in one way: its kit imports are relative paths into a byte-identical copy of the kit that sits beside it, with a checksum list.