# meta-progression.js (G-09 module, v1.0.1)

One plain script, no dependencies, no `import`/`export`, ASCII only. It defines one global, `GameDNA_MetaProgression`. Paste it into a `<script>` tag or load it with `<script src>`, without changing it. It owns the **between-runs layer of a roguelite**: a currency earned per run, a hub with a permanent unlock tree (nodes, links, costs, prerequisites, ranks, a lit-up animation when a node is bought), the bonuses handed to the next run exactly once, a run-end summary that counts the earnings up, a run-start banner listing the bonuses, and saving (its own `localStorage` key with an export / import code, or your save). **Your game owns its run**: it calls `beginRun()` when a run starts, applies the bonus it gets back, and calls `endRun(lines)` when the run ends. The module enforces the rules (costs, prerequisites, ranks) and never touches your variables.

Drawn in code at any resolution (HD, devicePixelRatio-friendly when your context is scaled): a framed hall panel with gold trim, metal-rimmed node medallions with icons, glowing links with flowing light, cost tags, a detail card, keycap hints. Landscape views get the detail card on the right; portrait views (taller than wide) stack the tree over the card. Designed for logical views of 480x270 and up (it scales with the view; 640x360 is 1:1).

## Quick start (15 lines)

```js
const meta = GameDNA_MetaProgression.create({ view: { x: 0, y: 0, w: 640, h: 360 }, key: 'my-game', nodes: NODES,
  params: { title: 'THE EMBER HALL', currency: 'Embers' }, autoplay: () => AUTOPLAY, uiRects: () => myHudRects() });
function startRun() {                                  // your run setup, once per run
  const r = meta.beginRun();                           // r = {run, fresh, bonus}
  if (r.fresh) { hero.maxHp = BASE_HP + (r.bonus.maxHp || 0); hero.hp = hero.maxHp; }   // apply ONLY when fresh
}
function onRunOver(stats) {                            // once, when the run ends
  meta.endRun([{ label: 'Foes felled', count: stats.kills, rate: 0.05 }, { label: 'Victory', amount: stats.won ? 30 : 10 }]);
}
function step() { meta.update(1000 / 60); }            // every fixed step, every scene, fast-forwards included
function render(ctx) { /* your game, HUD, result screen */ meta.draw(ctx); }      // last
addEventListener('keydown', e => { if (meta.isOpen()) { meta.key(e.key); e.preventDefault(); return; }
  if (e.key === 'x' && betweenRuns) meta.openHub(); /* your keys */ });
canvas.addEventListener('pointerdown', e => { if (meta.pointer('down', ...toLogical(e))) return; /* yours */ });
```

## The tree is data

```js
const NODES = [
  { id: 'hearth', name: 'Hearth Oil', icon: 'heart', cost: 20, col: 0, row: 1, effects: { maxHp: 20 }, text: '+{value} max HP every run.' },
  { id: 'stride', name: 'Swift Stride', icon: 'boot', cost: 35, col: 1, row: 0, requires: ['hearth'], effects: { speed: 0.1 } },
  { id: 'whet', name: 'Whetstone', icon: 'sword', cost: [65, 90, 130], ranks: 3, col: 2, row: 0, requires: ['stride'], effects: { might: 0.08 } },
  { id: 'tithe', name: 'Ember Tithe', icon: 'coin', cost: 60, col: 2, row: 1, requires: ['stride', 'hearth'], effects: { earn: 0.25 } },
  { id: 'wick', name: 'Second Wick', icon: 'lantern', cost: 90, col: 3, row: 0, requires: ['whet'], effects: { startWeapon: 'ember-ring' } }
];
```

| field | meaning |
|---|---|
| `id` | **Required**, unique. Saves use it. |
| `name`, `icon`, `text` | Shown in the detail card. `text`: `{value}` = what the next rank adds, `{total}` = the total after it (numbers under 1 are shown as percent). Without `text` the effects are listed. |
| `cost` | Number, or one number per rank (`[65, 90, 130]`). `params.costScale` multiplies it. |
| `ranks` | Default 1. A node with ranks shows pips; each rank is bought separately. |
| `requires` | Ids that must be owned (rank 1+) first: ALL of them. Drawn as links. |
| `col`, `row` | Grid position (fractions allowed): `col` is the tier (left to right in landscape, top to bottom in portrait). |
| `effects` | `{key: number}` (per rank, summed), `{key: [r1, r2, r3]}` (amount of each rank), or `{key: 'text'}` (listed: `bonus[key]` becomes an array of those values, e.g. weapon ids). **Reserved key `earn`**: +fraction of currency from every run (the module applies it in `endRun`). Every other key is yours to apply. |
| `apply(rank, state)` | Optional code run once when bought (a cosmetic unlock, an achievement); never for run bonuses. |

