Spaces:
Paused
Merge pull request #89: evolve the AI — a genome, mutation, and crossover
Browse filesParameterises the AI so it can evolve by mutation or by crossing two AIs, and
runs the first search. Zero files under engine/ change -- a candidate AI was
already JSON, so the genotype lives entirely in tools/.
tools/genome.js: GENOME_SCHEMA (28 genes, two chromosomes, six linkage groups)
with one operator per gene KIND -- multiplicative for ratios, additive for
counts so 0 stays reachable, rare flips for the epistatic switches, sequence
operators for the unitMix production cycle. Crossover cuts at module boundaries,
which map one-to-one onto the engine files that consume them.
ailab evolve: population, elites, tournament selection, self-adaptive step size,
fitness = Swiss-scheduled duel Elo anchored by the four shipped baselines,每
difficulty bracket rated separately and aggregated by the worst.
Two pre-existing bench bugs fixed: runDuel never forwarded a candidate's own
archetype (so every CLI duel gave both seats the world's temperament), and
duelSeed hashes the candidate names (so generated names drew their own maps each
generation) -- now an optional seedKey, byte-identical when omitted.
The first run's champion generalises -- it beats all four hand-tuned strategies
on four held-out worlds at full match length, 78% at Medium and 63% at Hard --
and is deliberately NOT promoted, because at Hard all 40 of its wins are
timeout-score and none is an elimination. It exploits victory.js's tiebreak
rather than playing better. Recorded as a candidate file with the reasoning in
docs/ai-evolution-design.md and the search ledger.
Suite 2401 -> 2433, zero regressions. ailab check's named-defect list did not
grow.
- CHANGELOG.md +15 -0
- docs/ai-evolution-design.md +547 -0
- docs/odyssey-ai-review.md +5 -0
- test/ailab.test.js +123 -0
- test/duelCore.test.js +30 -0
- test/genome.test.js +328 -0
- tools/ailab.js +340 -2
- tools/candidates/evolved-strategy.json +22 -0
- tools/duelCore.js +13 -2
- tools/genome.js +499 -0
|
@@ -62,6 +62,21 @@ All notable changes to this project are documented here. The format follows
|
|
| 62 |
Arsenal gate and fields a real Tier-2/3 composition instead of Skiffs only, and a `--apm`
|
| 63 |
flag so a probe can exercise a difficulty row's real APM throttle instead of always running
|
| 64 |
unthrottled.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
### Added
|
| 67 |
|
|
|
|
| 62 |
Arsenal gate and fields a real Tier-2/3 composition instead of Skiffs only, and a `--apm`
|
| 63 |
flag so a probe can exercise a difficulty row's real APM throttle instead of always running
|
| 64 |
unthrottled.
|
| 65 |
+
- **The AI opponent can now be EVOLVED** — `node tools/ailab.js evolve` breeds a population of
|
| 66 |
+
AI "genomes" (`tools/genome.js`: the dial tables as a schema'd, mutable, crossable data
|
| 67 |
+
structure) and selects them by real head-to-head self-play, with the four shipped strategies
|
| 68 |
+
riding along as a fixed rating anchor. Mutation is per gene *kind* — multiplicative for
|
| 69 |
+
ratios, additive for headcounts, rare flips for the switches that decide whether other genes
|
| 70 |
+
mean anything, and sequence operators for the unit-mix production cycle — and crossover cuts
|
| 71 |
+
at the boundaries between functional modules (offense / economy / defense / composition), so
|
| 72 |
+
a child inherits a working sub-plan intact rather than a shredded one. Nothing under
|
| 73 |
+
`engine/` changed: a candidate AI was already just JSON, which is what makes this possible at
|
| 74 |
+
all. Design, traps and results: `docs/ai-evolution-design.md`.
|
| 75 |
+
Two supporting fixes fell out of building it, both of which had been silently wrong:
|
| 76 |
+
`runDuel` never forwarded a candidate's own archetype to the match runner (so a CLI duel gave
|
| 77 |
+
both seats the *world's* temperament and ignored the candidate files), and `duelSeed` hashes
|
| 78 |
+
the candidates' names, so generated names drew their own map set every generation — it now
|
| 79 |
+
takes an optional `seedKey` to pin one, with today's derivation unchanged when it's omitted.
|
| 80 |
|
| 81 |
### Added
|
| 82 |
|
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evolving the AI — a genome, mutation, and crossover
|
| 2 |
+
|
| 3 |
+
*2026-08-06 — a brainstorm, not a commitment. No code changes accompany this document.*
|
| 4 |
+
|
| 5 |
+
The question: **how could the AI be parameterised so that it can evolve — by random mutation, or
|
| 6 |
+
by crossing over two AIs — and get better at the game?**
|
| 7 |
+
|
| 8 |
+
The short answer is that most of the machinery already exists and nobody has called it evolution.
|
| 9 |
+
`tools/ailab.js`'s `applyOverrides` is a genome loader. `tools/candidates/*.json` are genomes.
|
| 10 |
+
`runDuel`/`runSwissTournament` plus `elo.js` are a fitness function that pits individuals against
|
| 11 |
+
each other. `runSearch` is a search loop — just the weakest one in the family (a one-dial-at-a-time
|
| 12 |
+
coordinate scan). What is genuinely missing is three things: a **schema** that says what a legal
|
| 13 |
+
gene is, a set of **variation operators** (mutate, cross), and a **selection loop** that runs
|
| 14 |
+
generations instead of a single scan.
|
| 15 |
+
|
| 16 |
+
This document works through each, and then through the traps this particular codebase will spring.
|
| 17 |
+
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
## 1. The premise: a candidate AI is already data
|
| 21 |
+
|
| 22 |
+
`tools/ailab.js:508`:
|
| 23 |
+
|
| 24 |
+
```js
|
| 25 |
+
export function applyOverrides(ov = {}) {
|
| 26 |
+
for (const [name, row] of Object.entries(ov.strategies || {})) …
|
| 27 |
+
for (const [name, row] of Object.entries(ov.archetypes || {})) …
|
| 28 |
+
for (const [key, row] of Object.entries(ov.difficulties || {})) …
|
| 29 |
+
}
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Three plain exported tables — `STRATEGIES`, `ARCHETYPES`, `DIFFICULTY_OPTIONS` — every field of
|
| 33 |
+
which is read at its use site through `|| 1` or a falsy-flag default. That property is what makes
|
| 34 |
+
this whole idea cheap: **an arbitrary mutation is always a runnable AI.** There is no parser to
|
| 35 |
+
write, no patch to apply, no engine change, and no way for a malformed gene to crash a match — a
|
| 36 |
+
nonsense value produces a bad player, not an exception. Evolutionary algorithms need exactly that
|
| 37 |
+
(a *tolerant* genotype→phenotype map); most codebases have to be retrofitted for it and this one
|
| 38 |
+
already is, by accident of the `|| 1` convention.
|
| 39 |
+
|
| 40 |
+
`snapshotTables`/`restoreTables` (`tools/ailab.js:525`) already give clean isolation between
|
| 41 |
+
individuals, which is the other half of what a population loop needs.
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
|
| 45 |
+
## 2. The genome — three chromosomes, only two of which should evolve
|
| 46 |
+
|
| 47 |
+
| Layer | File | Evolve? | Why |
|
| 48 |
+
|---|---|---|---|
|
| 49 |
+
| **Strategy** | `engine/aiStrategy.js` | **Yes — the main chromosome** | Composes over any archetype; `galaxy.js:61` `neighbourAiProfile` draws strategies *uniformly at random*, so a new strategy row immediately populates ~1/N of the galaxy |
|
| 50 |
+
| **Archetype** | `engine/aiArchetypes.js` | **Yes, carefully** | Carries the world's identity (faction, unit mix, doctrine). Evolving it risks flattening the roster into one optimum — see §6E |
|
| 51 |
+
| **Difficulty** | `engine/aiDifficulty.js` | **No — freeze it** | It is the *fairness pin*. `pinnedDuelDials` (`tools/duelCore.js:34`) reads one difficulty row into one object both sides spread from. Let a genome touch it and fitness measures an APM edge, not strategy |
|
| 52 |
+
|
| 53 |
+
### 2.1 The gene inventory as it stands today
|
| 54 |
+
|
| 55 |
+
Everything the AI actually reads, with its type — this is the search space, and it is already
|
| 56 |
+
about 30-dimensional without adding a single new dial.
|
| 57 |
+
|
| 58 |
+
**Strategy chromosome** (`engine/aiStrategy.js`):
|
| 59 |
+
|
| 60 |
+
| Gene | Type | Read at |
|
| 61 |
+
|---|---|---|
|
| 62 |
+
| `attackTimeoutMult` | continuous ratio | `aiMilitary.js` `aiOffense` |
|
| 63 |
+
| `armyAttackSizeMult` | continuous ratio | `aiMilitary.js` |
|
| 64 |
+
| `garrisonMult` | continuous ratio | `aiMilitary.js` |
|
| 65 |
+
| `workerTargetMult` | continuous ratio | `aiEconomy.js:170` |
|
| 66 |
+
| `turretCountMult` | continuous ratio | `aiEconomy.js` |
|
| 67 |
+
| `standingArmyCap` | integer count | `aiEconomy.js` |
|
| 68 |
+
| `warFootingMult` | continuous ratio | `aiEconomy.js` |
|
| 69 |
+
| `warFootingTime` | seconds | `ai.js:146`, `aiEconomy.js` |
|
| 70 |
+
| `matchBuffer` | continuous ratio | `aiEconomy.js` |
|
| 71 |
+
| `matchFloor` | integer count | `aiEconomy.js` |
|
| 72 |
+
| `graceMult` / `grievanceMult` / `forgiveness` | continuous ratio | `engine/diplomacy.js` |
|
| 73 |
+
| `matchEnemyForce` | **flag** | `aiEconomy.js` |
|
| 74 |
+
| `neverInitiates` | **flag** | `aiMilitary.js` (×3) |
|
| 75 |
+
| `useBombOffensively` | **flag** | `aiSuperweapon.js` |
|
| 76 |
+
| `wantsIndustryAlways` | **flag** | `aiIndustry.js` (×2) |
|
| 77 |
+
|
| 78 |
+
**Archetype chromosome** (`engine/aiArchetypes.js`), plus its `odyssey:` overlay which shadows the
|
| 79 |
+
same names when `state.diplomacy` exists (`ai.js:133`, the `arch` reader):
|
| 80 |
+
|
| 81 |
+
| Gene | Type |
|
| 82 |
+
|---|---|
|
| 83 |
+
| `workerTarget`, `armyAttackSize`, `turretCount`, `maxBarracks`, `garrison`, `odyssey.probeMin` | integer counts |
|
| 84 |
+
| `attackTimeout` | seconds |
|
| 85 |
+
| `expandWhenNodesBelow` | continuous, bounded 0–1 |
|
| 86 |
+
| `wantsRefinery` | flag |
|
| 87 |
+
| `doctrine` | **categorical** (`assault` \| `bulwark`) |
|
| 88 |
+
| `faction` | **categorical** (`syndicate` \| `miners` \| `frontier` \| …) |
|
| 89 |
+
| `unitMix` | **sequence** — see §3.5, the interesting one |
|
| 90 |
+
|
| 91 |
+
### 2.2 Genes worth *adding* because evolution can find their values
|
| 92 |
+
|
| 93 |
+
Evolution is only as good as its search space. Three cheap additions widen it a lot, and each is a
|
| 94 |
+
`|| 1`-style read at one site, so each is a no-op when absent:
|
| 95 |
+
|
| 96 |
+
- **`expandAggressionMult`** — today expansion is one threshold (`expandWhenNodesBelow`). A
|
| 97 |
+
multiplier on *how many* expansions it will chase gives the GA a macro/greed axis it currently
|
| 98 |
+
cannot express.
|
| 99 |
+
- **`techRushBias`** — the AI's tech-gate order in `aiEconomy.js` `aiBaseAndTech` is hardcoded.
|
| 100 |
+
A single scalar reordering Barracks-first vs Foundry-first opens the whole build-order axis,
|
| 101 |
+
which is where real RTS strategy lives and where the genome is currently blind.
|
| 102 |
+
- **`waveCommitFraction`** — commit with a *fraction* of the army rather than all-but-garrison.
|
| 103 |
+
Turns a binary (attack / don't) into a continuous dial, and continuous dials are what mutation
|
| 104 |
+
operators are good at.
|
| 105 |
+
|
| 106 |
+
Without at least one build-order gene, evolution can only tune the AI's *tempo*, never its *plan*.
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## 3. Gene types decide the operators
|
| 111 |
+
|
| 112 |
+
The single most common way a GA fails on a mixed genome is one operator applied to every gene.
|
| 113 |
+
These five kinds each want different treatment.
|
| 114 |
+
|
| 115 |
+
### 3.1 Continuous ratios — mutate multiplicatively, not additively
|
| 116 |
+
|
| 117 |
+
`attackTimeoutMult`, `graceMult`, `workerTargetMult` … are *ratios*. An additive step of ±0.1 is a
|
| 118 |
+
50% change at 0.2 and a 7% change at 1.5 — so additive Gaussian mutation searches the low end far
|
| 119 |
+
too coarsely and the high end far too finely. Mutate in log space:
|
| 120 |
+
|
| 121 |
+
```js
|
| 122 |
+
gene *= Math.exp(sigma * gaussian()); // log-normal step; symmetric in ratio terms
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
with `sigma ≈ 0.15` for a fine local search and `≈ 0.4` for exploration. **Self-adapt sigma**
|
| 126 |
+
(carry it as a gene of its own, mutate it too): this is the single highest-value trick in
|
| 127 |
+
evolution strategies, and it costs about four lines.
|
| 128 |
+
|
| 129 |
+
### 3.2 Integer counts — geometric step, clamped at zero
|
| 130 |
+
|
| 131 |
+
`standingArmyCap`, `matchFloor`, `turretCount`, `maxBarracks`, `garrison`, `probeMin`. Round after
|
| 132 |
+
a small geometric/Poisson step and clamp to `[0, …]`. Note **0 is a meaningful allele**, not a
|
| 133 |
+
degenerate one — `rusher.turretCount: 0` and `rusher.garrison: 0` are deliberate. Never clamp to 1.
|
| 134 |
+
|
| 135 |
+
### 3.3 Flags — low bit-flip rate, because they are *epistatic switches*
|
| 136 |
+
|
| 137 |
+
`neverInitiates` is not one gene among fifteen. Flipping it decides whether
|
| 138 |
+
`attackTimeoutMult`/`armyAttackSizeMult` mean *anything at all* — under `neverInitiates: true`
|
| 139 |
+
every offense gene is inert (`aiMilitary.js` blocks every voluntary commit). Likewise
|
| 140 |
+
`matchEnemyForce` makes `standingArmyCap` dead, and `warFootingMult` is dead without
|
| 141 |
+
`warFootingTime`.
|
| 142 |
+
|
| 143 |
+
This is textbook **epistasis**, and it has two consequences:
|
| 144 |
+
|
| 145 |
+
1. Flip flags **rarely** (~2-5%). A flag flip is a jump to a different fitness landscape entirely;
|
| 146 |
+
at a 20% rate the population never settles anywhere long enough to tune the dials.
|
| 147 |
+
2. The inert genes become **junk DNA** — and that is a feature, not a bug. A lineage that has been
|
| 148 |
+
`neverInitiates` for ten generations still carries drifting offense genes; when a descendant
|
| 149 |
+
flips the flag back it lands somewhere new rather than at the ancestral value. This is how
|
| 150 |
+
evolution actually escapes local optima, and it comes free here because the `|| 1` convention
|
| 151 |
+
means an inert gene is *carried*, not *erased*.
|
| 152 |
+
|
| 153 |
+
### 3.4 Categoricals — resample uniformly; cross by allele choice
|
| 154 |
+
|
| 155 |
+
`doctrine`, `faction`. There is no metric on these — no sense in which `miners` is "between"
|
| 156 |
+
`syndicate` and `frontier`. Mutation = pick a different one uniformly; crossover = take one
|
| 157 |
+
parent's allele wholesale. Note `faction` interacts strongly with `unitMix` (both feed combat
|
| 158 |
+
strength through `factions.js`), so these two should be treated as one **linkage group** — see §4.
|
| 159 |
+
|
| 160 |
+
### 3.5 `unitMix` — the sequence gene, and the most interesting one in the game
|
| 161 |
+
|
| 162 |
+
```js
|
| 163 |
+
unitMix: ["skiff", "lancer", "lancer", "dreadnought", "colossus", "wraith"], // technologist
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
This is not a vector. It is a **cyclic sequence over an alphabet of unit types**, of variable
|
| 167 |
+
length, where order matters (it is the production cycle — `ai.js`'s comment: "a repeating
|
| 168 |
+
production cycle … not a random weighting, so a profile's composition is exact and testable") and
|
| 169 |
+
multiplicity matters (three `skiff`s in four slots is the Rusher's whole identity).
|
| 170 |
+
|
| 171 |
+
Its operators are the ones from sequence/permutation GAs:
|
| 172 |
+
|
| 173 |
+
| Operator | Effect |
|
| 174 |
+
|---|---|
|
| 175 |
+
| **Point substitution** | one slot → a different unit type. Changes composition ratio |
|
| 176 |
+
| **Duplication** | copy a slot in place. The classic way biology adds material — lengthens the cycle and doubles one unit's share |
|
| 177 |
+
| **Deletion** | drop a slot. Must guard length ≥ 1 |
|
| 178 |
+
| **Insertion** | a new random type at a random index |
|
| 179 |
+
| **Cyclic rotation** | *neutral in steady state, not in the opening* — rotating decides which unit gets built first, which is exactly the difference between a rush that works and one that dies |
|
| 180 |
+
| **Order crossover (OX)** | take a contiguous run from parent A, fill the rest from B in B's order — preserves composition and adjacency from both |
|
| 181 |
+
|
| 182 |
+
And the reason this is safe to mutate wildly: **`effectiveMix` already filters out units the world
|
| 183 |
+
cannot pay for** (`aiWorkers.js`; the Balanced archetype's Wraith/Aegis entries are dropped on
|
| 184 |
+
worlds without gas or ice). An illegal gene is silently ignored rather than fatal. That single
|
| 185 |
+
existing behaviour makes `unitMix` the most evolvable structure in the codebase — a random
|
| 186 |
+
`["colossus","colossus","colossus"]` on pyralis degrades to a no-op instead of a crash.
|
| 187 |
+
|
| 188 |
+
---
|
| 189 |
+
|
| 190 |
+
## 4. Crossover — cross at module boundaries, not per-gene
|
| 191 |
+
|
| 192 |
+
Uniform crossover (each gene independently from A or B) is the default and is probably wrong here.
|
| 193 |
+
The dials cluster into **functional modules that map one-to-one onto engine files**:
|
| 194 |
+
|
| 195 |
+
| Module | Genes | Consumer |
|
| 196 |
+
|---|---|---|
|
| 197 |
+
| OFFENSE | `attackTimeoutMult`, `armyAttackSizeMult`, `garrisonMult`, `neverInitiates`, `useBombOffensively` | `aiMilitary.js`, `aiSuperweapon.js` |
|
| 198 |
+
| ECONOMY | `workerTargetMult`, `standingArmyCap`, `warFooting*`, `wantsIndustryAlways` | `aiEconomy.js`, `aiIndustry.js` |
|
| 199 |
+
| DIPLOMACY | `graceMult`, `grievanceMult`, `forgiveness` | `diplomacy.js` |
|
| 200 |
+
| DEFENSE | `turretCountMult`, `matchEnemyForce`, `matchBuffer`, `matchFloor` | `aiEconomy.js` |
|
| 201 |
+
| COMPOSITION | `unitMix`, `faction`, `doctrine` | `aiWorkers.js`, `factions.js` |
|
| 202 |
+
|
| 203 |
+
Genes *within* a module interact strongly (a smaller muster only works with a thinner garrison);
|
| 204 |
+
genes *across* modules interact weakly. That is precisely the condition under which crossover beats
|
| 205 |
+
mutation alone: **cross at module boundaries and a working sub-solution survives intact.** Uniform
|
| 206 |
+
crossover would shred an offense package that only works as a set.
|
| 207 |
+
|
| 208 |
+
There is a documented, in-repo example of why this matters. `aiStrategy.js:53-64` records that the
|
| 209 |
+
Aggressive strategy was *last* of four in self-play (25W-47L), that a coordinate scan over its own
|
| 210 |
+
offense dials could not fix it, and that what fixed it was an **economy** gene (`workerTargetMult:
|
| 211 |
+
1.25`) borrowed from the Economic strategy — 25W-47L → 38W-34L. That is a hand-executed
|
| 212 |
+
module-wise crossover between two strategies. It worked. It took a human a search-and-a-half to
|
| 213 |
+
find. A GA doing module-wise crossover over a population containing both parents finds it in one
|
| 214 |
+
generation, by construction.
|
| 215 |
+
|
| 216 |
+
**Recommended recombination:** 60% module-wise crossover, 25% arithmetic blend (geometric mean in
|
| 217 |
+
log space for the continuous genes — good for fine-tuning between two similar parents), 15% clone.
|
| 218 |
+
Then mutate the offspring.
|
| 219 |
+
|
| 220 |
+
---
|
| 221 |
+
|
| 222 |
+
## 5. Fitness — three exist, and they reward different things
|
| 223 |
+
|
| 224 |
+
| Fitness | Where | Cost | What it actually rewards |
|
| 225 |
+
|---|---|---|---|
|
| 226 |
+
| `score()` | `tools/ailab.js:475` | ~seconds/world | Being a good *neighbour* in a play-forever sandbox: develops, keeps growing, spends, applies pressure proportional to hostility |
|
| 227 |
+
| `runLeaderboard` | `:559` | N × the above | The same thing, N times, ranked. **A proxy, not head-to-head** — its own header says so |
|
| 228 |
+
| `runDuel` / `runSwissTournament` + `elo.js` | `:667`, `:935` | ~a match each | *Winning.* Real self-play, resolved by `engine/victory.js` |
|
| 229 |
+
|
| 230 |
+
**Use Elo from Swiss-paired self-play as the fitness, and `score()` as a diagnostic only.**
|
| 231 |
+
Reasons:
|
| 232 |
+
|
| 233 |
+
- **Goodhart.** `score()`'s six components are a hand-written definition of good, and a GA is a
|
| 234 |
+
machine for exploiting hand-written definitions. `thrift: clamp01(1 - bankedFinal / 8000)`
|
| 235 |
+
rewards ending poor — a genome that dumps ore into worthless turrets scores well and plays
|
| 236 |
+
badly. `pressure` counts waves — a genome that trickles one unit at a time farms it. Every one
|
| 237 |
+
of these is a real attack surface. A win/loss cannot be farmed except by winning.
|
| 238 |
+
- **Cost.** `runSwissTournament` pairs by closest standing over `swissRoundCount(n)` rounds
|
| 239 |
+
(`pairing.js:223`) instead of the full C(n,2) round-robin — O(n log n) matches per generation
|
| 240 |
+
for a population of n. A 24-individual generation is ~5 rounds × 12 matches = 60 matches, not
|
| 241 |
+
276. This is the difference between a generation costing minutes and costing an hour.
|
| 242 |
+
- **Relative fitness is what a GA wants anyway.** Selection only needs a ranking.
|
| 243 |
+
|
| 244 |
+
**But coevolution has its own failure mode, and it must be planned for.** A population evolving
|
| 245 |
+
only against itself can cycle forever (rusher beats greedy-economy beats turtle beats rusher) with
|
| 246 |
+
no absolute progress — the Red Queen. Two standard countermeasures, both cheap here:
|
| 247 |
+
|
| 248 |
+
1. **Hall of fame.** Seed every generation's tournament with the four shipped baselines —
|
| 249 |
+
`tools/candidates/baseline-{adaptive,aggressive,economic,force-parity}.json` already exist and
|
| 250 |
+
are exactly this. Elo against a fixed anchor is absolute, not relative.
|
| 251 |
+
2. **Archive the best-of-generation** and pair against a random sample of past champions, not just
|
| 252 |
+
current peers. This is what stops the population from specialising into a rock-paper-scissors
|
| 253 |
+
loop that beats itself and loses to the shipped AI.
|
| 254 |
+
|
| 255 |
+
**And a hard filter on top of fitness:** any genome that trips a `CHECKS` entry
|
| 256 |
+
(`tools/ailab.js:977` — `supply-deadlock`, `hoarding`, `dev-flatline`, `hostile-but-idle`,
|
| 257 |
+
`production-stall`) is disqualified regardless of Elo. A genome that wins duels while deadlocking
|
| 258 |
+
its own supply is a bug the GA found, not a strategy.
|
| 259 |
+
|
| 260 |
+
---
|
| 261 |
+
|
| 262 |
+
## 6. Five loops, cheapest first
|
| 263 |
+
|
| 264 |
+
### A. (1+λ) hill climb with Gaussian mutation — *~150 lines, the obvious first step*
|
| 265 |
+
|
| 266 |
+
Take the current best, make λ mutated copies, keep the winner. This is a strict upgrade on
|
| 267 |
+
`runSearch`'s coordinate scan for one structural reason: **the scan moves one dial at a time and
|
| 268 |
+
keeps improvements greedily, so it cannot cross a valley where two dials must move together.**
|
| 269 |
+
Aggressive's documented fix — offense dials only pay off once the economy funds them — is exactly
|
| 270 |
+
such a valley, and the scan is on record as having failed to find it. Multi-dial Gaussian mutation
|
| 271 |
+
crosses valleys by default. No crossover, no population, no new concepts.
|
| 272 |
+
|
| 273 |
+
### B. (μ,λ)-ES with self-adaptive step size — *the noise-robust choice*
|
| 274 |
+
|
| 275 |
+
Keep the μ best of λ offspring, each carrying its own mutation sigma. Handles the 10-15 continuous
|
| 276 |
+
genes very well and is more robust to a noisy objective than any hill climb, because it averages
|
| 277 |
+
over a population rather than trusting one comparison. Still no crossover.
|
| 278 |
+
|
| 279 |
+
### C. Genetic algorithm with module-wise crossover — *the direct answer to the question*
|
| 280 |
+
|
| 281 |
+
Population of 20-30, Swiss tournament each generation, tournament selection (pick 3 at random,
|
| 282 |
+
best of them breeds — cheap and doesn't need normalised fitness), module-wise crossover per §4,
|
| 283 |
+
mutation per §3, 2 elites carried unchanged. This is the design that can find the
|
| 284 |
+
Aggressive-borrows-Economic's-economy result by itself.
|
| 285 |
+
|
| 286 |
+
### D. Island model — *the fix for "improved on the mean, regressed on three worlds"*
|
| 287 |
+
|
| 288 |
+
One sub-population per world group (or per archetype), evolving independently, with occasional
|
| 289 |
+
migration of champions between islands. The ai-lab skill's own warning is that "a mean that
|
| 290 |
+
improved because one world improved a lot and three got worse is a regression wearing a disguise";
|
| 291 |
+
islands attack that directly by never letting one world's optimum swamp the roster. It also
|
| 292 |
+
parallelises perfectly, which matters when each fitness evaluation is a real simulated match.
|
| 293 |
+
|
| 294 |
+
### E. MAP-Elites — *the one that fits this game best, and the recommendation*
|
| 295 |
+
|
| 296 |
+
Odyssey has no win condition. The game does not want *the* optimal AI; it wants a **cast of
|
| 297 |
+
distinct, interesting opponents** — which is what `ARCHETYPES` is trying to be by hand, with four
|
| 298 |
+
entries written by a human.
|
| 299 |
+
|
| 300 |
+
MAP-Elites keeps an archive binned by *behavioural* descriptors and stores the best genome in each
|
| 301 |
+
bin. Every descriptor it needs is already measured, in `sample()`/`summarise()`
|
| 302 |
+
(`tools/ailab.js:318`):
|
| 303 |
+
|
| 304 |
+
- mean army size (`army` / `armyValue`) — turtle ←→ swarm
|
| 305 |
+
- time to first wave (`waves` first non-zero) — rush ←→ late
|
| 306 |
+
- development at 40 min (`devFinal`) — brawler ←→ teched
|
| 307 |
+
- banked ore (`bankedFinal`) — spendthrift ←→ hoarder
|
| 308 |
+
- expansions (`buildings`) — tall ←→ wide
|
| 309 |
+
|
| 310 |
+
Output: a grid of the strongest AI *of each play style*, every cell a genome, every genome a
|
| 311 |
+
runnable roster entry. That is directly shippable content — new archetypes with authentic
|
| 312 |
+
identities, discovered rather than hand-tuned — and it dodges the "evolution converges on one
|
| 313 |
+
degenerate cheese strategy" failure that would make the game worse even while the fitness number
|
| 314 |
+
goes up. It also composes with C: use the GA as the variation operator, MAP-Elites as the archive.
|
| 315 |
+
|
| 316 |
+
---
|
| 317 |
+
|
| 318 |
+
## 7. Where it runs — three deployment options, increasingly ambitious
|
| 319 |
+
|
| 320 |
+
**7.1 Offline, in `tools/evolve.js`.** Genomes are JSON, results go in the search ledger
|
| 321 |
+
(`docs/odyssey-ai-review.md`), winners are promoted into `engine/` by hand under the existing
|
| 322 |
+
discipline (`npm test` + `ailab check` + a full-roster multi-seed sweep). Safest, matches the
|
| 323 |
+
established workflow exactly, and needs zero engine changes.
|
| 324 |
+
|
| 325 |
+
**7.2 In-game: the roster breeds.** The Competition mode already has everything — a persistent
|
| 326 |
+
roster (`competitionLedger.js` `addRosterEntry`), Elo brackets, Swiss/round-robin/knockout
|
| 327 |
+
scheduling (`pairing.js`), a background worker (`competitionWorker.js`), seasons
|
| 328 |
+
(`archiveSeason`). Add one thing: when a season is archived, **the top two entrants produce
|
| 329 |
+
offspring** that join the next season's roster. Genomes are already JSON, so they serialise into
|
| 330 |
+
the ledger with no new format. The player-facing pitch writes itself: *a ladder that gets harder
|
| 331 |
+
because the AIs are breeding.* Note `competitionWorker.js:109` already plumbs a per-entrant
|
| 332 |
+
`archetype`, so an entrant is already more than just a strategy name.
|
| 333 |
+
|
| 334 |
+
**7.3 In-galaxy: the living galaxy evolves.** Each Odyssey neighbour world carries a genome. When
|
| 335 |
+
you conquer a world and it is re-settled, the new neighbour inherits a crossover of the two
|
| 336 |
+
strongest *surviving* neighbours — so wiping out the aggressive worlds leaves you a galaxy of
|
| 337 |
+
economists, and the survivors' traits propagate. This is the most interesting design and the most
|
| 338 |
+
dangerous: it must be seeded from `galaxy.seed` (never wall-clock, never `Math.random`), it changes
|
| 339 |
+
the Odyssey meta permanently, and a difficulty ratchet with no ceiling is a balance problem, not a
|
| 340 |
+
feature. Worth prototyping only after 7.1 has produced genomes anyone actually wants to face.
|
| 341 |
+
|
| 342 |
+
---
|
| 343 |
+
|
| 344 |
+
## 8. Traps this codebase will spring
|
| 345 |
+
|
| 346 |
+
These are specific, and each one has cost someone time already or clearly will.
|
| 347 |
+
|
| 348 |
+
**8.1 `duelSeed` hashes the candidates' names — so renaming a genome changes its maps.**
|
| 349 |
+
`tools/duelCore.js:60`:
|
| 350 |
+
|
| 351 |
+
```js
|
| 352 |
+
return hashStr(`${base}:duel:${world}:${difficulty}:${[aName, bName].sort().join("|")}:${rep}`);
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
Within one duel this is fine and deliberate (the sort is there so a side-swap draws the identical
|
| 356 |
+
map). Across *generations* it is a real confound: `gen3-ind7` vs `gen2-ind4` is fought on entirely
|
| 357 |
+
different maps than `gen2-ind4` vs `gen1-ind2` was, so "the child scored better than its parent
|
| 358 |
+
did" is partly a statement about map luck. **Fixed** (§9): `duelSeed` takes an optional `seedKey`
|
| 359 |
+
that replaces the names segment and defaults to today's exact derivation; `runDuel` forwards it,
|
| 360 |
+
and the evolution loop passes one fixed key for the whole run. The cost of pinning is that a run
|
| 361 |
+
can overfit the pinned map set — which is what held-out worlds are for (§8.6).
|
| 362 |
+
|
| 363 |
+
**8.2 `assertNoOverrideCollision` will refuse a population of mutants.**
|
| 364 |
+
`tools/ailab.js:720` throws if two candidates override the same table key — correctly, since they
|
| 365 |
+
share one live table in a duel and the patches would merge. A GA whose individuals are all mutants
|
| 366 |
+
of `"aggressive"` hits this on the very first pairing. **Give every individual a unique key**
|
| 367 |
+
(`gen3-ind7`), and treat the existing check as the naming discipline it is.
|
| 368 |
+
|
| 369 |
+
**8.3 Difficulty must be pinned, and every genome evaluated across brackets.**
|
| 370 |
+
Layers compose *multiplicatively* (archetype × strategy × difficulty), so a mild-looking gene is a
|
| 371 |
+
3× swing on Hard + Aggressive + Rusher. `aiStrategy.js:60-64` records the exact failure:
|
| 372 |
+
`workerTargetMult` at 1.4 wins Medium harder but *loses* Hard, because Hard's own row already
|
| 373 |
+
carries 1.25 and 1.4 there is really 1.75×. **A genome scored on one difficulty is not scored.**
|
| 374 |
+
Fitness must be the worst — or at minimum the mean — across brackets, never a single one.
|
| 375 |
+
|
| 376 |
+
**8.4 `runDuel` didn't plumb per-side archetypes; `runDuelMatch` always has.**
|
| 377 |
+
`tools/duelCore.js:84` accepts `aArchetype`/`bArchetype` and `competitionWorker.js:109` passes
|
| 378 |
+
them, but `tools/ailab.js`'s `runDuel` never set them — so in a CLI duel **both sides played the
|
| 379 |
+
world's own archetype**, and a candidate file carrying its own was silently ignored. **Fixed**
|
| 380 |
+
(§9), which is what makes the macro/tempo/composition chromosome measurable at all. Note this was
|
| 381 |
+
a pre-existing bug in the shipped bench, not something evolution introduced: any `duel` run
|
| 382 |
+
comparing two archetypes before this was measuring something else.
|
| 383 |
+
|
| 384 |
+
**8.5 Engine purity is non-negotiable.** No `Math.random`, no `Date.now()` under `engine/`, ever
|
| 385 |
+
(`test/engine-purity.test.js`). All mutation RNG uses `mulberry32` from `engine/rng.js` with an
|
| 386 |
+
explicit seed, and lives in `tools/`. If evolution ever moves in-game (§7.3) it must draw from a
|
| 387 |
+
seeded stream derived from `galaxy.seed`, exactly as `neighbourAiProfile` already does.
|
| 388 |
+
|
| 389 |
+
**8.6 Overfitting the roster.** `runSearch` "optimises a noisy mean and will happily overfit three
|
| 390 |
+
worlds". A GA is far better at overfitting than a coordinate scan is. **Hold worlds out**: evolve
|
| 391 |
+
on six, validate the champion on the other five, and report both numbers. A champion that wins on
|
| 392 |
+
its training worlds and not on the held-out ones is a champion of the seed set.
|
| 393 |
+
|
| 394 |
+
**8.7 Noise, and how much compute to spend proving a winner.** Duels are high-variance; 4-1 over
|
| 395 |
+
five matches is not significance. Rather than raising the seed count for everyone, use **successive
|
| 396 |
+
halving**: evaluate the whole generation cheaply (few seeds), keep the top half, re-evaluate with
|
| 397 |
+
more seeds, repeat. Compute concentrates on the individuals that might actually win.
|
| 398 |
+
|
| 399 |
+
**8.8 Strong is not the same as fun.** The fitness function is a definition of "better AI" and
|
| 400 |
+
evolution will satisfy it literally. A GA optimising win rate will find cheese — the same all-in
|
| 401 |
+
opening every game — and it will be *correct* to do so, and the game will be worse. `WEIGHTS`
|
| 402 |
+
(`:466`) exists to be edited before optimising, not after; and §6E's MAP-Elites is the structural
|
| 403 |
+
answer, because it selects for a *diverse cast* rather than a single maximum.
|
| 404 |
+
|
| 405 |
+
**8.9 The blast radius of promoting a winner.** `neighbourAiProfile` (`galaxy.js:61`) draws
|
| 406 |
+
strategies uniformly, so adding one evolved strategy row changes roughly 1/N of every Odyssey
|
| 407 |
+
galaxy. Editing an *existing* row changes every save that uses it. Keeping evolved values in the
|
| 408 |
+
`odyssey:` overlay only (read behind the `state.diplomacy` guard, `ai.js:133`) leaves the skirmish
|
| 409 |
+
game byte-identical and the determinism tests green — the same containment `aiArchetypes.js`
|
| 410 |
+
already uses for its labour retuning.
|
| 411 |
+
|
| 412 |
+
---
|
| 413 |
+
|
| 414 |
+
## 9. Phase 1 — shipped
|
| 415 |
+
|
| 416 |
+
Everything in this section is implemented. Nothing under `engine/` changed: the shipped game, the
|
| 417 |
+
skirmish path, and every determinism guarantee are untouched, which is the whole point of the
|
| 418 |
+
genotype living in `tools/`.
|
| 419 |
+
|
| 420 |
+
### `tools/genome.js` — the schema and the operators
|
| 421 |
+
|
| 422 |
+
`GENOME_SCHEMA` is the one source of truth for what a legal gene is — `{ key, layer, kind, module,
|
| 423 |
+
min, max, odysseyOnly, gatedBy }` — the same role `DIFFICULTY_OPTIONS` plays for difficulty keys.
|
| 424 |
+
28 genes across two chromosomes and six linkage groups. Alongside it: `mutate`, `cross`,
|
| 425 |
+
`randomGenome`, `genomeFrom` (seed from a shipped row), and `toOverrides`/`toCandidate`, which
|
| 426 |
+
lower a genome back into exactly the `--overrides` / `{ name, strategy, overrides }` shapes the
|
| 427 |
+
rest of the bench already consumes. Pure and seeded — every operator takes an explicit `mulberry32`
|
| 428 |
+
stream, so a whole run reproduces from one integer.
|
| 429 |
+
|
| 430 |
+
Two schema fields are load-bearing and were not in the original sketch:
|
| 431 |
+
|
| 432 |
+
- **`odysseyOnly`** marks a gene whose use site is behind a `state.endless` / `state.diplomacy`
|
| 433 |
+
guard. Every duel is a **skirmish** (`tools/selfplay.js`: "no Odyssey, no diplomacy, no galaxy"),
|
| 434 |
+
so the entire DIPLOMACY module plus `wantsIndustryAlways` and `useBombOffensively` are read by
|
| 435 |
+
*nothing* under a duel objective. They are excluded by default; evolving them against duel Elo
|
| 436 |
+
would be optimising pure drift. This was nearly a silent waste of a whole search.
|
| 437 |
+
- **`gatedBy`** handles the genes whose use site tests *presence* rather than value.
|
| 438 |
+
`aiEconomy.js` reads `strategy.standingArmyCap != null`, so emitting a default would cap the army
|
| 439 |
+
of every genome in the population. It is modelled as an explicit `capsArmy` switch plus a value
|
| 440 |
+
that keeps drifting while the switch is off — §3.3's junk-DNA argument made concrete.
|
| 441 |
+
|
| 442 |
+
### The two plumbing fixes from §8
|
| 443 |
+
|
| 444 |
+
- **`duelSeed` takes an optional `seedKey`** (`tools/duelCore.js`) that replaces the sorted-names
|
| 445 |
+
segment of the hash. Omitted, it is byte-for-byte the derivation it has always been — pinned by a
|
| 446 |
+
test. The evolution loop passes one fixed key for the whole run, so every genome ever evaluated
|
| 447 |
+
in round *R* faced the identical maps.
|
| 448 |
+
- **`runDuel` now forwards each candidate's own `archetype`** to `runDuelMatch`, which has always
|
| 449 |
+
accepted it and which `competitionWorker.js` has always passed. Before this, a CLI duel gave both
|
| 450 |
+
seats whatever temperament the *world* hands out and silently ignored the candidate's own — so
|
| 451 |
+
the archetype chromosome could not have been measured at all.
|
| 452 |
+
|
| 453 |
+
### `node tools/ailab.js evolve`
|
| 454 |
+
|
| 455 |
+
Population, generations, elites, tournament selection, module-wise crossover, self-adaptive
|
| 456 |
+
mutation. Fitness is Swiss-scheduled duel Elo with the four shipped baselines riding along as a
|
| 457 |
+
hall of fame, every difficulty bracket rated separately and aggregated by the worst (`--agg min`).
|
| 458 |
+
The champion is written as a runnable candidate file, so it goes straight back into
|
| 459 |
+
`duel`/`sweep`/`leaderboard`.
|
| 460 |
+
|
| 461 |
+
One correction the implementation forced, worth recording because the bug was invisible:
|
| 462 |
+
`eloForMatches` folds every rating from a **fresh 1200** over one generation's own matches, so a
|
| 463 |
+
raw Elo is only comparable *within* a generation — the field changes every generation and the mean
|
| 464 |
+
is pinned at 1200 regardless of the field's absolute strength. Comparing generation 6's champion to
|
| 465 |
+
generation 1's on raw Elo would have measured nothing, reintroducing the exact Red Queen failure
|
| 466 |
+
the hall of fame exists to prevent, in the arithmetic rather than in the design. The loop therefore
|
| 467 |
+
reports **`edge`** — rating above the hall of fame's own mean in the same tournament. Anchors are
|
| 468 |
+
fixed genomes, so their mean is a fixed point of skill and an edge *is* comparable across
|
| 469 |
+
generations; within a generation it is a constant offset, so it changes no ranking.
|
| 470 |
+
|
| 471 |
+
`--screen` (CHECKS as a disqualifier) is **opt-in**, and that is a calibration argument rather than
|
| 472 |
+
a cost one. Every detector in `CHECKS` is written for a 40–60 sim-minute *Odyssey* run and several
|
| 473 |
+
carry an explicit "…and it never resolved in the last third" term keyed to that length; run over a
|
| 474 |
+
duel-length skirmish they fire on healthy genomes, which is precisely the failure this repo's own
|
| 475 |
+
CHECKS header records three rewrites of. So the screen runs at its own length, on its own Odyssey
|
| 476 |
+
worlds, and only when asked.
|
| 477 |
+
|
| 478 |
+
### What the first run actually found
|
| 479 |
+
|
| 480 |
+
12 genomes × 6 generations, korrath/ferros/vesper, Medium+Hard, 3h21m. Full rows in the search
|
| 481 |
+
ledger (`docs/odyssey-ai-review.md`); the three findings worth carrying forward:
|
| 482 |
+
|
| 483 |
+
**1. It works, and it generalises.** The champion beats all four hand-tuned strategies on four
|
| 484 |
+
worlds it never trained on, at a longer clock than it was selected under: 50W-14L (78%) at Medium,
|
| 485 |
+
40W-24L (63%) at Hard, over 320 matches. Medium is ~4.5σ over even. So the loop is not producing
|
| 486 |
+
noise, and it is not overfitting its training worlds.
|
| 487 |
+
|
| 488 |
+
**2. And it should not be promoted, because it is Goodhart's law in a can.** Stripped of inert
|
| 489 |
+
genes the champion is three dials — `neverInitiates`, `workerTargetMult` at the schema ceiling, and
|
| 490 |
+
no army cap — which is to say: *max economy, uncapped army, never attack*. At Hard **every one of
|
| 491 |
+
its 40 wins is a `timeout-score` win and none is an elimination**, while 16 of its 24 losses are
|
| 492 |
+
eliminations. It does not play better; it exploits the fact that `engine/victory.js` weights combat
|
| 493 |
+
units 1.35× and banked ore 0.25×, so an army that never fights and never takes attrition is the
|
| 494 |
+
most valuable thing you can own at the clock. §8.8 predicted this in the abstract; it took one
|
| 495 |
+
generation to arrive in practice.
|
| 496 |
+
|
| 497 |
+
This is the single most useful thing the run produced, and it is an argument about the *objective*,
|
| 498 |
+
not about the search. Duel-Elo was chosen over `score()` precisely because a win "cannot be farmed
|
| 499 |
+
except by winning" — that reasoning was incomplete. A win at the timeout is farmable, because the
|
| 500 |
+
timeout is scored by a heuristic, and any heuristic is a hand-written definition of good. Three
|
| 501 |
+
plausible responses, none free:
|
| 502 |
+
- **Score only eliminations** (a timeout is a draw). Cleanest, but it selects hard for all-in
|
| 503 |
+
aggression and would probably breed the opposite degenerate.
|
| 504 |
+
- **Fitness = win rate weighted toward elimination wins.** A dial, therefore another thing to
|
| 505 |
+
tune, therefore another thing to Goodhart.
|
| 506 |
+
- **Take the finding as being about the game, not the bench**: a tiebreak that pays 1.35× for an
|
| 507 |
+
army you never commit rewards turtling in *real* matches too, not just evolved ones. That is
|
| 508 |
+
worth a balance conversation independent of any of this.
|
| 509 |
+
|
| 510 |
+
**3. Read the trajectory, not the numbers.** Elitism accidentally supplied a control: generation
|
| 511 |
+
3's champion is cloned unchanged into generation 4 and scored **+199 then +118** — 81 edge points
|
| 512 |
+
apart on a byte-identical genome. The apparent per-generation climb is a flat line with ±80
|
| 513 |
+
scatter. Only the gap to the anchors (+120 to +200, consistently) survives that, and the held-out
|
| 514 |
+
round-robin is what actually confirmed it. **A single-seed generation cannot rank genomes**; the
|
| 515 |
+
next run spends its compute on `--seeds` or on §8.7's successive halving, not on more generations.
|
| 516 |
+
|
| 517 |
+
The honest summary: Phase 1 delivered a working variation-and-selection loop and a genuinely
|
| 518 |
+
generalising champion that the game should not ship. Both halves of that are the result.
|
| 519 |
+
|
| 520 |
+
---
|
| 521 |
+
|
| 522 |
+
## 10. Open questions
|
| 523 |
+
|
| 524 |
+
- **What should the objective be, now that duel-Elo is known to be farmable?** The three options in
|
| 525 |
+
§9 are the start of that argument, not the end of it. Until it is settled, no evolved genome
|
| 526 |
+
should be promoted into `engine/` on duel record alone — the held-out round-robin proves
|
| 527 |
+
generalisation, not quality.
|
| 528 |
+
- **Should the schema's bounds be widened where evolution pins them?** `workerTargetMult` landed
|
| 529 |
+
exactly on 2.0, its ceiling. A binding bound means the optimum is outside the range, and the
|
| 530 |
+
honest options are to widen it or to state why the range is a design constraint rather than a
|
| 531 |
+
search constraint (on Hard the difficulty row multiplies by a further 1.25, so 2.0 is really
|
| 532 |
+
2.5×).
|
| 533 |
+
- **`runEvolution` has no resume.** A 3-hour run that dies is a 3-hour run lost. Per-generation
|
| 534 |
+
checkpointing now writes the champion-so-far, but the *population* is not serialised, so a run
|
| 535 |
+
can be salvaged but not continued. The fix is the same shape as `Workflow`'s resume: write the
|
| 536 |
+
population alongside the champion and take a `--resume-from`.
|
| 537 |
+
|
| 538 |
+
- **Should the player ever see a genome?** A "Lineage" panel on a Competition roster entry —
|
| 539 |
+
parents, generation, which genes it inherited from which side — is nearly free (it is all JSON
|
| 540 |
+
already) and is the thing that would make §7.2 feel alive rather than like a number going up.
|
| 541 |
+
- **Does the game want an AI that keeps getting harder?** §7.3's ratchet has no ceiling. Capping
|
| 542 |
+
it against the player's own Elo (the ledger already tracks a human rating) is one answer; making
|
| 543 |
+
it a per-galaxy toggle is another.
|
| 544 |
+
- **Is `unitMix` better evolved or better hand-written?** It is the gene most tied to a world's
|
| 545 |
+
identity and flavour. Evolution may well produce a stronger mix that reads as characterless.
|
| 546 |
+
Worth measuring against a "does this still feel like Korrath" judgement that no fitness function
|
| 547 |
+
contains.
|
|
@@ -848,3 +848,8 @@ re-run.
|
|
| 848 |
| 2026-08-05 | …and the incidental finding, which is the biggest one: `production-stall` 18/44 was never real | — | **`production-stall` is 0/44 on the PRE-FIX engine under the new predicate.** That row has sat in this document since 2026-07-30, was attacked twice (parallel Habitats; then written off as "the Rusher doing what it is designed to do"), and every one of those 18 runs had a growing army in the last third. The AI was never stalled — the detector was counting a Barracks caught between jobs. Two paragraphs of §2 that explained the residue are now marked superseded rather than left standing (the Rusher's "six workers" is nine since §2.11, on top of it) | **yes** |
|
| 849 |
| 2026-08-05 | a property test can stop a fourth round of this, where three rounds of human scoreboard-reading did not | `test/ailab.test.js`: a synthetic HEALTHY curve, every magnitude scaled 1×/5×/20×/100×, must fire NO detector — plus its converse, that a genuinely stuck curve still fires the right one at 1× and 20× | Verified adversarially rather than assumed: run against the OLD predicates the invariance test fails immediately (`supply-deadlock` fires on the healthy curve even at 1×, blocked 0.33 while the ceiling climbed +72), which is what makes it a real guard rather than one that happens to pass. Both halves needed — invariance alone is satisfiable by a detector that never fires | **yes** |
|
| 850 |
| 2026-08-05 | (noted, not built) `production-stall`'s new "the army never grew" term would be satisfied by an AI legitimately pinned at a configured Population cap | — | The bench never sets `popCap`, so it cannot arise in `check` today. Recorded in §2.12 as a known boundary rather than discovered later: a future sweep that sets one should exclude those samples the way `armyCapped` already excludes a self-capping strategy | — |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 848 |
| 2026-08-05 | …and the incidental finding, which is the biggest one: `production-stall` 18/44 was never real | — | **`production-stall` is 0/44 on the PRE-FIX engine under the new predicate.** That row has sat in this document since 2026-07-30, was attacked twice (parallel Habitats; then written off as "the Rusher doing what it is designed to do"), and every one of those 18 runs had a growing army in the last third. The AI was never stalled — the detector was counting a Barracks caught between jobs. Two paragraphs of §2 that explained the residue are now marked superseded rather than left standing (the Rusher's "six workers" is nine since §2.11, on top of it) | **yes** |
|
| 849 |
| 2026-08-05 | a property test can stop a fourth round of this, where three rounds of human scoreboard-reading did not | `test/ailab.test.js`: a synthetic HEALTHY curve, every magnitude scaled 1×/5×/20×/100×, must fire NO detector — plus its converse, that a genuinely stuck curve still fires the right one at 1× and 20× | Verified adversarially rather than assumed: run against the OLD predicates the invariance test fails immediately (`supply-deadlock` fires on the healthy curve even at 1×, blocked 0.33 while the ceiling climbed +72), which is what makes it a real guard rather than one that happens to pass. Both halves needed — invariance alone is satisfiable by a detector that never fires | **yes** |
|
| 850 |
| 2026-08-05 | (noted, not built) `production-stall`'s new "the army never grew" term would be satisfied by an AI legitimately pinned at a configured Population cap | — | The bench never sets `popCap`, so it cannot arise in `check` today. Recorded in §2.12 as a known boundary rather than discovered later: a future sweep that sets one should exclude those samples the way `armyCapped` already excludes a self-capping strategy | — |
|
| 851 |
+
| 2026-08-06 | the three AI dial tables are already a genome — plain data read through `\|\| 1` accessors, so any mutation is a runnable AI rather than a crash — and a population with mutation plus module-wise crossover can search regions a coordinate scan structurally cannot (a valley where two dials must move *together*, which is exactly the shape of this ledger's own 2026-08-04 "Aggressive needs Economic's `workerTargetMult`" result) | `tools/genome.js` (GENOME_SCHEMA: 28 genes over 2 chromosomes and 6 linkage groups, one operator per gene KIND) + `ailab evolve` (Swiss-scheduled duel-Elo fitness, the four shipped baselines as a fixed rating anchor, per-bracket `min` aggregation). Two pre-existing bench bugs fixed to make it measurable: `runDuel` never forwarded a candidate's own archetype to `runDuelMatch` (so every CLI duel gave BOTH seats the world's temperament and silently ignored the candidate files), and `duelSeed` hashes the candidate names (so generated per-individual names drew their own map set each generation) — now an optional `seedKey`, byte-identical when omitted | Suite 2401 → 2433, zero regressions. **Zero files under `engine/` changed** (`git diff --name-only` against the merge base: only `tools/`, `test/`, `docs/`), so `check` is unchanged by construction — confirmed anyway rather than assumed: mean **0.714** over 44 runs, `supply-deadlock`/`hostile-but-idle`/`production-stall` all clean, `hoarding` 2/44 at exactly the `korrath/matching` + `oort/matching` residual the 2026-08-01 row already records, `dev-flatline` 5/44. The defect list did not grow | **yes (tooling)** |
|
| 852 |
+
| 2026-08-06 | a 12 × 6 GA on the strategy chromosome finds something the four hand-tuned strategies don't have | 12 genomes × 6 generations, korrath/ferros/vesper, Medium+Hard, 1 seed, 30-min matches (3 h 21 m wall clock) | **Champion is generation 3's `g3i0`; generations 4–6 never beat it.** Stripped of inert genes it is three dials — `neverInitiates: true`, `workerTargetMult: 2` (the schema CEILING, a binding bound), `turretCountMult: 1.05` — with no standing-army cap at all: *max economy, uncapped army, never attack*. Eight of the eleven dials it emits are junk DNA (`attackTimeoutMult`/`armyAttackSizeMult`/`garrisonMult` dead under `neverInitiates` per `aiMilitary.js`'s `readyToAttack` gate; `warFooting*` dead without a `standingArmyCap`; `matchBuffer`/`matchFloor` dead without `matchEnemyForce`) | candidate only — see the two rows below |
|
| 853 |
+
| 2026-08-06 | …and it generalises rather than overfitting the three worlds and the 30-minute clock it was selected under | 5-way round-robin on four HELD-OUT worlds (glacius/helix/forge/kybernet), 2 seeds, both brackets, full 40-min matches — 320 matches | **It wins both brackets.** Medium: evolved **50W-14L (78%)**, Economic 36-28, Force Parity 25-39, Aggressive 25-39, Adaptive 24-40. Hard: evolved **40W-24L (63%)**, Aggressive 38-26, Adaptive 37-27, Economic 29-35, Force Parity 16-48. At n=64/bracket, Medium is ~4.5σ over even and unambiguous; Hard's 40-vs-38 lead over Aggressive is a statistical tie, so the honest claim is "clearly best at Medium, joint-best at Hard" | the loop works — **yes** |
|
| 854 |
+
| 2026-08-06 | …but is it actually playing better? | same 320 matches, split by `winReason` | **No. It wins on the clock and loses when the clock doesn't save it.** At Hard **all 40 of its wins are `timeout-score`, zero by elimination**, while 16 of its 24 losses ARE eliminations; Medium is 44/50 timeout-score. `engine/victory.js` weights combat units 1.35× and banked ore 0.25×, so an army that never fights — and so never takes attrition — is the highest-scoring thing you can own when the clock runs out. Textbook Goodhart: the objective said "win duels", the shipped tiebreak says a 40-minute duel is won on stockpiled value, so evolution built the biggest stockpile and refused to risk it. Consistent with what this ledger already recorded by hand on 2026-08-04 (Economic, which also never initiates, took 71% at Medium; Aggressive finished last at 35%) — the GA rediscovered that family cold in ONE generation, then pushed it to its limit | **not promoted.** A stronger duel record bought with strictly more boring play is not an improvement to ship |
|
| 855 |
+
| 2026-08-06 | how much of the per-generation "improvement" was real? | elitism clones the top 2 genomes unchanged, so generation 3's champion `g3i0` reappears in generation 4 as `g4i0` — identical genes, identical σ | **A free control measurement, and it is damning for the trajectory.** The same genome scored **+199 in generation 3 and +118 in generation 4** — 81 edge points apart. Three functionally identical genomes within generation 4 spanned +163/+134/+118. So the run's tidy +152 → +175 → +199 → +163 → +190 → (+149) is a FLAT LINE with ±80 scatter, not a climb, and at 3 worlds × 1 seed this configuration cannot resolve anything smaller. What survives the noise is only the gap to the anchors (~+120 to +200, every generation) — which the held-out round-robin then confirmed independently. Next run: spend the compute on `--seeds`, or on the successive halving `docs/ai-evolution-design.md` §8.7 describes, rather than on more generations | n/a — methodology |
|
|
@@ -27,8 +27,10 @@ import {
|
|
| 27 |
run, labWorld, summarise, score, applyOverrides, CHECKS, OPPONENTS, WORLDS, WEIGHTS, runLeaderboard,
|
| 28 |
runDuel, runRoundRobin, pinnedDuelDials, runSwappedDuel, runDuelBrackets, runRoundRobinSwapped, runSearch,
|
| 29 |
runSwissTournament, pairRound, rankStandings, buildSwissBracket, snapshotTables, restoreTables,
|
|
|
|
| 30 |
} from "../tools/ailab.js";
|
| 31 |
import { STRATEGIES } from "../engine/aiStrategy.js";
|
|
|
|
| 32 |
import { DIFFICULTY_OPTIONS } from "../engine/aiDifficulty.js";
|
| 33 |
import { tick } from "../engine/sim.js";
|
| 34 |
import { hashStr } from "../engine/rng.js";
|
|
@@ -1161,3 +1163,124 @@ test("standings rank by RESULT, not by how many pairings the schedule handed out
|
|
| 1161 |
assert.equal(rankStandings([played, strictlyBetter])[0].name, "better",
|
| 1162 |
"a 75% record must outrank a 50% one even though it played fewer pairings");
|
| 1163 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
run, labWorld, summarise, score, applyOverrides, CHECKS, OPPONENTS, WORLDS, WEIGHTS, runLeaderboard,
|
| 28 |
runDuel, runRoundRobin, pinnedDuelDials, runSwappedDuel, runDuelBrackets, runRoundRobinSwapped, runSearch,
|
| 29 |
runSwissTournament, pairRound, rankStandings, buildSwissBracket, snapshotTables, restoreTables,
|
| 30 |
+
runEvolution,
|
| 31 |
} from "../tools/ailab.js";
|
| 32 |
import { STRATEGIES } from "../engine/aiStrategy.js";
|
| 33 |
+
import { ARCHETYPES } from "../engine/aiArchetypes.js";
|
| 34 |
import { DIFFICULTY_OPTIONS } from "../engine/aiDifficulty.js";
|
| 35 |
import { tick } from "../engine/sim.js";
|
| 36 |
import { hashStr } from "../engine/rng.js";
|
|
|
|
| 1163 |
assert.equal(rankStandings([played, strictlyBetter])[0].name, "better",
|
| 1164 |
"a 75% record must outrank a 50% one even though it played fewer pairings");
|
| 1165 |
});
|
| 1166 |
+
|
| 1167 |
+
/* ---------- the per-side archetype plumb through runDuel (docs/ai-evolution-design.md §8.4) ----------
|
| 1168 |
+
|
| 1169 |
+
tools/duelCore.js's runDuelMatch has always accepted aArchetype/bArchetype, and
|
| 1170 |
+
competitionWorker.js has always passed them — but runDuel never forwarded them, so a CLI duel
|
| 1171 |
+
silently ignored a candidate's own archetype and gave BOTH seats whatever temperament the world
|
| 1172 |
+
hands out. That is invisible from the outside: the duel runs, a winner is reported, and it is a
|
| 1173 |
+
measurement of something other than what the candidate files describe.
|
| 1174 |
+
---------- */
|
| 1175 |
+
|
| 1176 |
+
test("runDuel forwards each candidate's own archetype, so two temperaments really do meet", () => {
|
| 1177 |
+
const worlds = ["ferros"]; // an Economist world — neither candidate's own pick, so both differ from it
|
| 1178 |
+
const opts = { worlds, seeds: 1, minutes: 6 };
|
| 1179 |
+
const bothWorlds = runDuel({ name: "plain-a" }, { name: "plain-b" }, opts);
|
| 1180 |
+
const rusherVsTech = runDuel(
|
| 1181 |
+
{ name: "rush", archetype: "rusher" },
|
| 1182 |
+
{ name: "tech", archetype: "technologist" }, opts);
|
| 1183 |
+
// If the archetype were dropped, both duels would be the SAME match modulo candidate names — and
|
| 1184 |
+
// duelSeed hashes the names, so compare on the match OUTCOME rather than the seed.
|
| 1185 |
+
const shape = r => r.rows.map(x => `${x.winReason}:${x.time}:${x.aScore}:${x.bScore}`).join("|");
|
| 1186 |
+
assert.notEqual(shape(bothWorlds), shape(rusherVsTech),
|
| 1187 |
+
"a candidate's archetype reached nothing — runDuel is dropping aArchetype/bArchetype");
|
| 1188 |
+
});
|
| 1189 |
+
|
| 1190 |
+
test("an absent archetype is byte-identical to today's behaviour", () => {
|
| 1191 |
+
const opts = { worlds: ["korrath"], seeds: 1, minutes: 6 };
|
| 1192 |
+
const shape = r => r.rows.map(x => `${x.seed}:${x.winner}:${x.winReason}:${x.time}:${x.margin}`).join("|");
|
| 1193 |
+
assert.equal(
|
| 1194 |
+
shape(runDuel({ name: "a" }, { name: "b" }, opts)),
|
| 1195 |
+
shape(runDuel({ name: "a", archetype: null }, { name: "b", archetype: undefined }, opts)),
|
| 1196 |
+
"an absent/null archetype must not change a single existing duel row");
|
| 1197 |
+
});
|
| 1198 |
+
|
| 1199 |
+
test("runDuel's seedKey pins a pair's maps regardless of the candidates' names", () => {
|
| 1200 |
+
const opts = { worlds: ["ferros"], seeds: 2, minutes: 4, seedKey: "evolve" };
|
| 1201 |
+
const seeds = r => r.rows.map(x => x.seed).join("|");
|
| 1202 |
+
assert.equal(
|
| 1203 |
+
seeds(runDuel({ name: "g1i0" }, { name: "g1i1" }, opts)),
|
| 1204 |
+
seeds(runDuel({ name: "g9i7" }, { name: "g9i2" }, opts)),
|
| 1205 |
+
"with seedKey pinned, two differently-named pairs must draw the identical map set");
|
| 1206 |
+
assert.notEqual(
|
| 1207 |
+
seeds(runDuel({ name: "g1i0" }, { name: "g1i1" }, { ...opts, seedKey: undefined })),
|
| 1208 |
+
seeds(runDuel({ name: "g9i7" }, { name: "g9i2" }, { ...opts, seedKey: undefined })),
|
| 1209 |
+
"sanity: without it, the names DO reach the map draw — which is the confound seedKey exists for");
|
| 1210 |
+
});
|
| 1211 |
+
|
| 1212 |
+
/* ---------- evolve: a population, bred and selected by real self-play ----------
|
| 1213 |
+
|
| 1214 |
+
Short runs (tiny population, 4-minute matches) — this guards the LOOP, not the AI. Whether an
|
| 1215 |
+
evolved genome is actually better is a question for a long run and the search ledger, never for
|
| 1216 |
+
a test suite that has to finish in seconds.
|
| 1217 |
+
---------- */
|
| 1218 |
+
|
| 1219 |
+
const evoOpts = {
|
| 1220 |
+
population: 4, generations: 2, worlds: ["korrath"], seeds: 1, minutes: 4, rounds: 2, elites: 1,
|
| 1221 |
+
};
|
| 1222 |
+
|
| 1223 |
+
test("runEvolution is deterministic: the same seed breeds the same champion", () => {
|
| 1224 |
+
const strip = r => JSON.stringify({ best: r.best, log: r.log });
|
| 1225 |
+
assert.equal(strip(runEvolution({ ...evoOpts, seed: 5 })), strip(runEvolution({ ...evoOpts, seed: 5 })));
|
| 1226 |
+
});
|
| 1227 |
+
|
| 1228 |
+
test("a different seed breeds a different run — the search is actually stochastic", () => {
|
| 1229 |
+
const a = runEvolution({ ...evoOpts, seed: 5, generations: 3 });
|
| 1230 |
+
const b = runEvolution({ ...evoOpts, seed: 6, generations: 3 });
|
| 1231 |
+
assert.notEqual(JSON.stringify(a.log), JSON.stringify(b.log));
|
| 1232 |
+
});
|
| 1233 |
+
|
| 1234 |
+
test("the champion is a RUNNABLE candidate — it duels without an adapter", () => {
|
| 1235 |
+
const res = runEvolution({ ...evoOpts, seed: 3 });
|
| 1236 |
+
assert.ok(res.best.name && res.best.strategy && res.best.overrides.strategies[res.best.name]);
|
| 1237 |
+
// The actual contract: it goes straight back into the tooling it came from.
|
| 1238 |
+
const snap = snapshotTables();
|
| 1239 |
+
try {
|
| 1240 |
+
const duel = runDuel(res.best, { name: "Baseline: Adaptive" }, { worlds: ["korrath"], seeds: 1, minutes: 4 });
|
| 1241 |
+
assert.equal(duel.n, 1);
|
| 1242 |
+
assert.ok(["a", "b", "draw"].includes(duel.rows[0].winner));
|
| 1243 |
+
} finally { restoreTables(snap); }
|
| 1244 |
+
});
|
| 1245 |
+
|
| 1246 |
+
test("evolution leaves the shipped AI tables exactly as it found them", () => {
|
| 1247 |
+
// Every genome writes a row into STRATEGIES to be evaluated. If one leaked, every LATER
|
| 1248 |
+
// measurement in the same process — a sweep, a check, another duel — would silently be measuring
|
| 1249 |
+
// a mutant. runDuel snapshot/restores around each pairing; this asserts the whole loop does too.
|
| 1250 |
+
const before = JSON.stringify({ s: STRATEGIES, a: ARCHETYPES, d: DIFFICULTY_OPTIONS });
|
| 1251 |
+
runEvolution({ ...evoOpts, seed: 8, layers: ["strategy", "archetype"] });
|
| 1252 |
+
assert.equal(JSON.stringify({ s: STRATEGIES, a: ARCHETYPES, d: DIFFICULTY_OPTIONS }), before);
|
| 1253 |
+
});
|
| 1254 |
+
|
| 1255 |
+
test("the hall of fame is rated alongside the population and anchors the scale", () => {
|
| 1256 |
+
const hallOfFame = [{ name: "Baseline: Adaptive" }, { name: "Baseline: Aggressive", strategy: "aggressive" }];
|
| 1257 |
+
const res = runEvolution({ ...evoOpts, seed: 4, hallOfFame });
|
| 1258 |
+
for (const entry of res.log) {
|
| 1259 |
+
assert.deepEqual(entry.anchors.map(a => a.name), hallOfFame.map(h => h.name),
|
| 1260 |
+
"both baselines must appear in every generation's ratings");
|
| 1261 |
+
// edge is elo measured against the anchors' own mean — the only cross-generation-comparable
|
| 1262 |
+
// number here, since eloForMatches restarts from a fresh 1200 every generation.
|
| 1263 |
+
// (every term is logged rounded to 1dp, so the identity holds only to within that rounding)
|
| 1264 |
+
for (const r of entry.ranked) assert.ok(Math.abs((r.elo - entry.anchorMean) - r.edge) < 0.2,
|
| 1265 |
+
`edge must be elo above the anchor mean: ${r.elo} - ${entry.anchorMean} != ${r.edge}`);
|
| 1266 |
+
}
|
| 1267 |
+
});
|
| 1268 |
+
|
| 1269 |
+
test("Odyssey-gated genes are excluded by default, because a duel is a skirmish", () => {
|
| 1270 |
+
const res = runEvolution({ ...evoOpts, seed: 9 });
|
| 1271 |
+
const keys = res.genes.map(g => g.key);
|
| 1272 |
+
for (const dead of ["graceMult", "grievanceMult", "forgiveness", "wantsIndustryAlways", "useBombOffensively"])
|
| 1273 |
+
assert.ok(!keys.includes(dead), `${dead} is read by nothing in a skirmish — evolving it is scoring drift`);
|
| 1274 |
+
assert.ok(runEvolution({ ...evoOpts, seed: 9, odyssey: true }).genes.some(g => g.odysseyOnly),
|
| 1275 |
+
"…and asking for them explicitly must still work");
|
| 1276 |
+
});
|
| 1277 |
+
|
| 1278 |
+
test("elitism is monotone: the best genome is never lost to an unlucky mutation", () => {
|
| 1279 |
+
// With a noisy objective a generation WILL sometimes breed nothing better than what it had. The
|
| 1280 |
+
// guarantee elites buy is that the run's best-so-far can only ever improve.
|
| 1281 |
+
const res = runEvolution({ ...evoOpts, seed: 2, generations: 4, elites: 2 });
|
| 1282 |
+
let seen = -Infinity;
|
| 1283 |
+
for (const entry of res.log) seen = Math.max(seen, entry.champion.edge);
|
| 1284 |
+
assert.equal(+res.bestEdge.toFixed(1), seen, // the log rounds to 1dp; the result carries full precision
|
| 1285 |
+
"the reported best must be the best edge any generation actually reached");
|
| 1286 |
+
});
|
|
@@ -57,6 +57,36 @@ test("duelSeed genuinely varies with world, difficulty, replicate, and base seed
|
|
| 57 |
assert.notEqual(base, duelSeed(1, "ferros", "medium", "Alpha", "Gamma", 0), "the actual pair must vary the seed");
|
| 58 |
});
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
/* ---------- runDuelMatch (formerly ailab.js's own private duelRun) ---------- */
|
| 61 |
|
| 62 |
const dials = pinnedDuelDials("medium");
|
|
|
|
| 57 |
assert.notEqual(base, duelSeed(1, "ferros", "medium", "Alpha", "Gamma", 0), "the actual pair must vary the seed");
|
| 58 |
});
|
| 59 |
|
| 60 |
+
/* ---------- duelSeed's seedKey escape hatch (docs/ai-evolution-design.md §8.1) ---------- */
|
| 61 |
+
|
| 62 |
+
test("omitting seedKey leaves duelSeed byte-for-byte the derivation it has always been", () => {
|
| 63 |
+
// The whole point of the parameter is that it is invisible unless asked for: every existing
|
| 64 |
+
// caller (runDuel without an evolutionary opts, every recorded competition row, every saved
|
| 65 |
+
// --json duel result) must keep drawing the identical maps.
|
| 66 |
+
for (const [world, diff, rep] of [["ferros", "medium", 0], ["korrath", "hard", 3], ["vesper", "easy", 1]]) {
|
| 67 |
+
assert.equal(duelSeed(1, world, diff, "Alpha", "Beta", rep),
|
| 68 |
+
duelSeed(1, world, diff, "Alpha", "Beta", rep, undefined),
|
| 69 |
+
"an explicit undefined seedKey must be identical to omitting it");
|
| 70 |
+
}
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
test("seedKey replaces the NAMES in the hash, so differently-named pairs share one map set", () => {
|
| 74 |
+
// This is the property an evolutionary run needs: generated names (g3i7 vs g2i4) would otherwise
|
| 75 |
+
// hash to their own maps every generation, and "the child beat its parent's number" would be
|
| 76 |
+
// partly a statement about map luck rather than about the genome.
|
| 77 |
+
const a = duelSeed(1, "ferros", "medium", "g3i7", "g2i4", 0, "evolve");
|
| 78 |
+
const b = duelSeed(1, "ferros", "medium", "totally", "different", 0, "evolve");
|
| 79 |
+
assert.equal(a, b, "with a seedKey pinned, the candidate names must not reach the map draw");
|
| 80 |
+
assert.notEqual(a, duelSeed(1, "ferros", "medium", "g3i7", "g2i4", 0),
|
| 81 |
+
"and it must actually differ from the unpinned derivation, or it is doing nothing");
|
| 82 |
+
// Everything else still varies exactly as before — the key replaces the names, nothing else.
|
| 83 |
+
assert.notEqual(a, duelSeed(1, "korrath", "medium", "g3i7", "g2i4", 0, "evolve"));
|
| 84 |
+
assert.notEqual(a, duelSeed(1, "ferros", "hard", "g3i7", "g2i4", 0, "evolve"));
|
| 85 |
+
assert.notEqual(a, duelSeed(1, "ferros", "medium", "g3i7", "g2i4", 1, "evolve"));
|
| 86 |
+
assert.notEqual(a, duelSeed(2, "ferros", "medium", "g3i7", "g2i4", 0, "evolve"));
|
| 87 |
+
assert.notEqual(a, duelSeed(1, "ferros", "medium", "g3i7", "g2i4", 0, "evolve2"));
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
/* ---------- runDuelMatch (formerly ailab.js's own private duelRun) ---------- */
|
| 91 |
|
| 92 |
const dials = pinnedDuelDials("medium");
|
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ============================================================
|
| 2 |
+
Guards for tools/genome.js — the AI as a mutable, crossable data structure
|
| 3 |
+
(docs/ai-evolution-design.md).
|
| 4 |
+
|
| 5 |
+
An evolutionary search is only as trustworthy as its operators, and an operator bug here is
|
| 6 |
+
nearly invisible from the outside: a run still produces a champion, still prints an Elo, and
|
| 7 |
+
still looks like it worked. So these tests pin the properties that would fail SILENTLY —
|
| 8 |
+
|
| 9 |
+
1. LEGALITY. Every genome a random walk can reach is in bounds and lowers to a runnable
|
| 10 |
+
overrides document. A gene out of range doesn't crash; it just quietly wastes a run.
|
| 11 |
+
2. DETERMINISM. Same seed => same genome, everywhere. The bench's whole contract.
|
| 12 |
+
3. REACHABILITY. The properties that decide whether the search can MOVE: a ratio gene can
|
| 13 |
+
never reach an absorbing 0, a count gene CAN reach 0 (it's a real allele), and the mix
|
| 14 |
+
can change length in both directions.
|
| 15 |
+
4. THE GATE. standingArmyCap is emitted only behind capsArmy, because aiEconomy.js tests its
|
| 16 |
+
PRESENCE (`!= null`), so an ungated emit would turn the cap on for the whole population.
|
| 17 |
+
5. NO SHIPPED-TABLE MUTATION. Building genomes from the shipped rows must not write back into
|
| 18 |
+
STRATEGIES/ARCHETYPES — test/ailab.test.js's own history has a permanent-table-mutation
|
| 19 |
+
finding in it (docs/code-improvement-tiers.md), and this file builds from those tables on
|
| 20 |
+
every single call.
|
| 21 |
+
============================================================ */
|
| 22 |
+
|
| 23 |
+
import { test } from "node:test";
|
| 24 |
+
import assert from "node:assert/strict";
|
| 25 |
+
import {
|
| 26 |
+
GENOME_SCHEMA, MODULES, MIX_ALPHABET, geneKeys, genomeFrom, randomGenome, mutate, mutateMix,
|
| 27 |
+
cross, crossMix, cloneGenome, emptyGenome, toOverrides, toCandidate, diffGenes, rngFor,
|
| 28 |
+
} from "../tools/genome.js";
|
| 29 |
+
import { STRATEGIES } from "../engine/aiStrategy.js";
|
| 30 |
+
import { ARCHETYPES } from "../engine/aiArchetypes.js";
|
| 31 |
+
|
| 32 |
+
const ALL = geneKeys({ layers: ["strategy", "archetype"], odyssey: true });
|
| 33 |
+
|
| 34 |
+
/* ---------- the schema itself ---------- */
|
| 35 |
+
|
| 36 |
+
test("every gene declares a kind the operators implement, and bounds where its kind needs them", () => {
|
| 37 |
+
const KINDS = new Set(["ratio", "count", "unit01", "flag", "choice", "mix"]);
|
| 38 |
+
for (const g of GENOME_SCHEMA) {
|
| 39 |
+
assert.ok(KINDS.has(g.kind), `${g.key}: unknown kind "${g.kind}"`);
|
| 40 |
+
assert.ok(["strategy", "archetype"].includes(g.layer), `${g.key}: unknown layer "${g.layer}"`);
|
| 41 |
+
assert.ok(g.module, `${g.key}: no module — crossover cuts at module boundaries`);
|
| 42 |
+
if (["ratio", "count", "unit01"].includes(g.kind)) {
|
| 43 |
+
assert.equal(typeof g.min, "number", `${g.key}: needs min`);
|
| 44 |
+
assert.equal(typeof g.max, "number", `${g.key}: needs max`);
|
| 45 |
+
assert.ok(g.max > g.min, `${g.key}: max must exceed min`);
|
| 46 |
+
}
|
| 47 |
+
if (g.kind === "choice") assert.ok(g.of && g.of.length >= 2, `${g.key}: a choice needs 2+ alleles`);
|
| 48 |
+
// A ratio's lower bound must be strictly positive: 0 is ABSORBING under multiplicative
|
| 49 |
+
// mutation, so a gene that ever reached it could never leave. See the KINDS note in
|
| 50 |
+
// tools/genome.js's header for why that costs nothing (use sites round).
|
| 51 |
+
if (g.kind === "ratio") assert.ok(g.min > 0, `${g.key}: a ratio's min must be > 0 (0 is absorbing)`);
|
| 52 |
+
}
|
| 53 |
+
assert.ok(MODULES.length >= 4, "crossover needs several linkage groups to cut between");
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
test("gene keys are unique — a duplicate would silently shadow in the lowered row", () => {
|
| 57 |
+
const keys = GENOME_SCHEMA.map(g => `${g.layer}.${g.key}`);
|
| 58 |
+
assert.equal(new Set(keys).size, keys.length);
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
test("every gene key is one the engine actually reads, or the schema is tuning nothing", () => {
|
| 62 |
+
// A gene named after a field no use site consults is the quietest possible bug: the search runs,
|
| 63 |
+
// the numbers move, and the AI never changes. Checked against the shipped tables, which between
|
| 64 |
+
// them field every dial the engine reads — plus the two switches this file introduces on
|
| 65 |
+
// purpose (capsArmy gates standingArmyCap; matchEnemyForce/neverInitiates etc. are all shipped).
|
| 66 |
+
const shipped = new Set();
|
| 67 |
+
for (const row of Object.values(STRATEGIES)) Object.keys(row).forEach(k => shipped.add(`strategy.${k}`));
|
| 68 |
+
for (const row of Object.values(ARCHETYPES)) {
|
| 69 |
+
Object.keys(row).forEach(k => shipped.add(`archetype.${k}`));
|
| 70 |
+
Object.keys(row.odyssey || {}).forEach(k => shipped.add(`archetype.${k}`));
|
| 71 |
+
}
|
| 72 |
+
const INTRODUCED = new Set(["strategy.capsArmy"]); // this file's own explicit switch
|
| 73 |
+
for (const g of GENOME_SCHEMA) {
|
| 74 |
+
const id = `${g.layer}.${g.key}`;
|
| 75 |
+
assert.ok(shipped.has(id) || INTRODUCED.has(id), `${id} is read by nothing in the shipped tables`);
|
| 76 |
+
}
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
test("geneKeys defaults to the strategy chromosome and drops Odyssey-gated genes", () => {
|
| 80 |
+
const def = geneKeys();
|
| 81 |
+
assert.ok(def.length > 0);
|
| 82 |
+
assert.ok(def.every(g => g.layer === "strategy"), "default layer set is strategy-only");
|
| 83 |
+
assert.ok(def.every(g => !g.odysseyOnly),
|
| 84 |
+
"a duel is a skirmish — Odyssey-gated genes are read by nothing there, so they must not be searched");
|
| 85 |
+
// …and asking for them explicitly gets them back.
|
| 86 |
+
assert.ok(geneKeys({ odyssey: true }).some(g => g.odysseyOnly));
|
| 87 |
+
assert.ok(geneKeys({ layers: ["strategy", "archetype"] }).some(g => g.layer === "archetype"));
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
/* ---------- legality under a random walk ---------- */
|
| 91 |
+
|
| 92 |
+
const inBounds = (genome, genes) => {
|
| 93 |
+
for (const g of genes) {
|
| 94 |
+
const v = genome[g.layer][g.key];
|
| 95 |
+
switch (g.kind) {
|
| 96 |
+
case "ratio": case "unit01":
|
| 97 |
+
assert.equal(typeof v, "number", `${g.key} not a number: ${v}`);
|
| 98 |
+
assert.ok(Number.isFinite(v), `${g.key} not finite: ${v}`);
|
| 99 |
+
assert.ok(v >= g.min - 1e-9 && v <= g.max + 1e-9, `${g.key} out of [${g.min}, ${g.max}]: ${v}`);
|
| 100 |
+
break;
|
| 101 |
+
case "count":
|
| 102 |
+
assert.ok(Number.isInteger(v), `${g.key} not an integer: ${v}`);
|
| 103 |
+
assert.ok(v >= g.min && v <= g.max, `${g.key} out of [${g.min}, ${g.max}]: ${v}`);
|
| 104 |
+
break;
|
| 105 |
+
case "flag": assert.equal(typeof v, "boolean", `${g.key} not a boolean: ${v}`); break;
|
| 106 |
+
case "choice": assert.ok(g.of.includes(v), `${g.key} not an allele: ${v}`); break;
|
| 107 |
+
case "mix":
|
| 108 |
+
assert.ok(Array.isArray(v) && v.length >= 2, `${g.key} not a usable mix: ${JSON.stringify(v)}`);
|
| 109 |
+
assert.ok(v.every(t => MIX_ALPHABET.includes(t)), `${g.key} has a type off the alphabet: ${v}`);
|
| 110 |
+
break;
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
test("2000 generations of mutation never produce an out-of-bounds gene", () => {
|
| 116 |
+
const rng = rngFor(11);
|
| 117 |
+
let g = randomGenome(rng, ALL);
|
| 118 |
+
inBounds(g, ALL);
|
| 119 |
+
for (let i = 0; i < 2000; i++) {
|
| 120 |
+
g = mutate(g, rng, { rate: 0.5, flagRate: 0.2, genes: ALL });
|
| 121 |
+
inBounds(g, ALL);
|
| 122 |
+
assert.ok(g.sigma >= 0.03 - 1e-9 && g.sigma <= 0.8 + 1e-9, `sigma escaped: ${g.sigma}`);
|
| 123 |
+
}
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
test("crossover of two random parents is in bounds, for every mode", () => {
|
| 127 |
+
const rng = rngFor(12);
|
| 128 |
+
for (let i = 0; i < 500; i++) {
|
| 129 |
+
const a = randomGenome(rng, ALL), b = randomGenome(rng, ALL);
|
| 130 |
+
inBounds(cross(a, b, rng, { genes: ALL }), ALL);
|
| 131 |
+
inBounds(cross(a, b, rng, { moduleWise: 1, blend: 0, genes: ALL }), ALL);
|
| 132 |
+
inBounds(cross(a, b, rng, { moduleWise: 0, blend: 1, genes: ALL }), ALL);
|
| 133 |
+
inBounds(cross(a, b, rng, { moduleWise: 0, blend: 0, genes: ALL }), ALL); // clone
|
| 134 |
+
}
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
/* ---------- determinism ---------- */
|
| 138 |
+
|
| 139 |
+
test("same seed => byte-identical genome, through every operator", () => {
|
| 140 |
+
const walk = seed => {
|
| 141 |
+
const rng = rngFor(seed);
|
| 142 |
+
let g = randomGenome(rng, ALL);
|
| 143 |
+
for (let i = 0; i < 50; i++) g = mutate(cross(g, randomGenome(rng, ALL), rng, { genes: ALL }), rng, { genes: ALL });
|
| 144 |
+
return JSON.stringify(g);
|
| 145 |
+
};
|
| 146 |
+
assert.equal(walk(7), walk(7));
|
| 147 |
+
assert.notEqual(walk(7), walk(8));
|
| 148 |
+
});
|
| 149 |
+
|
| 150 |
+
test("building from the shipped tables never writes back into them", () => {
|
| 151 |
+
const before = JSON.stringify({ s: STRATEGIES, a: ARCHETYPES });
|
| 152 |
+
const rng = rngFor(3);
|
| 153 |
+
for (const key of Object.keys(STRATEGIES)) {
|
| 154 |
+
const g = genomeFrom({ strategy: key, genes: ALL });
|
| 155 |
+
const m = mutate(g, rng, { rate: 1, flagRate: 1, genes: ALL });
|
| 156 |
+
m.archetype.unitMix.push("skiff"); // mutate the copy as hard as a caller could
|
| 157 |
+
m.strategy.attackTimeoutMult = 99;
|
| 158 |
+
toOverrides(m, "x", { genes: ALL });
|
| 159 |
+
}
|
| 160 |
+
assert.equal(JSON.stringify({ s: STRATEGIES, a: ARCHETYPES }), before);
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
test("cloneGenome deep-copies the one gene that is a reference", () => {
|
| 164 |
+
const g = genomeFrom({ genes: ALL });
|
| 165 |
+
const c = cloneGenome(g);
|
| 166 |
+
c.archetype.unitMix.push("colossus");
|
| 167 |
+
assert.notEqual(g.archetype.unitMix.length, c.archetype.unitMix.length);
|
| 168 |
+
});
|
| 169 |
+
|
| 170 |
+
/* ---------- reachability: can the search actually move? ---------- */
|
| 171 |
+
|
| 172 |
+
test("a ratio gene never reaches 0 — 0 is absorbing under multiplicative mutation", () => {
|
| 173 |
+
const rng = rngFor(21);
|
| 174 |
+
const genes = geneKeys().filter(g => g.kind === "ratio");
|
| 175 |
+
let g = genomeFrom({ strategy: "aggressive" });
|
| 176 |
+
for (let i = 0; i < 3000; i++) {
|
| 177 |
+
g = mutate(g, rng, { rate: 1, genes: geneKeys() });
|
| 178 |
+
for (const gene of genes) assert.ok(g.strategy[gene.key] > 0, `${gene.key} hit 0 and can never leave`);
|
| 179 |
+
}
|
| 180 |
+
});
|
| 181 |
+
|
| 182 |
+
test("a count gene DOES reach 0 — it is a real allele (rusher.turretCount, rusher.garrison)", () => {
|
| 183 |
+
const rng = rngFor(22);
|
| 184 |
+
const genes = geneKeys();
|
| 185 |
+
let g = genomeFrom({ strategy: "economic", genes });
|
| 186 |
+
let sawZero = false;
|
| 187 |
+
for (let i = 0; i < 3000 && !sawZero; i++) {
|
| 188 |
+
g = mutate(g, rng, { rate: 1, genes });
|
| 189 |
+
if (g.strategy.standingArmyCap === 0 || g.strategy.matchFloor === 0) sawZero = true;
|
| 190 |
+
}
|
| 191 |
+
assert.ok(sawZero, "a count gene never reached 0 in 3000 mutations — the low end is unreachable");
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
test("the mix changes length in BOTH directions and stays inside its length bounds", () => {
|
| 195 |
+
const rng = rngFor(23);
|
| 196 |
+
let mix = [...ARCHETYPES.balanced.unitMix];
|
| 197 |
+
const start = mix.length;
|
| 198 |
+
let grew = false, shrank = false;
|
| 199 |
+
for (let i = 0; i < 2000; i++) {
|
| 200 |
+
mix = mutateMix(mix, rng);
|
| 201 |
+
assert.ok(mix.length >= 2 && mix.length <= 10, `mix length escaped: ${mix.length}`);
|
| 202 |
+
if (mix.length > start) grew = true;
|
| 203 |
+
if (mix.length < start) shrank = true;
|
| 204 |
+
}
|
| 205 |
+
assert.ok(grew && shrank, `mix never changed length both ways (grew ${grew}, shrank ${shrank})`);
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
test("order crossover of two mixes draws only from its parents' alphabet and keeps a legal length", () => {
|
| 209 |
+
const rng = rngFor(24);
|
| 210 |
+
for (let i = 0; i < 500; i++) {
|
| 211 |
+
const a = randomGenome(rng, ALL).archetype.unitMix;
|
| 212 |
+
const b = randomGenome(rng, ALL).archetype.unitMix;
|
| 213 |
+
const c = crossMix(a, b, rng);
|
| 214 |
+
assert.ok(c.length >= 2 && c.length <= 10, `crossMix length ${c.length}`);
|
| 215 |
+
const parents = new Set([...a, ...b]);
|
| 216 |
+
assert.ok(c.every(t => parents.has(t)), "crossMix invented a unit neither parent fielded");
|
| 217 |
+
}
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
test("self-adaptive sigma actually moves, in both directions", () => {
|
| 221 |
+
const rng = rngFor(25);
|
| 222 |
+
let g = emptyGenome();
|
| 223 |
+
let up = false, down = false;
|
| 224 |
+
for (let i = 0; i < 200; i++) {
|
| 225 |
+
const prev = g.sigma;
|
| 226 |
+
g = mutate(g, rng, { genes: [] });
|
| 227 |
+
if (g.sigma > prev) up = true;
|
| 228 |
+
if (g.sigma < prev) down = true;
|
| 229 |
+
}
|
| 230 |
+
assert.ok(up && down, "sigma is not self-adapting");
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
/* ---------- module-wise crossover is actually module-wise ---------- */
|
| 234 |
+
|
| 235 |
+
test("module-wise crossover takes whole linkage groups, never a mix of parents within one", () => {
|
| 236 |
+
const rng = rngFor(31);
|
| 237 |
+
const genes = geneKeys();
|
| 238 |
+
let sawSplit = false; // …and it must sometimes take DIFFERENT parents per module
|
| 239 |
+
for (let i = 0; i < 200; i++) {
|
| 240 |
+
const a = randomGenome(rng, genes), b = randomGenome(rng, genes);
|
| 241 |
+
const c = cross(a, b, rng, { moduleWise: 1, blend: 0, genes });
|
| 242 |
+
const parentOf = new Map();
|
| 243 |
+
for (const g of genes) {
|
| 244 |
+
const v = c[g.layer][g.key], va = a[g.layer][g.key], vb = b[g.layer][g.key];
|
| 245 |
+
if (va === vb) continue; // uninformative — both parents agree
|
| 246 |
+
const src = v === va ? "a" : v === vb ? "b" : "?";
|
| 247 |
+
assert.notEqual(src, "?", `${g.key} came from neither parent`);
|
| 248 |
+
if (parentOf.has(g.module)) assert.equal(src, parentOf.get(g.module),
|
| 249 |
+
`module "${g.module}" was split across parents — that is uniform crossover, not module-wise`);
|
| 250 |
+
parentOf.set(g.module, src);
|
| 251 |
+
}
|
| 252 |
+
if (new Set(parentOf.values()).size > 1) sawSplit = true;
|
| 253 |
+
}
|
| 254 |
+
assert.ok(sawSplit, "every child took every module from one parent — crossover is doing nothing");
|
| 255 |
+
});
|
| 256 |
+
|
| 257 |
+
test("blend crossover puts an ordered gene BETWEEN its parents", () => {
|
| 258 |
+
const rng = rngFor(32);
|
| 259 |
+
const genes = geneKeys().filter(g => g.kind === "ratio");
|
| 260 |
+
for (let i = 0; i < 200; i++) {
|
| 261 |
+
const a = randomGenome(rng, geneKeys()), b = randomGenome(rng, geneKeys());
|
| 262 |
+
const c = cross(a, b, rng, { moduleWise: 0, blend: 1, genes: geneKeys() });
|
| 263 |
+
for (const g of genes) {
|
| 264 |
+
const lo = Math.min(a.strategy[g.key], b.strategy[g.key]);
|
| 265 |
+
const hi = Math.max(a.strategy[g.key], b.strategy[g.key]);
|
| 266 |
+
const v = c.strategy[g.key];
|
| 267 |
+
assert.ok(v >= lo - 1e-3 && v <= hi + 1e-3, `${g.key}: ${v} is not between ${lo} and ${hi}`);
|
| 268 |
+
}
|
| 269 |
+
}
|
| 270 |
+
});
|
| 271 |
+
|
| 272 |
+
/* ---------- lowering ---------- */
|
| 273 |
+
|
| 274 |
+
test("standingArmyCap is emitted ONLY behind its capsArmy gate", () => {
|
| 275 |
+
const genes = geneKeys();
|
| 276 |
+
const on = genomeFrom({ strategy: "economic", genes });
|
| 277 |
+
assert.equal(on.strategy.capsArmy, true, "Economic ships a standingArmyCap, so its gate starts on");
|
| 278 |
+
assert.ok("standingArmyCap" in toOverrides(on, "x", { genes }).strategies.x);
|
| 279 |
+
|
| 280 |
+
const off = cloneGenome(on);
|
| 281 |
+
off.strategy.capsArmy = false;
|
| 282 |
+
const lowered = toOverrides(off, "x", { genes }).strategies.x;
|
| 283 |
+
// aiEconomy.js reads `strategy.standingArmyCap != null` — emitting a number at all IS the switch,
|
| 284 |
+
// so an ungated emit would cap the army of every genome in the population.
|
| 285 |
+
assert.ok(!("standingArmyCap" in lowered), "an ungated standingArmyCap caps the whole population");
|
| 286 |
+
// …and the gate itself is never emitted as a dial, because nothing reads it.
|
| 287 |
+
assert.ok(!("capsArmy" in lowered));
|
| 288 |
+
});
|
| 289 |
+
|
| 290 |
+
test("a lowered genome is exactly the --overrides shape, and archetypes get a key of their own", () => {
|
| 291 |
+
const genes = geneKeys({ layers: ["strategy", "archetype"] });
|
| 292 |
+
const g = genomeFrom({ strategy: "aggressive", archetype: "rusher", genes });
|
| 293 |
+
const cand = toCandidate(g, "gen1i0", { genes });
|
| 294 |
+
assert.equal(cand.name, "gen1i0");
|
| 295 |
+
assert.equal(cand.strategy, "gen1i0");
|
| 296 |
+
assert.deepEqual(Object.keys(cand.overrides.strategies), ["gen1i0"]);
|
| 297 |
+
// Never over a SHIPPED archetype key: two candidates in one duel share a live table and
|
| 298 |
+
// applyOverrides merges, so patching a shared key leaves both seats playing a row belonging to
|
| 299 |
+
// neither — the collision tools/ailab.js's assertNoOverrideCollision refuses outright.
|
| 300 |
+
assert.deepEqual(Object.keys(cand.overrides.archetypes), ["gen1i0-arch"]);
|
| 301 |
+
assert.equal(cand.archetype, "gen1i0-arch");
|
| 302 |
+
assert.ok(!Object.keys(ARCHETYPES).includes("gen1i0-arch"), "toCandidate must not touch the live table");
|
| 303 |
+
});
|
| 304 |
+
|
| 305 |
+
test("a strategy-only genome carries no archetype at all, so runDuel forwards null", () => {
|
| 306 |
+
const cand = toCandidate(genomeFrom({ strategy: "economic" }), "x");
|
| 307 |
+
assert.equal(cand.archetype, undefined);
|
| 308 |
+
assert.equal(cand.overrides.archetypes, undefined);
|
| 309 |
+
});
|
| 310 |
+
|
| 311 |
+
test("genomeFrom round-trips a shipped strategy's own values", () => {
|
| 312 |
+
const genes = geneKeys({ odyssey: true });
|
| 313 |
+
const g = genomeFrom({ strategy: "aggressive", genes });
|
| 314 |
+
assert.equal(g.strategy.attackTimeoutMult, STRATEGIES.aggressive.attackTimeoutMult);
|
| 315 |
+
assert.equal(g.strategy.garrisonMult, STRATEGIES.aggressive.garrisonMult);
|
| 316 |
+
assert.equal(g.strategy.useBombOffensively, true);
|
| 317 |
+
// A gene the shipped row doesn't carry is FILLED from the schema, never left absent — an absent
|
| 318 |
+
// gene has nothing to mutate multiplicatively and nothing to blend, so it would be frozen.
|
| 319 |
+
for (const gene of genes) assert.notEqual(g[gene.layer][gene.key], undefined, `${gene.key} left absent`);
|
| 320 |
+
});
|
| 321 |
+
|
| 322 |
+
test("diffGenes names what moved and stays silent when nothing did", () => {
|
| 323 |
+
const a = genomeFrom({ strategy: "default" });
|
| 324 |
+
assert.equal(diffGenes(a, cloneGenome(a)), "");
|
| 325 |
+
const b = cloneGenome(a);
|
| 326 |
+
b.strategy.garrisonMult = 2.5;
|
| 327 |
+
assert.match(diffGenes(b, a), /garrisonMult=2\.5/);
|
| 328 |
+
});
|
|
@@ -103,6 +103,11 @@ import { INITIAL_RATING, applySeries } from "../elo.js";
|
|
| 103 |
// this file's CLI half (docs/competitions-and-elo.md Phase 3). Imported under the SAME names this
|
| 104 |
// file has always used, and re-exported below exactly as before — see the TIER 5 header comment.
|
| 105 |
import { rankStandings, pairRound, buildSwissBracket, roundRobinPairs, swissRoundCount } from "../pairing.js";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
const WORLDS = [...Object.keys(PLANET_ARCHETYPE), ...Object.keys(ODYSSEY_EXTRA_ARCHETYPE)];
|
| 108 |
const DT = 0.1; // the sim's fixed step, same as the game loop
|
|
@@ -664,9 +669,19 @@ export function runLeaderboard(candidates, { worlds, difficulty = "medium", oppo
|
|
| 664 |
// rows through it, so a same-name pair would silently collide both candidates' Elo into one entry
|
| 665 |
// (elo.js's own applyResult throws on exactly this, as a backstop — this check just gives the CLI
|
| 666 |
// user a clear, immediate reason instead of a duel that runs to completion and THEN throws).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 667 |
export function runDuel(a, b, {
|
| 668 |
worlds = ["korrath", "ferros", "vesper", "kybernet"], difficulty = "medium",
|
| 669 |
-
seeds = 2, seedBase = 1, minutes,
|
| 670 |
} = {}) {
|
| 671 |
if (!a || !a.name) throw new Error('candidate A needs a "name"');
|
| 672 |
if (!b || !b.name) throw new Error('candidate B needs a "name"');
|
|
@@ -686,8 +701,9 @@ export function runDuel(a, b, {
|
|
| 686 |
for (const world of worlds)
|
| 687 |
for (let rep = 0; rep < seeds; rep++)
|
| 688 |
rows.push(duelRun({
|
| 689 |
-
world, seed: duelSeed(seedBase, world, difficulty, a.name, b.name, rep),
|
| 690 |
dials, aName: a.name, aStrategy, bName: b.name, bStrategy, minutes,
|
|
|
|
| 691 |
// Alternate the map's own asym halves by replicate parity — see the FAIRNESS
|
| 692 |
// paragraph above. A no-op on every world without an `asym` block.
|
| 693 |
swapAsym: rep % 2 === 1,
|
|
@@ -944,6 +960,217 @@ export function runSwissTournament(candidates, opts = {}) {
|
|
| 944 |
return list.map(diff => runSwissBracket(candidates, numRounds, { ...rest, difficulty: diff }));
|
| 945 |
}
|
| 946 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 947 |
/* ============================================================
|
| 948 |
HEALTH CHECKS — the findings this bench already turned up, encoded
|
| 949 |
|
|
@@ -1452,8 +1679,100 @@ const CMDS = {
|
|
| 1452 |
console.log(`\nwrote ${args.json}`);
|
| 1453 |
}
|
| 1454 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1455 |
};
|
| 1456 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1457 |
const USAGE = `AI LAB — a headless bench for the Odyssey opponent.
|
| 1458 |
|
| 1459 |
node tools/ailab.js probe [--world ferros] [--strategy default] [--difficulty medium]
|
|
@@ -1507,6 +1826,25 @@ const USAGE = `AI LAB — a headless bench for the Odyssey opponent.
|
|
| 1507 |
a greedy walk could've avoided -- see the TIER 5 header comment for
|
| 1508 |
the pairing/bye rules. SWISS STANDINGS carries the same elo column as
|
| 1509 |
'duel', folded through the whole bracket in round/pairing order.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1510 |
|
| 1511 |
Common flags
|
| 1512 |
--overrides f.json inject candidate rows into the AI tables before running:
|
|
|
|
| 103 |
// this file's CLI half (docs/competitions-and-elo.md Phase 3). Imported under the SAME names this
|
| 104 |
// file has always used, and re-exported below exactly as before — see the TIER 5 header comment.
|
| 105 |
import { rankStandings, pairRound, buildSwissBracket, roundRobinPairs, swissRoundCount } from "../pairing.js";
|
| 106 |
+
// The genome — the AI as a schema'd, mutable, crossable data structure (docs/ai-evolution-design.md).
|
| 107 |
+
// A leaf module like duelCore/pairing: it imports the three AI tables and mulberry32 and nothing
|
| 108 |
+
// else, so `evolve` below is the only thing in this file that knows evolution exists.
|
| 109 |
+
import { geneKeys, genomeFrom, randomGenome, mutate, cross, cloneGenome, toCandidate, rngFor, diffGenes }
|
| 110 |
+
from "./genome.js";
|
| 111 |
|
| 112 |
const WORLDS = [...Object.keys(PLANET_ARCHETYPE), ...Object.keys(ODYSSEY_EXTRA_ARCHETYPE)];
|
| 113 |
const DT = 0.1; // the sim's fixed step, same as the game loop
|
|
|
|
| 669 |
// rows through it, so a same-name pair would silently collide both candidates' Elo into one entry
|
| 670 |
// (elo.js's own applyResult throws on exactly this, as a backstop — this check just gives the CLI
|
| 671 |
// user a clear, immediate reason instead of a duel that runs to completion and THEN throws).
|
| 672 |
+
// `archetype` (docs/competitions-and-elo.md D3) is a per-candidate field tools/duelCore.js's
|
| 673 |
+
// runDuelMatch has always accepted and competitionWorker.js has always passed, but which this
|
| 674 |
+
// function never forwarded — so a CLI duel had both seats playing whatever temperament the WORLD
|
| 675 |
+
// hands out, and a candidate carrying its own archetype was silently ignored here while working
|
| 676 |
+
// in-game. Forwarded now (absent/undefined on every hand-written candidate file, and runDuelMatch
|
| 677 |
+
// treats absent as byte-identical to omitting it — test/duelCore.test.js pins that), which is what
|
| 678 |
+
// lets an evolved genome carry a macro/tempo/composition chromosome and not just a strategy row.
|
| 679 |
+
//
|
| 680 |
+
// `seedKey`, likewise, is forwarded straight to duelSeed — see its comment in tools/duelCore.js
|
| 681 |
+
// for why an evolutionary caller needs to pin a generation's maps and why nothing else should.
|
| 682 |
export function runDuel(a, b, {
|
| 683 |
worlds = ["korrath", "ferros", "vesper", "kybernet"], difficulty = "medium",
|
| 684 |
+
seeds = 2, seedBase = 1, minutes, seedKey,
|
| 685 |
} = {}) {
|
| 686 |
if (!a || !a.name) throw new Error('candidate A needs a "name"');
|
| 687 |
if (!b || !b.name) throw new Error('candidate B needs a "name"');
|
|
|
|
| 701 |
for (const world of worlds)
|
| 702 |
for (let rep = 0; rep < seeds; rep++)
|
| 703 |
rows.push(duelRun({
|
| 704 |
+
world, seed: duelSeed(seedBase, world, difficulty, a.name, b.name, rep, seedKey),
|
| 705 |
dials, aName: a.name, aStrategy, bName: b.name, bStrategy, minutes,
|
| 706 |
+
aArchetype: a.archetype || null, bArchetype: b.archetype || null,
|
| 707 |
// Alternate the map's own asym halves by replicate parity — see the FAIRNESS
|
| 708 |
// paragraph above. A no-op on every world without an `asym` block.
|
| 709 |
swapAsym: rep % 2 === 1,
|
|
|
|
| 960 |
return list.map(diff => runSwissBracket(candidates, numRounds, { ...rest, difficulty: diff }));
|
| 961 |
}
|
| 962 |
|
| 963 |
+
/* ============================================================
|
| 964 |
+
EVOLUTION — a population of genomes, selected by real self-play (docs/ai-evolution-design.md)
|
| 965 |
+
|
| 966 |
+
`search` above is a coordinate scan: it moves ONE dial at a time and greedily keeps whatever
|
| 967 |
+
improved. That is the cheapest thing that works, and it has a structural blind spot — it cannot
|
| 968 |
+
cross a valley where two dials must move TOGETHER. This codebase has the worked example already
|
| 969 |
+
written down: engine/aiStrategy.js records that Aggressive finished last of four in self-play,
|
| 970 |
+
that a coordinate scan over its own offense dials could not fix it, and that what fixed it was
|
| 971 |
+
an ECONOMY dial (workerTargetMult) borrowed from another strategy. A scan structurally cannot
|
| 972 |
+
find that; a population with mutation and crossover finds it by construction.
|
| 973 |
+
|
| 974 |
+
So this is the same "candidate vs a yardstick" shape the rest of the file has, with three
|
| 975 |
+
differences: candidates are generated rather than hand-written (tools/genome.js), there are many
|
| 976 |
+
of them at once, and the yardstick includes each other.
|
| 977 |
+
|
| 978 |
+
WHAT MAKES THE FITNESS TRUSTWORTHY, since that is the only part that decides whether any of this
|
| 979 |
+
is real:
|
| 980 |
+
|
| 981 |
+
• It is DUEL Elo, not score(). score()'s six weights are a hand-written definition of "better
|
| 982 |
+
AI", and a population is a machine for exploiting hand-written definitions — `thrift` pays
|
| 983 |
+
for ending poor (a genome that dumps ore into junk turrets farms it), `pressure` counts
|
| 984 |
+
waves (a genome that trickles one unit at a time farms it). A win cannot be farmed except by
|
| 985 |
+
winning. score() stays available as a DIAGNOSTIC via `sweep`, never as the objective here.
|
| 986 |
+
• It is SWISS-scheduled, so a generation costs O(n log n) pairings instead of round-robin's
|
| 987 |
+
C(n,2) — the difference between a generation taking minutes and taking an hour, which is
|
| 988 |
+
the difference between running this and not.
|
| 989 |
+
• The four shipped baselines ride along as a HALL OF FAME. A population evolving only against
|
| 990 |
+
itself can drift in a cycle forever (rusher beats greedy beats turtle beats rusher) with no
|
| 991 |
+
absolute progress — the Red Queen. Elo measured partly against a fixed anchor is absolute.
|
| 992 |
+
tools/candidates/baseline-*.json already exist and are exactly that anchor.
|
| 993 |
+
• Every bracket in `--difficulties` is rated SEPARATELY and then aggregated by the WORST of
|
| 994 |
+
them by default (`--agg min`). engine/aiStrategy.js has the cautionary row for this too: a
|
| 995 |
+
workerTargetMult of 1.4 wins Medium harder and LOSES Hard, because Hard's own row already
|
| 996 |
+
carries 1.25 and the layers compose multiplicatively. A genome scored on one difficulty is
|
| 997 |
+
not scored.
|
| 998 |
+
• Every pairing in the whole run shares ONE seedKey (tools/duelCore.js duelSeed), so every
|
| 999 |
+
genome ever evaluated in round R faced the identical maps. Without it, each generation's
|
| 1000 |
+
generated names hash to their own map set and "the child beat its parent's number" is partly
|
| 1001 |
+
a statement about map luck. The cost of pinning is that the run can overfit that map set,
|
| 1002 |
+
which is what `--holdout-worlds` is for: validate the champion on worlds it never trained on
|
| 1003 |
+
and report both numbers.
|
| 1004 |
+
============================================================ */
|
| 1005 |
+
|
| 1006 |
+
const EVO_SEED_KEY = "evolve"; // see the seedKey paragraph above — one pinned map set per run
|
| 1007 |
+
|
| 1008 |
+
/**
|
| 1009 |
+
* Rate one generation's field and return fitness per candidate name. One INDEPENDENT rating table
|
| 1010 |
+
* per difficulty bracket (elo.js D2: brackets are never blended), aggregated by `agg`.
|
| 1011 |
+
* @returns {{ fitness: Map<string, number>, perBracket: Object[] }}
|
| 1012 |
+
*/
|
| 1013 |
+
function rateGeneration(candidates, { difficulties, agg, ...opts }) {
|
| 1014 |
+
const brackets = runSwissTournament(candidates, { ...opts, difficulties });
|
| 1015 |
+
const ratings = brackets.map(b => eloForMatches(b.roundsLog.flatMap(r => r.matches)));
|
| 1016 |
+
const fitness = new Map();
|
| 1017 |
+
for (const c of candidates) {
|
| 1018 |
+
const vals = ratings.map(t => (t[c.name] ? t[c.name].rating : INITIAL_RATING));
|
| 1019 |
+
fitness.set(c.name, agg === "mean" ? vals.reduce((a, v) => a + v, 0) / vals.length : Math.min(...vals));
|
| 1020 |
+
}
|
| 1021 |
+
return { fitness, perBracket: brackets.map((b, i) => ({ difficulty: b.difficulty, standings: b.standings, ratings: ratings[i] })) };
|
| 1022 |
+
}
|
| 1023 |
+
|
| 1024 |
+
/**
|
| 1025 |
+
* Disqualify a genome that trips one of the named CHECKS — a genome that wins duels while
|
| 1026 |
+
* deadlocking its own supply is a bug the search found, not a strategy.
|
| 1027 |
+
*
|
| 1028 |
+
* OPT-IN, and that is a deliberate calibration argument rather than a cost one. Every detector in
|
| 1029 |
+
* CHECKS is written for a 40-60 sim-minute ODYSSEY run and several carry an explicit
|
| 1030 |
+
* "…and it never resolved in the last third" term keyed to that length. Run them over a duel-length
|
| 1031 |
+
* skirmish and they fire on healthy genomes — which is the exact failure this file's own CHECKS
|
| 1032 |
+
* header calls out ("a metric that fires on correct behaviour is worse than no metric", three
|
| 1033 |
+
* rewrites). So the screen runs at its OWN length on its OWN Odyssey worlds, and only when asked.
|
| 1034 |
+
*/
|
| 1035 |
+
function screenGenome(cand, { worlds, minutes, opponent, seedBase }) {
|
| 1036 |
+
const snap = snapshotTables();
|
| 1037 |
+
try {
|
| 1038 |
+
if (cand.overrides) applyOverrides(cand.overrides);
|
| 1039 |
+
const tripped = new Set();
|
| 1040 |
+
for (const world of worlds) {
|
| 1041 |
+
const r = run({ minutes, sample: 5, opponent, apm: "real", seedBase, world,
|
| 1042 |
+
strategy: cand.strategy, difficulty: "medium",
|
| 1043 |
+
seed: runSeed(seedBase, world, cand.strategy, "medium", 0) });
|
| 1044 |
+
for (const c of CHECKS) if (c.hit(r)) tripped.add(c.id);
|
| 1045 |
+
}
|
| 1046 |
+
return [...tripped];
|
| 1047 |
+
} finally {
|
| 1048 |
+
restoreTables(snap);
|
| 1049 |
+
}
|
| 1050 |
+
}
|
| 1051 |
+
|
| 1052 |
+
/**
|
| 1053 |
+
* Run the whole thing. Returns a plain result object (never console output) so the CLI and a test
|
| 1054 |
+
* can both read it — the same shape discipline runSearch already follows. `best` is the champion
|
| 1055 |
+
* lowered back into a runnable candidate; `bestEdge` (not `bestFitness`) is the cross-generation
|
| 1056 |
+
* comparable number — see the anchoring comment in the loop below.
|
| 1057 |
+
* @param {Object} opts
|
| 1058 |
+
* @returns {{ genes: Object[], layers: string[], odyssey: boolean, agg: string,
|
| 1059 |
+
* generations: number, population: number, bestName: string, bestGenome: Object,
|
| 1060 |
+
* bestFitness: number, bestEdge: number, bestGen: number, best: Object, log: Object[] }}
|
| 1061 |
+
*/
|
| 1062 |
+
export function runEvolution({
|
| 1063 |
+
population = 12, generations = 5, seed = 1, elites = 2,
|
| 1064 |
+
worlds = ["korrath", "ferros", "vesper"], difficulties = ["medium"], seeds = 1, minutes = 40,
|
| 1065 |
+
rounds, agg = "min", layers = ["strategy"], odyssey = false,
|
| 1066 |
+
hallOfFame = [], seedStrategies = Object.keys(STRATEGIES),
|
| 1067 |
+
screen = null, onGeneration = null,
|
| 1068 |
+
} = {}) {
|
| 1069 |
+
const genes = geneKeys({ layers, odyssey });
|
| 1070 |
+
if (!genes.length) throw new Error(`no genes selected — layers "${layers.join(",")}" matched nothing in GENOME_SCHEMA`);
|
| 1071 |
+
const rng = rngFor(hashStr(`${seed}:evolve`));
|
| 1072 |
+
|
| 1073 |
+
// SEED THE POPULATION from the shipped strategies first. They are the best starting points
|
| 1074 |
+
// anyone has — four rows with real human search already spent on them — and a run that discards
|
| 1075 |
+
// them starts from behind. The remainder is split between mutated copies of those (local search
|
| 1076 |
+
// around known-good) and uniformly random genomes (so the run can reach regions no shipped row
|
| 1077 |
+
// is near).
|
| 1078 |
+
let pop = [];
|
| 1079 |
+
for (const key of seedStrategies) {
|
| 1080 |
+
if (pop.length >= population) break;
|
| 1081 |
+
pop.push(genomeFrom({ strategy: key, genes }));
|
| 1082 |
+
}
|
| 1083 |
+
const seeded = pop.length;
|
| 1084 |
+
// Alternate mutant/random, and cycle the mutant's PARENT across all the seeded rows rather than
|
| 1085 |
+
// deriving from pop.length (which, at an even population, only ever lands on the even-indexed
|
| 1086 |
+
// seeds — half the shipped strategies would get no local search around them at all).
|
| 1087 |
+
for (let fill = 0; pop.length < population; fill++) {
|
| 1088 |
+
pop.push(fill % 2 === 0 && seeded
|
| 1089 |
+
? mutate(pop[Math.floor(fill / 2) % seeded], rng, { genes })
|
| 1090 |
+
: randomGenome(rng, genes));
|
| 1091 |
+
}
|
| 1092 |
+
|
| 1093 |
+
const log = [];
|
| 1094 |
+
let best = null;
|
| 1095 |
+
for (let gen = 1; gen <= generations; gen++) {
|
| 1096 |
+
const named = pop.map((genome, i) => {
|
| 1097 |
+
const name = `g${gen}i${i}`;
|
| 1098 |
+
return { genome, name, cand: toCandidate(genome, name, { genes }) };
|
| 1099 |
+
});
|
| 1100 |
+
const field = [...named.map(n => n.cand), ...hallOfFame];
|
| 1101 |
+
const { fitness, perBracket } = rateGeneration(field, {
|
| 1102 |
+
worlds, difficulties, seeds, seedBase: seed, minutes, rounds, agg, seedKey: EVO_SEED_KEY,
|
| 1103 |
+
});
|
| 1104 |
+
|
| 1105 |
+
// Screening runs AFTER rating (so the log records what a disqualified genome would have
|
| 1106 |
+
// scored) and only over the individuals that could actually be selected.
|
| 1107 |
+
const ranked = named.map(n => ({ ...n, fitness: fitness.get(n.name), tripped: [] }))
|
| 1108 |
+
.sort((x, y) => y.fitness - x.fitness);
|
| 1109 |
+
if (screen) {
|
| 1110 |
+
for (const r of ranked.slice(0, Math.max(elites, Math.ceil(ranked.length / 2)))) {
|
| 1111 |
+
r.tripped = screenGenome(r.cand, { ...screen, seedBase: seed });
|
| 1112 |
+
if (r.tripped.length) r.fitness = -Infinity;
|
| 1113 |
+
}
|
| 1114 |
+
ranked.sort((x, y) => y.fitness - x.fitness);
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
const anchors = hallOfFame.map(h => ({ name: h.name, elo: fitness.get(h.name) }));
|
| 1118 |
+
const champion = ranked[0];
|
| 1119 |
+
// ANCHOR THE SCALE. Elo is folded from a FRESH 1200 baseline over each generation's own
|
| 1120 |
+
// matches (eloForMatches — no persistence across runs, elo.js D7), so a raw rating is only
|
| 1121 |
+
// comparable WITHIN a generation: the field changes every generation and the mean is pinned at
|
| 1122 |
+
// 1200 whatever the field's absolute strength. Comparing generation 5's champion to generation
|
| 1123 |
+
// 1's on raw Elo would therefore measure nothing at all — the exact Red Queen failure the hall
|
| 1124 |
+
// of fame exists to prevent, reintroduced in the arithmetic.
|
| 1125 |
+
// `edge` is the rating ABOVE the hall of fame's own mean in the same tournament. The anchors
|
| 1126 |
+
// are fixed genomes, so their mean is a fixed point of skill, and an edge IS comparable across
|
| 1127 |
+
// generations. Within a generation it is a constant offset, so it changes no ranking.
|
| 1128 |
+
// With no hall of fame there is nothing to anchor to, and edge degenerates to "rating above
|
| 1129 |
+
// the 1200 origin" — still the honest number, just not an absolute one; the CLI says so.
|
| 1130 |
+
const anchorMean = anchors.length
|
| 1131 |
+
? anchors.reduce((a, x) => a + x.elo, 0) / anchors.length : INITIAL_RATING;
|
| 1132 |
+
for (const r of ranked) r.edge = r.fitness === -Infinity ? -Infinity : r.fitness - anchorMean;
|
| 1133 |
+
if (!best || champion.edge > best.edge) best = { ...champion, gen };
|
| 1134 |
+
log.push({
|
| 1135 |
+
gen, anchorMean: +anchorMean.toFixed(1),
|
| 1136 |
+
ranked: ranked.map(r => ({ name: r.name, elo: +r.fitness.toFixed(1), edge: +r.edge.toFixed(1),
|
| 1137 |
+
sigma: +r.genome.sigma.toFixed(3), tripped: r.tripped })),
|
| 1138 |
+
anchors: anchors.map(a => ({ name: a.name, elo: +a.elo.toFixed(1) })),
|
| 1139 |
+
perBracket: perBracket.map(b => ({ difficulty: b.difficulty, standings: b.standings })),
|
| 1140 |
+
champion: { name: champion.name, elo: +champion.fitness.toFixed(1), edge: +champion.edge.toFixed(1) },
|
| 1141 |
+
});
|
| 1142 |
+
if (onGeneration) onGeneration(log[log.length - 1], ranked, anchors);
|
| 1143 |
+
if (gen === generations) break;
|
| 1144 |
+
|
| 1145 |
+
// BREED. Elites carried through UNCHANGED — a generation that can lose its best individual to
|
| 1146 |
+
// an unlucky mutation is not monotonic, and with a noisy objective it will do that regularly.
|
| 1147 |
+
const next = ranked.slice(0, elites).map(r => cloneGenome(r.genome));
|
| 1148 |
+
// Tournament selection: three at random, fittest breeds. Cheap, needs no normalised fitness
|
| 1149 |
+
// (Elo is an interval scale with an arbitrary origin — proportional selection on it would be
|
| 1150 |
+
// meaningless), and its selection pressure is tunable by the tournament size alone.
|
| 1151 |
+
const draft = () => {
|
| 1152 |
+
let bestOf = null;
|
| 1153 |
+
for (let k = 0; k < 3; k++) {
|
| 1154 |
+
const c = ranked[Math.floor(rng() * ranked.length)];
|
| 1155 |
+
if (!bestOf || c.fitness > bestOf.fitness) bestOf = c;
|
| 1156 |
+
}
|
| 1157 |
+
return bestOf.genome;
|
| 1158 |
+
};
|
| 1159 |
+
while (next.length < population) {
|
| 1160 |
+
const p1 = draft(), p2 = draft();
|
| 1161 |
+
next.push(mutate(cross(p1, p2, rng, { genes }), rng, { genes }));
|
| 1162 |
+
}
|
| 1163 |
+
pop = next;
|
| 1164 |
+
}
|
| 1165 |
+
|
| 1166 |
+
return {
|
| 1167 |
+
genes, layers, odyssey, agg, generations, population,
|
| 1168 |
+
bestName: best.name, bestGenome: best.genome, bestFitness: best.fitness, bestEdge: best.edge,
|
| 1169 |
+
bestGen: best.gen, best: toCandidate(best.genome, "evolved", { genes }),
|
| 1170 |
+
log,
|
| 1171 |
+
};
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
/* ============================================================
|
| 1175 |
HEALTH CHECKS — the findings this bench already turned up, encoded
|
| 1176 |
|
|
|
|
| 1679 |
console.log(`\nwrote ${args.json}`);
|
| 1680 |
}
|
| 1681 |
},
|
| 1682 |
+
|
| 1683 |
+
// A population of genomes, bred and selected by the same side-swapped, difficulty-bracketed
|
| 1684 |
+
// self-play `duel`/`swiss` already run — see the EVOLUTION header comment above for why the
|
| 1685 |
+
// fitness is duel Elo rather than score(), why the shipped baselines ride along, and why the
|
| 1686 |
+
// whole run shares one pinned map set.
|
| 1687 |
+
evolve(args) {
|
| 1688 |
+
const layers = list(args.genes, ["strategy"]);
|
| 1689 |
+
const hallOfFame = list(args.baselines, [
|
| 1690 |
+
"tools/candidates/baseline-adaptive.json", "tools/candidates/baseline-aggressive.json",
|
| 1691 |
+
"tools/candidates/baseline-economic.json", "tools/candidates/baseline-force-parity.json",
|
| 1692 |
+
]).map(p => JSON.parse(readFileSync(p, "utf8")));
|
| 1693 |
+
const worlds = list(args.worlds, ["korrath", "ferros", "vesper"]);
|
| 1694 |
+
const difficulties = list(args.difficulties, [args.difficulty || "medium"]);
|
| 1695 |
+
const screen = args.screen && args.screen !== "false"
|
| 1696 |
+
? { worlds: list(args["screen-worlds"], ["ferros", "korrath"]),
|
| 1697 |
+
minutes: num(args["screen-minutes"], 40), opponent: args.opponent || "tech" }
|
| 1698 |
+
: null;
|
| 1699 |
+
const opts = {
|
| 1700 |
+
population: num(args.population, 12), generations: num(args.generations, 5),
|
| 1701 |
+
seed: num(args.seed, 1), elites: num(args.elites, 2),
|
| 1702 |
+
worlds, difficulties, seeds: num(args.seeds, 1),
|
| 1703 |
+
minutes: args.minutes !== undefined ? Number(args.minutes) : 40,
|
| 1704 |
+
rounds: args.rounds !== undefined ? Number(args.rounds) : undefined,
|
| 1705 |
+
agg: args.agg === "mean" ? "mean" : "min",
|
| 1706 |
+
layers, odyssey: args.odyssey === "true", hallOfFame, screen,
|
| 1707 |
+
};
|
| 1708 |
+
console.log(`EVOLVE — population ${opts.population} x ${opts.generations} generations`);
|
| 1709 |
+
console.log(` genes: ${geneKeys({ layers, odyssey: opts.odyssey }).map(g => g.key).join(", ")}`);
|
| 1710 |
+
console.log(` worlds: ${worlds.join(", ")} seeds ${opts.seeds} minutes ${opts.minutes}`);
|
| 1711 |
+
console.log(` brackets: ${difficulties.join(", ")} aggregated by ${opts.agg}`);
|
| 1712 |
+
console.log(` hall of fame: ${hallOfFame.map(h => h.name).join(", ") || "(none)"}`);
|
| 1713 |
+
console.log(` screen: ${screen ? `${screen.worlds.join("/")} @ ${screen.minutes}m vs ${screen.opponent}` : "off"}`);
|
| 1714 |
+
if (!opts.odyssey)
|
| 1715 |
+
console.log(` note: Odyssey-only genes are EXCLUDED — a duel is a skirmish, so diplomacy\n`
|
| 1716 |
+
+ ` and industry genes are read by nothing there. --odyssey true to include them\n`
|
| 1717 |
+
+ ` anyway (they will drift freely; the objective cannot see them).`);
|
| 1718 |
+
console.log();
|
| 1719 |
+
|
| 1720 |
+
const baseline = genomeFrom({ strategy: "default", genes: geneKeys({ layers, odyssey: opts.odyssey }) });
|
| 1721 |
+
// CHECKPOINT AFTER EVERY GENERATION, not just at the end. A real run is long — and it gets
|
| 1722 |
+
// LONGER as it succeeds, because a population converging on `neverInitiates` stops resolving
|
| 1723 |
+
// matches by elimination and starts running every one of them to the full clock. Writing only
|
| 1724 |
+
// on completion means an interrupted run yields nothing at all, which is the difference between
|
| 1725 |
+
// "the search is still going" and "the search has to start over". Purely an output side effect:
|
| 1726 |
+
// it consumes no rng and changes no decision, so a checkpointed run and an unwatched one breed
|
| 1727 |
+
// the identical champion.
|
| 1728 |
+
const out = args.out || "evolved.json";
|
| 1729 |
+
const partial = [];
|
| 1730 |
+
const writeCheckpoint = (genome, gen, edge) => {
|
| 1731 |
+
writeFileSync(out, JSON.stringify({ ...toCandidate(genome, "evolved", { genes: genesFor(opts) }), _hypothesis:
|
| 1732 |
+
`Evolved: population ${opts.population} x ${opts.generations} generations, fitness = duel Elo `
|
| 1733 |
+
+ `(${difficulties.join("/")}, agg ${opts.agg}) on ${worlds.join("/")}, seed ${opts.seed}.`
|
| 1734 |
+
+ ` Champion of generation ${gen}, edge ${edge >= 0 ? "+" : ""}${edge.toFixed(0)} vs the hall of fame.` }, null, 2));
|
| 1735 |
+
if (args.json) writeFileSync(args.json, JSON.stringify(partial, null, 1));
|
| 1736 |
+
};
|
| 1737 |
+
let bestSoFar = null;
|
| 1738 |
+
const res = runEvolution({
|
| 1739 |
+
...opts,
|
| 1740 |
+
onGeneration: (entry, ranked) => {
|
| 1741 |
+
partial.push(entry);
|
| 1742 |
+
if (!bestSoFar || ranked[0].edge > bestSoFar.edge) bestSoFar = { genome: ranked[0].genome, gen: entry.gen, edge: ranked[0].edge };
|
| 1743 |
+
writeCheckpoint(bestSoFar.genome, bestSoFar.gen, bestSoFar.edge);
|
| 1744 |
+
console.log(`-- generation ${entry.gen} --`);
|
| 1745 |
+
console.log(pad("#", 4) + pad("genome", 9) + padL("elo", 6) + padL("edge", 7) + padL("sigma", 7)
|
| 1746 |
+
+ " genes vs. Adaptive");
|
| 1747 |
+
ranked.slice(0, 5).forEach((r, i) => console.log(
|
| 1748 |
+
pad(String(i + 1), 4) + pad(r.name, 9)
|
| 1749 |
+
+ padL(r.fitness === -Infinity ? "DQ" : r.fitness.toFixed(0), 6)
|
| 1750 |
+
+ padL(r.edge === -Infinity ? "-" : (r.edge >= 0 ? "+" : "") + r.edge.toFixed(0), 7)
|
| 1751 |
+
+ padL(r.genome.sigma.toFixed(3), 7) + " "
|
| 1752 |
+
+ (r.tripped.length ? `[${r.tripped.join(",")}] ` : "")
|
| 1753 |
+
+ diffGenes(r.genome, baseline, { genes: genesFor(opts) }).slice(0, 92)));
|
| 1754 |
+
console.log(` anchors (mean ${entry.anchorMean.toFixed(0)}): `
|
| 1755 |
+
+ entry.anchors.map(a => `${a.name} ${a.elo.toFixed(0)}`).join(" "));
|
| 1756 |
+
console.log();
|
| 1757 |
+
},
|
| 1758 |
+
});
|
| 1759 |
+
|
| 1760 |
+
console.log(`BEST: ${res.bestName} from generation ${res.bestGen}, elo ${res.bestFitness.toFixed(0)} `
|
| 1761 |
+
+ `(${res.bestEdge >= 0 ? "+" : ""}${res.bestEdge.toFixed(0)} vs the hall of fame's own mean`
|
| 1762 |
+
+ `${hallOfFame.length ? "" : " — NO baselines given, so this is only vs the 1200 origin"})`);
|
| 1763 |
+
console.log(` ${diffGenes(res.bestGenome, baseline, { genes: res.genes })}`);
|
| 1764 |
+
// The final write goes through the same checkpoint path, so an interrupted run and a completed
|
| 1765 |
+
// one leave a file of exactly the same shape — no "the real output only exists if it finished".
|
| 1766 |
+
writeCheckpoint(res.bestGenome, res.bestGen, res.bestEdge);
|
| 1767 |
+
console.log(`\nwrote ${out} — a runnable candidate: duel it against a baseline, then sweep it.`);
|
| 1768 |
+
if (args.json) console.log(`wrote ${args.json}`);
|
| 1769 |
+
},
|
| 1770 |
};
|
| 1771 |
|
| 1772 |
+
// The gene set a given `evolve` invocation is varying — recomputed for the progress printer rather
|
| 1773 |
+
// than threaded through, since runEvolution's own result only becomes available after it returns.
|
| 1774 |
+
const genesFor = opts => geneKeys({ layers: opts.layers, odyssey: opts.odyssey });
|
| 1775 |
+
|
| 1776 |
const USAGE = `AI LAB — a headless bench for the Odyssey opponent.
|
| 1777 |
|
| 1778 |
node tools/ailab.js probe [--world ferros] [--strategy default] [--difficulty medium]
|
|
|
|
| 1826 |
a greedy walk could've avoided -- see the TIER 5 header comment for
|
| 1827 |
the pairing/bye rules. SWISS STANDINGS carries the same elo column as
|
| 1828 |
'duel', folded through the whole bracket in round/pairing order.
|
| 1829 |
+
node tools/ailab.js evolve [--population 12] [--generations 5] [--elites 2] [--seed 1]
|
| 1830 |
+
[--genes strategy|strategy,archetype] [--odyssey true]
|
| 1831 |
+
[--worlds a,b] [--difficulties medium,hard] [--agg min|mean]
|
| 1832 |
+
[--seeds 1] [--minutes 40] [--rounds N] [--baselines a.json,b.json]
|
| 1833 |
+
[--screen] [--screen-worlds a,b] [--screen-minutes 40]
|
| 1834 |
+
[--out evolved.json] [--json log.json]
|
| 1835 |
+
-- a POPULATION of genomes (tools/genome.js), mutated and crossed,
|
| 1836 |
+
selected by the same side-swapped, difficulty-bracketed self-play
|
| 1837 |
+
'swiss' already runs. Fitness is duel ELO, never score(): a weighted
|
| 1838 |
+
metric is a hand-written definition of "better" and a population is a
|
| 1839 |
+
machine for exploiting one. The four shipped baselines ride along as
|
| 1840 |
+
a HALL OF FAME so the rating is anchored to something fixed rather
|
| 1841 |
+
than drifting in a Red Queen cycle, and every difficulty bracket is
|
| 1842 |
+
rated separately then aggregated by the WORST of them (--agg min) --
|
| 1843 |
+
see the EVOLUTION header comment for both arguments. Writes the
|
| 1844 |
+
champion as a runnable candidate file, so it goes straight back into
|
| 1845 |
+
duel/sweep/leaderboard. Odyssey-gated genes (diplomacy, industry) are
|
| 1846 |
+
EXCLUDED by default: a duel is a skirmish, so nothing there reads
|
| 1847 |
+
them and evolving them would be scoring pure drift.
|
| 1848 |
|
| 1849 |
Common flags
|
| 1850 |
--overrides f.json inject candidate rows into the AI tables before running:
|
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "evolved",
|
| 3 |
+
"strategy": "evolved",
|
| 4 |
+
"overrides": {
|
| 5 |
+
"strategies": {
|
| 6 |
+
"evolved": {
|
| 7 |
+
"attackTimeoutMult": 0.55,
|
| 8 |
+
"armyAttackSizeMult": 0.628,
|
| 9 |
+
"garrisonMult": 0.374,
|
| 10 |
+
"neverInitiates": true,
|
| 11 |
+
"workerTargetMult": 2,
|
| 12 |
+
"warFootingMult": 3.162,
|
| 13 |
+
"warFootingTime": 54.077,
|
| 14 |
+
"turretCountMult": 1.051,
|
| 15 |
+
"matchEnemyForce": false,
|
| 16 |
+
"matchBuffer": 1.264,
|
| 17 |
+
"matchFloor": 10
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
},
|
| 21 |
+
"_hypothesis": "Evolved: population 12 x 6 generations, fitness = duel Elo (medium/hard, agg min) on korrath/ferros/vesper, seed 1."
|
| 22 |
+
}
|
|
@@ -48,6 +48,15 @@ export function pinnedDuelDials(difficulty) {
|
|
| 48 |
// side-symmetry bug would show up as those two disagreeing" — and with an order-dependent seed the
|
| 49 |
// two halves would differ in seat AND map, so a disagreement would be confounded with ordinary
|
| 50 |
// seed variance and carry no information at all.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
/**
|
| 52 |
* @param {number} base
|
| 53 |
* @param {string} world
|
|
@@ -55,10 +64,12 @@ export function pinnedDuelDials(difficulty) {
|
|
| 55 |
* @param {string} aName
|
| 56 |
* @param {string} bName
|
| 57 |
* @param {number} rep
|
|
|
|
| 58 |
* @returns {number}
|
| 59 |
*/
|
| 60 |
-
export function duelSeed(base, world, difficulty, aName, bName, rep) {
|
| 61 |
-
|
|
|
|
| 62 |
}
|
| 63 |
|
| 64 |
// Run ONE match: candidate A as owner "player", candidate B as owner "ai", both spending from the
|
|
|
|
| 48 |
// side-symmetry bug would show up as those two disagreeing" — and with an order-dependent seed the
|
| 49 |
// two halves would differ in seat AND map, so a disagreement would be confounded with ordinary
|
| 50 |
// seed variance and carry no information at all.
|
| 51 |
+
//
|
| 52 |
+
// `seedKey` OVERRIDES the name-derived half of that hash, and exists for one caller: an
|
| 53 |
+
// evolutionary search (tools/genome.js, docs/ai-evolution-design.md §8.1). Names in the hash are
|
| 54 |
+
// exactly right when the pair IS the experiment — two hand-written candidates, compared to each
|
| 55 |
+
// other — but wrong the moment names are generated per individual, because then a generation's
|
| 56 |
+
// every pairing draws its own map set and "the child scored better than its parent did" is partly
|
| 57 |
+
// a statement about map luck rather than about the genome. Passing one fixed key for a whole
|
| 58 |
+
// generation (or a whole run) pins every pairing in it to the same maps, so genomes are compared
|
| 59 |
+
// on identical ground. Omitted, this is byte-for-byte the seed derivation it has always been.
|
| 60 |
/**
|
| 61 |
* @param {number} base
|
| 62 |
* @param {string} world
|
|
|
|
| 64 |
* @param {string} aName
|
| 65 |
* @param {string} bName
|
| 66 |
* @param {number} rep
|
| 67 |
+
* @param {string} [seedKey] replaces the sorted-names segment; omit for today's exact behaviour.
|
| 68 |
* @returns {number}
|
| 69 |
*/
|
| 70 |
+
export function duelSeed(base, world, difficulty, aName, bName, rep, seedKey) {
|
| 71 |
+
const pairPart = seedKey != null ? seedKey : [aName, bName].sort().join("|");
|
| 72 |
+
return hashStr(`${base}:duel:${world}:${difficulty}:${pairPart}:${rep}`);
|
| 73 |
}
|
| 74 |
|
| 75 |
// Run ONE match: candidate A as owner "player", candidate B as owner "ai", both spending from the
|
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ============================================================
|
| 2 |
+
GENOME — the AI as a mutable, crossable data structure (docs/ai-evolution-design.md)
|
| 3 |
+
|
| 4 |
+
tools/ailab.js's own header already makes the observation this file builds on: "a candidate
|
| 5 |
+
strategy is a JSON object, not a code change". What that means, said in the other vocabulary,
|
| 6 |
+
is that the AI has a GENOTYPE — and that its genotype→phenotype map is unusually forgiving,
|
| 7 |
+
because ARCHETYPES / STRATEGIES / DIFFICULTY_OPTIONS are read at their use sites through
|
| 8 |
+
`|| 1`-style defaults. An arbitrary mutation is therefore always a RUNNABLE AI rather than a
|
| 9 |
+
crash, which is the expensive precondition for evolutionary search and which this codebase
|
| 10 |
+
happens to satisfy already.
|
| 11 |
+
|
| 12 |
+
This file adds the three things applyOverrides does not have:
|
| 13 |
+
|
| 14 |
+
1. A SCHEMA (GENOME_SCHEMA) — what a legal gene is: its layer, its kind, its bounds, and
|
| 15 |
+
which functional module it belongs to. One source of truth, the same role
|
| 16 |
+
DIFFICULTY_OPTIONS plays for difficulty keys.
|
| 17 |
+
2. VARIATION OPERATORS — mutate() and cross(), with an operator per gene KIND rather than
|
| 18 |
+
one operator for everything (see KINDS below; this is the design decision that matters
|
| 19 |
+
most and the most common way a mixed-genome GA fails).
|
| 20 |
+
3. A LOWERING (toOverrides / toCandidate) back into exactly the `--overrides` shape
|
| 21 |
+
tools/ailab.js already consumes, so an evolved genome drops straight into sweep / duel /
|
| 22 |
+
swiss / leaderboard with no adapter anywhere.
|
| 23 |
+
|
| 24 |
+
PURE AND SEEDED. Every operator takes an explicit `rng` (a mulberry32 stream) and reads no
|
| 25 |
+
clock — so a whole evolutionary run reproduces from one integer, exactly like every other
|
| 26 |
+
number this bench prints. Lives in tools/ for the same reason tools/ailab.js does: the engine
|
| 27 |
+
stays the pure shipped simulation and never learns that any of this exists.
|
| 28 |
+
|
| 29 |
+
THE KINDS, and why each needs its own operator
|
| 30 |
+
----------------------------------------------
|
| 31 |
+
ratio A multiplier composed onto an archetype's own number (attackTimeoutMult, …). These
|
| 32 |
+
are RATIOS, so they mutate multiplicatively — in log space — never additively: an
|
| 33 |
+
additive ±0.1 is a 50% change at 0.2 and a 7% change at 1.5, which searches the low
|
| 34 |
+
end far too coarsely and the high end far too finely.
|
| 35 |
+
Note the lower bounds below are small but never 0. Zero is an ABSORBING state
|
| 36 |
+
under multiplicative mutation (0 × anything is 0, forever), and it isn't needed:
|
| 37 |
+
every use site rounds, so garrisonMult 0.05 against an archetype garrison of 3 is
|
| 38 |
+
already `Math.round(0.15)` = 0, the all-in Rusher behaviour, reachably and
|
| 39 |
+
reversibly.
|
| 40 |
+
count An integer headcount (standingArmyCap, matchFloor, turretCount, …). Additive
|
| 41 |
+
integer step scaled to the gene's own range, so 0 stays REACHABLE — 0 is a
|
| 42 |
+
meaningful allele here, not a degenerate one (rusher.turretCount and
|
| 43 |
+
rusher.garrison are both deliberately 0).
|
| 44 |
+
unit01 A bounded fraction (expandWhenNodesBelow). Additive, clamped to its range.
|
| 45 |
+
flag A boolean. Flipped RARELY (flagRate, default 4%), because these are not ordinary
|
| 46 |
+
genes: they are EPISTATIC SWITCHES that decide whether other genes mean anything
|
| 47 |
+
at all. Under neverInitiates every offense gene is inert (aiMilitary.js blocks
|
| 48 |
+
every voluntary commit); under capsArmy=false standingArmyCap is never emitted.
|
| 49 |
+
At a high flip rate the population never settles in one landscape long enough to
|
| 50 |
+
tune the dials in it.
|
| 51 |
+
The inert genes keep drifting — junk DNA — and that is deliberate: a lineage
|
| 52 |
+
that flips a switch back lands somewhere NEW rather than at its ancestral value,
|
| 53 |
+
which is one of the main ways a GA escapes a local optimum. It costs nothing here
|
| 54 |
+
because the `|| 1` convention means an unread gene is carried, not erased.
|
| 55 |
+
choice An unordered categorical (doctrine, faction). No metric exists on these — `miners`
|
| 56 |
+
is not "between" `syndicate` and `frontier` — so mutation resamples uniformly and
|
| 57 |
+
crossover takes one parent's allele whole.
|
| 58 |
+
mix A CYCLIC SEQUENCE over an alphabet of unit types (unitMix), variable length, where
|
| 59 |
+
both order and multiplicity carry meaning: it is a repeating production cycle, so
|
| 60 |
+
three skiffs in four slots IS the Rusher, and a rotation decides which unit gets
|
| 61 |
+
built first. Its operators are the sequence-GA ones (substitute / duplicate /
|
| 62 |
+
delete / insert / rotate, and order crossover). Safe to mutate hard because
|
| 63 |
+
aiWorkers.js's effectiveMix already drops entries a world can't pay for or hasn't
|
| 64 |
+
teched to — an illegal mix degrades to a no-op instead of wedging production.
|
| 65 |
+
|
| 66 |
+
WHAT IS DELIBERATELY NOT A GENE
|
| 67 |
+
-------------------------------
|
| 68 |
+
The DIFFICULTY layer (engine/aiDifficulty.js). It is the duel FAIRNESS PIN: pinnedDuelDials
|
| 69 |
+
(tools/duelCore.js) reads one difficulty row into one object both sides spread from, and every
|
| 70 |
+
duel row reads apm/micro back off the live controllers to prove they never diverged. A genome
|
| 71 |
+
able to touch that layer would be selected for an APM edge, not for strategy.
|
| 72 |
+
============================================================ */
|
| 73 |
+
|
| 74 |
+
"use strict";
|
| 75 |
+
|
| 76 |
+
import { mulberry32 } from "../engine/rng.js";
|
| 77 |
+
import { STRATEGIES } from "../engine/aiStrategy.js";
|
| 78 |
+
import { ARCHETYPES } from "../engine/aiArchetypes.js";
|
| 79 |
+
|
| 80 |
+
/* ============================================================
|
| 81 |
+
THE SCHEMA
|
| 82 |
+
============================================================ */
|
| 83 |
+
|
| 84 |
+
// The unitMix alphabet is the UNION of the vocabulary the four shipped archetypes already field
|
| 85 |
+
// (engine/aiArchetypes.js) — deliberately NOT every UNITS entry with role "combat". Two reasons:
|
| 86 |
+
// it keeps evolution recombining a vocabulary a designer has already judged coherent, and it
|
| 87 |
+
// leaves out `leviathan`, whose Star Dock sits at the far end of the Odyssey industry chain and
|
| 88 |
+
// which no skirmish-length duel could ever reach.
|
| 89 |
+
export const MIX_ALPHABET =
|
| 90 |
+
["skiff", "bastion", "lancer", "breacher", "dreadnought", "wraith", "aegis", "colossus"];
|
| 91 |
+
|
| 92 |
+
const MIX_MIN_LEN = 2, MIX_MAX_LEN = 10;
|
| 93 |
+
|
| 94 |
+
/**
|
| 95 |
+
* Every gene, with the information the operators need to vary it legally.
|
| 96 |
+
* layer which table it is lowered into — "strategy" or "archetype".
|
| 97 |
+
* kind which operator applies (see the KINDS section in this file's header).
|
| 98 |
+
* module the LINKAGE GROUP crossover cuts at (see cross() below). These map one-to-one
|
| 99 |
+
* onto the engine files that consume them, which is why cutting here preserves a
|
| 100 |
+
* working sub-solution instead of shredding it.
|
| 101 |
+
* odysseyOnly the use site is behind a `state.endless` / `state.diplomacy` guard, so this
|
| 102 |
+
* gene is INERT in a skirmish — and every duel is a skirmish (tools/selfplay.js:
|
| 103 |
+
* "skirmish-only — no Odyssey, no diplomacy, no galaxy"). A duel-scored search
|
| 104 |
+
* must drop these or it is scoring pure drift; see geneKeys() and the evolve
|
| 105 |
+
* command's own `--fitness` handling.
|
| 106 |
+
* gatedBy this gene is only emitted when the named flag gene is true. Only for genes
|
| 107 |
+
* whose use site tests PRESENCE rather than value (standingArmyCap's `!= null`),
|
| 108 |
+
* where emitting a default would silently change behaviour.
|
| 109 |
+
* @typedef {{ key: string, layer: string, kind: string, module: string,
|
| 110 |
+
* min?: number, max?: number, of?: string[], odysseyOnly?: boolean, gatedBy?: string }} Gene
|
| 111 |
+
*/
|
| 112 |
+
/** @type {Gene[]} */
|
| 113 |
+
export const GENOME_SCHEMA = [
|
| 114 |
+
// ---- OFFENSE — engine/aiMilitary.js aiOffense, engine/aiSuperweapon.js ----
|
| 115 |
+
{ key: "attackTimeoutMult", layer: "strategy", kind: "ratio", min: 0.15, max: 3, module: "offense" },
|
| 116 |
+
{ key: "armyAttackSizeMult", layer: "strategy", kind: "ratio", min: 0.2, max: 3, module: "offense" },
|
| 117 |
+
{ key: "garrisonMult", layer: "strategy", kind: "ratio", min: 0.05, max: 3, module: "offense" },
|
| 118 |
+
{ key: "neverInitiates", layer: "strategy", kind: "flag", module: "offense" },
|
| 119 |
+
{ key: "useBombOffensively", layer: "strategy", kind: "flag", module: "offense", odysseyOnly: true },
|
| 120 |
+
|
| 121 |
+
// ---- ECONOMY — engine/aiEconomy.js, engine/aiIndustry.js ----
|
| 122 |
+
{ key: "workerTargetMult", layer: "strategy", kind: "ratio", min: 0.5, max: 2, module: "economy" },
|
| 123 |
+
// capsArmy is the SWITCH, standingArmyCap the value it gates: aiEconomy.js reads
|
| 124 |
+
// `strategy.standingArmyCap != null`, so emitting a number at all is what turns the cap on.
|
| 125 |
+
// Modelled as two genes rather than a nullable one so the epistasis is explicit and the value
|
| 126 |
+
// keeps drifting while the switch is off (see the flag note in this file's header).
|
| 127 |
+
{ key: "capsArmy", layer: "strategy", kind: "flag", module: "economy" },
|
| 128 |
+
{ key: "standingArmyCap", layer: "strategy", kind: "count", min: 0, max: 40, module: "economy", gatedBy: "capsArmy" },
|
| 129 |
+
{ key: "warFootingMult", layer: "strategy", kind: "ratio", min: 1, max: 10, module: "economy" },
|
| 130 |
+
{ key: "warFootingTime", layer: "strategy", kind: "ratio", min: 10, max: 300, module: "economy" },
|
| 131 |
+
{ key: "wantsIndustryAlways", layer: "strategy", kind: "flag", module: "economy", odysseyOnly: true },
|
| 132 |
+
|
| 133 |
+
// ---- DEFENSE — engine/aiEconomy.js turret cap + the Force Parity mirror ----
|
| 134 |
+
{ key: "turretCountMult", layer: "strategy", kind: "ratio", min: 0.2, max: 3, module: "defense" },
|
| 135 |
+
{ key: "matchEnemyForce", layer: "strategy", kind: "flag", module: "defense" },
|
| 136 |
+
{ key: "matchBuffer", layer: "strategy", kind: "ratio", min: 0.5, max: 2.5, module: "defense" },
|
| 137 |
+
{ key: "matchFloor", layer: "strategy", kind: "count", min: 0, max: 20, module: "defense" },
|
| 138 |
+
|
| 139 |
+
// ---- DIPLOMACY — engine/diplomacy.js. Odyssey-only, every one of them: a skirmish state has
|
| 140 |
+
// no state.diplomacy at all, so these are read by nothing in a duel.
|
| 141 |
+
{ key: "graceMult", layer: "strategy", kind: "ratio", min: 0.1, max: 3, module: "diplomacy", odysseyOnly: true },
|
| 142 |
+
{ key: "grievanceMult", layer: "strategy", kind: "ratio", min: 0.3, max: 3, module: "diplomacy", odysseyOnly: true },
|
| 143 |
+
{ key: "forgiveness", layer: "strategy", kind: "ratio", min: 0.3, max: 3, module: "diplomacy", odysseyOnly: true },
|
| 144 |
+
|
| 145 |
+
// ---- MACRO — the archetype's own counts. Only in play when the archetype chromosome is
|
| 146 |
+
// enabled (`--genes strategy,archetype`), which also requires the per-side archetype plumb
|
| 147 |
+
// through runDuel — see tools/ailab.js.
|
| 148 |
+
{ key: "workerTarget", layer: "archetype", kind: "count", min: 3, max: 30, module: "macro" },
|
| 149 |
+
{ key: "expandWhenNodesBelow", layer: "archetype", kind: "unit01", min: 0, max: 0.8, module: "macro" },
|
| 150 |
+
{ key: "maxBarracks", layer: "archetype", kind: "count", min: 1, max: 5, module: "macro" },
|
| 151 |
+
{ key: "wantsRefinery", layer: "archetype", kind: "flag", module: "macro" },
|
| 152 |
+
|
| 153 |
+
// ---- TEMPO — the archetype's own offense numbers, which the strategy multipliers compose onto.
|
| 154 |
+
{ key: "armyAttackSize", layer: "archetype", kind: "count", min: 2, max: 30, module: "tempo" },
|
| 155 |
+
{ key: "attackTimeout", layer: "archetype", kind: "ratio", min: 30, max: 400, module: "tempo" },
|
| 156 |
+
{ key: "garrison", layer: "archetype", kind: "count", min: 0, max: 15, module: "tempo" },
|
| 157 |
+
{ key: "turretCount", layer: "archetype", kind: "count", min: 0, max: 8, module: "tempo" },
|
| 158 |
+
|
| 159 |
+
// ---- COMPOSITION — what it actually builds, and who it builds it as.
|
| 160 |
+
{ key: "unitMix", layer: "archetype", kind: "mix", module: "composition" },
|
| 161 |
+
{ key: "doctrine", layer: "archetype", kind: "choice", of: ["assault", "bulwark"], module: "composition" },
|
| 162 |
+
{ key: "faction", layer: "archetype", kind: "choice", of: ["frontier", "miners", "syndicate"], module: "composition" },
|
| 163 |
+
];
|
| 164 |
+
|
| 165 |
+
const BY_KEY = new Map(GENOME_SCHEMA.map(g => [g.key, g]));
|
| 166 |
+
|
| 167 |
+
/** Every distinct linkage group in the schema, in declaration order. @returns {string[]} */
|
| 168 |
+
export const MODULES = [...new Set(GENOME_SCHEMA.map(g => g.module))];
|
| 169 |
+
|
| 170 |
+
/**
|
| 171 |
+
* The genes a given run is allowed to vary.
|
| 172 |
+
* @param {{ layers?: string[], odyssey?: boolean }} [opts]
|
| 173 |
+
* layers which chromosomes are in play (default: strategy only — see the design doc's Phase 1).
|
| 174 |
+
* odyssey include genes whose use site is Odyssey-gated. FALSE by default, because the duel
|
| 175 |
+
* objective is a skirmish and those genes are read by nothing there.
|
| 176 |
+
* @returns {Gene[]}
|
| 177 |
+
*/
|
| 178 |
+
export function geneKeys({ layers = ["strategy"], odyssey = false } = {}) {
|
| 179 |
+
return GENOME_SCHEMA.filter(g => layers.includes(g.layer) && (odyssey || !g.odysseyOnly));
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/* ============================================================
|
| 183 |
+
RANDOM SOURCES — all seeded, all explicit
|
| 184 |
+
============================================================ */
|
| 185 |
+
|
| 186 |
+
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
| 187 |
+
|
| 188 |
+
// Box-Muller. One draw costs two rng() calls; taking only the cosine half (rather than caching
|
| 189 |
+
// the sine) keeps the stream position a pure function of how many gaussians have been drawn,
|
| 190 |
+
// which is what makes a run reproducible from its seed alone.
|
| 191 |
+
function gauss(rng) {
|
| 192 |
+
const u = 1 - rng(); // (0, 1] — log(0) is -Infinity
|
| 193 |
+
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rng());
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
const pick = (rng, arr) => arr[Math.floor(rng() * arr.length)];
|
| 197 |
+
|
| 198 |
+
/** A seeded stream, so callers never reach for Math.random. @param {number} seed */
|
| 199 |
+
export const rngFor = seed => mulberry32(seed >>> 0);
|
| 200 |
+
|
| 201 |
+
/* ============================================================
|
| 202 |
+
THE GENOME ITSELF
|
| 203 |
+
============================================================ */
|
| 204 |
+
|
| 205 |
+
// The self-adaptive mutation step. Carried AS A GENE (mutated alongside the rest, in log space)
|
| 206 |
+
// rather than fixed by the caller: an individual whose lineage is still climbing benefits from a
|
| 207 |
+
// wide step, one sitting near an optimum from a narrow one, and evolution picks which by the only
|
| 208 |
+
// evidence that matters — whether the offspring survived. Four lines for the highest-value trick
|
| 209 |
+
// in evolution strategies.
|
| 210 |
+
const SIGMA_MIN = 0.03, SIGMA_MAX = 0.8, SIGMA_DEFAULT = 0.2;
|
| 211 |
+
const SIGMA_LEARNING_RATE = 0.3;
|
| 212 |
+
|
| 213 |
+
/** @typedef {{ strategy: Object, archetype: Object, sigma: number }} Genome */
|
| 214 |
+
|
| 215 |
+
/** An empty genome carrying no genes at all — every field absent, which every use site reads as
|
| 216 |
+
* its own default. The identity element for the operators below. @returns {Genome} */
|
| 217 |
+
export const emptyGenome = () => ({ strategy: {}, archetype: {}, sigma: SIGMA_DEFAULT });
|
| 218 |
+
|
| 219 |
+
/** Deep-enough copy: gene values are numbers, booleans, strings, or a flat array (unitMix).
|
| 220 |
+
* @param {Genome} g @returns {Genome} */
|
| 221 |
+
export const cloneGenome = g => ({
|
| 222 |
+
strategy: { ...g.strategy },
|
| 223 |
+
archetype: { ...g.archetype, ...(g.archetype.unitMix ? { unitMix: [...g.archetype.unitMix] } : {}) },
|
| 224 |
+
sigma: g.sigma,
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
/**
|
| 228 |
+
* Seed a genome from a SHIPPED row — the four hand-tuned strategies and the four archetypes are
|
| 229 |
+
* the best starting points anyone has, and a GA that throws them away is starting from behind.
|
| 230 |
+
* Genes the shipped row doesn't carry are filled from the schema's midpoint rather than left
|
| 231 |
+
* absent, so the genome is complete and every operator has something to work on (an absent gene
|
| 232 |
+
* would otherwise be frozen: nothing to mutate multiplicatively, nothing to blend).
|
| 233 |
+
* @param {{ strategy?: string, archetype?: string, genes?: Gene[] }} [opts]
|
| 234 |
+
* @returns {Genome}
|
| 235 |
+
*/
|
| 236 |
+
export function genomeFrom({ strategy = "default", archetype = "balanced", genes = geneKeys() } = {}) {
|
| 237 |
+
const src = { strategy: STRATEGIES[strategy] || {}, archetype: ARCHETYPES[archetype] || {} };
|
| 238 |
+
const out = emptyGenome();
|
| 239 |
+
for (const g of genes) {
|
| 240 |
+
const shipped = src[g.layer][g.key];
|
| 241 |
+
out[g.layer][g.key] = shipped !== undefined ? (g.kind === "mix" ? [...shipped] : shipped) : midpoint(g);
|
| 242 |
+
}
|
| 243 |
+
// capsArmy has no shipped counterpart — it is this file's own explicit rendering of "does this
|
| 244 |
+
// strategy carry a standingArmyCap at all", so derive it from whether the source row did.
|
| 245 |
+
if (BY_KEY.has("capsArmy") && genes.some(g => g.key === "capsArmy"))
|
| 246 |
+
out.strategy.capsArmy = src.strategy.standingArmyCap != null;
|
| 247 |
+
return out;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
function midpoint(g) {
|
| 251 |
+
switch (g.kind) {
|
| 252 |
+
case "ratio": return +Math.sqrt(g.min * g.max).toFixed(3); // geometric — a ratio's own midpoint
|
| 253 |
+
case "count": return Math.round((g.min + g.max) / 2);
|
| 254 |
+
case "unit01": return +((g.min + g.max) / 2).toFixed(3);
|
| 255 |
+
case "flag": return false;
|
| 256 |
+
case "choice": return g.of[0];
|
| 257 |
+
case "mix": return [...ARCHETYPES.balanced.unitMix];
|
| 258 |
+
default: throw new Error(`unknown gene kind "${g.kind}"`);
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
/** A uniformly random genome over `genes` — the exploration half of an initial population.
|
| 263 |
+
* @param {() => number} rng @param {Gene[]} [genes] @returns {Genome} */
|
| 264 |
+
export function randomGenome(rng, genes = geneKeys()) {
|
| 265 |
+
const out = emptyGenome();
|
| 266 |
+
for (const g of genes) {
|
| 267 |
+
switch (g.kind) {
|
| 268 |
+
// Uniform in LOG space, so a ratio gene is as likely to start below 1 as above it — a
|
| 269 |
+
// uniform draw on [0.15, 3] would put 80% of the population above parity.
|
| 270 |
+
case "ratio": out[g.layer][g.key] = +Math.exp(Math.log(g.min) + rng() * (Math.log(g.max) - Math.log(g.min))).toFixed(3); break;
|
| 271 |
+
case "count": out[g.layer][g.key] = g.min + Math.floor(rng() * (g.max - g.min + 1)); break;
|
| 272 |
+
case "unit01": out[g.layer][g.key] = +(g.min + rng() * (g.max - g.min)).toFixed(3); break;
|
| 273 |
+
case "flag": out[g.layer][g.key] = rng() < 0.5; break;
|
| 274 |
+
case "choice": out[g.layer][g.key] = pick(rng, g.of); break;
|
| 275 |
+
case "mix": out[g.layer][g.key] = randomMix(rng); break;
|
| 276 |
+
default: throw new Error(`unknown gene kind "${g.kind}"`);
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
out.sigma = SIGMA_DEFAULT;
|
| 280 |
+
return out;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
function randomMix(rng) {
|
| 284 |
+
const len = 3 + Math.floor(rng() * 4);
|
| 285 |
+
return Array.from({ length: len }, () => pick(rng, MIX_ALPHABET));
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/* ============================================================
|
| 289 |
+
MUTATION
|
| 290 |
+
============================================================ */
|
| 291 |
+
|
| 292 |
+
/**
|
| 293 |
+
* A mutated COPY of `genome`. Each eligible gene is varied with probability `rate` (flags with
|
| 294 |
+
* `flagRate`, which is deliberately far lower — see the KINDS note in this file's header), by the
|
| 295 |
+
* operator its kind calls for, at the genome's own self-adapted step size.
|
| 296 |
+
* @param {Genome} genome @param {() => number} rng
|
| 297 |
+
* @param {{ rate?: number, flagRate?: number, genes?: Gene[] }} [opts]
|
| 298 |
+
* @returns {Genome}
|
| 299 |
+
*/
|
| 300 |
+
export function mutate(genome, rng, { rate = 0.3, flagRate = 0.04, genes = geneKeys() } = {}) {
|
| 301 |
+
const out = cloneGenome(genome);
|
| 302 |
+
// The step size mutates FIRST and the new value is what this generation's genes are drawn at,
|
| 303 |
+
// so a lineage that inherited a lucky step size is the one whose offspring survive to pass it
|
| 304 |
+
// on — which is the entire mechanism by which self-adaptation works.
|
| 305 |
+
out.sigma = clamp(genome.sigma * Math.exp(SIGMA_LEARNING_RATE * gauss(rng)), SIGMA_MIN, SIGMA_MAX);
|
| 306 |
+
const sigma = out.sigma;
|
| 307 |
+
for (const g of genes) {
|
| 308 |
+
const p = g.kind === "flag" ? flagRate : rate;
|
| 309 |
+
if (rng() >= p) continue;
|
| 310 |
+
const cur = out[g.layer][g.key];
|
| 311 |
+
switch (g.kind) {
|
| 312 |
+
case "ratio":
|
| 313 |
+
out[g.layer][g.key] = +clamp(cur * Math.exp(sigma * gauss(rng)), g.min, g.max).toFixed(3);
|
| 314 |
+
break;
|
| 315 |
+
case "count": {
|
| 316 |
+
// Additive, scaled to the gene's own range — multiplicative would make 0 absorbing, and 0
|
| 317 |
+
// is a real allele for every count here (a Rusher's turretCount and garrison are both 0).
|
| 318 |
+
const step = gauss(rng) * sigma * Math.max(1, (g.max - g.min) * 0.5);
|
| 319 |
+
out[g.layer][g.key] = clamp(Math.round(cur + step), g.min, g.max);
|
| 320 |
+
break;
|
| 321 |
+
}
|
| 322 |
+
case "unit01":
|
| 323 |
+
out[g.layer][g.key] = +clamp(cur + gauss(rng) * sigma * (g.max - g.min), g.min, g.max).toFixed(3);
|
| 324 |
+
break;
|
| 325 |
+
case "flag":
|
| 326 |
+
out[g.layer][g.key] = !cur;
|
| 327 |
+
break;
|
| 328 |
+
case "choice": {
|
| 329 |
+
// Resample from the OTHER alleles, so a mutation that fires always actually moves — a
|
| 330 |
+
// uniform resample over all of them would silently no-op 1/|of| of the time and make the
|
| 331 |
+
// effective mutation rate on categoricals lower than the number the caller passed.
|
| 332 |
+
const others = g.of.filter(v => v !== cur);
|
| 333 |
+
out[g.layer][g.key] = others.length ? pick(rng, others) : cur;
|
| 334 |
+
break;
|
| 335 |
+
}
|
| 336 |
+
case "mix":
|
| 337 |
+
out[g.layer][g.key] = mutateMix(cur, rng);
|
| 338 |
+
break;
|
| 339 |
+
default:
|
| 340 |
+
throw new Error(`unknown gene kind "${g.kind}"`);
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
return out;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// One sequence operator, chosen uniformly. `duplicate` and `delete` are what let the cycle change
|
| 347 |
+
// LENGTH — the thing a fixed-width vector genome cannot express and the reason a mix can evolve
|
| 348 |
+
// from a Rusher's 4-slot spam into a Technologist's 6-slot elite ladder rather than only ever
|
| 349 |
+
// re-weighting a fixed number of slots.
|
| 350 |
+
export function mutateMix(mix, rng) {
|
| 351 |
+
const out = [...mix];
|
| 352 |
+
const i = Math.floor(rng() * out.length);
|
| 353 |
+
switch (Math.floor(rng() * 5)) {
|
| 354 |
+
case 0: out[i] = pick(rng, MIX_ALPHABET); break; // substitute
|
| 355 |
+
case 1: if (out.length < MIX_MAX_LEN) out.splice(i, 0, out[i]); break; // duplicate in place
|
| 356 |
+
case 2: if (out.length > MIX_MIN_LEN) out.splice(i, 1); break; // delete
|
| 357 |
+
case 3: if (out.length < MIX_MAX_LEN) out.splice(i, 0, pick(rng, MIX_ALPHABET)); break; // insert
|
| 358 |
+
// Rotate. NEUTRAL in the steady state of a repeating cycle — and decisive in the opening,
|
| 359 |
+
// which is where an RTS match is usually decided. The one operator here whose effect the
|
| 360 |
+
// scoreboard sees only in the first few minutes.
|
| 361 |
+
default: out.push(...out.splice(0, 1 + Math.floor(rng() * (out.length - 1)))); break;
|
| 362 |
+
}
|
| 363 |
+
return out;
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
/* ============================================================
|
| 367 |
+
CROSSOVER
|
| 368 |
+
============================================================ */
|
| 369 |
+
|
| 370 |
+
/**
|
| 371 |
+
* Recombine two parents. `a` should be the FITTER of the two — `clone` returns it, and the blend
|
| 372 |
+
* mode leans on nothing else about the order.
|
| 373 |
+
*
|
| 374 |
+
* MODULE-WISE is the default mode, not uniform-per-gene, and that is the substantive choice in
|
| 375 |
+
* this file. The genes cluster into linkage groups that map one-to-one onto the engine files
|
| 376 |
+
* consuming them (offense→aiMilitary, economy→aiEconomy, …). Genes WITHIN a group interact
|
| 377 |
+
* strongly — a smaller muster only works alongside a thinner garrison — and genes ACROSS groups
|
| 378 |
+
* interact weakly. Cutting at those boundaries therefore inherits a working sub-solution intact,
|
| 379 |
+
* where uniform crossover would shred an offense package that only functions as a set.
|
| 380 |
+
*
|
| 381 |
+
* The repo has the worked example. engine/aiStrategy.js records that Aggressive finished LAST of
|
| 382 |
+
* four in self-play (25W-47L), that a coordinate scan over its own offense dials could not fix
|
| 383 |
+
* it, and that what did fix it — 25W-47L to 38W-34L — was borrowing Economic's workerTargetMult.
|
| 384 |
+
* That is a hand-executed module-wise cross of the economy group onto an offense-heavy parent. It
|
| 385 |
+
* took a human two searches to find; it is one draw from this operator.
|
| 386 |
+
*
|
| 387 |
+
* @param {Genome} a the fitter parent @param {Genome} b @param {() => number} rng
|
| 388 |
+
* @param {{ moduleWise?: number, blend?: number, genes?: Gene[] }} [opts]
|
| 389 |
+
* moduleWise/blend are probabilities; the remainder is a clone of `a`.
|
| 390 |
+
* @returns {Genome}
|
| 391 |
+
*/
|
| 392 |
+
export function cross(a, b, rng, { moduleWise = 0.6, blend = 0.25, genes = geneKeys() } = {}) {
|
| 393 |
+
const roll = rng();
|
| 394 |
+
const out = cloneGenome(a);
|
| 395 |
+
// Geometric mean: sigma is a ratio like any other, and an arithmetic mean of 0.05 and 0.8
|
| 396 |
+
// would hand every child of a cautious and an exploratory parent a near-exploratory step.
|
| 397 |
+
out.sigma = clamp(Math.sqrt(a.sigma * b.sigma), SIGMA_MIN, SIGMA_MAX);
|
| 398 |
+
if (roll >= moduleWise + blend) return out; // clone the fitter parent
|
| 399 |
+
|
| 400 |
+
if (roll < moduleWise) {
|
| 401 |
+
// Draw one parent per linkage group. Drawn per MODULE, not per gene — that is the point.
|
| 402 |
+
const byModule = new Map(MODULES.map(m => [m, rng() < 0.5 ? a : b]));
|
| 403 |
+
for (const g of genes) {
|
| 404 |
+
const src = byModule.get(g.module);
|
| 405 |
+
const v = src[g.layer][g.key];
|
| 406 |
+
if (v !== undefined) out[g.layer][g.key] = g.kind === "mix" ? [...v] : v;
|
| 407 |
+
}
|
| 408 |
+
return out;
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
// BLEND — a child BETWEEN two similar parents, which is what finds the last few percent once a
|
| 412 |
+
// population has converged on a region. Only the ordered kinds can be averaged; the unordered
|
| 413 |
+
// ones (flag/choice/mix) have no midpoint, so they take a parent's allele by coin flip.
|
| 414 |
+
for (const g of genes) {
|
| 415 |
+
const va = a[g.layer][g.key], vb = b[g.layer][g.key];
|
| 416 |
+
if (va === undefined || vb === undefined) continue;
|
| 417 |
+
switch (g.kind) {
|
| 418 |
+
case "ratio": out[g.layer][g.key] = +clamp(Math.sqrt(va * vb), g.min, g.max).toFixed(3); break;
|
| 419 |
+
case "count": out[g.layer][g.key] = clamp(Math.round((va + vb) / 2), g.min, g.max); break;
|
| 420 |
+
case "unit01": out[g.layer][g.key] = +clamp((va + vb) / 2, g.min, g.max).toFixed(3); break;
|
| 421 |
+
case "mix": out[g.layer][g.key] = crossMix(va, vb, rng); break;
|
| 422 |
+
default: out[g.layer][g.key] = rng() < 0.5 ? va : vb; break;
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
return out;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
/**
|
| 429 |
+
* Order crossover for the production cycle: take a contiguous RUN from `a` — a build order is a
|
| 430 |
+
* sequence of adjacencies, and a run is the unit of it that means something — then fill out to
|
| 431 |
+
* `b`'s length from `b`, skipping nothing, so both parents' composition contributes. Length lands
|
| 432 |
+
* between the two parents' lengths, which is how the cycle keeps exploring size as well as
|
| 433 |
+
* content.
|
| 434 |
+
* @param {string[]} a @param {string[]} b @param {() => number} rng @returns {string[]}
|
| 435 |
+
*/
|
| 436 |
+
export function crossMix(a, b, rng) {
|
| 437 |
+
const cut = 1 + Math.floor(rng() * Math.max(1, a.length - 1));
|
| 438 |
+
const start = Math.floor(rng() * a.length);
|
| 439 |
+
const run = Array.from({ length: Math.min(cut, a.length) }, (_, i) => a[(start + i) % a.length]);
|
| 440 |
+
const target = clamp(Math.round((a.length + b.length) / 2), MIX_MIN_LEN, MIX_MAX_LEN);
|
| 441 |
+
const out = [...run];
|
| 442 |
+
for (let i = 0; out.length < target; i++) out.push(b[i % b.length]);
|
| 443 |
+
return out.slice(0, Math.max(MIX_MIN_LEN, target));
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
/* ============================================================
|
| 447 |
+
LOWERING — back into the shape tools/ailab.js already consumes
|
| 448 |
+
============================================================ */
|
| 449 |
+
|
| 450 |
+
/**
|
| 451 |
+
* A genome as an `--overrides` document. Two rules worth stating:
|
| 452 |
+
* • A gene with `gatedBy` is emitted ONLY when its gate is true, because its use site tests
|
| 453 |
+
* presence (`standingArmyCap != null`) rather than value — emitting a default would turn the
|
| 454 |
+
* cap on for every genome in the population.
|
| 455 |
+
* • The archetype row is written under a name of its OWN (`${name}-arch`), never over a shipped
|
| 456 |
+
* archetype key. Two candidates in one duel share a single live table and applyOverrides
|
| 457 |
+
* MERGES, so patching a shared key would leave both seats playing a row belonging to neither
|
| 458 |
+
* — the exact collision tools/ailab.js's assertNoOverrideCollision refuses.
|
| 459 |
+
* @param {Genome} genome @param {string} name @param {{ genes?: Gene[] }} [opts]
|
| 460 |
+
* @returns {{ strategies?: Object, archetypes?: Object }}
|
| 461 |
+
*/
|
| 462 |
+
export function toOverrides(genome, name, { genes = geneKeys() } = {}) {
|
| 463 |
+
const strategyRow = {}, archetypeRow = {};
|
| 464 |
+
for (const g of genes) {
|
| 465 |
+
if (g.gatedBy && !genome[g.layer][g.gatedBy]) continue;
|
| 466 |
+
if (g.kind === "flag" && g.key === "capsArmy") continue; // the switch itself is not a dial the engine reads
|
| 467 |
+
const v = genome[g.layer][g.key];
|
| 468 |
+
if (v === undefined) continue;
|
| 469 |
+
(g.layer === "strategy" ? strategyRow : archetypeRow)[g.key] = g.kind === "mix" ? [...v] : v;
|
| 470 |
+
}
|
| 471 |
+
const out = { strategies: { [name]: strategyRow } };
|
| 472 |
+
if (Object.keys(archetypeRow).length) out.archetypes = { [`${name}-arch`]: archetypeRow };
|
| 473 |
+
return out;
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
/**
|
| 477 |
+
* A genome as a CANDIDATE — the `{ name, strategy, overrides }` shape runLeaderboard, runDuel,
|
| 478 |
+
* runRoundRobin and runSwissTournament all already take, plus the `archetype` field
|
| 479 |
+
* tools/duelCore.js's runDuelMatch accepts per side. Drops straight into every one of them.
|
| 480 |
+
* @param {Genome} genome @param {string} name @param {{ genes?: Gene[] }} [opts]
|
| 481 |
+
*/
|
| 482 |
+
export function toCandidate(genome, name, { genes = geneKeys() } = {}) {
|
| 483 |
+
const overrides = toOverrides(genome, name, { genes });
|
| 484 |
+
const cand = { name, strategy: name, overrides };
|
| 485 |
+
if (overrides.archetypes) cand.archetype = `${name}-arch`;
|
| 486 |
+
return cand;
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
/** One-line human summary of the genes that differ from `other` — what a generation log wants.
|
| 490 |
+
* @param {Genome} genome @param {Genome} other @param {{ genes?: Gene[] }} [opts] @returns {string} */
|
| 491 |
+
export function diffGenes(genome, other, { genes = geneKeys() } = {}) {
|
| 492 |
+
const parts = [];
|
| 493 |
+
for (const g of genes) {
|
| 494 |
+
const a = genome[g.layer][g.key], b = other[g.layer][g.key];
|
| 495 |
+
const same = g.kind === "mix" ? JSON.stringify(a) === JSON.stringify(b) : a === b;
|
| 496 |
+
if (!same) parts.push(`${g.key}=${g.kind === "mix" ? `[${a}]` : a}`);
|
| 497 |
+
}
|
| 498 |
+
return parts.join(" ");
|
| 499 |
+
}
|