Built-in icons (drawn in code): `ember heart boot magnet coin sword shield gem scroll card hourglass bolt crown leaf potion lantern star key eye` (and aliases `hp speed gold coins blade guard ward might time light crystal`). Pass `icon: (ctx, key, x, y, size) => true` to draw your own (painted icons, an atlas); return `false` to keep the built-in one.

## API

`GameDNA_MetaProgression.create(options)` returns an instance.

| option | meaning |
|---|---|
| `view` | `{x, y, w, h}`: your logical canvas rect. `setView()` when it changes (a portrait phone). |
| `key` | Storage namespace, unique to your game (`'gamedna-meta/<key>'`), and the game key of export codes. |
| `nodes`, `labels` | The tree; `labels` = `{effectKey: 'max HP'}` for the banner and chips (default: the key in words). |
| `params` | `title`, `subtitle`, `currency` ('Embers'), `currencyIcon` ('ember'), `buyVerb` ('KINDLE'), `theme` (`ember frost verdant royal`), `layout` (`auto landscape portrait`), `costScale` 1, `summaryTitle`, `earnLabel` ('Boon bonus'), `storeLabel` ('IN THE HALL'), `countMs` 420, `lineGap` 360, `banner` 'on', `bannerMs` 2900, `autoStepMs` 420, `dim` 0.72, `flow` 'on', `labels` 'on' (name above the selected node), `reduced` 'off', `entryLabel` ('HALL'), `entryKey` ('X'), `store` ('local' or 'none') |
| `store` | `'local'` (default: its own key, every call in try/catch, memory when blocked) or `'none'` (you save `serialize()` in your own save, e.g. I-04 save-slots). |
| `fresh` | `true` = ignore what is stored (tests, a fresh demo). A page with `?freeze=1` never reads or writes storage; `?metaFresh=1` ignores it; `?metaCode=<code>` preloads an export code (stills of a given progress). |
| `autoplay` | `true` / `false` or a function, read every step: while the hub is open under autoplay, its bot buys the cheapest affordable node one at a time (cursor visible, about 1 s each) and closes the hub when nothing is affordable. |
| `uiRects()` | Your HUD and panels `[{x, y, w, h}]`: the summary and the banner pick a place clear of them (and stay there once shown). |
| `icon(ctx, key, x, y, size)`, `frame(ctx, rect, kind)` | Your art: return `true` when you drew it (`kind` = `panel`, `card`, `summary`). |
| `onBuy(e)`, `onChange(data)`, `onOpen()`, `onClose()`, `onRunStart(bonus, run)`, `debug(e)` | Optional; all in try/catch. `debug` events: `begin`, `end`, `buy`, `save`, `load`, `import`, `open`, `close`, `grant`. |

| method | |
|---|---|
| `beginRun()` | At the start of every run. Returns `{run, fresh, bonus}`; **`fresh` is true once per run**: a second call before `endRun()` returns the same bonus with `fresh: false`. Apply the bonus only when fresh. Closes the hub, hides the summary, shows the banner. |
| `endRun(lines, {title, rect})` | Once, when the run ends. `lines` = `[{label, count, rate}]` (amount = floor(count x rate)) or `[{label, amount}]`; `earn` boons add their percent. Pays the wallet at once, then shows the summary counting up. Returns `{run, earned, base, extra, wallet, lines}`, or `null` if no run was begun (once per run). |
| `openHub({select})`, `closeHub()`, `isOpen()` / `busy()` | The hall. While open it is modal: route keys and pointers to it, keep your world paused or behind a menu. |
| `key(k)` | `'left' 'right' 'up' 'down' 'ok' 'back'` or `KeyboardEvent.key` / `.code` (`ArrowLeft`, `z`, `Enter`, `x`, `Escape`). Returns true when used (always true while open, except `'auto'`). |
| `pointer(type, x, y)` | `'down' 'move'` in logical px: tap a node to read it, tap it again (or the button) to buy; the round X closes. With the hub closed, a tap on the entry badge opens it. Returns true when used. |
| `update(ms)`, `draw(ctx)` | Every fixed step (the only clock: no timers, no wall time) / last in your draw pass. Never throw. |
| `showEntry(on, {x, y, align})` | A small badge (currency + `[X] HALL`, a dot when something is affordable) for your title or results screen. |
| `hideSummary()`, `summaryActive()`, `summaryDone()` | The summary stays until `hideSummary()`, `openHub()` or `beginRun()`. |
| `buy(id)`, `status(id)`, `canBuy(id)` | Rules from code (`status` = `{state: 'affordable' \| 'short' \| 'locked' \| 'max', cost, need, missing, rank, max}`). |
| `bonuses()`, `runBonus()`, `wallet()`, `owned()`, `run()`, `runActive()` | Read state. `bonuses()` = what the next run gets; `runBonus()` = what this run got. |
| `serialize()`, `deserialize(data)` | Plain data `{wallet, owned, runs, earned, spent}` for your own save; `deserialize` validates (no node without its prerequisites, ranks capped, wallet >= 0). |
| `exportText()`, `importText(code)` | A code `GDNAMETA1.<base64>.<checksum>`; import checks the checksum and the game key, returns `{ok, error}`. |
| `reset()`, `grant(n)` | Forget progress / add currency (tests and demos; counted). |
| `state()`, `stats()`, `layout()`, `lastDrawn()`, `lastTexts()`, `selfTest()`, `setParams()`, `params()`, `setNodes()`, `setAuto()` | For tests and judges. |

`GameDNA_MetaProgression.rules` = the pure rule functions (`status`, `buy`, `bonuses`, `earn`, `valid`, `encode`, `decode`) for checks.

## Keep the game's other callers working

- **One place starts a run, one place ends it.** Find every path that starts a run (the start key, a restart, the autoplay timer, a title that boots a new game at load) and call `beginRun()` only where the run really begins. If your new-game code also runs at load (before the title), do not call it there: `beginRun()` at load and again at the real start leaves the real start with `fresh: false`.
- **Apply on fresh only, as absolute values or once.** `base + bonus`, never `+=` on something that survives the run. If your run setup reads its config before your start hook runs, write the config from `bonuses()` before the run is created (absolute values) and still call `beginRun()` at the start.
- **The hub is between runs.** Open it from your title / results screen (a key, the entry badge), never during a run; close it when a run starts (`beginRun()` does). Under autoplay, open it yourself after the summary (`summaryDone()`) if you want the bot to spend; it closes itself. It must close before your autoplay moves on.
- **Keys while open** go to `meta.key()` and nowhere else (keep your pause / autoplay toggle key). The key that opens it must not also act in your game.
- **`?t=&freeze=1`**: `update()` inside the fixed step; nothing reads storage on such a page, so stills never depend on a player's save. `?auto=1`: the run plays as before; the bot only spends between runs.
- **Saving**: own key by default. With your own save system pass `store: 'none'` and put `meta.serialize()` in your save, `meta.deserialize()` in your load.

## Self-check without a browser

1. The module file is byte-identical to the one you were given and loads before your game script.
2. Grep `beginRun(`: one call, where every run starts (not at load); the bonus is applied inside `if (r.fresh)`. Grep `endRun(`: one call per run end, with the run's numbers.
3. Walk one run by hand: a run ends with 1044 kills at rate 0.05 and a 30 win bonus -> 52 + 30 = 82 (+25 % with an earn boon = 102); buy a 20-cost root -> wallet - 20; the next run starts with base + 20 max HP, and a second `beginRun()` in that run returns `fresh: false`.
4. `update(` every step in every scene; `draw(` last; `openHub(` only between runs; keys go to `key()` while `isOpen()`.

## What it guarantees

- Costs, prerequisites and ranks are enforced by the module: no purchase without the currency and every prerequisite; the wallet never goes below 0.
- Bonuses are handed out `fresh` once per run; `endRun` pays once per run.
- Stored data is checksummed: a damaged value starts fresh (kept under `<key>-damaged`), a hand-edited one is cleaned (nodes without prerequisites dropped); export codes are checked.
- Same calls = same frames: animation runs on `update()` only; a seeded RNG for sparks.
